80 lines
3.9 KiB
Python
80 lines
3.9 KiB
Python
"""Run a patch's ci.sh with its output in a file the human can follow, and stop it where it runs too long."""
|
|
import contextlib
|
|
import os
|
|
import pathlib
|
|
import signal
|
|
import subprocess
|
|
import typing
|
|
|
|
from deploy_release.patch import Ci, CiRan
|
|
from failure import Failure
|
|
from deploy_release.trace import Say
|
|
from forge.pulls import WAIT_SECONDS
|
|
|
|
# As long as a pull request's checks get, since they run the same ci.sh.
|
|
CI_SECONDS = WAIT_SECONDS
|
|
# How long a stopped ci.sh has to end on SIGINT before it is killed.
|
|
GRACE_SECONDS = 10
|
|
# How long docker has to remove a stopped ci.sh's container.
|
|
REMOVE_SECONDS = 60
|
|
# Where ci.sh reads the name to give its test container.
|
|
CONTAINER = "CI_CONTAINER"
|
|
|
|
# Removes the container of a name, running or not; a Failure where it may still run.
|
|
Remove = typing.Callable[[str], Failure | None]
|
|
|
|
|
|
def ci_runner(log: pathlib.Path, seconds: float, say: Say, container: str, remove: Remove, grace: float = GRACE_SECONDS) -> Ci:
|
|
"""Runs ci.sh in a worktree with its output in log, as it comes, and its test container named container. A Failure where it can't start, where log can't be written, or where it still runs after seconds. In that last case the runner stops ci.sh, each process ci.sh started, and that container."""
|
|
def run(worktree: pathlib.Path) -> CiRan | Failure:
|
|
say(f"ci.sh's output goes to {log}; it is stopped where it still runs after {lasting(seconds)}")
|
|
try:
|
|
with log.open("wb") as output:
|
|
# In a session of its own, ci.sh and each process it starts share one process group, which `stopped` ends whole.
|
|
process = subprocess.Popen(["sh", "ci.sh"], cwd=worktree, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, start_new_session=True, env={**os.environ, CONTAINER: container})
|
|
try:
|
|
code = process.wait(timeout=seconds)
|
|
except subprocess.TimeoutExpired:
|
|
left = stopped(process, grace, container, remove)
|
|
running = f", but its container {container} may still run: {left.reason}" if left else ""
|
|
return Failure(f"ci.sh still ran after {lasting(seconds)} and was stopped{running}; {log} holds its output")
|
|
except BaseException:
|
|
# The cut is ending, as on Ctrl-C, which reaches only this process's group.
|
|
stopped(process, grace, container, remove)
|
|
raise
|
|
return CiRan(code, log.read_text(encoding="utf-8", errors="replace"))
|
|
except OSError as failure:
|
|
return Failure(f"ci.sh could not run: {failure}")
|
|
return run
|
|
|
|
|
|
def stopped(process: subprocess.Popen[bytes], grace: float, container: str, remove: Remove) -> Failure | None:
|
|
"""End process's whole group, SIGINT first, then SIGKILL once grace seconds have passed, and then its container; a Failure where the container may still run."""
|
|
try:
|
|
with contextlib.suppress(ProcessLookupError):
|
|
os.killpg(process.pid, signal.SIGINT)
|
|
with contextlib.suppress(subprocess.TimeoutExpired):
|
|
process.wait(timeout=grace)
|
|
finally:
|
|
with contextlib.suppress(ProcessLookupError):
|
|
os.killpg(process.pid, signal.SIGKILL)
|
|
process.wait()
|
|
# The daemon runs the container, outside the group, and no signal to ci.sh's docker CLI ends the tests in it. It is removed last, once nothing in the group can start it.
|
|
left = remove(container)
|
|
return left
|
|
|
|
|
|
def removed_container(container: str, run: typing.Callable[..., subprocess.CompletedProcess[str]] = subprocess.run) -> Failure | None:
|
|
"""Removes container with docker, running or not; None too where no such container exists."""
|
|
argv = ["docker", "rm", "--force", container]
|
|
try:
|
|
ran = run(argv, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=REMOVE_SECONDS)
|
|
except (OSError, subprocess.TimeoutExpired) as failure:
|
|
return Failure(f"{' '.join(argv)} failed: {failure}")
|
|
return Failure(f"{' '.join(argv)} failed: {ran.stderr.strip()}") if ran.returncode else None
|
|
|
|
|
|
def lasting(seconds: float) -> str:
|
|
count, unit = (seconds / 60, "minute") if seconds >= 60 else (seconds, "second")
|
|
return f"{count:g} {unit}{'' if count == 1 else 's'}"
|