From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.228 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796428614; b=TyjvqEcbDA77GLMMeiZqWVatazw2LhuxyRi2qJShSedkcL8yUcel0keS10w1F/AkV3Pm 3vL+aY7yMb1rxe3omxBJ9cC/D1A+079BkfhUdqxHK0fefufnTJY1deWs1Pxnm9c0RvEuE TR0V9+goWQqah6cRviX4Gy9+3a7rpst8Agcou23Nqw3xrZ3MAy95cqyuVc8WcuQEH06na LE99l3yjBwpds72TWRYcnK3bC3YqxfZlvvaTl25ZGxzNkHo4OPkb2yDJSWe7ljKFYqViJ Ono5viJwdGgA+SjMsC8DQwuAqZAfBupvh9hln7nYPRvF+01bhDZopwNZJW4tHRQf/pg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796428614; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Gm-Message-State:X-Gm-Gg:X-Received:Received:X-Relaying-Domain: Received:Received:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=HtifCZ0B30cpO8r1SuJxc0hsN7IjT6EzNLA4VRb/BxY=; b=qnhcZ8dyQKRxOjzeBIEmDQbNbsjBp3ta1qNyftpic+deE+BvFdzuGvh76KUbiBRnJqB6 uz4ultgrShnUYUYvygRIGIFJrA5wvEn0kSvax2yFmuUebxVCcNFs7URCP3aUTm+r+KEq3 8M+h0XT4V7SAfgTGeJ+1HojwRpxyy4AmOx+k1X8O8m6VWE8vYP0Ky1l8VUtEnKtGVnlR1 rc0jPdBSINjNl3uxZJU6WJcc5x45Tm/sarxgI5beeYNdpjTbqIe8rbDvROVUMpHR5FxQ7 rCWJJrt5ZHry97oVGQNHmHwrcKItQ20aNNRGbg42A1DvGytyCs6nl+4yi/6qxDyfP1w== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=purestorage.com; spf=pass smtp.mailfrom=purestorage.com; dkim=pass header.d=purestorage.com header.i=@purestorage.com header.a=rsa-sha256 header.s=google2022 header.b=VhEEv8Zn; arc=none smtp.remote-ip=74.125.82.228 Received: from mail-dy1-f228.google.com (mail-dy1-f228.google.com [74.125.82.228]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D34B9606A68E for ; Fri, 4 Dec 2026 23:56:53 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org D34B9606A68E Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=purestorage.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=purestorage.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=purestorage.com header.i=@purestorage.com header.a=rsa-sha256 header.s=google2022 header.b=VhEEv8Zn Received: by mail-dy1-f228.google.com with SMTP id 5a478bee46e88-386ab9ab619so2455300eec.1 for ; Fri, 04 Dec 2026 15:56:53 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=purestorage.com; s=google2022; t=1796428613; x=1797033413; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to:content-type; bh=HtifCZ0B30cpO8r1SuJxc0hsN7IjT6EzNLA4VRb/BxY=; b=VhEEv8ZnzA8vMhPm5wyw0EXDVXiDoL389LU4ma/MuMzUrSwbqI9pCN6qlL3mz5JtTN 6QCjAkzgct6F2LifFpB6nbF+Dtxn4ffRfKlfB65sYtiOAQ8GPVSyNs6NDirpCld7+qH1 v8u/yEgWQHdoAvYCDZmkvj5XojAYu+ALm0Q4ycpDOGD7184v0iCYcE7r5kBhiqZPn5EF R7RNbf3xw38svIPzhob6vJh57crkyCW09x/88SGLr8qqgNhx/ZTNoLwXPU1AUt8gLEsP dsOm1sw57JwIXRTYJXRf6lHpSHarY0vGh/32RJ+NZPDnIXILUrhKO/8wZHOXsg15NfZu WYrQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796428613; x=1797033413; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to:content-type; bh=HtifCZ0B30cpO8r1SuJxc0hsN7IjT6EzNLA4VRb/BxY=; b=baBdVQiL89XhVjNQCI6//IEcKnkA50KyGDebU2Ct6zVwvCtHRLhK5Ea8+BRgdunAaU D7hzxb6/VLqkswT8/3QbgLvyCyflWPaBPCnkALMFMCdVF2X+Hlm1Ngd3N8bqcWLgJ/xy JwlXrPfAC7dao1hkZ0AJhboCjPqoiNnVwhDiCnIPT6Ye69L60JsArhP92BaMGtLdHzOK a2E+eIVSGEOLiX/FUAt8J1ZEvXPR3hpYCz4dbmre6DPmy4rprhwzMHw0Tp6K+4yvO/qs Anq3R/oaRTaI453djyuh9sOs3tX98HFQWnN8Jhv8O7T5mHNhPe52c+QvHwTM+jtFmnYc mRGg== X-Gm-Message-State: AB4q+uEAhi3SWVkPK5IynWCje7FnRKC79y0cuq0q/qbKjCGoEG4gE6Ee PNRanVOwP/Ja9rCsgFBvtQGHFEjhZYr+lR5/c3PK9JLuq0UuWlkBi1vgPMNKwDCgL5F2ABfkiR0 Trc9p1w0FidpJK3TKmx3MurDGFxkz+LCCR7eK X-Gm-Gg: AZFdTZckX0yE3ijoZVDzLIjJ0AtjRnXw8FlCNpdckYOHZN1BuJw1iAVXD7Jw83kdEW7 Sb7c0UUx5tATvvUipwjosHj8lY+Gfk+HBhWGBA7bIKYdFvuKCRl5S1NX7DkroTUrl1G1QJ8W3DJ coC88ky7kJW0kGSfiV+3Bh64P/ZltFR6TwMhQYtXi5cDU3moOtgNW+ncSzySAdA7gIEw9XLr6vp VmkfU9wGy8k7ninCYs9jCruKs1MtmPxIUNHslz3WSXun9Yy5DNv0MlMa8qKYpV0AraVtwdednCw g31q+i7T2px+sXyO2rLgATYgk37hKUngZO2wwPXf74p4RXxvHKZP16wFlaCEiJ9APG87Vp59TdV ayi9DRRmL19WcQciB4yQ4VOqKQoeqGJMWYzE= X-Received: by 2002:a05:7301:9f06:b0:387:3dd4:e79 with SMTP id 5a478bee46e88-3875212fef3mr4463922eec.26.1796428612852; Fri, 04 Dec 2026 15:56:52 -0800 (PST) Received: from c7-smtp-2026.dev.purestorage.com ([208.88.159.128]) by smtp-relay.gmail.com with ESMTPS id 5a478bee46e88-3875220a322sm524330eec.26.2026.12.04.15.56.52 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 04 Dec 2026 15:56:52 -0800 (PST) X-Relaying-Domain: purestorage.com Received: from dev-rjethwani.dev.purestorage.com (dev-rjethwani.dev.purestorage.com [IPv6:2620:125:9025:23::2ea]) by c7-smtp-2026.dev.purestorage.com (Postfix) with ESMTP id 31022400F2; Fri, 4 Dec 2026 16:56:52 -0700 (MST) Received: by dev-rjethwani.dev.purestorage.com (Postfix, from userid 1557719937) id 2E85DDCE140; Fri, 4 Dec 2026 16:56:52 -0700 (MST) From: Rishikesh Jethwani To: netdev@vger.kernel.org Cc: Rishikesh Jethwani , "David S. Miller" , Eric Dumazet , Jakub Kicinski , Paolo Abeni , Willem de Bruijn , Simon Horman , Shuah Khan , Stanislav Fomichev , Joe Damato , linux-kselftest@vger.kernel.org Subject: [PATCH net v3 5/9] selftests: net: py: reap commands that fail to report ready Date: Fri, 4 Dec 2026 16:53:52 -0700 Message-ID: <20261204235642.36653-6-rjethwani@purestorage.com> X-Mailer: git-send-email 2.50.1 In-Reply-To: <20261204235642.36653-1-rjethwani@purestorage.com> References: <20261204235642.36653-1-rjethwani@purestorage.com> X-Mailing-List: netdev@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit 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