1 # Copyright (c) 2018 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:
6 # http://www.apache.org/licenses/LICENSE-2.0
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.
14 """Interface util library"""
16 from time import time, sleep
18 from robot.api import logger
20 from resources.libraries.python.ssh import SSH
21 from resources.libraries.python.IPUtil import convert_ipv4_netmask_prefix
22 from resources.libraries.python.DUTSetup import DUTSetup
23 from resources.libraries.python.ssh import exec_cmd_no_error
24 from resources.libraries.python.topology import NodeType, Topology
25 from resources.libraries.python.VatExecutor import VatExecutor, VatTerminal
26 from resources.libraries.python.VatJsonUtil import VatJsonUtil
27 from resources.libraries.python.parsers.JsonParser import JsonParser
30 class InterfaceUtil(object):
31 """General utilities for managing interfaces"""
33 __UDEV_IF_RULES_FILE = '/etc/udev/rules.d/10-network.rules'
36 def set_interface_state(node, interface, state, if_type="key"):
37 """Set interface state on a node.
39 Function can be used for DUTs as well as for TGs.
41 :param node: Node where the interface is.
42 :param interface: Interface key or sw_if_index or name.
43 :param state: One of 'up' or 'down'.
44 :param if_type: Interface type
46 :type interface: str or int
50 :raises ValueError: If the interface type is unknown.
51 :raises ValueError: If the state of interface is unexpected.
52 :raises ValueError: If the node has an unknown node type.
56 if isinstance(interface, basestring):
57 sw_if_index = Topology.get_interface_sw_index(node, interface)
58 iface_name = Topology.get_interface_name(node, interface)
60 sw_if_index = interface
61 elif if_type == "name":
62 iface_key = Topology.get_interface_by_name(node, interface)
63 if iface_key is not None:
64 sw_if_index = Topology.get_interface_sw_index(node, iface_key)
65 iface_name = interface
67 raise ValueError("if_type unknown: {}".format(if_type))
69 if node['type'] == NodeType.DUT:
71 state = 'admin-up link-up'
73 state = 'admin-down link-down'
75 raise ValueError('Unexpected interface state: {}'.format(state))
76 VatExecutor.cmd_from_template(node, 'set_if_state.vat',
77 sw_if_index=sw_if_index, state=state)
78 elif node['type'] == NodeType.TG or node['type'] == NodeType.VM:
79 cmd = 'ip link set {} {}'.format(iface_name, state)
80 exec_cmd_no_error(node, cmd, sudo=True)
82 raise ValueError('Node {} has unknown NodeType: "{}"'
83 .format(node['host'], node['type']))
86 def set_interface_ethernet_mtu(node, iface_key, mtu):
87 """Set Ethernet MTU for specified interface.
89 Function can be used only for TGs.
91 :param node: Node where the interface is.
92 :param iface_key: Interface key from topology file.
93 :param mtu: MTU to set.
98 :raises ValueError: If the node type is "DUT".
99 :raises ValueError: If the node has an unknown node type.
101 if node['type'] == NodeType.DUT:
102 raise ValueError('Node {}: Setting Ethernet MTU for interface '
103 'on DUT nodes not supported', node['host'])
104 elif node['type'] == NodeType.TG:
105 iface_name = Topology.get_interface_name(node, iface_key)
106 cmd = 'ip link set {} mtu {}'.format(iface_name, mtu)
107 exec_cmd_no_error(node, cmd, sudo=True)
109 raise ValueError('Node {} has unknown NodeType: "{}"'
110 .format(node['host'], node['type']))
113 def set_default_ethernet_mtu_on_all_interfaces_on_node(node):
114 """Set default Ethernet MTU on all interfaces on node.
116 Function can be used only for TGs.
118 :param node: Node where to set default MTU.
122 for ifc in node['interfaces']:
123 InterfaceUtil.set_interface_ethernet_mtu(node, ifc, 1500)
126 def vpp_set_interface_mtu(node, interface, mtu=9200):
127 """Set Ethernet MTU on interface.
129 :param node: VPP node.
130 :param interface: Interface to setup MTU. Default: 9200.
131 :param mtu: Ethernet MTU size in Bytes.
133 :type interface: str or int
136 if isinstance(interface, basestring):
137 sw_if_index = Topology.get_interface_sw_index(node, interface)
139 sw_if_index = interface
142 with VatTerminal(node, json_param=False) as vat:
143 vat.vat_terminal_exec_cmd_from_template(
144 "hw_interface_set_mtu.vat", sw_if_index=sw_if_index,
148 def vpp_set_interfaces_mtu_on_node(node, mtu=9200):
149 """Set Ethernet MTU on all interfaces.
151 :param node: VPP node.
152 :param mtu: Ethernet MTU size in Bytes. Default: 9200.
156 for interface in node['interfaces']:
157 InterfaceUtil.vpp_set_interface_mtu(node, interface, mtu)
160 def vpp_set_interfaces_mtu_on_all_duts(nodes, mtu=9200):
161 """Set Ethernet MTU on all interfaces on all DUTs.
163 :param nodes: VPP nodes.
164 :param mtu: Ethernet MTU size in Bytes. Default: 9200.
168 for node in nodes.values():
169 if node['type'] == NodeType.DUT:
170 InterfaceUtil.vpp_set_interfaces_mtu_on_node(node, mtu)
173 def vpp_node_interfaces_ready_wait(node, timeout=30):
174 """Wait until all interfaces with admin-up are in link-up state.
176 :param node: Node to wait on.
177 :param timeout: Waiting timeout in seconds (optional, default 10s).
181 :raises RuntimeError: If the timeout period value has elapsed.
187 out = InterfaceUtil.vpp_get_interface_data(node)
188 if time() - start > timeout:
189 for interface in out:
190 if interface.get('admin_up_down') == 1:
191 if interface.get('link_up_down') != 1:
192 logger.debug('{0} link-down'.format(
193 interface.get('interface_name')))
194 raise RuntimeError('timeout, not up {0}'.format(not_ready))
196 for interface in out:
197 if interface.get('admin_up_down') == 1:
198 if interface.get('link_up_down') != 1:
199 not_ready.append(interface.get('interface_name'))
203 logger.debug('Interfaces still in link-down state: {0}, '
204 'waiting...'.format(not_ready))
208 def vpp_nodes_interfaces_ready_wait(nodes, timeout=30):
209 """Wait until all interfaces with admin-up are in link-up state for
212 :param nodes: List of nodes to wait on.
213 :param timeout: Seconds to wait per node for all interfaces to come up.
219 InterfaceUtil.vpp_node_interfaces_ready_wait(node, timeout)
222 def all_vpp_interfaces_ready_wait(nodes, timeout=30):
223 """Wait until all interfaces with admin-up are in link-up state for all
224 nodes in the topology.
226 :param nodes: Nodes in the topology.
227 :param timeout: Seconds to wait per node for all interfaces to come up.
232 for node in nodes.values():
233 if node['type'] == NodeType.DUT:
234 InterfaceUtil.vpp_node_interfaces_ready_wait(node, timeout)
237 def vpp_get_interface_data(node, interface=None):
238 """Get all interface data from a VPP node. If a name or
239 sw_interface_index is provided, return only data for the matching
242 :param node: VPP node to get interface data from.
243 :param interface: Numeric index or name string of a specific interface.
245 :type interface: int or str
246 :returns: List of dictionaries containing data for each interface, or a
247 single dictionary for the specified interface.
249 :raises TypeError: if the data type of interface is neither basestring
252 with VatTerminal(node) as vat:
253 response = vat.vat_terminal_exec_cmd_from_template(
254 "interface_dump.vat")
258 if interface is not None:
259 if isinstance(interface, basestring):
260 param = "interface_name"
261 elif isinstance(interface, int):
262 param = "sw_if_index"
266 if data_if[param] == interface:
272 def vpp_get_interface_name(node, sw_if_index):
273 """Get interface name for the given SW interface index from actual
276 :param node: VPP node to get interface data from.
277 :param sw_if_index: SW interface index of the specific interface.
279 :type sw_if_index: int
280 :returns: Name of the given interface.
284 if_data = InterfaceUtil.vpp_get_interface_data(node, sw_if_index)
285 if if_data['sup_sw_if_index'] != if_data['sw_if_index']:
286 if_data = InterfaceUtil.vpp_get_interface_data(
287 node, if_data['sup_sw_if_index'])
289 if_name = if_data["interface_name"]
295 def vpp_get_interface_mac(node, interface=None):
296 """Get MAC address for the given interface from actual interface dump.
298 :param node: VPP node to get interface data from.
299 :param interface: Numeric index or name string of a specific interface.
301 :type interface: int or str
302 :returns: MAC address.
306 if_data = InterfaceUtil.vpp_get_interface_data(node, interface)
307 if if_data['sup_sw_if_index'] != if_data['sw_if_index']:
308 if_data = InterfaceUtil.vpp_get_interface_data(
309 node, if_data['sup_sw_if_index'])
310 mac_data = [str(hex(item))[2:] for item in if_data['l2_address'][:6]]
312 for item in mac_data:
315 mac_data_nice.append(item)
316 mac = ":".join(mac_data_nice)
320 def vpp_get_interface_ip_addresses(node, interface, ip_version):
321 """Get list of IP addresses from an interface on a VPP node.
323 :param node: VPP node to get data from.
324 :param interface: Name of an interface on the VPP node.
325 :param ip_version: IP protocol version (ipv4 or ipv6).
328 :type ip_version: str
329 :returns: List of dictionaries, each containing IP address, subnet
330 prefix length and also the subnet mask for ipv4 addresses.
331 Note: A single interface may have multiple IP addresses assigned.
336 sw_if_index = Topology.convert_interface_reference(
337 node, interface, "sw_if_index")
339 if isinstance(interface, basestring):
340 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface)
344 with VatTerminal(node) as vat:
345 response = vat.vat_terminal_exec_cmd_from_template(
346 "ip_address_dump.vat", ip_version=ip_version,
347 sw_if_index=sw_if_index)
351 if ip_version == "ipv4":
353 item["netmask"] = convert_ipv4_netmask_prefix(
354 item["prefix_length"])
358 def tg_set_interface_driver(node, pci_addr, driver):
359 """Set interface driver on the TG node.
361 :param node: Node to set interface driver on (must be TG node).
362 :param pci_addr: PCI address of the interface.
363 :param driver: Driver name.
367 :raises RuntimeError: If unbinding from the current driver fails.
368 :raises RuntimeError: If binding to the new driver fails.
370 old_driver = InterfaceUtil.tg_get_interface_driver(node, pci_addr)
371 if old_driver == driver:
377 # Unbind from current driver
378 if old_driver is not None:
379 cmd = 'sh -c "echo {0} > /sys/bus/pci/drivers/{1}/unbind"'\
380 .format(pci_addr, old_driver)
381 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
382 if int(ret_code) != 0:
383 raise RuntimeError("'{0}' failed on '{1}'"
384 .format(cmd, node['host']))
386 # Bind to the new driver
387 cmd = 'sh -c "echo {0} > /sys/bus/pci/drivers/{1}/bind"'\
388 .format(pci_addr, driver)
389 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
390 if int(ret_code) != 0:
391 raise RuntimeError("'{0}' failed on '{1}'"
392 .format(cmd, node['host']))
395 def tg_get_interface_driver(node, pci_addr):
396 """Get interface driver from the TG node.
398 :param node: Node to get interface driver on (must be TG node).
399 :param pci_addr: PCI address of the interface.
402 :returns: Interface driver or None if not found.
404 :raises RuntimeError: If PCI rescan or lspci command execution failed.
406 return DUTSetup.get_pci_dev_driver(node, pci_addr)
409 def tg_set_interfaces_udev_rules(node):
410 """Set udev rules for interfaces.
412 Create udev rules file in /etc/udev/rules.d where are rules for each
413 interface used by TG node, based on MAC interface has specific name.
414 So after unbind and bind again to kernel driver interface has same
415 name as before. This must be called after TG has set name for each
416 port in topology dictionary.
418 SUBSYSTEM=="net", ACTION=="add", ATTR{address}=="52:54:00:e1:8a:0f",
421 :param node: Node to set udev rules on (must be TG node).
423 :raises RuntimeError: If setting of udev rules fails.
428 cmd = 'rm -f {0}'.format(InterfaceUtil.__UDEV_IF_RULES_FILE)
429 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
430 if int(ret_code) != 0:
431 raise RuntimeError("'{0}' failed on '{1}'"
432 .format(cmd, node['host']))
434 for interface in node['interfaces'].values():
435 rule = 'SUBSYSTEM==\\"net\\", ACTION==\\"add\\", ATTR{address}' + \
436 '==\\"' + interface['mac_address'] + '\\", NAME=\\"' + \
437 interface['name'] + '\\"'
438 cmd = 'sh -c "echo \'{0}\' >> {1}"'.format(
439 rule, InterfaceUtil.__UDEV_IF_RULES_FILE)
440 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
441 if int(ret_code) != 0:
442 raise RuntimeError("'{0}' failed on '{1}'"
443 .format(cmd, node['host']))
445 cmd = '/etc/init.d/udev restart'
446 ssh.exec_command_sudo(cmd)
449 def tg_set_interfaces_default_driver(node):
450 """Set interfaces default driver specified in topology yaml file.
452 :param node: Node to setup interfaces driver on (must be TG node).
455 for interface in node['interfaces'].values():
456 InterfaceUtil.tg_set_interface_driver(node,
457 interface['pci_address'],
461 def update_vpp_interface_data_on_node(node):
462 """Update vpp generated interface data for a given node in DICT__nodes.
464 Updates interface names, software if index numbers and any other details
465 generated specifically by vpp that are unknown before testcase run.
466 It does this by dumping interface list to JSON output from all
467 devices using vpp_api_test, and pairing known information from topology
468 (mac address/pci address of interface) to state from VPP.
470 :param node: Node selected from DICT__nodes.
473 vat_executor = VatExecutor()
474 vat_executor.execute_script_json_out("dump_interfaces.vat", node)
475 interface_dump_json = vat_executor.get_script_stdout()
476 VatJsonUtil.update_vpp_interface_data_from_json(node,
480 def update_nic_interface_names(node):
481 """Update interface names based on nic type and PCI address.
483 This method updates interface names in the same format as VPP does.
485 :param node: Node dictionary.
488 for ifc in node['interfaces'].values():
489 if_pci = ifc['pci_address'].replace('.', ':').split(':')
490 bus = '{:x}'.format(int(if_pci[1], 16))
491 dev = '{:x}'.format(int(if_pci[2], 16))
492 fun = '{:x}'.format(int(if_pci[3], 16))
493 loc = '{bus}/{dev}/{fun}'.format(bus=bus, dev=dev, fun=fun)
494 if ifc['model'] == 'Intel-XL710':
495 ifc['name'] = 'FortyGigabitEthernet{loc}'.format(loc=loc)
496 elif ifc['model'] == 'Intel-X710':
497 ifc['name'] = 'TenGigabitEthernet{loc}'.format(loc=loc)
498 elif ifc['model'] == 'Intel-X520-DA2':
499 ifc['name'] = 'TenGigabitEthernet{loc}'.format(loc=loc)
500 elif ifc['model'] == 'Cisco-VIC-1385':
501 ifc['name'] = 'FortyGigabitEthernet{loc}'.format(loc=loc)
502 elif ifc['model'] == 'Cisco-VIC-1227':
503 ifc['name'] = 'TenGigabitEthernet{loc}'.format(loc=loc)
505 ifc['name'] = 'UnknownEthernet{loc}'.format(loc=loc)
508 def update_nic_interface_names_on_all_duts(nodes):
509 """Update interface names based on nic type and PCI address on all DUTs.
511 This method updates interface names in the same format as VPP does.
513 :param nodes: Topology nodes.
516 for node in nodes.values():
517 if node['type'] == NodeType.DUT:
518 InterfaceUtil.update_nic_interface_names(node)
521 def update_tg_interface_data_on_node(node):
522 """Update interface name for TG/linux node in DICT__nodes.
525 # for dev in `ls /sys/class/net/`;
526 > do echo "\"`cat /sys/class/net/$dev/address`\": \"$dev\""; done
527 "52:54:00:9f:82:63": "eth0"
528 "52:54:00:77:ae:a9": "eth1"
529 "52:54:00:e1:8a:0f": "eth2"
530 "00:00:00:00:00:00": "lo"
532 .. note:: TODO: parse lshw -json instead
534 :param node: Node selected from DICT__nodes.
536 :raises RuntimeError: If getting of interface name and MAC fails.
538 # First setup interface driver specified in yaml file
539 InterfaceUtil.tg_set_interfaces_default_driver(node)
541 # Get interface names
545 cmd = ('for dev in `ls /sys/class/net/`; do echo "\\"`cat '
546 '/sys/class/net/$dev/address`\\": \\"$dev\\""; done;')
548 (ret_code, stdout, _) = ssh.exec_command(cmd)
549 if int(ret_code) != 0:
550 raise RuntimeError('Get interface name and MAC failed')
551 tmp = "{" + stdout.rstrip().replace('\n', ',') + "}"
552 interfaces = JsonParser().parse_data(tmp)
553 for interface in node['interfaces'].values():
554 name = interfaces.get(interface['mac_address'])
557 interface['name'] = name
559 # Set udev rules for interfaces
560 InterfaceUtil.tg_set_interfaces_udev_rules(node)
563 def iface_update_numa_node(node):
564 """For all interfaces from topology file update numa node based on
565 information from the node.
567 :param node: Node from topology.
570 :raises ValueError: If numa node ia less than 0.
571 :raises RuntimeError: If update of numa node failes.
574 for if_key in Topology.get_node_interfaces(node):
575 if_pci = Topology.get_interface_pci_addr(node, if_key)
577 cmd = "cat /sys/bus/pci/devices/{}/numa_node".format(if_pci)
579 (ret, out, _) = ssh.exec_command(cmd)
586 logger.trace('Reading numa location failed for: {0}'\
589 Topology.set_interface_numa_node(node, if_key,
593 raise RuntimeError('Update numa node failed for: {0}'\
597 def update_all_numa_nodes(nodes, skip_tg=False):
598 """For all nodes and all their interfaces from topology file update numa
599 node information based on information from the node.
601 :param nodes: Nodes in the topology.
602 :param skip_tg: Skip TG node
607 for node in nodes.values():
608 if node['type'] == NodeType.DUT:
609 InterfaceUtil.iface_update_numa_node(node)
610 elif node['type'] == NodeType.TG and not skip_tg:
611 InterfaceUtil.iface_update_numa_node(node)
614 def update_all_interface_data_on_all_nodes(nodes, skip_tg=False,
616 """Update interface names on all nodes in DICT__nodes.
618 This method updates the topology dictionary by querying interface lists
619 of all nodes mentioned in the topology dictionary.
621 :param nodes: Nodes in the topology.
622 :param skip_tg: Skip TG node
623 :param numa_node: Retrieve numa_node location.
626 :type numa_node: bool
628 for node_data in nodes.values():
629 if node_data['type'] == NodeType.DUT:
630 InterfaceUtil.update_vpp_interface_data_on_node(node_data)
631 elif node_data['type'] == NodeType.TG and not skip_tg:
632 InterfaceUtil.update_tg_interface_data_on_node(node_data)
635 if node_data['type'] == NodeType.DUT:
636 InterfaceUtil.iface_update_numa_node(node_data)
637 elif node_data['type'] == NodeType.TG and not skip_tg:
638 InterfaceUtil.iface_update_numa_node(node_data)
641 def create_vlan_subinterface(node, interface, vlan):
642 """Create VLAN subinterface on node.
644 :param node: Node to add VLAN subinterface on.
645 :param interface: Interface name on which create VLAN subinterface.
646 :param vlan: VLAN ID of the subinterface to be created.
650 :returns: Name and index of created subinterface.
652 :raises RuntimeError: if it is unable to create VLAN subinterface on the
655 iface_key = Topology.get_interface_by_name(node, interface)
656 sw_if_index = Topology.get_interface_sw_index(node, iface_key)
658 output = VatExecutor.cmd_from_template(node, "create_vlan_subif.vat",
659 sw_if_index=sw_if_index,
661 if output[0]["retval"] == 0:
662 sw_subif_idx = output[0]["sw_if_index"]
663 logger.trace('VLAN subinterface with sw_if_index {} and VLAN ID {} '
664 'created on node {}'.format(sw_subif_idx,
666 if_key = Topology.add_new_port(node, "vlan_subif")
667 Topology.update_interface_sw_if_index(node, if_key, sw_subif_idx)
668 ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_subif_idx)
669 Topology.update_interface_name(node, if_key, ifc_name)
671 raise RuntimeError('Unable to create VLAN subinterface on node {}'
672 .format(node['host']))
674 with VatTerminal(node, False) as vat:
675 vat.vat_terminal_exec_cmd('exec show interfaces')
677 return '{}.{}'.format(interface, vlan), sw_subif_idx
680 def create_vxlan_interface(node, vni, source_ip, destination_ip):
681 """Create VXLAN interface and return sw if index of created interface.
683 Executes "vxlan_add_del_tunnel src {src} dst {dst} vni {vni}" VAT
686 :param node: Node where to create VXLAN interface.
687 :param vni: VXLAN Network Identifier.
688 :param source_ip: Source IP of a VXLAN Tunnel End Point.
689 :param destination_ip: Destination IP of a VXLAN Tunnel End Point.
693 :type destination_ip: str
694 :returns: SW IF INDEX of created interface.
696 :raises RuntimeError: if it is unable to create VxLAN interface on the
699 output = VatExecutor.cmd_from_template(node, "vxlan_create.vat",
705 if output["retval"] == 0:
706 sw_if_idx = output["sw_if_index"]
707 if_key = Topology.add_new_port(node, "vxlan_tunnel")
708 Topology.update_interface_sw_if_index(node, if_key, sw_if_idx)
709 ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_if_idx)
710 Topology.update_interface_name(node, if_key, ifc_name)
713 raise RuntimeError("Unable to create VXLAN interface on node {0}"
717 def vxlan_dump(node, interface=None):
718 """Get VxLAN data for the given interface.
720 :param node: VPP node to get interface data from.
721 :param interface: Numeric index or name string of a specific interface.
722 If None, information about all VxLAN interfaces is returned.
724 :type interface: int or str
725 :returns: Dictionary containing data for the given VxLAN interface or if
726 interface=None, the list of dictionaries with all VxLAN interfaces.
728 :raises TypeError: if the data type of interface is neither basestring
731 param = "sw_if_index"
732 if interface is None:
735 elif isinstance(interface, basestring):
736 sw_if_index = Topology.get_interface_sw_index(node, interface)
737 elif isinstance(interface, int):
738 sw_if_index = interface
740 raise TypeError("Wrong interface format {0}".format(interface))
742 with VatTerminal(node) as vat:
743 response = vat.vat_terminal_exec_cmd_from_template(
744 "vxlan_dump.vat", param=param, sw_if_index=sw_if_index)
747 for vxlan in response[0]:
748 if vxlan["sw_if_index"] == sw_if_index:
754 def vhost_user_dump(node):
755 """Get vhost-user data for the given node.
757 :param node: VPP node to get interface data from.
759 :returns: List of dictionaries with all vhost-user interfaces.
762 with VatTerminal(node) as vat:
763 response = vat.vat_terminal_exec_cmd_from_template(
764 "vhost_user_dump.vat")
769 def tap_dump(node, name=None):
770 """Get all TAP interface data from the given node, or data about
771 a specific TAP interface.
773 :param node: VPP node to get data from.
774 :param name: Optional name of a specific TAP interface.
777 :returns: Dictionary of information about a specific TAP interface, or
778 a List of dictionaries containing all TAP data for the given node.
781 with VatTerminal(node) as vat:
782 response = vat.vat_terminal_exec_cmd_from_template(
786 for item in response[0]:
787 if name == item['dev_name']:
792 def create_subinterface(node, interface, sub_id, outer_vlan_id=None,
793 inner_vlan_id=None, type_subif=None):
794 """Create sub-interface on node. It is possible to set required
795 sub-interface type and VLAN tag(s).
797 :param node: Node to add sub-interface.
798 :param interface: Interface name on which create sub-interface.
799 :param sub_id: ID of the sub-interface to be created.
800 :param outer_vlan_id: Optional outer VLAN ID.
801 :param inner_vlan_id: Optional inner VLAN ID.
802 :param type_subif: Optional type of sub-interface. Values supported by
803 VPP: [no_tags] [one_tag] [two_tags] [dot1ad] [exact_match]
806 :type interface: str or int
808 :type outer_vlan_id: int
809 :type inner_vlan_id: int
810 :type type_subif: str
811 :returns: Name and index of created sub-interface.
813 :raises RuntimeError: If it is not possible to create sub-interface.
816 outer_vlan_id = 'outer_vlan_id {0}'.format(outer_vlan_id)\
817 if outer_vlan_id else ''
819 inner_vlan_id = 'inner_vlan_id {0}'.format(inner_vlan_id)\
820 if inner_vlan_id else ''
822 if type_subif is None:
825 if isinstance(interface, basestring):
826 iface_key = Topology.get_interface_by_name(node, interface)
827 sw_if_index = Topology.get_interface_sw_index(node, iface_key)
829 sw_if_index = interface
831 output = VatExecutor.cmd_from_template(node, "create_sub_interface.vat",
832 sw_if_index=sw_if_index,
834 outer_vlan_id=outer_vlan_id,
835 inner_vlan_id=inner_vlan_id,
836 type_subif=type_subif)
838 if output[0]["retval"] == 0:
839 sw_subif_idx = output[0]["sw_if_index"]
840 logger.trace('Created subinterface with index {}'
841 .format(sw_subif_idx))
842 if_key = Topology.add_new_port(node, "subinterface")
843 Topology.update_interface_sw_if_index(node, if_key, sw_subif_idx)
844 ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_subif_idx)
845 Topology.update_interface_name(node, if_key, ifc_name)
847 raise RuntimeError('Unable to create sub-interface on node {}'
848 .format(node['host']))
850 with VatTerminal(node, json_param=False) as vat:
851 vat.vat_terminal_exec_cmd('exec show interfaces')
853 name = '{}.{}'.format(interface, sub_id)
854 return name, sw_subif_idx
857 def create_gre_tunnel_interface(node, source_ip, destination_ip):
858 """Create GRE tunnel interface on node.
860 :param node: VPP node to add tunnel interface.
861 :param source_ip: Source of the GRE tunnel.
862 :param destination_ip: Destination of the GRE tunnel.
865 :type destination_ip: str
866 :returns: Name and index of created GRE tunnel interface.
868 :raises RuntimeError: If unable to create GRE tunnel interface.
870 output = VatExecutor.cmd_from_template(node, "create_gre.vat",
875 if output["retval"] == 0:
876 sw_if_idx = output["sw_if_index"]
878 vat_executor = VatExecutor()
879 vat_executor.execute_script_json_out("dump_interfaces.vat", node)
880 interface_dump_json = vat_executor.get_script_stdout()
881 name = VatJsonUtil.get_interface_name_from_json(
882 interface_dump_json, sw_if_idx)
884 if_key = Topology.add_new_port(node, "gre_tunnel")
885 Topology.update_interface_sw_if_index(node, if_key, sw_if_idx)
886 Topology.update_interface_name(node, if_key, name)
888 return name, sw_if_idx
890 raise RuntimeError('Unable to create GRE tunnel on node {}.'
894 def vpp_create_loopback(node):
895 """Create loopback interface on VPP node.
897 :param node: Node to create loopback interface on.
899 :returns: SW interface index.
901 :raises RuntimeError: If it is not possible to create loopback on the
904 out = VatExecutor.cmd_from_template(node, "create_loopback.vat")
905 if out[0].get('retval') == 0:
906 sw_if_idx = out[0].get('sw_if_index')
907 if_key = Topology.add_new_port(node, "loopback")
908 Topology.update_interface_sw_if_index(node, if_key, sw_if_idx)
909 ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_if_idx)
910 Topology.update_interface_name(node, if_key, ifc_name)
913 raise RuntimeError('Create loopback failed on node "{}"'
914 .format(node['host']))
917 def vpp_create_bond_interface(node, mode, load_balance=None, mac=None):
918 """Create bond interface on VPP node.
920 :param node: DUT node from topology.
921 :param mode: Link bonding mode.
922 :param load_balance: Load balance (optional, valid for xor and lacp
923 modes, otherwise ignored).
924 :param mac: MAC address to assign to the bond interface (optional).
927 :type load_balance: str
929 :returns: Interface key (name) in topology.
931 :raises RuntimeError: If it is not possible to create bond interface on
934 hw_addr = '' if mac is None else 'hw-addr {mac}'.format(mac=mac)
935 ldb = '' if load_balance is None \
936 else 'lb {ldb}'.format(ldb=load_balance)
938 output = VatExecutor.cmd_from_template(
939 node, 'create_bond_interface.vat', mode=mode, lb=ldb, mac=hw_addr)
941 if output[0].get('retval') == 0:
942 sw_if_idx = output[0].get('sw_if_index')
943 InterfaceUtil.add_bond_eth_interface(node, sw_if_idx=sw_if_idx)
944 if_key = Topology.get_interface_by_sw_index(node, sw_if_idx)
947 raise RuntimeError('Create bond interface failed on "{host}"'
948 .format(host=node['host']))
951 def add_bond_eth_interface(node, ifc_name=None, sw_if_idx=None):
952 """Add BondEthernet interface to current topology.
954 :param node: DUT node from topology.
955 :param ifc_name: Name of the BondEthernet interface.
956 :param sw_if_idx: SW interface index.
961 if_key = Topology.add_new_port(node, 'eth_bond')
963 vat_executor = VatExecutor()
964 vat_executor.execute_script_json_out("dump_interfaces.vat", node)
965 interface_dump_json = vat_executor.get_script_stdout()
967 if ifc_name and sw_if_idx is None:
968 sw_if_idx = VatJsonUtil.get_interface_sw_index_from_json(
969 interface_dump_json, ifc_name)
970 Topology.update_interface_sw_if_index(node, if_key, sw_if_idx)
971 if sw_if_idx and ifc_name is None:
972 ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_if_idx)
973 Topology.update_interface_name(node, if_key, ifc_name)
974 ifc_mac = VatJsonUtil.get_interface_mac_from_json(
975 interface_dump_json, sw_if_idx)
976 Topology.update_interface_mac_address(node, if_key, ifc_mac)
979 def vpp_enslave_physical_interface(node, interface, bond_interface):
980 """Enslave physical interface to bond interface on VPP node.
982 :param node: DUT node from topology.
983 :param interface: Physical interface key from topology file.
984 :param bond_interface: Load balance
987 :type bond_interface: str
988 :raises RuntimeError: If it is not possible to enslave physical
989 interface to bond interface on the node.
991 ifc = Topology.get_interface_sw_index(node, interface)
992 bond_ifc = Topology.get_interface_sw_index(node, bond_interface)
994 output = VatExecutor.cmd_from_template(
995 node, 'enslave_physical_interface.vat', p_int=ifc, b_int=bond_ifc)
997 retval = output[0].get('retval', None)
998 if retval is None or int(retval) != 0:
999 raise RuntimeError('Enslave physical interface {ifc} to bond '
1000 'interface {bond} failed on node "{n}"'
1001 .format(ifc=interface, bond=bond_interface,
1005 def vpp_show_bond_data_on_node(node, details=False):
1006 """Show (detailed) bond information on VPP node.
1008 :param node: DUT node from topology.
1009 :param details: If detailed information is required or not.
1013 cmd = 'exec show bond details' if details else 'exec show bond'
1014 with VatTerminal(node, json_param=False) as vat:
1015 vat.vat_terminal_exec_cmd(cmd)
1018 def vpp_show_bond_data_on_all_nodes(nodes, details=False):
1019 """Show (detailed) bond information on all VPP nodes in DICT__nodes.
1021 :param nodes: Nodes in the topology.
1022 :param details: If detailed information is required or not.
1026 for node_data in nodes.values():
1027 if node_data['type'] == NodeType.DUT:
1028 InterfaceUtil.vpp_show_bond_data_on_node(node_data, details)
1031 def vpp_enable_input_acl_interface(node, interface, ip_version,
1033 """Enable input acl on interface.
1035 :param node: VPP node to setup interface for input acl.
1036 :param interface: Interface to setup input acl.
1037 :param ip_version: Version of IP protocol.
1038 :param table_index: Classify table index.
1040 :type interface: str or int
1041 :type ip_version: str
1042 :type table_index: int
1044 if isinstance(interface, basestring):
1045 sw_if_index = Topology.get_interface_sw_index(node, interface)
1047 sw_if_index = interface
1049 with VatTerminal(node) as vat:
1050 vat.vat_terminal_exec_cmd_from_template("input_acl_int.vat",
1051 sw_if_index=sw_if_index,
1052 ip_version=ip_version,
1053 table_index=table_index)
1056 def get_interface_classify_table(node, interface):
1057 """Get name of classify table for the given interface.
1059 :param node: VPP node to get data from.
1060 :param interface: Name or sw_if_index of a specific interface.
1062 :type interface: str or int
1063 :returns: Classify table name.
1066 if isinstance(interface, basestring):
1067 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface)
1069 sw_if_index = interface
1071 with VatTerminal(node) as vat:
1072 data = vat.vat_terminal_exec_cmd_from_template(
1073 "classify_interface_table.vat",
1074 sw_if_index=sw_if_index)
1078 def get_interface_vrf_table(node, interface):
1079 """Get vrf ID for the given interface.
1081 :param node: VPP node.
1082 :param interface: Name or sw_if_index of a specific interface.
1084 :type interface: str or int
1085 :returns: vrf ID of the specified interface.
1089 if isinstance(interface, basestring):
1090 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface)
1092 sw_if_index = interface
1094 with VatTerminal(node) as vat:
1095 data = vat.vat_terminal_exec_cmd_from_template(
1096 "interface_vrf_dump.vat",
1097 sw_if_index=sw_if_index)
1098 return data[0]["vrf_id"]
1101 def get_sw_if_index(node, interface_name):
1102 """Get sw_if_index for the given interface from actual interface dump.
1104 :param node: VPP node to get interface data from.
1105 :param interface_name: Name of the specific interface.
1107 :type interface_name: str
1108 :returns: sw_if_index of the given interface.
1112 with VatTerminal(node) as vat:
1113 if_data = vat.vat_terminal_exec_cmd_from_template(
1114 "interface_dump.vat")
1115 for interface in if_data[0]:
1116 if interface["interface_name"] == interface_name:
1117 return interface["sw_if_index"]
1122 def vxlan_gpe_dump(node, interface_name=None):
1123 """Get VxLAN GPE data for the given interface.
1125 :param node: VPP node to get interface data from.
1126 :param interface_name: Name of the specific interface. If None,
1127 information about all VxLAN GPE interfaces is returned.
1129 :type interface_name: str
1130 :returns: Dictionary containing data for the given VxLAN GPE interface
1131 or if interface=None, the list of dictionaries with all VxLAN GPE
1133 :rtype: dict or list
1136 with VatTerminal(node) as vat:
1137 vxlan_gpe_data = vat.vat_terminal_exec_cmd_from_template(
1138 "vxlan_gpe_dump.vat")
1141 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface_name)
1143 for vxlan_gpe in vxlan_gpe_data[0]:
1144 if vxlan_gpe["sw_if_index"] == sw_if_index:
1148 return vxlan_gpe_data[0]
1151 def vpp_proxy_arp_interface_enable(node, interface):
1152 """Enable proxy ARP on interface.
1154 :param node: VPP node to enable proxy ARP on interface.
1155 :param interface: Interface to enable proxy ARP.
1157 :type interface: str or int
1159 if isinstance(interface, basestring):
1160 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface)
1162 sw_if_index = interface
1164 with VatTerminal(node) as vat:
1165 vat.vat_terminal_exec_cmd_from_template(
1166 "proxy_arp_intfc_enable.vat",
1167 sw_if_index=sw_if_index)
1170 def vpp_ip_source_check_setup(node, interface):
1171 """Setup Reverse Path Forwarding source check on interface.
1173 :param node: Node to setup RPF source check.
1174 :param interface: Interface name to setup RPF source check.
1176 :type interface: str
1178 with VatTerminal(node) as vat:
1179 vat.vat_terminal_exec_cmd_from_template("ip_source_check.vat",
1180 interface_name=interface)
1183 def assign_interface_to_fib_table(node, interface, table_id, ipv6=False):
1184 """Assign VPP interface to specific VRF/FIB table.
1186 :param node: VPP node where the FIB and interface are located.
1187 :param interface: Interface to be assigned to FIB.
1188 :param table_id: VRF table ID.
1189 :param ipv6: Assign to IPv6 table. Default False.
1191 :type interface: str or int
1195 if isinstance(interface, basestring):
1196 sw_if_index = Topology.get_interface_sw_index(node, interface)
1198 sw_if_index = interface
1200 ipv6 = 'ipv6' if ipv6 else ''
1202 with VatTerminal(node) as vat:
1203 ret = vat.vat_terminal_exec_cmd_from_template(
1204 "set_fib_to_interface.vat",
1205 sw_index=sw_if_index, vrf=table_id, ipv6=ipv6)
1207 if ret[0]["retval"] != 0:
1208 raise RuntimeError('Unable to assign interface to FIB node {}.'
1212 def set_linux_interface_mac(node, interface, mac, namespace=None):
1213 """Set MAC address for interface in linux.
1215 :param node: Node where to execute command.
1216 :param interface: Interface in namespace.
1217 :param mac: MAC to be assigned to interface.
1218 :param namespace: Execute command in namespace. Optional
1220 :type interface: str
1222 :type namespace: str
1224 if namespace is not None:
1225 cmd = 'ip netns exec {} ip link set {} address {}'.format(
1226 namespace, interface, mac)
1228 cmd = 'ip link set {} address {}'.format(interface, mac)
1229 exec_cmd_no_error(node, cmd, sudo=True)