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:
6 # http://www.apache.org/licenses/LICENSE-2.0
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.
14 """Common IP utilities library."""
18 from enum import IntEnum
20 from ipaddress import ip_address
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
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
35 class AddressFamily(IntEnum):
36 """IP address family."""
41 class FibPathType(IntEnum):
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
52 FIB_PATH_TYPE_INTERFACE_RX = 9
53 FIB_PATH_TYPE_CLASSIFY = 10
56 class FibPathFlags(IntEnum):
58 FIB_PATH_FLAG_NONE = 0
59 FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED = 1 # pylint: disable=invalid-name
60 FIB_PATH_FLAG_RESOLVE_VIA_HOST = 2
63 class FibPathNhProto(IntEnum):
64 """FIB path next-hop protocol."""
65 FIB_PATH_NH_PROTO_IP4 = 0
66 FIB_PATH_NH_PROTO_IP6 = 1
67 FIB_PATH_NH_PROTO_MPLS = 2
68 FIB_PATH_NH_PROTO_ETHERNET = 3
69 FIB_PATH_NH_PROTO_BIER = 4
73 """Common IP utilities"""
76 def ip_to_int(ip_str):
77 """Convert IP address from string format (e.g. 10.0.0.1) to integer
78 representation (167772161).
80 :param ip_str: IP address in string representation.
82 :returns: Integer representation of IP address.
85 return int(ip_address(ip_str))
88 def int_to_ip(ip_int):
89 """Convert IP address from integer representation (e.g. 167772161) to
90 string format (10.0.0.1).
92 :param ip_int: IP address in integer representation.
94 :returns: String representation of IP address.
97 return str(ip_address(ip_int))
100 def vpp_get_interface_ip_addresses(node, interface, ip_version):
101 """Get list of IP addresses from an interface on a VPP node.
103 :param node: VPP node.
104 :param interface: Name of an interface on the VPP node.
105 :param ip_version: IP protocol version (ipv4 or ipv6).
108 :type ip_version: str
109 :returns: List of dictionaries, each containing IP address, subnet
110 prefix length and also the subnet mask for ipv4 addresses.
111 Note: A single interface may have multiple IP addresses assigned.
114 sw_if_index = InterfaceUtil.get_interface_index(node, interface)
119 is_ipv6 = 1 if ip_version == u"ipv6" else 0
121 cmd = u"ip_address_dump"
123 sw_if_index=sw_if_index,
126 err_msg = f"Failed to get L2FIB dump on host {node[u'host']}"
128 with PapiSocketExecutor(node) as papi_exec:
129 details = papi_exec.add(cmd, **args).get_details(err_msg)
131 # TODO: CSIT currently looks only whether the list is empty.
132 # Add proper value processing if values become important.
137 def vpp_get_ip_tables(node):
138 """Get dump of all IP FIB tables on a VPP node.
140 :param node: VPP node.
143 PapiSocketExecutor.run_cli_cmd(node, u"show ip fib")
144 PapiSocketExecutor.run_cli_cmd(node, u"show ip fib summary")
145 PapiSocketExecutor.run_cli_cmd(node, u"show ip6 fib")
146 PapiSocketExecutor.run_cli_cmd(node, u"show ip6 fib summary")
149 def vpp_get_ip_tables_prefix(node, address):
150 """Get dump of all IP FIB tables on a VPP node.
152 :param node: VPP node.
153 :param address: IP address.
157 addr = ip_address(address)
158 ip_ver = u"ip6" if addr.version == 6 else u"ip"
160 PapiSocketExecutor.run_cli_cmd(
161 node, f"show {ip_ver} fib {addr}/{addr.max_prefixlen}"
165 def get_interface_vrf_table(node, interface, ip_version='ipv4'):
166 """Get vrf ID for the given interface.
168 :param node: VPP node.
169 :param interface: Name or sw_if_index of a specific interface.
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.
177 sw_if_index = InterfaceUtil.get_interface_index(node, interface)
179 cmd = u"sw_interface_get_table"
181 sw_if_index=sw_if_index,
182 is_ipv6=bool(ip_version == u"ipv6")
184 err_msg = f"Failed to get VRF id assigned to interface {interface}"
186 with PapiSocketExecutor(node) as papi_exec:
187 reply = papi_exec.add(cmd, **args).get_reply(err_msg)
189 return reply[u"vrf_id"]
192 def vpp_ip_source_check_setup(node, if_name):
193 """Setup Reverse Path Forwarding source check on interface.
195 :param node: VPP node.
196 :param if_name: Interface name to setup RPF source check.
200 cmd = u"ip_source_check_interface_add_del"
202 sw_if_index=InterfaceUtil.get_interface_index(node, if_name),
206 err_msg = f"Failed to enable source check on interface {if_name}"
207 with PapiSocketExecutor(node) as papi_exec:
208 papi_exec.add(cmd, **args).get_reply(err_msg)
211 def vpp_ip_probe(node, interface, addr):
212 """Run ip probe on VPP node.
214 :param node: VPP node.
215 :param interface: Interface key or name.
216 :param addr: IPv4/IPv6 address.
221 cmd = u"ip_probe_neighbor"
223 sw_if_index=InterfaceUtil.get_interface_index(node, interface),
226 err_msg = f"VPP ip probe {interface} {addr} failed on {node[u'host']}"
228 with PapiSocketExecutor(node) as papi_exec:
229 papi_exec.add(cmd, **args).get_reply(err_msg)
232 def ip_addresses_should_be_equal(ip1, ip2):
233 """Fails if the given IP addresses are unequal.
235 :param ip1: IPv4 or IPv6 address.
236 :param ip2: IPv4 or IPv6 address.
240 addr1 = ip_address(ip1)
241 addr2 = ip_address(ip2)
244 raise AssertionError(f"IP addresses are not equal: {ip1} != {ip2}")
247 def setup_network_namespace(
248 node, namespace_name, interface_name, ip_addr, prefix):
249 """Setup namespace on given node and attach interface and IP to
250 this namespace. Applicable also on TG node.
252 :param node: VPP node.
253 :param namespace_name: Namespace name.
254 :param interface_name: Interface name.
255 :param ip_addr: IP address of namespace's interface.
256 :param prefix: IP address prefix length.
258 :type namespace_name: str
259 :type interface_name: str
263 cmd = f"ip netns add {namespace_name}"
264 exec_cmd_no_error(node, cmd, sudo=True)
266 cmd = f"ip link set dev {interface_name} up netns {namespace_name}"
267 exec_cmd_no_error(node, cmd, sudo=True)
269 cmd = f"ip netns exec {namespace_name} ip addr add {ip_addr}/{prefix}" \
270 f" dev {interface_name}"
271 exec_cmd_no_error(node, cmd, sudo=True)
274 def linux_enable_forwarding(node, ip_ver=u"ipv4"):
275 """Enable forwarding on a Linux node, e.g. VM.
277 :param node: VPP node.
278 :param ip_ver: IP version, 'ipv4' or 'ipv6'.
282 cmd = f"sysctl -w net.{ip_ver}.ip_forward=1"
283 exec_cmd_no_error(node, cmd, sudo=True)
286 def get_linux_interface_name(node, pci_addr):
287 """Get the interface name.
289 :param node: VPP/TG node.
290 :param pci_addr: PCI address
293 :returns: Interface name
295 :raises RuntimeError: If cannot get the information about interfaces.
298 r"pci@([0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}.[0-9a-f])\s" \
299 r"*([a-zA-Z0-9]*)\s*network"
301 cmd = u"lshw -class network -businfo"
302 ret_code, stdout, stderr = exec_cmd(node, cmd, timeout=30, sudo=True)
305 f"Could not get information about interfaces:\n{stderr}"
308 for line in stdout.splitlines()[2:]:
310 if re.search(regex_intf_info, line).group(1) == pci_addr:
311 return re.search(regex_intf_info, line).group(2)
312 except AttributeError:
317 def set_linux_interface_up(node, interface):
318 """Set the specified interface up.
320 :param node: VPP/TG node.
321 :param interface: Interface in namespace.
324 :raises RuntimeError: If the interface could not be set up.
326 cmd = f"ip link set {interface} up"
327 exec_cmd_no_error(node, cmd, timeout=30, sudo=True)
330 def set_linux_interface_ip(
331 node, interface, ip_addr, prefix, namespace=None):
332 """Set IP address to interface in linux.
334 :param node: VPP/TG node.
335 :param interface: Interface in namespace.
336 :param ip_addr: IP to be set on interface.
337 :param prefix: IP prefix.
338 :param namespace: Execute command in namespace. Optional
344 :raises RuntimeError: IP could not be set.
346 if namespace is not None:
347 cmd = f"ip netns exec {namespace} ip addr add {ip_addr}/{prefix}" \
350 cmd = f"ip addr add {ip_addr}/{prefix} dev {interface}"
352 exec_cmd_no_error(node, cmd, timeout=5, sudo=True)
355 def add_linux_route(node, ip_addr, prefix, gateway, namespace=None):
356 """Add linux route in namespace.
358 :param node: Node where to execute command.
359 :param ip_addr: Route destination IP address.
360 :param prefix: IP prefix.
361 :param namespace: Execute command in namespace. Optional.
362 :param gateway: Gateway address.
369 if namespace is not None:
370 cmd = f"ip netns exec {namespace} ip route add {ip_addr}/{prefix}" \
373 cmd = f"ip route add {ip_addr}/{prefix} via {gateway}"
375 exec_cmd_no_error(node, cmd, sudo=True)
378 def vpp_interface_set_ip_address(
379 node, interface, address, prefix_length=None):
380 """Set IP address to VPP interface.
382 :param node: VPP node.
383 :param interface: Interface name.
384 :param address: IP address.
385 :param prefix_length: Prefix length.
389 :type prefix_length: int
391 ip_addr = ip_address(address)
393 cmd = u"sw_interface_add_del_address"
395 sw_if_index=InterfaceUtil.get_interface_index(node, interface),
398 prefix=IPUtil.create_prefix_object(
400 prefix_length if prefix_length else 128
401 if ip_addr.version == 6 else 32
404 err_msg = f"Failed to add IP address on interface {interface}"
406 with PapiSocketExecutor(node) as papi_exec:
407 papi_exec.add(cmd, **args).get_reply(err_msg)
410 def vpp_add_ip_neighbor(node, iface_key, ip_addr, mac_address):
411 """Add IP neighbor on DUT node.
413 :param node: VPP node.
414 :param iface_key: Interface key.
415 :param ip_addr: IP address of the interface.
416 :param mac_address: MAC address of the interface.
420 :type mac_address: str
422 dst_ip = ip_address(ip_addr)
425 sw_if_index=Topology.get_interface_sw_index(node, iface_key),
427 mac_address=str(mac_address),
428 ip_address=str(dst_ip)
430 cmd = u"ip_neighbor_add_del"
435 err_msg = f"Failed to add IP neighbor on interface {iface_key}"
437 with PapiSocketExecutor(node) as papi_exec:
438 papi_exec.add(cmd, **args).get_reply(err_msg)
441 def union_addr(ip_addr):
442 """Creates union IP address.
444 :param ip_addr: IPv4 or IPv6 address.
445 :type ip_addr: IPv4Address or IPv6Address
446 :returns: Union IP address.
449 return dict(ip6=ip_addr.packed) if ip_addr.version == 6 \
450 else dict(ip4=ip_addr.packed)
453 def create_ip_address_object(ip_addr):
454 """Create IP address object.
456 :param ip_addr: IPv4 or IPv6 address
457 :type ip_addr: IPv4Address or IPv6Address
458 :returns: IP address object.
463 AddressFamily, u"ADDRESS_IP6" if ip_addr.version == 6
466 un=IPUtil.union_addr(ip_addr)
470 def create_prefix_object(ip_addr, addr_len):
471 """Create prefix object.
473 :param ip_addr: IPv4 or IPv6 address.
474 :para, addr_len: Length of IP address.
475 :type ip_addr: IPv4Address or IPv6Address
477 :returns: Prefix object.
480 addr = IPUtil.create_ip_address_object(ip_addr)
488 def compose_vpp_route_structure(node, network, prefix_len, **kwargs):
489 """Create route object for ip_route_add_del api call.
491 :param node: VPP node.
492 :param network: Route destination network address.
493 :param prefix_len: Route destination network prefix length.
494 :param kwargs: Optional key-value arguments:
496 gateway: Route gateway address. (str)
497 interface: Route interface. (str)
498 vrf: VRF table ID. (int)
499 count: number of IP addresses to add starting from network IP (int)
500 local: The route is local with same prefix (increment is 1).
501 If None, then is not used. (bool)
502 lookup_vrf: VRF table ID for lookup. (int)
503 multipath: Enable multipath routing. (bool)
504 weight: Weight value for unequal cost multipath routing. (int)
508 :type prefix_len: int
510 :returns: route parameter basic structure
513 interface = kwargs.get(u"interface", u"")
514 gateway = kwargs.get(u"gateway", u"")
516 net_addr = ip_address(network)
518 prefix = IPUtil.create_prefix_object(net_addr, prefix_len)
522 address=IPUtil.union_addr(ip_address(gateway)) if gateway else 0,
523 via_label=MPLS_LABEL_INVALID,
524 obj_id=Constants.BITWISE_NON_ZERO
527 sw_if_index=InterfaceUtil.get_interface_index(node, interface)
528 if interface else Constants.BITWISE_NON_ZERO,
529 table_id=int(kwargs.get(u"lookup_vrf", 0)),
530 rpf_id=Constants.BITWISE_NON_ZERO,
531 weight=int(kwargs.get(u"weight", 1)),
534 FibPathType, u"FIB_PATH_TYPE_LOCAL"
535 if kwargs.get(u"local", False)
536 else u"FIB_PATH_TYPE_NORMAL"
538 flags=getattr(FibPathFlags, u"FIB_PATH_FLAG_NONE").value,
540 FibPathNhProto, u"FIB_PATH_NH_PROTO_IP6"
541 if net_addr.version == 6
542 else u"FIB_PATH_NH_PROTO_IP4"
546 label_stack=list(0 for _ in range(16))
551 table_id=int(kwargs.get(u"vrf", 0)),
559 def vpp_route_add(node, network, prefix_len, **kwargs):
560 """Add route to the VPP node.
562 :param node: VPP node.
563 :param network: Route destination network address.
564 :param prefix_len: Route destination network prefix length.
565 :param kwargs: Optional key-value arguments:
567 gateway: Route gateway address. (str)
568 interface: Route interface. (str)
569 vrf: VRF table ID. (int)
570 count: number of IP addresses to add starting from network IP (int)
571 local: The route is local with same prefix (increment is 1).
572 If None, then is not used. (bool)
573 lookup_vrf: VRF table ID for lookup. (int)
574 multipath: Enable multipath routing. (bool)
575 weight: Weight value for unequal cost multipath routing. (int)
579 :type prefix_len: int
582 count = kwargs.get(u"count", 1)
585 gateway = kwargs.get(u"gateway", '')
586 interface = kwargs.get(u"interface", '')
587 vrf = kwargs.get(u"vrf", None)
588 multipath = kwargs.get(u"multipath", False)
590 with VatTerminal(node, json_param=False) as vat:
592 vat.vat_terminal_exec_cmd_from_template(
593 u"vpp_route_add.vat",
595 prefix_length=prefix_len,
596 via=f"via {gateway}" if gateway else u"",
597 sw_if_index=f"sw_if_index "
598 f"{InterfaceUtil.get_interface_index(node, interface)}"
599 if interface else u"",
600 vrf=f"vrf {vrf}" if vrf else u"",
601 count=f"count {count}" if count else u"",
602 multipath=u"multipath" if multipath else u""
606 net_addr = ip_address(network)
607 cmd = u"ip_route_add_del"
610 is_multipath=int(kwargs.get(u"multipath", False)),
613 err_msg = f"Failed to add route(s) on host {node[u'host']}"
615 with PapiSocketExecutor(node) as papi_exec:
616 for i in range(kwargs.get(u"count", 1)):
617 args[u"route"] = IPUtil.compose_vpp_route_structure(
618 node, net_addr + i, prefix_len, **kwargs
620 history = bool(not 1 < i < kwargs.get(u"count", 1))
621 papi_exec.add(cmd, history=history, **args)
622 papi_exec.get_replies(err_msg)
625 def flush_ip_addresses(node, interface):
626 """Flush all IP addresses from specified interface.
628 :param node: VPP node.
629 :param interface: Interface name.
633 cmd = u"sw_interface_add_del_address"
635 sw_if_index=InterfaceUtil.get_interface_index(node, interface),
639 err_msg = f"Failed to flush IP address on interface {interface}"
641 with PapiSocketExecutor(node) as papi_exec:
642 papi_exec.add(cmd, **args).get_reply(err_msg)
645 def add_fib_table(node, table_id, ipv6=False):
646 """Create new FIB table according to ID.
648 :param node: Node to add FIB on.
649 :param table_id: FIB table ID.
650 :param ipv6: Is this an IPv6 table
655 cmd = u"ip_table_add_del"
657 table_id=int(table_id),
664 err_msg = f"Failed to add FIB table on host {node[u'host']}"
666 with PapiSocketExecutor(node) as papi_exec:
667 papi_exec.add(cmd, **args).get_reply(err_msg)