Revert "fix(jobspec): Delete ipsec nfv density tests"
[csit.git] / resources / libraries / python / IPUtil.py
index dc4e8e5..933fa34 100644 (file)
@@ -1,5 +1,5 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
-# Copyright (c) 2021 PANTHEON.tech s.r.o.
+# Copyright (c) 2023 Cisco and/or its affiliates.
+# Copyright (c) 2023 PANTHEON.tech s.r.o.
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
 # You may obtain a copy of the License at:
@@ -13,6 +13,7 @@
 # limitations under the License.
 
 """Common IP utilities library."""
+
 import re
 
 from enum import IntEnum
@@ -26,7 +27,6 @@ from resources.libraries.python.IPAddress import IPAddress
 from resources.libraries.python.PapiExecutor import PapiSocketExecutor
 from resources.libraries.python.ssh import exec_cmd_no_error, exec_cmd
 from resources.libraries.python.topology import Topology
-from resources.libraries.python.VatExecutor import VatTerminal
 from resources.libraries.python.Namespaces import Namespaces
 
 
@@ -94,23 +94,30 @@ class IpDscp(IntEnum):
 class NetworkIncrement(ObjIncrement):
     """
     An iterator object which accepts an IPv4Network or IPv6Network and
-    returns a new network incremented by the increment each time it's
-    iterated or when inc_fmt is called. The increment may be positive,
-    negative or 0 (in which case the network is always the same).
+    returns a new network, its address part incremented by the increment
+    number of network sizes, each time it is iterated or when inc_fmt is called.
+    The increment may be positive, negative or 0
+    (in which case the network is always the same).
+
+    Both initial and subsequent IP address can have host bits set,
+    check the initial value before creating instance if needed.
+    String formatting is configurable via constructor argument.
     """
-    def __init__(self, initial_value, increment):
+    def __init__(self, initial_value, increment=1, format=u"dash"):
         """
-        :param initial_value: The initial network.
+        :param initial_value: The initial network. Can have host bits set.
         :param increment: The current network will be incremented by this
-            amount in each iteration/var_str call.
-        :type initial_value:
-            Union[ipaddress.IPv4Network, ipaddress.IPv6Network].
+            amount of network sizes in each iteration/var_str call.
+        :param format: Type of formatting to use, "dash" or "slash" or "addr".
+        :type initial_value: Union[ipaddress.IPv4Network, ipaddress.IPv6Network]
         :type increment: int
+        :type format: str
         """
         super().__init__(initial_value, increment)
         self._prefix_len = self._value.prefixlen
         host_len = self._value.max_prefixlen - self._prefix_len
         self._net_increment = self._increment * (1 << host_len)
+        self._format = str(format).lower()
 
     def _incr(self):
         """
@@ -120,17 +127,34 @@ class NetworkIncrement(ObjIncrement):
         """
         self._value = ip_network(
             f"{self._value.network_address + self._net_increment}"
-            f"/{self._prefix_len}"
+            f"/{self._prefix_len}", strict=False
         )
 
     def _str_fmt(self):
         """
-        The string representation of the network is
-        '<ip_address_start> - <ip_address_stop>' for the purposes of the
-        'ipsec policy add spd' cli.
+        The string representation of the network depends on format.
+
+        Dash format is '<ip_address_start> - <ip_address_stop>',
+        useful for 'ipsec policy add spd' CLI.
+
+        Slash format is '<ip_address_start>/<prefix_length>',
+        useful for other CLI.
+
+        Addr format is '<ip_address_start>', useful for PAPI.
+
+        :returns: Current value converted to string according to format.
+        :rtype: str
+        :raises RuntimeError: If the format is not supported.
         """
-        return f"{self._value.network_address} - " \
-               f"{self._value.broadcast_address}"
+        if self._format == u"dash":
+            return f"{self._value.network_address} - " \
+                   f"{self._value.broadcast_address}"
+        elif self._format == u"slash":
+            return f"{self._value.network_address}/{self._prefix_len}"
+        elif self._format == u"addr":
+            return f"{self._value.network_address}"
+
+        raise RuntimeError(f"Unsupported format {self._format}")
 
 
 class IPUtil:
