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