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(
787 for item in response[0]:
788 if name == item['dev_name']:
793 def create_subinterface(node, interface, sub_id, outer_vlan_id=None,
794 inner_vlan_id=None, type_subif=None):
795 """Create sub-interface on node. It is possible to set required
796 sub-interface type and VLAN tag(s).
798 :param node: Node to add sub-interface.
799 :param interface: Interface name on which create sub-interface.
800 :param sub_id: ID of the sub-interface to be created.
801 :param outer_vlan_id: Optional outer VLAN ID.
802 :param inner_vlan_id: Optional inner VLAN ID.
803 :param type_subif: Optional type of sub-interface. Values supported by
804 VPP: [no_tags] [one_tag] [two_tags] [dot1ad] [exact_match]
807 :type interface: str or int
809 :type outer_vlan_id: int
810 :type inner_vlan_id: int
811 :type type_subif: str
812 :returns: Name and index of created sub-interface.
814 :raises RuntimeError: If it is not possible to create sub-interface.
817 outer_vlan_id = 'outer_vlan_id {0}'.format(outer_vlan_id)\
818 if outer_vlan_id else ''
820 inner_vlan_id = 'inner_vlan_id {0}'.format(inner_vlan_id)\
821 if inner_vlan_id else ''
823 if type_subif is None:
826 if isinstance(interface, basestring):
827 iface_key = Topology.get_interface_by_name(node, interface)
828 sw_if_index = Topology.get_interface_sw_index(node, iface_key)
830 sw_if_index = interface
832 output = VatExecutor.cmd_from_template(node, "create_sub_interface.vat",
833 sw_if_index=sw_if_index,
835 outer_vlan_id=outer_vlan_id,
836 inner_vlan_id=inner_vlan_id,
837 type_subif=type_subif)
839 if output[0]["retval"] == 0:
840 sw_subif_idx = output[0]["sw_if_index"]
841 logger.trace('Created subinterface with index {}'
842 .format(sw_subif_idx))
843 if_key = Topology.add_new_port(node, "subinterface")
844 Topology.update_interface_sw_if_index(node, if_key, sw_subif_idx)
845 ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_subif_idx)
846 Topology.update_interface_name(node, if_key, ifc_name)
848 raise RuntimeError('Unable to create sub-interface on node {}'
849 .format(node['host']))
851 with VatTerminal(node, json_param=False) as vat:
852 vat.vat_terminal_exec_cmd('exec show interfaces')
854 name = '{}.{}'.format(interface, sub_id)
855 return name, sw_subif_idx
858 def create_gre_tunnel_interface(node, source_ip, destination_ip):
859 """Create GRE tunnel interface on node.
861 :param node: VPP node to add tunnel interface.
862 :param source_ip: Source of the GRE tunnel.
863 :param destination_ip: Destination of the GRE tunnel.
866 :type destination_ip: str
867 :returns: Name and index of created GRE tunnel interface.
869 :raises RuntimeError: If unable to create GRE tunnel interface.
871 output = VatExecutor.cmd_from_template(node, "create_gre.vat",
876 if output["retval"] == 0:
877 sw_if_idx = output["sw_if_index"]
879 vat_executor = VatExecutor()
880 vat_executor.execute_script_json_out("dump_interfaces.vat", node)
881 interface_dump_json = vat_executor.get_script_stdout()
882 name = VatJsonUtil.get_interface_name_from_json(
883 interface_dump_json, sw_if_idx)
885 if_key = Topology.add_new_port(node, "gre_tunnel")
886 Topology.update_interface_sw_if_index(node, if_key, sw_if_idx)
887 Topology.update_interface_name(node, if_key, name)
889 return name, sw_if_idx
891 raise RuntimeError('Unable to create GRE tunnel on node {}.'
895 def vpp_create_loopback(node):
896 """Create loopback interface on VPP node.
898 :param node: Node to create loopback interface on.
900 :returns: SW interface index.
902 :raises RuntimeError: If it is not possible to create loopback on the
905 out = VatExecutor.cmd_from_template(node, "create_loopback.vat")
906 if out[0].get('retval') == 0:
907 sw_if_idx = out[0].get('sw_if_index')
908 if_key = Topology.add_new_port(node, "loopback")
909 Topology.update_interface_sw_if_index(node, if_key, sw_if_idx)
910 ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_if_idx)
911 Topology.update_interface_name(node, if_key, ifc_name)
914 raise RuntimeError('Create loopback failed on node "{}"'
915 .format(node['host']))
918 def vpp_create_bond_interface(node, mode, load_balance=None, mac=None):
919 """Create bond interface on VPP node.
921 :param node: DUT node from topology.
922 :param mode: Link bonding mode.
923 :param load_balance: Load balance (optional, valid for xor and lacp
924 modes, otherwise ignored).
925 :param mac: MAC address to assign to the bond interface (optional).
928 :type load_balance: str
930 :returns: Interface key (name) in topology.
932 :raises RuntimeError: If it is not possible to create bond interface on
935 hw_addr = '' if mac is None else 'hw-addr {mac}'.format(mac=mac)
936 lb = '' if load_balance is None \
937 else 'lb {lb}'.format(lb=load_balance)
939 output = VatExecutor.cmd_from_template(
940 node, 'create_bond_interface.vat', mode=mode, lb=lb, mac=hw_addr)
942 if output[0].get('retval') == 0:
943 sw_if_idx = output[0].get('sw_if_index')
944 InterfaceUtil.add_bond_eth_interface(node, sw_if_idx=sw_if_idx)
945 if_key = Topology.get_interface_by_sw_index(node, sw_if_idx)
948 raise RuntimeError('Create bond interface failed on node "{n}"'
949 .format(n=node['host']))
952 def add_bond_eth_interface(node, ifc_name=None, sw_if_idx=None):
953 """Add BondEthernet interface to current topology.
955 :param node: DUT node from topology.
956 :param ifc_name: Name of the BondEthernet interface.
957 :param sw_if_idx: SW interface index.
962 if_key = Topology.add_new_port(node, 'eth_bond')
964 vat_executor = VatExecutor()
965 vat_executor.execute_script_json_out("dump_interfaces.vat", node)
966 interface_dump_json = vat_executor.get_script_stdout()
968 if ifc_name and sw_if_idx is None:
969 sw_if_idx = VatJsonUtil.get_interface_sw_index_from_json(
970 interface_dump_json, ifc_name)
971 Topology.update_interface_sw_if_index(node, if_key, sw_if_idx)
972 if sw_if_idx and ifc_name is None:
973 ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_if_idx)
974 Topology.update_interface_name(node, if_key, ifc_name)
975 ifc_mac = VatJsonUtil.get_interface_mac_from_json(
976 interface_dump_json, sw_if_idx)
977 Topology.update_interface_mac_address(node, if_key, ifc_mac)
980 def vpp_enslave_physical_interface(node, interface, bond_interface):
981 """Enslave physical interface to bond interface on VPP node.
983 :param node: DUT node from topology.
984 :param interface: Physical interface key from topology file.
985 :param bond_interface: Load balance
988 :type bond_interface: str
989 :raises RuntimeError: If it is not possible to enslave physical
990 interface to bond interface on the node.
992 ifc = Topology.get_interface_sw_index(node, interface)
993 bond_ifc = Topology.get_interface_sw_index(node, bond_interface)
995 output = VatExecutor.cmd_from_template(
996 node, 'enslave_physical_interface.vat', p_int=ifc, b_int=bond_ifc)
998 retval = output[0].get('retval', None)
999 if retval is None or int(retval) != 0:
1000 raise RuntimeError('Enslave physical interface {ifc} to bond '
1001 'interface {bond} failed on node "{n}"'
1002 .format(ifc=interface, bond=bond_interface,
1006 def vpp_show_bond_data_on_node(node, details=False):
1007 """Show (detailed) bond information on VPP node.
1009 :param node: DUT node from topology.
1010 :param details: If detailed information is required or not.
1014 cmd = 'exec show bond details' if details else 'exec show bond'
1015 with VatTerminal(node, json_param=False) as vat:
1016 vat.vat_terminal_exec_cmd(cmd)
1019 def vpp_show_bond_data_on_all_nodes(nodes, details=False):
1020 """Show (detailed) bond information on all VPP nodes in DICT__nodes.
1022 :param nodes: Nodes in the topology.
1023 :param details: If detailed information is required or not.
1027 for node_data in nodes.values():
1028 if node_data['type'] == NodeType.DUT:
1029 InterfaceUtil.vpp_show_bond_data_on_node(node_data, details)
1032 def vpp_enable_input_acl_interface(node, interface, ip_version,
1034 """Enable input acl on interface.
1036 :param node: VPP node to setup interface for input acl.
1037 :param interface: Interface to setup input acl.
1038 :param ip_version: Version of IP protocol.
1039 :param table_index: Classify table index.
1041 :type interface: str or int
1042 :type ip_version: str
1043 :type table_index: int
1045 if isinstance(interface, basestring):
1046 sw_if_index = Topology.get_interface_sw_index(node, interface)
1048 sw_if_index = interface
1050 with VatTerminal(node) as vat:
1051 vat.vat_terminal_exec_cmd_from_template("input_acl_int.vat",
1052 sw_if_index=sw_if_index,
1053 ip_version=ip_version,
1054 table_index=table_index)
1057 def get_interface_classify_table(node, interface):
1058 """Get name of classify table for the given interface.
1060 :param node: VPP node to get data from.
1061 :param interface: Name or sw_if_index of a specific interface.
1063 :type interface: str or int
1064 :returns: Classify table name.
1067 if isinstance(interface, basestring):
1068 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface)
1070 sw_if_index = interface
1072 with VatTerminal(node) as vat:
1073 data = vat.vat_terminal_exec_cmd_from_template(
1074 "classify_interface_table.vat",
1075 sw_if_index=sw_if_index)
1079 def get_interface_vrf_table(node, interface):
1080 """Get vrf ID for the given interface.
1082 :param node: VPP node.
1083 :param interface: Name or sw_if_index of a specific interface.
1085 :type interface: str or int
1086 :returns: vrf ID of the specified interface.
1090 if isinstance(interface, basestring):
1091 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface)
1093 sw_if_index = interface
1095 with VatTerminal(node) as vat:
1096 data = vat.vat_terminal_exec_cmd_from_template(
1097 "interface_vrf_dump.vat",
1098 sw_if_index=sw_if_index)
1099 return data[0]["vrf_id"]
1102 def get_sw_if_index(node, interface_name):
1103 """Get sw_if_index for the given interface from actual interface dump.
1105 :param node: VPP node to get interface data from.
1106 :param interface_name: Name of the specific interface.
1108 :type interface_name: str
1109 :returns: sw_if_index of the given interface.
1113 with VatTerminal(node) as vat:
1114 if_data = vat.vat_terminal_exec_cmd_from_template(
1115 "interface_dump.vat")
1116 for interface in if_data[0]:
1117 if interface["interface_name"] == interface_name:
1118 return interface["sw_if_index"]
1123 def vxlan_gpe_dump(node, interface_name=None):
1124 """Get VxLAN GPE data for the given interface.
1126 :param node: VPP node to get interface data from.
1127 :param interface_name: Name of the specific interface. If None,
1128 information about all VxLAN GPE interfaces is returned.
1130 :type interface_name: str
1131 :returns: Dictionary containing data for the given VxLAN GPE interface
1132 or if interface=None, the list of dictionaries with all VxLAN GPE
1134 :rtype: dict or list
1137 with VatTerminal(node) as vat:
1138 vxlan_gpe_data = vat.vat_terminal_exec_cmd_from_template(
1139 "vxlan_gpe_dump.vat")
1142 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface_name)
1144 for vxlan_gpe in vxlan_gpe_data[0]:
1145 if vxlan_gpe["sw_if_index"] == sw_if_index:
1149 return vxlan_gpe_data[0]
1152 def vpp_proxy_arp_interface_enable(node, interface):
1153 """Enable proxy ARP on interface.
1155 :param node: VPP node to enable proxy ARP on interface.
1156 :param interface: Interface to enable proxy ARP.
1158 :type interface: str or int
1160 if isinstance(interface, basestring):
1161 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface)
1163 sw_if_index = interface
1165 with VatTerminal(node) as vat:
1166 vat.vat_terminal_exec_cmd_from_template(
1167 "proxy_arp_intfc_enable.vat",
1168 sw_if_index=sw_if_index)
1171 def vpp_ip_source_check_setup(node, interface):
1172 """Setup Reverse Path Forwarding source check on interface.
1174 :param node: Node to setup RPF source check.
1175 :param interface: Interface name to setup RPF source check.
1177 :type interface: str
1179 with VatTerminal(node) as vat:
1180 vat.vat_terminal_exec_cmd_from_template("ip_source_check.vat",
1181 interface_name=interface)
1184 def assign_interface_to_fib_table(node, interface, table_id, ipv6=False):
1185 """Assign VPP interface to specific VRF/FIB table.
1187 :param node: VPP node where the FIB and interface are located.
1188 :param interface: Interface to be assigned to FIB.
1189 :param table_id: VRF table ID.
1190 :param ipv6: Assign to IPv6 table. Default False.
1192 :type interface: str or int
1196 if isinstance(interface, basestring):
1197 sw_if_index = Topology.get_interface_sw_index(node, interface)
1199 sw_if_index = interface
1201 ipv6 = 'ipv6' if ipv6 else ''
1203 with VatTerminal(node) as vat:
1204 ret = vat.vat_terminal_exec_cmd_from_template(
1205 "set_fib_to_interface.vat",
1206 sw_index=sw_if_index, vrf=table_id, ipv6=ipv6)
1208 if ret[0]["retval"] != 0:
1209 raise RuntimeError('Unable to assign interface to FIB node {}.'
1213 def set_linux_interface_mac(node, interface, mac, namespace=None):
1214 """Set MAC address for interface in linux.
1216 :param node: Node where to execute command.
1217 :param interface: Interface in namespace.
1218 :param mac: MAC to be assigned to interface.
1219 :param namespace: Execute command in namespace. Optional
1221 :type interface: str
1223 :type namespace: str
1225 if namespace is not None:
1226 cmd = 'ip netns exec {} ip link set {} address {}'.format(
1227 namespace, interface, mac)
1229 cmd = 'ip link set {} address {}'.format(interface, mac)
1230 exec_cmd_no_error(node, cmd, sudo=True)