FIX: IPUtil after vpp api changes
[csit.git] / resources / libraries / python / IPUtil.py
1 # Copyright (c) 2019 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 """Common IP utilities library."""
15
16 import re
17
18 from socket import AF_INET, AF_INET6, inet_pton
19
20 from enum import IntEnum
21 from ipaddress import ip_address
22 from ipaddress import IPv4Network, IPv6Network
23
24 from resources.libraries.python.Constants import Constants
25 from resources.libraries.python.InterfaceUtil import InterfaceUtil
26 from resources.libraries.python.PapiExecutor import PapiExecutor
27 from resources.libraries.python.ssh import exec_cmd_no_error, exec_cmd
28 from resources.libraries.python.topology import Topology
29
30
31 # from vpp/src/vnet/vnet/mpls/mpls_types.h
32 MPLS_IETF_MAX_LABEL = 0xfffff
33 MPLS_LABEL_INVALID = MPLS_IETF_MAX_LABEL + 1
34
35
36 class AddressFamily(IntEnum):
37     """IP address family."""
38     ADDRESS_IP4 = 0
39     ADDRESS_IP6 = 1
40
41
42 class FibPathType(IntEnum):
43     """FIB path types."""
44     FIB_PATH_TYPE_NORMAL = 0
45     FIB_PATH_TYPE_LOCAL = 1
46     FIB_PATH_TYPE_DROP = 2
47     FIB_PATH_TYPE_UDP_ENCAP = 3
48     FIB_PATH_TYPE_BIER_IMP = 4
49     FIB_PATH_TYPE_ICMP_UNREACH = 5
50     FIB_PATH_TYPE_ICMP_PROHIBIT = 6
51     FIB_PATH_TYPE_SOURCE_LOOKUP = 7
52     FIB_PATH_TYPE_DVR = 8
53     FIB_PATH_TYPE_INTERFACE_RX = 9
54     FIB_PATH_TYPE_CLASSIFY = 10
55
56
57 class FibPathFlags(IntEnum):
58     """FIB path flags."""
59     FIB_PATH_FLAG_NONE = 0
60     FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED = 1
61     FIB_PATH_FLAG_RESOLVE_VIA_HOST = 2
62
63
64 class FibPathNhProto(IntEnum):
65     """FIB path next-hop protocol."""
66     FIB_PATH_NH_PROTO_IP4 = 0
67     FIB_PATH_NH_PROTO_IP6 = 1
68     FIB_PATH_NH_PROTO_MPLS = 2
69     FIB_PATH_NH_PROTO_ETHERNET = 3
70     FIB_PATH_NH_PROTO_BIER = 4
71
72
73 class IPUtil(object):
74     """Common IP utilities"""
75
76     @staticmethod
77     def ip_to_int(ip_str):
78         """Convert IP address from string format (e.g. 10.0.0.1) to integer
79         representation (167772161).
80
81         :param ip_str: IP address in string representation.
82         :type ip_str: str
83         :returns: Integer representation of IP address.
84         :rtype: int
85         """
86         return int(ip_address(unicode(ip_str)))
87
88     @staticmethod
89     def int_to_ip(ip_int):
90         """Convert IP address from integer representation (e.g. 167772161) to
91         string format (10.0.0.1).
92
93         :param ip_int: IP address in integer representation.
94         :type ip_int: int
95         :returns: String representation of IP address.
96         :rtype: str
97         """
98         return str(ip_address(ip_int))
99
100     @staticmethod
101     def vpp_get_interface_ip_addresses(node, interface, ip_version):
102         """Get list of IP addresses from an interface on a VPP node.
103
104         :param node: VPP node.
105         :param interface: Name of an interface on the VPP node.
106         :param ip_version: IP protocol version (ipv4 or ipv6).
107         :type node: dict
108         :type interface: str
109         :type ip_version: str
110         :returns: List of dictionaries, each containing IP address, subnet
111             prefix length and also the subnet mask for ipv4 addresses.
112             Note: A single interface may have multiple IP addresses assigned.
113         :rtype: list
114         """
115         sw_if_index = InterfaceUtil.get_interface_index(node, interface)
116
117         data = list()
118         if sw_if_index:
119             is_ipv6 = 1 if ip_version == 'ipv6' else 0
120
121             cmd = 'ip_address_dump'
122             cmd_reply = 'ip_address_details'
123             args = dict(sw_if_index=sw_if_index,
124                         is_ipv6=is_ipv6)
125             err_msg = 'Failed to get L2FIB dump on host {host}'.format(
126                 host=node['host'])
127
128             with PapiExecutor(node) as papi_exec:
129                 papi_resp = papi_exec.add(cmd, **args).get_dump(err_msg)
130
131             for item in papi_resp.reply[0]['api_reply']:
132                 item[cmd_reply]['ip'] = item[cmd_reply]['prefix'].split('/')[0]
133                 item[cmd_reply]['prefix_length'] = int(
134                     item[cmd_reply]['prefix'].split('/')[1])
135                 item[cmd_reply]['is_ipv6'] = is_ipv6
136                 item[cmd_reply]['netmask'] = \
137                     str(IPv6Network(unicode('::/{pl}'.format(
138                         pl=item[cmd_reply]['prefix_length']))).netmask) \
139                     if is_ipv6 \
140                     else str(IPv4Network(unicode('0.0.0.0/{pl}'.format(
141                         pl=item[cmd_reply]['prefix_length']))).netmask)
142                 data.append(item[cmd_reply])
143
144         return data
145
146     @staticmethod
147     def get_interface_vrf_table(node, interface, ip_version='ipv4'):
148         """Get vrf ID for the given interface.
149
150         :param node: VPP node.
151         :param interface: Name or sw_if_index of a specific interface.
152         :type node: dict
153         :param ip_version: IP protocol version (ipv4 or ipv6).
154         :type interface: str or int
155         :type ip_version: str
156         :returns: vrf ID of the specified interface.
157         :rtype: int
158         """
159         sw_if_index = InterfaceUtil.get_interface_index(node, interface)
160
161         is_ipv6 = 1 if ip_version == 'ipv6' else 0
162
163         cmd = 'sw_interface_get_table'
164         args = dict(sw_if_index=sw_if_index,
165                     is_ipv6=is_ipv6)
166         err_msg = 'Failed to get VRF id assigned to interface {ifc}'.format(
167             ifc=interface)
168
169         with PapiExecutor(node) as papi_exec:
170             papi_resp = papi_exec.add(cmd, **args).get_replies(err_msg). \
171                 verify_reply(err_msg=err_msg)
172
173         return papi_resp['vrf_id']
174
175     @staticmethod
176     def vpp_ip_source_check_setup(node, if_name):
177         """Setup Reverse Path Forwarding source check on interface.
178
179         :param node: VPP node.
180         :param if_name: Interface name to setup RPF source check.
181         :type node: dict
182         :type if_name: str
183         """
184         cmd = 'ip_source_check_interface_add_del'
185         args = dict(
186             sw_if_index=InterfaceUtil.get_interface_index(node, if_name),
187             is_add=1,
188             loose=0)
189         err_msg = 'Failed to enable source check on interface {ifc}'.format(
190             ifc=if_name)
191         with PapiExecutor(node) as papi_exec:
192             papi_exec.add(cmd, **args).get_replies(err_msg). \
193                 verify_reply(err_msg=err_msg)
194
195     @staticmethod
196     def vpp_ip_probe(node, interface, addr):
197         """Run ip probe on VPP node.
198
199         :param node: VPP node.
200         :param interface: Interface key or name.
201         :param addr: IPv4/IPv6 address.
202         :type node: dict
203         :type interface: str
204         :type addr: str
205         """
206         cmd = 'ip_probe_neighbor'
207         cmd_reply = 'proxy_arp_intfc_enable_disable_reply'
208         args = dict(
209             sw_if_index=InterfaceUtil.get_interface_index(node, interface),
210             dst=str(addr))
211         err_msg = 'VPP ip probe {dev} {ip} failed on {h}'.format(
212             dev=interface, ip=addr, h=node['host'])
213
214         with PapiExecutor(node) as papi_exec:
215             papi_exec.add(cmd, **args).get_replies(err_msg). \
216                 verify_reply(cmd_reply=cmd_reply, err_msg=err_msg)
217
218     @staticmethod
219     def ip_addresses_should_be_equal(ip1, ip2):
220         """Fails if the given IP addresses are unequal.
221
222         :param ip1: IPv4 or IPv6 address.
223         :param ip2: IPv4 or IPv6 address.
224         :type ip1: str
225         :type ip2: str
226         """
227         addr1 = ip_address(unicode(ip1))
228         addr2 = ip_address(unicode(ip2))
229
230         if addr1 != addr2:
231             raise AssertionError('IP addresses are not equal: {0} != {1}'.
232                                  format(ip1, ip2))
233
234     @staticmethod
235     def setup_network_namespace(node, namespace_name, interface_name,
236                                 ip_addr, prefix):
237         """Setup namespace on given node and attach interface and IP to
238         this namespace. Applicable also on TG node.
239
240         :param node: VPP node.
241         :param namespace_name: Namespace name.
242         :param interface_name: Interface name.
243         :param ip_addr: IP address of namespace's interface.
244         :param prefix: IP address prefix length.
245         :type node: dict
246         :type namespace_name: str
247         :type interface_name: str
248         :type ip_addr: str
249         :type prefix: int
250         """
251         cmd = ('ip netns add {0}'.format(namespace_name))
252         exec_cmd_no_error(node, cmd, sudo=True)
253
254         cmd = ('ip link set dev {0} up netns {1}'.format(interface_name,
255                                                          namespace_name))
256         exec_cmd_no_error(node, cmd, sudo=True)
257
258         cmd = ('ip netns exec {0} ip addr add {1}/{2} dev {3}'.format(
259             namespace_name, ip_addr, prefix, interface_name))
260         exec_cmd_no_error(node, cmd, sudo=True)
261
262     @staticmethod
263     def linux_enable_forwarding(node, ip_ver='ipv4'):
264         """Enable forwarding on a Linux node, e.g. VM.
265
266         :param node: VPP node.
267         :param ip_ver: IP version, 'ipv4' or 'ipv6'.
268         :type node: dict
269         :type ip_ver: str
270         """
271         cmd = 'sysctl -w net.{0}.ip_forward=1'.format(ip_ver)
272         exec_cmd_no_error(node, cmd, sudo=True)
273
274     @staticmethod
275     def get_linux_interface_name(node, pci_addr):
276         """Get the interface name.
277
278         :param node: VPP/TG node.
279         :param pci_addr: PCI address
280         :type node: dict
281         :type pci_addr: str
282         :returns: Interface name
283         :rtype: str
284         :raises RuntimeError: If cannot get the information about interfaces.
285         """
286         regex_intf_info = r"pci@" \
287                           r"([0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}.[0-9a-f])\s*" \
288                           r"([a-zA-Z0-9]*)\s*network"
289
290         cmd = "lshw -class network -businfo"
291         ret_code, stdout, stderr = exec_cmd(node, cmd, timeout=30, sudo=True)
292         if ret_code != 0:
293             raise RuntimeError('Could not get information about interfaces:\n'
294                                '{err}'.format(err=stderr))
295
296         for line in stdout.splitlines()[2:]:
297             try:
298                 if re.search(regex_intf_info, line).group(1) == pci_addr:
299                     return re.search(regex_intf_info, line).group(2)
300             except AttributeError:
301                 continue
302         return None
303
304     @staticmethod
305     def set_linux_interface_up(node, interface):
306         """Set the specified interface up.
307
308         :param node: VPP/TG node.
309         :param interface: Interface in namespace.
310         :type node: dict
311         :type interface: str
312         :raises RuntimeError: If the interface could not be set up.
313         """
314         cmd = "ip link set {0} up".format(interface)
315         exec_cmd_no_error(node, cmd, timeout=30, sudo=True)
316
317     @staticmethod
318     def set_linux_interface_ip(node, interface, ip_addr, prefix,
319                                namespace=None):
320         """Set IP address to interface in linux.
321
322         :param node: VPP/TG node.
323         :param interface: Interface in namespace.
324         :param ip_addr: IP to be set on interface.
325         :param prefix: IP prefix.
326         :param namespace: Execute command in namespace. Optional
327         :type node: dict
328         :type interface: str
329         :type ip_addr: str
330         :type prefix: int
331         :type namespace: str
332         :raises RuntimeError: IP could not be set.
333         """
334         if namespace is not None:
335             cmd = 'ip netns exec {ns} ip addr add {ip}/{p} dev {dev}'.format(
336                 ns=namespace, ip=ip_addr, p=prefix, dev=interface)
337         else:
338             cmd = 'ip addr add {ip}/{p} dev {dev}'.format(
339                 ip=ip_addr, p=prefix, dev=interface)
340
341         exec_cmd_no_error(node, cmd, timeout=5, sudo=True)
342
343     @staticmethod
344     def add_linux_route(node, ip_addr, prefix, gateway, namespace=None):
345         """Add linux route in namespace.
346
347         :param node: Node where to execute command.
348         :param ip_addr: Route destination IP address.
349         :param prefix: IP prefix.
350         :param namespace: Execute command in namespace. Optional.
351         :param gateway: Gateway address.
352         :type node: dict
353         :type ip_addr: str
354         :type prefix: int
355         :type gateway: str
356         :type namespace: str
357         """
358         if namespace is not None:
359             cmd = 'ip netns exec {} ip route add {}/{} via {}'.format(
360                 namespace, ip_addr, prefix, gateway)
361         else:
362             cmd = 'ip route add {}/{} via {}'.format(ip_addr, prefix, gateway)
363         exec_cmd_no_error(node, cmd, sudo=True)
364
365     @staticmethod
366     def vpp_interface_set_ip_address(node, interface, address,
367                                      prefix_length=None):
368         """Set IP address to VPP interface.
369
370         :param node: VPP node.
371         :param interface: Interface name.
372         :param address: IP address.
373         :param prefix_length: Prefix length.
374         :type node: dict
375         :type interface: str
376         :type address: str
377         :type prefix_length: int
378         """
379         ip_addr = ip_address(unicode(address))
380
381         cmd = 'sw_interface_add_del_address'
382         args = dict(
383             sw_if_index=InterfaceUtil.get_interface_index(node, interface),
384             is_add=1,
385             is_ipv6=1 if ip_addr.version == 6 else 0,
386             del_all=0,
387             address_length=int(prefix_length) if prefix_length else 128
388             if ip_addr.version == 6 else 32,
389             address=inet_pton(
390                 AF_INET6 if ip_addr.version == 6 else AF_INET, str(ip_addr)))
391         err_msg = 'Failed to add IP address on interface {ifc}'.format(
392             ifc=interface)
393         with PapiExecutor(node) as papi_exec:
394             papi_exec.add(cmd, **args).get_replies(err_msg). \
395                 verify_reply(err_msg=err_msg)
396
397     @staticmethod
398     def vpp_add_ip_neighbor(node, iface_key, ip_addr, mac_address):
399         """Add IP neighbor on DUT node.
400
401         :param node: VPP node.
402         :param iface_key: Interface key.
403         :param ip_addr: IP address of the interface.
404         :param mac_address: MAC address of the interface.
405         :type node: dict
406         :type iface_key: str
407         :type ip_addr: str
408         :type mac_address: str
409         """
410         dst_ip = ip_address(unicode(ip_addr))
411
412         neighbor = dict(
413             sw_if_index=Topology.get_interface_sw_index(node, iface_key),
414             flags=0,
415             mac_address=str(mac_address),
416             ip_address=str(dst_ip))
417         cmd = 'ip_neighbor_add_del'
418         args = dict(
419             is_add=1,
420             neighbor=neighbor)
421         err_msg = 'Failed to add IP neighbor on interface {ifc}'.format(
422             ifc=iface_key)
423         with PapiExecutor(node) as papi_exec:
424             papi_exec.add(cmd, **args).get_replies(err_msg). \
425                 verify_reply(err_msg=err_msg)
426
427     @staticmethod
428     def vpp_route_add(node, network, prefix_len, **kwargs):
429         """Add route to the VPP node.
430
431         :param node: VPP node.
432         :param network: Route destination network address.
433         :param prefix_len: Route destination network prefix length.
434         :param kwargs: Optional key-value arguments:
435
436             gateway: Route gateway address. (str)
437             interface: Route interface. (str)
438             vrf: VRF table ID. (int)
439             count: number of IP addresses to add starting from network IP (int)
440             local: The route is local with same prefix (increment is 1).
441                 If None, then is not used. (bool)
442             lookup_vrf: VRF table ID for lookup. (int)
443             multipath: Enable multipath routing. (bool)
444             weight: Weight value for unequal cost multipath routing. (int)
445
446         :type node: dict
447         :type network: str
448         :type prefix_len: int
449         :type kwargs: dict
450         """
451         interface = kwargs.get('interface', '')
452         gateway = kwargs.get('gateway', '')
453
454         net_addr = ip_address(unicode(network))
455
456         def union_addr(ip_addr):
457             """Creates union IP address.
458
459             :param ip_addr: IPv4 or IPv6 address.
460             :type ip_addr: IPv4Address or IPv6Address
461             :returns: Union IP address.
462             :rtype: dict
463             """
464             return dict(ip6=inet_pton(AF_INET6, str(ip_addr))) \
465                 if ip_addr.version == 6 \
466                 else dict(ip4=inet_pton(AF_INET, str(ip_addr)))
467
468         addr = dict(
469             af=getattr(
470                 AddressFamily, 'ADDRESS_IP6' if net_addr.version == 6
471                 else 'ADDRESS_IP4').value)
472         prefix = dict(address_length=int(prefix_len))
473
474         paths = list()
475         n_hop = dict(
476             address=union_addr(ip_address(unicode(gateway))) if gateway else 0,
477             via_label=MPLS_LABEL_INVALID,
478             obj_id=Constants.BITWISE_NON_ZERO)
479         path = dict(
480             sw_if_index=InterfaceUtil.get_interface_index(node, interface)
481             if interface else Constants.BITWISE_NON_ZERO,
482             table_id=int(kwargs.get('lookup_vrf', 0)),
483             rpf_id=Constants.BITWISE_NON_ZERO,
484             weight=int(kwargs.get('weight', 1)),
485             preference=1,
486             type=getattr(
487                 FibPathType, 'FIB_PATH_TYPE_LOCAL'
488                 if kwargs.get('local', False)
489                 else 'FIB_PATH_TYPE_NORMAL').value,
490             flags=getattr(FibPathFlags, 'FIB_PATH_FLAG_NONE').value,
491             proto=getattr(
492                 FibPathNhProto, 'FIB_PATH_NH_PROTO_IP6'
493                 if net_addr.version == 6
494                 else 'FIB_PATH_NH_PROTO_IP4').value,
495             nh=n_hop,
496             n_labels=0,
497             label_stack=list(0 for _ in range(16)))
498         paths.append(path)
499
500         route = dict(
501             table_id=int(kwargs.get('vrf', 0)),
502             n_paths=len(paths),
503             paths=paths)
504         cmd = 'ip_route_add_del'
505         args = dict(
506             is_add=1,
507             is_multipath=int(kwargs.get('multipath', False)))
508
509         err_msg = 'Failed to add route(s) on host {host}'.format(
510             host=node['host'])
511         with PapiExecutor(node) as papi_exec:
512             for i in xrange(kwargs.get('count', 1)):
513                 addr['un'] = union_addr(net_addr + i)
514                 prefix['address'] = addr
515                 route['prefix'] = prefix
516                 history = False if 1 < i < kwargs.get('count', 1) else True
517                 papi_exec.add(cmd, history=history, route=route, **args)
518                 if i > 0 and i % Constants.PAPI_MAX_API_BULK == 0:
519                     papi_exec.get_replies(err_msg).verify_replies(
520                         err_msg=err_msg)
521             papi_exec.get_replies(err_msg).verify_replies(err_msg=err_msg)
522
523     @staticmethod
524     def flush_ip_addresses(node, interface):
525         """Flush all IP addresses from specified interface.
526
527         :param node: VPP node.
528         :param interface: Interface name.
529         :type node: dict
530         :type interface: str
531         """
532         cmd = 'sw_interface_add_del_address'
533         args = dict(
534             sw_if_index=InterfaceUtil.get_interface_index(node, interface),
535             del_all=1)
536         err_msg = 'Failed to flush IP address on interface {ifc}'.format(
537             ifc=interface)
538         with PapiExecutor(node) as papi_exec:
539             papi_exec.add(cmd, **args).get_replies(err_msg). \
540                 verify_reply(err_msg=err_msg)
541
542     @staticmethod
543     def add_fib_table(node, table_id, ipv6=False):
544         """Create new FIB table according to ID.
545
546         :param node: Node to add FIB on.
547         :param table_id: FIB table ID.
548         :param ipv6: Is this an IPv6 table
549         :type node: dict
550         :type table_id: int
551         :type ipv6: bool
552         """
553         cmd = 'ip_table_add_del'
554         table = dict(
555             table_id=int(table_id),
556             is_ip6=int(ipv6))
557         args = dict(
558             table=table,
559             is_add=1)
560         err_msg = 'Failed to add FIB table on host {host}'.format(
561             host=node['host'])
562         with PapiExecutor(node) as papi_exec:
563             papi_exec.add(cmd, **args).get_replies(err_msg). \
564                 verify_reply(err_msg=err_msg)