[RFC,v2,02/10] dts: add ssh command verification

Message ID 20221114165438.1133783-3-juraj.linkes@pantheon.tech (mailing list archive)
State Superseded, archived
Delegated to: Thomas Monjalon
Headers
Series dts: add hello world testcase |

Checks

Context Check Description
ci/checkpatch success coding style OK

Commit Message

Juraj Linkeš Nov. 14, 2022, 4:54 p.m. UTC
  This is a basic capability needed to check whether the command execution
was successful or not. If not, raise a RemoteCommandExecutionError. When
a failure is expected, the caller is supposed to catch the exception.

Signed-off-by: Juraj Linkeš <juraj.linkes@pantheon.tech>
---
 dts/framework/exception.py                    | 21 +++++++
 .../remote_session/remote_session.py          | 55 +++++++++++++------
 dts/framework/remote_session/ssh_session.py   | 11 +++-
 3 files changed, 67 insertions(+), 20 deletions(-)
  

Patch

diff --git a/dts/framework/exception.py b/dts/framework/exception.py
index cac8d84416..b282e48198 100644
--- a/dts/framework/exception.py
+++ b/dts/framework/exception.py
@@ -25,6 +25,7 @@  class ReturnCode(IntEnum):
     NO_ERR = 0
     GENERIC_ERR = 1
     SSH_ERR = 2
+    REMOTE_CMD_EXEC_ERR = 3
     NODE_SETUP_ERR = 20
     NODE_CLEANUP_ERR = 21
 
@@ -89,6 +90,26 @@  def __str__(self) -> str:
         return f"SSH session with {self.host} has died"
 
 
+class RemoteCommandExecutionError(DTSError):
+    """
+    Raised when a command executed on a Node returns a non-zero exit status.
+    """
+
+    command: str
+    command_return_code: int
+    return_code: ClassVar[ReturnCode] = ReturnCode.REMOTE_CMD_EXEC_ERR
+
+    def __init__(self, command: str, command_return_code: int) -> None:
+        self.command = command
+        self.command_return_code = command_return_code
+
+    def __str__(self) -> str:
+        return (
+            f"Command {self.command} returned a non-zero exit code: "
+            f"{self.command_return_code}"
+        )
+
+
 class NodeSetupError(DTSError):
     """
     Raised when setting up a node.
diff --git a/dts/framework/remote_session/remote_session.py b/dts/framework/remote_session/remote_session.py
index 4095e02c1b..fccd80a529 100644
--- a/dts/framework/remote_session/remote_session.py
+++ b/dts/framework/remote_session/remote_session.py
@@ -7,15 +7,29 @@ 
 from abc import ABC, abstractmethod
 
 from framework.config import NodeConfiguration
+from framework.exception import RemoteCommandExecutionError
 from framework.logger import DTSLOG
 from framework.settings import SETTINGS
 
 
 @dataclasses.dataclass(slots=True, frozen=True)
-class HistoryRecord:
+class CommandResult:
+    """
+    The result of remote execution of a command.
+    """
+
     name: str
     command: str
-    output: str | int
+    stdout: str
+    stderr: str
+    return_code: int
+
+    def __str__(self) -> str:
+        return (
+            f"stdout: '{self.stdout}'\n"
+            f"stderr: '{self.stderr}'\n"
+            f"return_code: '{self.return_code}'"
+        )
 
 
 class RemoteSession(ABC):
@@ -35,7 +49,7 @@  class RemoteSession(ABC):
     username: str
     password: str
     logger: DTSLOG
-    history: list[HistoryRecord]
+    history: list[CommandResult]
     _node_config: NodeConfiguration
 
     def __init__(
@@ -68,28 +82,33 @@  def _connect(self) -> None:
         Create connection to assigned node.
         """
 
-    def send_command(self, command: str, timeout: float = SETTINGS.timeout) -> str:
+    def send_command(
+        self, command: str, timeout: float = SETTINGS.timeout, verify: bool = False
+    ) -> CommandResult:
         """
-        Send a command and return the output.
+        Send a command to the connected node and return CommandResult.
+        If verify is True, check the return code of the executed command
+        and raise a RemoteCommandExecutionError if the command failed.
         """
-        self.logger.info(f"Sending: {command}")
-        out = self._send_command(command, timeout)
-        self.logger.debug(f"Received from {command}: {out}")
-        self._history_add(command=command, output=out)
-        return out
+        self.logger.info(f"Sending: '{command}'")
+        result = self._send_command(command, timeout)
+        if verify and result.return_code:
+            self.logger.debug(
+                f"Command '{command}' failed with return code '{result.return_code}'"
+            )
+            self.logger.debug(f"stdout: '{result.stdout}'")
+            self.logger.debug(f"stderr: '{result.stderr}'")
+            raise RemoteCommandExecutionError(command, result.return_code)
+        self.logger.debug(f"Received from '{command}':\n{result}")
+        self.history.append(result)
+        return result
 
     @abstractmethod
-    def _send_command(self, command: str, timeout: float) -> str:
+    def _send_command(self, command: str, timeout: float) -> CommandResult:
         """
-        Use the underlying protocol to execute the command and return the output
-        of the command.
+        Use the underlying protocol to execute the command and return CommandResult.
         """
 
-    def _history_add(self, command: str, output: str) -> None:
-        self.history.append(
-            HistoryRecord(name=self.name, command=command, output=output)
-        )
-
     def close(self, force: bool = False) -> None:
         """
         Close the remote session and free all used resources.
diff --git a/dts/framework/remote_session/ssh_session.py b/dts/framework/remote_session/ssh_session.py
index 5816b1ce6b..fb2f01dbc1 100644
--- a/dts/framework/remote_session/ssh_session.py
+++ b/dts/framework/remote_session/ssh_session.py
@@ -12,7 +12,7 @@ 
 from framework.logger import DTSLOG
 from framework.utils import GREEN, RED
 
-from .remote_session import RemoteSession
+from .remote_session import CommandResult, RemoteSession
 
 
 class SSHSession(RemoteSession):
@@ -163,7 +163,14 @@  def _flush(self) -> None:
     def is_alive(self) -> bool:
         return self.session.isalive()
 
-    def _send_command(self, command: str, timeout: float) -> str:
+    def _send_command(self, command: str, timeout: float) -> CommandResult:
+        output = self._send_command_get_output(command, timeout)
+        return_code = int(self._send_command_get_output("echo $?", timeout))
+
+        # we're capturing only stdout
+        return CommandResult(self.name, command, output, "", return_code)
+
+    def _send_command_get_output(self, command: str, timeout: float) -> str:
         try:
             self._clean_session()
             self._send_line(command)