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 """Defines nodes and topology structure."""
16 from collections import Counter
20 from robot.api import logger
21 from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
22 from robot.api.deco import keyword
24 __all__ = ["DICT__nodes", 'Topology']
27 def load_topo_from_yaml():
28 """Load topology from file defined in "${TOPOLOGY_PATH}" variable.
30 :returns: Nodes from loaded topology.
33 topo_path = BuiltIn().get_variable_value("${TOPOLOGY_PATH}")
34 except RobotNotRunningError:
37 with open(topo_path) as work_file:
38 return load(work_file.read())['nodes']
41 # pylint: disable=invalid-name
42 class NodeType(object):
43 """Defines node types used in topology dictionaries."""
44 # Device Under Test (this node has VPP running on it)
46 # Traffic Generator (this node has traffic generator on it)
48 # Virtual Machine (this node running on DUT node)
52 class NodeSubTypeTG(object):
53 """Defines node sub-type TG - traffic generator."""
54 # T-Rex traffic generator
61 DICT__nodes = load_topo_from_yaml()
64 class Topology(object):
65 """Topology data manipulation and extraction methods.
67 Defines methods used for manipulation and extraction of data from
70 "Active topology" contains initially data from the topology file and can be
71 extended with additional data from the DUTs like internal interface indexes
72 or names. Additional data which can be filled to the active topology are
73 - additional internal representation (index, name, ...)
74 - operational data (dynamic ports)
76 To access the port data it is recommended to use a port key because the key
77 does not rely on the data retrieved from nodes, this allows to call most of
78 the methods without having filled active topology with internal nodes data.
82 def add_new_port(node, ptype):
83 """Add new port to the node to active topology.
85 :param node: Node to add new port on.
86 :param ptype: Port type, used as key prefix.
89 :return: Port key or None
90 :rtype: string or None
94 for i in range(1, max_ports):
95 if node['interfaces'].get(str(ptype) + str(i)) is None:
96 iface = str(ptype) + str(i)
97 node['interfaces'][iface] = dict()
102 def remove_all_ports(node, ptype):
103 """Remove all ports with ptype as prefix.
105 :param node: Node to remove ports on.
106 :param: ptype: Port type, used as key prefix.
111 for if_key in list(node['interfaces']):
112 if if_key.startswith(str(ptype)):
113 node['interfaces'].pop(if_key)
116 def update_interface_sw_if_index(node, iface_key, sw_if_index):
117 """Update sw_if_index on the interface from the node.
119 :param node: Node to update sw_if_index on.
120 :param iface_key: Topology key of the interface.
121 :param sw_if_index: Internal index to store.
124 :type sw_if_index: int
126 node['interfaces'][iface_key]['vpp_sw_index'] = int(sw_if_index)
129 def update_interface_name(node, iface_key, name):
130 """Update name on the interface from the node.
132 :param node: Node to update name on.
133 :param iface_key: Topology key of the interface.
134 :param name: Interface name to store.
139 node['interfaces'][iface_key]['name'] = str(name)
142 def update_interface_mac_address(node, iface_key, mac_address):
143 """Update mac_address on the interface from the node.
145 :param node: Node to update MAC on.
146 :param iface_key: Topology key of the interface.
147 :param mac_address: MAC address.
150 :type mac_address: str
152 node['interfaces'][iface_key]['mac_address'] = str(mac_address)
155 def update_interface_vhost_socket(node, iface_key, vhost_socket):
156 """Update vhost socket name on the interface from the node.
158 :param node: Node to update socket name on.
159 :param iface_key: Topology key of the interface.
160 :param vhost_socket: Path to named socket on node.
163 :type vhost_socket: str
165 node['interfaces'][iface_key]['vhost_socket'] = str(vhost_socket)
168 def get_node_by_hostname(nodes, hostname):
169 """Get node from nodes of the topology by hostname.
171 :param nodes: Nodes of the test topology.
172 :param hostname: Host name.
175 :return: Node dictionary or None if not found.
177 for node in nodes.values():
178 if node['host'] == hostname:
184 def get_links(nodes):
185 """Get list of links(networks) in the topology.
187 :param nodes: Nodes of the test topology.
189 :return: Links in the topology.
194 for node in nodes.values():
195 for interface in node['interfaces'].values():
196 link = interface.get('link')
198 if link not in links:
204 def _get_interface_by_key_value(node, key, value):
205 """Return node interface key from topology file
206 according to key and value.
208 :param node: The node dictionary.
209 :param key: Key by which to select the interface.
210 :param value: Value that should be found using the key.
214 :return: Interface key from topology file
217 interfaces = node['interfaces']
219 for if_key, if_val in interfaces.iteritems():
220 k_val = if_val.get(key)
221 if k_val is not None:
228 def get_interface_by_name(node, iface_name):
229 """Return interface key based on name from DUT/TG.
231 This method returns interface key based on interface name
232 retrieved from the DUT, or TG.
234 :param node: The node topology dictionary.
235 :param iface_name: Interface name (string form).
237 :type iface_name: string
238 :return: Interface key.
241 return Topology._get_interface_by_key_value(node, "name", iface_name)
244 def get_interface_by_link_name(node, link_name):
245 """Return interface key of link on node.
247 This method returns the interface name associated with a given link
250 :param node: The node topology dictionary.
251 :param link_name: Name of the link that a interface is connected to.
253 :type link_name: string
254 :return: Interface key of the interface connected to the given link.
257 return Topology._get_interface_by_key_value(node, "link", link_name)
259 def get_interfaces_by_link_names(self, node, link_names):
260 """Return dictionary of dictionaries {"interfaceN", interface name}.
262 This method returns the interface names associated with given links
265 :param node: The node topology directory.
266 :param link_names: List of names of the link that a interface is
269 :type link_names: list
270 :return: Dictionary of interface names that are connected to the given
275 interface_key_tpl = "interface{}"
277 for link_name in link_names:
278 interface = self.get_interface_by_link_name(node, link_name)
279 interface_name = self.get_interface_name(node, interface)
280 interface_key = interface_key_tpl.format(str(interface_number))
281 retval[interface_key] = interface_name
282 interface_number += 1
286 def get_interface_by_sw_index(node, sw_index):
287 """Return interface name of link on node.
289 This method returns the interface name associated with a software
290 interface index assigned to the interface by vpp for a given node.
292 :param node: The node topology dictionary.
293 :param sw_index: Sw_index of the link that a interface is connected to.
296 :return: Interface name of the interface connected to the given link.
299 return Topology._get_interface_by_key_value(node, "vpp_sw_index",
303 def get_interface_sw_index(node, iface_key):
304 """Get VPP sw_if_index for the interface using interface key.
306 :param node: Node to get interface sw_if_index on.
307 :param iface_key: Interface key from topology file, or sw_index.
309 :type iface_key: str/int
310 :return: Return sw_if_index or None if not found.
313 if isinstance(iface_key, basestring):
314 return node['interfaces'][iface_key].get('vpp_sw_index')
315 # TODO: use only iface_key, do not use integer
317 return int(iface_key)
318 except (KeyError, ValueError):
322 def get_interface_sw_index_by_name(node, iface_name):
323 """Get VPP sw_if_index for the interface using interface name.
325 :param node: Node to get interface sw_if_index on.
326 :param iface_name: Interface name.
328 :type iface_name: str
329 :return: Return sw_if_index or None if not found.
330 :raises TypeError: If provided interface name is not a string.
333 if isinstance(iface_name, basestring):
334 iface_key = Topology.get_interface_by_name(node, iface_name)
335 return node['interfaces'][iface_key].get('vpp_sw_index')
337 raise TypeError("Interface name must be a string.")
338 except (KeyError, ValueError):
342 def get_interface_mtu(node, iface_key):
343 """Get interface MTU.
345 Returns physical layer MTU (max. size of Ethernet frame).
346 :param node: Node to get interface MTU on.
347 :param iface_key: Interface key from topology file.
350 :return: MTU or None if not found.
354 return node['interfaces'][iface_key].get('mtu')
359 def get_interface_name(node, iface_key):
360 """Get interface name (retrieved from DUT/TG).
362 Returns name in string format, retrieved from the node.
363 :param node: Node to get interface name on.
364 :param iface_key: Interface key from topology file.
367 :return: Interface name or None if not found.
371 return node['interfaces'][iface_key].get('name')
376 def convert_interface_reference_to_key(node, interface):
377 """Takes interface reference in any format
378 (name, link name, interface key or sw_if_index)
379 and converts to interface key using Topology methods.
381 :param node: Node in topology.
382 :param interface: Name, sw_if_index, link name or key of an interface
384 Valid formats are: sw_if_index, key, name.
386 :type interface: str or int
388 :return: Interface key.
391 :raises TypeError: If provided with invalid interface argument.
392 :raises RuntimeError: If the interface does not exist in topology.
395 if isinstance(interface, int):
396 key = Topology.get_interface_by_sw_index(node, interface)
398 raise RuntimeError("Interface with sw_if_index={0} does not "
399 "exist in topology.".format(interface))
400 elif interface in Topology.get_node_interfaces(node):
402 elif interface in Topology.get_links({"dut": node}):
403 key = Topology.get_interface_by_link_name(node, interface)
404 elif isinstance(interface, basestring):
405 key = Topology.get_interface_by_name(node, interface)
407 raise RuntimeError("Interface with key, name or link name "
408 "\"{0}\" does not exist in topology."
411 raise TypeError("Type of interface argument must be integer"
416 def convert_interface_reference(node, interface, wanted_format):
417 """Takes interface reference in any format
418 (name, link name, topology key or sw_if_index) and returns
419 its equivalent in the desired format.
421 :param node: Node in topology.
422 :param interface: Name, sw_if_index, link name or key of an interface
424 :param wanted_format: Format of return value wanted.
425 Valid options are: sw_if_index, key, name.
427 :type interface: str or int
428 :type wanted_format: str
430 :return: Interface name, interface key or sw_if_index.
433 :raises TypeError, ValueError: If provided with invalid arguments.
434 :raises RuntimeError: If the interface does not exist in topology.
437 key = Topology.convert_interface_reference_to_key(node, interface)
440 "key": lambda x, y: y,
441 "name": Topology.get_interface_name,
442 "sw_if_index": Topology.get_interface_sw_index
446 return conversions[wanted_format](node, key)
448 raise ValueError("Unrecognized return value wanted: {0}."
449 "Valid options are key, name, sw_if_index"
450 .format(wanted_format))
453 def get_interface_numa_node(node, iface_key):
454 """Get interface numa node.
456 Returns physical relation to numa node, numa_id.
458 :param node: Node to get numa id on.
459 :param iface_key: Interface key from topology file.
462 :return: numa node id, None if not available.
466 return node['interfaces'][iface_key].get('numa_node')
471 def get_interfaces_numa_node(node, *iface_keys):
472 """Get numa node on which are located most of the interfaces.
474 Return numa node with highest count of interfaces provided as arguments.
475 Return 0 if the interface does not have numa_node information available.
476 If all interfaces have unknown location (-1), then return 0.
477 If most of interfaces have unknown location (-1), but there are
478 some interfaces with known location, then return the second most
479 location of the provided interfaces.
481 :param node: Node from DICT__nodes.
482 :param iface_keys: Interface keys for lookup.
484 :type iface_keys: strings
487 for if_key in iface_keys:
489 numa_list.append(node['interfaces'][if_key].get('numa_node'))
493 numa_cnt_mc = Counter(numa_list).most_common()
495 if len(numa_cnt_mc) > 0 and numa_cnt_mc[0][0] != -1:
496 return numa_cnt_mc[0][0]
497 elif len(numa_cnt_mc) > 1 and numa_cnt_mc[0][0] == -1:
498 return numa_cnt_mc[1][0]
503 def get_interface_mac(node, iface_key):
504 """Get MAC address for the interface.
506 :param node: Node to get interface mac on.
507 :param iface_key: Interface key from topology file.
510 :return: Return MAC or None if not found.
513 return node['interfaces'][iface_key].get('mac_address')
518 def get_adjacent_node_and_interface(nodes_info, node, iface_key):
519 """Get node and interface adjacent to specified interface
522 :param nodes_info: Dictionary containing information on all nodes
524 :param node: Node that contains specified interface.
525 :param iface_key: Interface key from topology file.
526 :type nodes_info: dict
529 :return: Return (node, interface_key) tuple or None if not found.
533 # get link name where the interface belongs to
534 for if_key, if_val in node['interfaces'].iteritems():
537 if if_key == iface_key:
538 link_name = if_val['link']
541 if link_name is None:
545 for node_data in nodes_info.values():
547 if node_data['host'] == node['host']:
550 in node_data['interfaces'].iteritems():
551 if 'link' not in if_val:
553 if if_val['link'] == link_name:
554 return node_data, if_key
557 def get_interface_pci_addr(node, iface_key):
558 """Get interface PCI address.
560 :param node: Node to get interface PCI address on.
561 :param iface_key: Interface key from topology file.
564 :return: Return PCI address or None if not found.
567 return node['interfaces'][iface_key].get('pci_address')
572 def get_interface_driver(node, iface_key):
573 """Get interface driver.
575 :param node: Node to get interface driver on.
576 :param iface_key: Interface key from topology file.
579 :return: Return interface driver or None if not found.
582 return node['interfaces'][iface_key].get('driver')
587 def get_node_interfaces(node):
588 """Get all node interfaces.
590 :param node: Node to get list of interfaces from.
592 :return: Return list of keys of all interfaces.
595 return node['interfaces'].keys()
598 def get_node_link_mac(node, link_name):
599 """Return interface mac address by link name.
601 :param node: Node to get interface sw_index on.
602 :param link_name: Link name.
605 :return: MAC address string.
608 for port in node['interfaces'].values():
609 if port.get('link') == link_name:
610 return port.get('mac_address')
614 def _get_node_active_link_names(node, filter_list=None):
615 """Return list of link names that are other than mgmt links.
617 :param node: Node topology dictionary.
618 :param filter_list: Link filter criteria.
620 :type filter_list: list of strings
621 :return: List of strings that represent link names occupied by the node.
624 interfaces = node['interfaces']
626 for interface in interfaces.values():
627 if 'link' in interface:
628 if (filter_list is not None) and ('model' in interface):
629 for filt in filter_list:
630 if filt == interface['model']:
631 link_names.append(interface['link'])
632 elif (filter_list is not None) and ('model' not in interface):
633 logger.trace("Cannot apply filter on interface: {}"
634 .format(str(interface)))
636 link_names.append(interface['link'])
637 if len(link_names) == 0:
641 @keyword('Get active links connecting "${node1}" and "${node2}"')
642 def get_active_connecting_links(self, node1, node2,
643 filter_list_node1=None,
644 filter_list_node2=None):
645 """Return list of link names that connect together node1 and node2.
647 :param node1: Node topology dictionary.
648 :param node2: Node topology dictionary.
649 :param filter_list_node1: Link filter criteria for node1.
650 :param filter_list_node2: Link filter criteria for node2.
653 :type filter_list_node1: list of strings
654 :type filter_list_node2: list of strings
655 :return: List of strings that represent connecting link names.
659 logger.trace("node1: {}".format(str(node1)))
660 logger.trace("node2: {}".format(str(node2)))
661 node1_links = self._get_node_active_link_names(
663 filter_list=filter_list_node1)
664 node2_links = self._get_node_active_link_names(
666 filter_list=filter_list_node2)
668 connecting_links = None
669 if node1_links is None:
670 logger.error("Unable to find active links for node1")
671 elif node2_links is None:
672 logger.error("Unable to find active links for node2")
674 connecting_links = list(set(node1_links).intersection(node2_links))
676 return connecting_links
678 @keyword('Get first active connecting link between node "${node1}" and '
680 def get_first_active_connecting_link(self, node1, node2):
683 :param node1: Connected node.
684 :param node2: Connected node.
687 :return: Name of link connecting the two nodes together.
689 :raises: RuntimeError
691 connecting_links = self.get_active_connecting_links(node1, node2)
692 if len(connecting_links) == 0:
693 raise RuntimeError("No links connecting the nodes were found")
695 return connecting_links[0]
697 @keyword('Get egress interfaces name on "${node1}" for link with '
699 def get_egress_interfaces_name_for_nodes(self, node1, node2):
700 """Get egress interfaces on node1 for link with node2.
702 :param node1: First node, node to get egress interface on.
703 :param node2: Second node.
706 :return: Egress interfaces.
710 links = self.get_active_connecting_links(node1, node2)
712 raise RuntimeError('No link between nodes')
713 for interface in node1['interfaces'].values():
714 link = interface.get('link')
719 name = interface.get('name')
722 interfaces.append(name)
725 @keyword('Get first egress interface name on "${node1}" for link with '
727 def get_first_egress_interface_for_nodes(self, node1, node2):
728 """Get first egress interface on node1 for link with node2.
730 :param node1: First node, node to get egress interface name on.
731 :param node2: Second node.
734 :return: Egress interface name.
737 interfaces = self.get_egress_interfaces_name_for_nodes(node1, node2)
739 raise RuntimeError('No egress interface for nodes')
742 @keyword('Get link data useful in circular topology test from tg "${tgen}"'
743 ' dut1 "${dut1}" dut2 "${dut2}"')
744 def get_links_dict_from_nodes(self, tgen, dut1, dut2):
745 """Return link combinations used in tests in circular topology.
747 For the time being it returns links from the Node path:
749 The naming convention until changed to something more general is
751 DUT1_DUT2_LINK: link name between DUT! and DUT2
752 DUT1_TG_LINK: link name between DUT1 and TG
753 DUT2_TG_LINK: link name between DUT2 and TG
754 TG_TRAFFIC_LINKS: list of link names that generated traffic is sent
756 DUT1_BD_LINKS: list of link names that will be connected by the bridge
758 DUT2_BD_LINKS: list of link names that will be connected by the bridge
761 :param tgen: Traffic generator node data.
762 :param dut1: DUT1 node data.
763 :param dut2: DUT2 node data.
767 :return: Dictionary of possible link combinations.
770 # TODO: replace with generic function.
771 dut1_dut2_link = self.get_first_active_connecting_link(dut1, dut2)
772 dut1_tg_link = self.get_first_active_connecting_link(dut1, tgen)
773 dut2_tg_link = self.get_first_active_connecting_link(dut2, tgen)
774 tg_traffic_links = [dut1_tg_link, dut2_tg_link]
775 dut1_bd_links = [dut1_dut2_link, dut1_tg_link]
776 dut2_bd_links = [dut1_dut2_link, dut2_tg_link]
777 topology_links = {'DUT1_DUT2_LINK': dut1_dut2_link,
778 'DUT1_TG_LINK': dut1_tg_link,
779 'DUT2_TG_LINK': dut2_tg_link,
780 'TG_TRAFFIC_LINKS': tg_traffic_links,
781 'DUT1_BD_LINKS': dut1_bd_links,
782 'DUT2_BD_LINKS': dut2_bd_links}
783 return topology_links
786 def is_tg_node(node):
787 """Find out whether the node is TG.
789 :param node: Node to examine.
791 :return: True if node is type of TG, otherwise False.
794 return node['type'] == NodeType.TG
797 def get_node_hostname(node):
798 """Return host (hostname/ip address) of the node.
800 :param node: Node created from topology.
802 :return: Hostname or IP address.
808 def set_interface_numa_node(node, iface_key, numa_node_id):
809 """Set interface numa_node location.
811 :param node: Node to set numa_node on.
812 :param iface_key: Interface key from topology file.
815 :return: Return iface_key or None if not found.
818 node['interfaces'][iface_key]['numa_node'] = numa_node_id