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

©2016 FD.io a Linux Foundation Collaborative Project. All Rights Reserved.
Linux Foundation is a registered trademark of The Linux Foundation. Linux is a registered trademark of Linus Torvalds.
Please see our privacy policy and terms of use.