+ If the directory is still there, do not copy again.
+ If copying, also initialize CRC checker (this also performs
+ static checks), and remember PAPI package path.
+ Do not add that to PATH yet.
+ """
+ cls = self.__class__
+ if cls.api_package_path:
+ return
+ cls.api_root_dir = tempfile.TemporaryDirectory(dir=u"/tmp")
+ root_path = cls.api_root_dir.name
+ # Pack, copy and unpack Python part of VPP installation from _node.
+ # TODO: Use rsync or recursive version of ssh.scp_node instead?
+ node = self._node
+ exec_cmd_no_error(node, [u"rm", u"-rf", u"/tmp/papi.txz"])
+ # Papi python version depends on OS (and time).
+ # Python 2.7 or 3.4, site-packages or dist-packages.
+ installed_papi_glob = u"/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.
+ inner_cmd = u" ".join([
+ u"tar", u"cJf", u"/tmp/papi.txz", u"--exclude=*.pyc",
+ installed_papi_glob, u"/usr/share/vpp/api"
+ ])
+ exec_cmd_no_error(node, [u"bash", u"-c", u"'" + inner_cmd + u"'"])
+ scp_node(node, root_path + u"/papi.txz", u"/tmp/papi.txz", get=True)
+ run([u"tar", u"xf", root_path + u"/papi.txz", u"-C", root_path])
+ cls.api_json_path = root_path + u"/usr/share/vpp/api"
+ # Perform initial checks before .api.json files are gone,
+ # by creating the checker instance.
+ cls.crc_checker = VppApiCrcChecker(cls.api_json_path)
+ # When present locally, we finally can find the installation path.
+ cls.api_package_path = glob.glob(root_path + installed_papi_glob)[0]
+ # Package path has to be one level above the vpp_papi directory.
+ cls.api_package_path = cls.api_package_path.rsplit(u"/", 1)[0]
+
+ def ensure_vpp_instance(self):
+ """Create or reuse a closed client instance, return it.
+
+ The instance is initialized for unix domain socket access,
+ it has initialized all the bindings, it is removed from the internal
+ list of disconnected instances, but it is not connected
+ (to a local socket) yet.
+
+ :returns: VPP client instance ready for connect.
+ :rtype: vpp_papi.VPPApiClient
+ """
+ self.ensure_api_dirs()
+ cls = self.__class__
+ if cls.reusable_vpp_client_list:
+ # Reuse in LIFO fashion.
+ *cls.reusable_vpp_client_list, ret = cls.reusable_vpp_client_list
+ return ret
+ # Creating an instance leads to dynamic imports from VPP PAPI code,
+ # so the package directory has to be present until the instance.
+ # But it is simpler to keep the package dir around.
+ try:
+ sys.path.append(cls.api_package_path)
+ # TODO: Pylint says import-outside-toplevel and import-error.
+ # It is right, we should refactor the code and move initialization
+ # of package outside.
+ from vpp_papi.vpp_papi import VPPApiClient as vpp_class
+ vpp_class.apidir = cls.api_json_path
+ # We need to create instance before removing from sys.path.
+ vpp_instance = vpp_class(
+ use_socket=True, server_address=u"TBD", async_thread=False,
+ read_timeout=14, logger=FilteredLogger(logger, u"INFO")
+ )
+ # Cannot use loglevel parameter, robot.api.logger lacks support.
+ # TODO: Stop overriding read_timeout when VPP-1722 is fixed.
+ finally:
+ if sys.path[-1] == cls.api_package_path:
+ sys.path.pop()
+ return vpp_instance
+
+ @classmethod
+ def key_for_node_and_socket(cls, node, remote_socket):
+ """Return a hashable object to distinguish nodes.
+
+ The usual node object (of "dict" type) is not hashable,
+ and can contain mutable information (mostly virtual interfaces).
+ Use this method to get an object suitable for being a key in dict.
+
+ The fields to include are chosen by what ssh needs.
+
+ This class method is needed, for disconnect.
+
+ :param node: The node object to distinguish.
+ :param remote_socket: Path to remote socket.
+ :type node: dict
+ :type remote_socket: str
+ :return: Tuple of values distinguishing this node from similar ones.
+ :rtype: tuple of str
+ """
+ return (
+ node[u"host"],
+ node[u"port"],
+ remote_socket,
+ # TODO: Do we support sockets paths such as "~/vpp/api.socket"?
+ # If yes, add also:
+ # node[u"username"],
+ )
+
+ def key_for_self(self):
+ """Return a hashable object to distinguish nodes.
+
+ Just a wrapper around key_for_node_and_socket
+ which sets up proper arguments.
+
+ :return: Tuple of values distinguishing this node from similar ones.
+ :rtype: tuple of str
+ """
+ return self.__class__.key_for_node_and_socket(
+ self._node, self._remote_vpp_socket,
+ )
+
+ def set_connected_client(self, client):
+ """Add a connected client instance into cache.
+
+ This hides details of what the node key is.
+
+ If there already is a client for the computed key,
+ fail, as it is a sign of resource leakage.
+
+ :param client: VPP client instance in connected state.
+ :type client: vpp_papi.VPPApiClient
+ :raises RuntimeError: If related key already has a cached client.
+ """
+ key = self.key_for_self()
+ cache = self.__class__.conn_cache
+ if key in cache:
+ raise RuntimeError(f"Caching client with existing key: {key}")
+ cache[key] = client
+
+ def get_connected_client(self, check_connected=True):
+ """Return None or cached connected client.
+
+ 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).
+
+ This hides details of what the node key is.
+
+ :param check_connected: Whether cache miss raises.
+ :type check_connected: bool
+ :returns: Connected client instance, or None if uncached and no check.
+ :rtype: Optional[vpp_papi.VPPApiClient]
+ :raises RuntimeError: If cache miss and check enabled.
+ """
+ key = self.key_for_self()
+ ret = self.__class__.conn_cache.get(key, None)
+
+ if ret is None:
+ if check_connected:
+ 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