New version of RF tests.
[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 DICT__nodes = load_topo_from_yaml()
47
48
49 class Topology(object):
50     """Topology data manipulation and extraction methods
51
52     Defines methods used for manipulation and extraction of data from
53     the used topology.
54     """
55
56     def __init__(self):
57         pass
58
59     @staticmethod
60     def get_node_by_hostname(nodes, hostname):
61         """Get node from nodes of the topology by hostname.
62
63         :param nodes: Nodes of the test topology.
64         :param hostname: Host name.
65         :type nodes: dict
66         :type hostname: str
67         :return: Node dictionary or None if not found.
68         """
69         for node in nodes.values():
70             if node['host'] == hostname:
71                 return node
72
73         return None
74
75     @staticmethod
76     def get_links(nodes):
77         """Get list of links(networks) in the topology.
78
79         :param nodes: Nodes of the test topology.
80         :type nodes: dict
81         :return: Links in the topology.
82         :rtype: list
83         """
84         links = []
85
86         for node in nodes.values():
87             for interface in node['interfaces'].values():
88                 link = interface.get('link')
89                 if link is not None:
90                     if link not in links:
91                         links.append(link)
92
93         return links
94
95     @staticmethod
96     def _get_interface_by_key_value(node, key, value):
97         """ Return node interface name according to key and value
98
99         :param node: :param node: the node dictionary
100         :param key: key by which to select the interface.
101         :param value: value that should be found using the key.
102         :return:
103         """
104
105         interfaces = node['interfaces']
106         retval = None
107         for interface in interfaces.values():
108             k_val = interface.get(key)
109             if k_val is not None:
110                 if k_val == value:
111                     retval = interface['name']
112                     break
113         return retval
114
115     def get_interface_by_link_name(self, node, link_name):
116         """Return interface name of link on node.
117
118         This method returns the interface name asociated with a given link
119         for a given node.
120         :param link_name: name of the link that a interface is connected to.
121         :param node: the node topology dictionary
122         :return: interface name of the interface connected to the given link
123         """
124
125         return self._get_interface_by_key_value(node, "link", link_name)
126
127     def get_interfaces_by_link_names(self, node, link_names):
128         """Return dictionary of dicitonaries {"interfaceN", interface name}.
129
130         This method returns the interface names asociated with given links
131         for a given node.
132         The resulting dictionary can be then used to with VatConfigGenerator
133         to generate a VAT script with proper interface names.
134         :param link_names: list of names of the link that a interface is
135         connected to.
136         :param node: the node topology directory
137         :return: dictionary of interface names that are connected to the given
138         links
139         """
140
141         retval = {}
142         interface_key_tpl = "interface{}"
143         interface_number = 1
144         for link_name in link_names:
145             interface_name = self.get_interface_by_link_name(node, link_name)
146             interface_key = interface_key_tpl.format(str(interface_number))
147             retval[interface_key] = interface_name
148             interface_number += 1
149         return retval
150
151     def get_interface_by_sw_index(self, node, sw_index):
152         """Return interface name of link on node.
153
154         This method returns the interface name asociated with a software index
155         assigned to the interface by vpp for a given node.
156         :param sw_index: sw_index of the link that a interface is connected to.
157         :param node: the node topology dictionary
158         :return: interface name of the interface connected to the given link
159         """
160
161         return self._get_interface_by_key_value(node, "vpp_sw_index", sw_index)
162
163     @staticmethod
164     def convert_mac_to_number_list(mac_address):
165         """Convert mac address string to list of decimal numbers.
166
167         Converts a : separated mac address to decimal number list as used
168         in json interface dump.
169         :param mac_address: string mac address
170         :return: list representation of mac address
171         """
172
173         list_mac = []
174         for num in mac_address.split(":"):
175             list_mac.append(int(num, 16))
176         return list_mac
177
178     def _extract_vpp_interface_by_mac(self, interfaces_list, mac_address):
179         """Returns interface dictionary from interface_list by mac address.
180
181         Extracts interface dictionary from all of the interfaces in interfaces
182         list parsed from json according to mac_address of the interface
183         :param interfaces_list: dictionary of all interfaces parsed from json
184         :param mac_address: string mac address of interface we are looking for
185         :return: interface dictionary from json
186         """
187
188         interface_dict = {}
189         list_mac_address = self.convert_mac_to_number_list(mac_address)
190         logger.trace(list_mac_address.__str__())
191         for interface in interfaces_list:
192             # TODO: create vat json integrity checking and move there
193             if "l2_address" not in interface:
194                 raise KeyError(
195                     "key l2_address not found in interface dict."
196                     "Probably input list is not parsed from correct VAT "
197                     "json output.")
198             if "l2_address_length" not in interface:
199                 raise KeyError(
200                     "key l2_address_length not found in interface "
201                     "dict. Probably input list is not parsed from correct "
202                     "VAT json output.")
203             mac_from_json = interface["l2_address"][:6]
204             if mac_from_json == list_mac_address:
205                 if interface["l2_address_length"] != 6:
206                     raise ValueError("l2_address_length value is not 6.")
207                 interface_dict = interface
208                 break
209         return interface_dict
210
211     def vpp_interface_name_from_json_by_mac(self, json_data, mac_address):
212         """Return vpp interface name string from VAT interface dump json output
213
214         Extracts the name given to an interface by VPP.
215         These interface names differ from what you would see if you
216         used the ipconfig or similar command.
217         Required json data can be obtained by calling :
218         VatExecutor.execute_script_json_out("dump_interfaces.vat", node)
219         :param json_data: string json data from sw_interface_dump VAT command
220         :param mac_address: string containing mac address of interface
221         whose vpp name we wish to discover.
222         :return: string vpp interface name
223         """
224
225         interfaces_list = JsonParser().parse_data(json_data)
226         # TODO: checking if json data is parsed correctly
227         interface_dict = self._extract_vpp_interface_by_mac(interfaces_list,
228                                                             mac_address)
229         interface_name = interface_dict["interface_name"]
230         return interface_name
231
232     def _update_node_interface_data_from_json(self, node, interface_dump_json):
233         """ Update node vpp data in node__DICT from json interface dump.
234
235         This method updates vpp interface names and sw indexexs according to
236         interface mac addresses found in interface_dump_json
237         :param node: node dictionary
238         :param interface_dump_json: json output from dump_interface_list VAT
239         command
240         """
241
242         interface_list = JsonParser().parse_data(interface_dump_json)
243         for ifc in node['interfaces'].values():
244             if 'link' not in ifc:
245                 continue
246             if_mac = ifc['mac_address']
247             interface_dict = self._extract_vpp_interface_by_mac(interface_list,
248                                                                 if_mac)
249             ifc['name'] = interface_dict["interface_name"]
250             ifc['vpp_sw_index'] = interface_dict["sw_if_index"]
251
252     def update_vpp_interface_data_on_node(self, node):
253         """Update vpp generated interface data for a given node in DICT__nodes
254
255         Updates interface names, software index numbers and any other details
256         generated specifically by vpp that are unknown before testcase run.
257         :param node: Node selected from DICT__nodes
258         """
259
260         vat_executor = VatExecutor()
261         vat_executor.execute_script_json_out("dump_interfaces.vat", node)
262         interface_dump_json = vat_executor.get_script_stdout()
263         self._update_node_interface_data_from_json(node,
264                                                    interface_dump_json)
265
266     @staticmethod
267     def update_tg_interface_data_on_node(node):
268         """Update interface name for TG/linux node in DICT__nodes
269
270         :param node: Node selected from DICT__nodes.
271         :type node: dict
272
273         .. note::
274             # for dev in `ls /sys/class/net/`;
275             > do echo "\"`cat /sys/class/net/$dev/address`\": \"$dev\""; done
276             "52:54:00:9f:82:63": "eth0"
277             "52:54:00:77:ae:a9": "eth1"
278             "52:54:00:e1:8a:0f": "eth2"
279             "00:00:00:00:00:00": "lo"
280
281         .. todo:: parse lshw -json instead
282         """
283         # First setup interface driver specified in yaml file
284         InterfaceSetup.tg_set_interfaces_default_driver(node)
285
286         # Get interface names
287         ssh = SSH()
288         ssh.connect(node)
289
290         cmd = 'for dev in `ls /sys/class/net/`; do echo "\\"`cat ' \
291               '/sys/class/net/$dev/address`\\": \\"$dev\\""; done;'
292
293         (ret_code, stdout, _) = ssh.exec_command(cmd)
294         if int(ret_code) != 0:
295             raise Exception('Get interface name and MAC failed')
296         tmp = "{" + stdout.rstrip().replace('\n', ',') + "}"
297         interfaces = JsonParser().parse_data(tmp)
298         for if_k, if_v in node['interfaces'].items():
299             if if_k == 'mgmt':
300                 continue
301             name = interfaces.get(if_v['mac_address'])
302             if name is None:
303                 continue
304             if_v['name'] = name
305
306         # Set udev rules for interfaces
307         InterfaceSetup.tg_set_interfaces_udev_rules(node)
308
309     def update_all_interface_data_on_all_nodes(self, nodes):
310         """ Update interface names on all nodes in DICT__nodes
311
312         :param nodes: Nodes in the topology.
313         :type nodes: dict
314
315         This method updates the topology dictionary by querying interface lists
316         of all nodes mentioned in the topology dictionary.
317         It does this by dumping interface list to json output from all devices
318         using vpe_api_test, and pairing known information from topology
319         (mac address/pci address of interface) to state from VPP.
320         For TG/linux nodes add interface name only.
321         """
322
323         for node_data in nodes.values():
324             if node_data['type'] == NodeType.DUT:
325                 self.update_vpp_interface_data_on_node(node_data)
326             elif node_data['type'] == NodeType.TG:
327                 self.update_tg_interface_data_on_node(node_data)
328
329     @staticmethod
330     def get_interface_sw_index(node, interface):
331         """Get VPP sw_index for the interface.
332
333         :param node: Node to get interface sw_index on.
334         :param interface: Interface name.
335         :type node: dict
336         :type interface: str
337         :return: Return sw_index or None if not found.
338         """
339         for port in node['interfaces'].values():
340             port_name = port.get('name')
341             if port_name is None:
342                 continue
343             if port_name == interface:
344                 return port.get('vpp_sw_index')
345
346         return None
347
348     @staticmethod
349     def get_interface_mac(node, interface):
350         """Get MAC address for the interface.
351
352         :param node: Node to get interface sw_index on.
353         :param interface: Interface name.
354         :type node: dict
355         :type interface: str
356         :return: Return MAC or None if not found.
357         """
358         for port in node['interfaces'].values():
359             port_name = port.get('name')
360             if port_name is None:
361                 continue
362             if port_name == interface:
363                 return port.get('mac_address')
364
365         return None
366
367     @staticmethod
368     def get_adjacent_interface(node, interface_name):
369         """Get interface adjacent to specified interface on local network.
370
371            :param node: Node that contains specified interface.
372            :param interface_name: Interface name.
373            :type node: dict
374            :type interface_name: str
375            :return: Return interface or None if not found.
376            :rtype: dict
377         """
378         link_name = None
379         # get link name where the interface belongs to
380         for _, port_data in node['interfaces'].iteritems():
381             if port_data['name'] == interface_name:
382                 link_name = port_data['link']
383                 break
384
385         if link_name is None:
386             return None
387
388         # find link
389         for _, node_data in DICT__nodes.iteritems():
390             # skip self
391             if node_data['host'] == node['host']:
392                 continue
393             for interface, interface_data \
394                     in node_data['interfaces'].iteritems():
395                 if 'link' not in interface_data:
396                     continue
397                 if interface_data['link'] == link_name:
398                     return node_data['interfaces'][interface]
399
400     @staticmethod
401     def get_interface_pci_addr(node, interface):
402         """Get interface PCI address.
403
404         :param node: Node to get interface PCI address on.
405         :param interface: Interface name.
406         :type node: dict
407         :type interface: str
408         :return: Return PCI address or None if not found.
409         """
410         for port in node['interfaces'].values():
411             if interface == port.get('name'):
412                 return port.get('pci_address')
413         return None
414
415     @staticmethod
416     def get_interface_driver(node, interface):
417         """Get interface driver.
418
419         :param node: Node to get interface driver on.
420         :param interface: Interface name.
421         :type node: dict
422         :type interface: str
423         :return: Return interface driver or None if not found.
424         """
425         for port in node['interfaces'].values():
426             if interface == port.get('name'):
427                 return port.get('driver')
428         return None
429
430     @staticmethod
431     def get_node_link_mac(node, link_name):
432         """Return interface mac address by link name
433
434         :param node: Node to get interface sw_index on
435         :param link_name: link name
436         :type node: dict
437         :type link_name: string
438         :return: mac address string
439         """
440         for port in node['interfaces'].values():
441             if port.get('link') == link_name:
442                 return port.get('mac_address')
443         return None
444
445     @staticmethod
446     def _get_node_active_link_names(node):
447         """Returns list of link names that are other than mgmt links
448
449         :param node: node topology dictionary
450         :return: list of strings that represent link names occupied by the node
451         """
452         interfaces = node['interfaces']
453         link_names = []
454         for interface in interfaces.values():
455             if 'link' in interface:
456                 link_names.append(interface['link'])
457         if len(link_names) == 0:
458             link_names = None
459         return link_names
460
461     @keyword('Get active links connecting "${node1}" and "${node2}"')
462     def get_active_connecting_links(self, node1, node2):
463         """Returns list of link names that connect together node1 and node2
464
465         :param node1: node topology dictionary
466         :param node2: node topology dictionary
467         :return: list of strings that represent connecting link names
468         """
469
470         logger.trace("node1: {}".format(str(node1)))
471         logger.trace("node2: {}".format(str(node2)))
472         node1_links = self._get_node_active_link_names(node1)
473         node2_links = self._get_node_active_link_names(node2)
474         connecting_links = list(set(node1_links).intersection(node2_links))
475
476         return connecting_links
477
478     @keyword('Get first active connecting link between node "${node1}" and '
479              '"${node2}"')
480     def get_first_active_connecting_link(self, node1, node2):
481         """
482
483         :param node1: Connected node
484         :type node1: dict
485         :param node2: Connected node
486         :type node2: dict
487         :return: name of link connecting the two nodes together
488         :raises: RuntimeError
489         """
490
491         connecting_links = self.get_active_connecting_links(node1, node2)
492         if len(connecting_links) == 0:
493             raise RuntimeError("No links connecting the nodes were found")
494         else:
495             return connecting_links[0]
496
497     @keyword('Get egress interfaces on "${node1}" for link with "${node2}"')
498     def get_egress_interfaces_for_nodes(self, node1, node2):
499         """Get egress interfaces on node1 for link with node2.
500
501         :param node1: First node, node to get egress interface on.
502         :param node2: Second node.
503         :type node1: dict
504         :type node2: dict
505         :return: Engress interfaces.
506         :rtype: list
507         """
508         interfaces = []
509         links = self.get_active_connecting_links(node1, node2)
510         if len(links) == 0:
511             raise RuntimeError('No link between nodes')
512         for interface in node1['interfaces'].values():
513             link = interface.get('link')
514             if link is None:
515                 continue
516             if link in links:
517                 continue
518             name = interface.get('name')
519             if name is None:
520                 continue
521             interfaces.append(name)
522         return interfaces
523
524     @keyword('Get first egress interface on "${node1}" for link with '
525              '"${node2}"')
526     def get_first_egress_interface_for_nodes(self, node1, node2):
527         """Get first egress interface on node1 for link with node2.
528
529         :param node1: First node, node to get egress interface on.
530         :param node2: Second node.
531         :type node1: dict
532         :type node2: dict
533         :return: Engress interface.
534         :rtype: str
535         """
536         interfaces = self.get_egress_interfaces_for_nodes(node1, node2)
537         if not interfaces:
538             raise RuntimeError('No engress interface for nodes')
539         return interfaces[0]