From d95e56d9b672f504f09fca17e48f88e1d6960076 Mon Sep 17 00:00:00 2001 From: Liam Brady Date: Tue, 16 Jun 2026 12:28:02 -0400 Subject: [PATCH 1/2] munet: background command API This new background command API allows for generic commands to be started in the background and cleaned up later. The cleanup_pid API is refactored to allow for the best-effort cleanup of process groups. Fixes #79 Signed-off-by: Liam Brady --- .github/workflows/ci.yml | 6 + munet/base.py | 418 ++++++++++++++++-- munet/native.py | 39 +- munet/testing/fixtures.py | 35 +- tests/background/munet.yaml | 15 + tests/background/test_background.py | 77 ++++ tests/background/test_background_cleanup.py | 101 +++++ .../test_background_status_extra.py | 80 ++++ tests/background/test_cleanup_pid.py | 280 ++++++++++++ 9 files changed, 1005 insertions(+), 46 deletions(-) create mode 100644 tests/background/munet.yaml create mode 100644 tests/background/test_background.py create mode 100644 tests/background/test_background_cleanup.py create mode 100644 tests/background/test_background_status_extra.py create mode 100644 tests/background/test_cleanup_pid.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c605a2b..07b4f79 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,6 +36,12 @@ jobs: sudo apt-get update -y sudo apt-get install -y cloud-utils qemu-system-x86 + - name: Install tshark + run: | + uname -a + sudo apt-get update -y + sudo DEBIAN_FRONTEND=noninteractive apt-get install -y tshark + - name: Lint the project run: make ci-lint diff --git a/munet/base.py b/munet/base.py index 8ff9c79..4619d1e 100644 --- a/munet/base.py +++ b/munet/base.py @@ -78,6 +78,7 @@ def __init__(self, delta): self.delta = datetime.timedelta(seconds=delta) self.started_on = datetime.datetime.now() self.expires_on = self.started_on + self.delta + self.first_iteration = True def elapsed(self): elapsed = datetime.datetime.now() - self.started_on @@ -95,13 +96,42 @@ def __iter__(self): def __next__(self): remaining = self.remaining() - if remaining <= 0: + if remaining <= 0 and not self.first_iteration: raise StopIteration() - return remaining + self.first_iteration = False + return max(0, remaining) def __bool__(self): return self.is_expired() +class BackgroundCmd: + """An object that holds a running background command.""" + + def __init__( + self, + p, + cmds, + actual_cmd, + stdin_file, + stdout_file, + stderr_file, + ): + self.p = p + self.cmds = cmds + self.actual_cmd = actual_cmd + self.stdin_file = stdin_file + self.stdout_file = stdout_file + self.stderr_file = stderr_file + + def close_files(self): + """Idempotent file cleanup function.""" + if self.stdin_file is not None: + self.stdin_file.close() + if self.stdout_file is not None: + self.stdout_file.close() + if self.stderr_file is not None: + self.stderr_file.close() + def fsafe_name(name): return "".join(x if x.isalnum() else "_" for x in name) @@ -335,7 +365,7 @@ def __init__(self, name, logger=None, unet=None, **kwargs): logger: logger to use for logging commands a defualt is supplied if this is None unet: unet that owns this object, only used by Commander in run_in_window, - otherwise can be None. + and for background commands, otherwise can be None. """ # del kwargs # deal with lint warning # logging.warning("Commander: name %s kwargs %s", name, kwargs) @@ -346,6 +376,9 @@ def __init__(self, name, logger=None, unet=None, **kwargs): self.last = None self.exec_paths = {} + # For managing background processes + self.background_cmds = {} + # For running commands one time only (deals with asyncio) self.cmd_once_done = {} self.cmd_once_locks = {} @@ -437,42 +470,172 @@ def path_exists(self, path): """Check if path exists.""" return self.test("-e", path) - async def cleanup_pid(self, pid, kill_pid=None): + def pid_exists(self, pid, is_pgroup=False): + try: + if is_pgroup: + os.killpg(pid, 0) + else: + os.kill(pid, 0) + return True + except ProcessLookupError: + return False + except PermissionError: + # Exists, but its permissions have unexpectedly changed + return True + + def reap_pid(self, pid, proc=None): + reap_complete = False + rv = None + if proc is not None: + assert pid == proc.pid + try: + if isinstance(proc, asyncio.subprocess.Process): # pylint: disable=no-member + rv = proc.returncode + else: + rv = proc.poll() + reap_complete = rv is not None + except OSError as error: + self.logger.warning( + "%s: error waiting on proc pid %s: %s", self, pid, error + ) + else: + try: + wait_pid, status = os.waitpid(pid, os.WNOHANG) + if wait_pid != 0: + rv = os.waitstatus_to_exitcode(status) + reap_complete = True + self.logger.debug("%s: pid %s exited status %s", self, pid, rv) + except OSError as error: + if error.errno == errno.ECHILD: + self.logger.debug( + "%s: pid %s is not a waitable child (possibly already reaped)", + self, + pid, + ) + reap_complete = True + else: + self.logger.warning( + "%s: error waiting on pid %s: %s", self, pid, error + ) + return (reap_complete, rv) + + async def async_cleanup_pid( + self, + pid, + kill_pid=None, + wait_sec=30, + is_pgroup=False, + proc=None, + ): """Signal a pid to exit with escalating forcefulness.""" + if proc is not None and pid != proc.pid: + raise ValueError("Process specified, but proc.pid != pid") if kill_pid is None: kill_pid = pid + # Kill the process + rv = None + reap_complete = False for sn in (signal.SIGHUP, signal.SIGKILL): self.logger.debug( - "%s: %s %s (wait %s)", self, signal.Signals(sn).name, kill_pid, pid + "%s: %s %s (wait %s) %s", + self, + signal.Signals(sn).name, + kill_pid, + pid, + is_pgroup, ) - os.kill(kill_pid, sn) + try: + if is_pgroup: + os.killpg(kill_pid, sn) + else: + os.kill(kill_pid, sn) + except ProcessLookupError: + # Attempt to reap, but don't wait anymore + wait_sec = 1 + + # try each signal, waiting half the timeout before advancing + self.logger.debug("%s: waiting %ss for pid to exit", self, wait_sec) + for _ in Timeout(wait_sec): + # we want to confirm both of the following: + # 1. the specific pid identified by kill_pid was reaped + # 2. any applicable pgroups have exited + if not reap_complete: + reap_complete, rv = self.reap_pid(pid, proc) + if not reap_complete or self.pid_exists(kill_pid, is_pgroup=is_pgroup): + await asyncio.sleep(0.1) + else: + return rv + self.logger.debug("%s: timeout waiting on pid %s to exit", self, kill_pid) + + if not reap_complete: + raise TimeoutError(f"Failed to reap pid {pid}") + if self.pid_exists(kill_pid, is_pgroup=is_pgroup): + self.logger.warning( + "%s: failed to confirm termination of %s %s", + self, + "pgroup" if is_pgroup else "pid", + pid, + ) + return rv - # No need to wait after this. - if sn == signal.SIGKILL: - return + def cleanup_pid(self, pid, kill_pid=None, wait_sec=30, is_pgroup=False, proc=None): + """Signal a pid to exit with escalating forcefulness.""" + if proc is not None and pid != proc.pid: + raise ValueError("Process specified, but proc.pid != pid") + if isinstance(proc, asyncio.subprocess.Process): # pylint: disable=no-member + raise ValueError("Async process specified; cannot be reaped by sync API") + if kill_pid is None: + kill_pid = pid - # try each signal, waiting 15 seconds for exit before advancing - wait_sec = 30 + # Kill the process + rv = None + reap_complete = False + for sn in (signal.SIGHUP, signal.SIGKILL): + self.logger.debug( + "%s: %s %s (wait %s) %s", + self, + signal.Signals(sn).name, + kill_pid, + pid, + is_pgroup, + ) + + try: + if is_pgroup: + os.killpg(kill_pid, sn) + else: + os.kill(kill_pid, sn) + except ProcessLookupError: + # Attempt to reap, but don't wait anymore + wait_sec = 1 + + # try each signal, waiting half the timeout before advancing self.logger.debug("%s: waiting %ss for pid to exit", self, wait_sec) for _ in Timeout(wait_sec): - try: - status = os.waitpid(pid, os.WNOHANG) - if status == (0, 0): - await asyncio.sleep(0.1) - else: - self.logger.debug("pid %s exited status %s", pid, status) - return - except OSError as error: - if error.errno == errno.ECHILD: - self.logger.debug("%s: pid %s was reaped", self, pid) - else: - self.logger.warning( - "%s: error waiting on pid %s: %s", self, pid, error - ) - return - self.logger.debug("%s: timeout waiting on pid %s to exit", self, pid) + # we want to confirm both of the following: + # 1. the specific pid identified by kill_pid was reaped + # 2. any applicable pgroups have exited + if not reap_complete: + reap_complete, rv = self.reap_pid(pid, proc) + if not reap_complete or self.pid_exists(kill_pid, is_pgroup=is_pgroup): + time_mod.sleep(0.1) + else: + return rv + self.logger.debug("%s: timeout waiting on pid %s to exit", self, kill_pid) + + if not reap_complete: + raise TimeoutError(f"Failed to reap pid {pid}") + if self.pid_exists(kill_pid, is_pgroup=is_pgroup): + self.logger.warning( + "%s: failed to confirm termination of %s %s", + self, + "pgroup" if is_pgroup else "pid", + pid, + ) + return rv + def _get_sub_args(self, cmd_list, defaults, use_pty=False, ns_only=False, **kwargs): """Returns pre-command, cmd, and default keyword args.""" @@ -1051,8 +1214,8 @@ async def async_cleanup_proc(self, p, pid=None): "%s: [cleanup_proc] terminate process: %s (pid %s)", self, proc_str(p), pid ) try: - # This will SIGHUP and wait a while then SIGKILL and return immediately - await self.cleanup_pid(p.pid, pid) + # This will SIGHUP and wait a while then SIGKILL and reap the proc + await self.async_cleanup_pid(p.pid, pid, proc=p) # Wait another 2 seconds after the possible SIGKILL above for the # parent nsenter to cleanup and exit @@ -1066,7 +1229,7 @@ async def async_cleanup_proc(self, p, pid=None): self, proc_error(p, o, e), ) - except (asyncio.TimeoutError, subprocess.TimeoutExpired): + except (TimeoutError, asyncio.TimeoutError, subprocess.TimeoutExpired): self.logger.warning("%s: [cleanup_proc] SIGKILL timeout", self) return p except Exception as error: @@ -1146,6 +1309,125 @@ async def _async_cmd_status( e = e.decode(encoding) if e is not None else e return self._cmd_status_finish(p, cmds, actual_cmd, o, e, raises, warn) + def _background_cmd_start_status( + self, + cmds, + stdin=None, + stdout=None, + stderr=None, + text=None, + **kwargs, + ): + """Starts execution of a background command.""" + unet = self.unet if self.unet is not None else self + + # STDOUT/STDERR must be buffered somewhere, so write to tempfiles + stdin_file = tempfile.TemporaryFile(mode="w+b") + stdout_file = tempfile.TemporaryFile(mode="w+b") + stderr_file = tempfile.TemporaryFile(mode="w+b") + + pinput, stdin = Commander._cmd_status_input(stdin) + if text is False: + encoding = None + else: + encoding = kwargs.get("encoding", "utf-8") + + # Allow for stdout/stderr redirection to still occur + stdout = stdout_file if stdout is None else stdout + stderr = stderr_file if stderr is None else stderr + + if encoding is not None and isinstance(pinput, str): + pinput = pinput.encode(encoding) + + if pinput is not None: + stdin_file.write(pinput) + stdin_file.seek(0) + stdin = stdin_file + + try: + p, actual_cmd = self._popen( + "background_cmd_start", + cmds, + stdin=stdin, + stdout=stdout, + stderr=stderr, + start_new_session=True, + **kwargs + ) + except Exception: + stdin_file.close() + stdout_file.close() + stderr_file.close() + raise + + bg = BackgroundCmd( + p, + cmds, + actual_cmd, + stdin_file, + stdout_file, + stderr_file, + ) + unet.background_cmds[p.pid] = bg + self.logger.debug("%s: started with pid %s", self, p.pid) + + return p.pid + + def _background_cmd_end_status( + self, + pid, + raises=False, + warn=False, + text=None, + **kwargs, + ): + """Ends a background command with status.""" + unet = self.unet if self.unet is not None else self + bg = unet.background_cmds.get(pid, None) + if bg is None: + raise KeyError(f"Process {pid} is not tracked") + + timeout = 30 + if "timeout" in kwargs: + timeout = kwargs["timeout"] + del kwargs["timeout"] + + o = None + e = None + try: + self.cleanup_pid(pid, wait_sec=timeout, is_pgroup=True, proc=bg.p) + + bg.stdout_file.seek(0) + bg.stderr_file.seek(0) + o = bg.stdout_file.read() + e = bg.stderr_file.read() + except TimeoutError: + self.logger.error("%s: Process %s failed to exit", self, pid) + raise + + # Remove process only once it is confirmed to exit. + del unet.background_cmds[pid] + bg.close_files() + + if text is False: + encoding = None + else: + encoding = kwargs.get("encoding", "utf-8") + + if encoding is not None: + o = o.decode(encoding) if o is not None else o + e = e.decode(encoding) if e is not None else e + + return self._cmd_status_finish( + bg.p, + bg.cmds, + bg.actual_cmd, + o, + e, + raises, + warn, + ) + def _get_cmd_as_list(self, cmd): """Given a list or string return a list form for execution. @@ -1343,6 +1625,63 @@ async def async_cmd_raises_nsonly(self, cmd, **kwargs): ) return stdout + def background_cmd_start(self, cmd, **kwargs): + """Run given command in the background. + + Args: + cmd: `str` or `list` of the command to execute. If a string is given + it is run using a shell, otherwise the list is executed directly + as the binary and arguments. + **kwargs: kwargs is eventually passed on to Popen. If `command` is a string + then will be invoked with `bash -c`, otherwise `command` is a list and + will be invoked without a shell. + + Returns: + (pid) is returned + pid: the process id of the background command in the host + """ + return self._background_cmd_start_status(cmd, **kwargs) + + def background_cmd_start_nsonly(self, pid, **kwargs): + # Make sure the command runs on the host and not in any container. + return self._background_cmd_start_status(pid, ns_only=True, **kwargs) + + def background_cmd_end_status(self, pid, **kwargs): + """End a running background command, returning status and outputs. + + Args: + pid: process id of the background process + **kwargs: kwargs containing flags such as `warn` or `raise` + + Returns: + (status, output, error) are returned + status: the returncode of the command. + output: stdout as a string from the command. + error: stderr as a string from the command. + """ + # + # This method serves as the basis for all derived background cmd variations, so + # to override background cmd behavior simply override this function and *not* + # the other variations, unless you are changing only that variation's behavior + # + return self._background_cmd_end_status(pid, **kwargs) + + def background_cmd_end_raises(self, pid, **kwargs): + """End a background command. Raise an exception on errors. + + Args: + pid: process id of the background process + **kwargs: kwargs containing flags such as `warn` or `raise` + + Returns: + output: stdout as a string from the command. + + Raises: + CalledProcessError: on non-zero exit status + """ + _, stdout, _ = self._background_cmd_end_status(pid, raises=True, **kwargs) + return stdout + def cmd_legacy(self, cmd, **kwargs): """Execute a command with stdout and stderr joined, *IGNORES ERROR*.""" defaults = {"stderr": subprocess.STDOUT} @@ -1600,6 +1939,23 @@ async def _async_delete(self): invoke `super()._async_delete() without catching any exceptions raised therein. See other examples in `base.py` or `native.py` """ + # Terminate incomplete background commands at the same time + tasks = [ + asyncio.create_task(self.async_cleanup_pid(pid, is_pgroup=True, proc=bg.p)) + for pid, bg in self.background_cmds.items() + ] + self.logger.debug("%s: killing %s background cmds", self, len(tasks)) + results = await asyncio.gather(*tasks, return_exceptions=True) + + # Check status individually to better support logging + for rv, (pid, bg) in zip(results, list(self.background_cmds.items())): + del self.background_cmds[pid] + if isinstance(rv, BaseException): + self.logger.error("%s: Process %s failed with %s", self, pid, rv) + else: + self.logger.debug("%s: Process %s exited with %s", self, pid, rv) + bg.close_files() + self.logger.info("%s: deleted", self) async def async_delete(self): @@ -2603,7 +2959,7 @@ async def _async_delete(self): self.pid, self.p.pid if self.p else None, ) - await self.cleanup_pid(self.pid) + await self.async_cleanup_pid(self.pid) if self.p is not None: self.logger.debug("cleanup namespace proc pid %s", self.p.pid) diff --git a/munet/native.py b/munet/native.py index acc5d0e..32134e0 100644 --- a/munet/native.py +++ b/munet/native.py @@ -3507,6 +3507,32 @@ async def load_images(self, images): _, pending = await asyncio.wait(tasks, timeout=600) assert not pending, "Failed to pull container images" + def start_pcap(self, pcap, in_window=False): + """Start a packet capture on a target. + + Accepts NODE:INTF or NETWORK as targets + """ + if ":" in pcap: + host, intf = pcap.split(":") + pcap = f"{host}-{intf}" + host = self.hosts[host] + else: + host = self + intf = pcap + capfile = f"capture-{pcap}.pcap" + caplogfile = f"capture-{pcap}.log" + self.logger.info("%s: starting pcap (%s)", self, capfile) + host.background_cmd_start( + f"tshark -s 9200 -i {intf} -Pl -w {capfile} > {caplogfile} 2>&1", + ) + if in_window: + host.run_in_window( + f"tail -F {caplogfile}", + background=True, + title=f"cap:{pcap}", + ) + return capfile + async def run(self): tasks = [] hosts = self.hosts.values() @@ -3529,18 +3555,7 @@ async def run(self): pcapopt.update(self.switches.keys()) if pcapopt: for pcap in pcapopt: - if ":" in pcap: - host, intf = pcap.split(":") - pcap = f"{host}-{intf}" - host = self.hosts[host] - else: - host = self - intf = pcap - host.run_in_window( - f"tshark -s 9200 -i {intf} -P -w capture-{pcap}.pcap", - background=True, - title=f"cap:{pcap}", - ) + self.start_pcap(pcap, in_window=True) if launch_nodes: # would like a info when verbose here. diff --git a/munet/testing/fixtures.py b/munet/testing/fixtures.py index d32cc81..0239891 100644 --- a/munet/testing/fixtures.py +++ b/munet/testing/fixtures.py @@ -173,7 +173,11 @@ def rundir_module(): async def _unet_impl( - _rundir, _pytestconfig, unshare=None, top_level_pidns=None, param=None + _rundir, + _pytestconfig, + unshare=None, + top_level_pidns=None, + param=None ): try: # Default is not to unshare inline if not specified otherwise @@ -223,8 +227,11 @@ async def _unet_impl( except Exception as error: logging.error("unet fixture: yield unet unexpected exception: %s", error) - logging.debug("unet fixture: module done, deleting unet") - await _unet.async_delete() + if not _unet.deleting: + logging.debug("unet fixture: module done, deleting unet") + await _unet.async_delete() + else: + logging.debug("unet fixture: module done, unet already deleted") # No one ever awaits these so cancel them logging.debug("unet fixture: cleanup") @@ -252,6 +259,28 @@ async def unet(request, rundir_module, pytestconfig): # pylint: disable=W0621 yield x +@pytest.fixture(scope="function") +async def unet_function(request, rundir_module, pytestconfig): # pylint: disable=W0621 + """A unet creating fixture. + + This variant of the unet module is function-scoped. It is intendedd for test cases + where either fresh topologies are required or the topology will be destructively + altered (such as destroying it early). + + The request param is either the basename of the config file or a tuple of the form: + (basename, unshare, top_level_pidns), with the second and third elements boolean and + optional, defaulting to False, True. + + Note: This is NOT a module-level fixture. The topology exiss only for the single + function scope. + """ + param = request.param if hasattr(request, "param") else None + sdir = os.path.dirname(os.path.realpath(request.fspath)) + async with achdir(sdir, "unet_teardown fixture"): + async for x in _unet_impl(rundir_module, pytestconfig, param=param): + yield x + + @pytest.fixture(scope="module") async def unet_share(request, rundir_module, pytestconfig): # pylint: disable=W0621 """A unet creating fixutre. diff --git a/tests/background/munet.yaml b/tests/background/munet.yaml new file mode 100644 index 0000000..1c8b4d0 --- /dev/null +++ b/tests/background/munet.yaml @@ -0,0 +1,15 @@ +version: 1 +topology: + networks-autonumber: true + loopbacks-autonumber: true + networks: + - name: net0 + nodes: + - name: r1 + connections: + - to: net0 + name: eth1 + - name: r2 + connections: + - to: net0 + name: eth2 diff --git a/tests/background/test_background.py b/tests/background/test_background.py new file mode 100644 index 0000000..a549f98 --- /dev/null +++ b/tests/background/test_background.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 eval: (blacken-mode 1) -*- +# SPDX-License-Identifier: GPL-2.0-or-later +# +# September 03 2026, Liam Brady +# +# Copyright 2026, LabN Consulting, L.L.C. +# +"Testing of basic background command API." + + +import asyncio +import pytest + +# All tests are coroutines +pytestmark = pytest.mark.asyncio + + +async def test_background_capture(unet): + r1 = unet.hosts["r1"] + r2 = unet.hosts["r2"] + + oifname = 'eth2' + oip = r2.get_intf_addr(oifname).ip + pid = r1.background_cmd_start(f"ping -i 0.1 {oip}") + + rv, out, _ = await r2.async_cmd_status("tshark -i any -c 3 -f icmp") + assert rv == 0 + assert "Echo (ping) request" in out + + rv, out, _ = r1.background_cmd_end_status(pid, timeout=5) + + assert rv != 0 # This process was forcefully terminated! + assert "bytes from 10.0.1.2" in out + + +async def test_background_early_finish(unet): + r2 = unet.hosts["r2"] + + pid = r2.background_cmd_start("echo foo") + + await asyncio.sleep(1) + + rv, out, _ = r2.background_cmd_end_status(pid, timeout=5) + assert rv == 0 # This process exited normally! + assert "foo" in out + + +async def test_background_stdin(unet): + r2 = unet.hosts["r2"] + + pid = r2.background_cmd_start("cat", stdin="hello world") + + await asyncio.sleep(1) + + rv, out, _ = r2.background_cmd_end_status(pid, timeout=5) + assert rv == 0 # This process was forcefully terminated! + assert "hello world" in out + + +async def test_background_pcaps(unet): + r1 = unet.hosts["r1"] + r2 = unet.hosts["r2"] + + r1cap = unet.start_pcap("r1:eth1") + r2cap = unet.start_pcap("r2:eth2") + netcap = unet.start_pcap("net0") + + oifname = 'eth2' + oip = r2.get_intf_addr(oifname).ip + await r1.async_cmd_status(f"ping -i 0.1 {oip} -c 10") + + _, o, _ = r1.cmd_status(f"tshark -r {r1cap}") + assert "Echo (ping) request" in o + _, o, _ = r2.cmd_status(f"tshark -r {r2cap}") + assert "Echo (ping) request" in o + _, o, _ = unet.cmd_status(f"tshark -r {netcap}") + assert "Echo (ping) request" in o diff --git a/tests/background/test_background_cleanup.py b/tests/background/test_background_cleanup.py new file mode 100644 index 0000000..dc9c90a --- /dev/null +++ b/tests/background/test_background_cleanup.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 eval: (blacken-mode 1) -*- +# SPDX-License-Identifier: GPL-2.0-or-later +# +# September 03 2026, Liam Brady +# +# Copyright 2026, LabN Consulting, L.L.C. +# +"Testing of basic background command API automatic cleanup." + + +import asyncio +import os +import signal +from pathlib import Path + +import pytest + +# All tests are coroutines +pytestmark = pytest.mark.asyncio + + +async def test_background_process_cleanup(unet_function): + unet = unet_function + r1 = unet.hosts["r1"] + + pid = r1.background_cmd_start("ping 10.0.1.2 -i 0.1") + + await asyncio.sleep(1) + + # Ensure that process still exists + os.kill(pid, 0) + + # We let the munet topology clean up the background command. + await unet.async_delete() + + assert len(unet.background_cmds) == 0 + + try: + os.kill(pid, 0) + except ProcessLookupError: + pass + else: + assert False, f"Process {pid} survived cleanup" + + +@pytest.mark.parametrize("parent_waits", [True, False]) +async def test_background_process_group_cleanup(unet_function, parent_waits): + unet = unet_function + r1 = unet.hosts["r1"] + + heartbeat_file = f"/tmp/unet_child_heartbeat_{parent_waits}.log" + pid = r1.background_cmd_start( + f"""(while true; do date +%s%N > {heartbeat_file}; sleep 0.1; done) & """ + f"""wait""" + ) + + await asyncio.sleep(1) + + # Ensure that process and pgroup still exists + os.kill(pid, 0) + pgid = os.getpgid(pid) + assert pgid != os.getpgrp() + assert pgid == os.getpgid(pid) + os.killpg(pgid, 0) + + # Force child to become an orphan process + if parent_waits: + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + + # Ensure that the orphan child is still running + for _ in range(50): + if os.path.exists(heartbeat_file): + break + await asyncio.sleep(0.1) + assert os.path.exists(heartbeat_file), "Child never started" + + before = Path(heartbeat_file).read_text(encoding="utf-8").strip() + await asyncio.sleep(0.5) + after = Path(heartbeat_file).read_text(encoding="utf-8").strip() + assert after != before + + # We let the munet topology clean up the background command. + await unet.async_delete() + + assert len(unet.background_cmds) == 0 + + try: + os.killpg(pid, 0) + except ProcessLookupError: + pass + else: + assert False, f"Process group {pid} survived cleanup" + + # Ensure that the orphan child has died + before = Path(heartbeat_file).read_text(encoding="utf-8").strip() + await asyncio.sleep(0.5) + after = Path(heartbeat_file).read_text(encoding="utf-8").strip() + assert after == before, "Child process survived cleanup" diff --git a/tests/background/test_background_status_extra.py b/tests/background/test_background_status_extra.py new file mode 100644 index 0000000..18ec261 --- /dev/null +++ b/tests/background/test_background_status_extra.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 eval: (blacken-mode 1) -*- +# SPDX-License-Identifier: GPL-2.0-or-later +# +# November 02 2026, Liam Brady +# +# Copyright 2026, LabN Consulting, L.L.C. +# +"""Additional background-command tests related to return codes.""" + +import sys + +import pytest + +from munet.base import CalledProcessError + +# All tests are coroutines +pytestmark = pytest.mark.asyncio + +@pytest.mark.parametrize("exit_code", [0, 23]) +async def test_background_cmd_end_with_status(unet, exit_code): + pid = unet.background_cmd_start( + [sys.executable, "-c", f"import sys; print('result'); sys.exit({exit_code})"] + ) + bg = unet.background_cmds[pid] + try: + # Premtively reaps the process. Subprocesses should + # preserve the return value into the end_status call. + assert bg.p.wait(timeout=3) == exit_code + + # Intentionally omit the timeout keyword. + rv, stdout, stderr = unet.background_cmd_end_status(pid) + assert rv == exit_code + assert "result" in stdout + assert not stderr + assert pid not in unet.background_cmds + assert bg.stdin_file.closed + assert bg.stdout_file.closed + assert bg.stderr_file.closed + finally: + if pid in unet.background_cmds: + try: + unet.background_cmd_end_status(pid, timeout=0.3) + except Exception: + pass + + +async def test_background_cmd_end_with_raises(unet): + pid = unet.background_cmd_start( + [sys.executable, "-c", "import sys; print('bad'); sys.exit(23)"] + ) + bg = unet.background_cmds[pid] + try: + assert bg.p.wait(timeout=3) == 23 + with pytest.raises(CalledProcessError) as caught: + unet.background_cmd_end_raises(pid) + assert caught.value.returncode == 23 + assert "bad" in caught.value.output + assert pid not in unet.background_cmds + finally: + if pid in unet.background_cmds: + try: + unet.background_cmd_end_status(pid, timeout=0.3) + except Exception: + pass + + +async def test_background_cmd_end_when_running(unet): + pid = unet.background_cmd_start( + [sys.executable, "-c", "import time; time.sleep(60)"] + ) + try: + # Exercises the default timeout while the child still needs signalling. + rv, _, _ = unet.background_cmd_end_status(pid) + assert rv in (-1, -9) # SIGHUP or SIGKILL + finally: + if pid in unet.background_cmds: + try: + unet.background_cmd_end_status(pid, timeout=0.3) + except Exception: + pass diff --git a/tests/background/test_cleanup_pid.py b/tests/background/test_cleanup_pid.py new file mode 100644 index 0000000..530400b --- /dev/null +++ b/tests/background/test_cleanup_pid.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 eval: (blacken-mode 1) -*- +# SPDX-License-Identifier: GPL-2.0-or-later +# +# November 02 2026, Liam Brady +# +# Copyright 2026, LabN Consulting, L.L.C. +# +"""Regression tests for Commander PID, process, and process-group cleanup.""" + +import asyncio +import os +import select +import signal +import subprocess +import sys +import time + +import pytest + +from munet.base import Commander, Timeout + +# pylint: disable=redefined-outer-name + +@pytest.fixture +def commander(): + """A Commander needs no network topology for process cleanup.""" + return Commander("cleanup-tests") + + +def _python(code, *args): + return [sys.executable, "-u", "-c", code, *map(str, args)] + + +def _stop_sync(proc): + """Avoid leaking test subprocesses if an assertion fails.""" + if proc.poll() is None: + proc.kill() + proc.wait(timeout=3) + if proc.stdout is not None: + proc.stdout.close() + if proc.stderr is not None: + proc.stderr.close() + + +async def _stop_async(proc): + if proc.returncode is None: + try: + proc.kill() + except ProcessLookupError: + pass + await asyncio.wait_for(proc.wait(), timeout=3) + + +def _sync_readline(proc, timeout=3): + ready, _, _ = select.select([proc.stdout], [], [], timeout) + assert ready, f"process {proc.pid} did not produce a line" + return proc.stdout.readline() + + +def _wait_unreaped(pid, timeout=3): + """Observe child exit without consuming its wait status (Linux).""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + info = os.waitid( + os.P_PID, + pid, + os.WEXITED | os.WNOHANG | os.WNOWAIT, + ) + if info is not None: + return + time.sleep(0.01) + pytest.fail(f"child {pid} did not exit") + + +async def test_timeout_zero_runs_once(): + assert list(Timeout(0)) == [0] + assert list(Timeout(-1)) == [0] + + +@pytest.mark.parametrize("exit_code", [0, 42]) +@pytest.mark.parametrize("async_cleanup", [False, True]) +async def test_cleanup_pid_already_reaped_popen(commander, exit_code, async_cleanup): + proc = subprocess.Popen(_python(f"import sys; sys.exit({exit_code})")) + try: + assert proc.wait(timeout=3) == exit_code + if async_cleanup: + rv = await commander.async_cleanup_pid(proc.pid, proc=proc, wait_sec=0) + else: + rv = commander.cleanup_pid(proc.pid, proc=proc, wait_sec=0) + assert rv == exit_code + assert proc.returncode == exit_code + finally: + _stop_sync(proc) + + +@pytest.mark.parametrize("exit_code", [0, 42]) +async def test_cleanup_pid_already_reaped_asyncio(commander, exit_code): + proc = await asyncio.create_subprocess_exec( + *_python(f"import sys; sys.exit({exit_code})") + ) + try: + assert await asyncio.wait_for(proc.wait(), timeout=3) == exit_code + rv = await commander.async_cleanup_pid(proc.pid, proc=proc, wait_sec=0) + assert rv == exit_code + finally: + await _stop_async(proc) + + +@pytest.mark.parametrize("async_cleanup", [False, True]) +@pytest.mark.parametrize("ignore_hup", [False, True]) +async def test_cleanup_pid_signal_exit_status( + commander, async_cleanup, ignore_hup +): + code = ( + "import signal, time\n" + + ( + "signal.signal(signal.SIGHUP, signal.SIG_IGN)\n" + if ignore_hup + else "signal.signal(signal.SIGHUP, signal.SIG_DFL)\n" + ) + + "print('READY', flush=True)\n" + + "while True: time.sleep(1)\n" + ) + proc = subprocess.Popen( + _python(code), stdout=subprocess.PIPE, text=True + ) + try: + # The child has installed its signal handling before we send SIGHUP. + assert _sync_readline(proc).strip() == "READY" + if async_cleanup: + rv = await commander.async_cleanup_pid( + proc.pid, proc=proc, wait_sec=0.3 + ) + else: + rv = commander.cleanup_pid(proc.pid, proc=proc, wait_sec=0.3) + expected = -signal.SIGKILL if ignore_hup else -signal.SIGHUP + assert rv == expected + assert proc.returncode == expected + finally: + _stop_sync(proc) + + +@pytest.mark.parametrize("exit_code", [0, 37]) +def test_reap_pid_popen(commander, exit_code): + proc = subprocess.Popen(_python(f"import sys; sys.exit({exit_code})")) + try: + assert proc.wait(timeout=3) == exit_code + assert commander.reap_pid(proc.pid, proc) == (True, exit_code) + finally: + _stop_sync(proc) + + +@pytest.mark.parametrize("exit_code", [0, 37]) +async def test_reap_pid_asyncio(commander, exit_code): + proc = await asyncio.create_subprocess_exec( + *_python(f"import sys; sys.exit({exit_code})") + ) + try: + assert await asyncio.wait_for(proc.wait(), timeout=3) == exit_code + assert commander.reap_pid(proc.pid, proc) == (True, exit_code) + finally: + await _stop_async(proc) + + +@pytest.mark.skipif(not hasattr(os, "WNOWAIT"), reason="requires waitid/WNOWAIT") +@pytest.mark.parametrize("exit_code", [0, 37]) +def test_reap_pid_raw_waitpid(commander, exit_code): + # Do not call Popen.wait/poll: reap_pid is the sole waiter here. + proc = subprocess.Popen(_python(f"import sys; sys.exit({exit_code})")) + try: + _wait_unreaped(proc.pid) + assert commander.reap_pid(proc.pid) == (True, exit_code) + assert commander.reap_pid(proc.pid) == (True, None) # ECHILD + finally: + _stop_sync(proc) + + +async def test_cleanup_pid_rejects_mismatched_popen(commander): + proc = subprocess.Popen(_python("pass")) + try: + with pytest.raises(ValueError, match="proc.pid"): + commander.cleanup_pid(proc.pid + 1, proc=proc) + with pytest.raises(ValueError, match="proc.pid"): + await commander.async_cleanup_pid(proc.pid + 1, proc=proc) + finally: + _stop_sync(proc) + + +async def test_sync_cleanup_pid_rejects_asyncio(commander): + proc = await asyncio.create_subprocess_exec(*_python("pass")) + try: + with pytest.raises(ValueError, match="Async process"): + commander.cleanup_pid(proc.pid, proc=proc) + finally: + await _stop_async(proc) + + +@pytest.mark.parametrize("kind", ["popen", "asyncio"]) +async def test_async_cleanup_proc_different_signal_pid(commander, kind): + # An nsenter-like wrapper waits for its child. The signal must go to the + # child, while the wrapper's Popen/asyncio Process owns reaping. + wrapper = """ +import subprocess +import sys +child = subprocess.Popen( + [sys.executable, '-c', 'import time; time.sleep(60)'], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, +) +print(child.pid, flush=True) +child.wait() +""" + if kind == "popen": + proc = subprocess.Popen( + _python(wrapper), stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, start_new_session=True + ) + else: + proc = await asyncio.create_subprocess_exec( + *_python(wrapper), stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, start_new_session=True + ) + + try: + if kind == "popen": + child_pid = int(_sync_readline(proc).strip()) + else: + line = await asyncio.wait_for(proc.stdout.readline(), 3) + child_pid = int(line.strip()) + assert child_pid != proc.pid + result = await asyncio.wait_for( + commander.async_cleanup_proc(proc, pid=child_pid), timeout=5 + ) + assert result is None + assert proc.returncode == 0 + finally: + # Safely kill the wrapper and any surviving descendants together. + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kind == "popen": + _stop_sync(proc) + else: + await _stop_async(proc) + + +@pytest.mark.parametrize("kind", ["popen", "asyncio"]) +async def test_async_cleanup_proc_direct_process(commander, kind): + code = ( + "import signal, time\n" + "signal.signal(signal.SIGHUP, signal.SIG_DFL)\n" + "print('READY', flush=True)\n" + "while True: time.sleep(1)\n" + ) + if kind == "popen": + proc = subprocess.Popen( + _python(code), stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True + ) + else: + proc = await asyncio.create_subprocess_exec( + *_python(code), stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE + ) + + try: + if kind == "popen": + assert _sync_readline(proc).strip() == "READY" + else: + line = await asyncio.wait_for(proc.stdout.readline(), 3) + assert line.strip() == b"READY" + assert await asyncio.wait_for(commander.async_cleanup_proc(proc), 5) is None + assert proc.returncode == -signal.SIGHUP + finally: + if kind == "popen": + _stop_sync(proc) + else: + await _stop_async(proc) From 71f955e996d91827d1efcb422946a4e78486a09f Mon Sep 17 00:00:00 2001 From: Liam Brady Date: Mon, 2 Nov 2026 13:40:09 -0500 Subject: [PATCH 2/2] mutest: background step API Background steps are started with background_start(). The provided cmd runs in the background while execution continues on with the next mutest step. Running cmds can be ended with the background_* variant of the familiar mutest step API. Such steps interrupt or terminate the cmd if it hasn't yet ended. Signed-off-by: Liam Brady --- doc/source/mutest.rst | 42 ++ munet/mutest/userapi.py | 426 ++++++++++++++++++-- tests/mutest/mutest_matchwait_background.py | 362 +++++++++++++++++ 3 files changed, 790 insertions(+), 40 deletions(-) create mode 100644 tests/mutest/mutest_matchwait_background.py diff --git a/doc/source/mutest.rst b/doc/source/mutest.rst index 4ca1be6..b306b82 100644 --- a/doc/source/mutest.rst +++ b/doc/source/mutest.rst @@ -119,6 +119,10 @@ used to check that the state of the interface actually changes. step("r1", 'vtysh -c "conf t\n interface eth0\n shut"') match_step("r1", 'vtysh -c "show interface eth0", "DOWN", "Check for interface DOWN") + +JSON Commands +~~~~~~~~~~~~~~~~~~~ + Additionally, json variants of various functions are also available, namely :py:func:`match_step_json`, :py:func:`wait_step_json`, and :py:func:`step_json`. These json variants compare a json value ``match`` with the json result from ``cmd``. @@ -212,5 +216,43 @@ When ``exact_match`` is ``True``, the comparison will only succeed when all data in ``match`` is present in the ``cmd`` result *and* all data present in the ``cmd`` result is present in ``match``. In other words they exactly match. + +Background Commands +~~~~~~~~~~~~~~~~~~~ + +Mutest supports running commands in the background, allowing other test steps to +execute while the command remains active. This is useful for monitoring traffic, +collecting logs, or running commands whose output depends on subsequent test +operations. + +Use :py:func:`background_start()` to launch a command and obtain its host process ID +(PID). The command can later be terminated and its output evaluated using one of +the following functions: + +- :py:func:`background_step()` — Terminates the command and returns its captured output. +- :py:func:`background_match_step()` — Terminates the command and matches its output against a regular expression. +- :py:func:`background_step_json()` — Terminates the command and returns its output as parsed JSON. +- :py:func:`background_match_step_json()` — Terminates the command and compares its JSON output against an expected value. + +For example: + +.. code-block:: python + + pid = background_start("r1", "tcpdump -i eth0 -n") + + step("r2", "ping -c 5 10.0.0.1") + + background_match_step( + pid, + r"5 packets captured", + "Verify captured traffic", + ) + +**Each background command can be completed only once.** Calling any background +step terminates the command and consumes its PID, preventing further +background-step operations on that command. Background commands that are never +explicitly completed are automatically cleaned up when the owning munet topology +is deleted. + To see all the available functions and their specifications see :ref:`mutest-api`. diff --git a/munet/mutest/userapi.py b/munet/mutest/userapi.py index b50d082..76b2b32 100644 --- a/munet/mutest/userapi.py +++ b/munet/mutest/userapi.py @@ -23,6 +23,14 @@ - :py:func:`wait_step_json` + - :py:func:`background_start` + + - :py:func:`background_step` + + - :py:func:`background_match_step` + + - :py:func:`background_match_step_json` + Control/Utility functions: - :py:func:`script_dir` @@ -219,6 +227,7 @@ def __init__( self.__in_section = False self.targets = targets + self.background_targets = {} self.args = args self.last = "" @@ -440,6 +449,60 @@ def __end_test(self) -> (int, int): self.info.run_time = time.time() - self.info.start_time return passed, failed + def _command_finish( + self, + cmd_out, + ) -> str: + """Finish running a ``cmd``. + + Args: + cmd_out: the raw command output. + """ + self.last = cmd_out = cmd_out.rstrip() + report = cmd_out if cmd_out else "" + self.logf("COMMAND OUTPUT:\n%s", report) + return cmd_out + + def _command_finish_json( + self, + cmd_out, + ) -> Union[list, dict]: + """Finish running a json ``cmd`` and prepare json result. + + Args: + cmd_out: the raw command output. + """ + self.last = cmd_out = cmd_out.rstrip() + try: + js = json.loads(cmd_out) + except Exception as error: + js = None + self.olog.warning( + "JSON load failed. Check command output is in JSON format: %s", + error, + ) + self.logf("COMMAND OUTPUT:\n%s", cmd_out) + return js + + def _background_command_start( + self, + target: str, + cmd: str, + ) -> int: + """Start a ``cmd`` and return the pid. + + Args: + target: the target to execute the command on. + cmd: string to execut on the target. + """ + pid = self.targets[target].background_cmd_start( + cmd, stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT + ) + self.background_targets[pid] = target + self.last = "" + self.logf("COMMAND STARTED: pid%s", pid) + return pid + def _command( self, target: str, @@ -454,10 +517,7 @@ def _command( out = self.targets[target].cmd_nostatus( cmd, stdin=subprocess.DEVNULL, warn=False ) - self.last = out = out.rstrip() - report = out if out else "" - self.logf("COMMAND OUTPUT:\n%s", report) - return out + return self._command_finish(out) def _command_json( self, @@ -473,32 +533,74 @@ def _command_json( out = self.targets[target].cmd_nostatus( cmd, stdin=subprocess.DEVNULL, warn=False ) - self.last = out = out.rstrip() + return self._command_finish_json(out) + + def _background_command_end( + self, + pid: int, + ) -> (str, str): + """Finish a ``cmd`` and return result. + + Args: + pid: background cmd pid + """ + target = self.background_targets.pop(pid, None) + if target is None: + raise KeyError(f"Unknown background command PID: {pid}") + try: - js = json.loads(out) - except Exception as error: - js = None + _, out, _ = self.targets[target].background_cmd_end_status( + pid, warn=False + ) + except TimeoutError as error: self.olog.warning( - "JSON load failed. Check command output is in JSON format: %s", + "Failed to terminate background command: %s", error, ) - self.logf("COMMAND OUTPUT:\n%s", out) - return js + cmd_out = None + else: + cmd_out = self._command_finish(out) + return target, cmd_out - def _match_command( + def _background_command_end_json( self, - target: str, - cmd: str, + pid: int, + ) -> (str, Union[list, dict]): + """Finish a json ``cmd`` and return json result. + + Args: + pid: background cmd pid + """ + target = self.background_targets.pop(pid, None) + if target is None: + raise KeyError(f"Unknown background command PID: {pid}") + + try: + _, out, _ = self.targets[target].background_cmd_end_status( + pid, warn=False + ) + except TimeoutError as error: + self.olog.warning( + "Failed to terminate background json command: %s", + error, + ) + cmd_out = None + else: + cmd_out = self._command_finish_json(out) + return target, cmd_out + + def _match_output( + self, + cmd_out: str, match: str, expect_fail: bool, flags: int, exact_match: bool, ) -> (bool, Union[str, list]): - """Execute a ``cmd`` and check result. + """Match and check result from a ``cmd``. Args: - target: the target to execute the command on. - cmd: string to execute on the target. + out: command output match: regex to ``re.search()`` for in output. expect_fail: if True then succeed when the regexp doesn't match. flags: python regex flags to modify matching behavior @@ -510,9 +612,12 @@ def _match_command( otherwise if there were matching groups then groups() will be returned in ``matches`` otherwise group(0) (i.e., the matching text). """ - out = self._command(target, cmd) + if cmd_out is None: + # Always fail on bad cmd output, even if user expected failure + return False, None + if exact_match: - if match not in out: + if match not in cmd_out: success = expect_fail ret = None else: @@ -522,7 +627,7 @@ def _match_command( self.olog.log(level, "exactly matched:%s:", ret) return success, ret - search = re.search(match, out, flags) + search = re.search(match, cmd_out, flags) self.last_m = search if search is None: success = expect_fail @@ -537,26 +642,23 @@ def _match_command( self.olog.log(level, "matched:%s:", ret) return success, ret - def _match_command_json( + def _match_output_json( self, - target: str, - cmd: str, + cmd_out_js: Union[list, dict], match: Union[str, list, dict], expect_fail: bool, exact_match: bool, ) -> (bool, Union[list, dict]): - """Execute a json ``cmd`` and check result. + """Match and check json result from a json ``cmd``. Args: - target: the target to execute the command on. - cmd: string to execut on the target. + cmd_out_js: json command output match: A json ``str``, object (``dict``), or array (``list``) to compare against the json output from ``cmd``. expect_fail: if True then succeed when the json doesn't match. exact_match: if True then the json must exactly match. """ - js = self._command_json(target, cmd) - if js is None: + if cmd_out_js is None: # Always fail on bad json, even if user expected failure # return expect_fail, {} return False, {} @@ -576,13 +678,13 @@ def _match_command_json( return False, {} if exact_match: - deep_diff = json_cmp(expect, js) + deep_diff = json_cmp(expect, cmd_out_js) # Convert DeepDiff completely into dicts or lists at all levels json_diff = json.loads(deep_diff.to_json()) else: deep_diff = json_cmp( expect, - js, + cmd_out_js, ignore_order=True, cutoff_intersection_for_pairs=1, cutoff_distance_for_pairs=1, @@ -607,7 +709,7 @@ def _match_command_json( return success, json_diff success = not expect_fail - return success, js + return success, cmd_out_js def _wait( self, @@ -638,12 +740,14 @@ def _wait( ret = None while not success and time.time() < endt: if is_json: - success, ret = self._match_command_json( - target, cmd, match, expect_fail, exact_match + js = self._command_json(target, cmd) + success, ret = self._match_output_json( + js, match, expect_fail, exact_match ) else: - success, ret = self._match_command( - target, cmd, match, expect_fail, flags, exact_match + out = self._command(target, cmd) + success, ret = self._match_output( + out, match, expect_fail, flags, exact_match ) if not success: time.sleep(interval) @@ -799,7 +903,8 @@ def step_json(self, target: str, cmd: str) -> Union[list, dict]: target, cmd, ) - return self._command_json(target, cmd) + js = self._command_json(target, cmd) + return {} if js is None else js def match_step( self, @@ -828,8 +933,9 @@ def match_step( flags, exact_match, ) - success, ret = self._match_command( - target, cmd, match, expect_fail, flags, exact_match + out = self._command(target, cmd) + success, ret = self._match_output( + out, match, expect_fail, flags, exact_match ) if desc: self.__post_result(target, success, desc) @@ -871,8 +977,9 @@ def match_step_json( expect_fail, exact_match, ) - success, ret = self._match_command_json( - target, cmd, match, expect_fail, exact_match + js = self._command_json(target, cmd) + success, ret = self._match_output_json( + js, match, expect_fail, exact_match, ) if desc: self.__post_result(target, success, desc) @@ -967,6 +1074,117 @@ def wait_step_json( act_on_result(success, self.args, desc) return success, ret + def background_start(self, target: str, cmd: str) -> int: + """See :py:func:`~munet.mutest.userapi.background_start`. + + :meta private: + """ + self.logf( + "#%s.%s:%s:BACKGROUND_START:%s:%s", + self.tag, + self.steps + 1, + self.info.path, + target, + cmd, + ) + return self._background_command_start(target, cmd) + + def background_step(self, pid: int) -> str: + """See :py:func:`~munet.mutest.userapi.background_step`. + + :meta private: + """ + self.logf( + "#%s.%s:%s:BACKGROUND_STEP:%s", + self.tag, + self.steps + 1, + self.info.path, + pid, + ) + _, out = self._background_command_end(pid) + return out + + def background_step_json(self, pid: int) -> Union[dict, list]: + """See :py:func:`~munet.mutest.userapi.background_step_json`. + + :meta private: + """ + self.logf( + "#%s.%s:%s:BACKGROUND_STEP_JSON:%s", + self.tag, + self.steps + 1, + self.info.path, + pid, + ) + _, js = self._background_command_end_json(pid) + return {} if js is None else js + + def background_match_step( + self, + pid: int, + match: str, + desc: str = "", + expect_fail: bool = False, + flags: int = re.DOTALL, + exact_match: bool = False, + ) -> (bool, Union[str, list]): + """See :py:func:`~munet.mutest.userapi.background_match_step`. + + :meta private: + """ + self.logf( + "#%s.%s:%s:BACKGROUND_MATCH_STEP:%s:%s:%s:%s:%s:%s", + self.tag, + self.steps + 1, + self.info.path, + pid, + match, + desc, + expect_fail, + flags, + exact_match, + ) + target, out = self._background_command_end(pid) + success, ret = self._match_output( + out, match, expect_fail, flags, exact_match + ) + if desc: + self.__post_result(target, success, desc) + act_on_result(success, self.args, desc) + return success, ret + + def background_match_step_json( + self, + pid: int, + match: Union[str, list, dict], + desc: str = "", + expect_fail: bool = False, + exact_match: bool = False, + ) -> (bool, Union[list, dict]): + """See :py:func:`~munet.mutest.userapi.background_match_step_json`. + + :meta private: + """ + self.logf( + "#%s.%s:%s:BACKGROUND_MATCH_STEP_JSON:%s:%s:%s:%s:%s", + self.tag, + self.steps + 1, + self.info.path, + pid, + match, + desc, + expect_fail, + exact_match, + ) + target, js = self._background_command_end_json(pid) + success, ret = self._match_output_json( + js, match, expect_fail, exact_match + ) + if desc: + self.__post_result(target, success, desc) + act_on_result(success, self.args, desc) + return success, ret + # A non-rentrant global to allow for simplified operations TestCase.g_tc = None @@ -1253,6 +1471,134 @@ def wait_step_json( ) +def background_start(target: str, cmd: str) -> int: + """Start executing a ``cmd`` on a ``target`` in the background. + + Args: + target: the target to execute the ``cmd`` on. + cmd: string to execute on the target. + + Returns: + Returns the ``int`` pid of the ``cmd``. + """ + return TestCase.g_tc.background_start(target, cmd) + + +def background_step(pid: int) -> str: + """End a background ``cmd`` and return the output. + + Args: + pid: the pid of the ``cmd`` returned by background_start() + + Returns: + Returns the ``str`` output of the ``cmd``. + + Raises: + KeyError: If the PID is unknown or the background command + is no longer being tracked. + """ + return TestCase.g_tc.background_step(pid) + + +def background_step_json(pid: int) -> Union[list, dict]: + """End a background json ``cmd`` and return the json object or array. + + Args: + pid: the pid of the ``cmd`` returned by background_start() + + Returns: + Returns the json object or array after parsing the ``cmd`` output. + + If json parse fails, a warning is logged and an empty ``dict`` is used. + + Raises: + KeyError: If the PID is unknown or the background command + is no longer being tracked. + """ + return TestCase.g_tc.background_step_json(pid) + + +def background_match_step( + pid: int, + match: str, + desc: str = "", + expect_fail: bool = False, + flags: int = re.DOTALL, + exact_match: bool = False, +) -> (bool, Union[str, list]): + """End a background ``cmd`` and check result. + + End a background ``cmd`` and check if the regexp in ``match`` matches + or doesn't match (according to the ``expect_fail`` value) the ``cmd`` + output. + + If the ``match`` regexp includes groups and if the match succeeds + the group values will be returned in a list, otherwise the command + output is returned. + + Args: + pid: the pid of the ``cmd`` returned by background_start() + match: regex to match against output. + desc: description of test, if no description then step failure is not + considered an error and no result is logged. + expect_fail: if True then succeed when the regexp doesn't match. + flags: python regex flags to modify matching behavior + exact_match: if True then ``match`` must be exactly matched somewhere + in the output of ``cmd`` using ``str.find()``. + + Returns: + Returns a 2-tuple. The first value is a bool indicating ``success``. + The second value will be a list from ``re.Match.groups()`` if non-empty, + otherwise ``re.Match.group(0)`` if there was a match otherwise None. + + Raises: + KeyError: If the PID is unknown or the background command + is no longer being tracked. + """ + return TestCase.g_tc.background_match_step( + pid, match, desc, expect_fail, flags, exact_match + ) + + +def background_match_step_json( + pid: int, + match: Union[str, list, dict], + desc: str = "", + expect_fail: bool = False, + exact_match: bool = False, +) -> (bool, Union[list, dict]): + """End a background json ``cmd`` and check result. + + End a ``cmd`` and check if the json object or array in ``match`` + matches or doesn't match (according to the ``expect_fail`` value) the + json output from ``cmd``. + + Args: + pid: the pid of the ``cmd`` returned by background_start() + match: A json ``str``, object (``dict``), or array (``list``) to compare + against the json output from ``cmd``. + desc: description of test, if no description then step failure is not + considered an error and no result is logged. + expect_fail: if True then succeed if the a json doesn't match. + exact_match: if True then the json must exactly match. + + Returns: + Returns a 2-tuple. The first value is a bool indicating ``success``. The + second value is a ``dict`` of the diff if there is a difference found in + the json compare, otherwise the value is the json object (``dict``) or + array (``list``) from the ``cmd``. + + If json parse fails, a warning is logged and an empty ``dict`` is used. + + Raises: + KeyError: If the PID is unknown or the background command + is no longer being tracked. + """ + return TestCase.g_tc.background_match_step_json( + pid, match, desc, expect_fail, exact_match + ) + + def luInclude(filename, CallOnFail=None): """Backward compatible API, do not use in new tests.""" return include(filename) diff --git a/tests/mutest/mutest_matchwait_background.py b/tests/mutest/mutest_matchwait_background.py new file mode 100644 index 0000000..356eae0 --- /dev/null +++ b/tests/mutest/mutest_matchwait_background.py @@ -0,0 +1,362 @@ +"""Test background command steps and send/expect functionality.""" + +import re +import shlex +import uuid + +from munet.mutest.userapi import background_match_step +from munet.mutest.userapi import background_match_step_json +from munet.mutest.userapi import background_start +from munet.mutest.userapi import background_step +from munet.mutest.userapi import background_step_json +from munet.mutest.userapi import section +from munet.mutest.userapi import step +from munet.mutest.userapi import test_step +from munet.mutest.userapi import wait_step + + +section("Test background_step and stdout/stderr capture") +pid = background_start( + "r1", + "echo 'stdout message'; echo 'stderr message' >&2; touch /tmp/mutest-bg-done", +) +wait_step( + "r1", + "test -f /tmp/mutest-bg-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) +step("r1", "rm -f /tmp/mutest-bg-done") +out = background_step(pid) +test_step( + "stdout message" in out and "stderr message" in out, + "Verify background stdout/stderr capture", + "r1", +) + +section("Test background_step API misuse") +# An ending step consumes the PID. A second ending step is invalid usage. +try: + background_step(pid) +except KeyError: + test_step(True, "Reject a previously consumed background PID", "r1") +else: + test_step(False, "Reject a previously consumed background PID", "r1") + +try: + background_step(-12345) +except KeyError: + test_step(True, "Reject an unknown background PID", "r1") +else: + test_step(False, "Reject an unknown background PID", "r1") + +section("Test positive background_match_step calls") +step("r1", "rm -f /tmp/mutest-bg-match-done") +pid = background_start( + "r1", + "echo 'Neighbor 10.0.0.1 established'; touch /tmp/mutest-bg-match-done", +) +wait_step( + "r1", + "test -f /tmp/mutest-bg-match-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) +step("r1", "rm -f /tmp/mutest-bg-match-done") +result = background_match_step( + pid, + r"Neighbor (\S+) established", + "Match background command output", +) +test_step( + result is not None, + "Verify background_match_step returns a match", + "r1", +) + +pid = background_start( + "r1", + "printf 'first line\\nsecond line\\n'; touch /tmp/mutest-bg-match-done", +) +wait_step( + "r1", + "test -f /tmp/mutest-bg-match-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) +step("r1", "rm -f /tmp/mutest-bg-match-done") +success, matched = background_match_step( + pid, + "first line\nsecond line", + "Match exact multiline background output", + exact_match=True, +) +test_step( + success and matched == "first line\nsecond line", + "Return the exact matching text", + "r1", +) + + +section("Test negative (expect_fail) background_match_step calls") +pid = background_start( + "r1", + "printf 'interface UP\\n'; touch /tmp/mutest-bg-match-done", +) +wait_step( + "r1", + "test -f /tmp/mutest-bg-match-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) +step("r1", "rm -f /tmp/mutest-bg-match-done") +success, matched = background_match_step( + pid, + "interface DOWN", + "Verify that background output does not contain DOWN", + expect_fail=True, +) +test_step( + success and matched is None, + "Return success for the expected absence of a regex match", + "host1", +) + + +section("Test background commands across sections") +step("r1", "rm -f /tmp/mutest-bg-section-done") +pid = background_start( + "r1", + "echo 'background across sections'; " + "touch /tmp/mutest-bg-section-done", +) +wait_step( + "r1", + "test -f /tmp/mutest-bg-section-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) + +section("Complete background commands started in a previous section") +out = background_step(pid) +test_step( + "background across sections" in out, + "Verify background command survives section changes", + "r1", +) +step("r1", "rm -f /tmp/mutest-bg-section-done") + + +section("Test background commands across includes") +step("r1", "rm -f /tmp/mutest-bg-section-done") +pid = background_start( + "r1", + "echo 'background across includes'; " + "touch /tmp/mutest-bg-include-done", +) +wait_step( + "r1", + "test -f /tmp/mutest-bg-include-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) +include("include/inc_subtest.py") +out = background_step(pid) +test_step( + "background across includes" in out, + "Verify background command survives include changes", + "r1", +) +step("r1", "rm -f /tmp/mutest-bg-include-done") + + +section("Test background_step_json") +step("r1", "rm -f /tmp/mutest-bg-json-done") +pid = background_start( + "r1", + """echo '{"status": "ok", "count": 3}'; touch /tmp/mutest-bg-json-done""", +) +wait_step( + "r1", + "test -f /tmp/mutest-bg-json-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) +result = background_step_json(pid) +test_step( + result == {"status": "ok", "count": 3}, + "Verify background_step_json parses valid JSON", + "r1", +) +step("r1", "rm -f /tmp/mutest-bg-json-done") + + +step("r1", "rm -f /tmp/mutest-bg-json-done") +pid = background_start( + "r1", + """echo 'not json'; touch /tmp/mutest-bg-json-done""", +) +wait_step( + "r1", + "test -f /tmp/mutest-bg-json-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) +result = background_step_json(pid) +test_step( + result == {}, + "Verify background_step_json handles invalid JSON", + "r1", +) +step("r1", "rm -f /tmp/mutest-bg-json-done") + + +section("Test positive background_match_step_json calls") +step("r1", "rm -f /tmp/mutest-bg-json-match-done") +pid = background_start( + "r1", + """echo '{"status": "ok", "count": 3, "neighbor": "10.0.0.1"}'; """ + "touch /tmp/mutest-bg-json-match-done", +) +wait_step( + "r1", + "test -f /tmp/mutest-bg-json-match-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) +result = background_match_step_json( + pid, + {"status": "ok", "count": 3}, + "Verify background JSON subset matching", +) +test_step( + result is not None, + "Verify background_match_step_json returned a match", + "r1", +) + +step("r1", "rm -f /tmp/mutest-bg-json-match-done") +pid = background_start( + "r1", + """echo '{"status": "ok", "count": 3}'; """ + "touch /tmp/mutest-bg-json-exact-done", +) +wait_step( + "r1", + "test -f /tmp/mutest-bg-json-exact-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) +result = background_match_step_json( + pid, + {"status": "ok", "count": 3}, + "Verify exact background JSON matching", + exact_match=True, +) +test_step( + result is not None, + "Verify exact background JSON match succeeds", + "r1", +) + + +section("Test negative (expect_fail) background_match_step_json calls") +step("r1", "rm -f /tmp/mutest-bg-json-exact-done") +pid = background_start( + "r1", + """echo '{"status": "failed", "count": 3}'; """ + "touch /tmp/mutest-bg-json-fail-done", +) +wait_step( + "r1", + "test -f /tmp/mutest-bg-json-fail-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) +result = background_match_step_json( + pid, + {"status": "ok"}, + "Verify expected background JSON mismatch", + expect_fail=True, +) +test_step( + result is not None, + "Verify expected JSON mismatch is recognized", + "r1", +) +step("r1", "rm -f /tmp/mutest-bg-json-fail-done") + + +section("Test background matching with nonzero exit status") +step("r1", "rm -f /tmp/mutest-bg-nonzero") +pid = background_start( + "r1", + "echo 'expected output'; touch /tmp/mutest-bg-nonzero; exit 42", +) +wait_step( + "r1", + "test -f /tmp/mutest-bg-nonzero && echo READY", + "READY", + timeout=5, + interval=0.1, +) +background_match_step( + pid, + "expected output", + "Match output from a command with nonzero exit status", +) +step("r1", "rm -f /tmp/mutest-bg-nonzero") + + +section("Test simultaneous background commands") +step("r1", "rm -f /tmp/mutest-bg-r1-done") +step("host1", "rm -f /tmp/mutest-bg-host1-done") +pid1 = background_start( + "r1", + "echo 'output from r1'; touch /tmp/mutest-bg-r1-done", +) +pid2 = background_start( + "host1", + "echo 'output from host1'; touch /tmp/mutest-bg-host1-done", +) +# Wait for both commands to produce their output. +wait_step( + "r1", + "test -f /tmp/mutest-bg-r1-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) +wait_step( + "host1", + "test -f /tmp/mutest-bg-host1-done && echo READY", + "READY", + timeout=5, + interval=0.1, +) +# Complete the commands in reverse order. +out2 = background_step(pid2) +out1 = background_step(pid1) +test_step( + "output from host1" in out2 and "output from r1" not in out2, + "Verify host1 background output", + "host1", +) +test_step( + "output from r1" in out1 and "output from host1" not in out1, + "Verify r1 background output", + "r1", +) +step("r1", "rm -f /tmp/mutest-bg-r1-done") +step("host1", "rm -f /tmp/mutest-bg-host1-done")