Claude Code's Code Mode only starts in an interactive terminal session
(-p runs without it and can't resume a session started in it) and with
the entrypoint 'cli'. A run asked for in Code Mode (spawn codeMode, or
any resume/fork of a session whose transcript has a repl-mode record)
now goes through sidecar/ptyrun.py: the same argv minus the print-mode
flags, the prompt last behind --, on a pty. The wrapper answers the
trust / consent / bypass dialogs, reads the start banner into
<sid>.codemode.json, and types /exit once stop_guard's new turn-end
marker says the turn is over with no background task left — so the
run lives exactly as long as a -p one.
A proxied account (ANTHROPIC_BASE_URL) or a CLI older than 2.1.323
can't: a new run goes as a normal one and says why; a Code Mode
session there is a 409 code_mode_unavailable. /health reports
codeMode {ok, cli, reason}; /sessions each run's banner state.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
654 lines
27 KiB
Python
654 lines
27 KiB
Python
"""
|
|
Process sampling: the CPU and memory of every agent run on this machine and of
|
|
each process it started — what the hub's Performance dashboard is built from
|
|
(it polls ``GET /procs``).
|
|
|
|
One scan reads ``/proc/<pid>/stat`` for every process (one small read each,
|
|
~50 ms for ~800 processes; psutil on macOS) and sorts them three ways:
|
|
|
|
- **agent roots** — a run this sidecar launched (``logs/<sid>.pid``) or any
|
|
Claude session on the box (``<config dir>/sessions/<pid>.json``, the CLI's
|
|
own registry: terminal sessions too), pinned to their start-time so a
|
|
recycled PID is never taken for one;
|
|
- **a run's tree** — every process whose nearest agent-root ancestor is that
|
|
root. Another agent root starts a tree of its own (a session started from a
|
|
session is its own run);
|
|
- **attributed by environment** — the rest. Every process a session starts
|
|
inherits ``CLAUDE_SESSION_ID`` (set by the sidecar) or
|
|
``CLAUDE_CODE_SESSION_ID`` (set by the CLI itself), so a process that left
|
|
its tree (``setsid nohup``, a dev server whose shell exited) still names its
|
|
conversation: *detached* while that session runs, a **leftover** once it
|
|
has ended. The environment is read once per process (cached on pid +
|
|
start-time).
|
|
|
|
CPU is measured on the tree's **cumulative** CPU time — each live process's
|
|
own time plus the time of the children it already reaped (``cutime`` +
|
|
``cstime``) — so a ``tsc`` or ``grep`` that ran and exited between two scans
|
|
still counts. Memory is RSS: cheap, and it over-counts pages shared between
|
|
processes (Chrome's renderers), which is fine for "which run is heavy".
|
|
|
|
Sampling is lazy: a scan runs when ``/procs`` is asked and the last one is
|
|
older than ``MIN_INTERVAL_S``; CPU % is the delta against the previous scan.
|
|
Nothing runs on a machine nobody polls.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import shlex
|
|
import signal
|
|
import threading
|
|
import time
|
|
|
|
from fastapi import APIRouter, Header
|
|
from pydantic import BaseModel
|
|
|
|
from config import (ACCOUNTS, GUEST_ACCOUNTS, GUEST_ACCOUNTS_DIR, IS_WORKER,
|
|
LOG_DIR)
|
|
import pids
|
|
from validate import _auth, _valid_uuid
|
|
|
|
MIN_INTERVAL_S = 2.0
|
|
# A tree's process list is for display; a Chrome can bring dozens.
|
|
MAX_TREE_PROCS = 80
|
|
SESSION_ENV = (b"CLAUDE_SESSION_ID=", b"CLAUDE_CODE_SESSION_ID=")
|
|
_UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
|
|
|
|
_HAVE_PROC = pids._HAVE_PROC
|
|
_TICK = os.sysconf("SC_CLK_TCK") if hasattr(os, "sysconf") else 100
|
|
_PAGE = os.sysconf("SC_PAGE_SIZE") if hasattr(os, "sysconf") else 4096
|
|
|
|
|
|
class Proc:
|
|
"""One process as one scan saw it. ``cpu`` = own CPU seconds, ``cum`` =
|
|
own + reaped children's; ``start`` = the start-time fingerprint
|
|
(``pids._proc_starttime``'s unit), ``started`` = epoch seconds."""
|
|
|
|
__slots__ = ("pid", "ppid", "start", "started", "comm", "cpu", "cum",
|
|
"rss", "threads")
|
|
|
|
def __init__(self, pid, ppid, start, started, comm, cpu, cum, rss, threads):
|
|
self.pid, self.ppid, self.start, self.started = pid, ppid, start, started
|
|
self.comm, self.cpu, self.cum = comm, cpu, cum
|
|
self.rss, self.threads = rss, threads
|
|
|
|
|
|
# ---- reading the process table ------------------------------------------------
|
|
|
|
def _boot_time() -> float:
|
|
try:
|
|
for line in pathlib.Path("/proc/stat").read_text().splitlines():
|
|
if line.startswith("btime "):
|
|
return float(line.split()[1])
|
|
except OSError:
|
|
pass
|
|
return 0.0
|
|
|
|
|
|
_BOOT = _boot_time() if _HAVE_PROC else 0.0
|
|
|
|
|
|
def _scan_proc() -> dict[int, Proc]:
|
|
out: dict[int, Proc] = {}
|
|
for name in os.listdir("/proc"):
|
|
if not name.isdigit():
|
|
continue
|
|
try:
|
|
with open(f"/proc/{name}/stat", "rb") as f:
|
|
raw = f.read().decode("utf-8", "replace")
|
|
close = raw.rindex(")")
|
|
comm = raw[raw.index("(") + 1:close]
|
|
f_ = raw[close + 2:].split()
|
|
# f_[0] = field 3 (state); field n is f_[n - 3]
|
|
if f_[0] == "Z":
|
|
continue
|
|
ppid = int(f_[1])
|
|
if ppid == 2 or int(name) == 2:
|
|
continue # kernel threads
|
|
ut, st, cut, cst = (int(x) for x in f_[11:15])
|
|
start = int(f_[19])
|
|
out[int(name)] = Proc(
|
|
int(name), ppid, start, _BOOT + start / _TICK, comm,
|
|
(ut + st) / _TICK, (ut + st + cut + cst) / _TICK,
|
|
int(f_[21]) * _PAGE, int(f_[17]))
|
|
except (OSError, ValueError, IndexError):
|
|
continue
|
|
return out
|
|
|
|
|
|
def _scan_psutil() -> dict[int, Proc]:
|
|
import psutil # noqa: PLC0415 — macOS worker only
|
|
out: dict[int, Proc] = {}
|
|
for p in psutil.process_iter(["pid", "ppid", "name", "create_time",
|
|
"cpu_times", "memory_info", "num_threads"]):
|
|
i = p.info
|
|
try:
|
|
ct, mi = i["cpu_times"], i["memory_info"]
|
|
if ct is None or mi is None:
|
|
continue
|
|
own = ct.user + ct.system
|
|
kids = getattr(ct, "children_user", 0) + getattr(ct, "children_system", 0)
|
|
out[i["pid"]] = Proc(
|
|
i["pid"], i["ppid"] or 0, round(i["create_time"], 2),
|
|
i["create_time"], i["name"] or "?", own, own + kids, mi.rss,
|
|
i["num_threads"] or 1)
|
|
except Exception:
|
|
continue
|
|
return out
|
|
|
|
|
|
def _read_bytes(path: str) -> bytes | None:
|
|
try:
|
|
with open(path, "rb") as f:
|
|
return f.read()
|
|
except OSError:
|
|
return None
|
|
|
|
|
|
def _cmdline(pid: int) -> list[str]:
|
|
if _HAVE_PROC:
|
|
raw = _read_bytes(f"/proc/{pid}/cmdline") or b""
|
|
return [a.decode("utf-8", "replace") for a in raw.split(b"\0") if a]
|
|
try:
|
|
import psutil # noqa: PLC0415
|
|
return psutil.Process(pid).cmdline()
|
|
except Exception:
|
|
return []
|
|
|
|
|
|
def _session_env(pid: int) -> str | None:
|
|
"""The conversation a process belongs to, from its inherited environment."""
|
|
if _HAVE_PROC:
|
|
raw = _read_bytes(f"/proc/{pid}/environ")
|
|
if not raw:
|
|
return None
|
|
found = {}
|
|
for var in raw.split(b"\0"):
|
|
for key in SESSION_ENV:
|
|
if var.startswith(key):
|
|
found[key] = var[len(key):].decode("ascii", "replace")
|
|
sid = found.get(SESSION_ENV[0]) or found.get(SESSION_ENV[1])
|
|
else:
|
|
try:
|
|
import psutil # noqa: PLC0415
|
|
env = psutil.Process(pid).environ()
|
|
except Exception:
|
|
return None
|
|
sid = env.get("CLAUDE_SESSION_ID") or env.get("CLAUDE_CODE_SESSION_ID")
|
|
return sid if sid and _UUID_RE.match(sid) else None
|
|
|
|
|
|
def _host() -> dict:
|
|
"""Machine-wide CPU (cumulative busy/total seconds) and memory."""
|
|
if not _HAVE_PROC:
|
|
try:
|
|
import psutil # noqa: PLC0415
|
|
vm, sw, ct = psutil.virtual_memory(), psutil.swap_memory(), psutil.cpu_times()
|
|
total = sum(ct)
|
|
return {"cpus": psutil.cpu_count() or 1, "busy": total - ct.idle,
|
|
"total": total, "memTotal": vm.total,
|
|
"memAvailable": vm.available, "swapTotal": sw.total,
|
|
"swapUsed": sw.used, "load": list(os.getloadavg())}
|
|
except Exception:
|
|
return {}
|
|
out: dict = {"cpus": os.cpu_count() or 1}
|
|
try:
|
|
cpu = pathlib.Path("/proc/stat").read_text().split("\n", 1)[0].split()[1:]
|
|
vals = [int(x) for x in cpu[:8]]
|
|
idle = vals[3] + vals[4]
|
|
out["total"] = sum(vals) / _TICK
|
|
out["busy"] = (sum(vals) - idle) / _TICK
|
|
except (OSError, ValueError, IndexError):
|
|
pass
|
|
try:
|
|
mem = {}
|
|
for line in pathlib.Path("/proc/meminfo").read_text().splitlines():
|
|
k, _, v = line.partition(":")
|
|
mem[k] = int(v.split()[0]) * 1024
|
|
out.update(memTotal=mem.get("MemTotal"), memAvailable=mem.get("MemAvailable"),
|
|
swapTotal=mem.get("SwapTotal"),
|
|
swapUsed=(mem.get("SwapTotal", 0) - mem.get("SwapFree", 0)))
|
|
except (OSError, ValueError, IndexError):
|
|
pass
|
|
try:
|
|
out["load"] = list(os.getloadavg())
|
|
except OSError:
|
|
pass
|
|
return out
|
|
|
|
|
|
# ---- which processes are agent runs ------------------------------------------
|
|
|
|
def _registry_dirs() -> list[pathlib.Path]:
|
|
"""Every Claude config dir's ``sessions/`` (the CLI's live-session
|
|
registry): the default login's, each declared account's, each guest's."""
|
|
dirs = [pathlib.Path.home() / ".claude"]
|
|
dirs += [d for d in ACCOUNTS.values() if d is not None]
|
|
if GUEST_ACCOUNTS and not IS_WORKER and GUEST_ACCOUNTS_DIR.is_dir():
|
|
dirs += [d for d in GUEST_ACCOUNTS_DIR.iterdir() if d.is_dir()]
|
|
return [d / "sessions" for d in dirs]
|
|
|
|
|
|
def _roots(procs: dict[int, Proc]) -> dict[int, dict]:
|
|
"""pid → {sessionId, harness, source, account} for every live agent run."""
|
|
roots: dict[int, dict] = {}
|
|
|
|
def add(pid, start, info):
|
|
p = procs.get(pid)
|
|
if p is None:
|
|
return
|
|
try: # pinned to the start-time: a recycled pid is not the run
|
|
if start is not None and abs(float(p.start) - float(start)) > 1:
|
|
return
|
|
except (TypeError, ValueError):
|
|
pass
|
|
roots.setdefault(pid, info)
|
|
|
|
hub_sids: set[str] = set()
|
|
if LOG_DIR.is_dir():
|
|
for f in LOG_DIR.glob("*.pid"):
|
|
hub_sids.add(f.stem)
|
|
rec = pids._read_record(f.stem)
|
|
if rec and rec.get("pid"):
|
|
add(int(rec["pid"]), rec.get("starttime"), {
|
|
"sessionId": f.stem, "harness": rec.get("harness") or "claude",
|
|
"source": "hub", "account": rec.get("account"),
|
|
"model": rec.get("model"), "cwd": rec.get("cwd")})
|
|
for reg in _registry_dirs():
|
|
if not reg.is_dir():
|
|
continue
|
|
for f in reg.glob("*.json"):
|
|
try:
|
|
d = json.loads(f.read_text())
|
|
pid, sid = int(d["pid"]), d["sessionId"]
|
|
except (OSError, ValueError, KeyError, TypeError):
|
|
continue
|
|
add(pid, d.get("procStart"), {
|
|
"sessionId": sid, "harness": "claude",
|
|
# a Code Mode run's CLI says `cli` (launch.py) — its pid record says hub
|
|
"source": "hub" if d.get("entrypoint") == "ai-agent-sidecar"
|
|
or sid in hub_sids else "terminal",
|
|
"account": None, "model": None, "cwd": d.get("cwd")})
|
|
return roots
|
|
|
|
|
|
# ---- labels -------------------------------------------------------------------
|
|
|
|
# Programs that only run another command: labelled by the command they run.
|
|
_WRAPPERS = {"env", "nohup", "setsid", "timeout", "xvfb-run", "rtk", "uvx",
|
|
"npx", "time", "nice", "flock", "stdbuf"}
|
|
# Runtimes whose own name says nothing: labelled with what they run.
|
|
_RUNTIMES = {"node", "python", "python3", "bash", "sh", "zsh", "dash", "ruby",
|
|
"perl", "java", "deno"}
|
|
_PKG_RUNNERS = {"npm", "pnpm", "yarn", "bun"}
|
|
# A wrapper's flags that take the next word as their value.
|
|
_FLAG_ARGS = {"--with", "--from", "--python", "-p", "--directory", "--project",
|
|
"-C", "--cwd", "--prefix", "-k", "-s", "--signal", "-w"}
|
|
# Shell keywords in front of a command (`until grep …`): skipped, the command kept.
|
|
_KEYWORDS = {"until", "while", "if", "elif", "then", "do", "else", "!", "{", "time"}
|
|
# Commands that set up the real one rather than being it: the segment is skipped.
|
|
_SHELL_SETUP = {"cd", "export", "source", ".", "set", "shopt", "unset", "local",
|
|
"pushd", "popd", "true", "false", "echo", "printf", "sleep", "test",
|
|
"[", "[[", "for", "done", "fi", "case", "esac", "}", "trap", "wait",
|
|
"exec", "read", "return", "exit"}
|
|
_ASSIGN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=.*")
|
|
# Claude Code's Bash tool runs `bash -c "source <snapshot> … && eval '<cmd>' …"`.
|
|
_EVAL_RE = re.compile(r"\beval '((?:[^']|'\\'')*)'")
|
|
_SECRET_RE = re.compile(
|
|
r"(?i)((?:token|secret|password|passwd|api[_-]?key|authorization)"
|
|
r"[\"']?\s*[:=\s]\s*(?:bearer\s+|basic\s+)?|bearer\s+)[\"']?[^\s\"']{6,}")
|
|
|
|
|
|
def label(argv: list[str], comm: str) -> str:
|
|
"""A short, stable name for what a process is — ``vite``, ``npm run build``,
|
|
``python3 -m http.server``, ``chrome (renderer)`` — what the heaviest-
|
|
commands ranking groups on."""
|
|
if not argv:
|
|
return comm
|
|
if len(argv) == 1 and " " in argv[0]:
|
|
argv = argv[0].split() # a rewritten process title (`npm exec vite …`)
|
|
prog = re.sub(r"^(python3?)\.\d+$", r"\1", os.path.basename(argv[0]))
|
|
rest = argv[1:]
|
|
if prog == "uv" and rest[:1] == ["run"]:
|
|
prog, rest = "uvx", rest[1:]
|
|
if prog == "rtk" and rest[:1] == ["proxy"]:
|
|
rest = rest[1:]
|
|
if prog in _WRAPPERS:
|
|
i = 0
|
|
while i < len(rest) and (rest[i].startswith("-") or "=" in rest[i]
|
|
or (prog == "timeout" and re.fullmatch(r"[\d.]+[smhd]?", rest[i]))):
|
|
i += 2 if rest[i] in _FLAG_ARGS else 1
|
|
if prog == "flock" and i < len(rest):
|
|
i += 1 # the lock file
|
|
return label(rest[i:], comm) if i < len(rest) else prog
|
|
if prog in _PKG_RUNNERS:
|
|
return " ".join([prog, *[a for a in rest[:3] if not a.startswith("-")][:2]])
|
|
if prog not in _RUNTIMES:
|
|
typ = next((a[7:] for a in rest if a.startswith("--type=")), None)
|
|
return f"{prog} ({typ})" if typ else prog
|
|
for i, a in enumerate(rest):
|
|
if a == "-m" and i + 1 < len(rest):
|
|
return f"{prog} -m {rest[i + 1]}"
|
|
if a == "-c":
|
|
return f"{prog} -c"
|
|
if a.startswith("-"):
|
|
continue
|
|
m = re.search(r"node_modules/(?:\.bin/)?((?:@[^/]+/)?[^/]+)", a)
|
|
return m.group(1) if m else f"{prog} {os.path.basename(a.rstrip('/')) or a}"
|
|
return prog
|
|
|
|
|
|
def tool_command(argv: list[str]) -> str | None:
|
|
"""The command a Claude Bash-tool shell runs (its ``eval '…'``), else None."""
|
|
if len(argv) < 3 or os.path.basename(argv[0]) not in ("bash", "sh", "zsh") \
|
|
or "-c" not in argv[1:3]:
|
|
return None
|
|
m = _EVAL_RE.search(argv[-1])
|
|
return m.group(1).replace("'\\''", "'") if m else None
|
|
|
|
|
|
def command_label(cmd: str) -> str:
|
|
"""The label of a shell command line: its first real command — ``cd x &&
|
|
npm run build 2>&1 | tail`` is ``npm run build``."""
|
|
lex = shlex.shlex(cmd, posix=True, punctuation_chars=True)
|
|
lex.whitespace_split = True
|
|
try:
|
|
words = list(lex)
|
|
except ValueError: # unbalanced quotes (a heredoc body…): split coarsely
|
|
words = [w for part in re.split(r"(&&|\|\||[;|&\n])", cmd) for w in
|
|
([part] if part in ("&&", "||", ";", "|", "&", "\n") else part.split())]
|
|
seg: list[str] = []
|
|
redirect = False
|
|
for w in [*words, ";"]:
|
|
if w and set(w) <= set("<>&") and set(w) & set("<>"):
|
|
redirect = True # `> out`, `2>&1`, `<<EOF`: the rest isn't argv
|
|
elif w and set(w) <= set("&|;()\n"):
|
|
while seg and (_ASSIGN_RE.fullmatch(seg[0]) or seg[0] in _KEYWORDS):
|
|
seg.pop(0) # VAR=value prefix, `until`, `if !`…
|
|
if seg and os.path.basename(seg[0]) not in _SHELL_SETUP:
|
|
return label(seg, seg[0])[:60]
|
|
seg, redirect = [], False
|
|
elif not redirect:
|
|
seg.append(w)
|
|
first = next((w for w in words if not _ASSIGN_RE.fullmatch(w)
|
|
and not set(w) <= set("&|;()<>\n")), "bash")
|
|
return os.path.basename(first)[:60]
|
|
|
|
|
|
def _redact(cmd: str) -> str:
|
|
return _SECRET_RE.sub(r"\1…", cmd)[:240]
|
|
|
|
|
|
# ---- the sampler -------------------------------------------------------------
|
|
|
|
class Sampler:
|
|
"""Keeps the previous scan (for CPU deltas) and the per-process caches."""
|
|
|
|
def __init__(self):
|
|
self._lock = threading.Lock()
|
|
self._prev_at: float | None = None
|
|
self._prev_cpu: dict[tuple, float] = {}
|
|
self._prev_cum: dict[tuple, float] = {}
|
|
self._prev_host: tuple[float, float] | None = None
|
|
self._env: dict[tuple, str | None] = {}
|
|
self._argv: dict[tuple, list[str]] = {}
|
|
self._last: dict | None = None
|
|
|
|
def snapshot(self, max_age: float = MIN_INTERVAL_S) -> dict:
|
|
with self._lock:
|
|
if self._last is not None and time.time() - self._last["at"] < max_age:
|
|
return self._last
|
|
self._last = self._scan()
|
|
return self._last
|
|
|
|
def _argv_of(self, p: Proc) -> list[str]:
|
|
key = (p.pid, p.start)
|
|
if key not in self._argv:
|
|
self._argv[key] = _cmdline(p.pid)
|
|
return self._argv[key]
|
|
|
|
def _env_of(self, p: Proc) -> str | None:
|
|
key = (p.pid, p.start)
|
|
if key not in self._env:
|
|
self._env[key] = _session_env(p.pid)
|
|
return self._env[key]
|
|
|
|
def _scan(self) -> dict:
|
|
t0 = time.perf_counter()
|
|
now = time.time()
|
|
procs = _scan_proc() if _HAVE_PROC else _scan_psutil()
|
|
dt = (now - self._prev_at) if self._prev_at else None
|
|
roots = _roots(procs)
|
|
|
|
# nearest agent-root ancestor of every process (memoized walk up)
|
|
owner: dict[int, int | None] = {}
|
|
|
|
def root_of(pid: int) -> int | None:
|
|
chain = []
|
|
cur: int | None = pid
|
|
while cur is not None and cur not in owner:
|
|
if cur in roots:
|
|
owner[cur] = cur
|
|
break
|
|
chain.append(cur)
|
|
p = procs.get(cur)
|
|
cur = p.ppid if p and p.ppid and p.ppid != cur else None
|
|
found = owner.get(cur) if cur is not None else None
|
|
for c in chain:
|
|
owner[c] = found
|
|
return found
|
|
|
|
me = os.getpid()
|
|
trees: dict[int, list[Proc]] = {r: [] for r in roots}
|
|
stray: dict[str, list[Proc]] = {}
|
|
live_sids = {info["sessionId"]: r for r, info in roots.items()}
|
|
for pid, p in procs.items():
|
|
r = root_of(pid)
|
|
if r is not None:
|
|
trees[r].append(p)
|
|
elif pid != me: # never offer the sidecar itself for a kill
|
|
sid = self._env_of(p)
|
|
if sid:
|
|
stray.setdefault(sid, []).append(p)
|
|
|
|
def pct(p: Proc) -> float | None:
|
|
if dt is None:
|
|
return None
|
|
key = (p.pid, p.start)
|
|
before = self._prev_cpu.get(key)
|
|
if before is None:
|
|
# born since the last scan ⇒ its whole life is in the window
|
|
before = 0.0 if p.started >= now - dt else None
|
|
return None if before is None else max(0.0, (p.cpu - before) / dt * 100)
|
|
|
|
in_tool: dict[int, bool] = {} # pid → it or an ancestor is a Bash-tool shell
|
|
|
|
def row(p: Proc, depth: int, sub: dict[int, tuple[float, int]],
|
|
detached: bool = False) -> dict:
|
|
argv = self._argv_of(p)
|
|
tool = tool_command(argv)
|
|
tcpu, trss = sub.get(p.pid, (p.cum, p.rss))
|
|
# rows come parent first (ordered()), so the parent's flag is known;
|
|
# the call probe measures these exactly — rankings skip them
|
|
# a detached process or a leftover was started by a call too (the
|
|
# probe follows those to their exit)
|
|
in_tool[p.pid] = bool(tool) or detached or in_tool.get(p.ppid, False)
|
|
return {"pid": p.pid, "ppid": p.ppid, "depth": depth, "inTool": in_tool[p.pid],
|
|
"label": command_label(tool) if tool else label(argv, p.comm),
|
|
"cmd": _redact(tool or " ".join(argv) or p.comm),
|
|
"kind": "tool" if tool else None,
|
|
"cpu": _round(pct(p)), "cpuSeconds": round(p.cpu, 2),
|
|
"rss": p.rss, "threads": p.threads,
|
|
# the process and everything under it (reaped children too)
|
|
"treeCpuSeconds": round(tcpu, 2), "treeRss": trss,
|
|
"startedAt": round(p.started, 1), "detached": detached}
|
|
|
|
def subtree(order: list[tuple[Proc, int]]) -> dict[int, tuple[float, int]]:
|
|
"""pid → (cumulative CPU s, RSS) of the process and its descendants."""
|
|
acc: dict[int, list] = {p.pid: [p.cum, p.rss] for p, _ in order}
|
|
for p, _ in reversed(order): # children come after their parent
|
|
if p.ppid in acc:
|
|
acc[p.ppid][0] += acc[p.pid][0]
|
|
acc[p.ppid][1] += acc[p.pid][1]
|
|
return {k: (v[0], v[1]) for k, v in acc.items()}
|
|
|
|
def ordered(members: list[Proc]) -> list[tuple[Proc, int]]:
|
|
"""Depth-first, oldest first: (process, depth) — a tree's root at
|
|
depth 0, a leftover group's topmost processes too."""
|
|
ids = {m.pid for m in members}
|
|
kids: dict[int, list[Proc]] = {}
|
|
for m in members:
|
|
kids.setdefault(m.ppid if m.ppid in ids else -1, []).append(m)
|
|
out: list[tuple[Proc, int]] = []
|
|
|
|
def walk(parent: int, depth: int):
|
|
for k in sorted(kids.get(parent, []), key=lambda x: x.started):
|
|
out.append((k, depth))
|
|
walk(k.pid, depth + 1)
|
|
walk(-1, 0)
|
|
return out
|
|
|
|
sessions = []
|
|
cum_now: dict[tuple, float] = {}
|
|
for r, info in roots.items():
|
|
members = trees[r]
|
|
detached = stray.pop(info["sessionId"], [])
|
|
cum = sum(p.cum for p in members) + sum(p.cum for p in detached)
|
|
key = (info["sessionId"], r, procs[r].start)
|
|
cum_now[key] = cum
|
|
before = self._prev_cum.get(key)
|
|
if before is None and dt is not None and procs[r].started >= now - dt:
|
|
before = 0.0 # started since the last scan
|
|
cpu = None if dt is None or before is None else max(0.0, (cum - before) / dt * 100)
|
|
order = ordered(members)
|
|
sub = subtree(order)
|
|
rows = [row(p, d, sub) for p, d in order][:MAX_TREE_PROCS]
|
|
dorder = ordered(detached)
|
|
dsub = subtree(dorder)
|
|
rows += [row(p, d + 1, dsub, True) for p, d in dorder]
|
|
sessions.append({
|
|
**info, "rootPid": r, "rootStart": procs[r].start,
|
|
"startedAt": round(procs[r].started, 1),
|
|
"cpu": _round(cpu), "cpuSeconds": round(cum, 2),
|
|
"rss": sum(p.rss for p in members) + sum(p.rss for p in detached),
|
|
"procs": len(members) + len(detached),
|
|
"threads": sum(p.threads for p in members) + sum(p.threads for p in detached),
|
|
"processes": rows})
|
|
|
|
leftovers = []
|
|
for sid, members in stray.items():
|
|
if sid in live_sids:
|
|
continue
|
|
order = ordered(members)
|
|
sub = subtree(order)
|
|
rows = [row(p, d, sub, True) | {"detached": False} for p, d in order]
|
|
cpu = [x["cpu"] for x in rows if x["cpu"] is not None]
|
|
leftovers.append({
|
|
"sessionId": sid, "procs": len(members),
|
|
"rss": sum(p.rss for p in members),
|
|
"cpu": _round(sum(cpu)) if cpu else None,
|
|
"cpuSeconds": round(sum(p.cpu for p in members), 2),
|
|
"processes": rows})
|
|
|
|
host = _host()
|
|
hcpu = None
|
|
if "busy" in host and self._prev_host:
|
|
db = host["busy"] - self._prev_host[0]
|
|
dtot = host["total"] - self._prev_host[1]
|
|
hcpu = db / dtot * 100 * host["cpus"] if dtot > 0 else None
|
|
if "busy" in host:
|
|
self._prev_host = (host.pop("busy"), host.pop("total"))
|
|
host["cpu"] = _round(hcpu)
|
|
|
|
# keep only what still exists, so the caches don't grow forever
|
|
alive = {(p.pid, p.start) for p in procs.values()}
|
|
self._env = {k: v for k, v in self._env.items() if k in alive}
|
|
self._argv = {k: v for k, v in self._argv.items() if k in alive}
|
|
self._prev_cpu = {(p.pid, p.start): p.cpu for p in procs.values()}
|
|
self._prev_cum = cum_now
|
|
self._prev_at = now
|
|
return {"at": now, "interval": _round(dt), "host": host,
|
|
"sessions": sessions, "leftovers": leftovers,
|
|
"scanMs": round((time.perf_counter() - t0) * 1000, 1)}
|
|
|
|
# ---- kill -------------------------------------------------------------------
|
|
|
|
def kill(self, session_id: str, targets: list[dict] | None,
|
|
grace: float = 3.0) -> dict:
|
|
"""SIGTERM (then SIGKILL after ``grace``) a session's leftover
|
|
processes — all of them, or the ``[{pid, startedAt}]`` given. Only a
|
|
process a fresh scan still attributes to ``session_id`` as a
|
|
**leftover** is signalled: never a live run's tree, never anything
|
|
whose pid was recycled since the dashboard showed it."""
|
|
snap = self.snapshot(max_age=0)
|
|
group = next((g for g in snap["leftovers"] if g["sessionId"] == session_id), None)
|
|
if group is None:
|
|
return {"killed": [], "missing": [t.get("pid") for t in targets or []]}
|
|
rows = {r["pid"]: r for r in group["processes"]}
|
|
want = rows if not targets else {
|
|
t["pid"]: rows[t["pid"]] for t in targets
|
|
if t.get("pid") in rows and (t.get("startedAt") is None or
|
|
abs(rows[t["pid"]]["startedAt"] - t["startedAt"]) < 2)}
|
|
sent = []
|
|
for pid in want:
|
|
try:
|
|
os.kill(pid, signal.SIGTERM)
|
|
sent.append(pid)
|
|
except OSError:
|
|
pass
|
|
deadline = time.time() + grace
|
|
while sent and time.time() < deadline:
|
|
if not any(_exists(p) for p in sent):
|
|
break
|
|
time.sleep(0.1)
|
|
forced = []
|
|
for pid in sent:
|
|
if _exists(pid):
|
|
try:
|
|
os.kill(pid, signal.SIGKILL)
|
|
forced.append(pid)
|
|
except OSError:
|
|
pass
|
|
self._last = None
|
|
missing = [t.get("pid") for t in targets or [] if t.get("pid") not in want]
|
|
return {"killed": sent, "forced": forced, "missing": missing}
|
|
|
|
|
|
def _exists(pid: int) -> bool:
|
|
state = pids._proc_state(pid)
|
|
return state is not None and state != "Z"
|
|
|
|
|
|
def _round(x: float | None) -> float | None:
|
|
return None if x is None else round(x, 1)
|
|
|
|
|
|
SAMPLER = Sampler()
|
|
|
|
|
|
# ---- routes -------------------------------------------------------------------
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
class KillBody(BaseModel):
|
|
sessionId: str
|
|
# [{pid, startedAt}] — omitted ⇒ every leftover of the session
|
|
processes: list[dict] | None = None
|
|
|
|
|
|
@router.get("/procs")
|
|
def procs(authorization: str | None = Header(default=None)) -> dict:
|
|
"""This machine's agent runs with their process trees, the leftovers of
|
|
ended ones and the host's CPU / memory (the hub polls it every few s)."""
|
|
_auth(authorization)
|
|
return SAMPLER.snapshot()
|
|
|
|
|
|
@router.post("/procs/kill")
|
|
def procs_kill(body: KillBody, authorization: str | None = Header(default=None)) -> dict:
|
|
"""Stop an ended conversation's leftover processes (``Sampler.kill``)."""
|
|
_auth(authorization)
|
|
return SAMPLER.kill(_valid_uuid(body.sessionId), body.processes)
|