Fix pylint warnings in python libraries
[csit.git] / resources / libraries / python / IPv4Setup.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 """IPv4 setup library"""
15
16 from socket import inet_ntoa
17 from struct import pack
18 from abc import ABCMeta, abstractmethod
19
20 from robot.api.deco import keyword
21
22 from resources.libraries.python.ssh import exec_cmd_no_error
23 from resources.libraries.python.Routing import Routing
24 from resources.libraries.python.topology import NodeType, Topology
25 from resources.libraries.python.VatExecutor import VatExecutor
26
27
28 class IPv4Node(object):
29     """Abstract class of a node in a topology."""
30     __metaclass__ = ABCMeta
31
32     def __init__(self, node_info):
33         self.node_info = node_info
34
35     @staticmethod
36     def _get_netmask(prefix_length):
37         """Convert IPv4 network prefix length into IPV4 network mask.
38
39         :param prefix_length: Length of network prefix.
40         :type prefix_length: int
41
42         :return: Network mask.
43         :rtype: str
44         """
45
46         bits = 0xffffffff ^ (1 << 32 - prefix_length) - 1
47         return inet_ntoa(pack('>I', bits))
48
49     @abstractmethod
50     def set_ip(self, interface, address, prefix_length):
51         """Configure IPv4 address on interface.
52
53         :param interface: Interface name.
54         :param address: IPv4 address.
55         :param prefix_length: IPv4 prefix length.
56         :type interface: str
57         :type address: str
58         :type prefix_length: int
59         :return: nothing
60         """
61         pass
62
63     @abstractmethod
64     def set_route(self, network, prefix_length, gateway, interface):
65         """Configure IPv4 route.
66
67         :param network: Network IPv4 address.
68         :param prefix_length: IPv4 prefix length.
69         :param gateway: IPv4 address of the gateway.
70         :param interface: Interface name.
71         :type network: str
72         :type prefix_length: int
73         :type gateway: str
74         :type interface: str
75         :return: nothing
76         """
77         pass
78
79     @abstractmethod
80     def unset_route(self, network, prefix_length, gateway, interface):
81         """Remove specified IPv4 route.
82
83         :param network: Network IPv4 address.
84         :param prefix_length: IPv4 prefix length.
85         :param gateway: IPv4 address of the gateway.
86         :param interface: Interface name.
87         :type network: str
88         :type prefix_length: int
89         :type gateway: str
90         :type interface: str
91         :return: nothing
92         """
93         pass
94
95     @abstractmethod
96     def flush_ip_addresses(self, interface):
97         """Flush all IPv4 addresses from specified interface.
98
99         :param interface: Interface name.
100         :type interface: str
101         :return: nothing
102         """
103         pass
104
105     @abstractmethod
106     def ping(self, destination_address, source_interface):
107         """Send an ICMP request to destination node.
108
109         :param destination_address: Address to send the ICMP request.
110         :param source_interface: Source interface name.
111         :type destination_address: str
112         :type source_interface: str
113         :return: nothing
114         """
115         pass
116
117
118 class Tg(IPv4Node):
119     """Traffic generator node"""
120     def __init__(self, node_info):
121         super(Tg, self).__init__(node_info)
122
123     def _execute(self, cmd):
124         """Executes the specified command on TG using SSH.
125
126         :param cmd: Command to be executed.
127         :type cmd: str
128
129         :return: Content of stdout and stderr returned by command.
130         :rtype: tuple
131         """
132         return exec_cmd_no_error(self.node_info, cmd)
133
134     def _sudo_execute(self, cmd):
135         """Executes the specified command with sudo on TG using SSH.
136
137         :param cmd: Command to be executed.
138         :type cmd: str
139
140         :return: Content of stdout and stderr returned by command.
141         :rtype: tuple
142         """
143         return exec_cmd_no_error(self.node_info, cmd, sudo=True)
144
145     def set_ip(self, interface, address, prefix_length):
146         cmd = 'ip -4 addr flush dev {}'.format(interface)
147         self._sudo_execute(cmd)
148         cmd = 'ip addr add {}/{} dev {}'.format(address, prefix_length,
149                                                 interface)
150         self._sudo_execute(cmd)
151
152     def set_route(self, network, prefix_length, gateway, interface):
153         netmask = self._get_netmask(prefix_length)
154         cmd = 'route add -net {} netmask {} gw {}'.\
155             format(network, netmask, gateway)
156         self._sudo_execute(cmd)
157
158     def unset_route(self, network, prefix_length, gateway, interface):
159         self._sudo_execute('ip route delete {}/{}'.
160                            format(network, prefix_length))
161
162     def arp_ping(self, destination_address, source_interface):
163         """Execute 'arping' command to send one ARP packet from the TG node.
164
165         :param destination_address: Destination IP address for the ARP packet.
166         :param source_interface: Name of an interface to send ARP packet from.
167         :type destination_address: str
168         :type source_interface: str
169         """
170         self._sudo_execute('arping -c 1 -I {} {}'.format(source_interface,
171                                                          destination_address))
172
173     def ping(self, destination_address, source_interface):
174         self._execute('ping -c 1 -w 5 -I {} {}'.format(source_interface,
175                                                        destination_address))
176
177     def flush_ip_addresses(self, interface):
178         self._sudo_execute('ip addr flush dev {}'.format(interface))
179
180
181 class Dut(IPv4Node):
182     """Device under test"""
183     def __init__(self, node_info):
184         super(Dut, self).__init__(node_info)
185
186     def get_sw_if_index(self, interface):
187         """Get sw_if_index of specified interface from current node.
188
189         :param interface: Interface name.
190         :type interface: str
191         :return: sw_if_index of the interface or None.
192         :rtype: int
193         """
194         return Topology().get_interface_sw_index(self.node_info, interface)
195
196     def exec_vat(self, script, **args):
197         """Wrapper for VAT executor.
198
199         :param script: Script to execute.
200         :param args: Parameters to the script.
201         :type script: str
202         :type args: dict
203         :return: nothing
204         """
205         # TODO: check return value
206         VatExecutor.cmd_from_template(self.node_info, script, **args)
207
208     def set_arp(self, iface_key, ip_address, mac_address, vrf=None):
209         """Set entry in ARP cache.
210
211         :param iface_key: Interface key.
212         :param ip_address: IP address.
213         :param mac_address: MAC address.
214         :param vrf: VRF table ID (Optional).
215         :type iface_key: str
216         :type ip_address: str
217         :type mac_address: str
218         :type vrf: int
219         """
220         vrf = "vrf {}".format(vrf) if vrf else ''
221         self.exec_vat('add_ip_neighbor.vat',
222                       sw_if_index=self.get_sw_if_index(iface_key),
223                       ip_address=ip_address, mac_address=mac_address,
224                       vrf=vrf)
225
226     def set_ip(self, interface, address, prefix_length):
227         self.exec_vat('add_ip_address.vat',
228                       sw_if_index=self.get_sw_if_index(interface),
229                       address=address, prefix_length=prefix_length)
230
231     def set_route(self, network, prefix_length, gateway, interface, count=1):
232         Routing.vpp_route_add(self.node_info,
233                               network=network, prefix_len=prefix_length,
234                               gateway=gateway, interface=interface, count=count)
235
236     def unset_route(self, network, prefix_length, gateway, interface):
237         self.exec_vat('del_route.vat', network=network,
238                       prefix_length=prefix_length, gateway=gateway,
239                       sw_if_index=self.get_sw_if_index(interface))
240
241     def arp_ping(self, destination_address, source_interface):
242         """Does nothing."""
243         pass
244
245     def flush_ip_addresses(self, interface):
246         self.exec_vat('flush_ip_addresses.vat',
247                       sw_if_index=self.get_sw_if_index(interface))
248
249     def ping(self, destination_address, source_interface):
250         pass
251
252
253 def get_node(node_info):
254     """Creates a class instance derived from Node based on type.
255
256     :param node_info: Dictionary containing information on nodes in topology.
257     :type node_info: dict
258     :return: Class instance that is derived from Node.
259     """
260     if node_info['type'] == NodeType.TG:
261         return Tg(node_info)
262     elif node_info['type'] == NodeType.DUT:
263         return Dut(node_info)
264     else:
265         raise NotImplementedError('Node type "{}" unsupported!'.
266                                   format(node_info['type']))
267
268
269 class IPv4Setup(object):
270     """IPv4 setup in topology."""
271
272     @staticmethod
273     def vpp_nodes_set_ipv4_addresses(nodes, nodes_addr):
274         """Set IPv4 addresses on all VPP nodes in topology.
275
276         :param nodes: Nodes of the test topology.
277         :param nodes_addr: Available nodes IPv4 addresses.
278         :type nodes: dict
279         :type nodes_addr: dict
280         :return: Affected interfaces as list of (node, interface) tuples.
281         :rtype: list
282         """
283         interfaces = []
284         for net in nodes_addr.values():
285             for port in net['ports'].values():
286                 host = port.get('node')
287                 if host is None:
288                     continue
289                 topo = Topology()
290                 node = topo.get_node_by_hostname(nodes, host)
291                 if node is None:
292                     continue
293                 if node['type'] != NodeType.DUT:
294                     continue
295                 iface_key = topo.get_interface_by_name(node, port['if'])
296                 get_node(node).set_ip(iface_key, port['addr'], net['prefix'])
297                 interfaces.append((node, port['if']))
298
299         return interfaces
300
301     @staticmethod
302     @keyword('Get IPv4 address of node "${node}" interface "${port}" '
303              'from "${nodes_addr}"')
304     def get_ip_addr(node, iface_key, nodes_addr):
305         """Return IPv4 address of the node port.
306
307         :param node: Node in the topology.
308         :param iface_key: Interface key of the node.
309         :param nodes_addr: Nodes IPv4 addresses.
310         :type node: dict
311         :type iface_key: str
312         :type nodes_addr: dict
313         :return: IPv4 address.
314         :rtype: str
315         """
316         interface = Topology.get_interface_name(node, iface_key)
317         for net in nodes_addr.values():
318             for port in net['ports'].values():
319                 host = port.get('node')
320                 dev = port.get('if')
321                 if host == node['host'] and dev == interface:
322                     ip_addr = port.get('addr')
323                     if ip_addr is not None:
324                         return ip_addr
325                     else:
326                         raise Exception(
327                             'Node {n} port {p} IPv4 address is not set'.format(
328                                 n=node['host'], p=interface))
329
330         raise Exception('Node {n} port {p} IPv4 address not found.'.format(
331             n=node['host'], p=interface))
332
333     @staticmethod
334     def setup_arp_on_all_duts(nodes_info, nodes_addr):
335         """For all DUT nodes extract MAC and IP addresses of adjacent
336         interfaces from topology and use them to setup ARP entries.
337
338         :param nodes_info: Dictionary containing information on all nodes
339         in topology.
340         :param nodes_addr: Nodes IPv4 addresses.
341         :type nodes_info: dict
342         :type nodes_addr: dict
343         """
344         for node in nodes_info.values():
345             if node['type'] == NodeType.TG:
346                 continue
347             for iface_key in node['interfaces'].keys():
348                 adj_node, adj_int = Topology.\
349                     get_adjacent_node_and_interface(nodes_info, node, iface_key)
350                 ip_address = IPv4Setup.get_ip_addr(adj_node, adj_int,
351                                                    nodes_addr)
352                 mac_address = Topology.get_interface_mac(adj_node, adj_int)
353                 get_node(node).set_arp(iface_key, ip_address, mac_address)
354
355     @staticmethod
356     def add_arp_on_dut(node, iface_key, ip_address, mac_address, vrf=None):
357         """Set ARP cache entree on DUT node.
358
359         :param node: VPP Node in the topology.
360         :param iface_key: Interface key.
361         :param ip_address: IP address of the interface.
362         :param mac_address: MAC address of the interface.
363         :param vrf: VRF table ID (Optional).
364         :type node: dict
365         :type iface_key: str
366         :type ip_address: str
367         :type mac_address: str
368         :type vrf: int
369         """
370         get_node(node).set_arp(iface_key, ip_address, mac_address, vrf)