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