@@ -474,7 +498,7 @@ class IPUtil:
         :type ip_addr: str
         :type prefix_length: int
         :type namespace: str
-        :rtype boolean
+        :rtype: boolean
         :raises RuntimeError: Request fails.
         """
         ip_addr_with_prefix = f"{ip_addr}/{prefix_length}"
@@ -626,10 +650,10 @@ class IPUtil:
             vrf: VRF table ID. (int)
             count: number of IP addresses to add starting from network IP (int)
             local: The route is local with same prefix (increment is 1).
-                If None, then is not used. (bool)
+            If None, then is not used. (bool)
             lookup_vrf: VRF table ID for lookup. (int)
-            multipath: Enable multipath routing. (bool)
             weight: Weight value for unequal cost multipath routing. (int)
+            (Multipath value enters at higher level.)
 
         :type node: dict
         :type network: str
@@ -684,68 +708,52 @@ class IPUtil:
         return route
 
     @staticmethod
-    def vpp_route_add(node, network, prefix_len, **kwargs):
-        """Add route to the VPP node.
+    def vpp_route_add(node, network, prefix_len, strict=True, **kwargs):
+        """Add route to the VPP node. Prefer multipath behavior.
 
         :param node: VPP node.
         :param network: Route destination network address.
         :param prefix_len: Route destination network prefix length.
+        :param strict: If true, fail if address has host bits set.
         :param kwargs: Optional key-value arguments:
 
             gateway: Route gateway address. (str)
             interface: Route interface. (str)
             vrf: VRF table ID. (int)
             count: number of IP addresses to add starting from network IP (int)
-            local: The route is local with same prefix (increment is 1).
-                If None, then is not used. (bool)
+            local: The route is local with same prefix (increment is 1 network)
+            If None, then is not used. (bool)
             lookup_vrf: VRF table ID for lookup. (int)
-            multipath: Enable multipath routing. (bool)
+            multipath: Enable multipath routing. (bool) Default: True.
             weight: Weight value for unequal cost multipath routing. (int)
 
         :type node: dict
         :type network: str
         :type prefix_len: int
+        :type strict: bool
         :type kwargs: dict
+        :raises RuntimeError: If the argument combination is not supported.
         """
         count = kwargs.get(u"count", 1)
 
-        if count > 100:
-            gateway = kwargs.get(u"gateway", '')
-            interface = kwargs.get(u"interface", '')
-            vrf = kwargs.get(u"vrf", None)
-            multipath = kwargs.get(u"multipath", False)
-
-            with VatTerminal(node, json_param=False) as vat:
-
-                vat.vat_terminal_exec_cmd_from_template(
-                    u"vpp_route_add.vat",
-                    network=network,
-                    prefix_length=prefix_len,
-                    via=f"via {gateway}" if gateway else u"",
-                    sw_if_index=f"sw_if_index "
-                    f"{InterfaceUtil.get_interface_index(node, interface)}"
-                    if interface else u"",
-                    vrf=f"vrf {vrf}" if vrf else u"",
-                    count=f"count {count}" if count else u"",
-                    multipath=u"multipath" if multipath else u""
-                )
-            return
-
-        net_addr = ip_address(network)
         cmd = u"ip_route_add_del"
         args = dict(
             is_add=True,
-            is_multipath=kwargs.get(u"multipath", False),
+            is_multipath=kwargs.get(u"multipath", True),
             route=None
         )
         err_msg = f"Failed to add route(s) on host {node[u'host']}"
 
-        with PapiSocketExecutor(node) as papi_exec:
-            for i in range(kwargs.get(u"count", 1)):
+        netiter = NetworkIncrement(
+            ip_network(f"{network}/{prefix_len}", strict=strict),
+            format=u"addr"
+        )
+        with PapiSocketExecutor(node, is_async=True) as papi_exec:
+            for i in range(count):
                 args[u"route"] = IPUtil.compose_vpp_route_structure(
-                    node, net_addr + i, prefix_len, **kwargs
+                    node, netiter.inc_fmt(), prefix_len, **kwargs
                 )
-                history = bool(not 1 < i < kwargs.get(u"count", 1))
+                history = bool(not 0 < i < count - 1)
                 papi_exec.add(cmd, history=history, **args)
             papi_exec.get_replies(err_msg)