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