LF testbed2 topology, T-REX upgrade, vpe->vpp rename
[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     """Loads 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 class NodeSubTypeTG(object):
47     #T-Rex traffic generator
48     TREX = 'TREX'
49     # Moongen
50     MOONGEN = 'MOONGEN'
51     #IxNetwork
52     IXNET = 'IXNET'
53
54 DICT__nodes = load_topo_from_yaml()
55
56
57 class Topology(object):
58     """Topology data manipulation and extraction methods
59
60     Defines methods used for manipulation and extraction of data from
61     the used topology.
62     """
63
64     def __init__(self):
65         pass
66
67     @staticmethod
68     def get_node_by_hostname(nodes, hostname):
69         """Get node from nodes of the topology by hostname.
70
71         :param nodes: Nodes of the test topology.
72         :param hostname: Host name.
73         :type nodes: dict
74         :type hostname: str
75         :return: Node dictionary or None if not found.
76         """
77         for node in nodes.values():
78             if node['host'] == hostname:
79                 return node
80
81         return None
82
83     @staticmethod
84     def get_links(nodes):
85         """Get list of links(networks) in the topology.
86
87         :param nodes: Nodes of the test topology.
88         :type nodes: dict
89         :return: Links in the topology.
90         :rtype: list
91         """
92         links = []
93
94         for node in nodes.values():
95             for interface in node['interfaces'].values():
96                 link = interface.get('link')
97                 if link is not None:
98                     if link not in links:
99                         links.append(link)
100
101         return links
102
103     @staticmethod
104     def _get_interface_by_key_value(node, key, value):
105         """ Return node interface name according to key and value
106
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.
110         :return:
111         """
112
113         interfaces = node['interfaces']
114         retval = None
115         for interface in interfaces.values():
116             k_val = interface.get(key)
117             if k_val is not None:
118                 if k_val == value:
119                     retval = interface['name']
120                     break
121         return retval
122
123     def get_interface_by_link_name(self, node, link_name):
124         """Return interface name of link on node.
125
126         This method returns the interface name asociated with a given link
127         for a given node.
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
131         """
132
133         return self._get_interface_by_key_value(node, "link", link_name)
134
135     def get_interfaces_by_link_names(self, node, link_names):
136         """Return dictionary of dicitonaries {"interfaceN", interface name}.
137
138         This method returns the interface names asociated with given links
139         for a given node.
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
143         connected to.
144         :param node: the node topology directory
145         :return: dictionary of interface names that are connected to the given
146         links
147         """
148
149         retval = {}
150         interface_key_tpl = "interface{}"
151         interface_number = 1
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
157         return retval
158
159     def get_interface_by_sw_index(self, node, sw_index):
160         """Return interface name of link on node.
161
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
167         """
168
169         return self._get_interface_by_key_value(node, "vpp_sw_index", sw_index)
170
171     @staticmethod
172     def convert_mac_to_number_list(mac_address):
173         """Convert mac address string to list of decimal numbers.
174
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
179         """
180
181         list_mac = []
182         for num in mac_address.split(":"):
183             list_mac.append(int(num, 16))
184         return list_mac
185
186     def _extract_vpp_interface_by_mac(self, interfaces_list, mac_address):
187         """Returns interface dictionary from interface_list by mac address.
188
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
194         """
195
196         interface_dict = {}
197         list_mac_address = self.convert_mac_to_number_list(mac_address)
198         logger.trace(list_mac_address.__str__())
199         for interface in interfaces_list:
200             # TODO: create vat json integrity checking and move there
201             if "l2_address" not in interface:
202                 raise KeyError(
203                     "key l2_address not found in interface dict."
204                     "Probably input list is not parsed from correct VAT "
205                     "json output.")
206             if "l2_address_length" not in interface:
207                 raise KeyError(
208                     "key l2_address_length not found in interface "
209                     "dict. Probably input list is not parsed from correct "
210                     "VAT json output.")
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
216                 break
217         return interface_dict
218
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
221
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
231         """
232
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,
236                                                             mac_address)
237         interface_name = interface_dict["interface_name"]
238         return interface_name
239
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.
242
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
247         command
248         """
249
250         interface_list = JsonParser().parse_data(interface_dump_json)
251         for ifc in node['interfaces'].values():
252             if 'link' not in ifc:
253                 continue
254             if_mac = ifc['mac_address']
255             interface_dict = self._extract_vpp_interface_by_mac(interface_list,
256                                                                 if_mac)
257             ifc['name'] = interface_dict["interface_name"]
258             ifc['vpp_sw_index'] = interface_dict["sw_if_index"]
259
260     def update_vpp_interface_data_on_node(self, node):
261         """Update vpp generated interface data for a given node in DICT__nodes
262
263         Updates interface names, software index numbers and any other details
264         generated specifically by vpp that are unknown before testcase run.
265         :param node: Node selected from DICT__nodes
266         """
267
268         vat_executor = VatExecutor()
269         vat_executor.execute_script_json_out("dump_interfaces.vat", node)
270         interface_dump_json = vat_executor.get_script_stdout()
271         self._update_node_interface_data_from_json(node,
272                                                    interface_dump_json)
273
274     @staticmethod
275     def update_tg_interface_data_on_node(node):
276         """Update interface name for TG/linux node in DICT__nodes
277
278         :param node: Node selected from DICT__nodes.
279         :type node: dict
280
281         .. note::
282             # for dev in `ls /sys/class/net/`;
283             > do echo "\"`cat /sys/class/net/$dev/address`\": \"$dev\""; done
284             "52:54:00:9f:82:63": "eth0"
285             "52:54:00:77:ae:a9": "eth1"
286             "52:54:00:e1:8a:0f": "eth2"
287             "00:00:00:00:00:00": "lo"
288
289         .. todo:: parse lshw -json instead
290         """
291         # First setup interface driver specified in yaml file
292         InterfaceSetup.tg_set_interfaces_default_driver(node)
293
294         # Get interface names
295         ssh = SSH()
296         ssh.connect(node)
297
298         cmd = 'for dev in `ls /sys/class/net/`; do echo "\\"`cat ' \
299               '/sys/class/net/$dev/address`\\": \\"$dev\\""; done;'
300
301         (ret_code, stdout, _) = ssh.exec_command(cmd)
302         if int(ret_code) != 0:
303             raise Exception('Get interface name and MAC failed')
304         tmp = "{" + stdout.rstrip().replace('\n', ',') + "}"
305         interfaces = JsonParser().parse_data(tmp)
306         for if_k, if_v in node['interfaces'].items():
307             if if_k == 'mgmt':
308                 continue
309             name = interfaces.get(if_v['mac_address'])
310             if name is None:
311                 continue
312             if_v['name'] = name
313
314         # Set udev rules for interfaces
315         InterfaceSetup.tg_set_interfaces_udev_rules(node)
316
317     def update_all_interface_data_on_all_nodes(self, nodes):
318         """ Update interface names on all nodes in DICT__nodes
319
320         :param nodes: Nodes in the topology.
321         :type nodes: dict
322
323         This method updates the topology dictionary by querying interface lists
324         of all nodes mentioned in the topology dictionary.
325         It does this by dumping interface list to json output from all devices
326         using vpp_api_test, and pairing known information from topology
327         (mac address/pci address of interface) to state from VPP.
328         For TG/linux nodes add interface name only.
329         """
330
331         for node_data in nodes.values():
332             if node_data['type'] == NodeType.DUT:
333                 self.update_vpp_interface_data_on_node(node_data)
334             elif node_data['type'] == NodeType.TG:
335                 self.update_tg_interface_data_on_node(node_data)
336
337     @staticmethod
338     def get_interface_sw_index(node, interface):
339         """Get VPP sw_index for the interface.
340
341         :param node: Node to get interface sw_index on.
342         :param interface: Interface name.
343         :type node: dict
344         :type interface: str
345         :return: Return sw_index or None if not found.
346         """
347         for port in node['interfaces'].values():
348             port_name = port.get('name')
349             if port_name is None:
350                 continue
351             if port_name == interface:
352                 return port.get('vpp_sw_index')
353
354         return None
355
356     @staticmethod
357     def get_interface_mac_by_port_key(node, port_key):
358         """Get MAC address for the interface based on port key.
359
360         :param node: Node to get interface mac on.
361         :param port_key: Dictionary key name of interface.
362         :type node: dict
363         :type port_key: str
364         :return: Return MAC or None if not found.
365         """
366         for port_name, port_data in node['interfaces'].iteritems():
367             if port_name == port_key:
368                 return port_data['mac_address']
369
370         return None
371
372     @staticmethod
373     def get_interface_mac(node, interface):
374         """Get MAC address for the interface.
375
376         :param node: Node to get interface sw_index on.
377         :param interface: Interface name.
378         :type node: dict
379         :type interface: str
380         :return: Return MAC or None if not found.
381         """
382         for port in node['interfaces'].values():
383             port_name = port.get('name')
384             if port_name is None:
385                 continue
386             if port_name == interface:
387                 return port.get('mac_address')
388
389         return None
390
391     @staticmethod
392     def get_adjacent_node_and_interface_by_key(nodes_info, node, port_key):
393         """Get node and interface adjacent to specified interface
394         on local network.
395
396         :param nodes_info: Dictionary containing information on all nodes
397         in topology.
398         :param node: Node that contains specified interface.
399         :param port_key: Interface port key.
400         :type nodes_info: dict
401         :type node: dict
402         :type port_key: str
403         :return: Return (node, interface info) tuple or None if not found.
404         :rtype: (dict, dict)
405         """
406         link_name = None
407        # get link name where the interface belongs to
408         for port_name, port_data in node['interfaces'].iteritems():
409             if port_name == 'mgmt':
410                 continue
411             if port_name == port_key:
412                 link_name = port_data['link']
413                 break
414
415         if link_name is None: 
416             return None
417
418         # find link
419         for node_data in nodes_info.values():
420             # skip self
421             if node_data['host'] == node['host']:
422                 continue
423             for interface, interface_data \
424                     in node_data['interfaces'].iteritems():
425                 if 'link' not in interface_data:
426                     continue
427                 if interface_data['link'] == link_name:
428                     return node_data, node_data['interfaces'][interface]
429
430     @staticmethod
431     def get_adjacent_node_and_interface(nodes_info, node, interface_name):
432         """Get node and interface adjacent to specified interface
433         on local network.
434
435         :param nodes_info: Dictionary containing information on all nodes
436         in topology.
437         :param node: Node that contains specified interface.
438         :param interface_name: Interface name.
439         :type nodes_info: dict
440         :type node: dict
441         :type interface_name: str
442         :return: Return (node, interface info) tuple or None if not found.
443         :rtype: (dict, dict)
444         """
445         link_name = None
446         # get link name where the interface belongs to
447         for port_name, port_data in node['interfaces'].iteritems():
448             if port_name == 'mgmt':
449                 continue
450             if port_data['name'] == interface_name:
451                 link_name = port_data['link']
452                 break
453
454         if link_name is None:
455             return None
456
457         # find link
458         for node_data in nodes_info.values():
459             # skip self
460             if node_data['host'] == node['host']:
461                 continue
462             for interface, interface_data \
463                     in node_data['interfaces'].iteritems():
464                 if 'link' not in interface_data:
465                     continue
466                 if interface_data['link'] == link_name:
467                     return node_data, node_data['interfaces'][interface]
468
469     @staticmethod
470     def get_interface_pci_addr(node, interface):
471         """Get interface PCI address.
472
473         :param node: Node to get interface PCI address on.
474         :param interface: Interface name.
475         :type node: dict
476         :type interface: str
477         :return: Return PCI address or None if not found.
478         """
479         for port in node['interfaces'].values():
480             if interface == port.get('name'):
481                 return port.get('pci_address')
482         return None
483
484     @staticmethod
485     def get_interface_driver(node, interface):
486         """Get interface driver.
487
488         :param node: Node to get interface driver on.
489         :param interface: Interface name.
490         :type node: dict
491         :type interface: str
492         :return: Return interface driver or None if not found.
493         """
494         for port in node['interfaces'].values():
495             if interface == port.get('name'):
496                 return port.get('driver')
497         return None
498
499     @staticmethod
500     def get_node_link_mac(node, link_name):
501         """Return interface mac address by link name
502
503         :param node: Node to get interface sw_index on
504         :param link_name: link name
505         :type node: dict
506         :type link_name: string
507         :return: mac address string
508         """
509         for port in node['interfaces'].values():
510             if port.get('link') == link_name:
511                 return port.get('mac_address')
512         return None
513
514     @staticmethod
515     def _get_node_active_link_names(node):
516         """Returns list of link names that are other than mgmt links
517
518         :param node: node topology dictionary
519         :return: list of strings that represent link names occupied by the node
520         """
521         interfaces = node['interfaces']
522         link_names = []
523         for interface in interfaces.values():
524             if 'link' in interface:
525                 link_names.append(interface['link'])
526         if len(link_names) == 0:
527             link_names = None
528         return link_names
529
530     @keyword('Get active links connecting "${node1}" and "${node2}"')
531     def get_active_connecting_links(self, node1, node2):
532         """Returns list of link names that connect together node1 and node2
533
534         :param node1: node topology dictionary
535         :param node2: node topology dictionary
536         :return: list of strings that represent connecting link names
537         """
538
539         logger.trace("node1: {}".format(str(node1)))
540         logger.trace("node2: {}".format(str(node2)))
541         node1_links = self._get_node_active_link_names(node1)
542         node2_links = self._get_node_active_link_names(node2)
543         connecting_links = list(set(node1_links).intersection(node2_links))
544
545         return connecting_links
546
547     @keyword('Get first active connecting link between node "${node1}" and '
548              '"${node2}"')
549     def get_first_active_connecting_link(self, node1, node2):
550         """
551
552         :param node1: Connected node
553         :type node1: dict
554         :param node2: Connected node
555         :type node2: dict
556         :return: name of link connecting the two nodes together
557         :raises: RuntimeError
558         """
559
560         connecting_links = self.get_active_connecting_links(node1, node2)
561         if len(connecting_links) == 0:
562             raise RuntimeError("No links connecting the nodes were found")
563         else:
564             return connecting_links[0]
565
566     @keyword('Get egress interfaces on "${node1}" for link with "${node2}"')
567     def get_egress_interfaces_for_nodes(self, node1, node2):
568         """Get egress interfaces on node1 for link with node2.
569
570         :param node1: First node, node to get egress interface on.
571         :param node2: Second node.
572         :type node1: dict
573         :type node2: dict
574         :return: Engress interfaces.
575         :rtype: list
576         """
577         interfaces = []
578         links = self.get_active_connecting_links(node1, node2)
579         if len(links) == 0:
580             raise RuntimeError('No link between nodes')
581         for interface in node1['interfaces'].values():
582             link = interface.get('link')
583             if link is None:
584                 continue
585             if link in links:
586                 continue
587             name = interface.get('name')
588             if name is None:
589                 continue
590             interfaces.append(name)
591         return interfaces
592
593     @keyword('Get first egress interface on "${node1}" for link with '
594              '"${node2}"')
595     def get_first_egress_interface_for_nodes(self, node1, node2):
596         """Get first egress interface on node1 for link with node2.
597
598         :param node1: First node, node to get egress interface on.
599         :param node2: Second node.
600         :type node1: dict
601         :type node2: dict
602         :return: Engress interface.
603         :rtype: str
604         """
605         interfaces = self.get_egress_interfaces_for_nodes(node1, node2)
606         if not interfaces:
607             raise RuntimeError('No engress interface for nodes')
608         return interfaces[0]
609
610     @keyword('Get link data useful in circular topology test from tg "${tgen}"'
611              ' dut1 "${dut1}" dut2 "${dut2}"')
612     def get_links_dict_from_nodes(self, tgen, dut1, dut2):
613         """Returns link combinations used in tests in circular topology.
614
615         For the time being it returns links from the Node path:
616         TG->DUT1->DUT2->TG
617         :param tg: traffic generator node data
618         :param dut1: DUT1 node data
619         :param dut2: DUT2 node data
620         :type tg: dict
621         :type dut1: dict
622         :type dut2: dict
623         :return: dictionary of possible link combinations
624         the naming convention until changed to something more general is
625         implemented is this:
626         DUT1_DUT2_LINK: link name between DUT! and DUT2
627         DUT1_TG_LINK: link name between DUT1 and TG
628         DUT2_TG_LINK: link name between DUT2 and TG
629         TG_TRAFFIC_LINKS: list of link names that generated traffic is sent
630         to and from
631         DUT1_BD_LINKS: list of link names that will be connected by the bridge
632         domain on DUT1
633         DUT2_BD_LINKS: list of link names that will be connected by the bridge
634         domain on DUT2
635         """
636         # TODO: replace with generic function.
637         dut1_dut2_link = self.get_first_active_connecting_link(dut1, dut2)
638         dut1_tg_link = self.get_first_active_connecting_link(dut1, tgen)
639         dut2_tg_link = self.get_first_active_connecting_link(dut2, tgen)
640         tg_traffic_links = [dut1_tg_link, dut2_tg_link]
641         dut1_bd_links = [dut1_dut2_link, dut1_tg_link]
642         dut2_bd_links = [dut1_dut2_link, dut2_tg_link]
643         topology_links = {'DUT1_DUT2_LINK': dut1_dut2_link,
644                           'DUT1_TG_LINK': dut1_tg_link,
645                           'DUT2_TG_LINK': dut2_tg_link,
646                           'TG_TRAFFIC_LINKS': tg_traffic_links,
647                           'DUT1_BD_LINKS': dut1_bd_links,
648                           'DUT2_BD_LINKS': dut2_bd_links}
649         return topology_links