From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from mails.dpdk.org (mails.dpdk.org [217.70.189.124]) by inbox.dpdk.org (Postfix) with ESMTP id 54EA7A00C5; Fri, 4 Nov 2022 12:06:09 +0100 (CET) Received: from [217.70.189.124] (localhost [127.0.0.1]) by mails.dpdk.org (Postfix) with ESMTP id 2100142D3B; Fri, 4 Nov 2022 12:05:40 +0100 (CET) Received: from lb.pantheon.sk (lb.pantheon.sk [46.229.239.20]) by mails.dpdk.org (Postfix) with ESMTP id F3CA842D3A for ; Fri, 4 Nov 2022 12:05:38 +0100 (CET) Received: from localhost (localhost [127.0.0.1]) by lb.pantheon.sk (Postfix) with ESMTP id 0DF5A1BA5AB; Fri, 4 Nov 2022 12:05:38 +0100 (CET) X-Virus-Scanned: amavisd-new at siecit.sk Received: from lb.pantheon.sk ([127.0.0.1]) by localhost (lb.pantheon.sk [127.0.0.1]) (amavisd-new, port 10024) with ESMTP id pSWDT9BHOqCG; Fri, 4 Nov 2022 12:05:35 +0100 (CET) Received: from entguard.lab.pantheon.local (unknown [46.229.239.141]) by lb.pantheon.sk (Postfix) with ESMTP id E46E71BA5AE; Fri, 4 Nov 2022 12:05:28 +0100 (CET) From: =?UTF-8?q?Juraj=20Linke=C5=A1?= To: thomas@monjalon.net, Honnappa.Nagarahalli@arm.com, ohilyard@iol.unh.edu, lijuan.tu@intel.com, kda@semihalf.com, bruce.richardson@intel.com Cc: dev@dpdk.org, =?UTF-8?q?Juraj=20Linke=C5=A1?= Subject: [PATCH v8 6/9] dts: add ssh session module Date: Fri, 4 Nov 2022 11:05:20 +0000 Message-Id: <20221104110523.511367-7-juraj.linkes@pantheon.tech> X-Mailer: git-send-email 2.25.1 In-Reply-To: <20221104110523.511367-1-juraj.linkes@pantheon.tech> References: <20221103151934.450887-1-juraj.linkes@pantheon.tech> <20221104110523.511367-1-juraj.linkes@pantheon.tech> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-BeenThere: dev@dpdk.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: DPDK patches and discussions List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: dev-bounces@dpdk.org The module uses the pexpect python library and implements connection to a node and two ways to interact with the node: 1. Send a string with specified prompt which will be matched after the string has been sent to the node. 2. Send a command to be executed. No prompt is specified here. Signed-off-by: Owen Hilyard Signed-off-by: Juraj Linkeš --- dts/framework/exception.py | 56 ++++++ dts/framework/remote_session/__init__.py | 12 ++ dts/framework/remote_session/ssh_session.py | 184 ++++++++++++++++++++ dts/framework/utils.py | 12 ++ 4 files changed, 264 insertions(+) create mode 100644 dts/framework/exception.py create mode 100644 dts/framework/remote_session/ssh_session.py create mode 100644 dts/framework/utils.py diff --git a/dts/framework/exception.py b/dts/framework/exception.py new file mode 100644 index 0000000000..8b2f08a8f0 --- /dev/null +++ b/dts/framework/exception.py @@ -0,0 +1,56 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2010-2014 Intel Corporation +# Copyright(c) 2022 PANTHEON.tech s.r.o. +# Copyright(c) 2022 University of New Hampshire + +""" +User-defined exceptions used across the framework. +""" + + +class SSHTimeoutError(Exception): + """ + Command execution timeout. + """ + + command: str + output: str + + def __init__(self, command: str, output: str): + self.command = command + self.output = output + + def __str__(self) -> str: + return f"TIMEOUT on {self.command}" + + def get_output(self) -> str: + return self.output + + +class SSHConnectionError(Exception): + """ + SSH connection error. + """ + + host: str + + def __init__(self, host: str): + self.host = host + + def __str__(self) -> str: + return f"Error trying to connect with {self.host}" + + +class SSHSessionDeadError(Exception): + """ + SSH session is not alive. + It can no longer be used. + """ + + host: str + + def __init__(self, host: str): + self.host = host + + def __str__(self) -> str: + return f"SSH session with {self.host} has died" diff --git a/dts/framework/remote_session/__init__.py b/dts/framework/remote_session/__init__.py index 9bb042a482..a227d8db22 100644 --- a/dts/framework/remote_session/__init__.py +++ b/dts/framework/remote_session/__init__.py @@ -1,2 +1,14 @@ # SPDX-License-Identifier: BSD-3-Clause # Copyright(c) 2022 PANTHEON.tech s.r.o. + +from framework.config import NodeConfiguration +from framework.logger import DTSLOG + +from .remote_session import RemoteSession +from .ssh_session import SSHSession + + +def create_remote_session( + node_config: NodeConfiguration, name: str, logger: DTSLOG +) -> RemoteSession: + return SSHSession(node_config, name, logger) diff --git a/dts/framework/remote_session/ssh_session.py b/dts/framework/remote_session/ssh_session.py new file mode 100644 index 0000000000..7ec327054d --- /dev/null +++ b/dts/framework/remote_session/ssh_session.py @@ -0,0 +1,184 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2010-2014 Intel Corporation +# Copyright(c) 2022 PANTHEON.tech s.r.o. +# Copyright(c) 2022 University of New Hampshire + +import time + +from pexpect import pxssh # type: ignore + +from framework.config import NodeConfiguration +from framework.exception import SSHConnectionError, SSHSessionDeadError, SSHTimeoutError +from framework.logger import DTSLOG +from framework.utils import GREEN, RED + +from .remote_session import RemoteSession + + +class SSHSession(RemoteSession): + """ + Module for creating Pexpect SSH sessions to a node. + """ + + session: pxssh.pxssh + magic_prompt: str + + def __init__( + self, + node_config: NodeConfiguration, + session_name: str, + logger: DTSLOG, + ): + self.magic_prompt = "MAGIC PROMPT" + super(SSHSession, self).__init__(node_config, session_name, logger) + + def _connect(self) -> None: + """ + Create connection to assigned node. + """ + retry_attempts = 10 + login_timeout = 20 if self.port else 10 + password_regex = ( + r"(?i)(?:password:)|(?:passphrase for key)|(?i)(password for .+:)" + ) + try: + for retry_attempt in range(retry_attempts): + self.session = pxssh.pxssh(encoding="utf-8") + try: + self.session.login( + self.ip, + self.username, + self.password, + original_prompt="[$#>]", + port=self.port, + login_timeout=login_timeout, + password_regex=password_regex, + ) + break + except Exception as e: + self.logger.warning(e) + time.sleep(2) + self.logger.info( + f"Retrying connection: retry number {retry_attempt + 1}." + ) + else: + raise Exception(f"Connection to {self.hostname} failed") + + self.send_expect("stty -echo", "#") + self.send_expect("stty columns 1000", "#") + except Exception as e: + self.logger.error(RED(str(e))) + if getattr(self, "port", None): + suggestion = ( + f"\nSuggestion: Check if the firewall on {self.hostname} is " + f"stopped.\n" + ) + self.logger.info(GREEN(suggestion)) + + raise SSHConnectionError(self.hostname) + + def send_expect( + self, command: str, prompt: str, timeout: float = 15, verify: bool = False + ) -> str | int: + try: + ret = self.send_expect_base(command, prompt, timeout) + if verify: + ret_status = self.send_expect_base("echo $?", prompt, timeout) + try: + retval = int(ret_status) + if retval: + self.logger.error(f"Command: {command} failure!") + self.logger.error(ret) + return retval + else: + return ret + except ValueError: + return ret + else: + return ret + except Exception as e: + self.logger.error( + f"Exception happened in [{command}] and output is " + f"[{self._get_output()}]" + ) + raise e + + def send_expect_base(self, command: str, prompt: str, timeout: float) -> str: + self._clean_session() + original_prompt = self.session.PROMPT + self.session.PROMPT = prompt + self._send_line(command) + self._prompt(command, timeout) + + before = self._get_output() + self.session.PROMPT = original_prompt + return before + + def _clean_session(self) -> None: + self.session.PROMPT = self.magic_prompt + self.get_output(timeout=0.01) + self.session.PROMPT = self.session.UNIQUE_PROMPT + + def _send_line(self, command: str) -> None: + if not self.is_alive(): + raise SSHSessionDeadError(self.hostname) + if len(command) == 2 and command.startswith("^"): + self.session.sendcontrol(command[1]) + else: + self.session.sendline(command) + + def _prompt(self, command: str, timeout: float) -> None: + if not self.session.prompt(timeout): + raise SSHTimeoutError(command, self._get_output()) from None + + def get_output(self, timeout: float = 15) -> str: + """ + Get all output before timeout + """ + try: + self.session.prompt(timeout) + except Exception: + pass + + before = self._get_output() + self._flush() + + return before + + def _get_output(self) -> str: + if not self.is_alive(): + raise SSHSessionDeadError(self.hostname) + before = self.session.before.rsplit("\r\n", 1)[0] + if before == "[PEXPECT]": + return "" + return before + + def _flush(self) -> None: + """ + Clear all session buffer + """ + self.session.buffer = "" + self.session.before = "" + + def is_alive(self) -> bool: + return self.session.isalive() + + def _send_command(self, command: str, timeout: float) -> str: + try: + self._clean_session() + self._send_line(command) + except Exception as e: + raise e + + output = self.get_output(timeout=timeout) + self.session.PROMPT = self.session.UNIQUE_PROMPT + self.session.prompt(0.1) + + return output + + def _close(self, force: bool = False) -> None: + if force is True: + self.session.close() + else: + if self.is_alive(): + self.session.logout() diff --git a/dts/framework/utils.py b/dts/framework/utils.py new file mode 100644 index 0000000000..9c1975a22f --- /dev/null +++ b/dts/framework/utils.py @@ -0,0 +1,12 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2010-2014 Intel Corporation +# Copyright(c) 2022 PANTHEON.tech s.r.o. +# Copyright(c) 2022 University of New Hampshire + + +def GREEN(text: str) -> str: + return f"\u001B[32;1m{str(text)}\u001B[0m" + + +def RED(text: str) -> str: + return f"\u001B[31;1m{str(text)}\u001B[0m" -- 2.30.2