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.ssh import exec_cmd_no_error
22 from resources.libraries.python.topology import NodeType, Topology
23 from resources.libraries.python.VatExecutor import VatExecutor, VatTerminal
24 from resources.libraries.python.VatJsonUtil import VatJsonUtil
25 from resources.libraries.python.parsers.JsonParser import JsonParser
28 class InterfaceUtil(object):
29 """General utilities for managing interfaces"""
31 __UDEV_IF_RULES_FILE = '/etc/udev/rules.d/10-network.rules'
34 def set_interface_state(node, interface, state):
35 """Set interface state on a node.
37 Function can be used for DUTs as well as for TGs.
39 :param node: Node where the interface is.
40 :param interface: Interface name or sw_if_index.
41 :param state: One of 'up' or 'down'.
43 :type interface: str or int
47 if node['type'] == NodeType.DUT:
53 raise ValueError('Unexpected interface state: {}'.format(state))
55 if isinstance(interface, basestring):
56 sw_if_index = Topology.get_interface_sw_index(node, interface)
58 sw_if_index = interface
60 VatExecutor.cmd_from_template(node, 'set_if_state.vat',
61 sw_if_index=sw_if_index, state=state)
63 elif node['type'] == NodeType.TG or node['type'] == NodeType.VM:
64 cmd = 'ip link set {} {}'.format(interface, state)
65 exec_cmd_no_error(node, cmd, sudo=True)
67 raise Exception('Node {} has unknown NodeType: "{}"'.
68 format(node['host'], node['type']))
71 def set_interface_ethernet_mtu(node, interface, mtu):
72 """Set Ethernet MTU for specified interface.
74 Function can be used only for TGs.
76 :param node: Node where the interface is.
77 :param interface: Interface name.
78 :param mtu: MTU to set.
84 if node['type'] == NodeType.DUT:
85 ValueError('Node {}: Setting Ethernet MTU for interface '
86 'on DUT nodes not supported', node['host'])
87 elif node['type'] == NodeType.TG:
88 cmd = 'ip link set {} mtu {}'.format(interface, mtu)
89 exec_cmd_no_error(node, cmd, sudo=True)
91 raise ValueError('Node {} has unknown NodeType: "{}"'.
92 format(node['host'], node['type']))
95 def set_default_ethernet_mtu_on_all_interfaces_on_node(node):
96 """Set default Ethernet MTU on all interfaces on node.
98 Function can be used only for TGs.
100 :param node: Node where to set default MTU.
104 for ifc in node['interfaces'].values():
105 InterfaceUtil.set_interface_ethernet_mtu(node, ifc['name'], 1500)
108 def vpp_node_interfaces_ready_wait(node, timeout=10):
109 """Wait until all interfaces with admin-up are in link-up state.
111 :param node: Node to wait on.
112 :param timeout: Waiting timeout in seconds (optional, default 10s).
115 :raises: RuntimeError if the timeout period value has elapsed.
121 out = InterfaceUtil.vpp_get_interface_data(node)
122 if time() - start > timeout:
123 for interface in out:
124 if interface.get('admin_up_down') == 1:
125 if interface.get('link_up_down') != 1:
126 logger.debug('{0} link-down'.format(
127 interface.get('interface_name')))
128 raise RuntimeError('timeout, not up {0}'.format(not_ready))
130 for interface in out:
131 if interface.get('admin_up_down') == 1:
132 if interface.get('link_up_down') != 1:
133 not_ready.append(interface.get('interface_name'))
137 logger.debug('Interfaces still in link-down state: {0}, '
138 'waiting...'.format(not_ready))
142 def vpp_nodes_interfaces_ready_wait(nodes, timeout=10):
143 """Wait until all interfaces with admin-up are in link-up state for
146 :param nodes: List of nodes to wait on.
147 :param timeout: Seconds to wait per node for all interfaces to come up.
150 :raises: RuntimeError if the timeout period value has elapsed.
153 InterfaceUtil.vpp_node_interfaces_ready_wait(node, timeout)
156 def all_vpp_interfaces_ready_wait(nodes, timeout=10):
157 """Wait until all interfaces with admin-up are in link-up state for all
158 nodes in the topology.
160 :param nodes: Nodes in the topology.
161 :param timeout: Seconds to wait per node for all interfaces to come up.
164 :raises: RuntimeError if the timeout period value has elapsed.
166 for node in nodes.values():
167 if node['type'] == NodeType.DUT:
168 InterfaceUtil.vpp_node_interfaces_ready_wait(node, timeout)
171 def vpp_get_interface_data(node, interface=None):
172 """Get all interface data from a VPP node. If a name or
173 sw_interface_index is provided, return only data for the matching
176 :param node: VPP node to get interface data from.
177 :param interface: Numeric index or name string of a specific interface.
179 :type interface: int or str
180 :return: List of dictionaries containing data for each interface, or a
181 single dictionary for the specified interface.
184 with VatTerminal(node) as vat:
185 response = vat.vat_terminal_exec_cmd_from_template(
186 "interface_dump.vat")
190 if interface is not None:
191 if isinstance(interface, basestring):
192 sw_if_index = Topology.get_interface_sw_index(node, interface)
194 sw_if_index = interface
197 if data_if["sw_if_index"] == sw_if_index:
204 def tg_set_interface_driver(node, pci_addr, driver):
205 """Set interface driver on the TG node.
207 :param node: Node to set interface driver on (must be TG node).
208 :param pci_addr: PCI address of the interface.
209 :param driver: Driver name.
214 old_driver = InterfaceUtil.tg_get_interface_driver(node, pci_addr)
215 if old_driver == driver:
221 # Unbind from current driver
222 if old_driver is not None:
223 cmd = 'sh -c "echo {0} > /sys/bus/pci/drivers/{1}/unbind"'.format(
224 pci_addr, old_driver)
225 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
226 if int(ret_code) != 0:
227 raise Exception("'{0}' failed on '{1}'".format(cmd,
230 # Bind to the new driver
231 cmd = 'sh -c "echo {0} > /sys/bus/pci/drivers/{1}/bind"'.format(
233 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
234 if int(ret_code) != 0:
235 raise Exception("'{0}' failed on '{1}'".format(cmd, node['host']))
238 def tg_get_interface_driver(node, pci_addr):
239 """Get interface driver from the TG node.
241 :param node: Node to get interface driver on (must be TG node).
242 :param pci_addr: PCI address of the interface.
245 :return: Interface driver or None if not found.
249 # lspci -vmmks 0000:00:05.0
251 Class: Ethernet controller
253 Device: Virtio network device
254 SVendor: Red Hat, Inc
262 cmd = 'lspci -vmmks {0}'.format(pci_addr)
264 (ret_code, stdout, _) = ssh.exec_command(cmd)
265 if int(ret_code) != 0:
266 raise Exception("'{0}' failed on '{1}'".format(cmd, node['host']))
268 for line in stdout.splitlines():
271 (name, value) = line.split("\t", 1)
272 if name == 'Driver:':
278 def tg_set_interfaces_udev_rules(node):
279 """Set udev rules for interfaces.
281 Create udev rules file in /etc/udev/rules.d where are rules for each
282 interface used by TG node, based on MAC interface has specific name.
283 So after unbind and bind again to kernel driver interface has same
284 name as before. This must be called after TG has set name for each
285 port in topology dictionary.
287 SUBSYSTEM=="net", ACTION=="add", ATTR{address}=="52:54:00:e1:8a:0f",
290 :param node: Node to set udev rules on (must be TG node).
296 cmd = 'rm -f {0}'.format(InterfaceUtil.__UDEV_IF_RULES_FILE)
297 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
298 if int(ret_code) != 0:
299 raise Exception("'{0}' failed on '{1}'".format(cmd, node['host']))
301 for interface in node['interfaces'].values():
302 rule = 'SUBSYSTEM==\\"net\\", ACTION==\\"add\\", ATTR{address}' + \
303 '==\\"' + interface['mac_address'] + '\\", NAME=\\"' + \
304 interface['name'] + '\\"'
305 cmd = 'sh -c "echo \'{0}\' >> {1}"'.format(
306 rule, InterfaceUtil.__UDEV_IF_RULES_FILE)
307 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
308 if int(ret_code) != 0:
309 raise Exception("'{0}' failed on '{1}'".format(cmd,
312 cmd = '/etc/init.d/udev restart'
313 ssh.exec_command_sudo(cmd)
316 def tg_set_interfaces_default_driver(node):
317 """Set interfaces default driver specified in topology yaml file.
319 :param node: Node to setup interfaces driver on (must be TG node).
322 for interface in node['interfaces'].values():
323 InterfaceUtil.tg_set_interface_driver(node,
324 interface['pci_address'],
328 def update_vpp_interface_data_on_node(node):
329 """Update vpp generated interface data for a given node in DICT__nodes.
331 Updates interface names, software if index numbers and any other details
332 generated specifically by vpp that are unknown before testcase run.
333 It does this by dumping interface list to JSON output from all
334 devices using vpp_api_test, and pairing known information from topology
335 (mac address/pci address of interface) to state from VPP.
337 :param node: Node selected from DICT__nodes.
340 vat_executor = VatExecutor()
341 vat_executor.execute_script_json_out("dump_interfaces.vat", node)
342 interface_dump_json = vat_executor.get_script_stdout()
343 VatJsonUtil.update_vpp_interface_data_from_json(node,
347 def update_tg_interface_data_on_node(node):
348 """Update interface name for TG/linux node in DICT__nodes.
350 :param node: Node selected from DICT__nodes.
354 # for dev in `ls /sys/class/net/`;
355 > do echo "\"`cat /sys/class/net/$dev/address`\": \"$dev\""; done
356 "52:54:00:9f:82:63": "eth0"
357 "52:54:00:77:ae:a9": "eth1"
358 "52:54:00:e1:8a:0f": "eth2"
359 "00:00:00:00:00:00": "lo"
361 .. todo:: parse lshw -json instead
363 # First setup interface driver specified in yaml file
364 InterfaceUtil.tg_set_interfaces_default_driver(node)
366 # Get interface names
370 cmd = ('for dev in `ls /sys/class/net/`; do echo "\\"`cat '
371 '/sys/class/net/$dev/address`\\": \\"$dev\\""; done;')
373 (ret_code, stdout, _) = ssh.exec_command(cmd)
374 if int(ret_code) != 0:
375 raise Exception('Get interface name and MAC failed')
376 tmp = "{" + stdout.rstrip().replace('\n', ',') + "}"
377 interfaces = JsonParser().parse_data(tmp)
378 for interface in node['interfaces'].values():
379 name = interfaces.get(interface['mac_address'])
382 interface['name'] = name
384 # Set udev rules for interfaces
385 InterfaceUtil.tg_set_interfaces_udev_rules(node)
388 def update_all_interface_data_on_all_nodes(nodes):
389 """Update interface names on all nodes in DICT__nodes.
391 This method updates the topology dictionary by querying interface lists
392 of all nodes mentioned in the topology dictionary.
394 :param nodes: Nodes in the topology.
397 for node_data in nodes.values():
398 if node_data['type'] == NodeType.DUT:
399 InterfaceUtil.update_vpp_interface_data_on_node(node_data)
400 elif node_data['type'] == NodeType.TG:
401 InterfaceUtil.update_tg_interface_data_on_node(node_data)
404 def create_vlan_subinterface(node, interface, vlan):
405 """Create VLAN subinterface on node.
407 :param node: Node to add VLAN subinterface on.
408 :param interface: Interface name on which create VLAN subinterface.
409 :param vlan: VLAN ID of the subinterface to be created.
413 :return: Name and index of created subinterface.
416 sw_if_index = Topology.get_interface_sw_index(node, interface)
418 output = VatExecutor.cmd_from_template(node, "create_vlan_subif.vat",
419 sw_if_index=sw_if_index,
421 if output[0]["retval"] == 0:
422 sw_subif_index = output[0]["sw_if_index"]
423 logger.trace('VLAN subinterface with sw_if_index {} and VLAN ID {} '
424 'created on node {}'.format(sw_subif_index,
427 raise RuntimeError('Unable to create VLAN subinterface on node {}'
428 .format(node['host']))
430 with VatTerminal(node, False) as vat:
431 vat.vat_terminal_exec_cmd('exec show interfaces')
433 return '{}.{}'.format(interface, vlan), sw_subif_index
436 def create_vxlan_interface(node, vni, source_ip, destination_ip):
437 """Create VXLAN interface and return sw if index of created interface.
439 Executes "vxlan_add_del_tunnel src {src} dst {dst} vni {vni}" VAT
442 :param node: Node where to create VXLAN interface.
443 :param vni: VXLAN Network Identifier.
444 :param source_ip: Source IP of a VXLAN Tunnel End Point.
445 :param destination_ip: Destination IP of a VXLAN Tunnel End Point.
449 :type destination_ip: str
450 :return: SW IF INDEX of created interface.
453 output = VatExecutor.cmd_from_template(node, "vxlan_create.vat",
459 if output["retval"] == 0:
460 return output["sw_if_index"]
462 raise RuntimeError('Unable to create VXLAN interface on node {}'
466 def create_subinterface(node, interface, sub_id, outer_vlan_id,
467 inner_vlan_id, type_subif):
468 """Create sub-interface on node.
470 :param node: Node to add sub-interface.
471 :param interface: Interface name on which create sub-interface.
472 :param sub_id: ID of the sub-interface to be created.
473 :param outer_vlan_id: Outer VLAN ID.
474 :param inner_vlan_id: Inner VLAN ID.
475 :param type_subif: Type of sub-interface.
477 :type interface: str or int
479 :type outer_vlan_id: int
480 :type inner_vlan_id: int
481 :type type_subif: str
482 :return: name and index of created sub-interface
486 if isinstance(interface, basestring):
487 sw_if_index = Topology.get_interface_sw_index(node, interface)
489 sw_if_index = interface
491 output = VatExecutor.cmd_from_template(node, "create_sub_interface.vat",
492 sw_if_index=sw_if_index,
494 outer_vlan_id=outer_vlan_id,
495 inner_vlan_id=inner_vlan_id,
496 type_subif=type_subif)
498 if output[0]["retval"] == 0:
499 sw_subif_index = output[0]["sw_if_index"]
500 logger.trace('Created subinterface with index {}'
501 .format(sw_subif_index))
503 raise RuntimeError('Unable to create subinterface on node {}'
504 .format(node['host']))
506 with VatTerminal(node) as vat:
507 vat.vat_terminal_exec_cmd('exec show interfaces')
509 return '{}.{}'.format(interface, sub_id), sw_subif_index
512 def vpp_create_loopback(node):
513 """Create loopback interface on VPP node.
515 :param node: Node to create loopback interface on.
517 :return: SW interface index.
520 out = VatExecutor.cmd_from_template(node, "create_loopback.vat")
521 if out[0].get('retval') == 0:
522 return out[0].get('sw_if_index')
524 raise RuntimeError('Create loopback failed on node "{}"'
525 .format(node['host']))