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