69096491a27f2316c932f64ffabf2fa10a528da2
[csit.git] / resources / libraries / python / VppConfigGenerator.py
1 # Copyright (c) 2016 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """VPP Configuration File Generator library."""
15
16 import re
17 import time
18
19 from resources.libraries.python.ssh import SSH
20 from resources.libraries.python.topology import NodeType
21 from resources.libraries.python.topology import Topology
22
23 __all__ = ['VppConfigGenerator']
24
25
26 class VppConfigGenerator(object):
27     """VPP Configuration File Generator."""
28
29     def __init__(self):
30         """Initialize library."""
31         # VPP Node to apply configuration on
32         self._node = ''
33         # VPP Hostname
34         self._hostname = ''
35         # VPP Configuration
36         self._nodeconfig = {}
37         # Serialized VPP Configuration
38         self._vpp_config = ''
39         # VPP Service name
40         self._vpp_service_name = 'vpp'
41
42     def set_node(self, node):
43         """Set DUT node.
44
45         :param node: Node to store configuration on.
46         :type node: dict
47         :raises RuntimeError: If Node type is not DUT.
48         """
49         if node['type'] != NodeType.DUT:
50             raise RuntimeError('Startup config can only be applied to DUT'
51                                'node.')
52         self._node = node
53         self._hostname = Topology.get_node_hostname(node)
54
55     def get_config_str(self):
56         """Get dumped startup configuration in VPP config format.
57
58         :returns: Startup configuration in VPP config format.
59         :rtype: str
60         """
61         self.dump_config(self._nodeconfig)
62         return self._vpp_config
63
64     def add_config_item(self, config, value, path):
65         """Add startup configuration item.
66
67         :param config: Startup configuration of node.
68         :param value: Value to insert.
69         :param path: Path where to insert item.
70         :type config: dict
71         :type value: str
72         :type path: list
73         """
74         if len(path) == 1:
75             config[path[0]] = value
76             return
77         if path[0] not in config:
78             config[path[0]] = {}
79         self.add_config_item(config[path[0]], value, path[1:])
80
81     def dump_config(self, obj, level=-1):
82         """Dump the startup configuration in VPP config format.
83
84         :param obj: Python Object to print.
85         :param level: Nested level for indentation.
86         :type obj: Obj
87         :type level: int
88         :returns: nothing
89         """
90         indent = '  '
91         if level >= 0:
92             self._vpp_config += '{}{{\n'.format((level) * indent)
93         if isinstance(obj, dict):
94             for key, val in obj.items():
95                 if hasattr(val, '__iter__'):
96                     self._vpp_config += '{}{}\n'.format((level + 1) * indent,
97                                                         key)
98                     self.dump_config(val, level + 1)
99                 else:
100                     self._vpp_config += '{}{} {}\n'.format((level + 1) * indent,
101                                                            key, val)
102         else:
103             for val in obj:
104                 self._vpp_config += '{}{}\n'.format((level + 1) * indent, val)
105         if level >= 0:
106             self._vpp_config += '{}}}\n'.format(level * indent)
107
108     def add_unix_log(self, value='/tmp/vpe.log'):
109         """Add UNIX log configuration.
110
111         :param value: Log file.
112         :type value: str
113         """
114         path = ['unix', 'log']
115         self.add_config_item(self._nodeconfig, value, path)
116
117     def add_unix_cli_listen(self, value='localhost:5002'):
118         """Add UNIX cli-listen configuration.
119
120         :param value: CLI listen address and port.
121         :type value: str
122         """
123         path = ['unix', 'cli-listen']
124         self.add_config_item(self._nodeconfig, value, path)
125
126     def add_unix_nodaemon(self):
127         """Add UNIX nodaemon configuration."""
128         path = ['unix', 'nodaemon']
129         self.add_config_item(self._nodeconfig, '', path)
130
131     def add_unix_exec(self, value):
132         """Add UNIX exec configuration."""
133         path = ['unix', 'exec']
134         self.add_config_item(self._nodeconfig, value, path)
135
136     def add_dpdk_dev(self, *devices):
137         """Add DPDK PCI device configuration.
138
139         :param devices: PCI device(s) (format xxxx:xx:xx.x)
140         :type devices: tuple
141         :raises ValueError: If PCI address format is not valid.
142         """
143         pattern = re.compile("^[0-9A-Fa-f]{4}:[0-9A-Fa-f]{2}:"
144                              "[0-9A-Fa-f]{2}\\.[0-9A-Fa-f]$")
145         for device in devices:
146             if not pattern.match(device):
147                 raise ValueError('PCI address {} to be added to host {} '
148                                  'is not in valid format xxxx:xx:xx.x'.
149                                  format(device, self._hostname))
150             path = ['dpdk', 'dev {0}'.format(device)]
151             self.add_config_item(self._nodeconfig, '', path)
152
153     def add_dpdk_cryptodev(self, count):
154         """Add DPDK Crypto PCI device configuration.
155
156         :param count: Number of crypto devices to add.
157         :type count: int
158         """
159         cryptodev = Topology.get_cryptodev(self._node)
160         for i in range(count):
161             cryptodev_config = 'dev {0}'.format(
162                 re.sub(r'\d.\d$', '1.'+str(i), cryptodev))
163             path = ['dpdk', cryptodev_config]
164             self.add_config_item(self._nodeconfig, '', path)
165         self.add_dpdk_uio_driver('igb_uio')
166
167     def add_dpdk_dev_default_rxq(self, value):
168         """Add DPDK dev default rxq configuration.
169
170         :param value: Default number of rxqs.
171         :type value: str
172         """
173         path = ['dpdk', 'dev default', 'num-rx-queues']
174         self.add_config_item(self._nodeconfig, value, path)
175
176     def add_dpdk_dev_default_txq(self, value):
177         """Add DPDK dev default txq configuration.
178
179         :param value: Default number of txqs.
180         :type value: str
181         """
182         path = ['dpdk', 'dev default', 'num-tx-queues']
183         self.add_config_item(self._nodeconfig, value, path)
184
185     def add_dpdk_dev_default_rxd(self, value):
186         """Add DPDK dev default rxd configuration.
187
188         :param value: Default number of rxds.
189         :type value: str
190         """
191         path = ['dpdk', 'dev default', 'num-rx-desc']
192         self.add_config_item(self._nodeconfig, value, path)
193
194     def add_dpdk_dev_default_txd(self, value):
195         """Add DPDK dev default txd configuration.
196
197         :param value: Default number of txds.
198         :type value: str
199         """
200         path = ['dpdk', 'dev default', 'num-tx-desc']
201         self.add_config_item(self._nodeconfig, value, path)
202
203     def add_dpdk_socketmem(self, value):
204         """Add DPDK socket memory configuration.
205
206         :param value: Socket memory size.
207         :type value: str
208         """
209         path = ['dpdk', 'socket-mem']
210         self.add_config_item(self._nodeconfig, value, path)
211
212     def add_dpdk_uio_driver(self, value):
213         """Add DPDK uio-driver configuration.
214
215         :param value: DPDK uio-driver configuration.
216         :type value: str
217         """
218         path = ['dpdk', 'uio-driver']
219         self.add_config_item(self._nodeconfig, value, path)
220
221     def add_cpu_main_core(self, value):
222         """Add CPU main core configuration.
223
224         :param value: Main core option.
225         :type value: str
226         """
227         path = ['cpu', 'main-core']
228         self.add_config_item(self._nodeconfig, value, path)
229
230     def add_cpu_corelist_workers(self, value):
231         """Add CPU corelist-workers configuration.
232
233         :param value: Corelist-workers option.
234         :type value: str
235         """
236         path = ['cpu', 'corelist-workers']
237         self.add_config_item(self._nodeconfig, value, path)
238
239     def add_heapsize(self, value):
240         """Add Heapsize configuration.
241
242         :param value: Amount of heapsize.
243         :type value: str
244         """
245         path = ['heapsize']
246         self.add_config_item(self._nodeconfig, value, path)
247
248     def add_api_trace(self):
249         """Add API trace configuration."""
250         path = ['api-trace', 'on']
251         self.add_config_item(self._nodeconfig, '', path)
252
253     def add_ip6_hash_buckets(self, value):
254         """Add IP6 hash buckets configuration.
255
256         :param value: Number of IP6 hash buckets.
257         :type value: str
258         """
259         path = ['ip6', 'hash-buckets']
260         self.add_config_item(self._nodeconfig, value, path)
261
262     def add_ip6_heap_size(self, value):
263         """Add IP6 heap-size configuration.
264
265         :param value: IP6 Heapsize amount.
266         :type value: str
267         """
268         path = ['ip6', 'heap-size']
269         self.add_config_item(self._nodeconfig, value, path)
270
271     def add_plugin_disable(self, *plugins):
272         """Add plugin disable for specific plugin.
273
274         :param plugins: Plugin(s) to disable.
275         :type plugins: list
276         """
277         for plugin in plugins:
278             path = ['plugins', 'plugin {0}'.format(plugin), 'disable']
279             self.add_config_item(self._nodeconfig, ' ', path)
280
281     def add_dpdk_no_multi_seg(self):
282         """Add DPDK no-multi-seg configuration."""
283         path = ['dpdk', 'no-multi-seg']
284         self.add_config_item(self._nodeconfig, '', path)
285
286     def add_nat(self, value='deterministic'):
287         """Add NAT configuration.
288
289         :param value: NAT mode.
290         :type value: str
291         """
292         path = ['nat']
293         self.add_config_item(self._nodeconfig, value, path)
294
295     def apply_config(self, filename='/etc/vpp/startup.conf', waittime=5,
296                      retries=12, restart_vpp=True):
297         """Generate and apply VPP configuration for node.
298
299         Use data from calls to this class to form a startup.conf file and
300         replace /etc/vpp/startup.conf with it on node.
301
302         :param filename: Startup configuration file name.
303         :param waittime: Time to wait for VPP to restart (default 5 seconds).
304         :param retries: Number of times (default 12) to re-try waiting.
305         :param restart_vpp: Whether to restart VPP.
306         :type filename: str
307         :type waittime: int
308         :type retries: int
309         :type restart_vpp: bool.
310         :raises RuntimeError: If writing config file failed, or restarting of
311         VPP failed.
312         """
313         self.dump_config(self._nodeconfig)
314
315         ssh = SSH()
316         ssh.connect(self._node)
317
318         (ret, _, _) = \
319             ssh.exec_command('echo "{config}" | sudo tee {filename}'.
320                              format(config=self._vpp_config,
321                                     filename=filename))
322
323         if ret != 0:
324             raise RuntimeError('Writing config file failed to node {}'.
325                                format(self._hostname))
326
327         if restart_vpp:
328             # Instead of restarting, we'll do separate start and stop
329             # actions. This way we don't care whether VPP was running
330             # to begin with.
331             ssh.exec_command('sudo service {} stop'
332                              .format(self._vpp_service_name))
333             (ret, _, _) = \
334                 ssh.exec_command('sudo service {} start'
335                                  .format(self._vpp_service_name))
336             if ret != 0:
337                 raise RuntimeError('Restarting VPP failed on node {}'.
338                                    format(self._hostname))
339
340             # Sleep <waittime> seconds, up to <retry> times,
341             # and verify if VPP is running.
342             for _ in range(retries):
343                 time.sleep(waittime)
344                 (ret, _, _) = \
345                     ssh.exec_command('echo show hardware-interfaces | '
346                                      'nc 0 5002 || echo "VPP not yet running"')
347                 if ret == 0:
348                     break
349             else:
350                 raise RuntimeError('VPP failed to restart on node {}'.
351                                    format(self._hostname))