From 7bdd6a0ade3c82d39beb71475bbac431117b4aca Mon Sep 17 00:00:00 2001 From: Douglas Raillard Date: Thu, 6 Apr 2023 18:14:45 +0100 Subject: [PATCH] connection: Terminate background commands on close() Ensure all background commands are terminated before we close the connection. --- devlib/connection.py | 11 +++++++++++ devlib/utils/ssh.py | 3 --- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/devlib/connection.py b/devlib/connection.py index 020db20..9699d76 100644 --- a/devlib/connection.py +++ b/devlib/connection.py @@ -66,6 +66,7 @@ class ConnectionBase(InitCheckpoint): self._closed = False self._close_lock = threading.Lock() self.busybox = None + self.logger = logging.getLogger('Connection') def cancel_running_command(self): bg_cmds = set(self._current_bg_cmds) @@ -83,11 +84,21 @@ class ConnectionBase(InitCheckpoint): """ def close(self): + + def finish_bg(): + bg_cmds = set(self._current_bg_cmds) + n = len(bg_cmds) + if n: + self.logger.debug(f'Canceling {n} background commands before closing connection') + for bg_cmd in bg_cmds: + bg_cmd.cancel() + # Locking the closing allows any thread to safely call close() as long # as the connection can be closed from a thread that is not the one it # started its life in. with self._close_lock: if not self._closed: + finish_bg() self._close() self._closed = True diff --git a/devlib/utils/ssh.py b/devlib/utils/ssh.py index 39d7046..c3f71f5 100644 --- a/devlib/utils/ssh.py +++ b/devlib/utils/ssh.py @@ -696,9 +696,6 @@ class SshConnection(SshConnectionBase): def _close(self): logger.debug('Logging out {}@{}'.format(self.username, self.host)) with _handle_paramiko_exceptions(): - bg_cmds = set(self._current_bg_cmds) - for bg_cmd in bg_cmds: - bg_cmd.close() self.client.close() def _execute_command(self, command, as_root, log, timeout, executor):