Introduce VPP-IPsec container tests.
[csit.git] / resources / libraries / python / VppConfigGenerator.py
1 # Copyright (c) 2019 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 TODO: Support initialization with default values,
17 so that we do not need to have block of 6 "Add Unix" commands
18 in 7 various places of CSIT code.
19 """
20
21 import re
22
23 from resources.libraries.python.Constants import Constants
24 from resources.libraries.python.ssh import exec_cmd_no_error
25 from resources.libraries.python.topology import NodeType
26 from resources.libraries.python.topology import Topology
27 from resources.libraries.python.VPPUtil import VPPUtil
28
29 __all__ = [u"VppConfigGenerator"]
30
31
32 def pci_dev_check(pci_dev):
33     """Check if provided PCI address is in correct format.
34
35     :param pci_dev: PCI address (expected format: xxxx:xx:xx.x).
36     :type pci_dev: str
37     :returns: True if PCI address is in correct format.
38     :rtype: bool
39     :raises ValueError: If PCI address is in incorrect format.
40     """
41     pattern = re.compile(
42         r"^[0-9A-Fa-f]{4}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}\.[0-9A-Fa-f]$"
43     )
44     if not re.match(pattern, pci_dev):
45         raise ValueError(
46             f"PCI address {pci_dev} is not in valid format xxxx:xx:xx.x"
47         )
48     return True
49
50
51 class VppConfigGenerator:
52     """VPP Configuration File Generator."""
53
54     def __init__(self):
55         """Initialize library."""
56         # VPP Node to apply configuration on
57         self._node = u""
58         # Topology node key
59         self._node_key = u""
60         # VPP Configuration
61         self._nodeconfig = dict()
62         # Serialized VPP Configuration
63         self._vpp_config = u""
64         # VPP Service name
65         self._vpp_service_name = u"vpp"
66         # VPP Logfile location
67         self._vpp_logfile = u"/tmp/vpe.log"
68         # VPP Startup config location
69         self._vpp_startup_conf = u"/etc/vpp/startup.conf"
70         # VPP Startup config backup location
71         self._vpp_startup_conf_backup = None
72
73     def set_node(self, node, node_key=None):
74         """Set DUT node.
75
76         :param node: Node to store configuration on.
77         :param node_key: Topology node key.
78         :type node: dict
79         :type node_key: str
80         :raises RuntimeError: If Node type is not DUT.
81         """
82         if node[u"type"] != NodeType.DUT:
83             raise RuntimeError(
84                 u"Startup config can only be applied to DUTnode."
85             )
86         self._node = node
87         self._node_key = node_key
88
89     def set_vpp_logfile(self, logfile):
90         """Set VPP logfile location.
91
92         :param logfile: VPP logfile location.
93         :type logfile: str
94         """
95         self._vpp_logfile = logfile
96
97     def set_vpp_startup_conf_backup(self, backup=u"/etc/vpp/startup.backup"):
98         """Set VPP startup configuration backup.
99
100         :param backup: VPP logfile location.
101         :type backup: str
102         """
103         self._vpp_startup_conf_backup = backup
104
105     def get_config_str(self):
106         """Get dumped startup configuration in VPP config format.
107
108         :returns: Startup configuration in VPP config format.
109         :rtype: str
110         """
111         self.dump_config(self._nodeconfig)
112         return self._vpp_config
113
114     def add_config_item(self, config, value, path):
115         """Add startup configuration item.
116
117         :param config: Startup configuration of node.
118         :param value: Value to insert.
119         :param path: Path where to insert item.
120         :type config: dict
121         :type value: str
122         :type path: list
123         """
124         if len(path) == 1:
125             config[path[0]] = value
126             return
127         if path[0] not in config:
128             config[path[0]] = dict()
129         elif isinstance(config[path[0]], str):
130             config[path[0]] = dict() if config[path[0]] == u"" \
131                 else {config[path[0]]: u""}
132         self.add_config_item(config[path[0]], value, path[1:])
133
134     def dump_config(self, obj, level=-1):
135         """Dump the startup configuration in VPP config format.
136
137         :param obj: Python Object to print.
138         :param level: Nested level for indentation.
139         :type obj: Obj
140         :type level: int
141         :returns: nothing
142         """
143         indent = u"  "
144         if level >= 0:
145             self._vpp_config += f"{level * indent}{{\n"
146         if isinstance(obj, dict):
147             for key, val in obj.items():
148                 if hasattr(val, u"__iter__") and not isinstance(val, str):
149                     self._vpp_config += f"{(level + 1) * indent}{key}\n"
150                     self.dump_config(val, level + 1)
151                 else:
152                     self._vpp_config += f"{(level + 1) * indent}{key} {val}\n"
153         else:
154             for val in obj:
155                 self._vpp_config += f"{(level + 1) * indent}{val}\n"
156         if level >= 0:
157             self._vpp_config += f"{level * indent}}}\n"
158
159     def add_unix_log(self, value=None):
160         """Add UNIX log configuration.
161
162         :param value: Log file.
163         :type value: str
164         """
165         path = [u"unix", u"log"]
166         if value is None:
167             value = self._vpp_logfile
168         self.add_config_item(self._nodeconfig, value, path)
169
170     def add_unix_cli_listen(self, value=u"/run/vpp/cli.sock"):
171         """Add UNIX cli-listen configuration.
172
173         :param value: CLI listen address and port or path to CLI socket.
174         :type value: str
175         """
176         path = [u"unix", u"cli-listen"]
177         self.add_config_item(self._nodeconfig, value, path)
178
179     def add_unix_gid(self, value=u"vpp"):
180         """Add UNIX gid configuration.
181
182         :param value: Gid.
183         :type value: str
184         """
185         path = [u"unix", u"gid"]
186         self.add_config_item(self._nodeconfig, value, path)
187
188     def add_unix_nodaemon(self):
189         """Add UNIX nodaemon configuration."""
190         path = [u"unix", u"nodaemon"]
191         self.add_config_item(self._nodeconfig, u"", path)
192
193     def add_unix_coredump(self):
194         """Add UNIX full-coredump configuration."""
195         path = [u"unix", u"full-coredump"]
196         self.add_config_item(self._nodeconfig, u"", path)
197
198     def add_unix_exec(self, value):
199         """Add UNIX exec configuration."""
200         path = [u"unix", u"exec"]
201         self.add_config_item(self._nodeconfig, value, path)
202
203     def add_socksvr(self, socket=Constants.SOCKSVR_PATH):
204         """Add socksvr configuration."""
205         path = ['socksvr', u"socket-name"]
206         self.add_config_item(self._nodeconfig, socket, path)
207
208     def add_api_segment_gid(self, value=u"vpp"):
209         """Add API-SEGMENT gid configuration.
210
211         :param value: Gid.
212         :type value: str
213         """
214         path = [u"api-segment", u"gid"]
215         self.add_config_item(self._nodeconfig, value, path)
216
217     def add_api_segment_global_size(self, value):
218         """Add API-SEGMENT global-size configuration.
219
220         :param value: Global size.
221         :type value: str
222         """
223         path = [u"api-segment", u"global-size"]
224         self.add_config_item(self._nodeconfig, value, path)
225
226     def add_api_segment_api_size(self, value):
227         """Add API-SEGMENT api-size configuration.
228
229         :param value: API size.
230         :type value: str
231         """
232         path = [u"api-segment", u"api-size"]
233         self.add_config_item(self._nodeconfig, value, path)
234
235     def add_buffers_per_numa(self, value):
236         """Increase number of buffers allocated.
237
238         :param value: Number of buffers allocated.
239         :type value: int
240         """
241         path = [u"buffers", u"buffers-per-numa"]
242         self.add_config_item(self._nodeconfig, value, path)
243
244     def add_dpdk_dev(self, *devices):
245         """Add DPDK PCI device configuration.
246
247         :param devices: PCI device(s) (format xxxx:xx:xx.x)
248         :type devices: tuple
249         """
250         for device in devices:
251             if pci_dev_check(device):
252                 path = [u"dpdk", f"dev {device}"]
253                 self.add_config_item(self._nodeconfig, u"", path)
254
255     def add_dpdk_dev_parameter(self, device, parameter, value):
256         """Add parameter for DPDK device.
257
258         :param device: PCI device (format xxxx:xx:xx.x).
259         :param parameter: Parameter name.
260         :param value: Parameter value.
261         :type device: str
262         :type parameter: str
263         :type value: str
264         """
265         if pci_dev_check(device):
266             path = [u"dpdk", f"dev {device}", parameter]
267             self.add_config_item(self._nodeconfig, value, path)
268
269     def add_dpdk_cryptodev(self, count):
270         """Add DPDK Crypto PCI device configuration.
271
272         :param count: Number of HW crypto devices to add.
273         :type count: int
274         """
275         cryptodev = Topology.get_cryptodev(self._node)
276         for i in range(count):
277             cryptodev_config = re.sub(r"\d.\d$", f"1.{str(i)}", cryptodev)
278             path = [u"dpdk", f"dev {cryptodev_config}"]
279             self.add_config_item(self._nodeconfig, u"", path)
280         self.add_dpdk_uio_driver(u"vfio-pci")
281
282     def add_dpdk_sw_cryptodev(self, sw_pmd_type, socket_id, count):
283         """Add DPDK SW Crypto device configuration.
284
285         :param sw_pmd_type: Type of SW crypto device PMD to add.
286         :param socket_id: Socket ID.
287         :param count: Number of SW crypto devices to add.
288         :type sw_pmd_type: str
289         :type socket_id: int
290         :type count: int
291         """
292         for _ in range(count):
293             cryptodev_config = f"vdev cryptodev_{sw_pmd_type}_pmd," \
294                 f"socket_id={str(socket_id)}"
295             path = [u"dpdk", cryptodev_config]
296             self.add_config_item(self._nodeconfig, u"", path)
297
298     def add_dpdk_eth_bond_dev(self, ethbond_id, mode, xmit_policy, *slaves):
299         """Add DPDK Eth_bond device configuration.
300
301         :param ethbond_id: Eth_bond device ID.
302         :param mode: Link bonding mode.
303         :param xmit_policy: Transmission policy.
304         :param slaves: PCI device(s) to be bonded (format xxxx:xx:xx.x).
305         :type ethbond_id: str or int
306         :type mode: str or int
307         :type xmit_policy: str
308         :type slaves: list
309         """
310         slaves_config = u"slave=" + u",slave=".join(
311             slave if pci_dev_check(slave) else u"" for slave in slaves
312         )
313         ethbond_config = f"vdev eth_bond{ethbond_id}," \
314             f"mode={mode}{slaves_config},xmit_policy={xmit_policy}"
315         path = [u"dpdk", ethbond_config]
316         self.add_config_item(self._nodeconfig, u"", path)
317
318     def add_dpdk_dev_default_rxq(self, value):
319         """Add DPDK dev default rxq configuration.
320
321         :param value: Default number of rxqs.
322         :type value: str
323         """
324         path = [u"dpdk", u"dev default", u"num-rx-queues"]
325         self.add_config_item(self._nodeconfig, value, path)
326
327     def add_dpdk_dev_default_txq(self, value):
328         """Add DPDK dev default txq configuration.
329
330         :param value: Default number of txqs.
331         :type value: str
332         """
333         path = [u"dpdk", u"dev default", u"num-tx-queues"]
334         self.add_config_item(self._nodeconfig, value, path)
335
336     def add_dpdk_dev_default_rxd(self, value):
337         """Add DPDK dev default rxd configuration.
338
339         :param value: Default number of rxds.
340         :type value: str
341         """
342         path = [u"dpdk", u"dev default", u"num-rx-desc"]
343         self.add_config_item(self._nodeconfig, value, path)
344
345     def add_dpdk_dev_default_txd(self, value):
346         """Add DPDK dev default txd configuration.
347
348         :param value: Default number of txds.
349         :type value: str
350         """
351         path = [u"dpdk", u"dev default", u"num-tx-desc"]
352         self.add_config_item(self._nodeconfig, value, path)
353
354     def add_dpdk_log_level(self, value):
355         """Add DPDK log-level configuration.
356
357         :param value: Log level.
358         :type value: str
359         """
360         path = [u"dpdk", u"log-level"]
361         self.add_config_item(self._nodeconfig, value, path)
362
363     def add_dpdk_no_pci(self):
364         """Add DPDK no-pci."""
365         path = [u"dpdk", u"no-pci"]
366         self.add_config_item(self._nodeconfig, u"", path)
367
368     def add_dpdk_uio_driver(self, value=None):
369         """Add DPDK uio-driver configuration.
370
371         :param value: DPDK uio-driver configuration. By default, driver will be
372             loaded automatically from Topology file, still leaving option
373             to manually override by parameter.
374         :type value: str
375         """
376         if value is None:
377             value = Topology.get_uio_driver(self._node)
378         path = [u"dpdk", u"uio-driver"]
379         self.add_config_item(self._nodeconfig, value, path)
380
381     def add_cpu_main_core(self, value):
382         """Add CPU main core configuration.
383
384         :param value: Main core option.
385         :type value: str
386         """
387         path = [u"cpu", u"main-core"]
388         self.add_config_item(self._nodeconfig, value, path)
389
390     def add_cpu_corelist_workers(self, value):
391         """Add CPU corelist-workers configuration.
392
393         :param value: Corelist-workers option.
394         :type value: str
395         """
396         path = [u"cpu", u"corelist-workers"]
397         self.add_config_item(self._nodeconfig, value, path)
398
399     def add_heapsize(self, value):
400         """Add Heapsize configuration.
401
402         :param value: Amount of heapsize.
403         :type value: str
404         """
405         path = [u"heapsize"]
406         self.add_config_item(self._nodeconfig, value, path)
407
408     def add_api_trace(self):
409         """Add API trace configuration."""
410         path = [u"api-trace", u"on"]
411         self.add_config_item(self._nodeconfig, u"", path)
412
413     def add_ip6_hash_buckets(self, value):
414         """Add IP6 hash buckets configuration.
415
416         :param value: Number of IP6 hash buckets.
417         :type value: str
418         """
419         path = [u"ip6", u"hash-buckets"]
420         self.add_config_item(self._nodeconfig, value, path)
421
422     def add_ip6_heap_size(self, value):
423         """Add IP6 heap-size configuration.
424
425         :param value: IP6 Heapsize amount.
426         :type value: str
427         """
428         path = [u"ip6", u"heap-size"]
429         self.add_config_item(self._nodeconfig, value, path)
430
431     def add_ip_heap_size(self, value):
432         """Add IP heap-size configuration.
433
434         :param value: IP Heapsize amount.
435         :type value: str
436         """
437         path = [u"ip", u"heap-size"]
438         self.add_config_item(self._nodeconfig, value, path)
439
440     def add_statseg_size(self, value):
441         """Add stats segment heap size configuration.
442
443         :param value: Stats heapsize amount.
444         :type value: str
445         """
446         path = [u"statseg", u"size"]
447         self.add_config_item(self._nodeconfig, value, path)
448
449     def add_statseg_per_node_counters(self, value):
450         """Add stats per-node-counters configuration.
451
452         :param value: "on" to switch the counters on.
453         :type value: str
454         """
455         path = [u"statseg", u"per-node-counters"]
456         self.add_config_item(self._nodeconfig, value, path)
457
458     def add_plugin(self, state, *plugins):
459         """Add plugin section for specific plugin(s).
460
461         :param state: State of plugin [enable|disable].
462         :param plugins: Plugin(s) to disable.
463         :type state: str
464         :type plugins: list
465         """
466         for plugin in plugins:
467             path = [u"plugins", f"plugin {plugin}", state]
468             self.add_config_item(self._nodeconfig, u" ", path)
469
470     def add_dpdk_no_multi_seg(self):
471         """Add DPDK no-multi-seg configuration."""
472         path = [u"dpdk", u"no-multi-seg"]
473         self.add_config_item(self._nodeconfig, u"", path)
474
475     def add_dpdk_no_tx_checksum_offload(self):
476         """Add DPDK no-tx-checksum-offload configuration."""
477         path = [u"dpdk", u"no-tx-checksum-offload"]
478         self.add_config_item(self._nodeconfig, u"", path)
479
480     def add_nat(self, value=u"deterministic"):
481         """Add NAT configuration.
482
483         :param value: NAT mode.
484         :type value: str
485         """
486         path = [u"nat"]
487         self.add_config_item(self._nodeconfig, value, path)
488
489     def add_tcp_preallocated_connections(self, value):
490         """Add TCP pre-allocated connections.
491
492         :param value: The number of pre-allocated connections.
493         :type value: int
494         """
495         path = [u"tcp", u"preallocated-connections"]
496         self.add_config_item(self._nodeconfig, value, path)
497
498     def add_tcp_preallocated_half_open_connections(self, value):
499         """Add TCP pre-allocated half open connections.
500
501         :param value: The number of pre-allocated half open connections.
502         :type value: int
503         """
504         path = [u"tcp", u"preallocated-half-open-connections"]
505         self.add_config_item(self._nodeconfig, value, path)
506
507     def add_session_event_queue_length(self, value):
508         """Add session event queue length.
509
510         :param value: Session event queue length.
511         :type value: int
512         """
513         path = [u"session", u"event-queue-length"]
514         self.add_config_item(self._nodeconfig, value, path)
515
516     def add_session_preallocated_sessions(self, value):
517         """Add the number of pre-allocated sessions.
518
519         :param value: Number of pre-allocated sessions.
520         :type value: int
521         """
522         path = [u"session", u"preallocated-sessions"]
523         self.add_config_item(self._nodeconfig, value, path)
524
525     def add_session_v4_session_table_buckets(self, value):
526         """Add number of v4 session table buckets to the config.
527
528         :param value: Number of v4 session table buckets.
529         :type value: int
530         """
531         path = [u"session", u"v4-session-table-buckets"]
532         self.add_config_item(self._nodeconfig, value, path)
533
534     def add_session_v4_session_table_memory(self, value):
535         """Add the size of v4 session table memory.
536
537         :param value: Size of v4 session table memory.
538         :type value: str
539         """
540         path = [u"session", u"v4-session-table-memory"]
541         self.add_config_item(self._nodeconfig, value, path)
542
543     def add_session_v4_halfopen_table_buckets(self, value):
544         """Add the number of v4 halfopen table buckets.
545
546         :param value: Number of v4 halfopen table buckets.
547         :type value: int
548         """
549         path = [u"session", u"v4-halfopen-table-buckets"]
550         self.add_config_item(self._nodeconfig, value, path)
551
552     def add_session_v4_halfopen_table_memory(self, value):
553         """Add the size of v4 halfopen table memory.
554
555         :param value: Size of v4 halfopen table memory.
556         :type value: str
557         """
558         path = [u"session", u"v4-halfopen-table-memory"]
559         self.add_config_item(self._nodeconfig, value, path)
560
561     def add_session_local_endpoints_table_buckets(self, value):
562         """Add the number of local endpoints table buckets.
563
564         :param value: Number of local endpoints table buckets.
565         :type value: int
566         """
567         path = [u"session", u"local-endpoints-table-buckets"]
568         self.add_config_item(self._nodeconfig, value, path)
569
570     def add_session_local_endpoints_table_memory(self, value):
571         """Add the size of local endpoints table memory.
572
573         :param value: Size of local endpoints table memory.
574         :type value: str
575         """
576         path = [u"session", u"local-endpoints-table-memory"]
577         self.add_config_item(self._nodeconfig, value, path)
578
579     def write_config(self, filename=None):
580         """Generate and write VPP startup configuration to file.
581
582         Use data from calls to this class to form a startup.conf file and
583         replace /etc/vpp/startup.conf with it on topology node.
584
585         :param filename: Startup configuration file name.
586         :type filename: str
587         """
588         self.dump_config(self._nodeconfig)
589
590         if filename is None:
591             filename = self._vpp_startup_conf
592
593         if self._vpp_startup_conf_backup is not None:
594             cmd = f"cp {self._vpp_startup_conf} {self._vpp_startup_conf_backup}"
595             exec_cmd_no_error(
596                 self._node, cmd, sudo=True, message=u"Copy config file failed!"
597             )
598
599         cmd = f"echo \"{self._vpp_config}\" | sudo tee {filename}"
600         exec_cmd_no_error(
601             self._node, cmd, message=u"Writing config file failed!"
602         )
603
604     def apply_config(self, filename=None, verify_vpp=True):
605         """Generate and write VPP startup configuration to file and restart VPP.
606
607         Use data from calls to this class to form a startup.conf file and
608         replace /etc/vpp/startup.conf with it on topology node.
609
610         :param filename: Startup configuration file name.
611         :param verify_vpp: Verify VPP is running after restart.
612         :type filename: str
613         :type verify_vpp: bool
614         """
615         self.write_config(filename=filename)
616
617         VPPUtil.restart_vpp_service(self._node, self._node_key)
618         if verify_vpp:
619             VPPUtil.verify_vpp(self._node)
620
621     def restore_config(self):
622         """Restore VPP startup.conf from backup."""
623         cmd = f"cp {self._vpp_startup_conf_backup} {self._vpp_startup_conf}"
624         exec_cmd_no_error(
625             self._node, cmd, sudo=True, message=u"Copy config file failed!"
626         )