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