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