56 lines
2.4 KiB
Python
56 lines
2.4 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
|
|
|
|
from deploy_release.patch import Ci, CiRan
|
|
from failure import Failure
|
|
from deploy_release.trace import Say
|
|
|
|
# As long as forge.pulls waits for a pull request's checks, which run the same ci.sh.
|
|
CI_SECONDS = 30 * 60
|
|
# How long a stopped ci.sh has to end on SIGINT, which a container's CLI passes on to its container, before it is killed.
|
|
GRACE_SECONDS = 10
|
|
|
|
|
|
def ci_runner(log: pathlib.Path, seconds: float, say: Say, grace: float = GRACE_SECONDS) -> Ci:
|
|
"""Runs ci.sh in a worktree with its output in log, as it comes. A Failure where it can't start, where log can't be written, or where it still runs after seconds, which stops it and each process it started."""
|
|
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("w", encoding="utf-8") 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)
|
|
try:
|
|
code = process.wait(timeout=seconds)
|
|
except subprocess.TimeoutExpired:
|
|
stopped(process, grace)
|
|
return Failure(f"ci.sh still ran after {lasting(seconds)} and was stopped; {log} holds its output")
|
|
except BaseException:
|
|
# The cut is ending, as on Ctrl-C, which reaches only this process's group.
|
|
stopped(process, grace)
|
|
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) -> None:
|
|
"""End process's whole group: SIGINT first, then SIGKILL once grace seconds have passed."""
|
|
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()
|
|
|
|
|
|
def lasting(seconds: float) -> str:
|
|
return f"{seconds / 60:g} minutes" if seconds >= 60 else f"{seconds:g} seconds"
|