0333c9c0921db59e358e3d0bf2ca9742fad59cec
[csit.git] / resources / libraries / python / InterfaceUtil.py
1 # Copyright (c) 2020 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 """Interface util library."""
15
16 from time import sleep
17 from enum import IntEnum
18
19 from ipaddress import ip_address
20 from robot.api import logger
21
22 from resources.libraries.python.Constants import Constants
23 from resources.libraries.python.CpuUtils import CpuUtils
24 from resources.libraries.python.DUTSetup import DUTSetup
25 from resources.libraries.python.L2Util import L2Util
26 from resources.libraries.python.PapiExecutor import PapiSocketExecutor
27 from resources.libraries.python.parsers.JsonParser import JsonParser
28 from resources.libraries.python.ssh import SSH, exec_cmd_no_error
29 from resources.libraries.python.topology import NodeType, Topology
30 from resources.libraries.python.VPPUtil import VPPUtil
31
32
33 class InterfaceStatusFlags(IntEnum):
34     """Interface status flags."""
35     IF_STATUS_API_FLAG_ADMIN_UP = 1
36     IF_STATUS_API_FLAG_LINK_UP = 2
37
38
39 class MtuProto(IntEnum):
40     """MTU protocol."""
41     MTU_PROTO_API_L3 = 0
42     MTU_PROTO_API_IP4 = 1
43     MTU_PROTO_API_IP6 = 2
44     MTU_PROTO_API_MPLS = 3
45     MTU_PROTO_API_N = 4
46
47
48 class LinkDuplex(IntEnum):
49     """Link duplex"""
50     LINK_DUPLEX_API_UNKNOWN = 0
51     LINK_DUPLEX_API_HALF = 1
52     LINK_DUPLEX_API_FULL = 2
53
54
55 class SubInterfaceFlags(IntEnum):
56     """Sub-interface flags."""
57     SUB_IF_API_FLAG_NO_TAGS = 1
58     SUB_IF_API_FLAG_ONE_TAG = 2
59     SUB_IF_API_FLAG_TWO_TAGS = 4
60     SUB_IF_API_FLAG_DOT1AD = 8
61     SUB_IF_API_FLAG_EXACT_MATCH = 16
62     SUB_IF_API_FLAG_DEFAULT = 32
63     SUB_IF_API_FLAG_OUTER_VLAN_ID_ANY = 64
64     SUB_IF_API_FLAG_INNER_VLAN_ID_ANY = 128
65     SUB_IF_API_FLAG_DOT1AH = 256
66
67
68 class RxMode(IntEnum):
69     """RX mode"""
70     RX_MODE_API_UNKNOWN = 0
71     RX_MODE_API_POLLING = 1
72     RX_MODE_API_INTERRUPT = 2
73     RX_MODE_API_ADAPTIVE = 3
74     RX_MODE_API_DEFAULT = 4
75
76
77 class IfType(IntEnum):
78     """Interface type"""
79     # A hw interface
80     IF_API_TYPE_HARDWARE = 0
81     # A sub-interface
82     IF_API_TYPE_SUB = 1
83     IF_API_TYPE_P2P = 2
84     IF_API_TYPE_PIPE = 3
85
86
87 class LinkBondLoadBalanceAlgo(IntEnum):
88     """Link bonding load balance algorithm."""
89     BOND_API_LB_ALGO_L2 = 0
90     BOND_API_LB_ALGO_L34 = 1
91     BOND_API_LB_ALGO_L23 = 2
92     BOND_API_LB_ALGO_RR = 3
93     BOND_API_LB_ALGO_BC = 4
94     BOND_API_LB_ALGO_AB = 5
95
96
97 class LinkBondMode(IntEnum):
98     """Link bonding mode."""
99     BOND_API_MODE_ROUND_ROBIN = 1
100     BOND_API_MODE_ACTIVE_BACKUP = 2
101     BOND_API_MODE_XOR = 3
102     BOND_API_MODE_BROADCAST = 4
103     BOND_API_MODE_LACP = 5
104
105
106 class RdmaMode(IntEnum):
107     """RDMA interface mode."""
108     RDMA_API_MODE_AUTO = 0
109     RDMA_API_MODE_IBV = 1
110     RDMA_API_MODE_DV = 2
111
112
113 class InterfaceUtil:
114     """General utilities for managing interfaces"""
115
116     @staticmethod
117     def pci_to_int(pci_str):
118         """Convert PCI address from string format (0000:18:0a.0) to
119         integer representation (169345024).
120
121         :param pci_str: PCI address in string representation.
122         :type pci_str: str
123         :returns: Integer representation of PCI address.
124         :rtype: int
125         """
126         pci = list(pci_str.split(u":")[0:2])
127         pci.extend(pci_str.split(u":")[2].split(u"."))
128
129         return (int(pci[0], 16) | int(pci[1], 16) << 16 |
130                 int(pci[2], 16) << 24 | int(pci[3], 16) << 29)
131
132     @staticmethod
133     def pci_to_eth(node, pci_str):
134         """Convert PCI address on DUT to Linux ethernet name.
135
136         :param node: DUT node
137         :param pci_str: PCI address.
138         :type node: dict
139         :type pci_str: str
140         :returns: Ethernet name.
141         :rtype: str
142         """
143         cmd = f"basename /sys/bus/pci/devices/{pci_str}/net/*"
144         try:
145             stdout, _ = exec_cmd_no_error(node, cmd)
146         except RuntimeError:
147             raise RuntimeError(f"Cannot convert {pci_str} to ethernet name!")
148
149         return stdout.strip()
150
151     @staticmethod
152     def get_interface_index(node, interface):
153         """Get interface sw_if_index from topology file.
154
155         :param node: Node where the interface is.
156         :param interface: Numeric index or name string of a specific interface.
157         :type node: dict
158         :type interface: str or int
159         :returns: SW interface index.
160         :rtype: int
161         """
162         try:
163             sw_if_index = int(interface)
164         except ValueError:
165             sw_if_index = Topology.get_interface_sw_index(node, interface)
166             if sw_if_index is None:
167                 sw_if_index = \
168                     Topology.get_interface_sw_index_by_name(node, interface)
169         except TypeError as err:
170             raise TypeError(f"Wrong interface format {interface}") from err
171
172         return sw_if_index
173
174     @staticmethod
175     def set_interface_state(node, interface, state, if_type=u"key"):
176         """Set interface state on a node.
177
178         Function can be used for DUTs as well as for TGs.
179
180         :param node: Node where the interface is.
181         :param interface: Interface key or sw_if_index or name.
182         :param state: One of 'up' or 'down'.
183         :param if_type: Interface type
184         :type node: dict
185         :type interface: str or int
186         :type state: str
187         :type if_type: str
188         :returns: Nothing.
189         :raises ValueError: If the interface type is unknown.
190         :raises ValueError: If the state of interface is unexpected.
191         :raises ValueError: If the node has an unknown node type.
192         """
193         if if_type == u"key":
194             if isinstance(interface, str):
195                 sw_if_index = Topology.get_interface_sw_index(node, interface)
196                 iface_name = Topology.get_interface_name(node, interface)
197             else:
198                 sw_if_index = interface
199         elif if_type == u"name":
200             iface_key = Topology.get_interface_by_name(node, interface)
201             if iface_key is not None:
202                 sw_if_index = Topology.get_interface_sw_index(node, iface_key)
203             iface_name = interface
204         else:
205             raise ValueError(f"Unknown if_type: {if_type}")
206
207         if node[u"type"] == NodeType.DUT:
208             if state == u"up":
209                 flags = InterfaceStatusFlags.IF_STATUS_API_FLAG_ADMIN_UP.value
210             elif state == u"down":
211                 flags = 0
212             else:
213                 raise ValueError(f"Unexpected interface state: {state}")
214             cmd = u"sw_interface_set_flags"
215             err_msg = f"Failed to set interface state on host {node[u'host']}"
216             args = dict(
217                 sw_if_index=int(sw_if_index),
218                 flags=flags
219             )
220             with PapiSocketExecutor(node) as papi_exec:
221                 papi_exec.add(cmd, **args).get_reply(err_msg)
222         elif node[u"type"] == NodeType.TG or node[u"type"] == NodeType.VM:
223             cmd = f"ip link set {iface_name} {state}"
224             exec_cmd_no_error(node, cmd, sudo=True)
225         else:
226             raise ValueError(
227                 f"Node {node[u'host']} has unknown NodeType: {node[u'type']}"
228             )
229
230     @staticmethod
231     def set_interface_ethernet_mtu(node, iface_key, mtu):
232         """Set Ethernet MTU for specified interface.
233
234         Function can be used only for TGs.
235
236         :param node: Node where the interface is.
237         :param iface_key: Interface key from topology file.
238         :param mtu: MTU to set.
239         :type node: dict
240         :type iface_key: str
241         :type mtu: int
242         :returns: Nothing.
243         :raises ValueError: If the node type is "DUT".
244         :raises ValueError: If the node has an unknown node type.
245         """
246         if node[u"type"] == NodeType.DUT:
247             msg = f"Node {node[u'host']}: Setting Ethernet MTU for interface " \
248                 f"on DUT nodes not supported"
249         elif node[u"type"] != NodeType.TG:
250             msg = f"Node {node[u'host']} has unknown NodeType: {node[u'type']}"
251         else:
252             iface_name = Topology.get_interface_name(node, iface_key)
253             cmd = f"ip link set {iface_name} mtu {mtu}"
254             exec_cmd_no_error(node, cmd, sudo=True)
255             return
256         raise ValueError(msg)
257
258     @staticmethod
259     def set_default_ethernet_mtu_on_all_interfaces_on_node(node):
260         """Set default Ethernet MTU on all interfaces on node.
261
262         Function can be used only for TGs.
263
264         :param node: Node where to set default MTU.
265         :type node: dict
266         :returns: Nothing.
267         """
268         for ifc in node[u"interfaces"]:
269             InterfaceUtil.set_interface_ethernet_mtu(node, ifc, 1500)
270
271     @staticmethod
272     def vpp_set_interface_mtu(node, interface, mtu=9200):
273         """Set Ethernet MTU on interface.
274
275         :param node: VPP node.
276         :param interface: Interface to setup MTU. Default: 9200.
277         :param mtu: Ethernet MTU size in Bytes.
278         :type node: dict
279         :type interface: str or int
280         :type mtu: int
281         """
282         if isinstance(interface, str):
283             sw_if_index = Topology.get_interface_sw_index(node, interface)
284         else:
285             sw_if_index = interface
286
287         cmd = u"hw_interface_set_mtu"
288         err_msg = f"Failed to set interface MTU on host {node[u'host']}"
289         args = dict(
290             sw_if_index=sw_if_index,
291             mtu=int(mtu)
292         )
293         try:
294             with PapiSocketExecutor(node) as papi_exec:
295                 papi_exec.add(cmd, **args).get_reply(err_msg)
296         except AssertionError as err:
297             # TODO: Make failure tolerance optional.
298             logger.debug(f"Setting MTU failed. Expected?\n{err}")
299
300     @staticmethod
301     def vpp_set_interfaces_mtu_on_node(node, mtu=9200):
302         """Set Ethernet MTU on all interfaces.
303
304         :param node: VPP node.
305         :param mtu: Ethernet MTU size in Bytes. Default: 9200.
306         :type node: dict
307         :type mtu: int
308         """
309         for interface in node[u"interfaces"]:
310             InterfaceUtil.vpp_set_interface_mtu(node, interface, mtu)
311
312     @staticmethod
313     def vpp_set_interfaces_mtu_on_all_duts(nodes, mtu=9200):
314         """Set Ethernet MTU on all interfaces on all DUTs.
315
316         :param nodes: VPP nodes.
317         :param mtu: Ethernet MTU size in Bytes. Default: 9200.
318         :type nodes: dict
319         :type mtu: int
320         """
321         for node in nodes.values():
322             if node[u"type"] == NodeType.DUT:
323                 InterfaceUtil.vpp_set_interfaces_mtu_on_node(node, mtu)
324
325     @staticmethod
326     def vpp_node_interfaces_ready_wait(node, retries=15):
327         """Wait until all interfaces with admin-up are in link-up state.
328
329         :param node: Node to wait on.
330         :param retries: Number of retries to check interface status (optional,
331             default 15).
332         :type node: dict
333         :type retries: int
334         :returns: Nothing.
335         :raises RuntimeError: If any interface is not in link-up state after
336             defined number of retries.
337         """
338         for _ in range(0, retries):
339             not_ready = list()
340             out = InterfaceUtil.vpp_get_interface_data(node)
341             for interface in out:
342                 if interface.get(u"flags") == 1:
343                     not_ready.append(interface.get(u"interface_name"))
344             if not_ready:
345                 logger.debug(
346                     f"Interfaces still not in link-up state:\n{not_ready}"
347                 )
348                 sleep(1)
349             else:
350                 break
351         else:
352             err = f"Timeout, interfaces not up:\n{not_ready}" \
353                 if u"not_ready" in locals() else u"No check executed!"
354             raise RuntimeError(err)
355
356     @staticmethod
357     def all_vpp_interfaces_ready_wait(nodes, retries=15):
358         """Wait until all interfaces with admin-up are in link-up state for all
359         nodes in the topology.
360
361         :param nodes: Nodes in the topology.
362         :param retries: Number of retries to check interface status (optional,
363             default 15).
364         :type nodes: dict
365         :type retries: int
366         :returns: Nothing.
367         """
368         for node in nodes.values():
369             if node[u"type"] == NodeType.DUT:
370                 InterfaceUtil.vpp_node_interfaces_ready_wait(node, retries)
371
372     @staticmethod
373     def vpp_get_interface_data(node, interface=None):
374         """Get all interface data from a VPP node. If a name or
375         sw_interface_index is provided, return only data for the matching
376         interface(s).
377
378         :param node: VPP node to get interface data from.
379         :param interface: Numeric index or name string of a specific interface.
380         :type node: dict
381         :type interface: int or str
382         :returns: List of dictionaries containing data for each interface, or a
383             single dictionary for the specified interface.
384         :rtype: list or dict
385         :raises TypeError: if the data type of interface is neither basestring
386             nor int.
387         """
388         def process_if_dump(if_dump):
389             """Process interface dump.
390
391             :param if_dump: Interface dump.
392             :type if_dump: dict
393             :returns: Processed interface dump.
394             :rtype: dict
395             """
396             if_dump[u"l2_address"] = str(if_dump[u"l2_address"])
397             if_dump[u"b_dmac"] = str(if_dump[u"b_dmac"])
398             if_dump[u"b_smac"] = str(if_dump[u"b_smac"])
399             if_dump[u"flags"] = if_dump[u"flags"].value
400             if_dump[u"type"] = if_dump[u"type"].value
401             if_dump[u"link_duplex"] = if_dump[u"link_duplex"].value
402             if_dump[u"sub_if_flags"] = if_dump[u"sub_if_flags"].value \
403                 if hasattr(if_dump[u"sub_if_flags"], u"value") \
404                 else int(if_dump[u"sub_if_flags"])
405
406             return if_dump
407
408         if interface is not None:
409             if isinstance(interface, str):
410                 param = u"interface_name"
411             elif isinstance(interface, int):
412                 param = u"sw_if_index"
413             else:
414                 raise TypeError(f"Wrong interface format {interface}")
415         else:
416             param = u""
417
418         cmd = u"sw_interface_dump"
419         args = dict(
420             name_filter_valid=False,
421             name_filter=u""
422         )
423         err_msg = f"Failed to get interface dump on host {node[u'host']}"
424
425         with PapiSocketExecutor(node) as papi_exec:
426             details = papi_exec.add(cmd, **args).get_details(err_msg)
427         logger.debug(f"Received data:\n{details!r}")
428
429         data = list() if interface is None else dict()
430         for dump in details:
431             if interface is None:
432                 data.append(process_if_dump(dump))
433             elif str(dump.get(param)).rstrip(u"\x00") == str(interface):
434                 data = process_if_dump(dump)
435                 break
436
437         logger.debug(f"Interface data:\n{data}")
438         return data
439
440     @staticmethod
441     def vpp_get_interface_name(node, sw_if_index):
442         """Get interface name for the given SW interface index from actual
443         interface dump.
444
445         :param node: VPP node to get interface data from.
446         :param sw_if_index: SW interface index of the specific interface.
447         :type node: dict
448         :type sw_if_index: int
449         :returns: Name of the given interface.
450         :rtype: str
451         """
452         if_data = InterfaceUtil.vpp_get_interface_data(node, sw_if_index)
453         if if_data[u"sup_sw_if_index"] != if_data[u"sw_if_index"]:
454             if_data = InterfaceUtil.vpp_get_interface_data(
455                 node, if_data[u"sup_sw_if_index"]
456             )
457
458         return if_data.get(u"interface_name")
459
460     @staticmethod
461     def vpp_get_interface_sw_index(node, interface_name):
462         """Get interface name for the given SW interface index from actual
463         interface dump.
464
465         :param node: VPP node to get interface data from.
466         :param interface_name: Interface name.
467         :type node: dict
468         :type interface_name: str
469         :returns: Name of the given interface.
470         :rtype: str
471         """
472         if_data = InterfaceUtil.vpp_get_interface_data(node, interface_name)
473
474         return if_data.get(u"sw_if_index")
475
476     @staticmethod
477     def vpp_get_interface_mac(node, interface):
478         """Get MAC address for the given interface from actual interface dump.
479
480         :param node: VPP node to get interface data from.
481         :param interface: Numeric index or name string of a specific interface.
482         :type node: dict
483         :type interface: int or str
484         :returns: MAC address.
485         :rtype: str
486         """
487         if_data = InterfaceUtil.vpp_get_interface_data(node, interface)
488         if if_data[u"sup_sw_if_index"] != if_data[u"sw_if_index"]:
489             if_data = InterfaceUtil.vpp_get_interface_data(
490                 node, if_data[u"sup_sw_if_index"])
491
492         return if_data.get(u"l2_address")
493
494     @staticmethod
495     def vpp_set_interface_mac(node, interface, mac):
496         """Set MAC address for the given interface.
497
498         :param node: VPP node to set interface MAC.
499         :param interface: Numeric index or name string of a specific interface.
500         :param mac: Required MAC address.
501         :type node: dict
502         :type interface: int or str
503         :type mac: str
504         """
505         cmd = u"sw_interface_set_mac_address"
506         args = dict(
507             sw_if_index=InterfaceUtil.get_interface_index(node, interface),
508             mac_address=L2Util.mac_to_bin(mac)
509         )
510         err_msg = f"Failed to set MAC address of interface {interface}" \
511             f"on host {node[u'host']}"
512         with PapiSocketExecutor(node) as papi_exec:
513             papi_exec.add(cmd, **args).get_reply(err_msg)
514
515     @staticmethod
516     def tg_set_interface_driver(node, pci_addr, driver):
517         """Set interface driver on the TG node.
518
519         :param node: Node to set interface driver on (must be TG node).
520         :param pci_addr: PCI address of the interface.
521         :param driver: Driver name.
522         :type node: dict
523         :type pci_addr: str
524         :type driver: str
525         :raises RuntimeError: If unbinding from the current driver fails.
526         :raises RuntimeError: If binding to the new driver fails.
527         """
528         old_driver = InterfaceUtil.tg_get_interface_driver(node, pci_addr)
529         if old_driver == driver:
530             return
531
532         ssh = SSH()
533         ssh.connect(node)
534
535         # Unbind from current driver
536         if old_driver is not None:
537             cmd = f"sh -c \"echo {pci_addr} > " \
538                 f"/sys/bus/pci/drivers/{old_driver}/unbind\""
539             ret_code, _, _ = ssh.exec_command_sudo(cmd)
540             if int(ret_code) != 0:
541                 raise RuntimeError(f"'{cmd}' failed on '{node[u'host']}'")
542
543         # Bind to the new driver
544         cmd = f"sh -c \"echo {pci_addr} > /sys/bus/pci/drivers/{driver}/bind\""
545         ret_code, _, _ = ssh.exec_command_sudo(cmd)
546         if int(ret_code) != 0:
547             raise RuntimeError(f"'{cmd}' failed on '{node[u'host']}'")
548
549     @staticmethod
550     def tg_get_interface_driver(node, pci_addr):
551         """Get interface driver from the TG node.
552
553         :param node: Node to get interface driver on (must be TG node).
554         :param pci_addr: PCI address of the interface.
555         :type node: dict
556         :type pci_addr: str
557         :returns: Interface driver or None if not found.
558         :rtype: str
559         :raises RuntimeError: If PCI rescan or lspci command execution failed.
560         """
561         return DUTSetup.get_pci_dev_driver(node, pci_addr)
562
563     @staticmethod
564     def tg_set_interfaces_default_driver(node):
565         """Set interfaces default driver specified in topology yaml file.
566
567         :param node: Node to setup interfaces driver on (must be TG node).
568         :type node: dict
569         """
570         for interface in node[u"interfaces"].values():
571             InterfaceUtil.tg_set_interface_driver(
572                 node, interface[u"pci_address"], interface[u"driver"]
573             )
574
575     @staticmethod
576     def update_vpp_interface_data_on_node(node):
577         """Update vpp generated interface data for a given node in DICT__nodes.
578
579         Updates interface names, software if index numbers and any other details
580         generated specifically by vpp that are unknown before testcase run.
581         It does this by dumping interface list from all devices using python
582         api, and pairing known information from topology (mac address) to state
583         from VPP.
584
585         :param node: Node selected from DICT__nodes.
586         :type node: dict
587         """
588         interface_list = InterfaceUtil.vpp_get_interface_data(node)
589         interface_dict = dict()
590         for ifc in interface_list:
591             interface_dict[ifc[u"l2_address"]] = ifc
592
593         for if_name, if_data in node[u"interfaces"].items():
594             ifc_dict = interface_dict.get(if_data[u"mac_address"])
595             if ifc_dict is not None:
596                 if_data[u"name"] = ifc_dict[u"interface_name"]
597                 if_data[u"vpp_sw_index"] = ifc_dict[u"sw_if_index"]
598                 if_data[u"mtu"] = ifc_dict[u"mtu"][0]
599                 logger.trace(
600                     f"Interface {if_name} found by MAC "
601                     f"{if_data[u'mac_address']}"
602                 )
603             else:
604                 logger.trace(
605                     f"Interface {if_name} not found by MAC "
606                     f"{if_data[u'mac_address']}"
607                 )
608                 if_data[u"vpp_sw_index"] = None
609
610     @staticmethod
611     def update_nic_interface_names(node):
612         """Update interface names based on nic type and PCI address.
613
614         This method updates interface names in the same format as VPP does.
615
616         :param node: Node dictionary.
617         :type node: dict
618         """
619         for ifc in node[u"interfaces"].values():
620             if_pci = ifc[u"pci_address"].replace(u".", u":").split(u":")
621             loc = f"{int(if_pci[1], 16):x}/{int(if_pci[2], 16):x}/" \
622                 f"{int(if_pci[3], 16):x}"
623             if ifc[u"model"] == u"Intel-XL710":
624                 ifc[u"name"] = f"FortyGigabitEthernet{loc}"
625             elif ifc[u"model"] == u"Intel-X710":
626                 ifc[u"name"] = f"TenGigabitEthernet{loc}"
627             elif ifc[u"model"] == u"Intel-X520-DA2":
628                 ifc[u"name"] = f"TenGigabitEthernet{loc}"
629             elif ifc[u"model"] == u"Cisco-VIC-1385":
630                 ifc[u"name"] = f"FortyGigabitEthernet{loc}"
631             elif ifc[u"model"] == u"Cisco-VIC-1227":
632                 ifc[u"name"] = f"TenGigabitEthernet{loc}"
633             else:
634                 ifc[u"name"] = f"UnknownEthernet{loc}"
635
636     @staticmethod
637     def update_nic_interface_names_on_all_duts(nodes):
638         """Update interface names based on nic type and PCI address on all DUTs.
639
640         This method updates interface names in the same format as VPP does.
641
642         :param nodes: Topology nodes.
643         :type nodes: dict
644         """
645         for node in nodes.values():
646             if node[u"type"] == NodeType.DUT:
647                 InterfaceUtil.update_nic_interface_names(node)
648
649     @staticmethod
650     def update_tg_interface_data_on_node(node):
651         """Update interface name for TG/linux node in DICT__nodes.
652
653         .. note::
654             # for dev in `ls /sys/class/net/`;
655             > do echo "\"`cat /sys/class/net/$dev/address`\": \"$dev\""; done
656             "52:54:00:9f:82:63": "eth0"
657             "52:54:00:77:ae:a9": "eth1"
658             "52:54:00:e1:8a:0f": "eth2"
659             "00:00:00:00:00:00": "lo"
660
661         :param node: Node selected from DICT__nodes.
662         :type node: dict
663         :raises RuntimeError: If getting of interface name and MAC fails.
664         """
665         # First setup interface driver specified in yaml file
666         InterfaceUtil.tg_set_interfaces_default_driver(node)
667
668         # Get interface names
669         ssh = SSH()
670         ssh.connect(node)
671
672         cmd = u'for dev in `ls /sys/class/net/`; do echo "\\"`cat ' \
673               u'/sys/class/net/$dev/address`\\": \\"$dev\\""; done;'
674
675         ret_code, stdout, _ = ssh.exec_command(cmd)
676         if int(ret_code) != 0:
677             raise RuntimeError(u"Get interface name and MAC failed")
678         tmp = u"{" + stdout.rstrip().replace(u"\n", u",") + u"}"
679
680         interfaces = JsonParser().parse_data(tmp)
681         for interface in node[u"interfaces"].values():
682             name = interfaces.get(interface[u"mac_address"])
683             if name is None:
684                 continue
685             interface[u"name"] = name
686
687     @staticmethod
688     def iface_update_numa_node(node):
689         """For all interfaces from topology file update numa node based on
690            information from the node.
691
692         :param node: Node from topology.
693         :type node: dict
694         :returns: Nothing.
695         :raises ValueError: If numa node ia less than 0.
696         :raises RuntimeError: If update of numa node failed.
697         """
698         def check_cpu_node_count(node_n, val):
699             val = int(val)
700             if val < 0:
701                 if CpuUtils.cpu_node_count(node_n) == 1:
702                     val = 0
703                 else:
704                     raise ValueError
705             return val
706         ssh = SSH()
707         for if_key in Topology.get_node_interfaces(node):
708             if_pci = Topology.get_interface_pci_addr(node, if_key)
709             ssh.connect(node)
710             cmd = f"cat /sys/bus/pci/devices/{if_pci}/numa_node"
711             for _ in range(3):
712                 ret, out, _ = ssh.exec_command(cmd)
713                 if ret == 0:
714                     try:
715                         numa_node = check_cpu_node_count(node, out)
716                     except ValueError:
717                         logger.trace(
718                             f"Reading numa location failed for: {if_pci}"
719                         )
720                     else:
721                         Topology.set_interface_numa_node(
722                             node, if_key, numa_node
723                         )
724                         break
725             else:
726                 raise RuntimeError(f"Update numa node failed for: {if_pci}")
727
728     @staticmethod
729     def update_all_interface_data_on_all_nodes(
730             nodes, skip_tg=False, skip_vpp=False):
731         """Update interface names on all nodes in DICT__nodes.
732
733         This method updates the topology dictionary by querying interface lists
734         of all nodes mentioned in the topology dictionary.
735
736         :param nodes: Nodes in the topology.
737         :param skip_tg: Skip TG node.
738         :param skip_vpp: Skip VPP node.
739         :type nodes: dict
740         :type skip_tg: bool
741         :type skip_vpp: bool
742         """
743         for node in nodes.values():
744             if node[u"type"] == NodeType.DUT and not skip_vpp:
745                 InterfaceUtil.update_vpp_interface_data_on_node(node)
746             elif node[u"type"] == NodeType.TG and not skip_tg:
747                 InterfaceUtil.update_tg_interface_data_on_node(node)
748             InterfaceUtil.iface_update_numa_node(node)
749
750     @staticmethod
751     def create_vlan_subinterface(node, interface, vlan):
752         """Create VLAN sub-interface on node.
753
754         :param node: Node to add VLAN subinterface on.
755         :param interface: Interface name or index on which create VLAN
756             subinterface.
757         :param vlan: VLAN ID of the subinterface to be created.
758         :type node: dict
759         :type interface: str on int
760         :type vlan: int
761         :returns: Name and index of created subinterface.
762         :rtype: tuple
763         :raises RuntimeError: if it is unable to create VLAN subinterface on the
764             node or interface cannot be converted.
765         """
766         sw_if_index = InterfaceUtil.get_interface_index(node, interface)
767
768         cmd = u"create_vlan_subif"
769         args = dict(
770             sw_if_index=sw_if_index,
771             vlan_id=int(vlan)
772         )
773         err_msg = f"Failed to create VLAN sub-interface on host {node[u'host']}"
774
775         with PapiSocketExecutor(node) as papi_exec:
776             sw_if_index = papi_exec.add(cmd, **args).get_sw_if_index(err_msg)
777
778         if_key = Topology.add_new_port(node, u"vlan_subif")
779         Topology.update_interface_sw_if_index(node, if_key, sw_if_index)
780         ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_if_index)
781         Topology.update_interface_name(node, if_key, ifc_name)
782
783         return f"{interface}.{vlan}", sw_if_index
784
785     @staticmethod
786     def create_vxlan_interface(node, vni, source_ip, destination_ip):
787         """Create VXLAN interface and return sw if index of created interface.
788
789         :param node: Node where to create VXLAN interface.
790         :param vni: VXLAN Network Identifier.
791         :param source_ip: Source IP of a VXLAN Tunnel End Point.
792         :param destination_ip: Destination IP of a VXLAN Tunnel End Point.
793         :type node: dict
794         :type vni: int
795         :type source_ip: str
796         :type destination_ip: str
797         :returns: SW IF INDEX of created interface.
798         :rtype: int
799         :raises RuntimeError: if it is unable to create VxLAN interface on the
800             node.
801         """
802         src_address = ip_address(source_ip)
803         dst_address = ip_address(destination_ip)
804
805         cmd = u"vxlan_add_del_tunnel"
806         args = dict(
807             is_add=1,
808             is_ipv6=1 if src_address.version == 6 else 0,
809             instance=Constants.BITWISE_NON_ZERO,
810             src_address=src_address.packed,
811             dst_address=dst_address.packed,
812             mcast_sw_if_index=Constants.BITWISE_NON_ZERO,
813             encap_vrf_id=0,
814             decap_next_index=Constants.BITWISE_NON_ZERO,
815             vni=int(vni)
816         )
817         err_msg = f"Failed to create VXLAN tunnel interface " \
818             f"on host {node[u'host']}"
819         with PapiSocketExecutor(node) as papi_exec:
820             sw_if_index = papi_exec.add(cmd, **args).get_sw_if_index(err_msg)
821
822         if_key = Topology.add_new_port(node, u"vxlan_tunnel")
823         Topology.update_interface_sw_if_index(node, if_key, sw_if_index)
824         ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_if_index)
825         Topology.update_interface_name(node, if_key, ifc_name)
826
827         return sw_if_index
828
829     @staticmethod
830     def set_vxlan_bypass(node, interface=None):
831         """Add the 'ip4-vxlan-bypass' graph node for a given interface.
832
833         By adding the IPv4 vxlan-bypass graph node to an interface, the node
834         checks for and validate input vxlan packet and bypass ip4-lookup,
835         ip4-local, ip4-udp-lookup nodes to speedup vxlan packet forwarding.
836         This node will cause extra overhead to for non-vxlan packets which is
837         kept at a minimum.
838
839         :param node: Node where to set VXLAN bypass.
840         :param interface: Numeric index or name string of a specific interface.
841         :type node: dict
842         :type interface: int or str
843         :raises RuntimeError: if it failed to set VXLAN bypass on interface.
844         """
845         sw_if_index = InterfaceUtil.get_interface_index(node, interface)
846
847         cmd = u"sw_interface_set_vxlan_bypass"
848         args = dict(
849             is_ipv6=0,
850             sw_if_index=sw_if_index,
851             enable=1
852         )
853         err_msg = f"Failed to set VXLAN bypass on interface " \
854             f"on host {node[u'host']}"
855         with PapiSocketExecutor(node) as papi_exec:
856             papi_exec.add(cmd, **args).get_replies(err_msg)
857
858     @staticmethod
859     def vxlan_dump(node, interface=None):
860         """Get VxLAN data for the given interface.
861
862         :param node: VPP node to get interface data from.
863         :param interface: Numeric index or name string of a specific interface.
864             If None, information about all VxLAN interfaces is returned.
865         :type node: dict
866         :type interface: int or str
867         :returns: Dictionary containing data for the given VxLAN interface or if
868             interface=None, the list of dictionaries with all VxLAN interfaces.
869         :rtype: dict or list
870         :raises TypeError: if the data type of interface is neither basestring
871             nor int.
872         """
873         def process_vxlan_dump(vxlan_dump):
874             """Process vxlan dump.
875
876             :param vxlan_dump: Vxlan interface dump.
877             :type vxlan_dump: dict
878             :returns: Processed vxlan interface dump.
879             :rtype: dict
880             """
881             if vxlan_dump[u"is_ipv6"]:
882                 vxlan_dump[u"src_address"] = \
883                     ip_address(vxlan_dump[u"src_address"])
884                 vxlan_dump[u"dst_address"] =  \
885                     ip_address(vxlan_dump[u"dst_address"])
886             else:
887                 vxlan_dump[u"src_address"] = \
888                     ip_address(vxlan_dump[u"src_address"][0:4])
889                 vxlan_dump[u"dst_address"] = \
890                     ip_address(vxlan_dump[u"dst_address"][0:4])
891             return vxlan_dump
892
893         if interface is not None:
894             sw_if_index = InterfaceUtil.get_interface_index(node, interface)
895         else:
896             sw_if_index = int(Constants.BITWISE_NON_ZERO)
897
898         cmd = u"vxlan_tunnel_dump"
899         args = dict(
900             sw_if_index=sw_if_index
901         )
902         err_msg = f"Failed to get VXLAN dump on host {node[u'host']}"
903
904         with PapiSocketExecutor(node) as papi_exec:
905             details = papi_exec.add(cmd, **args).get_details(err_msg)
906
907         data = list() if interface is None else dict()
908         for dump in details:
909             if interface is None:
910                 data.append(process_vxlan_dump(dump))
911             elif dump[u"sw_if_index"] == sw_if_index:
912                 data = process_vxlan_dump(dump)
913                 break
914
915         logger.debug(f"VXLAN data:\n{data}")
916         return data
917
918     @staticmethod
919     def create_subinterface(
920             node, interface, sub_id, outer_vlan_id=None, inner_vlan_id=None,
921             type_subif=None):
922         """Create sub-interface on node. It is possible to set required
923         sub-interface type and VLAN tag(s).
924
925         :param node: Node to add sub-interface.
926         :param interface: Interface name on which create sub-interface.
927         :param sub_id: ID of the sub-interface to be created.
928         :param outer_vlan_id: Optional outer VLAN ID.
929         :param inner_vlan_id: Optional inner VLAN ID.
930         :param type_subif: Optional type of sub-interface. Values supported by
931             VPP: [no_tags] [one_tag] [two_tags] [dot1ad] [exact_match]
932             [default_sub]
933         :type node: dict
934         :type interface: str or int
935         :type sub_id: int
936         :type outer_vlan_id: int
937         :type inner_vlan_id: int
938         :type type_subif: str
939         :returns: Name and index of created sub-interface.
940         :rtype: tuple
941         :raises RuntimeError: If it is not possible to create sub-interface.
942         """
943         subif_types = type_subif.split()
944
945         flags = 0
946         if u"no_tags" in subif_types:
947             flags = flags | SubInterfaceFlags.SUB_IF_API_FLAG_NO_TAGS
948         if u"one_tag" in subif_types:
949             flags = flags | SubInterfaceFlags.SUB_IF_API_FLAG_ONE_TAG
950         if u"two_tags" in subif_types:
951             flags = flags | SubInterfaceFlags.SUB_IF_API_FLAG_TWO_TAGS
952         if u"dot1ad" in subif_types:
953             flags = flags | SubInterfaceFlags.SUB_IF_API_FLAG_DOT1AD
954         if u"exact_match" in subif_types:
955             flags = flags | SubInterfaceFlags.SUB_IF_API_FLAG_EXACT_MATCH
956         if u"default_sub" in subif_types:
957             flags = flags | SubInterfaceFlags.SUB_IF_API_FLAG_DEFAULT
958         if type_subif == u"default_sub":
959             flags = flags | SubInterfaceFlags.SUB_IF_API_FLAG_INNER_VLAN_ID_ANY\
960                     | SubInterfaceFlags.SUB_IF_API_FLAG_OUTER_VLAN_ID_ANY
961
962         cmd = u"create_subif"
963         args = dict(
964             sw_if_index=InterfaceUtil.get_interface_index(node, interface),
965             sub_id=int(sub_id),
966             sub_if_flags=flags.value if hasattr(flags, u"value")
967             else int(flags),
968             outer_vlan_id=int(outer_vlan_id) if outer_vlan_id else 0,
969             inner_vlan_id=int(inner_vlan_id) if inner_vlan_id else 0
970         )
971         err_msg = f"Failed to create sub-interface on host {node[u'host']}"
972         with PapiSocketExecutor(node) as papi_exec:
973             sw_if_index = papi_exec.add(cmd, **args).get_sw_if_index(err_msg)
974
975         if_key = Topology.add_new_port(node, u"subinterface")
976         Topology.update_interface_sw_if_index(node, if_key, sw_if_index)
977         ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_if_index)
978         Topology.update_interface_name(node, if_key, ifc_name)
979
980         return f"{interface}.{sub_id}", sw_if_index
981
982     @staticmethod
983     def create_gre_tunnel_interface(node, source_ip, destination_ip):
984         """Create GRE tunnel interface on node.
985
986         :param node: VPP node to add tunnel interface.
987         :param source_ip: Source of the GRE tunnel.
988         :param destination_ip: Destination of the GRE tunnel.
989         :type node: dict
990         :type source_ip: str
991         :type destination_ip: str
992         :returns: Name and index of created GRE tunnel interface.
993         :rtype: tuple
994         :raises RuntimeError: If unable to create GRE tunnel interface.
995         """
996         cmd = u"gre_tunnel_add_del"
997         tunnel = dict(
998             type=0,
999             instance=Constants.BITWISE_NON_ZERO,
1000             src=str(source_ip),
1001             dst=str(destination_ip),
1002             outer_fib_id=0,
1003             session_id=0
1004         )
1005         args = dict(
1006             is_add=1,
1007             tunnel=tunnel
1008         )
1009         err_msg = f"Failed to create GRE tunnel interface " \
1010             f"on host {node[u'host']}"
1011         with PapiSocketExecutor(node) as papi_exec:
1012             sw_if_index = papi_exec.add(cmd, **args).get_sw_if_index(err_msg)
1013
1014         if_key = Topology.add_new_port(node, u"gre_tunnel")
1015         Topology.update_interface_sw_if_index(node, if_key, sw_if_index)
1016         ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_if_index)
1017         Topology.update_interface_name(node, if_key, ifc_name)
1018
1019         return ifc_name, sw_if_index
1020
1021     @staticmethod
1022     def vpp_create_loopback(node, mac=None):
1023         """Create loopback interface on VPP node.
1024
1025         :param node: Node to create loopback interface on.
1026         :param mac: Optional MAC address for loopback interface.
1027         :type node: dict
1028         :type mac: str
1029         :returns: SW interface index.
1030         :rtype: int
1031         :raises RuntimeError: If it is not possible to create loopback on the
1032             node.
1033         """
1034         cmd = u"create_loopback"
1035         args = dict(
1036             mac_address=L2Util.mac_to_bin(mac) if mac else 0
1037         )
1038         err_msg = f"Failed to create loopback interface on host {node[u'host']}"
1039         with PapiSocketExecutor(node) as papi_exec:
1040             sw_if_index = papi_exec.add(cmd, **args).get_sw_if_index(err_msg)
1041
1042         if_key = Topology.add_new_port(node, u"loopback")
1043         Topology.update_interface_sw_if_index(node, if_key, sw_if_index)
1044         ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_if_index)
1045         Topology.update_interface_name(node, if_key, ifc_name)
1046         if mac:
1047             mac = InterfaceUtil.vpp_get_interface_mac(node, ifc_name)
1048             Topology.update_interface_mac_address(node, if_key, mac)
1049
1050         return sw_if_index
1051
1052     @staticmethod
1053     def vpp_create_bond_interface(node, mode, load_balance=None, mac=None):
1054         """Create bond interface on VPP node.
1055
1056         :param node: DUT node from topology.
1057         :param mode: Link bonding mode.
1058         :param load_balance: Load balance (optional, valid for xor and lacp
1059             modes, otherwise ignored).
1060         :param mac: MAC address to assign to the bond interface (optional).
1061         :type node: dict
1062         :type mode: str
1063         :type load_balance: str
1064         :type mac: str
1065         :returns: Interface key (name) in topology.
1066         :rtype: str
1067         :raises RuntimeError: If it is not possible to create bond interface on
1068             the node.
1069         """
1070         cmd = u"bond_create"
1071         args = dict(
1072             id=int(Constants.BITWISE_NON_ZERO),
1073             use_custom_mac=bool(mac is not None),
1074             mac_address=L2Util.mac_to_bin(mac) if mac else None,
1075             mode=getattr(
1076                 LinkBondMode,
1077                 f"BOND_API_MODE_{mode.replace(u'-', u'_').upper()}"
1078             ).value,
1079             lb=0 if load_balance is None else getattr(
1080                 LinkBondLoadBalanceAlgo,
1081                 f"BOND_API_LB_ALGO_{load_balance.upper()}"
1082             ).value,
1083             numa_only=False
1084         )
1085         err_msg = f"Failed to create bond interface on host {node[u'host']}"
1086         with PapiSocketExecutor(node) as papi_exec:
1087             sw_if_index = papi_exec.add(cmd, **args).get_sw_if_index(err_msg)
1088
1089         InterfaceUtil.add_eth_interface(
1090             node, sw_if_index=sw_if_index, ifc_pfx=u"eth_bond"
1091         )
1092         if_key = Topology.get_interface_by_sw_index(node, sw_if_index)
1093
1094         return if_key
1095
1096     @staticmethod
1097     def add_eth_interface(
1098             node, ifc_name=None, sw_if_index=None, ifc_pfx=None,
1099             host_if_key=None):
1100         """Add ethernet interface to current topology.
1101
1102         :param node: DUT node from topology.
1103         :param ifc_name: Name of the interface.
1104         :param sw_if_index: SW interface index.
1105         :param ifc_pfx: Interface key prefix.
1106         :param host_if_key: Host interface key from topology file.
1107         :type node: dict
1108         :type ifc_name: str
1109         :type sw_if_index: int
1110         :type ifc_pfx: str
1111         :type host_if_key: str
1112         """
1113         if_key = Topology.add_new_port(node, ifc_pfx)
1114
1115         if ifc_name and sw_if_index is None:
1116             sw_if_index = InterfaceUtil.vpp_get_interface_sw_index(
1117                 node, ifc_name)
1118         Topology.update_interface_sw_if_index(node, if_key, sw_if_index)
1119         if sw_if_index and ifc_name is None:
1120             ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_if_index)
1121         Topology.update_interface_name(node, if_key, ifc_name)
1122         ifc_mac = InterfaceUtil.vpp_get_interface_mac(node, sw_if_index)
1123         Topology.update_interface_mac_address(node, if_key, ifc_mac)
1124         if host_if_key is not None:
1125             Topology.set_interface_numa_node(
1126                 node, if_key, Topology.get_interface_numa_node(
1127                     node, host_if_key
1128                 )
1129             )
1130             Topology.update_interface_pci_address(
1131                 node, if_key, Topology.get_interface_pci_addr(node, host_if_key)
1132             )
1133
1134     @staticmethod
1135     def vpp_create_avf_interface(
1136             node, if_key, num_rx_queues=None, rxq_size=0, txq_size=0):
1137         """Create AVF interface on VPP node.
1138
1139         :param node: DUT node from topology.
1140         :param if_key: Interface key from topology file of interface
1141             to be bound to i40evf driver.
1142         :param num_rx_queues: Number of RX queues.
1143         :param rxq_size: Size of RXQ (0 = Default API; 512 = Default VPP).
1144         :param txq_size: Size of TXQ (0 = Default API; 512 = Default VPP).
1145         :type node: dict
1146         :type if_key: str
1147         :type num_rx_queues: int
1148         :type rxq_size: int
1149         :type txq_size: int
1150         :returns: AVF interface key (name) in topology.
1151         :rtype: str
1152         :raises RuntimeError: If it is not possible to create AVF interface on
1153             the node.
1154         """
1155         PapiSocketExecutor.run_cli_cmd(
1156             node, u"set logging class avf level debug"
1157         )
1158
1159         cmd = u"avf_create"
1160         vf_pci_addr = Topology.get_interface_pci_addr(node, if_key)
1161         args = dict(
1162             pci_addr=InterfaceUtil.pci_to_int(vf_pci_addr),
1163             enable_elog=0,
1164             rxq_num=int(num_rx_queues) if num_rx_queues else 0,
1165             rxq_size=rxq_size,
1166             txq_size=txq_size
1167         )
1168         err_msg = f"Failed to create AVF interface on host {node[u'host']}"
1169         with PapiSocketExecutor(node) as papi_exec:
1170             sw_if_index = papi_exec.add(cmd, **args).get_sw_if_index(err_msg)
1171
1172         InterfaceUtil.add_eth_interface(
1173             node, sw_if_index=sw_if_index, ifc_pfx=u"eth_avf",
1174             host_if_key=if_key
1175         )
1176
1177         return Topology.get_interface_by_sw_index(node, sw_if_index)
1178
1179     @staticmethod
1180     def vpp_create_rdma_interface(
1181             node, if_key, num_rx_queues=None, rxq_size=0, txq_size=0,
1182             mode=u"auto"):
1183         """Create RDMA interface on VPP node.
1184
1185         :param node: DUT node from topology.
1186         :param if_key: Physical interface key from topology file of interface
1187             to be bound to rdma-core driver.
1188         :param num_rx_queues: Number of RX queues.
1189         :param rxq_size: Size of RXQ (0 = Default API; 512 = Default VPP).
1190         :param txq_size: Size of TXQ (0 = Default API; 512 = Default VPP).
1191         :param mode: RDMA interface mode - auto/ibv/dv.
1192         :type node: dict
1193         :type if_key: str
1194         :type num_rx_queues: int
1195         :type rxq_size: int
1196         :type txq_size: int
1197         :type mode: str
1198         :returns: Interface key (name) in topology file.
1199         :rtype: str
1200         :raises RuntimeError: If it is not possible to create RDMA interface on
1201             the node.
1202         """
1203         cmd = u"rdma_create"
1204         pci_addr = Topology.get_interface_pci_addr(node, if_key)
1205         args = dict(
1206             name=InterfaceUtil.pci_to_eth(node, pci_addr),
1207             host_if=InterfaceUtil.pci_to_eth(node, pci_addr),
1208             rxq_num=int(num_rx_queues) if num_rx_queues else 0,
1209             rxq_size=rxq_size,
1210             txq_size=txq_size,
1211             mode=getattr(RdmaMode,f"RDMA_API_MODE_{mode.upper()}").value,
1212         )
1213         err_msg = f"Failed to create RDMA interface on host {node[u'host']}"
1214         with PapiSocketExecutor(node) as papi_exec:
1215             sw_if_index = papi_exec.add(cmd, **args).get_sw_if_index(err_msg)
1216
1217         InterfaceUtil.vpp_set_interface_mac(
1218             node, sw_if_index, Topology.get_interface_mac(node, if_key)
1219         )
1220         InterfaceUtil.add_eth_interface(
1221             node, sw_if_index=sw_if_index, ifc_pfx=u"eth_rdma",
1222             host_if_key=if_key
1223         )
1224
1225         return Topology.get_interface_by_sw_index(node, sw_if_index)
1226
1227     @staticmethod
1228     def vpp_enslave_physical_interface(node, interface, bond_if):
1229         """Enslave physical interface to bond interface on VPP node.
1230
1231         :param node: DUT node from topology.
1232         :param interface: Physical interface key from topology file.
1233         :param bond_if: Load balance
1234         :type node: dict
1235         :type interface: str
1236         :type bond_if: str
1237         :raises RuntimeError: If it is not possible to enslave physical
1238             interface to bond interface on the node.
1239         """
1240         cmd = u"bond_enslave"
1241         args = dict(
1242             sw_if_index=Topology.get_interface_sw_index(node, interface),
1243             bond_sw_if_index=Topology.get_interface_sw_index(node, bond_if),
1244             is_passive=False,
1245             is_long_timeout=False
1246         )
1247         err_msg = f"Failed to enslave physical interface {interface} to bond " \
1248             f"interface {bond_if} on host {node[u'host']}"
1249         with PapiSocketExecutor(node) as papi_exec:
1250             papi_exec.add(cmd, **args).get_reply(err_msg)
1251
1252     @staticmethod
1253     def vpp_show_bond_data_on_node(node, verbose=False):
1254         """Show (detailed) bond information on VPP node.
1255
1256         :param node: DUT node from topology.
1257         :param verbose: If detailed information is required or not.
1258         :type node: dict
1259         :type verbose: bool
1260         """
1261         cmd = u"sw_interface_bond_dump"
1262         err_msg = f"Failed to get bond interface dump on host {node[u'host']}"
1263
1264         data = f"Bond data on node {node[u'host']}:\n"
1265         with PapiSocketExecutor(node) as papi_exec:
1266             details = papi_exec.add(cmd).get_details(err_msg)
1267
1268         for bond in details:
1269             data += f"{bond[u'interface_name']}\n"
1270             data += u"  mode: {m}\n".format(
1271                 m=bond[u"mode"].name.replace(u"BOND_API_MODE_", u"").lower()
1272             )
1273             data += u"  load balance: {lb}\n".format(
1274                 lb=bond[u"lb"].name.replace(u"BOND_API_LB_ALGO_", u"").lower()
1275             )
1276             data += f"  number of active slaves: {bond[u'active_slaves']}\n"
1277             if verbose:
1278                 slave_data = InterfaceUtil.vpp_bond_slave_dump(
1279                     node, Topology.get_interface_by_sw_index(
1280                         node, bond[u"sw_if_index"]
1281                     )
1282                 )
1283                 for slave in slave_data:
1284                     if not slave[u"is_passive"]:
1285                         data += f"    {slave[u'interface_name']}\n"
1286             data += f"  number of slaves: {bond[u'slaves']}\n"
1287             if verbose:
1288                 for slave in slave_data:
1289                     data += f"    {slave[u'interface_name']}\n"
1290             data += f"  interface id: {bond[u'id']}\n"
1291             data += f"  sw_if_index: {bond[u'sw_if_index']}\n"
1292         logger.info(data)
1293
1294     @staticmethod
1295     def vpp_bond_slave_dump(node, interface):
1296         """Get bond interface slave(s) data on VPP node.
1297
1298         :param node: DUT node from topology.
1299         :param interface: Physical interface key from topology file.
1300         :type node: dict
1301         :type interface: str
1302         :returns: Bond slave interface data.
1303         :rtype: dict
1304         """
1305         cmd = u"sw_interface_slave_dump"
1306         args = dict(
1307             sw_if_index=Topology.get_interface_sw_index(node, interface)
1308         )
1309         err_msg = f"Failed to get slave dump on host {node[u'host']}"
1310
1311         with PapiSocketExecutor(node) as papi_exec:
1312             details = papi_exec.add(cmd, **args).get_details(err_msg)
1313
1314         logger.debug(f"Slave data:\n{details}")
1315         return details
1316
1317     @staticmethod
1318     def vpp_show_bond_data_on_all_nodes(nodes, verbose=False):
1319         """Show (detailed) bond information on all VPP nodes in DICT__nodes.
1320
1321         :param nodes: Nodes in the topology.
1322         :param verbose: If detailed information is required or not.
1323         :type nodes: dict
1324         :type verbose: bool
1325         """
1326         for node_data in nodes.values():
1327             if node_data[u"type"] == NodeType.DUT:
1328                 InterfaceUtil.vpp_show_bond_data_on_node(node_data, verbose)
1329
1330     @staticmethod
1331     def vpp_enable_input_acl_interface(
1332             node, interface, ip_version, table_index):
1333         """Enable input acl on interface.
1334
1335         :param node: VPP node to setup interface for input acl.
1336         :param interface: Interface to setup input acl.
1337         :param ip_version: Version of IP protocol.
1338         :param table_index: Classify table index.
1339         :type node: dict
1340         :type interface: str or int
1341         :type ip_version: str
1342         :type table_index: int
1343         """
1344         cmd = u"input_acl_set_interface"
1345         args = dict(
1346             sw_if_index=InterfaceUtil.get_interface_index(node, interface),
1347             ip4_table_index=table_index if ip_version == u"ip4"
1348             else Constants.BITWISE_NON_ZERO,
1349             ip6_table_index=table_index if ip_version == u"ip6"
1350             else Constants.BITWISE_NON_ZERO,
1351             l2_table_index=table_index if ip_version == u"l2"
1352             else Constants.BITWISE_NON_ZERO,
1353             is_add=1)
1354         err_msg = f"Failed to enable input acl on interface {interface}"
1355         with PapiSocketExecutor(node) as papi_exec:
1356             papi_exec.add(cmd, **args).get_reply(err_msg)
1357
1358     @staticmethod
1359     def get_interface_classify_table(node, interface):
1360         """Get name of classify table for the given interface.
1361
1362         TODO: Move to Classify.py.
1363
1364         :param node: VPP node to get data from.
1365         :param interface: Name or sw_if_index of a specific interface.
1366         :type node: dict
1367         :type interface: str or int
1368         :returns: Classify table name.
1369         :rtype: str
1370         """
1371         if isinstance(interface, str):
1372             sw_if_index = InterfaceUtil.get_sw_if_index(node, interface)
1373         else:
1374             sw_if_index = interface
1375
1376         cmd = u"classify_table_by_interface"
1377         args = dict(
1378             sw_if_index=sw_if_index
1379         )
1380         err_msg = f"Failed to get classify table name by interface {interface}"
1381         with PapiSocketExecutor(node) as papi_exec:
1382             reply = papi_exec.add(cmd, **args).get_reply(err_msg)
1383
1384         return reply
1385
1386     @staticmethod
1387     def get_sw_if_index(node, interface_name):
1388         """Get sw_if_index for the given interface from actual interface dump.
1389
1390         FIXME: Delete and redirect callers to vpp_get_interface_sw_index.
1391
1392         :param node: VPP node to get interface data from.
1393         :param interface_name: Name of the specific interface.
1394         :type node: dict
1395         :type interface_name: str
1396         :returns: sw_if_index of the given interface.
1397         :rtype: str
1398         """
1399         interface_data = InterfaceUtil.vpp_get_interface_data(
1400             node, interface=interface_name
1401         )
1402         return interface_data.get(u"sw_if_index")
1403
1404     @staticmethod
1405     def vxlan_gpe_dump(node, interface_name=None):
1406         """Get VxLAN GPE data for the given interface.
1407
1408         :param node: VPP node to get interface data from.
1409         :param interface_name: Name of the specific interface. If None,
1410             information about all VxLAN GPE interfaces is returned.
1411         :type node: dict
1412         :type interface_name: str
1413         :returns: Dictionary containing data for the given VxLAN GPE interface
1414             or if interface=None, the list of dictionaries with all VxLAN GPE
1415             interfaces.
1416         :rtype: dict or list
1417         """
1418         def process_vxlan_gpe_dump(vxlan_dump):
1419             """Process vxlan_gpe dump.
1420
1421             :param vxlan_dump: Vxlan_gpe nterface dump.
1422             :type vxlan_dump: dict
1423             :returns: Processed vxlan_gpe interface dump.
1424             :rtype: dict
1425             """
1426             if vxlan_dump[u"is_ipv6"]:
1427                 vxlan_dump[u"local"] = ip_address(vxlan_dump[u"local"])
1428                 vxlan_dump[u"remote"] = ip_address(vxlan_dump[u"remote"])
1429             else:
1430                 vxlan_dump[u"local"] = ip_address(vxlan_dump[u"local"][0:4])
1431                 vxlan_dump[u"remote"] = ip_address(vxlan_dump[u"remote"][0:4])
1432             return vxlan_dump
1433
1434         if interface_name is not None:
1435             sw_if_index = InterfaceUtil.get_interface_index(
1436                 node, interface_name
1437             )
1438         else:
1439             sw_if_index = int(Constants.BITWISE_NON_ZERO)
1440
1441         cmd = u"vxlan_gpe_tunnel_dump"
1442         args = dict(
1443             sw_if_index=sw_if_index
1444         )
1445         err_msg = f"Failed to get VXLAN-GPE dump on host {node[u'host']}"
1446         with PapiSocketExecutor(node) as papi_exec:
1447             details = papi_exec.add(cmd, **args).get_details(err_msg)
1448
1449         data = list() if interface_name is None else dict()
1450         for dump in details:
1451             if interface_name is None:
1452                 data.append(process_vxlan_gpe_dump(dump))
1453             elif dump[u"sw_if_index"] == sw_if_index:
1454                 data = process_vxlan_gpe_dump(dump)
1455                 break
1456
1457         logger.debug(f"VXLAN-GPE data:\n{data}")
1458         return data
1459
1460     @staticmethod
1461     def assign_interface_to_fib_table(node, interface, table_id, ipv6=False):
1462         """Assign VPP interface to specific VRF/FIB table.
1463
1464         :param node: VPP node where the FIB and interface are located.
1465         :param interface: Interface to be assigned to FIB.
1466         :param table_id: VRF table ID.
1467         :param ipv6: Assign to IPv6 table. Default False.
1468         :type node: dict
1469         :type interface: str or int
1470         :type table_id: int
1471         :type ipv6: bool
1472         """
1473         cmd = u"sw_interface_set_table"
1474         args = dict(
1475             sw_if_index=InterfaceUtil.get_interface_index(node, interface),
1476             is_ipv6=ipv6,
1477             vrf_id=int(table_id)
1478         )
1479         err_msg = f"Failed to assign interface {interface} to FIB table"
1480         with PapiSocketExecutor(node) as papi_exec:
1481             papi_exec.add(cmd, **args).get_reply(err_msg)
1482
1483     @staticmethod
1484     def set_linux_interface_mac(
1485             node, interface, mac, namespace=None, vf_id=None):
1486         """Set MAC address for interface in linux.
1487
1488         :param node: Node where to execute command.
1489         :param interface: Interface in namespace.
1490         :param mac: MAC to be assigned to interface.
1491         :param namespace: Execute command in namespace. Optional
1492         :param vf_id: Virtual Function id. Optional
1493         :type node: dict
1494         :type interface: str
1495         :type mac: str
1496         :type namespace: str
1497         :type vf_id: int
1498         """
1499         mac_str = f"vf {vf_id} mac {mac}" if vf_id is not None \
1500             else f"address {mac}"
1501         ns_str = f"ip netns exec {namespace}" if namespace else u""
1502
1503         cmd = f"{ns_str} ip link set {interface} {mac_str}"
1504         exec_cmd_no_error(node, cmd, sudo=True)
1505
1506     @staticmethod
1507     def set_linux_interface_trust_on(
1508             node, interface, namespace=None, vf_id=None):
1509         """Set trust on (promisc) for interface in linux.
1510
1511         :param node: Node where to execute command.
1512         :param interface: Interface in namespace.
1513         :param namespace: Execute command in namespace. Optional
1514         :param vf_id: Virtual Function id. Optional
1515         :type node: dict
1516         :type interface: str
1517         :type namespace: str
1518         :type vf_id: int
1519         """
1520         trust_str = f"vf {vf_id} trust on" if vf_id is not None else u"trust on"
1521         ns_str = f"ip netns exec {namespace}" if namespace else u""
1522
1523         cmd = f"{ns_str} ip link set dev {interface} {trust_str}"
1524         exec_cmd_no_error(node, cmd, sudo=True)
1525
1526     @staticmethod
1527     def set_linux_interface_spoof_off(
1528             node, interface, namespace=None, vf_id=None):
1529         """Set spoof off for interface in linux.
1530
1531         :param node: Node where to execute command.
1532         :param interface: Interface in namespace.
1533         :param namespace: Execute command in namespace. Optional
1534         :param vf_id: Virtual Function id. Optional
1535         :type node: dict
1536         :type interface: str
1537         :type namespace: str
1538         :type vf_id: int
1539         """
1540         spoof_str = f"vf {vf_id} spoof off" if vf_id is not None \
1541             else u"spoof off"
1542         ns_str = f"ip netns exec {namespace}" if namespace else u""
1543
1544         cmd = f"{ns_str} ip link set dev {interface} {spoof_str}"
1545         exec_cmd_no_error(node, cmd, sudo=True)
1546
1547     @staticmethod
1548     def init_avf_interface(node, ifc_key, numvfs=1, osi_layer=u"L2"):
1549         """Init PCI device by creating VIFs and bind them to vfio-pci for AVF
1550         driver testing on DUT.
1551
1552         :param node: DUT node.
1553         :param ifc_key: Interface key from topology file.
1554         :param numvfs: Number of VIFs to initialize, 0 - disable the VIFs.
1555         :param osi_layer: OSI Layer type to initialize TG with.
1556             Default value "L2" sets linux interface spoof off.
1557         :type node: dict
1558         :type ifc_key: str
1559         :type numvfs: int
1560         :type osi_layer: str
1561         :returns: Virtual Function topology interface keys.
1562         :rtype: list
1563         :raises RuntimeError: If a reason preventing initialization is found.
1564         """
1565         # Read PCI address and driver.
1566         pf_pci_addr = Topology.get_interface_pci_addr(node, ifc_key)
1567         pf_mac_addr = Topology.get_interface_mac(node, ifc_key).split(":")
1568         uio_driver = Topology.get_uio_driver(node)
1569         kernel_driver = Topology.get_interface_driver(node, ifc_key)
1570         if kernel_driver not in (u"i40e", u"i40evf"):
1571             raise RuntimeError(
1572                 f"AVF needs i40e-compatible driver, not {kernel_driver} "
1573                 f"at node {node[u'host']} ifc {ifc_key}"
1574             )
1575         current_driver = DUTSetup.get_pci_dev_driver(
1576             node, pf_pci_addr.replace(u":", r"\:"))
1577
1578         VPPUtil.stop_vpp_service(node)
1579         if current_driver != kernel_driver:
1580             # PCI device must be re-bound to kernel driver before creating VFs.
1581             DUTSetup.verify_kernel_module(node, kernel_driver, force_load=True)
1582             # Stop VPP to prevent deadlock.
1583             # Unbind from current driver.
1584             DUTSetup.pci_driver_unbind(node, pf_pci_addr)
1585             # Bind to kernel driver.
1586             DUTSetup.pci_driver_bind(node, pf_pci_addr, kernel_driver)
1587
1588         # Initialize PCI VFs.
1589         DUTSetup.set_sriov_numvfs(node, pf_pci_addr, numvfs)
1590
1591         vf_ifc_keys = []
1592         # Set MAC address and bind each virtual function to uio driver.
1593         for vf_id in range(numvfs):
1594             vf_mac_addr = u":".join(
1595                 [pf_mac_addr[0], pf_mac_addr[2], pf_mac_addr[3], pf_mac_addr[4],
1596                  pf_mac_addr[5], f"{vf_id:02x}"
1597                  ]
1598             )
1599
1600             pf_dev = f"`basename /sys/bus/pci/devices/{pf_pci_addr}/net/*`"
1601             InterfaceUtil.set_linux_interface_trust_on(
1602                 node, pf_dev, vf_id=vf_id
1603             )
1604             if osi_layer == u"L2":
1605                 InterfaceUtil.set_linux_interface_spoof_off(
1606                     node, pf_dev, vf_id=vf_id
1607                 )
1608             InterfaceUtil.set_linux_interface_mac(
1609                 node, pf_dev, vf_mac_addr, vf_id=vf_id
1610             )
1611
1612             DUTSetup.pci_vf_driver_unbind(node, pf_pci_addr, vf_id)
1613             DUTSetup.pci_vf_driver_bind(node, pf_pci_addr, vf_id, uio_driver)
1614
1615             # Add newly created ports into topology file
1616             vf_ifc_name = f"{ifc_key}_vif"
1617             vf_pci_addr = DUTSetup.get_virtfn_pci_addr(node, pf_pci_addr, vf_id)
1618             vf_ifc_key = Topology.add_new_port(node, vf_ifc_name)
1619             Topology.update_interface_name(
1620                 node, vf_ifc_key, vf_ifc_name+str(vf_id+1)
1621             )
1622             Topology.update_interface_mac_address(node, vf_ifc_key, vf_mac_addr)
1623             Topology.update_interface_pci_address(node, vf_ifc_key, vf_pci_addr)
1624             Topology.set_interface_numa_node(
1625                 node, vf_ifc_key, Topology.get_interface_numa_node(
1626                     node, ifc_key
1627                 )
1628             )
1629             vf_ifc_keys.append(vf_ifc_key)
1630
1631         return vf_ifc_keys
1632
1633     @staticmethod
1634     def vpp_sw_interface_rx_placement_dump(node):
1635         """Dump VPP interface RX placement on node.
1636
1637         :param node: Node to run command on.
1638         :type node: dict
1639         :returns: Thread mapping information as a list of dictionaries.
1640         :rtype: list
1641         """
1642         cmd = u"sw_interface_rx_placement_dump"
1643         err_msg = f"Failed to run '{cmd}' PAPI command on host {node[u'host']}!"
1644         with PapiSocketExecutor(node) as papi_exec:
1645             for ifc in node[u"interfaces"].values():
1646                 if ifc[u"vpp_sw_index"] is not None:
1647                     papi_exec.add(cmd, sw_if_index=ifc[u"vpp_sw_index"])
1648             details = papi_exec.get_details(err_msg)
1649         return sorted(details, key=lambda k: k[u"sw_if_index"])
1650
1651     @staticmethod
1652     def vpp_sw_interface_set_rx_placement(
1653             node, sw_if_index, queue_id, worker_id):
1654         """Set interface RX placement to worker on node.
1655
1656         :param node: Node to run command on.
1657         :param sw_if_index: VPP SW interface index.
1658         :param queue_id: VPP interface queue ID.
1659         :param worker_id: VPP worker ID (indexing from 0).
1660         :type node: dict
1661         :type sw_if_index: int
1662         :type queue_id: int
1663         :type worker_id: int
1664         :raises RuntimeError: If failed to run command on host or if no API
1665             reply received.
1666         """
1667         cmd = u"sw_interface_set_rx_placement"
1668         err_msg = f"Failed to set interface RX placement to worker " \
1669             f"on host {node[u'host']}!"
1670         args = dict(
1671             sw_if_index=sw_if_index,
1672             queue_id=queue_id,
1673             worker_id=worker_id,
1674             is_main=False
1675         )
1676         with PapiSocketExecutor(node) as papi_exec:
1677             papi_exec.add(cmd, **args).get_reply(err_msg)
1678
1679     @staticmethod
1680     def vpp_round_robin_rx_placement(node, prefix):
1681         """Set Round Robin interface RX placement on all worker threads
1682         on node.
1683
1684         :param node: Topology nodes.
1685         :param prefix: Interface name prefix.
1686         :type node: dict
1687         :type prefix: str
1688         """
1689         worker_id = 0
1690         worker_cnt = len(VPPUtil.vpp_show_threads(node)) - 1
1691         if not worker_cnt:
1692             return
1693         for placement in InterfaceUtil.vpp_sw_interface_rx_placement_dump(node):
1694             for interface in node[u"interfaces"].values():
1695                 if placement[u"sw_if_index"] == interface[u"vpp_sw_index"] \
1696                     and prefix in interface[u"name"]:
1697                     InterfaceUtil.vpp_sw_interface_set_rx_placement(
1698                         node, placement[u"sw_if_index"], placement[u"queue_id"],
1699                         worker_id % worker_cnt
1700                     )
1701                     worker_id += 1
1702
1703     @staticmethod
1704     def vpp_round_robin_rx_placement_on_all_duts(nodes, prefix):
1705         """Set Round Robin interface RX placement on all worker threads
1706         on all DUTs.
1707
1708         :param nodes: Topology nodes.
1709         :param prefix: Interface name prefix.
1710         :type nodes: dict
1711         :type prefix: str
1712         """
1713         for node in nodes.values():
1714             if node[u"type"] == NodeType.DUT:
1715                 InterfaceUtil.vpp_round_robin_rx_placement(node, prefix)