1 # Copyright (c) 2016 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.ssh import exec_cmd_no_error
23 from resources.libraries.python.topology import NodeType, Topology
24 from resources.libraries.python.VatExecutor import VatExecutor, VatTerminal
25 from resources.libraries.python.VatJsonUtil import VatJsonUtil
26 from resources.libraries.python.parsers.JsonParser import JsonParser
29 class InterfaceUtil(object):
30 """General utilities for managing interfaces"""
32 __UDEV_IF_RULES_FILE = '/etc/udev/rules.d/10-network.rules'
35 def set_interface_state(node, interface, state, if_type="key"):
36 """Set interface state on a node.
38 Function can be used for DUTs as well as for TGs.
40 :param node: Node where the interface is.
41 :param interface: Interface key or sw_if_index or name.
42 :param state: One of 'up' or 'down'.
43 :param if_type: Interface type
45 :type interface: str or int
49 :raises ValueError: If the interface type is unknown.
50 :raises ValueError: If the state of interface is unexpected.
51 :raises ValueError: If the node has an unknown node type.
55 if isinstance(interface, basestring):
56 sw_if_index = Topology.get_interface_sw_index(node, interface)
57 iface_name = Topology.get_interface_name(node, interface)
59 sw_if_index = interface
60 elif if_type == "name":
61 iface_key = Topology.get_interface_by_name(node, interface)
62 if iface_key is not None:
63 sw_if_index = Topology.get_interface_sw_index(node, iface_key)
64 iface_name = interface
66 raise ValueError("if_type unknown: {}".format(if_type))
68 if node['type'] == NodeType.DUT:
74 raise ValueError('Unexpected interface state: {}'.format(state))
75 VatExecutor.cmd_from_template(node, 'set_if_state.vat',
76 sw_if_index=sw_if_index, state=state)
77 elif node['type'] == NodeType.TG or node['type'] == NodeType.VM:
78 cmd = 'ip link set {} {}'.format(iface_name, state)
79 exec_cmd_no_error(node, cmd, sudo=True)
81 raise ValueError('Node {} has unknown NodeType: "{}"'
82 .format(node['host'], node['type']))
85 def set_interface_ethernet_mtu(node, iface_key, mtu):
86 """Set Ethernet MTU for specified interface.
88 Function can be used only for TGs.
90 :param node: Node where the interface is.
91 :param iface_key: Interface key from topology file.
92 :param mtu: MTU to set.
97 :raises ValueError: If the node type is "DUT".
98 :raises ValueError: If the node has an unknown node type.
100 if node['type'] == NodeType.DUT:
101 raise ValueError('Node {}: Setting Ethernet MTU for interface '
102 'on DUT nodes not supported', node['host'])
103 elif node['type'] == NodeType.TG:
104 iface_name = Topology.get_interface_name(node, iface_key)
105 cmd = 'ip link set {} mtu {}'.format(iface_name, mtu)
106 exec_cmd_no_error(node, cmd, sudo=True)
108 raise ValueError('Node {} has unknown NodeType: "{}"'
109 .format(node['host'], node['type']))
112 def set_default_ethernet_mtu_on_all_interfaces_on_node(node):
113 """Set default Ethernet MTU on all interfaces on node.
115 Function can be used only for TGs.
117 :param node: Node where to set default MTU.
121 for ifc in node['interfaces']:
122 InterfaceUtil.set_interface_ethernet_mtu(node, ifc, 1500)
125 def vpp_node_interfaces_ready_wait(node, timeout=10):
126 """Wait until all interfaces with admin-up are in link-up state.
128 :param node: Node to wait on.
129 :param timeout: Waiting timeout in seconds (optional, default 10s).
133 :raises: RuntimeError if the timeout period value has elapsed.
139 out = InterfaceUtil.vpp_get_interface_data(node)
140 if time() - start > timeout:
141 for interface in out:
142 if interface.get('admin_up_down') == 1:
143 if interface.get('link_up_down') != 1:
144 logger.debug('{0} link-down'.format(
145 interface.get('interface_name')))
146 raise RuntimeError('timeout, not up {0}'.format(not_ready))
148 for interface in out:
149 if interface.get('admin_up_down') == 1:
150 if interface.get('link_up_down') != 1:
151 not_ready.append(interface.get('interface_name'))
155 logger.debug('Interfaces still in link-down state: {0}, '
156 'waiting...'.format(not_ready))
160 def vpp_nodes_interfaces_ready_wait(nodes, timeout=10):
161 """Wait until all interfaces with admin-up are in link-up state for
164 :param nodes: List of nodes to wait on.
165 :param timeout: Seconds to wait per node for all interfaces to come up.
171 InterfaceUtil.vpp_node_interfaces_ready_wait(node, timeout)
174 def all_vpp_interfaces_ready_wait(nodes, timeout=10):
175 """Wait until all interfaces with admin-up are in link-up state for all
176 nodes in the topology.
178 :param nodes: Nodes in the topology.
179 :param timeout: Seconds to wait per node for all interfaces to come up.
184 for node in nodes.values():
185 if node['type'] == NodeType.DUT:
186 InterfaceUtil.vpp_node_interfaces_ready_wait(node, timeout)
189 def vpp_get_interface_data(node, interface=None):
190 """Get all interface data from a VPP node. If a name or
191 sw_interface_index is provided, return only data for the matching
194 :param node: VPP node to get interface data from.
195 :param interface: Numeric index or name string of a specific interface.
197 :type interface: int or str
198 :returns: List of dictionaries containing data for each interface, or a
199 single dictionary for the specified interface.
201 :raises TypeError: if the data type of interface is neither basestring
204 with VatTerminal(node) as vat:
205 response = vat.vat_terminal_exec_cmd_from_template(
206 "interface_dump.vat")
210 if interface is not None:
211 if isinstance(interface, basestring):
212 param = "interface_name"
213 elif isinstance(interface, int):
214 param = "sw_if_index"
218 if data_if[param] == interface:
224 def vpp_get_interface_mac(node, interface=None):
225 """Get MAC address for the given interface from actual interface dump.
227 :param node: VPP node to get interface data from.
228 :param interface: Numeric index or name string of a specific interface.
230 :type interface: int or str
231 :returns: MAC address.
235 if_data = InterfaceUtil.vpp_get_interface_data(node, interface)
236 if if_data['sup_sw_if_index'] != if_data['sw_if_index']:
237 if_data = InterfaceUtil.vpp_get_interface_data(
238 node, if_data['sup_sw_if_index'])
239 mac_data = [str(hex(item))[2:] for item in if_data['l2_address'][:6]]
241 for item in mac_data:
244 mac_data_nice.append(item)
245 mac = ":".join(mac_data_nice)
249 def vpp_get_interface_ip_addresses(node, interface, ip_version):
250 """Get list of IP addresses from an interface on a VPP node.
252 :param node: VPP node to get data from.
253 :param interface: Name of an interface on the VPP node.
254 :param ip_version: IP protocol version (ipv4 or ipv6).
257 :type ip_version: str
258 :returns: List of dictionaries, each containing IP address, subnet
259 prefix length and also the subnet mask for ipv4 addresses.
260 Note: A single interface may have multiple IP addresses assigned.
265 sw_if_index = Topology.convert_interface_reference(
266 node, interface, "sw_if_index")
268 if isinstance(interface, basestring):
269 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface)
273 with VatTerminal(node) as vat:
274 response = vat.vat_terminal_exec_cmd_from_template(
275 "ip_address_dump.vat", ip_version=ip_version,
276 sw_if_index=sw_if_index)
280 if ip_version == "ipv4":
282 item["netmask"] = convert_ipv4_netmask_prefix(
283 item["prefix_length"])
287 def tg_set_interface_driver(node, pci_addr, driver):
288 """Set interface driver on the TG node.
290 :param node: Node to set interface driver on (must be TG node).
291 :param pci_addr: PCI address of the interface.
292 :param driver: Driver name.
297 :raises RuntimeError: If unbinding from the current driver fails.
298 :raises RuntimeError: If binding to the new driver fails.
300 old_driver = InterfaceUtil.tg_get_interface_driver(node, pci_addr)
301 if old_driver == driver:
307 # Unbind from current driver
308 if old_driver is not None:
309 cmd = 'sh -c "echo {0} > /sys/bus/pci/drivers/{1}/unbind"'\
310 .format(pci_addr, old_driver)
311 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
312 if int(ret_code) != 0:
313 raise RuntimeError("'{0}' failed on '{1}'"
314 .format(cmd, node['host']))
316 # Bind to the new driver
317 cmd = 'sh -c "echo {0} > /sys/bus/pci/drivers/{1}/bind"'\
318 .format(pci_addr, driver)
319 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
320 if int(ret_code) != 0:
321 raise RuntimeError("'{0}' failed on '{1}'"
322 .format(cmd, node['host']))
325 def tg_get_interface_driver(node, pci_addr):
326 """Get interface driver from the TG node.
328 :param node: Node to get interface driver on (must be TG node).
329 :param pci_addr: PCI address of the interface.
332 :returns: Interface driver or None if not found.
334 :raises RuntimeError: If it is not possible to get the interface driver
335 information from the node.
338 # lspci -vmmks 0000:00:05.0
340 Class: Ethernet controller
342 Device: Virtio network device
343 SVendor: Red Hat, Inc
351 cmd = 'lspci -vmmks {0}'.format(pci_addr)
353 (ret_code, stdout, _) = ssh.exec_command(cmd)
354 if int(ret_code) != 0:
355 raise RuntimeError("'{0}' failed on '{1}'"
356 .format(cmd, node['host']))
358 for line in stdout.splitlines():
361 (name, value) = line.split("\t", 1)
362 if name == 'Driver:':
368 def tg_set_interfaces_udev_rules(node):
369 """Set udev rules for interfaces.
371 Create udev rules file in /etc/udev/rules.d where are rules for each
372 interface used by TG node, based on MAC interface has specific name.
373 So after unbind and bind again to kernel driver interface has same
374 name as before. This must be called after TG has set name for each
375 port in topology dictionary.
377 SUBSYSTEM=="net", ACTION=="add", ATTR{address}=="52:54:00:e1:8a:0f",
380 :param node: Node to set udev rules on (must be TG node).
382 :raises RuntimeError: If setting of udev rules fails.
387 cmd = 'rm -f {0}'.format(InterfaceUtil.__UDEV_IF_RULES_FILE)
388 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
389 if int(ret_code) != 0:
390 raise RuntimeError("'{0}' failed on '{1}'"
391 .format(cmd, node['host']))
393 for interface in node['interfaces'].values():
394 rule = 'SUBSYSTEM==\\"net\\", ACTION==\\"add\\", ATTR{address}' + \
395 '==\\"' + interface['mac_address'] + '\\", NAME=\\"' + \
396 interface['name'] + '\\"'
397 cmd = 'sh -c "echo \'{0}\' >> {1}"'.format(
398 rule, InterfaceUtil.__UDEV_IF_RULES_FILE)
399 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
400 if int(ret_code) != 0:
401 raise RuntimeError("'{0}' failed on '{1}'"
402 .format(cmd, node['host']))
404 cmd = '/etc/init.d/udev restart'
405 ssh.exec_command_sudo(cmd)
408 def tg_set_interfaces_default_driver(node):
409 """Set interfaces default driver specified in topology yaml file.
411 :param node: Node to setup interfaces driver on (must be TG node).
414 for interface in node['interfaces'].values():
415 InterfaceUtil.tg_set_interface_driver(node,
416 interface['pci_address'],
420 def update_vpp_interface_data_on_node(node):
421 """Update vpp generated interface data for a given node in DICT__nodes.
423 Updates interface names, software if index numbers and any other details
424 generated specifically by vpp that are unknown before testcase run.
425 It does this by dumping interface list to JSON output from all
426 devices using vpp_api_test, and pairing known information from topology
427 (mac address/pci address of interface) to state from VPP.
429 :param node: Node selected from DICT__nodes.
432 vat_executor = VatExecutor()
433 vat_executor.execute_script_json_out("dump_interfaces.vat", node)
434 interface_dump_json = vat_executor.get_script_stdout()
435 VatJsonUtil.update_vpp_interface_data_from_json(node,
439 def update_tg_interface_data_on_node(node):
440 """Update interface name for TG/linux node in DICT__nodes.
442 :param node: Node selected from DICT__nodes.
444 :raises RuntimeError: If getting of interface name and MAC fails.
447 # for dev in `ls /sys/class/net/`;
448 > do echo "\"`cat /sys/class/net/$dev/address`\": \"$dev\""; done
449 "52:54:00:9f:82:63": "eth0"
450 "52:54:00:77:ae:a9": "eth1"
451 "52:54:00:e1:8a:0f": "eth2"
452 "00:00:00:00:00:00": "lo"
454 .. todo:: parse lshw -json instead
456 # First setup interface driver specified in yaml file
457 InterfaceUtil.tg_set_interfaces_default_driver(node)
459 # Get interface names
463 cmd = ('for dev in `ls /sys/class/net/`; do echo "\\"`cat '
464 '/sys/class/net/$dev/address`\\": \\"$dev\\""; done;')
466 (ret_code, stdout, _) = ssh.exec_command(cmd)
467 if int(ret_code) != 0:
468 raise RuntimeError('Get interface name and MAC failed')
469 tmp = "{" + stdout.rstrip().replace('\n', ',') + "}"
470 interfaces = JsonParser().parse_data(tmp)
471 for interface in node['interfaces'].values():
472 name = interfaces.get(interface['mac_address'])
475 interface['name'] = name
477 # Set udev rules for interfaces
478 InterfaceUtil.tg_set_interfaces_udev_rules(node)
481 def iface_update_numa_node(node):
482 """For all interfaces from topology file update numa node based on
483 information from the node.
485 :param node: Node from topology.
488 :raises ValueError: If numa node ia less than 0.
489 :raises RuntimeError: If update of numa node failes.
492 for if_key in Topology.get_node_interfaces(node):
493 if_pci = Topology.get_interface_pci_addr(node, if_key)
495 cmd = "cat /sys/bus/pci/devices/{}/numa_node".format(if_pci)
497 (ret, out, _) = ssh.exec_command(cmd)
504 logger.trace('Reading numa location failed for: {0}'\
507 Topology.set_interface_numa_node(node, if_key,
511 raise RuntimeError('Update numa node failed for: {0}'\
515 def update_all_numa_nodes(nodes, skip_tg=False):
516 """For all nodes and all their interfaces from topology file update numa
517 node information based on information from the node.
519 :param nodes: Nodes in the topology.
520 :param skip_tg: Skip TG node
525 for node in nodes.values():
526 if node['type'] == NodeType.DUT:
527 InterfaceUtil.iface_update_numa_node(node)
528 elif node['type'] == NodeType.TG and not skip_tg:
529 InterfaceUtil.iface_update_numa_node(node)
532 def update_all_interface_data_on_all_nodes(nodes, skip_tg=False,
534 """Update interface names on all nodes in DICT__nodes.
536 This method updates the topology dictionary by querying interface lists
537 of all nodes mentioned in the topology dictionary.
539 :param nodes: Nodes in the topology.
540 :param skip_tg: Skip TG node
541 :param numa_node: Retrieve numa_node location.
544 :type numa_node: bool
546 for node_data in nodes.values():
547 if node_data['type'] == NodeType.DUT:
548 InterfaceUtil.update_vpp_interface_data_on_node(node_data)
549 elif node_data['type'] == NodeType.TG and not skip_tg:
550 InterfaceUtil.update_tg_interface_data_on_node(node_data)
553 if node_data['type'] == NodeType.DUT:
554 InterfaceUtil.iface_update_numa_node(node_data)
555 elif node_data['type'] == NodeType.TG and not skip_tg:
556 InterfaceUtil.iface_update_numa_node(node_data)
559 def create_vlan_subinterface(node, interface, vlan):
560 """Create VLAN subinterface on node.
562 :param node: Node to add VLAN subinterface on.
563 :param interface: Interface name on which create VLAN subinterface.
564 :param vlan: VLAN ID of the subinterface to be created.
568 :returns: Name and index of created subinterface.
570 :raises RuntimeError: if it is unable to create VLAN subinterface on the
573 iface_key = Topology.get_interface_by_name(node, interface)
574 sw_if_index = Topology.get_interface_sw_index(node, iface_key)
576 output = VatExecutor.cmd_from_template(node, "create_vlan_subif.vat",
577 sw_if_index=sw_if_index,
579 if output[0]["retval"] == 0:
580 sw_subif_index = output[0]["sw_if_index"]
581 logger.trace('VLAN subinterface with sw_if_index {} and VLAN ID {} '
582 'created on node {}'.format(sw_subif_index,
585 raise RuntimeError('Unable to create VLAN subinterface on node {}'
586 .format(node['host']))
588 with VatTerminal(node, False) as vat:
589 vat.vat_terminal_exec_cmd('exec show interfaces')
591 return '{}.{}'.format(interface, vlan), sw_subif_index
594 def create_vxlan_interface(node, vni, source_ip, destination_ip):
595 """Create VXLAN interface and return sw if index of created interface.
597 Executes "vxlan_add_del_tunnel src {src} dst {dst} vni {vni}" VAT
600 :param node: Node where to create VXLAN interface.
601 :param vni: VXLAN Network Identifier.
602 :param source_ip: Source IP of a VXLAN Tunnel End Point.
603 :param destination_ip: Destination IP of a VXLAN Tunnel End Point.
607 :type destination_ip: str
608 :returns: SW IF INDEX of created interface.
610 :raises RuntimeError: if it is unable to create VxLAN interface on the
613 output = VatExecutor.cmd_from_template(node, "vxlan_create.vat",
619 if output["retval"] == 0:
620 return output["sw_if_index"]
622 raise RuntimeError('Unable to create VXLAN interface on node {0}'
626 def vxlan_dump(node, interface=None):
627 """Get VxLAN data for the given interface.
629 :param node: VPP node to get interface data from.
630 :param interface: Numeric index or name string of a specific interface.
631 If None, information about all VxLAN interfaces is returned.
633 :type interface: int or str
634 :returns: Dictionary containing data for the given VxLAN interface or if
635 interface=None, the list of dictionaries with all VxLAN interfaces.
637 :raises TypeError: if the data type of interface is neither basestring
640 param = "sw_if_index"
641 if interface is None:
644 elif isinstance(interface, basestring):
645 sw_if_index = Topology.get_interface_sw_index(node, interface)
646 elif isinstance(interface, int):
647 sw_if_index = interface
649 raise TypeError("Wrong interface format {0}".format(interface))
651 with VatTerminal(node) as vat:
652 response = vat.vat_terminal_exec_cmd_from_template(
653 "vxlan_dump.vat", param=param, sw_if_index=sw_if_index)
656 for vxlan in response[0]:
657 if vxlan["sw_if_index"] == sw_if_index:
663 def vhost_user_dump(node):
664 """Get vhost-user data for the given node.
666 :param node: VPP node to get interface data from.
668 :returns: List of dictionaries with all vhost-user interfaces.
671 with VatTerminal(node) as vat:
672 response = vat.vat_terminal_exec_cmd_from_template(
673 "vhost_user_dump.vat")
678 def tap_dump(node, name=None):
679 """Get all TAP interface data from the given node, or data about
680 a specific TAP interface.
682 :param node: VPP node to get data from.
683 :param name: Optional name of a specific TAP interface.
686 :returns: Dictionary of information about a specific TAP interface, or
687 a List of dictionaries containing all TAP data for the given node.
690 with VatTerminal(node) as vat:
691 response = vat.vat_terminal_exec_cmd_from_template(
696 for item in response[0]:
697 if name == item['dev_name']:
702 def create_subinterface(node, interface, sub_id, outer_vlan_id=None,
703 inner_vlan_id=None, type_subif=None):
704 """Create sub-interface on node. It is possible to set required
705 sub-interface type and VLAN tag(s).
707 :param node: Node to add sub-interface.
708 :param interface: Interface name on which create sub-interface.
709 :param sub_id: ID of the sub-interface to be created.
710 :param outer_vlan_id: Optional outer VLAN ID.
711 :param inner_vlan_id: Optional inner VLAN ID.
712 :param type_subif: Optional type of sub-interface. Values supported by
713 VPP: [no_tags] [one_tag] [two_tags] [dot1ad] [exact_match] [default_sub]
715 :type interface: str or int
717 :type outer_vlan_id: int
718 :type inner_vlan_id: int
719 :type type_subif: str
720 :returns: Name and index of created sub-interface.
722 :raises RuntimeError: If it is not possible to create sub-interface.
725 outer_vlan_id = 'outer_vlan_id {0}'.format(outer_vlan_id)\
726 if outer_vlan_id else ''
728 inner_vlan_id = 'inner_vlan_id {0}'.format(inner_vlan_id)\
729 if inner_vlan_id else ''
731 if type_subif is None:
734 if isinstance(interface, basestring):
735 iface_key = Topology.get_interface_by_name(node, interface)
736 sw_if_index = Topology.get_interface_sw_index(node, iface_key)
738 sw_if_index = interface
740 output = VatExecutor.cmd_from_template(node, "create_sub_interface.vat",
741 sw_if_index=sw_if_index,
743 outer_vlan_id=outer_vlan_id,
744 inner_vlan_id=inner_vlan_id,
745 type_subif=type_subif)
747 if output[0]["retval"] == 0:
748 sw_subif_index = output[0]["sw_if_index"]
749 logger.trace('Created subinterface with index {}'
750 .format(sw_subif_index))
752 raise RuntimeError('Unable to create sub-interface on node {}'
753 .format(node['host']))
755 with VatTerminal(node, json_param=False) as vat:
756 vat.vat_terminal_exec_cmd('exec show interfaces')
758 name = '{}.{}'.format(interface, sub_id)
759 return name, sw_subif_index
762 def create_gre_tunnel_interface(node, source_ip, destination_ip):
763 """Create GRE tunnel interface on node.
765 :param node: VPP node to add tunnel interface.
766 :param source_ip: Source of the GRE tunnel.
767 :param destination_ip: Destination of the GRE tunnel.
770 :type destination_ip: str
771 :returns: Name and index of created GRE tunnel interface.
773 :raises RuntimeError: If unable to create GRE tunnel interface.
775 output = VatExecutor.cmd_from_template(node, "create_gre.vat",
780 if output["retval"] == 0:
781 sw_if_index = output["sw_if_index"]
783 vat_executor = VatExecutor()
784 vat_executor.execute_script_json_out("dump_interfaces.vat", node)
785 interface_dump_json = vat_executor.get_script_stdout()
786 name = VatJsonUtil.get_interface_name_from_json(
787 interface_dump_json, sw_if_index)
788 return name, sw_if_index
790 raise RuntimeError('Unable to create GRE tunnel on node {}.'
794 def vpp_create_loopback(node):
795 """Create loopback interface on VPP node.
797 :param node: Node to create loopback interface on.
799 :returns: SW interface index.
801 :raises RuntimeError: If it is not possible to create loopback on the
804 out = VatExecutor.cmd_from_template(node, "create_loopback.vat")
805 if out[0].get('retval') == 0:
806 return out[0].get('sw_if_index')
808 raise RuntimeError('Create loopback failed on node "{}"'
809 .format(node['host']))
812 def vpp_enable_input_acl_interface(node, interface, ip_version,
814 """Enable input acl on interface.
816 :param node: VPP node to setup interface for input acl.
817 :param interface: Interface to setup input acl.
818 :param ip_version: Version of IP protocol.
819 :param table_index: Classify table index.
821 :type interface: str or int
822 :type ip_version: str
823 :type table_index: int
825 if isinstance(interface, basestring):
826 sw_if_index = Topology.get_interface_sw_index(node, interface)
828 sw_if_index = interface
830 with VatTerminal(node) as vat:
831 vat.vat_terminal_exec_cmd_from_template("input_acl_int.vat",
832 sw_if_index=sw_if_index,
833 ip_version=ip_version,
834 table_index=table_index)
837 def get_interface_classify_table(node, interface):
838 """Get name of classify table for the given interface.
840 :param node: VPP node to get data from.
841 :param interface: Name or sw_if_index of a specific interface.
843 :type interface: str or int
844 :returns: Classify table name.
847 if isinstance(interface, basestring):
848 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface)
850 sw_if_index = interface
852 with VatTerminal(node) as vat:
853 data = vat.vat_terminal_exec_cmd_from_template(
854 "classify_interface_table.vat",
855 sw_if_index=sw_if_index)
859 def get_interface_vrf_table(node, interface):
860 """Get vrf ID for the given interface.
862 :param node: VPP node.
863 :param interface: Name or sw_if_index of a specific interface.
865 :type interface: str or int
866 :returns: vrf ID of the specified interface.
870 if isinstance(interface, basestring):
871 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface)
873 sw_if_index = interface
875 with VatTerminal(node) as vat:
876 data = vat.vat_terminal_exec_cmd_from_template(
877 "interface_vrf_dump.vat",
878 sw_if_index=sw_if_index)
879 return data[0]["vrf_id"]
882 def get_sw_if_index(node, interface_name):
883 """Get sw_if_index for the given interface from actual interface dump.
885 :param node: VPP node to get interface data from.
886 :param interface_name: Name of the specific interface.
888 :type interface_name: str
889 :returns: sw_if_index of the given interface.
893 with VatTerminal(node) as vat:
894 if_data = vat.vat_terminal_exec_cmd_from_template(
895 "interface_dump.vat")
896 for interface in if_data[0]:
897 if interface["interface_name"] == interface_name:
898 return interface["sw_if_index"]
903 def vxlan_gpe_dump(node, interface_name=None):
904 """Get VxLAN GPE data for the given interface.
906 :param node: VPP node to get interface data from.
907 :param interface_name: Name of the specific interface. If None,
908 information about all VxLAN GPE interfaces is returned.
910 :type interface_name: str
911 :returns: Dictionary containing data for the given VxLAN GPE interface
912 or if interface=None, the list of dictionaries with all VxLAN GPE
917 with VatTerminal(node) as vat:
918 vxlan_gpe_data = vat.vat_terminal_exec_cmd_from_template(
919 "vxlan_gpe_dump.vat")
922 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface_name)
924 for vxlan_gpe in vxlan_gpe_data[0]:
925 if vxlan_gpe["sw_if_index"] == sw_if_index:
929 return vxlan_gpe_data[0]
932 def vpp_proxy_arp_interface_enable(node, interface):
933 """Enable proxy ARP on interface.
935 :param node: VPP node to enable proxy ARP on interface.
936 :param interface: Interface to enable proxy ARP.
938 :type interface: str or int
940 if isinstance(interface, basestring):
941 sw_if_index = InterfaceUtil.get_sw_if_index(node, interface)
943 sw_if_index = interface
945 with VatTerminal(node) as vat:
946 vat.vat_terminal_exec_cmd_from_template(
947 "proxy_arp_intfc_enable.vat",
948 sw_if_index=sw_if_index)
951 def vpp_ip_source_check_setup(node, interface):
952 """Setup Reverse Path Forwarding source check on interface.
954 :param node: Node to setup RPF source check.
955 :param interface: Interface name to setup RPF source check.
959 with VatTerminal(node) as vat:
960 vat.vat_terminal_exec_cmd_from_template("ip_source_check.vat",
961 interface_name=interface)
964 def assign_interface_to_fib_table(node, interface, table_id, ipv6=False):
965 """Assign VPP interface to specific VRF/FIB table.
967 :param node: VPP node where the FIB and interface are located.
968 :param interface: Interface to be assigned to FIB.
969 :param table_id: VRF table ID.
970 :param ipv6: Assign to IPv6 table. Default False.
972 :type interface: str or int
976 if isinstance(interface, basestring):
977 sw_if_index = Topology.get_interface_sw_index(node, interface)
979 sw_if_index = interface
981 ipv6 = 'ipv6' if ipv6 else ''
983 with VatTerminal(node) as vat:
984 ret = vat.vat_terminal_exec_cmd_from_template(
985 "set_fib_to_interface.vat",
986 sw_index=sw_if_index, vrf=table_id, ipv6=ipv6)
988 if ret[0]["retval"] != 0:
989 raise RuntimeError('Unable to assign interface to FIB node {}.'
994 def set_linux_interface_mac(node, interface, mac, namespace=None):
995 """Set MAC address for interface in linux.
997 :param node: Node where to execute command.
998 :param interface: Interface in namespace.
999 :param mac: MAC to be assigned to interface.
1000 :param namespace: Execute command in namespace. Optional
1002 :type interface: str
1004 :type namespace: str
1006 if namespace is not None:
1007 cmd = 'ip netns exec {} ip link set {} address {}'.format(
1008 namespace, interface, mac)
1010 cmd = 'ip link set {} address {}'.format(interface, mac)
1011 exec_cmd_no_error(node, cmd, sudo=True)