Modify sweep ping test cases
[csit.git] / resources / libraries / python / topology.py
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:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
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.
13
14 """Defines nodes and topology structure."""
15
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
23 from yaml import load
24
25 __all__ = ["DICT__nodes", 'Topology']
26
27
28 def load_topo_from_yaml():
29     """Load topology from file defined in "${TOPOLOGY_PATH}" variable
30
31     :return: nodes from loaded topology
32     """
33     topo_path = BuiltIn().get_variable_value("${TOPOLOGY_PATH}")
34
35     with open(topo_path) as work_file:
36         return load(work_file.read())['nodes']
37
38
39 class NodeType(object):
40     """Defines node types used in topology dictionaries"""
41     # Device Under Test (this node has VPP running on it)
42     DUT = 'DUT'
43     # Traffic Generator (this node has traffic generator on it)
44     TG = 'TG'
45
46
47 class NodeSubTypeTG(object):
48     #T-Rex traffic generator
49     TREX = 'TREX'
50     # Moongen
51     MOONGEN = 'MOONGEN'
52     # IxNetwork
53     IXNET = 'IXNET'
54
55 DICT__nodes = load_topo_from_yaml()
56
57
58 class Topology(object):
59     """Topology data manipulation and extraction methods
60
61     Defines methods used for manipulation and extraction of data from
62     the used topology.
63     """
64
65     @staticmethod
66     def get_node_by_hostname(nodes, hostname):
67         """Get node from nodes of the topology by hostname.
68
69         :param nodes: Nodes of the test topology.
70         :param hostname: Host name.
71         :type nodes: dict
72         :type hostname: str
73         :return: Node dictionary or None if not found.
74         """
75         for node in nodes.values():
76             if node['host'] == hostname:
77                 return node
78
79         return None
80
81     @staticmethod
82     def get_links(nodes):
83         """Get list of links(networks) in the topology.
84
85         :param nodes: Nodes of the test topology.
86         :type nodes: dict
87         :return: Links in the topology.
88         :rtype: list
89         """
90         links = []
91
92         for node in nodes.values():
93             for interface in node['interfaces'].values():
94                 link = interface.get('link')
95                 if link is not None:
96                     if link not in links:
97                         links.append(link)
98
99         return links
100
101     @staticmethod
102     def _get_interface_by_key_value(node, key, value):
103         """Return node interface name according to key and value
104
105         :param node: :param node: the node dictionary
106         :param key: key by which to select the interface.
107         :param value: value that should be found using the key.
108         :return:
109         """
110
111         interfaces = node['interfaces']
112         retval = None
113         for interface in interfaces.values():
114             k_val = interface.get(key)
115             if k_val is not None:
116                 if k_val == value:
117                     retval = interface['name']
118                     break
119         return retval
120
121     def get_interface_by_link_name(self, node, link_name):
122         """Return interface name of link on node.
123
124         This method returns the interface name asociated with a given link
125         for a given node.
126         :param link_name: name of the link that a interface is connected to.
127         :param node: the node topology dictionary
128         :return: interface name of the interface connected to the given link
129         """
130
131         return self._get_interface_by_key_value(node, "link", link_name)
132
133     def get_interfaces_by_link_names(self, node, link_names):
134         """Return dictionary of dicitonaries {"interfaceN", interface name}.
135
136         This method returns the interface names asociated with given links
137         for a given node.
138         The resulting dictionary can be then used to with VatConfigGenerator
139         to generate a VAT script with proper interface names.
140         :param link_names: list of names of the link that a interface is
141         connected to.
142         :param node: the node topology directory
143         :return: dictionary of interface names that are connected to the given
144         links
145         """
146
147         retval = {}
148         interface_key_tpl = "interface{}"
149         interface_number = 1
150         for link_name in link_names:
151             interface_name = self.get_interface_by_link_name(node, link_name)
152             interface_key = interface_key_tpl.format(str(interface_number))
153             retval[interface_key] = interface_name
154             interface_number += 1
155         return retval
156
157     def get_interface_by_sw_index(self, node, sw_index):
158         """Return interface name of link on node.
159
160         This method returns the interface name asociated with a software index
161         assigned to the interface by vpp for a given node.
162         :param sw_index: sw_index of the link that a interface is connected to.
163         :param node: the node topology dictionary
164         :return: interface name of the interface connected to the given link
165         """
166
167         return self._get_interface_by_key_value(node, "vpp_sw_index", sw_index)
168
169     @staticmethod
170     def convert_mac_to_number_list(mac_address):
171         """Convert mac address string to list of decimal numbers.
172
173         Converts a : separated mac address to decimal number list as used
174         in json interface dump.
175         :param mac_address: string mac address
176         :return: list representation of mac address
177         """
178
179         list_mac = []
180         for num in mac_address.split(":"):
181             list_mac.append(int(num, 16))
182         return list_mac
183
184     def _extract_vpp_interface_by_mac(self, interfaces_list, mac_address):
185         """Return interface dictionary from interface_list by mac address.
186
187         Extracts interface dictionary from all of the interfaces in interfaces
188         list parsed from json according to mac_address of the interface
189         :param interfaces_list: dictionary of all interfaces parsed from json
190         :param mac_address: string mac address of interface we are looking for
191         :return: interface dictionary from json
192         """
193
194         interface_dict = {}
195         list_mac_address = self.convert_mac_to_number_list(mac_address)
196         logger.trace(str(list_mac_address))
197         for interface in interfaces_list:
198             # TODO: create vat json integrity checking and move there
199             if "l2_address" not in interface:
200                 raise KeyError(
201                     "key l2_address not found in interface dict."
202                     "Probably input list is not parsed from correct VAT "
203                     "json output.")
204             if "l2_address_length" not in interface:
205                 raise KeyError(
206                     "key l2_address_length not found in interface "
207                     "dict. Probably input list is not parsed from correct "
208                     "VAT json output.")
209             mac_from_json = interface["l2_address"][:6]
210             if mac_from_json == list_mac_address:
211                 if interface["l2_address_length"] != 6:
212                     raise ValueError("l2_address_length value is not 6.")
213                 interface_dict = interface
214                 break
215         return interface_dict
216
217     def vpp_interface_name_from_json_by_mac(self, json_data, mac_address):
218         """Return vpp interface name string from VAT interface dump json output
219
220         Extracts the name given to an interface by VPP.
221         These interface names differ from what you would see if you
222         used the ipconfig or similar command.
223         Required json data can be obtained by calling :
224         VatExecutor.execute_script_json_out("dump_interfaces.vat", node)
225         :param json_data: string json data from sw_interface_dump VAT command
226         :param mac_address: string containing mac address of interface
227         whose vpp name we wish to discover.
228         :return: string vpp interface name
229         """
230
231         interfaces_list = JsonParser().parse_data(json_data)
232         # TODO: checking if json data is parsed correctly
233         interface_dict = self._extract_vpp_interface_by_mac(interfaces_list,
234                                                             mac_address)
235         interface_name = interface_dict["interface_name"]
236         return interface_name
237
238     def _update_node_interface_data_from_json(self, node, interface_dump_json):
239         """Update node vpp data in node__DICT from json interface dump.
240
241         This method updates vpp interface names and sw indexexs according to
242         interface mac addresses found in interface_dump_json
243         :param node: node dictionary
244         :param interface_dump_json: json output from dump_interface_list VAT
245         command
246         """
247
248         interface_list = JsonParser().parse_data(interface_dump_json)
249         for ifc in node['interfaces'].values():
250             if 'link' not in ifc:
251                 continue
252             if_mac = ifc['mac_address']
253             interface_dict = self._extract_vpp_interface_by_mac(interface_list,
254                                                                 if_mac)
255             if not interface_dict:
256                 raise Exception('Interface {0} not found by MAC {1}'.
257                         format(ifc, if_mac))
258             ifc['name'] = interface_dict["interface_name"]
259             ifc['vpp_sw_index'] = interface_dict["sw_if_index"]
260             ifc['mtu'] = interface_dict["mtu"]
261
262     def update_vpp_interface_data_on_node(self, node):
263         """Update vpp generated interface data for a given node in DICT__nodes
264
265         Updates interface names, software index numbers and any other details
266         generated specifically by vpp that are unknown before testcase run.
267         :param node: Node selected from DICT__nodes
268         """
269
270         vat_executor = VatExecutor()
271         vat_executor.execute_script_json_out("dump_interfaces.vat", node)
272         interface_dump_json = vat_executor.get_script_stdout()
273         self._update_node_interface_data_from_json(node,
274                                                    interface_dump_json)
275
276     @staticmethod
277     def update_tg_interface_data_on_node(node):
278         """Update interface name for TG/linux node in DICT__nodes
279
280         :param node: Node selected from DICT__nodes.
281         :type node: dict
282
283         .. note::
284             # for dev in `ls /sys/class/net/`;
285             > do echo "\"`cat /sys/class/net/$dev/address`\": \"$dev\""; done
286             "52:54:00:9f:82:63": "eth0"
287             "52:54:00:77:ae:a9": "eth1"
288             "52:54:00:e1:8a:0f": "eth2"
289             "00:00:00:00:00:00": "lo"
290
291         .. todo:: parse lshw -json instead
292         """
293         # First setup interface driver specified in yaml file
294         InterfaceSetup.tg_set_interfaces_default_driver(node)
295
296         # Get interface names
297         ssh = SSH()
298         ssh.connect(node)
299
300         cmd = 'for dev in `ls /sys/class/net/`; do echo "\\"`cat ' \
301               '/sys/class/net/$dev/address`\\": \\"$dev\\""; done;'
302
303         (ret_code, stdout, _) = ssh.exec_command(cmd)
304         if int(ret_code) != 0:
305             raise Exception('Get interface name and MAC failed')
306         tmp = "{" + stdout.rstrip().replace('\n', ',') + "}"
307         interfaces = JsonParser().parse_data(tmp)
308         for if_k, if_v in node['interfaces'].items():
309             if if_k == 'mgmt':
310                 continue
311             name = interfaces.get(if_v['mac_address'])
312             if name is None:
313                 continue
314             if_v['name'] = name
315
316         # Set udev rules for interfaces
317         InterfaceSetup.tg_set_interfaces_udev_rules(node)
318
319     def update_all_interface_data_on_all_nodes(self, nodes):
320         """Update interface names on all nodes in DICT__nodes
321
322         :param nodes: Nodes in the topology.
323         :type nodes: dict
324
325         This method updates the topology dictionary by querying interface lists
326         of all nodes mentioned in the topology dictionary.
327         It does this by dumping interface list to json output from all devices
328         using vpp_api_test, and pairing known information from topology
329         (mac address/pci address of interface) to state from VPP.
330         For TG/linux nodes add interface name only.
331         """
332
333         for node_data in nodes.values():
334             if node_data['type'] == NodeType.DUT:
335                 self.update_vpp_interface_data_on_node(node_data)
336             elif node_data['type'] == NodeType.TG:
337                 self.update_tg_interface_data_on_node(node_data)
338
339     @staticmethod
340     def get_interface_sw_index(node, interface):
341         """Get VPP sw_index for the interface.
342
343         :param node: Node to get interface sw_index on.
344         :param interface: Interface name.
345         :type node: dict
346         :type interface: str
347         :return: Return sw_index or None if not found.
348         """
349         for port in node['interfaces'].values():
350             port_name = port.get('name')
351             if port_name == interface:
352                 return port.get('vpp_sw_index')
353
354         return None
355
356     @staticmethod
357     def get_interface_mtu(node, interface):
358         """Get interface MTU.
359
360         Returns physical layer MTU (max. size of Ethernet frame).
361         :param node: Node to get interface MTU on.
362         :param interface: Interface name.
363         :type node: dict
364         :type interface: str
365         :return: MTU or None if not found.
366         :rtype: int
367         """
368         for port in node['interfaces'].values():
369             port_name = port.get('name')
370             if port_name == interface:
371                 return port.get('mtu')
372
373         return None
374
375     @staticmethod
376     def get_interface_mac_by_port_key(node, port_key):
377         """Get MAC address for the interface based on port key.
378
379         :param node: Node to get interface mac on.
380         :param port_key: Dictionary key name of interface.
381         :type node: dict
382         :type port_key: str
383         :return: Return MAC or None if not found.
384         """
385         for port_name, port_data in node['interfaces'].iteritems():
386             if port_name == port_key:
387                 return port_data['mac_address']
388
389         return None
390
391     @staticmethod
392     def get_interface_mac(node, interface):
393         """Get MAC address for the interface.
394
395         :param node: Node to get interface sw_index on.
396         :param interface: Interface name.
397         :type node: dict
398         :type interface: str
399         :return: Return MAC or None if not found.
400         """
401         for port in node['interfaces'].values():
402             port_name = port.get('name')
403             if port_name == interface:
404                 return port.get('mac_address')
405
406         return None
407
408     @staticmethod
409     def get_adjacent_node_and_interface_by_key(nodes_info, node, port_key):
410         """Get node and interface adjacent to specified interface
411         on local network.
412
413         :param nodes_info: Dictionary containing information on all nodes
414         in topology.
415         :param node: Node that contains specified interface.
416         :param port_key: Interface port key.
417         :type nodes_info: dict
418         :type node: dict
419         :type port_key: str
420         :return: Return (node, interface info) tuple or None if not found.
421         :rtype: (dict, dict)
422         """
423         link_name = None
424         # get link name where the interface belongs to
425         for port_name, port_data in node['interfaces'].iteritems():
426             if port_name == 'mgmt':
427                 continue
428             if port_name == port_key:
429                 link_name = port_data['link']
430                 break
431
432         if link_name is None: 
433             return None
434
435         # find link
436         for node_data in nodes_info.values():
437             # skip self
438             if node_data['host'] == node['host']:
439                 continue
440             for interface, interface_data \
441                     in node_data['interfaces'].iteritems():
442                 if 'link' not in interface_data:
443                     continue
444                 if interface_data['link'] == link_name:
445                     return node_data, node_data['interfaces'][interface]
446
447     @staticmethod
448     def get_adjacent_node_and_interface(nodes_info, node, interface_name):
449         """Get node and interface adjacent to specified interface
450         on local network.
451
452         :param nodes_info: Dictionary containing information on all nodes
453         in topology.
454         :param node: Node that contains specified interface.
455         :param interface_name: Interface name.
456         :type nodes_info: dict
457         :type node: dict
458         :type interface_name: str
459         :return: Return (node, interface info) tuple or None if not found.
460         :rtype: (dict, dict)
461         """
462         link_name = None
463         # get link name where the interface belongs to
464         for port_name, port_data in node['interfaces'].iteritems():
465             if port_name == 'mgmt':
466                 continue
467             if port_data['name'] == interface_name:
468                 link_name = port_data['link']
469                 break
470
471         if link_name is None:
472             return None
473
474         # find link
475         for node_data in nodes_info.values():
476             # skip self
477             if node_data['host'] == node['host']:
478                 continue
479             for interface, interface_data \
480                     in node_data['interfaces'].iteritems():
481                 if 'link' not in interface_data:
482                     continue
483                 if interface_data['link'] == link_name:
484                     return node_data, node_data['interfaces'][interface]
485
486     @staticmethod
487     def get_interface_pci_addr(node, interface):
488         """Get interface PCI address.
489
490         :param node: Node to get interface PCI address on.
491         :param interface: Interface name.
492         :type node: dict
493         :type interface: str
494         :return: Return PCI address or None if not found.
495         """
496         for port in node['interfaces'].values():
497             if interface == port.get('name'):
498                 return port.get('pci_address')
499         return None
500
501     @staticmethod
502     def get_interface_driver(node, interface):
503         """Get interface driver.
504
505         :param node: Node to get interface driver on.
506         :param interface: Interface name.
507         :type node: dict
508         :type interface: str
509         :return: Return interface driver or None if not found.
510         """
511         for port in node['interfaces'].values():
512             if interface == port.get('name'):
513                 return port.get('driver')
514         return None
515
516     @staticmethod
517     def get_node_link_mac(node, link_name):
518         """Return interface mac address by link name
519
520         :param node: Node to get interface sw_index on
521         :param link_name: link name
522         :type node: dict
523         :type link_name: string
524         :return: mac address string
525         """
526         for port in node['interfaces'].values():
527             if port.get('link') == link_name:
528                 return port.get('mac_address')
529         return None
530
531     @staticmethod
532     def _get_node_active_link_names(node):
533         """Return list of link names that are other than mgmt links
534
535         :param node: node topology dictionary
536         :return: list of strings that represent link names occupied by the node
537         """
538         interfaces = node['interfaces']
539         link_names = []
540         for interface in interfaces.values():
541             if 'link' in interface:
542                 link_names.append(interface['link'])
543         if len(link_names) == 0:
544             link_names = None
545         return link_names
546
547     @keyword('Get active links connecting "${node1}" and "${node2}"')
548     def get_active_connecting_links(self, node1, node2):
549         """Return list of link names that connect together node1 and node2
550
551         :param node1: node topology dictionary
552         :param node2: node topology dictionary
553         :return: list of strings that represent connecting link names
554         """
555
556         logger.trace("node1: {}".format(str(node1)))
557         logger.trace("node2: {}".format(str(node2)))
558         node1_links = self._get_node_active_link_names(node1)
559         node2_links = self._get_node_active_link_names(node2)
560         connecting_links = list(set(node1_links).intersection(node2_links))
561
562         return connecting_links
563
564     @keyword('Get first active connecting link between node "${node1}" and '
565              '"${node2}"')
566     def get_first_active_connecting_link(self, node1, node2):
567         """
568
569         :param node1: Connected node
570         :type node1: dict
571         :param node2: Connected node
572         :type node2: dict
573         :return: name of link connecting the two nodes together
574         :raises: RuntimeError
575         """
576
577         connecting_links = self.get_active_connecting_links(node1, node2)
578         if len(connecting_links) == 0:
579             raise RuntimeError("No links connecting the nodes were found")
580         else:
581             return connecting_links[0]
582
583     @keyword('Get egress interfaces on "${node1}" for link with "${node2}"')
584     def get_egress_interfaces_for_nodes(self, node1, node2):
585         """Get egress interfaces on node1 for link with node2.
586
587         :param node1: First node, node to get egress interface on.
588         :param node2: Second node.
589         :type node1: dict
590         :type node2: dict
591         :return: Egress interfaces.
592         :rtype: list
593         """
594         interfaces = []
595         links = self.get_active_connecting_links(node1, node2)
596         if len(links) == 0:
597             raise RuntimeError('No link between nodes')
598         for interface in node1['interfaces'].values():
599             link = interface.get('link')
600             if link is None:
601                 continue
602             if link in links:
603                 continue
604             name = interface.get('name')
605             if name is None:
606                 continue
607             interfaces.append(name)
608         return interfaces
609
610     @keyword('Get first egress interface on "${node1}" for link with '
611              '"${node2}"')
612     def get_first_egress_interface_for_nodes(self, node1, node2):
613         """Get first egress interface on node1 for link with node2.
614
615         :param node1: First node, node to get egress interface on.
616         :param node2: Second node.
617         :type node1: dict
618         :type node2: dict
619         :return: Egress interface.
620         :rtype: str
621         """
622         interfaces = self.get_egress_interfaces_for_nodes(node1, node2)
623         if not interfaces:
624             raise RuntimeError('No egress interface for nodes')
625         return interfaces[0]
626
627     @keyword('Get link data useful in circular topology test from tg "${tgen}"'
628              ' dut1 "${dut1}" dut2 "${dut2}"')
629     def get_links_dict_from_nodes(self, tgen, dut1, dut2):
630         """Return link combinations used in tests in circular topology.
631
632         For the time being it returns links from the Node path:
633         TG->DUT1->DUT2->TG
634         :param tgen: traffic generator node data
635         :param dut1: DUT1 node data
636         :param dut2: DUT2 node data
637         :type tgen: dict
638         :type dut1: dict
639         :type dut2: dict
640         :return: dictionary of possible link combinations
641         the naming convention until changed to something more general is
642         implemented is this:
643         DUT1_DUT2_LINK: link name between DUT! and DUT2
644         DUT1_TG_LINK: link name between DUT1 and TG
645         DUT2_TG_LINK: link name between DUT2 and TG
646         TG_TRAFFIC_LINKS: list of link names that generated traffic is sent
647         to and from
648         DUT1_BD_LINKS: list of link names that will be connected by the bridge
649         domain on DUT1
650         DUT2_BD_LINKS: list of link names that will be connected by the bridge
651         domain on DUT2
652         """
653         # TODO: replace with generic function.
654         dut1_dut2_link = self.get_first_active_connecting_link(dut1, dut2)
655         dut1_tg_link = self.get_first_active_connecting_link(dut1, tgen)
656         dut2_tg_link = self.get_first_active_connecting_link(dut2, tgen)
657         tg_traffic_links = [dut1_tg_link, dut2_tg_link]
658         dut1_bd_links = [dut1_dut2_link, dut1_tg_link]
659         dut2_bd_links = [dut1_dut2_link, dut2_tg_link]
660         topology_links = {'DUT1_DUT2_LINK': dut1_dut2_link,
661                           'DUT1_TG_LINK': dut1_tg_link,
662                           'DUT2_TG_LINK': dut2_tg_link,
663                           'TG_TRAFFIC_LINKS': tg_traffic_links,
664                           'DUT1_BD_LINKS': dut1_bd_links,
665                           'DUT2_BD_LINKS': dut2_bd_links}
666         return topology_links
667
668     @staticmethod
669     def is_tg_node(node):
670         """Find out whether the node is TG
671
672         :param node: node to examine
673         :return: True if node is type of TG; False otherwise
674         """
675         return node['type'] == NodeType.TG
676
677     @staticmethod
678     def get_node_hostname(node):
679         """Return host (hostname/ip address) of the node.
680
681         :param node: Node created from topology.
682         :type node: dict
683         :return: host as 'str' type
684         """
685         return node['host']