feat(kvb-org-queue): end a held job whose process tree stands still for 60 min
queue.py hold probes the command's process tree from /proc every poll (standstill.py): the descendants by parent link plus every process still in the command's session, their CPU ticks, rchar/wchar/read_bytes/ write_bytes and the process set. Unchanged for HUNG_SECONDS (3600) it records the stuck processes (pid, comm, state, wchan; never a command line), SIGTERMs the tree and the sessions its members lead, waits KILL_GRACE_SECONDS while recording what appears, SIGKILLs the rest on every pass and exits 124. A tree running docker, podman or ssh, or with a stopped member, is never judged. The history row carries the probe as `hung`, learn() skips such rows, and list marks an active job past three times its longest learned run (at least 30 min) `suspect hung`. Residual: a process that setsids out of the tree and every recorded session between two passes escapes; only a subreaper or a cgroup per job would hold it. 🎯 Fix: 90 % 💥 Break: 5 % 💸 Tokens: 104 % ⏱️ Velocity: 100 % 🛡️ Security: 100 % 🏆 Score: 82 🚦 Gate: ⚠️ tokens 104 % > 100: operator approved the commit (2026-11-15) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b44cac5d37
commit
3d7a83f4d4
7 files changed
+991
-25
No files matched your search
@@ -6,7 +6,9 @@ and the copy the kvb-org-organize watch hook keeps in ~/.local/state.
|
||||
A row: id, kind, signature, workdir, start, end (epoch seconds), minutes, exit,
|
||||
free_before_gb, min_free_gb, disk_gb (free_before_gb - min_free_gb, at least
|
||||
0), mem_before, mem_max, cpu_before, cpu_max (percent), concurrent (other
|
||||
active jobs at the grant).
|
||||
active jobs at the grant), and HUNG ({cpu_s, read_bytes, written_bytes,
|
||||
still_min, members, tree}, the report of standstill.py) only on a run hold
|
||||
ended for standing still, whose exit is 124.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -33,6 +35,7 @@ NAME_KEY = operator.itemgetter("signature")
|
||||
KIND_KEY = operator.itemgetter("kind")
|
||||
ANY_KIND = "*"
|
||||
RAM_CAP = "ram_cap_percent"
|
||||
HUNG = "hung"
|
||||
SIGNATURE_HEADER = ("Signature", "Kind", "Runs", "Median min", "p90 disk GB", "p90 RAM %", "Need GB")
|
||||
KIND_HEADER = ("Kind", "Runs", "p90 RAM share %", "Median CPU share %", "Slot limit", "Source")
|
||||
|
||||
@@ -156,11 +159,12 @@ def grouped(rows: list[dict], key: Callable[[dict], Hashable]) -> dict[Hashable,
|
||||
|
||||
|
||||
def command_stats(rows: list[dict]) -> dict:
|
||||
stats = {"runs": len(rows), "minutes": None, "disk_gb": None, "ram_share": None, "cpu_share": None, "need_gb": None}
|
||||
stats = {"runs": len(rows), "minutes": None, "longest": None, "disk_gb": None, "ram_share": None, "cpu_share": None,
|
||||
"need_gb": None}
|
||||
if len(rows) >= MIN_RUNS:
|
||||
disk = p90([r["disk_gb"] for r in rows])
|
||||
stats.update(
|
||||
minutes=statistics.median(r["minutes"] for r in rows), disk_gb=disk,
|
||||
minutes=statistics.median(r["minutes"] for r in rows), longest=max(r["minutes"] for r in rows), disk_gb=disk,
|
||||
ram_share=p90(shares(rows, "mem")), cpu_share=statistics.median(shares(rows, "cpu")),
|
||||
need_gb=math.ceil(disk + DISK_MARGIN_GB),
|
||||
)
|
||||
@@ -186,7 +190,8 @@ def learn(rows: list[dict], now: float, cfg: dict) -> tuple[dict[tuple[str, str]
|
||||
"""Derive disk need per command and slot limit per kind from recent rows.
|
||||
|
||||
Args:
|
||||
rows: history rows, as read() returns them.
|
||||
rows: history rows, as read() returns them; HUNG rows are ignored, as
|
||||
their standstill would stretch the minutes and the shares.
|
||||
now: epoch seconds; rows that ended more than WINDOW_SECONDS earlier are
|
||||
ignored.
|
||||
cfg: the config; load_limits.mem_percent and cpu_percent bound a limit,
|
||||
@@ -195,19 +200,20 @@ def learn(rows: list[dict], now: float, cfg: dict) -> tuple[dict[tuple[str, str]
|
||||
|
||||
Returns:
|
||||
(signatures, kinds). signatures: {(kind, signature): {runs, minutes,
|
||||
disk_gb, ram_share, cpu_share, need_gb}}, and {(ANY_KIND, signature):
|
||||
longest, disk_gb, ram_share, cpu_share, need_gb}}, and {(ANY_KIND, signature):
|
||||
...} over the rows of every kind with that signature, which is what a
|
||||
queue before the per-kind learning booked; kinds: {kind: {runs,
|
||||
ram_share, cpu_share, limit, light, ram_cap}}, ram_cap None without a
|
||||
cap. With fewer than MIN_RUNS rows every value but runs, light and
|
||||
ram_cap is None.
|
||||
minutes is the median, disk_gb and ram_share the p90 of the disk taken
|
||||
minutes is the median and longest the largest minutes, disk_gb and
|
||||
ram_share the p90 of the disk taken
|
||||
and of max minus before in percentage points, cpu_share the median of
|
||||
max minus before; need_gb is ceil(disk_gb + DISK_MARGIN_GB); limit is
|
||||
max(1, min over RAM and CPU of floor((load limit - median before) /
|
||||
max(share, MIN_SHARE_PERCENT))).
|
||||
"""
|
||||
recent = [r for r in rows if now - r["end"] <= WINDOW_SECONDS]
|
||||
recent = [r for r in rows if now - r["end"] <= WINDOW_SECONDS and HUNG not in r]
|
||||
light = set(cfg.get("light_kinds", []))
|
||||
caps = cfg.get(RAM_CAP, {})
|
||||
signatures = {(ANY_KIND, name): command_stats(group) for name, group in grouped(recent, NAME_KEY).items()}
|
||||
|
||||
@@ -41,9 +41,10 @@ Args:
|
||||
proposing it (latched()); measure disk, RAM and CPU, run
|
||||
CMD in the current directory with inherited stdio in a session of its
|
||||
own, forward SIGINT and SIGTERM to its process group, measure every
|
||||
POLL_SECONDS and at its end, record its history row and leave the
|
||||
queue. The entry carries its code (a hash of this file and the
|
||||
SIBLINGS); a poll that finds other code installed in
|
||||
POLL_SECONDS and at its end, end its process tree once the tree stood
|
||||
still for standstill.HUNG_SECONDS (supervise()), record its history
|
||||
row and leave the queue. The entry carries its code (a hash of this
|
||||
file and the SIBLINGS); a poll that finds other code installed in
|
||||
~/.agents/skills leaves the queue ungranted and restarts the same hold
|
||||
with the installed queue.py, which keeps its entry id, place and
|
||||
enqueue time (hand_over()).
|
||||
@@ -74,7 +75,9 @@ Args:
|
||||
poll, host load included, such as `waits in line behind <id>` or
|
||||
`drained for <id>`, the head's after `escalated <step>: ` once the
|
||||
stall reached it; `backfilled` for a job started past a blocked one;
|
||||
prefixed when the entry runs other code than the installed one).
|
||||
led by `suspect hung (<runtime> min)` for an active job past
|
||||
standstill.suspect_seconds() (suspected()); prefixed when the entry
|
||||
runs other code than the installed one).
|
||||
Entries of dead holders are dropped first.
|
||||
--json: print the same rows as a JSON list (listed()), each with
|
||||
the trace of the evaluate() pass that set its reason.
|
||||
@@ -109,7 +112,8 @@ watch.py documents them. A signature is `<repository>: <command signature>`
|
||||
(aliases()).
|
||||
|
||||
Exit codes:
|
||||
hold: the command's exit code unchanged, 128+N when signal N ended it;
|
||||
hold: the command's exit code unchanged, 128+N when signal N ended it,
|
||||
standstill.HUNG_EXIT (124) when hold ended it for standing still;
|
||||
a command exiting 75 (EX_TEMPFAIL: it did no work, such as a declined
|
||||
`operator.py granted`) leaves no history row;
|
||||
before the command started 2 on a usage or config error or when it
|
||||
@@ -154,6 +158,7 @@ SIBLINGS = {
|
||||
"council": SKILLS / "kvb-org-organize" / "scripts" / "council.py",
|
||||
"rasci": SKILLS / "kvb-org-rasci" / "scripts" / "rasci.py",
|
||||
"history": Path(__file__).resolve().parent / "history.py",
|
||||
"standstill": Path(__file__).resolve().parent / "standstill.py",
|
||||
"nofollow": SKILLS / "kvb-org-organize" / "scripts" / "nofollow.py",
|
||||
"councilroot": SKILLS / "kvb-org-organize" / "scripts" / "councilroot.py",
|
||||
}
|
||||
@@ -228,6 +233,7 @@ def sibling(name: str) -> ModuleType:
|
||||
|
||||
watch = sibling("watch")
|
||||
history = sibling("history")
|
||||
standstill = sibling("standstill")
|
||||
nofollow = sibling("nofollow")
|
||||
STORE = watch.ROOT / "queue.json"
|
||||
LOCK = watch.ROOT / "queue.lock"
|
||||
@@ -1444,23 +1450,54 @@ def measure(cfg: dict) -> dict[str, float]:
|
||||
return {"free_gb": free, "mem": mem, "cpu": cpu}
|
||||
|
||||
|
||||
def supervise(cfg: dict, child: subprocess.Popen, samples: list[dict[str, float]]) -> int:
|
||||
def supervise(cfg: dict, child: subprocess.Popen, samples: list[dict[str, float]]) -> tuple[int, dict | None]:
|
||||
"""Wait for the child, measuring every POLL_SECONDS and once at its end.
|
||||
|
||||
Args:
|
||||
cfg: the config.
|
||||
child: the running command.
|
||||
child: the running command, leading a session of its own.
|
||||
samples: the measurements so far; each new one is appended.
|
||||
|
||||
Returns:
|
||||
The child's return code.
|
||||
(the child's return code, None); (standstill.HUNG_EXIT, the probe of
|
||||
standstill.Clock.report()) once its process tree stood still for
|
||||
standstill.HUNG_SECONDS and stop() ended it.
|
||||
"""
|
||||
clock = standstill.Clock(child.pid)
|
||||
code = None
|
||||
while code is None:
|
||||
with contextlib.suppress(subprocess.TimeoutExpired):
|
||||
code = child.wait(timeout=POLL_SECONDS)
|
||||
samples.append(measure(cfg))
|
||||
return code
|
||||
if code is None and clock.hung() and child.poll() is None:
|
||||
probe = clock.report()
|
||||
print(f"queue: {standstill.told(probe)}; ending the tree", file=sys.stderr, flush=True)
|
||||
return stop(child), probe
|
||||
return code, None
|
||||
|
||||
|
||||
def stop(child: subprocess.Popen) -> int:
|
||||
"""SIGTERM every process of the child's tree (standstill.members()), of
|
||||
the sessions its members lead and the descendants those have now,
|
||||
SIGKILL the ones still there after standstill.KILL_GRACE_SECONDS and
|
||||
those standstill.settle() found during it, again at each pass of the
|
||||
SIGKILL grace, a recorded member only while its start time matches; the
|
||||
child's process group (send()) when /proc does not show the child. A
|
||||
process that leaves the tree and every recorded session between two
|
||||
passes (setsid, then its parent dies) escapes; only a subreaper or a
|
||||
cgroup per job would hold it.
|
||||
|
||||
Returns:
|
||||
standstill.HUNG_EXIT, also when a process outlives SIGKILL by another
|
||||
grace (uninterruptible sleep), so hold never waits on it.
|
||||
"""
|
||||
targets = standstill.members(child.pid)
|
||||
for signum, repeat in ((signal.SIGTERM, None), (signal.SIGKILL, signal.SIGKILL)):
|
||||
living = standstill.signal_all(targets, signum)
|
||||
if child.pid not in living:
|
||||
send(child, signum)
|
||||
targets = standstill.settle(targets | living, child.poll, repeat)
|
||||
return standstill.HUNG_EXIT
|
||||
|
||||
|
||||
def keep(row: dict) -> None:
|
||||
@@ -1582,10 +1619,10 @@ def cmd_hold(args: argparse.Namespace) -> int:
|
||||
for signum in caught:
|
||||
send(child, signum)
|
||||
update(entry["id"], child=child.pid, child_start=identity(child.pid))
|
||||
code = supervise(cfg, child, samples)
|
||||
code, hung = supervise(cfg, child, samples)
|
||||
code = code if code >= 0 else 128 - code
|
||||
job = {"id": f"{entry['id']}-{time.time_ns()}", "kind": args.kind, "signature": names[0],
|
||||
"workdir": entry["workdir"]}
|
||||
"workdir": entry["workdir"], **({} if hung is None else {history.HUNG: hung})}
|
||||
record(job, start, code, samples, concurrent)
|
||||
keep_receipt(gates, args, here, before, code)
|
||||
return code
|
||||
@@ -1607,7 +1644,8 @@ def cmd_list(args: argparse.Namespace) -> int:
|
||||
by_id = {e["id"]: e for e in entries}
|
||||
running = [(key_of(e), e["granted"]) for e in entries if e["status"] == "active"]
|
||||
rows = [
|
||||
(None, e, history.eta(signatures, [(key_of(e), e["granted"])], [], now), e.get("reason") or "-", e.get("trace", []))
|
||||
(None, e, history.eta(signatures, [(key_of(e), e["granted"])], [], now), suspected(e, e.get("reason"), signatures, now) or "-",
|
||||
e.get("trace", []))
|
||||
for e in entries if e["status"] == "active"
|
||||
]
|
||||
ahead: list[tuple[str, str]] = []
|
||||
@@ -1633,6 +1671,20 @@ def cmd_list(args: argparse.Namespace) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def suspected(entry: dict, reason: str | None, signatures: dict[tuple[str, str], dict], now: float) -> str | None:
|
||||
"""Returns:
|
||||
reason led by `suspect hung (<runtime> min)` once the active entry
|
||||
runs past standstill.suspect_seconds() of the longest run its
|
||||
signature learned (history.learned_value()), else reason.
|
||||
"""
|
||||
longest = history.learned_value(signatures, entry["kind"], aliases_of(entry), "longest")
|
||||
runtime = now - entry["granted"]
|
||||
if runtime < standstill.suspect_seconds(longest):
|
||||
return reason
|
||||
mark = f"suspect hung ({runtime / 60:.0f} min)"
|
||||
return mark if reason is None else f"{mark}; {reason}"
|
||||
|
||||
|
||||
def stamped(entry: dict, reason: str, host: str) -> str:
|
||||
if entry.get("code") == host:
|
||||
return reason
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
"""Tell a held command that stands still from one that works, from /proc alone.
|
||||
|
||||
queue.py's supervise() asks a Clock at every poll; once the process tree of
|
||||
the command (tree()) stood still for HUNG_SECONDS, hold signals every member
|
||||
(members(), signal_all(), settle()) and exits HUNG_EXIT, and list marks an
|
||||
active job that runs SUSPECT_FACTOR times its longest learned run, at least
|
||||
SUSPECT_FLOOR_SECONDS, as suspect hung.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable, Iterable
|
||||
from pathlib import Path
|
||||
from typing import NamedTuple
|
||||
|
||||
PROC = Path("/proc")
|
||||
HUNG_SECONDS = 3600
|
||||
KILL_GRACE_SECONDS = 30
|
||||
SETTLE_SECONDS = 0.2
|
||||
HUNG_EXIT = 124
|
||||
SUSPECT_FACTOR = 3
|
||||
SUSPECT_FLOOR_SECONDS = 1800
|
||||
TRACE_LIMIT = 20
|
||||
STATE, PARENT, SESSION, START = 0, 1, 3, 19
|
||||
TIMES = slice(11, 15)
|
||||
IO_KEYS = (b"rchar", b"wchar", b"read_bytes", b"write_bytes")
|
||||
PAUSED = frozenset({b"T", b"t"})
|
||||
GONE = frozenset({b"Z", b"X"})
|
||||
ELSEWHERE = frozenset({b"docker", b"docker-compose", b"docker-buildx", b"podman", b"podman-compose", b"ssh"})
|
||||
TICKS = os.sysconf("SC_CLK_TCK")
|
||||
|
||||
|
||||
class Process(NamedTuple):
|
||||
pid: int
|
||||
comm: bytes
|
||||
state: bytes
|
||||
parent: int
|
||||
session: int
|
||||
ticks: int
|
||||
start: int
|
||||
|
||||
|
||||
class Sample(NamedTuple):
|
||||
members: frozenset[tuple[int, int]]
|
||||
ticks: int
|
||||
io: tuple[int, ...]
|
||||
elsewhere: tuple[bytes, ...]
|
||||
paused: bool
|
||||
|
||||
@property
|
||||
def held(self) -> bool:
|
||||
return bool(self.elsewhere) or self.paused
|
||||
|
||||
|
||||
def parse_stat(data: bytes) -> Process:
|
||||
"""Args:
|
||||
data: the bytes of /proc/<pid>/stat; field 2, the command name in
|
||||
parentheses, may hold spaces and parentheses itself, so the
|
||||
fields are split after the last `)`.
|
||||
|
||||
Returns:
|
||||
The process: pid (field 1), comm (2), state (3), parent (4), session
|
||||
(6), utime + stime + cutime + cstime (14 to 17, in clock ticks) and
|
||||
start time (22, in clock ticks after boot).
|
||||
"""
|
||||
head, tail = data.rsplit(b")", 1)
|
||||
pid, comm = head.split(b"(", 1)
|
||||
fields = tail.split()
|
||||
return Process(int(pid), comm, fields[STATE], int(fields[PARENT]), int(fields[SESSION]),
|
||||
sum(int(ticks) for ticks in fields[TIMES]), int(fields[START]))
|
||||
|
||||
|
||||
def read(name: str) -> Process | None:
|
||||
try:
|
||||
return parse_stat((PROC / name / "stat").read_bytes())
|
||||
except (OSError, ValueError, IndexError):
|
||||
return None
|
||||
|
||||
|
||||
def table() -> dict[int, Process] | None:
|
||||
"""Returns:
|
||||
Every process /proc lists, by pid, skipping one that vanished
|
||||
between the listing and the read; None when /proc cannot be listed.
|
||||
"""
|
||||
try:
|
||||
names = [name for name in os.listdir(PROC) if name.isdigit()]
|
||||
except OSError:
|
||||
return None
|
||||
return {found.pid: found for found in map(read, names) if found is not None}
|
||||
|
||||
|
||||
def family(processes: dict[int, Process], roots: Iterable[int]) -> set[int]:
|
||||
"""Returns:
|
||||
The roots processes shows and all their descendants, whatever
|
||||
session or process group each one moved to.
|
||||
"""
|
||||
children: dict[int, list[int]] = {}
|
||||
for process in processes.values():
|
||||
children.setdefault(process.parent, []).append(process.pid)
|
||||
found: set[int] = set()
|
||||
todo = [pid for pid in roots if pid in processes]
|
||||
while todo:
|
||||
pid = todo.pop()
|
||||
if pid not in found:
|
||||
found.add(pid)
|
||||
todo.extend(children.get(pid, ()))
|
||||
return found
|
||||
|
||||
|
||||
def tree(processes: dict[int, Process], root: int) -> list[Process]:
|
||||
"""Returns:
|
||||
root, its descendants (family()) and every process still in the
|
||||
session root leads, as an orphan handed to init keeps it.
|
||||
"""
|
||||
session = {process.pid for process in processes.values() if process.session == root}
|
||||
return [processes[pid] for pid in family(processes, [root]) | session]
|
||||
|
||||
|
||||
def io_of(pid: int) -> tuple[int, ...]:
|
||||
"""Returns:
|
||||
The IO_KEYS counters of /proc/<pid>/io; zeros when that file cannot
|
||||
be read (a setuid member's, or one that vanished after its stat),
|
||||
which leaves its CPU time counted.
|
||||
"""
|
||||
try:
|
||||
pairs = dict(line.split(b":", 1) for line in (PROC / str(pid) / "io").read_bytes().splitlines())
|
||||
return tuple(int(pairs[key]) for key in IO_KEYS)
|
||||
except (OSError, ValueError, KeyError):
|
||||
return (0,) * len(IO_KEYS)
|
||||
|
||||
|
||||
def wchan_of(pid: int) -> str:
|
||||
"""Returns:
|
||||
The kernel function /proc/<pid>/wchan names as the one the process
|
||||
sleeps in; empty while it runs and when that file cannot be read.
|
||||
"""
|
||||
try:
|
||||
name = (PROC / str(pid) / "wchan").read_text(encoding="ascii", errors="replace")
|
||||
except OSError:
|
||||
return ""
|
||||
return "" if name == "0" else name
|
||||
|
||||
|
||||
def trace(root: int) -> list[str]:
|
||||
"""Returns:
|
||||
`<pid> <comm> <state> [<wchan>]` of the tree() members of root, the
|
||||
ones without a child in the tree first (the stuck one, not the
|
||||
ancestors waiting on it), then by pid, at most TRACE_LIMIT; comm with
|
||||
control bytes escaped, as a process sets its own. Never a command
|
||||
line, which can carry credentials. Empty when /proc cannot be listed
|
||||
or does not show root.
|
||||
"""
|
||||
processes = table()
|
||||
if processes is None or root not in processes:
|
||||
return []
|
||||
in_tree = tree(processes, root)
|
||||
parents = {process.parent for process in in_tree}
|
||||
return [" ".join(filter(None, (str(process.pid), process.comm.decode(errors="replace").encode("unicode_escape").decode(),
|
||||
process.state.decode(), wchan_of(process.pid))))
|
||||
for process in sorted(in_tree, key=lambda process: (process.pid in parents, process.pid))[:TRACE_LIMIT]]
|
||||
|
||||
|
||||
def probe(root: int) -> Sample | None:
|
||||
"""Args:
|
||||
root: the pid of the held command.
|
||||
|
||||
Returns:
|
||||
The tree() of root: its members as (pid, start time), their CPU
|
||||
ticks and io_of() counters summed, the ELSEWHERE commands among them
|
||||
and whether one is stopped or traced; None when /proc cannot be
|
||||
listed or does not show root, as a /proc of another PID namespace
|
||||
does not.
|
||||
"""
|
||||
processes = table()
|
||||
if processes is None or root not in processes:
|
||||
return None
|
||||
in_tree = tree(processes, root)
|
||||
return Sample(
|
||||
frozenset((process.pid, process.start) for process in in_tree),
|
||||
sum(process.ticks for process in in_tree),
|
||||
tuple(map(sum, zip(*(io_of(process.pid) for process in in_tree)))),
|
||||
tuple(sorted({process.comm for process in in_tree} & ELSEWHERE)),
|
||||
any(process.state in PAUSED for process in in_tree),
|
||||
)
|
||||
|
||||
|
||||
def say(text: str) -> None:
|
||||
print(f"queue: {text}", file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
class Clock:
|
||||
"""Clock how long the process tree of a held command stood still.
|
||||
|
||||
Args:
|
||||
root: the command's pid.
|
||||
"""
|
||||
|
||||
def __init__(self, root: int) -> None:
|
||||
self.root = root
|
||||
self.seen: Sample | None = None
|
||||
self.since = time.monotonic()
|
||||
self.blind = False
|
||||
self.away = False
|
||||
|
||||
def hung(self) -> bool:
|
||||
"""Returns:
|
||||
Whether probe() of the tree gave the same sample for
|
||||
HUNG_SECONDS. A probe that sees nothing, a tree running an
|
||||
ELSEWHERE client, whose work runs outside the tree, and a tree
|
||||
with a stopped or traced member restart the clock and never fire.
|
||||
"""
|
||||
now = time.monotonic()
|
||||
seen = probe(self.root)
|
||||
self.warn(seen)
|
||||
if seen is None or seen.held or seen != self.seen:
|
||||
self.since = now
|
||||
self.seen = seen
|
||||
return seen is not None and not seen.held and now - self.since >= HUNG_SECONDS
|
||||
|
||||
def warn(self, seen: Sample | None) -> None:
|
||||
"""Args:
|
||||
seen: the probe() of this poll; the first None of the run says
|
||||
on stderr that the guard is off, the first naming an
|
||||
ELSEWHERE client that it holds off.
|
||||
"""
|
||||
if seen is None and not self.blind:
|
||||
say(f"/proc does not show process {self.root}; the hung-job guard is off for it")
|
||||
self.blind = True
|
||||
if seen is not None and seen.elsewhere and not self.away:
|
||||
names = ", ".join(name.decode(errors="replace") for name in seen.elsewhere)
|
||||
say(f"the command runs {names}, whose work /proc does not show; the hung-job guard holds off while one runs")
|
||||
self.away = True
|
||||
|
||||
def report(self) -> dict[str, float | int | list[str]]:
|
||||
"""Returns:
|
||||
The sample of the last hung() that saw the tree, for the history
|
||||
row: cpu_s (CPU seconds), read_bytes and written_bytes (rchar and
|
||||
wchar), still_min (minutes without a change), members (the
|
||||
number of processes) and tree (their trace(), taken now, before
|
||||
any signal).
|
||||
"""
|
||||
rchar, wchar = self.seen.io[:2]
|
||||
return {"cpu_s": round(self.seen.ticks / TICKS, 2), "read_bytes": rchar, "written_bytes": wchar,
|
||||
"still_min": round((time.monotonic() - self.since) / 60, 1), "members": len(self.seen.members),
|
||||
"tree": trace(self.root)}
|
||||
|
||||
|
||||
def told(report: dict) -> str:
|
||||
return (f"the command's process tree stood still for {report['still_min']:g} min (CPU {report['cpu_s']:g} s, "
|
||||
f"{report['read_bytes']} bytes read, {report['written_bytes']} written, all unchanged); "
|
||||
f"tree of {report['members']}: {', '.join(report['tree'])}")
|
||||
|
||||
|
||||
def members(root: int) -> dict[int, int]:
|
||||
"""Returns:
|
||||
The tree() of root as {pid: start time}; empty when /proc cannot be
|
||||
listed or does not show root.
|
||||
"""
|
||||
processes = table()
|
||||
if processes is None or root not in processes:
|
||||
return {}
|
||||
return {process.pid: process.start for process in tree(processes, root)}
|
||||
|
||||
|
||||
def alive(targets: dict[int, int]) -> dict[int, int]:
|
||||
"""Args:
|
||||
targets: {pid: start time} as members() recorded them, the command
|
||||
among them (a zombie still shows in /proc).
|
||||
|
||||
Returns:
|
||||
The targets still running with their recorded start time, so a
|
||||
reused pid never counts, the members of every session such a target
|
||||
or a target gone from /proc leads, as a process a member starts
|
||||
during the grace keeps its session when its parent exits (Linux
|
||||
keeps a session id allocated while a member lives, so no reused pid
|
||||
matches it), and the descendants all of them have now, as
|
||||
{pid: start time}; zombies are left out, and nothing when /proc
|
||||
cannot be listed.
|
||||
"""
|
||||
processes = table() or {}
|
||||
kept = [pid for pid, start in targets.items() if pid in processes and processes[pid].start == start]
|
||||
leaders = {pid for pid, start in targets.items() if pid not in processes or processes[pid].start == start}
|
||||
kept += [process.pid for process in processes.values() if process.session in leaders]
|
||||
return {pid: processes[pid].start for pid in family(processes, kept) if processes[pid].state not in GONE}
|
||||
|
||||
|
||||
def signal_all(targets: dict[int, int], signum: int) -> dict[int, int]:
|
||||
"""Send signum to every process alive() finds of targets.
|
||||
|
||||
Returns:
|
||||
Those processes as {pid: start time}.
|
||||
"""
|
||||
living = alive(targets)
|
||||
for pid in living:
|
||||
with contextlib.suppress(ProcessLookupError, PermissionError):
|
||||
os.kill(pid, signum)
|
||||
return living
|
||||
|
||||
|
||||
def settle(targets: dict[int, int], reap: Callable[[], int | None], signum: int | None) -> dict[int, int]:
|
||||
"""Wait up to KILL_GRACE_SECONDS until the command is reaped and alive()
|
||||
finds none of targets, recording every process it finds on the way, so
|
||||
one a member starts in a session of its own during the grace stays a
|
||||
target after its parent exits; one started and orphaned between two
|
||||
passes, SETTLE_SECONDS and a /proc scan apart, is not seen.
|
||||
|
||||
Args:
|
||||
targets: {pid: start time} of the tree.
|
||||
reap: Popen.poll of the command, None while it runs.
|
||||
signum: sent to everything each pass finds (signal_all()), so a
|
||||
process forked while the last pass signalled gets it too; None
|
||||
only waits, letting a member's cleanup run out the grace.
|
||||
|
||||
Returns:
|
||||
targets and every process found, as {pid: start time}.
|
||||
"""
|
||||
seen = dict(targets)
|
||||
deadline = time.monotonic() + KILL_GRACE_SECONDS
|
||||
while time.monotonic() < deadline:
|
||||
living = alive(seen) if signum is None else signal_all(seen, signum)
|
||||
seen |= living
|
||||
if reap() is not None and not living:
|
||||
break
|
||||
time.sleep(SETTLE_SECONDS)
|
||||
return seen
|
||||
|
||||
|
||||
def suspect_seconds(longest: float | None) -> float:
|
||||
"""Args:
|
||||
longest: the longest learned run of a job's signature in minutes,
|
||||
None while nothing is learned.
|
||||
|
||||
Returns:
|
||||
The runtime past which list marks the job suspect hung:
|
||||
SUSPECT_FACTOR times longest, at least SUSPECT_FLOOR_SECONDS.
|
||||
"""
|
||||
if longest is None:
|
||||
return SUSPECT_FLOOR_SECONDS
|
||||
return max(SUSPECT_FLOOR_SECONDS, SUSPECT_FACTOR * longest * 60)
|
||||
Reference in new issue
Block a user