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