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 resources.libraries.python.parsers.JsonParser import JsonParser
17 from resources.libraries.python.VatExecutor import VatExecutor
18 from resources.libraries.python.ssh import SSH
19 from resources.libraries.python.InterfaceSetup import InterfaceSetup
20 from robot.api import logger
21 from robot.libraries.BuiltIn import BuiltIn
22 from robot.api.deco import keyword
25 __all__ = ["DICT__nodes", 'Topology']
28 def load_topo_from_yaml():
29 """Load topology from file defined in "${TOPOLOGY_PATH}" variable
31 :return: nodes from loaded topology
33 topo_path = BuiltIn().get_variable_value("${TOPOLOGY_PATH}")
35 with open(topo_path) as work_file:
36 return load(work_file.read())['nodes']
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 #T-Rex traffic generator
57 DICT__nodes = load_topo_from_yaml()
60 class Topology(object):
61 """Topology data manipulation and extraction methods
63 Defines methods used for manipulation and extraction of data from
68 def get_node_by_hostname(nodes, hostname):
69 """Get node from nodes of the topology by hostname.
71 :param nodes: Nodes of the test topology.
72 :param hostname: Host name.
75 :return: Node dictionary or None if not found.
77 for node in nodes.values():
78 if node['host'] == hostname:
85 """Get list of links(networks) in the topology.
87 :param nodes: Nodes of the test topology.
89 :return: Links in the topology.
94 for node in nodes.values():
95 for interface in node['interfaces'].values():
96 link = interface.get('link')
104 def _get_interface_by_key_value(node, key, value):
105 """Return node interface name according to key and value
107 :param node: :param node: the node dictionary
108 :param key: key by which to select the interface.
109 :param value: value that should be found using the key.
113 interfaces = node['interfaces']
115 for interface in interfaces.values():
116 k_val = interface.get(key)
117 if k_val is not None:
119 retval = interface['name']
123 def get_interface_by_link_name(self, node, link_name):
124 """Return interface name of link on node.
126 This method returns the interface name asociated with a given link
128 :param link_name: name of the link that a interface is connected to.
129 :param node: the node topology dictionary
130 :return: interface name of the interface connected to the given link
133 return self._get_interface_by_key_value(node, "link", link_name)
135 def get_interfaces_by_link_names(self, node, link_names):
136 """Return dictionary of dicitonaries {"interfaceN", interface name}.
138 This method returns the interface names asociated with given links
140 The resulting dictionary can be then used to with VatConfigGenerator
141 to generate a VAT script with proper interface names.
142 :param link_names: list of names of the link that a interface is
144 :param node: the node topology directory
145 :return: dictionary of interface names that are connected to the given
150 interface_key_tpl = "interface{}"
152 for link_name in link_names:
153 interface_name = self.get_interface_by_link_name(node, link_name)
154 interface_key = interface_key_tpl.format(str(interface_number))
155 retval[interface_key] = interface_name
156 interface_number += 1
159 def get_interface_by_sw_index(self, node, sw_index):
160 """Return interface name of link on node.
162 This method returns the interface name asociated with a software index
163 assigned to the interface by vpp for a given node.
164 :param sw_index: sw_index of the link that a interface is connected to.
165 :param node: the node topology dictionary
166 :return: interface name of the interface connected to the given link
169 return self._get_interface_by_key_value(node, "vpp_sw_index", sw_index)
172 def convert_mac_to_number_list(mac_address):
173 """Convert mac address string to list of decimal numbers.
175 Converts a : separated mac address to decimal number list as used
176 in json interface dump.
177 :param mac_address: string mac address
178 :return: list representation of mac address
182 for num in mac_address.split(":"):
183 list_mac.append(int(num, 16))
186 def _extract_vpp_interface_by_mac(self, interfaces_list, mac_address):
187 """Return interface dictionary from interface_list by mac address.
189 Extracts interface dictionary from all of the interfaces in interfaces
190 list parsed from json according to mac_address of the interface
191 :param interfaces_list: dictionary of all interfaces parsed from json
192 :param mac_address: string mac address of interface we are looking for
193 :return: interface dictionary from json
197 list_mac_address = self.convert_mac_to_number_list(mac_address)
198 logger.trace(str(list_mac_address))
199 for interface in interfaces_list:
200 # TODO: create vat json integrity checking and move there
201 if "l2_address" not in interface:
203 "key l2_address not found in interface dict."
204 "Probably input list is not parsed from correct VAT "
206 if "l2_address_length" not in interface:
208 "key l2_address_length not found in interface "
209 "dict. Probably input list is not parsed from correct "
211 mac_from_json = interface["l2_address"][:6]
212 if mac_from_json == list_mac_address:
213 if interface["l2_address_length"] != 6:
214 raise ValueError("l2_address_length value is not 6.")
215 interface_dict = interface
217 return interface_dict
219 def vpp_interface_name_from_json_by_mac(self, json_data, mac_address):
220 """Return vpp interface name string from VAT interface dump json output
222 Extracts the name given to an interface by VPP.
223 These interface names differ from what you would see if you
224 used the ipconfig or similar command.
225 Required json data can be obtained by calling :
226 VatExecutor.execute_script_json_out("dump_interfaces.vat", node)
227 :param json_data: string json data from sw_interface_dump VAT command
228 :param mac_address: string containing mac address of interface
229 whose vpp name we wish to discover.
230 :return: string vpp interface name
233 interfaces_list = JsonParser().parse_data(json_data)
234 # TODO: checking if json data is parsed correctly
235 interface_dict = self._extract_vpp_interface_by_mac(interfaces_list,
237 interface_name = interface_dict["interface_name"]
238 return interface_name
240 def _update_node_interface_data_from_json(self, node, interface_dump_json):
241 """Update node vpp data in node__DICT from json interface dump.
243 This method updates vpp interface names and sw indexexs according to
244 interface mac addresses found in interface_dump_json
245 :param node: node dictionary
246 :param interface_dump_json: json output from dump_interface_list VAT
250 interface_list = JsonParser().parse_data(interface_dump_json)
251 for ifc in node['interfaces'].values():
252 if 'link' not in ifc:
254 if_mac = ifc['mac_address']
255 interface_dict = self._extract_vpp_interface_by_mac(interface_list,
257 if not interface_dict:
258 raise Exception('Interface {0} not found by MAC {1}'.
260 ifc['name'] = interface_dict["interface_name"]
261 ifc['vpp_sw_index'] = interface_dict["sw_if_index"]
262 ifc['mtu'] = interface_dict["mtu"]
264 def update_vpp_interface_data_on_node(self, node):
265 """Update vpp generated interface data for a given node in DICT__nodes
267 Updates interface names, software index numbers and any other details
268 generated specifically by vpp that are unknown before testcase run.
269 :param node: Node selected from DICT__nodes
272 vat_executor = VatExecutor()
273 vat_executor.execute_script_json_out("dump_interfaces.vat", node)
274 interface_dump_json = vat_executor.get_script_stdout()
275 self._update_node_interface_data_from_json(node,
279 def update_tg_interface_data_on_node(node):
280 """Update interface name for TG/linux node in DICT__nodes
282 :param node: Node selected from DICT__nodes.
286 # for dev in `ls /sys/class/net/`;
287 > do echo "\"`cat /sys/class/net/$dev/address`\": \"$dev\""; done
288 "52:54:00:9f:82:63": "eth0"
289 "52:54:00:77:ae:a9": "eth1"
290 "52:54:00:e1:8a:0f": "eth2"
291 "00:00:00:00:00:00": "lo"
293 .. todo:: parse lshw -json instead
295 # First setup interface driver specified in yaml file
296 InterfaceSetup.tg_set_interfaces_default_driver(node)
298 # Get interface names
302 cmd = 'for dev in `ls /sys/class/net/`; do echo "\\"`cat ' \
303 '/sys/class/net/$dev/address`\\": \\"$dev\\""; done;'
305 (ret_code, stdout, _) = ssh.exec_command(cmd)
306 if int(ret_code) != 0:
307 raise Exception('Get interface name and MAC failed')
308 tmp = "{" + stdout.rstrip().replace('\n', ',') + "}"
309 interfaces = JsonParser().parse_data(tmp)
310 for if_k, if_v in node['interfaces'].items():
313 name = interfaces.get(if_v['mac_address'])
318 # Set udev rules for interfaces
319 InterfaceSetup.tg_set_interfaces_udev_rules(node)
321 def update_all_interface_data_on_all_nodes(self, nodes):
322 """Update interface names on all nodes in DICT__nodes
324 :param nodes: Nodes in the topology.
327 This method updates the topology dictionary by querying interface lists
328 of all nodes mentioned in the topology dictionary.
329 It does this by dumping interface list to json output from all devices
330 using vpp_api_test, and pairing known information from topology
331 (mac address/pci address of interface) to state from VPP.
332 For TG/linux nodes add interface name only.
335 for node_data in nodes.values():
336 if node_data['type'] == NodeType.DUT:
337 self.update_vpp_interface_data_on_node(node_data)
338 elif node_data['type'] == NodeType.TG:
339 self.update_tg_interface_data_on_node(node_data)
342 def get_interface_sw_index(node, interface):
343 """Get VPP sw_index for the interface.
345 :param node: Node to get interface sw_index on.
346 :param interface: Interface name.
349 :return: Return sw_index or None if not found.
351 for port in node['interfaces'].values():
352 port_name = port.get('name')
353 if port_name == interface:
354 return port.get('vpp_sw_index')
359 def get_interface_mtu(node, interface):
360 """Get interface MTU.
362 Returns physical layer MTU (max. size of Ethernet frame).
363 :param node: Node to get interface MTU on.
364 :param interface: Interface name.
367 :return: MTU or None if not found.
370 for port in node['interfaces'].values():
371 port_name = port.get('name')
372 if port_name == interface:
373 return port.get('mtu')
378 def get_interface_mac_by_port_key(node, port_key):
379 """Get MAC address for the interface based on port key.
381 :param node: Node to get interface mac on.
382 :param port_key: Dictionary key name of interface.
385 :return: Return MAC or None if not found.
387 for port_name, port_data in node['interfaces'].iteritems():
388 if port_name == port_key:
389 return port_data['mac_address']
394 def get_interface_mac(node, interface):
395 """Get MAC address for the interface.
397 :param node: Node to get interface sw_index on.
398 :param interface: Interface name.
401 :return: Return MAC or None if not found.
403 for port in node['interfaces'].values():
404 port_name = port.get('name')
405 if port_name == interface:
406 return port.get('mac_address')
411 def get_adjacent_node_and_interface_by_key(nodes_info, node, port_key):
412 """Get node and interface adjacent to specified interface
415 :param nodes_info: Dictionary containing information on all nodes
417 :param node: Node that contains specified interface.
418 :param port_key: Interface port key.
419 :type nodes_info: dict
422 :return: Return (node, interface info) tuple or None if not found.
426 # get link name where the interface belongs to
427 for port_name, port_data in node['interfaces'].iteritems():
428 if port_name == 'mgmt':
430 if port_name == port_key:
431 link_name = port_data['link']
434 if link_name is None:
438 for node_data in nodes_info.values():
440 if node_data['host'] == node['host']:
442 for interface, interface_data \
443 in node_data['interfaces'].iteritems():
444 if 'link' not in interface_data:
446 if interface_data['link'] == link_name:
447 return node_data, node_data['interfaces'][interface]
450 def get_adjacent_node_and_interface(nodes_info, node, interface_name):
451 """Get node and interface adjacent to specified interface
454 :param nodes_info: Dictionary containing information on all nodes
456 :param node: Node that contains specified interface.
457 :param interface_name: Interface name.
458 :type nodes_info: dict
460 :type interface_name: str
461 :return: Return (node, interface info) tuple or None if not found.
465 # get link name where the interface belongs to
466 for port_name, port_data in node['interfaces'].iteritems():
467 if port_name == 'mgmt':
469 if port_data['name'] == interface_name:
470 link_name = port_data['link']
473 if link_name is None:
477 for node_data in nodes_info.values():
479 if node_data['host'] == node['host']:
481 for interface, interface_data \
482 in node_data['interfaces'].iteritems():
483 if 'link' not in interface_data:
485 if interface_data['link'] == link_name:
486 return node_data, node_data['interfaces'][interface]
489 def get_interface_pci_addr(node, interface):
490 """Get interface PCI address.
492 :param node: Node to get interface PCI address on.
493 :param interface: Interface name.
496 :return: Return PCI address or None if not found.
498 for port in node['interfaces'].values():
499 if interface == port.get('name'):
500 return port.get('pci_address')
504 def get_interface_driver(node, interface):
505 """Get interface driver.
507 :param node: Node to get interface driver on.
508 :param interface: Interface name.
511 :return: Return interface driver or None if not found.
513 for port in node['interfaces'].values():
514 if interface == port.get('name'):
515 return port.get('driver')
519 def get_node_link_mac(node, link_name):
520 """Return interface mac address by link name
522 :param node: Node to get interface sw_index on
523 :param link_name: link name
525 :type link_name: string
526 :return: mac address string
528 for port in node['interfaces'].values():
529 if port.get('link') == link_name:
530 return port.get('mac_address')
534 def _get_node_active_link_names(node):
535 """Return list of link names that are other than mgmt links
537 :param node: node topology dictionary
538 :return: list of strings that represent link names occupied by the node
540 interfaces = node['interfaces']
542 for interface in interfaces.values():
543 if 'link' in interface:
544 link_names.append(interface['link'])
545 if len(link_names) == 0:
549 @keyword('Get active links connecting "${node1}" and "${node2}"')
550 def get_active_connecting_links(self, node1, node2):
551 """Return list of link names that connect together node1 and node2
553 :param node1: node topology dictionary
554 :param node2: node topology dictionary
555 :return: list of strings that represent connecting link names
558 logger.trace("node1: {}".format(str(node1)))
559 logger.trace("node2: {}".format(str(node2)))
560 node1_links = self._get_node_active_link_names(node1)
561 node2_links = self._get_node_active_link_names(node2)
562 connecting_links = list(set(node1_links).intersection(node2_links))
564 return connecting_links
566 @keyword('Get first active connecting link between node "${node1}" and '
568 def get_first_active_connecting_link(self, node1, node2):
571 :param node1: Connected node
573 :param node2: Connected node
575 :return: name of link connecting the two nodes together
576 :raises: RuntimeError
579 connecting_links = self.get_active_connecting_links(node1, node2)
580 if len(connecting_links) == 0:
581 raise RuntimeError("No links connecting the nodes were found")
583 return connecting_links[0]
585 @keyword('Get egress interfaces on "${node1}" for link with "${node2}"')
586 def get_egress_interfaces_for_nodes(self, node1, node2):
587 """Get egress interfaces on node1 for link with node2.
589 :param node1: First node, node to get egress interface on.
590 :param node2: Second node.
593 :return: Egress interfaces.
597 links = self.get_active_connecting_links(node1, node2)
599 raise RuntimeError('No link between nodes')
600 for interface in node1['interfaces'].values():
601 link = interface.get('link')
606 name = interface.get('name')
609 interfaces.append(name)
612 @keyword('Get first egress interface on "${node1}" for link with '
614 def get_first_egress_interface_for_nodes(self, node1, node2):
615 """Get first egress interface on node1 for link with node2.
617 :param node1: First node, node to get egress interface on.
618 :param node2: Second node.
621 :return: Egress interface.
624 interfaces = self.get_egress_interfaces_for_nodes(node1, node2)
626 raise RuntimeError('No egress interface for nodes')
629 @keyword('Get link data useful in circular topology test from tg "${tgen}"'
630 ' dut1 "${dut1}" dut2 "${dut2}"')
631 def get_links_dict_from_nodes(self, tgen, dut1, dut2):
632 """Return link combinations used in tests in circular topology.
634 For the time being it returns links from the Node path:
636 :param tgen: traffic generator node data
637 :param dut1: DUT1 node data
638 :param dut2: DUT2 node data
642 :return: dictionary of possible link combinations
643 the naming convention until changed to something more general is
645 DUT1_DUT2_LINK: link name between DUT! and DUT2
646 DUT1_TG_LINK: link name between DUT1 and TG
647 DUT2_TG_LINK: link name between DUT2 and TG
648 TG_TRAFFIC_LINKS: list of link names that generated traffic is sent
650 DUT1_BD_LINKS: list of link names that will be connected by the bridge
652 DUT2_BD_LINKS: list of link names that will be connected by the bridge
655 # TODO: replace with generic function.
656 dut1_dut2_link = self.get_first_active_connecting_link(dut1, dut2)
657 dut1_tg_link = self.get_first_active_connecting_link(dut1, tgen)
658 dut2_tg_link = self.get_first_active_connecting_link(dut2, tgen)
659 tg_traffic_links = [dut1_tg_link, dut2_tg_link]
660 dut1_bd_links = [dut1_dut2_link, dut1_tg_link]
661 dut2_bd_links = [dut1_dut2_link, dut2_tg_link]
662 topology_links = {'DUT1_DUT2_LINK': dut1_dut2_link,
663 'DUT1_TG_LINK': dut1_tg_link,
664 'DUT2_TG_LINK': dut2_tg_link,
665 'TG_TRAFFIC_LINKS': tg_traffic_links,
666 'DUT1_BD_LINKS': dut1_bd_links,
667 'DUT2_BD_LINKS': dut2_bd_links}
668 return topology_links
671 def is_tg_node(node):
672 """Find out whether the node is TG
674 :param node: node to examine
675 :return: True if node is type of TG; False otherwise
677 return node['type'] == NodeType.TG
680 def get_node_hostname(node):
681 """Return host (hostname/ip address) of the node.
683 :param node: Node created from topology.
685 :return: host as 'str' type