A readiness timeout leaves the command running with its pipes open. Killing only the command can also leave a wrapper's workers behind. Give readiness-enabled commands their own process group. Kill the group on timeout; on readiness EOF, allow one second after SIGTERM before escalating. Drain output, but bound the wait: a worker can keep a pipe open after its parent exits. Keep the wait FD open until teardown is complete so EOF does not resume a paused helper. Clean up the group on interruption without masking the original exception. Use poll() so readiness also works above FD_SETSIZE. Found while developing the TLS bond tests. Tested locally with TERM-ignoring workers, inherited pipes, large output, high-numbered FDs and Ctrl-C during readiness and teardown. Fixes: 71477137994f ("selftests: drv-net: add a way to wait for a local process") Signed-off-by: Rishikesh Jethwani --- tools/testing/selftests/net/lib/py/utils.py | 246 ++++++++++++++++++-- 1 file changed, 231 insertions(+), 15 deletions(-) diff --git a/tools/testing/selftests/net/lib/py/utils.py b/tools/testing/selftests/net/lib/py/utils.py index 1727bc418073..9edfc4f88621 100644 --- a/tools/testing/selftests/net/lib/py/utils.py +++ b/tools/testing/selftests/net/lib/py/utils.py @@ -1,9 +1,12 @@ # SPDX-License-Identifier: GPL-2.0 +import contextlib import json as _json +import math import os import re import select +import signal import socket import subprocess import time @@ -27,9 +30,28 @@ class CmdExitZeroFailure(CmdExitFailure): """ Command succeeded (returned zero exit code), but expected failure. """ +def _poll_timeout_ms(timeout): + """Convert a timeout in seconds to poll()'s milliseconds. + + None waits forever. poll() takes a negative timeout as forever too, + where select() raised, and overflows past INT_MAX milliseconds: refuse + both. Also lets cmd() check a timeout before spawning its command. + """ + if timeout is None: + return None + if (not 0 <= timeout or not math.isfinite(timeout) or + math.ceil(timeout * 1000) > 2**31 - 1): + raise ValueError(f"timeout must be between 0 and " + f"{(2**31 - 1) / 1000}s, not {timeout}") + return timeout * 1000 + + def fd_read_timeout(fd, timeout): - rlist, _, _ = select.select([fd], [], [], timeout) - if rlist: + timeout_ms = _poll_timeout_ms(timeout) + # poll(), not select(): select() rejects FDs >= FD_SETSIZE. + poller = select.poll() + poller.register(fd, select.POLLIN) + if poller.poll(timeout_ms): return os.read(fd, 1024) raise TimeoutError("Timeout waiting for fd read") @@ -58,6 +80,7 @@ class cmd: self.stderr = None self.ret = None self.ksft_term_fd = None + self._own_pgrp = False self.host = host self.comm = comm @@ -74,6 +97,8 @@ class cmd: # Similarly term_fd tells child it's time to exit. pass_fds = [] env = os.environ.copy() + # Before spawning: fd_read_timeout() would refuse it only after. + _poll_timeout_ms(ksft_wait) if ksft_wait is not None: wait_fd, self.ksft_term_fd = os.pipe() pass_fds.append(wait_fd) @@ -84,26 +109,207 @@ class cmd: pass_fds.append(ready_fd) env["KSFT_READY_FD"] = str(ready_fd) + # A command that reports ready leads its own process group, so + # that _reap_unready() and _kill_leftovers() can stop what it + # started too. Terminal signals then no longer reach it: on + # Ctrl-C, KeyboardInterrupt here leads to the same cleanup. + self._own_pgrp = ksft_ready is not None self.proc = subprocess.Popen(comm, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, pass_fds=pass_fds, - env=env) + env=env, + start_new_session=self._own_pgrp) if ksft_wait is not None: os.close(wait_fd) if ksft_ready is not None: os.close(ready_fd) - msg = fd_read_timeout(rfd, ksft_wait) - os.close(rfd) + timed_out = False + try: + msg = fd_read_timeout(rfd, ksft_wait) + except TimeoutError: + msg = None + timed_out = True + except BaseException: + # Interrupted: stop the command, then let the + # interruption, not any cleanup failure, propagate. + self._cleanup_quietly(self._reap_unready, kill=True) + raise + finally: + os.close(rfd) if not msg: - terminate = self.proc.poll() is None - self._process_terminate(terminate=terminate, timeout=1) + self._reap_unready(kill=timed_out) raise CmdInitFailure("Did not receive ready message", self) if not background: self.process(terminate=False, fail=fail, expect_fail=expect_fail, timeout=timeout) + def _drain_until_exit(self, bufs, timeout): + """Read the command's output into bufs until it exits. + + Reading keeps a command that writes while shutting down from + blocking on a full pipe. Returns False if the command is still + running after timeout seconds. + """ + fds = {self.proc.stdout.fileno(): bufs[0], + self.proc.stderr.fileno(): bufs[1]} + poller = select.poll() + for fd in fds: + poller.register(fd, select.POLLIN) + deadline = time.monotonic() + timeout + while self.proc.poll() is None: + left = deadline - time.monotonic() + if left <= 0: + return False + if not fds: + # Both pipes are at EOF: nothing left to drain. + try: + self.proc.wait(timeout=left) + except subprocess.TimeoutExpired: + return False + break + # Poll the exit status at least every 100ms: descendants can + # keep the pipes open, and quiet, after the command exits. + for fd, _ in poller.poll(min(left, 0.1) * 1000): + data = os.read(fd, 65536) + if data: + fds[fd].append(data) + else: + poller.unregister(fd) + del fds[fd] + return True + + def _cleanup_quietly(self, func, *args, **kwargs): + """Run a cleanup step while an exception is propagating. + + Report a failure instead of raising it, which would replace that + exception. A second interruption still propagates. + """ + try: + func(*args, **kwargs) + except Exception as e: + print(f"# Warning: cleanup of {self.comm!r} failed: " + f"{type(e).__name__}: {e}") + + @contextlib.contextmanager + def _killed_on_interrupt(self): + """Guard a wait for the command to exit. + + If the wait ends in an exception, KeyboardInterrupt say, SIGKILL + the process group the command leads: terminal signals do not reach + it, so it and what it started would run on. The exception stays + the one raised. + """ + try: + yield + except BaseException: + self._cleanup_quietly(self._kill_leftovers) + raise + + def _kill_leftovers(self): + """SIGKILL what is left of the process group the command leads.""" + if not self._own_pgrp: + return + self._kill_group(signal.SIGKILL) + if self.proc.returncode is None: + try: + self.proc.wait(timeout=1) + except subprocess.TimeoutExpired: + pass + self.proc.stdout.close() + self.proc.stderr.close() + # Only now: EOF on the ksft_wait pipe lets a command go on. + if self.ksft_term_fd: + os.close(self.ksft_term_fd) + self.ksft_term_fd = None + + def _kill_group(self, sig): + """Signal the process group the command leads. + + The group outlives the command while any of its descendants are + left in it, so this reaches them after the command is reaped too. + """ + try: + os.killpg(self.proc.pid, sig) + except ProcessLookupError: + pass + + def _reap_unready(self, kill): + """Stop and reap a local command that did not report ready. + + A command that closed the ready FD gets SIGTERM, as before, and a + grace period to exit, with its output drained meanwhile. One that + never answered gets SIGKILL, since it may ignore SIGTERM, as does + one still running after the grace period. The signals go to the + command's whole process group, and whatever is left of the group + once the command is gone gets SIGKILL, so that a wrapper's workers + do not outlive it. Wait for the command itself rather than for EOF + on its output: a shell's descendants can keep its stdout/stderr + pipes open after it exits, so take only the output that is there. + + Close the ksft_wait pipe only once all that is done: ksft_wait() + takes EOF on it as leave to go on, so closing it first lets a + command that is still running resume. + """ + out, err = [], [] + with self._killed_on_interrupt(): + if self.proc.poll() is None: + self._kill_group(signal.SIGKILL if kill else signal.SIGTERM) + self._drain_until_exit((out, err), timeout=1) + self._collect_reaped(out, err) + + def _reap_cancelled(self, terminate, timeout): + """Stop and reap a local command whose bkg() was cancelled. + + Ask the command to exit as a normal exit would, through the + ksft_wait pipe or with SIGTERM to its group, and wait for it, not + for EOF: what it started may hold its pipes open. Then SIGKILL the + rest of its group, as _reap_unready() does. + """ + if self.ksft_term_fd: + try: + os.write(self.ksft_term_fd, b"1") + except BrokenPipeError: + pass + out, err = [], [] + with self._killed_on_interrupt(): + if self.proc.poll() is None: + if terminate: + self._kill_group(signal.SIGTERM) + self._drain_until_exit((out, err), timeout=timeout) + self._collect_reaped(out, err) + + def _collect_reaped(self, out, err): + """SIGKILL the command's group, reap it and keep its output. + + out and err hold output drained so far. + """ + self._kill_group(signal.SIGKILL) + # A command stuck in the kernel does not die even then: give up + # on it rather than hang, leaving ret unset. + try: + self.proc.wait(timeout=1) + except subprocess.TimeoutExpired: + pass + try: + stdout, stderr = self.proc.communicate(timeout=1) + except subprocess.TimeoutExpired as e: + stdout, stderr = e.stdout or b"", e.stderr or b"" + stdout = b"".join(out) + stdout + stderr = b"".join(err) + stderr + self.stdout = stdout.decode("utf-8", "replace") + self.stderr = stderr.decode("utf-8", "replace") + self.proc.stdout.close() + self.proc.stderr.close() + self.ret = self.proc.returncode + if self.ksft_term_fd: + os.close(self.ksft_term_fd) + self.ksft_term_fd = None + def _process_terminate(self, terminate, timeout): if terminate: - self.proc.terminate() + if self._own_pgrp: + self._kill_group(signal.SIGTERM) + else: + self.proc.terminate() stdout, stderr = self.proc.communicate(timeout=timeout) self.stdout = stdout.decode("utf-8") self.stderr = stderr.decode("utf-8") @@ -117,11 +323,11 @@ class cmd: if fail is None: fail = not terminate - if self.ksft_term_fd: - os.write(self.ksft_term_fd, b"1") - - stdout, stderr = self._process_terminate(terminate=terminate, - timeout=timeout) + with self._killed_on_interrupt(): + if self.ksft_term_fd: + os.write(self.ksft_term_fd, b"1") + stdout, stderr = self._process_terminate(terminate=terminate, + timeout=timeout) # Fail on unexpected test failure if fail. # Fail on unexpected test success if expect_fail. @@ -202,8 +408,18 @@ class bkg(cmd): # since forcing termination silences failures with fail=None if self.proc.poll() is None: terminate = terminate or (self._exit_wait and ex_type is not None) - return self.process(terminate=terminate, fail=self.check_fail, - expect_fail=self.expect_fail) + if ex_type is None: + return self.process(terminate=terminate, fail=self.check_fail, + expect_fail=self.expect_fail) + # Cancelled, e.g. by Ctrl-C: stop the command and what it started, + # without replacing the exception in flight. + if self._own_pgrp: + self._cleanup_quietly(self._reap_cancelled, terminate, 20) + else: + self._cleanup_quietly(self.process, terminate=terminate, + fail=self.check_fail, + expect_fail=self.expect_fail) + return None GLOBAL_DEFER_QUEUE = [] -- 2.50.1