IPsec: add nth SPD entry outbound flow cache TCs
[csit.git] / resources / libraries / python / VppConfigGenerator.py
1 # Copyright (c) 2021 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 = [u"socksvr", u"socket-name"]
206         self.add_config_item(self._nodeconfig, socket, path)
207
208     def add_graph_node_variant(self, variant=Constants.GRAPH_NODE_VARIANT):
209         """Add default graph node variant.
210
211         :param value: Graph node variant default value.
212         :type value: str
213         """
214         if variant == u"":
215             return
216         variant_list = [u"hsw", u"skx", u"icl"]
217         if variant not in variant_list:
218             raise ValueError("Invalid graph node variant value")
219         path = [u"node", u"default", u"variant"]
220         self.add_config_item(self._nodeconfig, variant, path)
221
222     def add_api_segment_gid(self, value=u"vpp"):
223         """Add API-SEGMENT gid configuration.
224
225         :param value: Gid.
226         :type value: str
227         """
228         path = [u"api-segment", u"gid"]
229         self.add_config_item(self._nodeconfig, value, path)
230
231     def add_api_segment_global_size(self, value):
232         """Add API-SEGMENT global-size configuration.
233
234         :param value: Global size.
235         :type value: str
236         """
237         path = [u"api-segment", u"global-size"]
238         self.add_config_item(self._nodeconfig, value, path)
239
240     def add_api_segment_api_size(self, value):
241         """Add API-SEGMENT api-size configuration.
242
243         :param value: API size.
244         :type value: str
245         """
246         path = [u"api-segment", u"api-size"]
247         self.add_config_item(self._nodeconfig, value, path)
248
249     def add_buffers_per_numa(self, value):
250         """Increase number of buffers allocated.
251
252         :param value: Number of buffers allocated.
253         :type value: int
254         """
255         path = [u"buffers", u"buffers-per-numa"]
256         self.add_config_item(self._nodeconfig, value, path)
257
258     def add_buffers_default_data_size(self, value):
259         """Increase buffers data-size allocated.
260
261         :param value: Buffers data-size allocated.
262         :type value: int
263         """
264         path = [u"buffers", u"default data-size"]
265         self.add_config_item(self._nodeconfig, value, path)
266
267     def add_dpdk_dev(self, *devices):
268         """Add DPDK PCI device configuration.
269
270         :param devices: PCI device(s) (format xxxx:xx:xx.x)
271         :type devices: tuple
272         """
273         for device in devices:
274             if pci_dev_check(device):
275                 path = [u"dpdk", f"dev {device}"]
276                 self.add_config_item(self._nodeconfig, u"", path)
277
278     def add_dpdk_dev_parameter(self, device, parameter, value):
279         """Add parameter for DPDK device.
280
281         :param device: PCI device (format xxxx:xx:xx.x).
282         :param parameter: Parameter name.
283         :param value: Parameter value.
284         :type device: str
285         :type parameter: str
286         :type value: str
287         """
288         if pci_dev_check(device):
289             path = [u"dpdk", f"dev {device}", parameter]
290             self.add_config_item(self._nodeconfig, value, path)
291
292     def add_dpdk_cryptodev(self, count):
293         """Add DPDK Crypto PCI device configuration.
294
295         :param count: Number of HW crypto devices to add.
296         :type count: int
297         """
298         cryptodev = Topology.get_cryptodev(self._node)
299         for i in range(count):
300             cryptodev_config = re.sub(r"\d.\d$", f"1.{str(i)}", cryptodev)
301             path = [u"dpdk", f"dev {cryptodev_config}"]
302             self.add_config_item(self._nodeconfig, u"", path)
303         self.add_dpdk_uio_driver(u"vfio-pci")
304
305     def add_dpdk_sw_cryptodev(self, sw_pmd_type, socket_id, count):
306         """Add DPDK SW Crypto device configuration.
307
308         :param sw_pmd_type: Type of SW crypto device PMD to add.
309         :param socket_id: Socket ID.
310         :param count: Number of SW crypto devices to add.
311         :type sw_pmd_type: str
312         :type socket_id: int
313         :type count: int
314         """
315         for _ in range(count):
316             cryptodev_config = f"vdev cryptodev_{sw_pmd_type}_pmd," \
317                 f"socket_id={str(socket_id)}"
318             path = [u"dpdk", cryptodev_config]
319             self.add_config_item(self._nodeconfig, u"", path)
320
321     def add_dpdk_dev_default_rxq(self, value):
322         """Add DPDK dev default rxq configuration.
323
324         :param value: Default number of rxqs.
325         :type value: str
326         """
327         path = [u"dpdk", u"dev default", u"num-rx-queues"]
328         self.add_config_item(self._nodeconfig, value, path)
329
330     def add_dpdk_dev_default_txq(self, value):
331         """Add DPDK dev default txq configuration.
332
333         :param value: Default number of txqs.
334         :type value: str
335         """
336         path = [u"dpdk", u"dev default", u"num-tx-queues"]
337         self.add_config_item(self._nodeconfig, value, path)
338
339     def add_dpdk_dev_default_rxd(self, value):
340         """Add DPDK dev default rxd configuration.
341
342         :param value: Default number of rxds.
343         :type value: str
344         """
345         path = [u"dpdk", u"dev default", u"num-rx-desc"]
346         self.add_config_item(self._nodeconfig, value, path)
347
348     def add_dpdk_dev_default_txd(self, value):
349         """Add DPDK dev default txd configuration.
350
351         :param value: Default number of txds.
352         :type value: str
353         """
354         path = [u"dpdk", u"dev default", u"num-tx-desc"]
355         self.add_config_item(self._nodeconfig, value, path)
356
357     def add_dpdk_log_level(self, value):
358         """Add DPDK log-level configuration.
359
360         :param value: Log level.
361         :type value: str
362         """
363         path = [u"dpdk", u"log-level"]
364         self.add_config_item(self._nodeconfig, value, path)
365
366     def add_dpdk_no_pci(self):
367         """Add DPDK no-pci."""
368         path = [u"dpdk", u"no-pci"]
369         self.add_config_item(self._nodeconfig, u"", path)
370
371     def add_dpdk_uio_driver(self, value=None):
372         """Add DPDK uio-driver configuration.
373
374         :param value: DPDK uio-driver configuration. By default, driver will be
375             loaded automatically from Topology file, still leaving option
376             to manually override by parameter.
377         :type value: str
378         """
379         if value is None:
380             value = Topology.get_uio_driver(self._node)
381         path = [u"dpdk", u"uio-driver"]
382         self.add_config_item(self._nodeconfig, value, path)
383
384     def add_dpdk_max_simd_bitwidth(self, variant=Constants.GRAPH_NODE_VARIANT):
385         """Add DPDK max-simd-bitwidth configuration.
386
387         :param value: Graph node variant default value.
388         :type value: str
389         """
390         if variant == u"icl":
391             value = 512
392         elif variant in [u"skx", u"hsw"]:
393             value = 256
394         else:
395             return
396
397         path = [u"dpdk", u"max-simd-bitwidth"]
398         self.add_config_item(self._nodeconfig, value, path)
399
400     def add_cpu_main_core(self, value):
401         """Add CPU main core configuration.
402
403         :param value: Main core option.
404         :type value: str
405         """
406         path = [u"cpu", u"main-core"]
407         self.add_config_item(self._nodeconfig, value, path)
408
409     def add_cpu_corelist_workers(self, value):
410         """Add CPU corelist-workers configuration.
411
412         :param value: Corelist-workers option.
413         :type value: str
414         """
415         path = [u"cpu", u"corelist-workers"]
416         self.add_config_item(self._nodeconfig, value, path)
417
418     def add_main_heap_size(self, value):
419         """Add Main Heap Size configuration.
420
421         :param value: Amount of heap.
422         :type value: str
423         """
424         path = [u"memory", u"main-heap-size"]
425         self.add_config_item(self._nodeconfig, value, path)
426
427     def add_main_heap_page_size(self, value):
428         """Add Main Heap Page Size configuration.
429
430         :param value: Heap page size.
431         :type value: str
432         """
433         path = [u"memory", u"main-heap-page-size"]
434         self.add_config_item(self._nodeconfig, value, path)
435
436     def add_api_trace(self):
437         """Add API trace configuration."""
438         path = [u"api-trace", u"on"]
439         self.add_config_item(self._nodeconfig, u"", path)
440
441     def add_ip6_hash_buckets(self, value):
442         """Add IP6 hash buckets configuration.
443
444         :param value: Number of IP6 hash buckets.
445         :type value: str
446         """
447         path = [u"ip6", u"hash-buckets"]
448         self.add_config_item(self._nodeconfig, value, path)
449
450     def add_ip6_heap_size(self, value):
451         """Add IP6 heap-size configuration.
452
453         :param value: IP6 Heapsize amount.
454         :type value: str
455         """
456         path = [u"ip6", u"heap-size"]
457         self.add_config_item(self._nodeconfig, value, path)
458
459     def add_spd_flow_cache_ipv4_outbound(self):
460         """Add SPD flow cache for IP4 outbound traffic"""
461         path = [u"ipsec", u"ipv4-outbound-spd-flow-cache"]
462         self.add_config_item(self._nodeconfig, "on", path)
463
464     def add_statseg_size(self, value):
465         """Add Stats Heap Size configuration.
466
467         :param value: Stats heapsize amount.
468         :type value: str
469         """
470         path = [u"statseg", u"size"]
471         self.add_config_item(self._nodeconfig, value, path)
472
473     def add_statseg_page_size(self, value):
474         """Add Stats Heap Page Size configuration.
475
476         :param value: Stats heapsize amount.
477         :type value: str
478         """
479         path = [u"statseg", u"page-size"]
480         self.add_config_item(self._nodeconfig, value, path)
481
482     def add_statseg_per_node_counters(self, value):
483         """Add stats per-node-counters configuration.
484
485         :param value: "on" to switch the counters on.
486         :type value: str
487         """
488         path = [u"statseg", u"per-node-counters"]
489         self.add_config_item(self._nodeconfig, value, path)
490
491     def add_plugin(self, state, *plugins):
492         """Add plugin section for specific plugin(s).
493
494         :param state: State of plugin [enable|disable].
495         :param plugins: Plugin(s) to disable.
496         :type state: str
497         :type plugins: list
498         """
499         for plugin in plugins:
500             path = [u"plugins", f"plugin {plugin}", state]
501             self.add_config_item(self._nodeconfig, u" ", path)
502
503     def add_dpdk_no_multi_seg(self):
504         """Add DPDK no-multi-seg configuration."""
505         path = [u"dpdk", u"no-multi-seg"]
506         self.add_config_item(self._nodeconfig, u"", path)
507
508     def add_dpdk_no_tx_checksum_offload(self):
509         """Add DPDK no-tx-checksum-offload configuration."""
510         path = [u"dpdk", u"no-tx-checksum-offload"]
511         self.add_config_item(self._nodeconfig, u"", path)
512
513     def add_nat(self, value=u"deterministic"):
514         """Add NAT mode configuration.
515
516         :param value: NAT mode.
517         :type value: str
518         """
519         path = [u"nat", value]
520         self.add_config_item(self._nodeconfig, u"", path)
521
522     def add_nat_max_translations_per_thread(self, value):
523         """Add NAT max. translations per thread number configuration.
524
525         :param value: NAT mode.
526         :type value: str
527         """
528         path = [u"nat", u"max translations per thread"]
529         self.add_config_item(self._nodeconfig, value, path)
530
531     def add_nsim_poll_main_thread(self):
532         """Add NSIM poll-main-thread configuration."""
533         path = [u"nsim", u"poll-main-thread"]
534         self.add_config_item(self._nodeconfig, u"", path)
535
536     def add_tcp_congestion_control_algorithm(self, value=u"cubic"):
537         """Add TCP congestion control algorithm.
538
539         :param value: The congestion control algorithm to use. Example: cubic
540         :type value: str
541         """
542         path = [u"tcp", u"cc-algo"]
543         self.add_config_item(self._nodeconfig, value, path)
544
545     def add_tcp_preallocated_connections(self, value):
546         """Add TCP pre-allocated connections.
547
548         :param value: The number of pre-allocated connections.
549         :type value: int
550         """
551         path = [u"tcp", u"preallocated-connections"]
552         self.add_config_item(self._nodeconfig, value, path)
553
554     def add_tcp_preallocated_half_open_connections(self, value):
555         """Add TCP pre-allocated half open connections.
556
557         :param value: The number of pre-allocated half open connections.
558         :type value: int
559         """
560         path = [u"tcp", u"preallocated-half-open-connections"]
561         self.add_config_item(self._nodeconfig, value, path)
562
563     def add_session_enable(self):
564         """Add session enable."""
565         path = [u"session", u"enable"]
566         self.add_config_item(self._nodeconfig, u"", path)
567
568     def add_session_event_queues_memfd_segment(self):
569         """Add session event queue memfd segment."""
570         path = [u"session", u"evt_qs_memfd_seg"]
571         self.add_config_item(self._nodeconfig, u"", path)
572
573     def add_session_event_queue_length(self, value):
574         """Add session event queue length.
575
576         :param value: Session event queue length.
577         :type value: int
578         """
579         path = [u"session", u"event-queue-length"]
580         self.add_config_item(self._nodeconfig, value, path)
581
582     def add_session_event_queues_segment_size(self, value):
583         """Add session event queue length.
584
585         :param value: Session event queue segment size.
586         :type value: str
587         """
588         path = [u"session", u"evt_qs_seg_size"]
589         self.add_config_item(self._nodeconfig, value, path)
590
591     def add_session_preallocated_sessions(self, value):
592         """Add the number of pre-allocated sessions.
593
594         :param value: Number of pre-allocated sessions.
595         :type value: int
596         """
597         path = [u"session", u"preallocated-sessions"]
598         self.add_config_item(self._nodeconfig, value, path)
599
600     def add_session_v4_session_table_buckets(self, value):
601         """Add number of v4 session table buckets to the config.
602
603         :param value: Number of v4 session table buckets.
604         :type value: int
605         """
606         path = [u"session", u"v4-session-table-buckets"]
607         self.add_config_item(self._nodeconfig, value, path)
608
609     def add_session_v4_session_table_memory(self, value):
610         """Add the size of v4 session table memory.
611
612         :param value: Size of v4 session table memory.
613         :type value: str
614         """
615         path = [u"session", u"v4-session-table-memory"]
616         self.add_config_item(self._nodeconfig, value, path)
617
618     def add_session_v4_halfopen_table_buckets(self, value):
619         """Add the number of v4 halfopen table buckets.
620
621         :param value: Number of v4 halfopen table buckets.
622         :type value: int
623         """
624         path = [u"session", u"v4-halfopen-table-buckets"]
625         self.add_config_item(self._nodeconfig, value, path)
626
627     def add_session_v4_halfopen_table_memory(self, value):
628         """Add the size of v4 halfopen table memory.
629
630         :param value: Size of v4 halfopen table memory.
631         :type value: str
632         """
633         path = [u"session", u"v4-halfopen-table-memory"]
634         self.add_config_item(self._nodeconfig, value, path)
635
636     def add_session_local_endpoints_table_buckets(self, value):
637         """Add the number of local endpoints table buckets.
638
639         :param value: Number of local endpoints table buckets.
640         :type value: int
641         """
642         path = [u"session", u"local-endpoints-table-buckets"]
643         self.add_config_item(self._nodeconfig, value, path)
644
645     def add_session_local_endpoints_table_memory(self, value):
646         """Add the size of local endpoints table memory.
647
648         :param value: Size of local endpoints table memory.
649         :type value: str
650         """
651         path = [u"session", u"local-endpoints-table-memory"]
652         self.add_config_item(self._nodeconfig, value, path)
653
654     def write_config(self, filename=None):
655         """Generate and write VPP startup configuration to file.
656
657         Use data from calls to this class to form a startup.conf file and
658         replace /etc/vpp/startup.conf with it on topology node.
659
660         :param filename: Startup configuration file name.
661         :type filename: str
662         """
663         self.dump_config(self._nodeconfig)
664
665         if filename is None:
666             filename = self._vpp_startup_conf
667
668         if self._vpp_startup_conf_backup is not None:
669             cmd = f"cp {self._vpp_startup_conf} {self._vpp_startup_conf_backup}"
670             exec_cmd_no_error(
671                 self._node, cmd, sudo=True, message=u"Copy config file failed!"
672             )
673
674         cmd = f"echo \"{self._vpp_config}\" | sudo tee {filename}"
675         exec_cmd_no_error(
676             self._node, cmd, message=u"Writing config file failed!"
677         )
678
679     def apply_config(self, filename=None, verify_vpp=True):
680         """Generate and write VPP startup configuration to file and restart VPP.
681
682         Use data from calls to this class to form a startup.conf file and
683         replace /etc/vpp/startup.conf with it on topology node.
684
685         :param filename: Startup configuration file name.
686         :param verify_vpp: Verify VPP is running after restart.
687         :type filename: str
688         :type verify_vpp: bool
689         """
690         self.write_config(filename=filename)
691
692         VPPUtil.restart_vpp_service(self._node, self._node_key)
693         if verify_vpp:
694             VPPUtil.verify_vpp(self._node)
695
696     def restore_config(self):
697         """Restore VPP startup.conf from backup."""
698         cmd = f"cp {self._vpp_startup_conf_backup} {self._vpp_startup_conf}"
699         exec_cmd_no_error(
700             self._node, cmd, sudo=True, message=u"Copy config file failed!"
701         )