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
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 :return: Nodes from loaded topology.
32 topo_path = BuiltIn().get_variable_value("${TOPOLOGY_PATH}")
34 with open(topo_path) as work_file:
35 return load(work_file.read())['nodes']
38 # pylint: disable=invalid-name
39 class NodeType(object):
40 """Defines node types used in topology dictionaries."""
41 # Device Under Test (this node has VPP running on it)
43 # Traffic Generator (this node has traffic generator on it)
45 # Virtual Machine (this node running on DUT node)
49 class NodeSubTypeTG(object):
50 """Defines node sub-type TG - traffic generator."""
51 # T-Rex traffic generator
58 DICT__nodes = load_topo_from_yaml()
61 class Topology(object):
62 """Topology data manipulation and extraction methods.
64 Defines methods used for manipulation and extraction of data from
67 "Active topology" contains initially data from the topology file and can be
68 extended with additional data from the DUTs like internal interface indexes
69 or names. Additional data which can be filled to the active topology are
70 - additional internal representation (index, name, ...)
71 - operational data (dynamic ports)
73 To access the port data it is recommended to use a port key because the key
74 does not rely on the data retrieved from nodes, this allows to call most of
75 the methods without having filled active topology with internal nodes data.
79 def add_new_port(node, ptype):
80 """Add new port to the node to active topology.
82 :param node: Node to add new port on.
83 :param ptype: Port type, used as key prefix.
86 :return: Port key or None
87 :rtype: string or None
91 for i in range(1, max_ports):
92 if node['interfaces'].get(str(ptype) + str(i)) is None:
93 iface = str(ptype) + str(i)
94 node['interfaces'][iface] = dict()
99 def remove_all_ports(node, ptype):
100 """Remove all ports with ptype as prefix.
102 :param node: Node to remove ports on.
103 :param: ptype: Port type, used as key prefix.
108 for if_key in list(node['interfaces']):
109 if if_key.startswith(str(ptype)):
110 node['interfaces'].pop(if_key)
113 def update_interface_sw_if_index(node, iface_key, sw_if_index):
114 """Update sw_if_index on the interface from the node.
116 :param node: Node to update sw_if_index on.
117 :param iface_key: Topology key of the interface.
118 :param sw_if_index: Internal index to store.
121 :type sw_if_index: int
123 node['interfaces'][iface_key]['vpp_sw_index'] = int(sw_if_index)
126 def update_interface_mac_address(node, iface_key, mac_address):
127 """Update mac_address on the interface from the node.
129 :param node: Node to update MAC on.
130 :param iface_key: Topology key of the interface.
131 :param mac_address: MAC address.
134 :type mac_address: str
136 node['interfaces'][iface_key]['mac_address'] = str(mac_address)
139 def update_interface_vhost_socket(node, iface_key, vhost_socket):
140 """Update vhost socket name on the interface from the node.
142 :param node: Node to update socket name on.
143 :param iface_key: Topology key of the interface.
144 :param vhost_socket: Path to named socket on node.
147 :type vhost_socket: str
149 node['interfaces'][iface_key]['vhost_socket'] = str(vhost_socket)
152 def get_node_by_hostname(nodes, hostname):
153 """Get node from nodes of the topology by hostname.
155 :param nodes: Nodes of the test topology.
156 :param hostname: Host name.
159 :return: Node dictionary or None if not found.
161 for node in nodes.values():
162 if node['host'] == hostname:
168 def get_links(nodes):
169 """Get list of links(networks) in the topology.
171 :param nodes: Nodes of the test topology.
173 :return: Links in the topology.
178 for node in nodes.values():
179 for interface in node['interfaces'].values():
180 link = interface.get('link')
182 if link not in links:
188 def _get_interface_by_key_value(node, key, value):
189 """Return node interface key from topology file
190 according to key and value.
192 :param node: The node dictionary.
193 :param key: Key by which to select the interface.
194 :param value: Value that should be found using the key.
198 :return: Interface key from topology file
201 interfaces = node['interfaces']
203 for if_key, if_val in interfaces.iteritems():
204 k_val = if_val.get(key)
205 if k_val is not None:
212 def get_interface_by_name(node, iface_name):
213 """Return interface key based on name from DUT/TG.
215 This method returns interface key based on interface name
216 retrieved from the DUT, or TG.
218 :param node: The node topology dictionary.
219 :param iface_name: Interface name (string form).
221 :type iface_name: string
222 :return: Interface key.
225 return Topology._get_interface_by_key_value(node, "name", iface_name)
228 def get_interface_by_link_name(node, link_name):
229 """Return interface key of link on node.
231 This method returns the interface name associated with a given link
234 :param node: The node topology dictionary.
235 :param link_name: Name of the link that a interface is connected to.
237 :type link_name: string
238 :return: Interface key of the interface connected to the given link.
241 return Topology._get_interface_by_key_value(node, "link", link_name)
243 def get_interfaces_by_link_names(self, node, link_names):
244 """Return dictionary of dictionaries {"interfaceN", interface name}.
246 This method returns the interface names associated with given links
249 :param node: The node topology directory.
250 :param link_names: List of names of the link that a interface is
253 :type link_names: list
254 :return: Dictionary of interface names that are connected to the given
259 interface_key_tpl = "interface{}"
261 for link_name in link_names:
262 interface = self.get_interface_by_link_name(node, link_name)
263 interface_name = self.get_interface_name(node, interface)
264 interface_key = interface_key_tpl.format(str(interface_number))
265 retval[interface_key] = interface_name
266 interface_number += 1
270 def get_interface_by_sw_index(node, sw_index):
271 """Return interface name of link on node.
273 This method returns the interface name associated with a software
274 interface index assigned to the interface by vpp for a given node.
276 :param node: The node topology dictionary.
277 :param sw_index: Sw_index of the link that a interface is connected to.
280 :return: Interface name of the interface connected to the given link.
283 return Topology._get_interface_by_key_value(node, "vpp_sw_index",
287 def get_interface_sw_index(node, iface_key):
288 """Get VPP sw_if_index for the interface using interface key.
290 :param node: Node to get interface sw_if_index on.
291 :param iface_key: Interface key from topology file, or sw_index.
293 :type iface_key: str/int
294 :return: Return sw_if_index or None if not found.
297 if isinstance(iface_key, basestring):
298 return node['interfaces'][iface_key].get('vpp_sw_index')
299 #FIXME: use only iface_key, do not use integer
301 return int(iface_key)
302 except (KeyError, ValueError):
306 def get_interface_sw_index_by_name(node, iface_name):
307 """Get VPP sw_if_index for the interface using interface name.
309 :param node: Node to get interface sw_if_index on.
310 :param iface_name: Interface name.
312 :type iface_name: str
313 :return: Return sw_if_index or None if not found.
314 :raises TypeError: If provided interface name is not a string.
317 if isinstance(iface_name, basestring):
318 iface_key = Topology.get_interface_by_name(node, iface_name)
319 return node['interfaces'][iface_key].get('vpp_sw_index')
321 raise TypeError("Interface name must be a string.")
322 except (KeyError, ValueError):
326 def get_interface_mtu(node, iface_key):
327 """Get interface MTU.
329 Returns physical layer MTU (max. size of Ethernet frame).
330 :param node: Node to get interface MTU on.
331 :param iface_key: Interface key from topology file.
334 :return: MTU or None if not found.
338 return node['interfaces'][iface_key].get('mtu')
343 def get_interface_name(node, iface_key):
344 """Get interface name (retrieved from DUT/TG).
346 Returns name in string format, retrieved from the node.
347 :param node: Node to get interface name on.
348 :param iface_key: Interface key from topology file.
351 :return: Interface name or None if not found.
355 return node['interfaces'][iface_key].get('name')
360 def convert_interface_reference_to_key(node, interface):
361 """Takes interface reference in any format
362 (name, link name, interface key or sw_if_index)
363 and converts to interface key using Topology methods.
365 :param node: Node in topology.
366 :param interface: Name, sw_if_index, link name or key of an interface
368 Valid formats are: sw_if_index, key, name.
370 :type interface: str or int
372 :return: Interface key.
375 :raises TypeError: If provided with invalid interface argument.
376 :raises RuntimeError: If the interface does not exist in topology.
379 if isinstance(interface, int):
380 key = Topology.get_interface_by_sw_index(node, interface)
382 raise RuntimeError("Interface with sw_if_index={0} does not "
383 "exist in topology.".format(interface))
384 elif interface in Topology.get_node_interfaces(node):
386 elif interface in Topology.get_links({"dut": node}):
387 key = Topology.get_interface_by_link_name(node, interface)
388 elif isinstance(interface, basestring):
389 key = Topology.get_interface_by_name(node, interface)
391 raise RuntimeError("Interface with key, name or link name "
392 "\"{0}\" does not exist in topology."
395 raise TypeError("Type of interface argument must be integer"
400 def convert_interface_reference(node, interface, wanted_format):
401 """Takes interface reference in any format
402 (name, link name, topology key or sw_if_index) and returns
403 its equivalent in the desired format.
405 :param node: Node in topology.
406 :param interface: Name, sw_if_index, link name or key of an interface
408 :param wanted_format: Format of return value wanted.
409 Valid options are: sw_if_index, key, name.
411 :type interface: str or int
412 :type wanted_format: str
414 :return: Interface name, interface key or sw_if_index.
417 :raises TypeError, ValueError: If provided with invalid arguments.
418 :raises RuntimeError: If the interface does not exist in topology.
421 key = Topology.convert_interface_reference_to_key(node, interface)
424 "key": lambda x, y: y,
425 "name": Topology.get_interface_name,
426 "sw_if_index": Topology.get_interface_sw_index
430 return conversions[wanted_format](node, key)
432 raise ValueError("Unrecognized return value wanted: {0}."
433 "Valid options are key, name, sw_if_index"
434 .format(wanted_format))
437 def get_interface_numa_node(node, iface_key):
438 """Get interface numa node.
440 Returns physical relation to numa node, numa_id.
442 :param node: Node to get numa id on.
443 :param iface_key: Interface key from topology file.
446 :return: numa node id, None if not available.
450 return node['interfaces'][iface_key].get('numa_node')
455 def get_interfaces_numa_node(node, *iface_keys):
456 """Get numa node on which are located most of the interfaces.
458 Return numa node with highest count of interfaces provided as arguments.
459 Return 0 if the interface does not have numa_node information available.
460 If all interfaces have unknown location (-1), then return 0.
461 If most of interfaces have unknown location (-1), but there are
462 some interfaces with known location, then return the second most
463 location of the provided interfaces.
465 :param node: Node from DICT__nodes.
466 :param iface_keys: Interface keys for lookup.
468 :type iface_keys: strings
471 for if_key in iface_keys:
473 numa_list.append(node['interfaces'][if_key].get('numa_node'))
477 numa_cnt_mc = Counter(numa_list).most_common()
479 if len(numa_cnt_mc) > 0 and numa_cnt_mc[0][0] != -1:
480 return numa_cnt_mc[0][0]
481 elif len(numa_cnt_mc) > 1 and numa_cnt_mc[0][0] == -1:
482 return numa_cnt_mc[1][0]
487 def get_interface_mac(node, iface_key):
488 """Get MAC address for the interface.
490 :param node: Node to get interface mac on.
491 :param iface_key: Interface key from topology file.
494 :return: Return MAC or None if not found.
497 return node['interfaces'][iface_key].get('mac_address')
502 def get_adjacent_node_and_interface(nodes_info, node, iface_key):
503 """Get node and interface adjacent to specified interface
506 :param nodes_info: Dictionary containing information on all nodes
508 :param node: Node that contains specified interface.
509 :param iface_key: Interface key from topology file.
510 :type nodes_info: dict
513 :return: Return (node, interface_key) tuple or None if not found.
517 # get link name where the interface belongs to
518 for if_key, if_val in node['interfaces'].iteritems():
521 if if_key == iface_key:
522 link_name = if_val['link']
525 if link_name is None:
529 for node_data in nodes_info.values():
531 if node_data['host'] == node['host']:
534 in node_data['interfaces'].iteritems():
535 if 'link' not in if_val:
537 if if_val['link'] == link_name:
538 return node_data, if_key
541 def get_interface_pci_addr(node, iface_key):
542 """Get interface PCI address.
544 :param node: Node to get interface PCI address on.
545 :param iface_key: Interface key from topology file.
548 :return: Return PCI address or None if not found.
551 return node['interfaces'][iface_key].get('pci_address')
556 def get_interface_driver(node, iface_key):
557 """Get interface driver.
559 :param node: Node to get interface driver on.
560 :param iface_key: Interface key from topology file.
563 :return: Return interface driver or None if not found.
566 return node['interfaces'][iface_key].get('driver')
571 def get_node_interfaces(node):
572 """Get all node interfaces.
574 :param node: Node to get list of interfaces from.
576 :return: Return list of keys of all interfaces.
579 return node['interfaces'].keys()
582 def get_node_link_mac(node, link_name):
583 """Return interface mac address by link name.
585 :param node: Node to get interface sw_index on.
586 :param link_name: Link name.
589 :return: MAC address string.
592 for port in node['interfaces'].values():
593 if port.get('link') == link_name:
594 return port.get('mac_address')
598 def _get_node_active_link_names(node, filter_list=None):
599 """Return list of link names that are other than mgmt links.
601 :param node: Node topology dictionary.
602 :param filter_list: Link filter criteria.
604 :type filter_list: list of strings
605 :return: List of strings that represent link names occupied by the node.
608 interfaces = node['interfaces']
610 for interface in interfaces.values():
611 if 'link' in interface:
612 if (filter_list is not None) and ('model' in interface):
613 for filt in filter_list:
614 if filt == interface['model']:
615 link_names.append(interface['link'])
616 elif (filter_list is not None) and ('model' not in interface):
617 logger.trace("Cannot apply filter on interface: {}"
618 .format(str(interface)))
620 link_names.append(interface['link'])
621 if len(link_names) == 0:
625 @keyword('Get active links connecting "${node1}" and "${node2}"')
626 def get_active_connecting_links(self, node1, node2,
627 filter_list_node1=None,
628 filter_list_node2=None):
629 """Return list of link names that connect together node1 and node2.
631 :param node1: Node topology dictionary.
632 :param node2: Node topology dictionary.
633 :param filter_list_node1: Link filter criteria for node1.
634 :param filter_list_node2: Link filter criteria for node2.
637 :type filter_list_node1: list of strings
638 :type filter_list_node2: list of strings
639 :return: List of strings that represent connecting link names.
643 logger.trace("node1: {}".format(str(node1)))
644 logger.trace("node2: {}".format(str(node2)))
645 node1_links = self._get_node_active_link_names(
647 filter_list=filter_list_node1)
648 node2_links = self._get_node_active_link_names(
650 filter_list=filter_list_node2)
652 connecting_links = None
653 if node1_links is None:
654 logger.error("Unable to find active links for node1")
655 elif node2_links is None:
656 logger.error("Unable to find active links for node2")
658 connecting_links = list(set(node1_links).intersection(node2_links))
660 return connecting_links
662 @keyword('Get first active connecting link between node "${node1}" and '
664 def get_first_active_connecting_link(self, node1, node2):
667 :param node1: Connected node.
668 :param node2: Connected node.
671 :return: Name of link connecting the two nodes together.
673 :raises: RuntimeError
675 connecting_links = self.get_active_connecting_links(node1, node2)
676 if len(connecting_links) == 0:
677 raise RuntimeError("No links connecting the nodes were found")
679 return connecting_links[0]
681 @keyword('Get egress interfaces name on "${node1}" for link with '
683 def get_egress_interfaces_name_for_nodes(self, node1, node2):
684 """Get egress interfaces on node1 for link with node2.
686 :param node1: First node, node to get egress interface on.
687 :param node2: Second node.
690 :return: Egress interfaces.
694 links = self.get_active_connecting_links(node1, node2)
696 raise RuntimeError('No link between nodes')
697 for interface in node1['interfaces'].values():
698 link = interface.get('link')
703 name = interface.get('name')
706 interfaces.append(name)
709 @keyword('Get first egress interface name on "${node1}" for link with '
711 def get_first_egress_interface_for_nodes(self, node1, node2):
712 """Get first egress interface on node1 for link with node2.
714 :param node1: First node, node to get egress interface name on.
715 :param node2: Second node.
718 :return: Egress interface name.
721 interfaces = self.get_egress_interfaces_name_for_nodes(node1, node2)
723 raise RuntimeError('No egress interface for nodes')
726 @keyword('Get link data useful in circular topology test from tg "${tgen}"'
727 ' dut1 "${dut1}" dut2 "${dut2}"')
728 def get_links_dict_from_nodes(self, tgen, dut1, dut2):
729 """Return link combinations used in tests in circular topology.
731 For the time being it returns links from the Node path:
733 The naming convention until changed to something more general is
735 DUT1_DUT2_LINK: link name between DUT! and DUT2
736 DUT1_TG_LINK: link name between DUT1 and TG
737 DUT2_TG_LINK: link name between DUT2 and TG
738 TG_TRAFFIC_LINKS: list of link names that generated traffic is sent
740 DUT1_BD_LINKS: list of link names that will be connected by the bridge
742 DUT2_BD_LINKS: list of link names that will be connected by the bridge
745 :param tgen: Traffic generator node data.
746 :param dut1: DUT1 node data.
747 :param dut2: DUT2 node data.
751 :return: Dictionary of possible link combinations.
754 # TODO: replace with generic function.
755 dut1_dut2_link = self.get_first_active_connecting_link(dut1, dut2)
756 dut1_tg_link = self.get_first_active_connecting_link(dut1, tgen)
757 dut2_tg_link = self.get_first_active_connecting_link(dut2, tgen)
758 tg_traffic_links = [dut1_tg_link, dut2_tg_link]
759 dut1_bd_links = [dut1_dut2_link, dut1_tg_link]
760 dut2_bd_links = [dut1_dut2_link, dut2_tg_link]
761 topology_links = {'DUT1_DUT2_LINK': dut1_dut2_link,
762 'DUT1_TG_LINK': dut1_tg_link,
763 'DUT2_TG_LINK': dut2_tg_link,
764 'TG_TRAFFIC_LINKS': tg_traffic_links,
765 'DUT1_BD_LINKS': dut1_bd_links,
766 'DUT2_BD_LINKS': dut2_bd_links}
767 return topology_links
770 def is_tg_node(node):
771 """Find out whether the node is TG.
773 :param node: Node to examine.
775 :return: True if node is type of TG, otherwise False.
778 return node['type'] == NodeType.TG
781 def get_node_hostname(node):
782 """Return host (hostname/ip address) of the node.
784 :param node: Node created from topology.
786 :return: Hostname or IP address.
792 def set_interface_numa_node(node, iface_key, numa_node_id):
793 """Set interface numa_node location.
795 :param node: Node to set numa_node on.
796 :param iface_key: Interface key from topology file.
799 :return: Return iface_key or None if not found.
802 node['interfaces'][iface_key]['numa_node'] = numa_node_id