aboutsummaryrefslogtreecommitdiffstats
path: root/resources/libraries
diff options
context:
space:
mode:
Diffstat (limited to 'resources/libraries')
-rw-r--r--resources/libraries/python/IPUtil.py6
-rw-r--r--resources/libraries/python/IPsecUtil.py14
-rw-r--r--resources/libraries/python/InterfaceUtil.py4
-rw-r--r--resources/libraries/python/L2Util.py16
-rw-r--r--resources/libraries/python/NATUtil.py12
-rw-r--r--resources/libraries/python/PapiExecutor.py513
-rw-r--r--resources/libraries/python/TestConfig.py27
7 files changed, 418 insertions, 174 deletions
diff --git a/resources/libraries/python/IPUtil.py b/resources/libraries/python/IPUtil.py
index 4a5a413fc8..359bd1dce9 100644
--- a/resources/libraries/python/IPUtil.py
+++ b/resources/libraries/python/IPUtil.py
@@ -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:
@@ -796,7 +796,7 @@ class IPUtil:
ip_network(f"{network}/{prefix_len}", strict=strict),
format=u"addr"
)
- with PapiSocketExecutor(node) as papi_exec:
+ with PapiSocketExecutor(node, is_async=True) as papi_exec:
for i in range(count):
args[u"route"] = IPUtil.compose_vpp_route_structure(
node, netiter.inc_fmt(), prefix_len, **kwargs
diff --git a/resources/libraries/python/IPsecUtil.py b/resources/libraries/python/IPsecUtil.py
index 86bed716d1..d7f2136138 100644
--- a/resources/libraries/python/IPsecUtil.py
+++ b/resources/libraries/python/IPsecUtil.py
@@ -1,5 +1,5 @@
-# Copyright (c) 2022 Cisco and/or its affiliates.
-# Copyright (c) 2022 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:
@@ -585,7 +585,7 @@ class IPsecUtil:
udp_dst_port=4500, # default value in api
)
args = dict(entry=sad_entry)
- with PapiSocketExecutor(node) as papi_exec:
+ with PapiSocketExecutor(node, is_async=True) as papi_exec:
for i in range(n_entries):
args[u"entry"][u"sad_id"] = int(sad_id) + i
args[u"entry"][u"spi"] = int(spi) + i
@@ -689,7 +689,7 @@ class IPsecUtil:
else f"Failed to configure IP addresses and IP routes " \
f"on interface {interface} on host {node[u'host']}"
- with PapiSocketExecutor(node) as papi_exec:
+ with PapiSocketExecutor(node, is_async=True) as papi_exec:
for i in range(n_tunnels):
tunnel_dst_addr = tunnel_dst + i * addr_incr
args1[u"prefix"] = IPUtil.create_prefix_object(
@@ -1409,7 +1409,7 @@ class IPsecUtil:
loop_sw_if_idx = InterfaceUtil.vpp_get_interface_sw_index(
nodes[u"DUT1"], u"loop0"
)
- with PapiSocketExecutor(nodes[u"DUT1"]) as papi_exec:
+ with PapiSocketExecutor(nodes[u"DUT1"], is_async=True) as papi_exec:
# Configure IP addresses on loop0 interface
cmd = u"sw_interface_add_del_address"
args = dict(
@@ -1649,7 +1649,7 @@ class IPsecUtil:
:type spi_d: dict
:type existing_tunnels: int
"""
- with PapiSocketExecutor(nodes[u"DUT2"]) as papi_exec:
+ with PapiSocketExecutor(nodes[u"DUT2"], is_async=True) as papi_exec:
if not existing_tunnels:
# Set IP address on VPP node 2 interface
cmd = u"sw_interface_add_del_address"
@@ -1666,7 +1666,7 @@ class IPsecUtil:
)
err_msg = f"Failed to set IP address on interface {if2_key} " \
f"on host {nodes[u'DUT2'][u'host']}"
- papi_exec.add(cmd, **args).get_reply(err_msg)
+ papi_exec.add(cmd, **args).get_replies(err_msg)
# Configure IPIP tunnel interfaces
cmd = u"ipip_add_tunnel"
ipip_tunnel = dict(
diff --git a/resources/libraries/python/InterfaceUtil.py b/resources/libraries/python/InterfaceUtil.py
index 7578716023..03e0e69d42 100644
--- a/resources/libraries/python/InterfaceUtil.py
+++ b/resources/libraries/python/InterfaceUtil.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2022 Cisco and/or its affiliates.
+# Copyright (c) 2023 Cisco and/or its affiliates.
# 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:
@@ -882,7 +882,7 @@ class InterfaceUtil:
err_msg = f"Failed to set VXLAN bypass on interface " \
f"on host {node[u'host']}"
with PapiSocketExecutor(node) as papi_exec:
- papi_exec.add(cmd, **args).get_replies(err_msg)
+ papi_exec.add(cmd, **args).get_reply(err_msg)
@staticmethod
def vxlan_dump(node, interface=None):
diff --git a/resources/libraries/python/L2Util.py b/resources/libraries/python/L2Util.py
index 0f00787bd4..b951e6257a 100644
--- a/resources/libraries/python/L2Util.py
+++ b/resources/libraries/python/L2Util.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
+# Copyright (c) 2023 Cisco and/or its affiliates.
# 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:
@@ -254,8 +254,10 @@ class L2Util:
f"on host {node[u'host']}"
with PapiSocketExecutor(node) as papi_exec:
- papi_exec.add(cmd1, **args1).add(cmd2, **args2).add(cmd2, **args3)
- papi_exec.get_replies(err_msg)
+ # Cannot use get_replies due to VPP-2203.
+ papi_exec.add(cmd1, **args1).get_reply(err_msg)
+ papi_exec.add(cmd2, **args2).get_reply(err_msg)
+ papi_exec.add(cmd2, **args3).get_reply(err_msg)
@staticmethod
def vpp_setup_bidirectional_cross_connect(node, interface1, interface2):
@@ -293,7 +295,9 @@ class L2Util:
f"on host {node['host']}"
with PapiSocketExecutor(node) as papi_exec:
- papi_exec.add(cmd, **args1).add(cmd, **args2).get_replies(err_msg)
+ # Cannot use get_replies due to VPP-2203.
+ papi_exec.add(cmd, **args1).get_reply(err_msg)
+ papi_exec.add(cmd, **args2).get_reply(err_msg)
@staticmethod
def vpp_setup_bidirectional_l2_patch(node, interface1, interface2):
@@ -331,7 +335,9 @@ class L2Util:
f"on host {node['host']}"
with PapiSocketExecutor(node) as papi_exec:
- papi_exec.add(cmd, **args1).add(cmd, **args2).get_replies(err_msg)
+ # Cannot use get_replies due to VPP-2203.
+ papi_exec.add(cmd, **args1).get_reply(err_msg)
+ papi_exec.add(cmd, **args2).get_reply(err_msg)
@staticmethod
def linux_add_bridge(node, br_name, if_1, if_2, set_up=True):
diff --git a/resources/libraries/python/NATUtil.py b/resources/libraries/python/NATUtil.py
index 5d3d131c80..e5f530ab46 100644
--- a/resources/libraries/python/NATUtil.py
+++ b/resources/libraries/python/NATUtil.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2022 Cisco and/or its affiliates.
+# Copyright (c) 2023 Cisco and/or its affiliates.
# 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:
@@ -182,10 +182,9 @@ class NATUtil:
"""Delete and re-add the NAT range setting."""
with PapiSocketExecutor(node) as papi_exec:
args_in[u"is_add"] = False
- papi_exec.add(cmd, **args_in)
+ papi_exec.add(cmd, **args_in).get_reply(err_msg)
args_in[u"is_add"] = True
- papi_exec.add(cmd, **args_in)
- papi_exec.get_replies(err_msg)
+ papi_exec.add(cmd, **args_in).get_reply(err_msg)
return resetter
@@ -427,10 +426,9 @@ class NATUtil:
"""Delete and re-add the deterministic NAT mapping."""
with PapiSocketExecutor(node) as papi_exec:
args_in[u"is_add"] = False
- papi_exec.add(cmd, **args_in)
+ papi_exec.add(cmd, **args_in).get_reply(err_msg)
args_in[u"is_add"] = True
- papi_exec.add(cmd, **args_in)
- papi_exec.get_replies(err_msg)
+ papi_exec.add(cmd, **args_in).get_reply(err_msg)
return resetter
diff --git a/resources/libraries/python/PapiExecutor.py b/resources/libraries/python/PapiExecutor.py
index d7cae91c71..b0fe6f5b7b 100644
--- a/resources/libraries/python/PapiExecutor.py
+++ b/resources/libraries/python/PapiExecutor.py
@@ -11,19 +11,22 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""Python API executor library."""
+"""Python API executor library.
+
+TODO: Document sync and async handling properly.
+"""
import copy
import glob
import json
+import logging
import shutil
import struct # vpp-papi can raise struct.error
import subprocess
import sys
import tempfile
import time
-from collections import UserDict
-
+from collections import deque, UserDict
from pprint import pformat
from robot.api import logger
@@ -68,47 +71,50 @@ def dictize(obj):
:param obj: Arbitrary object to dictize.
:type obj: object
:returns: Dictized object.
- :rtype: same as obj type or collections.OrderedDict
+ :rtype: same as obj type or collections.UserDict
"""
if not hasattr(obj, "_asdict"):
return obj
overriden = UserDict(obj._asdict())
old_get = overriden.__getitem__
- new_get = lambda self, key: dictize(old_get(self, key))
- overriden.__getitem__ = new_get
+ overriden.__getitem__ = lambda self, key: dictize(old_get(self, key))
return overriden
-class PapiSocketExecutor:
- """Methods for executing VPP Python API commands on forwarded socket.
+def dictize_and_check_retval(obj, err_msg):
+ """Make namedtuple-like object accessible as dict, check retval if exists.
- Previously, we used an implementation with single client instance
- and connection being handled by a resource manager.
- On "with" statement, the instance connected, and disconnected
- on exit from the "with" block.
- This was limiting (no nested with blocks) and mainly it was slow:
- 0.7 seconds per disconnect cycle on Skylake, more than 3 second on Taishan.
+ If the object contains "retval" field, raise when the value is non-zero.
- The currently used implementation caches the connected client instances,
- providing speedup and making "with" blocks unnecessary.
- But with many call sites, "with" blocks are still the main usage pattern.
- Documentation still lists that as the intended pattern.
+ See dictize() for what it means to dictize.
- As a downside, clients need to be explicitly told to disconnect
- before VPP restart.
- There is some amount of retries and disconnects on disconnect
- (so unresponsive VPPs do not breach test much more than needed),
- but it is hard to verify all that works correctly.
- Especially, if Robot crashes, files and ssh processes may leak.
+ :param obj: Arbitrary object to dictize.
+ :param err_msg: The (additional) text for the raised exception.
+ :type obj: object
+ :type err_msg: str
+ :returns: Dictized object.
+ :rtype: same as obj type or collections.UserDict
+ :raises AssertionError: If retval field is present with nonzero value.
+ """
+ ret = dictize(obj)
+ # *_details messages do not contain retval.
+ retval = ret.get("retval", 0)
+ if retval != 0:
+ raise AssertionError(f"{err_msg}\nRetval nonzero in object {ret!r}")
+ return ret
- Delay for accepting socket connection is 10s.
- TODO: Decrease 10s to value that is long enough for creating connection
- and short enough to not affect performance.
+
+class PapiSocketExecutor:
+ """Methods for executing VPP Python API commands on forwarded socket.
The current implementation downloads and parses .api.json files only once
and caches client instances for reuse.
Cleanup metadata is added as additional attributes
- directly to client instances.
+ directly to the client instances.
+
+ The current implementation caches the connected client instances.
+ As a downside, clients need to be explicitly told to disconnect
+ before VPP restart.
The current implementation seems to run into read error occasionally.
Not sure if the error is in Python code on Robot side, ssh forwarding,
@@ -116,14 +122,16 @@ class PapiSocketExecutor:
seems to help, hoping repeated command execution does not lead to surprises.
The reconnection is logged at WARN level, so it is prominently shown
in log.html, so we can see how frequently it happens.
+ There are similar retries cleanups in other places
+ (so unresponsive VPPs do not break test much more than needed),
+ but it is hard to verify all that works correctly.
+ Especially, if Robot crashes, files and ssh processes may leak.
- TODO: Support handling of retval!=0 without try/except in caller.
-
- Note: Use only with "with" statement, e.g.:
+ TODO: Decrease current timeout value when creating connections
+ so broken VPP does not prolong job duration too much
+ while good VPP (almost) never fails to connect.
- cmd = 'show_version'
- with PapiSocketExecutor(node) as papi_exec:
- reply = papi_exec.add(cmd).get_reply(err_msg)
+ TODO: Support handling of retval!=0 without try/except in caller.
This class processes two classes of VPP PAPI methods:
1. Simple request / reply: method='request'.
@@ -133,27 +141,37 @@ class PapiSocketExecutor:
The recommended ways of use are (examples):
- 1. Simple request / reply
+ 1. Simple request / reply. Example with no arguments:
- a. One request with no arguments:
-
- cmd = 'show_version'
+ cmd = "show_version"
with PapiSocketExecutor(node) as papi_exec:
reply = papi_exec.add(cmd).get_reply(err_msg)
- b. Three requests with arguments, the second and the third ones are the same
- but with different arguments.
+ 2. Dump functions:
+ cmd = "sw_interface_rx_placement_dump"
with PapiSocketExecutor(node) as papi_exec:
+ papi_exec.add(cmd, sw_if_index=ifc["vpp_sw_index"])
+ details = papi_exec.get_details(err_msg)
+
+ 3. Multiple requests with one reply each.
+ In this example, there are three requests with arguments,
+ the second and the third ones are the same but with different arguments.
+ This example also showcases method chaining.
+
+ with PapiSocketExecutor(node, is_async=True) as papi_exec:
replies = papi_exec.add(cmd1, **args1).add(cmd2, **args2).\
add(cmd2, **args3).get_replies(err_msg)
- 2. Dump functions
+ The "is_async=True" part in the last example enables "async handling mode",
+ which imposes limitations but gains speed and saves memory.
+ This is different than async mode of VPP PAPI, as the default handling mode
+ also uses async PAPI connections.
- cmd = 'sw_interface_rx_placement_dump'
- with PapiSocketExecutor(node) as papi_exec:
- details = papi_exec.add(cmd, sw_if_index=ifc['vpp_sw_index']).\
- get_details(err_msg)
+ The implementation contains more hidden details, such as
+ support for old VPP PAPI async mode behavior, API CRC checking
+ conditional usage of control ping, and possible susceptibility to VPP-2033.
+ See docstring of methods for more detailed info.
"""
# Class cache for reuse between instances.
@@ -177,16 +195,21 @@ class PapiSocketExecutor:
conn_cache = dict()
"""Mapping from node key to connected client instance."""
- def __init__(self, node, remote_vpp_socket=Constants.SOCKSVR_PATH):
+ def __init__(
+ self, node, remote_vpp_socket=Constants.SOCKSVR_PATH, is_async=False
+ ):
"""Store the given arguments, declare managed variables.
:param node: Node to connect to and forward unix domain socket from.
:param remote_vpp_socket: Path to remote socket to tunnel to.
+ :param is_async: Whether to use async handling.
:type node: dict
:type remote_vpp_socket: str
+ :type is_async: bool
"""
self._node = node
self._remote_vpp_socket = remote_vpp_socket
+ self._is_async = is_async
# The list of PAPI commands to be executed on the node.
self._api_command_list = list()
@@ -201,6 +224,8 @@ class PapiSocketExecutor:
cls = self.__class__
if cls.api_package_path:
return
+ # Pylint suggests to use "with" statement, which we cannot,
+ # do as the dir should stay for multiple ensure_vpp_instance calls.
cls.api_root_dir = tempfile.TemporaryDirectory(dir="/tmp")
root_path = cls.api_root_dir.name
# Pack, copy and unpack Python part of VPP installation from _node.
@@ -208,7 +233,7 @@ class PapiSocketExecutor:
node = self._node
exec_cmd_no_error(node, ["rm", "-rf", "/tmp/papi.txz"])
# Papi python version depends on OS (and time).
- # Python 2.7 or 3.4, site-packages or dist-packages.
+ # Python 3.4 or higher, site-packages or dist-packages.
installed_papi_glob = "/usr/lib/python3*/*-packages/vpp_papi"
# We need to wrap this command in bash, in order to expand globs,
# and as ssh does join, the inner command has to be quoted.
@@ -222,7 +247,7 @@ class PapiSocketExecutor:
"/usr/share/vpp/api",
]
)
- exec_cmd_no_error(node, ["bash", "-c", "'" + inner_cmd + "'"])
+ exec_cmd_no_error(node, ["bash", "-c", f"'{inner_cmd}'"])
scp_node(node, root_path + "/papi.txz", "/tmp/papi.txz", get=True)
run(["tar", "xf", root_path + "/papi.txz", "-C", root_path])
cls.api_json_path = root_path + "/usr/share/vpp/api"
@@ -263,15 +288,19 @@ class PapiSocketExecutor:
vpp_class.apidir = cls.api_json_path
# We need to create instance before removing from sys.path.
+ # Cannot use loglevel parameter, robot.api.logger lacks the support.
vpp_instance = vpp_class(
use_socket=True,
server_address="TBD",
async_thread=False,
+ # Large read timeout was originally there for VPP-1722,
+ # it may still be helping against AVF device creation failures.
read_timeout=14,
logger=FilteredLogger(logger, "INFO"),
)
- # Cannot use loglevel parameter, robot.api.logger lacks support.
- # TODO: Stop overriding read_timeout when VPP-1722 is fixed.
+ # The following is needed to prevent union (e.g. Ip4) debug logging
+ # of VPP part of PAPI from spamming robot logs.
+ logging.getLogger("vpp_papi.serializer").setLevel(logging.INFO)
finally:
if sys.path[-1] == cls.api_package_path:
sys.path.pop()
@@ -343,10 +372,11 @@ class PapiSocketExecutor:
If check_connected, RuntimeError is raised when the client is
not in cache. None is returned if client is not in cache
(and the check is disabled).
+ Successful retrieval from cache is logged only when check_connected.
This hides details of what the node key is.
- :param check_connected: Whether cache miss raises.
+ :param check_connected: Whether cache miss raises (and success logs).
:type check_connected: bool
:returns: Connected client instance, or None if uncached and no check.
:rtype: Optional[vpp_papi.VPPApiClient]
@@ -354,11 +384,9 @@ class PapiSocketExecutor:
"""
key = self.key_for_self()
ret = self.__class__.conn_cache.get(key, None)
-
- if ret is None:
- if check_connected:
+ if check_connected:
+ if ret is None:
raise RuntimeError(f"Client not cached for key: {key}")
- else:
# When reading logs, it is good to see which VPP is accessed.
logger.debug(f"Activated cached PAPI client for key: {key}")
return ret
@@ -380,6 +408,8 @@ class PapiSocketExecutor:
- This socket controls the local ssh process doing the forwarding.
csit_local_vpp_socket
- This is the forwarded socket to talk with remote VPP.
+ csit_deque
+ - Queue for responses.
The attribute names do not start with underscore,
so pylint does not complain about accessing private attribute.
@@ -394,7 +424,7 @@ class PapiSocketExecutor:
if vpp_instance is not None:
return self
# No luck, create and connect a new instance.
- time_enter = time.time()
+ time_enter = time.monotonic()
node = self._node
# Parsing takes longer than connecting, prepare instance before tunnel.
vpp_instance = self.ensure_vpp_instance()
@@ -435,7 +465,7 @@ class PapiSocketExecutor:
ssh_socket,
"-M",
"-L",
- api_socket + ":" + self._remote_vpp_socket,
+ f"{api_socket}:{self._remote_vpp_socket}",
"-p",
str(node["port"]),
"-o",
@@ -446,7 +476,7 @@ class PapiSocketExecutor:
"StrictHostKeyChecking=no",
"-o",
"ExitOnForwardFailure=yes",
- node["username"] + "@" + node["host"],
+ f"{node['username']}@{node['host']}",
"sleep",
"30",
]
@@ -464,19 +494,19 @@ class PapiSocketExecutor:
if password:
# Prepend sshpass command to set password.
ssh_cmd[:0] = ["sshpass", "-p", password]
- time_stop = time.time() + 10.0
+ time_stop = time.monotonic() + 10.0
# subprocess.Popen seems to be the best way to run commands
# on background. Other ways (shell=True with "&" and ssh with -f)
# seem to be too dependent on shell behavior.
# In particular, -f does NOT return values for run().
subprocess.Popen(ssh_cmd)
# Check socket presence on local side.
- while time.time() < time_stop:
+ while time.monotonic() < time_stop:
# It can take a moment for ssh to create the socket file.
ret_code, _ = run(["ls", "-l", api_socket], check=False)
if not ret_code:
break
- time.sleep(0.1)
+ time.sleep(0.01)
else:
raise RuntimeError("Local side socket has not appeared.")
if priv_key:
@@ -485,10 +515,10 @@ class PapiSocketExecutor:
# Everything is ready, set the local socket address and connect.
vpp_instance.transport.server_address = api_socket
# It seems we can get read error even if every preceding check passed.
- # Single retry seems to help.
+ # Single retry seems to help. TODO: Confirm this is still needed.
for _ in range(2):
try:
- vpp_instance.connect_sync("csit_socket")
+ vpp_instance.connect("csit_socket", do_async=True)
except (IOError, struct.error) as err:
logger.warn(f"Got initial connect error {err!r}")
vpp_instance.disconnect()
@@ -496,9 +526,15 @@ class PapiSocketExecutor:
break
else:
raise RuntimeError("Failed to connect to VPP over a socket.")
- logger.trace(
- f"Establishing socket connection took {time.time()-time_enter}s"
- )
+ # Only after rls2302 all relevant VPP builds should have do_async.
+ if hasattr(vpp_instance.transport, "do_async"):
+ deq = deque()
+ vpp_instance.csit_deque = deq
+ vpp_instance.register_event_callback(lambda x, y: deq.append(y))
+ else:
+ vpp_instance.csit_deque = None
+ duration_conn = time.monotonic() - time_enter
+ logger.trace(f"Establishing socket connection took {duration_conn}s.")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
@@ -608,10 +644,8 @@ class PapiSocketExecutor:
"""Add next command to internal command list; return self.
Unless disabled, new entry to papi history is also added at this point.
- The argument name 'csit_papi_command' must be unique enough as it cannot
- be repeated in kwargs.
- The kwargs dict is deep-copied, so it is safe to use the original
- with partial modifications for subsequent commands.
+ The kwargs dict is serialized or deep-copied, so it is safe to use
+ the original with partial modifications for subsequent calls.
Any pending conflicts from .api.json processing are raised.
Then the command name is checked for known CRCs.
@@ -621,6 +655,16 @@ class PapiSocketExecutor:
Each CRC issue is raised only once, so subsequent tests
can raise other issues.
+ With async handling mode, this method also serializes and sends
+ the command, skips CRC check to gain speed, and saves memory
+ by putting a sentinel (instead of deepcopy) to api command list.
+
+ For scale tests, the call sites are responsible to set history values
+ in a way that hints what is done without overwhelming the papi history.
+
+ Note to contributors: Do not rename "csit_papi_command"
+ to anything VPP could possibly use as an API field name.
+
:param csit_papi_command: VPP API command.
:param history: Enable/disable adding command to PAPI command history.
:param kwargs: Optional key-value arguments.
@@ -633,20 +677,39 @@ class PapiSocketExecutor:
"""
self.crc_checker.report_initial_conflicts()
if history:
+ # No need for deepcopy yet, serialization isolates from edits.
PapiHistory.add_to_papi_history(
self._node, csit_papi_command, **kwargs
)
self.crc_checker.check_api_name(csit_papi_command)
- self._api_command_list.append(
- dict(api_name=csit_papi_command, api_args=copy.deepcopy(kwargs))
- )
+ if self._is_async:
+ # Save memory but still count the number of expected replies.
+ self._api_command_list.append(0)
+ api_object = self.get_connected_client(check_connected=False).api
+ func = getattr(api_object, csit_papi_command)
+ # No need for deepcopy yet, serialization isolates from edits.
+ func(**kwargs)
+ else:
+ # No serialization, so deepcopy is needed here.
+ self._api_command_list.append(
+ dict(api_name=csit_papi_command, api_args=copy.deepcopy(kwargs))
+ )
return self
def get_replies(self, err_msg="Failed to get replies."):
- """Get replies from VPP Python API.
+ """Get reply for each command from VPP Python API.
+
+ This method expects one reply per command,
+ and gains performance by reading replies only after
+ sending all commands.
The replies are parsed into dict-like objects,
- "retval" field is guaranteed to be zero on success.
+ "retval" field (if present) is guaranteed to be zero on success.
+
+ Do not use this for messages with variable number of replies,
+ use get_details instead.
+ Do not use for commands trigering VPP-2033,
+ use series of get_reply instead.
:param err_msg: The message used if the PAPI command(s) execution fails.
:type err_msg: str
@@ -654,15 +717,18 @@ class PapiSocketExecutor:
:rtype: list of dict
:raises RuntimeError: If retval is nonzero, parsing or ssh error.
"""
- return self._execute(err_msg=err_msg)
+ if not self._is_async:
+ raise RuntimeError("Sync handling does not suport get_replies.")
+ return self._execute(err_msg=err_msg, do_async=True)
def get_reply(self, err_msg="Failed to get reply."):
- """Get reply from VPP Python API.
+ """Get reply to single command from VPP Python API.
- The reply is parsed into dict-like object,
- "retval" field is guaranteed to be zero on success.
+ This method waits for a single reply (no control ping),
+ thus avoiding bugs like VPP-2033.
- TODO: Discuss exception types to raise, unify with inner methods.
+ The reply is parsed into a dict-like object,
+ "retval" field (if present) is guaranteed to be zero on success.
:param err_msg: The message used if the PAPI command(s) execution fails.
:type err_msg: str
@@ -670,7 +736,9 @@ class PapiSocketExecutor:
:rtype: dict
:raises AssertionError: If retval is nonzero, parsing or ssh error.
"""
- replies = self.get_replies(err_msg=err_msg)
+ if self._is_async:
+ raise RuntimeError("Async handling does not suport get_reply.")
+ replies = self._execute(err_msg=err_msg, do_async=False)
if len(replies) != 1:
raise RuntimeError(f"Expected single reply, got {replies!r}")
return replies[0]
@@ -679,9 +747,8 @@ class PapiSocketExecutor:
"""Get sw_if_index from reply from VPP Python API.
Frequently, the caller is only interested in sw_if_index field
- of the reply, this wrapper makes such call sites shorter.
-
- TODO: Discuss exception types to raise, unify with inner methods.
+ of the reply, this wrapper around get_reply (thus safe against VPP-2033)
+ makes such call sites shorter.
:param err_msg: The message used if the PAPI command(s) execution fails.
:type err_msg: str
@@ -689,12 +756,13 @@ class PapiSocketExecutor:
:rtype: int
:raises AssertionError: If retval is nonzero, parsing or ssh error.
"""
+ if self._is_async:
+ raise RuntimeError("Async handling does not suport get_sw_if_index")
reply = self.get_reply(err_msg=err_msg)
- logger.trace(f"Getting index from {reply!r}")
return reply["sw_if_index"]
def get_details(self, err_msg="Failed to get dump details."):
- """Get dump details from VPP Python API.
+ """Get details (for possibly multiple dumps) from VPP Python API.
The details are parsed into dict-like objects.
The number of details per single dump command can vary,
@@ -703,12 +771,18 @@ class PapiSocketExecutor:
logging everything at once for debugging purposes),
it is recommended to call get_details for each dump (type) separately.
+ This method uses control ping to detect end of replies,
+ so it is not suitable for commands which trigger VPP-2033
+ (but arguably no dump currently triggers it).
+
:param err_msg: The message used if the PAPI command(s) execution fails.
:type err_msg: str
:returns: Details, dict objects with fields due to API without "retval".
:rtype: list of dict
"""
- return self._execute(err_msg)
+ if self._is_async:
+ raise RuntimeError("Async handling does not suport get_details.")
+ return self._execute(err_msg, do_async=False, single_reply=False)
@staticmethod
def run_cli_cmd(
@@ -717,6 +791,7 @@ class PapiSocketExecutor:
"""Run a CLI command as cli_inband, return the "reply" field of reply.
Optionally, log the field value.
+ This is a convenience wrapper around get_reply.
:param node: Node to run command on.
:param cli_cmd: The CLI command to be run on the node.
@@ -749,6 +824,8 @@ class PapiSocketExecutor:
def run_cli_cmd_on_all_sockets(node, cli_cmd, log=True):
"""Run a CLI command as cli_inband, on all sockets in topology file.
+ Just a run_cli_cmd, looping over sockets.
+
:param node: Node to run command on.
:param cli_cmd: The CLI command to be run on the node.
:param log: If True, the response is logged.
@@ -767,6 +844,8 @@ class PapiSocketExecutor:
def dump_and_log(node, cmds):
"""Dump and log requested information, return None.
+ Just a get_details (with logging), looping over commands.
+
:param node: DUT node.
:param cmds: Dump commands to be executed.
:type node: dict
@@ -777,65 +856,230 @@ class PapiSocketExecutor:
dump = papi_exec.add(cmd).get_details()
logger.debug(f"{cmd}:\n{pformat(dump)}")
- def _execute(self, err_msg="Undefined error message", exp_rv=0):
+ @staticmethod
+ def _read_internal(vpp_instance, timeout=None):
+ """Blockingly read within timeout.
+
+ This covers behaviors both before and after 37758.
+ One read attempt is guaranteed even with zero timeout.
+
+ TODO: Simplify after 2302 RCA is done.
+
+ :param vpp_instance: Client instance to read from.
+ :param timeout: How long to wait for reply (or transport default).
+ :type vpp_instance: vpp_papi.VPPApiClient
+ :type timeout: Optional[float]
+ :returns: Message read or None if nothing got read.
+ :rtype: Optional[namedtuple]
+ """
+ timeout = vpp_instance.read_timeout if timeout is None else timeout
+ if vpp_instance.csit_deque is None:
+ return vpp_instance.read_blocking(timeout=timeout)
+ time_stop = time.monotonic() + timeout
+ while 1:
+ try:
+ return vpp_instance.csit_deque.popleft()
+ except IndexError:
+ # We could busy-wait but that seems to starve the reader thread.
+ time.sleep(0.01)
+ if time.monotonic() > time_stop:
+ return None
+
+ @staticmethod
+ def _read(vpp_instance, tries=3):
+ """Blockingly read within timeout, retry on early None.
+
+ For (sometimes) unknown reasons, VPP client in async mode likes
+ to return None occasionally before time runs out.
+ This function retries in that case.
+
+ Most of the time, early None means VPP crashed (see VPP-2033),
+ but is is better to give VPP more chances to respond without failure.
+
+ TODO: Perhaps CSIT now never triggers VPP-2033,
+ so investigate and remove this layer if even more speed is needed.
+
+ :param vpp_instance: Client instance to read from.
+ :param tries: Maximum number of tries to attempt.
+ :type vpp_instance: vpp_papi.VPPApiClient
+ :type tries: int
+ :returns: Message read or None if nothing got read even with retries.
+ :rtype: Optional[namedtuple]
+ """
+ timeout = vpp_instance.read_timeout
+ for _ in range(tries):
+ time_stop = time.monotonic() + 0.9 * timeout
+ reply = PapiSocketExecutor._read_internal(vpp_instance)
+ if reply is None and time.monotonic() < time_stop:
+ logger.trace("Early None. Retry?")
+ continue
+ return reply
+ logger.trace(f"Got {tries} early Nones, probably a real None.")
+ return None
+
+ @staticmethod
+ def _drain(vpp_instance, err_msg, timeout=30.0):
+ """Keep reading with until None or timeout.
+
+ This is needed to mitigate the risk of a state with unread responses
+ (e.g. after non-zero retval in the middle of get_replies)
+ causing failures in everything subsequent (until disconnect).
+
+ The reads are done without any waiting.
+
+ It is possible some responses have not arrived yet,
+ but that is unlikely as Python is usually slower than VPP.
+
+ :param vpp_instance: Client instance to read from.
+ :param err_msg: Error message to use when overstepping timeout.
+ :param timeout: How long to try before giving up.
+ :type vpp_instance: vpp_papi.VPPApiClient
+ :type err_msg: str
+ :type timeout: float
+ :raises RuntimeError: If read keeps returning nonzero after timeout.
+ """
+ time_stop = time.monotonic() + timeout
+ while time.monotonic() < time_stop:
+ if PapiSocketExecutor._read_internal(vpp_instance, 0.0) is None:
+ return
+ raise RuntimeError(f"{err_msg}\nTimed out while draining.")
+
+ def _execute(self, err_msg, do_async, single_reply=True):
"""Turn internal command list into data and execute; return replies.
This method also clears the internal command list.
- IMPORTANT!
- Do not use this method in L1 keywords. Use:
- - get_replies()
- - get_reply()
- - get_sw_if_index()
- - get_details()
-
:param err_msg: The message used if the PAPI command(s) execution fails.
+ :param do_async: If true, assume one reply per command and do not wait
+ for each reply before sending next request.
+ Dump commands (and calls causing VPP-2033) need False.
+ :param single_reply: For sync emulation mode (cannot be False
+ if do_async is True). When false use control ping.
+ When true, wait for a single reply.
:type err_msg: str
- :returns: Papi responses parsed into a dict-like object,
+ :type do_async: bool
+ :type single_reply: bool
+ :returns: Papi replies parsed into a dict-like object,
with fields due to API (possibly including retval).
- :rtype: list of dict
+ :rtype: NoneType or list of dict
:raises RuntimeError: If the replies are not all correct.
"""
- vpp_instance = self.get_connected_client()
local_list = self._api_command_list
# Clear first as execution may fail.
self._api_command_list = list()
- replies = list()
+ if do_async:
+ if not single_reply:
+ raise RuntimeError("Async papi needs one reply per request.")
+ return self._execute_async(local_list, err_msg=err_msg)
+ return self._execute_sync(
+ local_list, err_msg=err_msg, single_reply=single_reply
+ )
+
+ def _execute_sync(self, local_list, err_msg, single_reply):
+ """Execute commands waiting for replies one by one; return replies.
+
+ This implementation either expects a single response per request,
+ or uses control ping to emulate sync PAPI calls.
+ Reliable, but slow. Required for dumps. Needed for calls
+ which trigger VPP-2033.
+
+ CRC checking is done for the replies (requests are checked in .add).
+
+ :param local_list: The list of PAPI commands to be executed on the node.
+ :param err_msg: The message used if the PAPI command(s) execution fails.
+ :param single_reply: When false use control ping.
+ When true, wait for a single reply.
+ :type local_list: list of dict
+ :type err_msg: str
+ :type single_reply: bool
+ :returns: Papi replies parsed into a dict-like object,
+ with fields due to API (possibly including retval).
+ :rtype: List[UserDict]
+ :raises RuntimeError: If the replies are not all correct.
+ """
+ vpp_instance = self.get_connected_client()
+ control_ping_fn = getattr(vpp_instance.api, "control_ping")
+ ret_list = list()
for command in local_list:
api_name = command["api_name"]
papi_fn = getattr(vpp_instance.api, api_name)
+ replies = list()
try:
- try:
- reply = papi_fn(**command["api_args"])
- except (IOError, struct.error) as err:
- # Occasionally an error happens, try reconnect.
- logger.warn(f"Reconnect after error: {err!r}")
- vpp_instance.disconnect()
- # Testing shows immediate reconnect fails.
- time.sleep(1)
- vpp_instance.connect_sync("csit_socket")
- logger.trace("Reconnected.")
- reply = papi_fn(**command["api_args"])
+ # Send the command maybe followed by control ping.
+ main_context = papi_fn(**command["api_args"])
+ if single_reply:
+ replies.append(PapiSocketExecutor._read(vpp_instance))
+ else:
+ ping_context = control_ping_fn()
+ # Receive the replies.
+ while 1:
+ reply = PapiSocketExecutor._read(vpp_instance)
+ if reply is None:
+ raise RuntimeError(
+ f"{err_msg}\nSync PAPI timed out."
+ )
+ if reply.context == ping_context:
+ break
+ if reply.context != main_context:
+ raise RuntimeError(
+ f"{err_msg}\nUnexpected context: {reply!r}"
+ )
+ replies.append(reply)
except (AttributeError, IOError, struct.error) as err:
- raise AssertionError(err_msg) from err
- # *_dump commands return list of objects, convert, ordinary reply.
- if not isinstance(reply, list):
- reply = [reply]
- for item in reply:
- message_name = item.__class__.__name__
- self.crc_checker.check_api_name(message_name)
- dict_item = dictize(item)
- if "retval" in dict_item.keys():
- # *_details messages do not contain retval.
- retval = dict_item["retval"]
- if retval != exp_rv:
- raise AssertionError(
- f"Retval {retval!r} does not match expected"
- f" retval {exp_rv!r} in message {message_name}"
- f" for command {command}."
- )
- replies.append(dict_item)
- return replies
+ # TODO: Add retry if it is still needed.
+ raise AssertionError(f"{err_msg}") from err
+ finally:
+ # Discard any unprocessed replies to avoid secondary failures.
+ PapiSocketExecutor._drain(vpp_instance, err_msg)
+ # Process replies for this command.
+ for reply in replies:
+ self.crc_checker.check_api_name(reply.__class__.__name__)
+ dictized_reply = dictize_and_check_retval(reply, err_msg)
+ ret_list.append(dictized_reply)
+ return ret_list
+
+ def _execute_async(self, local_list, err_msg):
+ """Read, process and return replies.
+
+ The messages were already sent by .add() in this mode,
+ local_list is used just so we know how many replies to read.
+
+ Beware: It is not clear what to do when socket read fails
+ in the middle of async processing.
+
+ The implementation assumes each command results in exactly one reply,
+ there is no reordering in either commands nor replies,
+ and context numbers increase one by one (and are matching for replies).
+
+ To speed processing up, reply CRC values are not checked.
+
+ The current implementation does not limit the number of messages
+ in-flight, we rely on VPP PAPI background thread to move replies
+ from socket to queue fast enough.
+
+ :param local_list: The list of PAPI commands to get replies for.
+ :param err_msg: The message used if the PAPI command(s) execution fails.
+ :type local_list: list
+ :type err_msg: str
+ :returns: Papi replies parsed into a dict-like object, with fields
+ according to API (possibly including retval).
+ :rtype: List[UserDict]
+ :raises RuntimeError: If the replies are not all correct.
+ """
+ vpp_instance = self.get_connected_client()
+ ret_list = list()
+ try:
+ for index, _ in enumerate(local_list):
+ # Blocks up to timeout.
+ reply = PapiSocketExecutor._read(vpp_instance)
+ if reply is None:
+ time_msg = f"PAPI async timeout: idx {index}"
+ raise RuntimeError(f"{err_msg}\n{time_msg}")
+ ret_list.append(dictize_and_check_retval(reply, err_msg))
+ finally:
+ # Discard any unprocessed replies to avoid secondary failures.
+ PapiSocketExecutor._drain(vpp_instance, err_msg)
+ return ret_list
class Disconnector:
@@ -860,8 +1104,7 @@ class Disconnector:
"""
cls = PapiSocketExecutor
# Iterate over copy of entries so deletions do not mess with iterator.
- keys_copy = list(cls.conn_cache.keys())
- for key in keys_copy:
+ for key in list(cls.conn_cache.keys()):
cls.disconnect_by_key(key)
@@ -922,11 +1165,9 @@ class PapiExecutor:
def __enter__(self):
try:
self._ssh.connect(self._node)
- except IOError:
- raise RuntimeError(
- f"Cannot open SSH connection to host {self._node['host']}"
- f" to execute PAPI command(s)"
- )
+ except IOError as err:
+ msg = f"PAPI: Cannot open SSH connection to {self._node['host']}"
+ raise RuntimeError(msg) from err
return self
def __exit__(self, exc_type, exc_val, exc_tb):
diff --git a/resources/libraries/python/TestConfig.py b/resources/libraries/python/TestConfig.py
index 28c740e42e..3a00afbf27 100644
--- a/resources/libraries/python/TestConfig.py
+++ b/resources/libraries/python/TestConfig.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
+# Copyright (c) 2023 Cisco and/or its affiliates.
# 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:
@@ -174,7 +174,7 @@ class TestConfig:
vlan_id=None
)
- with PapiSocketExecutor(node) as papi_exec:
+ with PapiSocketExecutor(node, is_async=True) as papi_exec:
for i in range(0, vxlan_count):
try:
src_ip = src_ip_start + i * ip_step
@@ -198,9 +198,9 @@ class TestConfig:
args2[u"vni"] = int(vni_start) + i
args3[u"vlan_id"] = i + 1
history = bool(not 1 < i < vxlan_count - 1)
- papi_exec.add(cmd1, history=history, **args1).\
- add(cmd2, history=history, **args2).\
- add(cmd3, history=history, **args3)
+ papi_exec.add(cmd1, history=history, **args1)
+ papi_exec.add(cmd2, history=history, **args2)
+ papi_exec.add(cmd3, history=history, **args3)
papi_exec.get_replies()
return vxlan_count
@@ -274,7 +274,7 @@ class TestConfig:
flags=InterfaceStatusFlags.IF_STATUS_API_FLAG_ADMIN_UP.value
)
- with PapiSocketExecutor(node) as papi_exec:
+ with PapiSocketExecutor(node, is_async=True) as papi_exec:
for i in range(0, vxlan_count):
vxlan_subif_key = Topology.add_new_port(node, u"vxlan_tunnel")
vxlan_subif_name = f"vxlan_tunnel{i}"
@@ -310,9 +310,8 @@ class TestConfig:
)
args2[u"sw_if_index"] = vlan_idx
history = bool(not 1 < i < vxlan_count - 1)
- papi_exec.add(cmd, history=history, **args1). \
- add(cmd, history=history, **args2)
- papi_exec.add(cmd, **args1).add(cmd, **args2)
+ papi_exec.add(cmd, history=history, **args1)
+ papi_exec.add(cmd, history=history, **args2)
papi_exec.get_replies()
@staticmethod
@@ -422,7 +421,7 @@ class TestConfig:
enable=1
)
- with PapiSocketExecutor(node) as papi_exec:
+ with PapiSocketExecutor(node, is_async=True) as papi_exec:
for i in range(0, vxlan_count):
args1[u"neighbor"][u"ip_address"] = \
str(dst_ip_start + i * ip_step)
@@ -439,8 +438,8 @@ class TestConfig:
)
args4[u"bd_id"] = int(bd_id_start+i)
history = bool(not 1 < i < vxlan_count - 1)
- papi_exec.add(cmd1, history=history, **args1). \
- add(cmd2, history=history, **args2). \
- add(cmd3, history=history, **args3). \
- add(cmd3, history=history, **args4)
+ papi_exec.add(cmd1, history=history, **args1)
+ papi_exec.add(cmd2, history=history, **args2)
+ papi_exec.add(cmd3, history=history, **args3)
+ papi_exec.add(cmd3, history=history, **args4)
papi_exec.get_replies()