New version of RF tests.
[csit.git] / resources / libraries / python / InterfaceSetup.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 """Interface setup library."""
15
16 from ssh import SSH
17
18
19 class InterfaceSetup(object):
20     """Interface setup utilities."""
21
22     __UDEV_IF_RULES_FILE = '/etc/udev/rules.d/10-network.rules'
23
24     def __init__(self):
25         pass
26
27     @staticmethod
28     def tg_set_interface_driver(node, pci_addr, driver):
29         """Set interface driver on the TG node.
30
31         :param node: Node to set interface driver on (must be TG node).
32         :param interface: Interface name.
33         :param driver: Driver name.
34         :type node: dict
35         :type interface: str
36         :type driver: str
37         """
38         old_driver = InterfaceSetup.tg_get_interface_driver(node, pci_addr)
39         if old_driver == driver:
40             return
41
42         ssh = SSH()
43         ssh.connect(node)
44
45         # Unbind from current driver
46         if old_driver is not None:
47             cmd = 'sh -c "echo {0} > /sys/bus/pci/drivers/{1}/unbind"'.format(
48                 pci_addr, old_driver)
49             (ret_code, _, _) = ssh.exec_command_sudo(cmd)
50             if int(ret_code) != 0:
51                 raise Exception("'{0}' failed on '{1}'".format(cmd,
52                                                                node['host']))
53
54         # Bind to the new driver
55         cmd = 'sh -c "echo {0} > /sys/bus/pci/drivers/{1}/bind"'.format(
56             pci_addr, driver)
57         (ret_code, _, _) = ssh.exec_command_sudo(cmd)
58         if int(ret_code) != 0:
59             raise Exception("'{0}' failed on '{1}'".format(cmd, node['host']))
60
61     @staticmethod
62     def tg_get_interface_driver(node, pci_addr):
63         """Get interface driver from the TG node.
64
65         :param node: Node to get interface driver on (must be TG node).
66         :param interface: Interface name.
67         :type node: dict
68         :type interface: str
69         :return: Interface driver or None if not found.
70         :rtype: str
71
72         .. note::
73             # lspci -vmmks 0000:00:05.0
74             Slot:   00:05.0
75             Class:  Ethernet controller
76             Vendor: Red Hat, Inc
77             Device: Virtio network device
78             SVendor:        Red Hat, Inc
79             SDevice:        Device 0001
80             PhySlot:        5
81             Driver: virtio-pci
82         """
83         ssh = SSH()
84         ssh.connect(node)
85
86         cmd = 'lspci -vmmks {0}'.format(pci_addr)
87
88         (ret_code, stdout, _) = ssh.exec_command(cmd)
89         if int(ret_code) != 0:
90             raise Exception("'{0}' failed on '{1}'".format(cmd, node['host']))
91
92         for line in stdout.splitlines():
93             if len(line) == 0:
94                 continue
95             (name, value) = line.split("\t", 1)
96             if name == 'Driver:':
97                 return value
98
99         return None
100
101     @staticmethod
102     def tg_set_interfaces_udev_rules(node):
103         """Set udev rules for interfaces.
104
105         Create udev rules file in /etc/udev/rules.d where are rules for each
106         interface used by TG node, based on MAC interface has specific name.
107         So after unbind and bind again to kernel driver interface has same
108         name as before. This must be called after TG has set name for each
109         port in topology dictionary.
110         udev rule example
111         SUBSYSTEM=="net", ACTION=="add", ATTR{address}=="52:54:00:e1:8a:0f",
112         NAME="eth1"
113
114         :param node: Node to set udev rules on (must be TG node).
115         :type node: dict
116         """
117         ssh = SSH()
118         ssh.connect(node)
119
120         cmd = 'rm -f {0}'.format(InterfaceSetup.__UDEV_IF_RULES_FILE)
121         (ret_code, _, _) = ssh.exec_command_sudo(cmd)
122         if int(ret_code) != 0:
123             raise Exception("'{0}' failed on '{1}'".format(cmd, node['host']))
124
125         for if_k, if_v in node['interfaces'].items():
126             if if_k == 'mgmt':
127                 continue
128             rule = 'SUBSYSTEM==\\"net\\", ACTION==\\"add\\", ATTR{address}' + \
129                 '==\\"' + if_v['mac_address'] + '\\", NAME=\\"' + \
130                 if_v['name'] + '\\"'
131             cmd = 'sh -c "echo \'{0}\' >> {1}"'.format(
132                 rule, InterfaceSetup.__UDEV_IF_RULES_FILE)
133             (ret_code, _, _) = ssh.exec_command_sudo(cmd)
134             if int(ret_code) != 0:
135                 raise Exception("'{0}' failed on '{1}'".format(cmd,
136                                                                node['host']))
137
138         cmd = '/etc/init.d/udev restart'
139         ssh.exec_command_sudo(cmd)
140
141     @staticmethod
142     def tg_set_interfaces_default_driver(node):
143         """Set interfaces default driver specified in topology yaml file.
144
145         :param node: Node to setup interfaces driver on (must be TG node).
146         :type node: dict
147         """
148         for if_k, if_v in node['interfaces'].items():
149             if if_k == 'mgmt':
150                 continue
151             InterfaceSetup.tg_set_interface_driver(node, if_v['pci_address'],
152                                                    if_v['driver'])