Update of LXCUtil library
[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 class VppConfigGenerator(object):
26     """VPP Configuration File Generator."""
27
28     def __init__(self):
29         # VPP Node to apply configuration on
30         self._node = ''
31         # VPP Hostname
32         self._hostname = ''
33         # VPP Configuration
34         self._nodeconfig = {}
35         # Serialized VPP Configuration
36         self._vpp_config = ''
37         # VPP Service name
38         self._vpp_service_name = 'vpp'
39         # VPP Configuration file path
40         self._vpp_config_filename = '/etc/vpp/startup.conf'
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
50         if node['type'] != NodeType.DUT:
51             raise RuntimeError('Startup config can only be applied to DUT'
52                                'node.')
53         self._node = node
54         self._hostname = Topology.get_node_hostname(node)
55
56     def set_config_filename(self, filename):
57         """Set startup configuration filename.
58
59         :param filename: Startup configuration filename.
60         :type filename: str
61         """
62         self._vpp_config_filename = filename
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
75         if len(path) == 1:
76             config[path[0]] = value
77             return
78         if not config.has_key(path[0]):
79             config[path[0]] = {}
80         self.add_config_item(config[path[0]], value, path[1:])
81
82     def dump_config(self, obj, level=-1):
83         """Dump the startup configuration in VPP config format.
84
85         :param obj: Python Object to print.
86         :param nested_level: Nested level for indentation.
87         :type obj: Obj
88         :type nested_level: int
89         :returns: nothing
90         """
91         indent = '  '
92         if level >= 0:
93             self._vpp_config += '{}{{\n'.format((level) * indent)
94         if isinstance(obj, dict):
95             for key, val in obj.items():
96                 if hasattr(val, '__iter__'):
97                     self._vpp_config += '{}{}\n'.format((level + 1) * indent,
98                                                         key)
99                     self.dump_config(val, level + 1)
100                 else:
101                     self._vpp_config += '{}{} {}\n'.format((level + 1) * indent,
102                                                            key, val)
103         else:
104             for val in obj:
105                 self._vpp_config += '{}{}\n'.format((level + 1) * indent, val)
106         if level >= 0:
107             self._vpp_config += '{}}}\n'.format(level * indent)
108
109     def add_unix_log(self, value='/tmp/vpe.log'):
110         """Add UNIX log configuration.
111
112         :param value: Log file.
113         :type value: str
114         """
115         path = ['unix', 'log']
116         self.add_config_item(self._nodeconfig, value, path)
117
118     def add_unix_cli_listen(self, value='localhost:5002'):
119         """Add UNIX cli-listen configuration.
120
121         :param value: CLI listen address and port.
122         :type value: str
123         """
124         path = ['unix', 'cli-listen']
125         self.add_config_item(self._nodeconfig, value, path)
126
127     def add_unix_nodaemon(self):
128         """Add UNIX nodaemon configuration."""
129         path = ['unix', 'nodaemon']
130         self.add_config_item(self._nodeconfig, '', path)
131
132     def add_unix_exec(self, value):
133         """Add UNIX exec configuration."""
134         path = ['unix', 'exec']
135         self.add_config_item(self._nodeconfig, value, path)
136
137     def add_dpdk_dev(self, *devices):
138         """Add DPDK PCI device configuration.
139
140         :param devices: PCI device(s) (format xxxx:xx:xx.x)
141         :type devices: tuple
142         :raises ValueError: If PCI address format is not valid.
143         """
144
145         pattern = re.compile("^[0-9A-Fa-f]{4}:[0-9A-Fa-f]{2}:"
146                              "[0-9A-Fa-f]{2}\\.[0-9A-Fa-f]$")
147         for device in devices:
148             if not pattern.match(device):
149                 raise ValueError('PCI address {} to be added to host {} '
150                                  'is not in valid format xxxx:xx:xx.x'.
151                                  format(device, self._hostname))
152             path = ['dpdk', 'dev {0}'.format(device)]
153             self.add_config_item(self._nodeconfig, '', path)
154
155     def add_dpdk_cryptodev(self, count):
156         """Add DPDK Crypto PCI device configuration.
157
158         :param count: Number of crypto devices to add.
159         :type count: int
160         """
161         cryptodev = Topology.get_cryptodev(self._node)
162         for i in range(count):
163             cryptodev_config = 'dev {0}'.format(
164                 re.sub(r'\d.\d$', '1.'+str(i), cryptodev))
165             path = ['dpdk', cryptodev_config]
166             self.add_config_item(self._nodeconfig, '', path)
167         self.add_dpdk_uio_driver('igb_uio')
168
169     def add_dpdk_dev_default_rxq(self, value):
170         """Add DPDK dev default rxq configuration.
171
172         :param value: Default number of rxqs.
173         :type value: str
174         """
175         path = ['dpdk', 'dev default', 'num-rx-queues']
176         self.add_config_item(self._nodeconfig, value, path)
177
178     def add_dpdk_dev_default_txq(self, value):
179         """Add DPDK dev default txq configuration.
180
181         :param value: Default number of txqs.
182         :type value: str
183         """
184         path = ['dpdk', 'dev default', 'num-tx-queues']
185         self.add_config_item(self._nodeconfig, value, path)
186
187     def add_dpdk_socketmem(self, value):
188         """Add DPDK socket memory configuration.
189
190         :param value: Socket memory size.
191         :type value: str
192         """
193         path = ['dpdk', 'socket-mem']
194         self.add_config_item(self._nodeconfig, value, path)
195
196     def add_dpdk_uio_driver(self, value):
197         """Add DPDK uio-driver configuration.
198
199         :param value: DPDK uio-driver configuration.
200         :type value: str
201         """
202         path = ['dpdk', 'uio-driver']
203         self.add_config_item(self._nodeconfig, value, path)
204
205     def add_cpu_main_core(self, value):
206         """Add CPU main core configuration.
207
208         :param value: Main core option.
209         :type value: str
210         """
211         path = ['cpu', 'main-core']
212         self.add_config_item(self._nodeconfig, value, path)
213
214     def add_cpu_corelist_workers(self, value):
215         """Add CPU corelist-workers configuration.
216
217         :param value: Corelist-workers option.
218         :type value: str
219         """
220         path = ['cpu', 'corelist-workers']
221         self.add_config_item(self._nodeconfig, value, path)
222
223     def add_heapsize(self, value):
224         """Add Heapsize configuration.
225
226         :param value: Amount of heapsize.
227         :type value: str
228         """
229         path = ['heapsize']
230         self.add_config_item(self._nodeconfig, value, path)
231
232     def add_api_trace(self):
233         """Add API trace configuration."""
234         path = ['api-trace', 'on']
235         self.add_config_item(self._nodeconfig, '', path)
236
237     def add_ip6_hash_buckets(self, value):
238         """Add IP6 hash buckets configuration.
239
240         :param value: Number of IP6 hash buckets.
241         :type value: str
242         """
243         path = ['ip6', 'hash-buckets']
244         self.add_config_item(self._nodeconfig, value, path)
245
246     def add_ip6_heap_size(self, value):
247         """Add IP6 heap-size configuration.
248
249         :param value: IP6 Heapsize amount.
250         :type value: str
251         """
252         path = ['ip6', 'heap-size']
253         self.add_config_item(self._nodeconfig, value, path)
254
255     def add_plugin_disable(self, *plugins):
256         """Add plugin disable for specific plugin.
257
258         :param plugins: Plugin(s) to disable.
259         :type plugins: list
260         """
261         for plugin in plugins:
262             path = ['plugins', 'plugin {0}'.format(plugin), 'disable']
263             self.add_config_item(self._nodeconfig, ' ', path)
264
265     def add_dpdk_no_multi_seg(self):
266         """Add DPDK no-multi-seg configuration."""
267         path = ['dpdk', 'no-multi-seg']
268         self.add_config_item(self._nodeconfig, '', path)
269
270     def add_snat(self, value='deterministic'):
271         """Add SNAT configuration.
272
273         :param value: SNAT mode.
274         :type value: str
275         """
276         path = ['snat']
277         self.add_config_item(self._nodeconfig, value, path)
278
279     def apply_config(self, waittime=5, retries=12):
280         """Generate and apply VPP configuration for node.
281
282         Use data from calls to this class to form a startup.conf file and
283         replace /etc/vpp/startup.conf with it on node.
284
285         :param waittime: Time to wait for VPP to restart (default 5 seconds).
286         :param retries: Number of times (default 12) to re-try waiting.
287         :type waittime: int
288         :type retries: int
289         :raises RuntimeError: If writing config file failed, or restarting of
290         VPP failed.
291         """
292         self.dump_config(self._nodeconfig)
293
294         ssh = SSH()
295         ssh.connect(self._node)
296
297         # We're using this "| sudo tee" construct because redirecting
298         # a sudo's output ("sudo echo xxx > /path/to/file") does not
299         # work on most platforms...
300         (ret, _, _) = \
301             ssh.exec_command('echo "{0}" | sudo tee {1}'.
302                              format(self._vpp_config,
303                                     self._vpp_config_filename))
304
305         if ret != 0:
306             raise RuntimeError('Writing config file failed to node {}'.
307                                format(self._hostname))
308
309         # Instead of restarting, we'll do separate start and stop
310         # actions. This way we don't care whether VPP was running
311         # to begin with.
312         ssh.exec_command('sudo service {} stop'
313                          .format(self._vpp_service_name))
314         (ret, _, _) = \
315             ssh.exec_command('sudo service {} start'
316                              .format(self._vpp_service_name))
317         if ret != 0:
318             raise RuntimeError('Restarting VPP failed on node {}'.
319                                format(self._hostname))
320
321         # Sleep <waittime> seconds, up to <retry> times,
322         # and verify if VPP is running.
323         for _ in range(retries):
324             time.sleep(waittime)
325             (ret, _, _) = \
326                 ssh.exec_command('echo show hardware-interfaces | '
327                                  'nc 0 5002 || echo "VPP not yet running"')
328             if ret == 0:
329                 break
330         else:
331             raise RuntimeError('VPP failed to restart on node {}'.
332                                format(self._hostname))
333
334     def apply_config_lxc(self, lxc_name, waittime=5, retries=12):
335         """Generate and apply VPP configuration for node in a container.
336
337         Use data from calls to this class to form a startup.conf file and
338         replace /etc/vpp/startup.conf with it on node inside a container.
339
340         :param lxc_name: LXC container name.
341         :param waittime: Time to wait for VPP to restart (default 5 seconds).
342         :param retries: Number of times (default 12) to re-try waiting.
343         :type lxc_name: str
344         :type waittime: int
345         :type retries: int
346         :raises RuntimeError: If writing config file failed, or restarting of
347         VPP failed.
348         """
349         self.dump_config(self._nodeconfig)
350
351         ssh = SSH()
352         ssh.connect(self._node)
353
354         # We're using this "| sudo tee" construct because redirecting
355         # a sudo's output ("sudo echo xxx > /path/to/file") does not
356         # work on most platforms...
357         (ret, _, _) = \
358             ssh.exec_command_lxc('echo "{0}" | sudo tee {1}'.
359                                  format(self._vpp_config,
360                                         self._vpp_config_filename), lxc_name)
361
362         if ret != 0:
363             raise RuntimeError('Writing config file failed in {0} to node {1}'.
364                                format(lxc_name, self._hostname))
365
366         # Instead of restarting, we'll do separate start and stop
367         # actions. This way we don't care whether VPP was running
368         # to begin with.
369         ssh.exec_command_lxc('service {0} stop'.
370                              format(self._vpp_service_name), lxc_name)
371         (ret, _, _) = \
372             ssh.exec_command_lxc('service {0} start'.
373                                  format(self._vpp_service_name), lxc_name)
374         if ret != 0:
375             raise RuntimeError('Restarting VPP failed in {0} on node {1}'.
376                                format(lxc_name, self._hostname))
377
378         # Sleep <waittime> seconds, up to <retry> times,
379         # and verify if VPP is running.
380         for _ in range(retries):
381             time.sleep(waittime)
382             (ret, _, _) = \
383                 ssh.exec_command_lxc('echo show hardware-interfaces | '
384                                      'nc 0 5002 || echo "VPP not yet running"',
385                                      lxc_name)
386             if ret == 0:
387                 break
388         else:
389             raise RuntimeError('VPP failed to restart in {0} on node {1}'.
390                                format(lxc_name, self._hostname))