HC Test: update routing test keyword due to namespace changes
[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):
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         :type iface_key: str
212         :type ip_address: str
213         :type mac_address: str
214         """
215         self.exec_vat('add_ip_neighbor.vat',
216                       sw_if_index=self.get_sw_if_index(iface_key),
217                       ip_address=ip_address, mac_address=mac_address)
218
219     def set_ip(self, interface, address, prefix_length):
220         self.exec_vat('add_ip_address.vat',
221                       sw_if_index=self.get_sw_if_index(interface),
222                       address=address, prefix_length=prefix_length)
223
224     def set_route(self, network, prefix_length, gateway, interface, count=1):
225         Routing.vpp_route_add(self.node_info,
226                               network=network, prefix_len=prefix_length,
227                               gateway=gateway, interface=interface, count=count)
228
229     def unset_route(self, network, prefix_length, gateway, interface):
230         self.exec_vat('del_route.vat', network=network,
231                       prefix_length=prefix_length, gateway=gateway,
232                       sw_if_index=self.get_sw_if_index(interface))
233
234     def arp_ping(self, destination_address, source_interface):
235         """Does nothing."""
236         pass
237
238     def flush_ip_addresses(self, interface):
239         self.exec_vat('flush_ip_addresses.vat',
240                       sw_if_index=self.get_sw_if_index(interface))
241
242     def ping(self, destination_address, source_interface):
243         pass
244
245
246 def get_node(node_info):
247     """Creates a class instance derived from Node based on type.
248
249     :param node_info: Dictionary containing information on nodes in topology.
250     :type node_info: dict
251     :returns: Class instance that is derived from Node.
252     """
253     if node_info['type'] == NodeType.TG:
254         return Tg(node_info)
255     elif node_info['type'] == NodeType.DUT:
256         return Dut(node_info)
257     else:
258         raise NotImplementedError('Node type "{}" unsupported!'.
259                                   format(node_info['type']))
260
261
262 class IPv4Setup(object):
263     """IPv4 setup in topology."""
264
265     @staticmethod
266     def vpp_nodes_set_ipv4_addresses(nodes, nodes_addr):
267         """Set IPv4 addresses on all VPP nodes in topology.
268
269         :param nodes: Nodes of the test topology.
270         :param nodes_addr: Available nodes IPv4 addresses.
271         :type nodes: dict
272         :type nodes_addr: dict
273         :returns: Affected interfaces as list of (node, interface) tuples.
274         :rtype: list
275         """
276         interfaces = []
277         for net in nodes_addr.values():
278             for port in net['ports'].values():
279                 host = port.get('node')
280                 if host is None:
281                     continue
282                 topo = Topology()
283                 node = topo.get_node_by_hostname(nodes, host)
284                 if node is None:
285                     continue
286                 if node['type'] != NodeType.DUT:
287                     continue
288                 iface_key = topo.get_interface_by_name(node, port['if'])
289                 get_node(node).set_ip(iface_key, port['addr'], net['prefix'])
290                 interfaces.append((node, port['if']))
291
292         return interfaces
293
294     @staticmethod
295     @keyword('Get IPv4 address of node "${node}" interface "${port}" '
296              'from "${nodes_addr}"')
297     def get_ip_addr(node, iface_key, nodes_addr):
298         """Return IPv4 address of the node port.
299
300         :param node: Node in the topology.
301         :param iface_key: Interface key of the node.
302         :param nodes_addr: Nodes IPv4 addresses.
303         :type node: dict
304         :type iface_key: str
305         :type nodes_addr: dict
306         :returns: IPv4 address.
307         :rtype: str
308         """
309         interface = Topology.get_interface_name(node, iface_key)
310         for net in nodes_addr.values():
311             for port in net['ports'].values():
312                 host = port.get('node')
313                 dev = port.get('if')
314                 if host == node['host'] and dev == interface:
315                     ip_addr = port.get('addr')
316                     if ip_addr is not None:
317                         return ip_addr
318                     else:
319                         raise Exception(
320                             'Node {n} port {p} IPv4 address is not set'.format(
321                                 n=node['host'], p=interface))
322
323         raise Exception('Node {n} port {p} IPv4 address not found.'.format(
324             n=node['host'], p=interface))
325
326     @staticmethod
327     def setup_arp_on_all_duts(nodes_info, nodes_addr):
328         """For all DUT nodes extract MAC and IP addresses of adjacent
329         interfaces from topology and use them to setup ARP entries.
330
331         :param nodes_info: Dictionary containing information on all nodes
332         in topology.
333         :param nodes_addr: Nodes IPv4 addresses.
334         :type nodes_info: dict
335         :type nodes_addr: dict
336         """
337         for node in nodes_info.values():
338             if node['type'] == NodeType.TG:
339                 continue
340             for iface_key in node['interfaces'].keys():
341                 adj_node, adj_int = Topology.\
342                     get_adjacent_node_and_interface(nodes_info, node, iface_key)
343                 ip_address = IPv4Setup.get_ip_addr(adj_node, adj_int,
344                                                    nodes_addr)
345                 mac_address = Topology.get_interface_mac(adj_node, adj_int)
346                 get_node(node).set_arp(iface_key, ip_address, mac_address)
347
348     @staticmethod
349     def add_arp_on_dut(node, iface_key, ip_address, mac_address):
350         """Set ARP cache entree on DUT node.
351
352         :param node: VPP Node in the topology.
353         :param iface_key: Interface key.
354         :param ip_address: IP address of the interface.
355         :param mac_address: MAC address of the interface.
356         :type node: dict
357         :type iface_key: str
358         :type ip_address: str
359         :type mac_address: str
360         """
361         get_node(node).set_arp(iface_key, ip_address, mac_address)