Honeycomb setup and utils
[csit.git] / resources / libraries / python / InterfaceUtil.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 util library"""
15
16 from time import time, sleep
17 from robot.api import logger
18 from resources.libraries.python.ssh import exec_cmd_no_error
19 from resources.libraries.python.topology import NodeType, Topology
20 from resources.libraries.python.VatExecutor import VatExecutor, VatTerminal
21
22
23 class InterfaceUtil(object):
24     """General utilities for managing interfaces"""
25
26     @staticmethod
27     def set_interface_state(node, interface, state):
28         """Set interface state on a node.
29
30         Function can be used for DUTs as well as for TGs.
31
32         :param node: node where the interface is
33         :param interface: interface name or sw_if_index
34         :param state: one of 'up' or 'down'
35         :type node: dict
36         :type interface: str or int
37         :type state: str
38         :return: nothing
39         """
40         if node['type'] == NodeType.DUT:
41             if state == 'up':
42                 state = 'admin-up'
43             elif state == 'down':
44                 state = 'admin-down'
45             else:
46                 raise ValueError('Unexpected interface state: {}'.format(state))
47
48             if isinstance(interface, basestring):
49                 sw_if_index = Topology.get_interface_sw_index(node, interface)
50             else:
51                 sw_if_index = interface
52
53             VatExecutor.cmd_from_template(node, 'set_if_state.vat',
54                                           sw_if_index=sw_if_index, state=state)
55
56         elif node['type'] == NodeType.TG or node['type'] == NodeType.VM:
57             cmd = 'ip link set {} {}'.format(interface, state)
58             exec_cmd_no_error(node, cmd, sudo=True)
59         else:
60             raise Exception('Node {} has unknown NodeType: "{}"'.
61                             format(node['host'], node['type']))
62
63     @staticmethod
64     def set_interface_ethernet_mtu(node, interface, mtu):
65         """Set Ethernet MTU for specified interface.
66
67         Function can be used only for TGs.
68
69         :param node: node where the interface is
70         :param interface: interface name
71         :param mtu: MTU to set
72         :type node: dict
73         :type interface: str
74         :type mtu: int
75         :return: nothing
76         """
77         if node['type'] == NodeType.DUT:
78             ValueError('Node {}: Setting Ethernet MTU for interface '
79                        'on DUT nodes not supported', node['host'])
80         elif node['type'] == NodeType.TG:
81             cmd = 'ip link set {} mtu {}'.format(interface, mtu)
82             exec_cmd_no_error(node, cmd, sudo=True)
83         else:
84             raise ValueError('Node {} has unknown NodeType: "{}"'.
85                              format(node['host'], node['type']))
86
87     @staticmethod
88     def set_default_ethernet_mtu_on_all_interfaces_on_node(node):
89         """Set default Ethernet MTU on all interfaces on node.
90
91         Function can be used only for TGs.
92
93         :param node: node where to set default MTU
94         :type node: dict
95         :return: nothing
96         """
97         for ifc in node['interfaces'].values():
98             InterfaceUtil.set_interface_ethernet_mtu(node, ifc['name'], 1500)
99
100     @staticmethod
101     def vpp_node_interfaces_ready_wait(node, timeout=10):
102         """Wait until all interfaces with admin-up are in link-up state.
103
104         :param node: Node to wait on.
105         :param timeout: Waiting timeout in seconds (optional, default 10s)
106         :type node: dict
107         :type timeout: int
108         :raises: RuntimeError if the timeout period value has elapsed.
109         """
110         if_ready = False
111         not_ready = []
112         start = time()
113         while not if_ready:
114             out = InterfaceUtil.vpp_get_interface_data(node)
115             if time() - start > timeout:
116                 for interface in out:
117                     if interface.get('admin_up_down') == 1:
118                         if interface.get('link_up_down') != 1:
119                             logger.debug('{0} link-down'.format(
120                                 interface.get('interface_name')))
121                 raise RuntimeError('timeout, not up {0}'.format(not_ready))
122             not_ready = []
123             for interface in out:
124                 if interface.get('admin_up_down') == 1:
125                     if interface.get('link_up_down') != 1:
126                         not_ready.append(interface.get('interface_name'))
127             if not not_ready:
128                 if_ready = True
129             else:
130                 logger.debug('Interfaces still in link-down state: {0}, '
131                              'waiting...'.format(not_ready))
132                 sleep(1)
133
134     @staticmethod
135     def vpp_nodes_interfaces_ready_wait(nodes, timeout=10):
136         """Wait until all interfaces with admin-up are in link-up state for
137         listed nodes.
138
139         :param nodes: List of nodes to wait on.
140         :param timeout: Seconds to wait per node for all interfaces to come up.
141         :type nodes: list
142         :type timeout: int
143         :raises: RuntimeError if the timeout period value has elapsed.
144         """
145         for node in nodes:
146             InterfaceUtil.vpp_node_interfaces_ready_wait(node, timeout)
147
148     @staticmethod
149     def all_vpp_interfaces_ready_wait(nodes, timeout=10):
150         """Wait until all interfaces with admin-up are in link-up state for all
151         nodes in the topology.
152
153         :param nodes: Nodes in the topology.
154         :param timeout: Seconds to wait per node for all interfaces to come up.
155         :type nodes: dict
156         :type timeout: int
157         :raises: RuntimeError if the timeout period value has elapsed.
158         """
159         for node in nodes.values():
160             if node['type'] == NodeType.DUT:
161                 InterfaceUtil.vpp_node_interfaces_ready_wait(node, timeout)
162
163     @staticmethod
164     def vpp_get_interface_data(node, interface=None):
165         """Get all interface data from a VPP node. If a name or
166         sw_interface_index is provided, return only data for the matching
167         interface.
168         :param node: VPP node to get interface data from.
169         :param interface: Numeric index or name string of a specific interface.
170         :type node: dict
171         :type interface: int or str
172         :return: List of dictionaries containing data for each interface, or a
173         single dictionary for the specified interface.
174         :rtype: list or dict
175         """
176         with VatTerminal(node) as vat:
177             response = vat.vat_terminal_exec_cmd_from_template(
178                 "interface_dump.vat")
179
180         data = response[0]
181
182         if interface is not None:
183             if isinstance(interface, basestring):
184                 sw_if_index = Topology.get_interface_sw_index(node, interface)
185             else:
186                 sw_if_index = interface
187
188             for data_if in data:
189                 if data_if["sw_if_index"] == sw_if_index:
190
191                     return data_if
192
193         return data