From 4034873fa675e6e695509fe4f83641c224dcf373 Mon Sep 17 00:00:00 2001 From: AgentSparko <124781906+AgentSparko@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:42:28 +0200 Subject: [PATCH] fix(engines): stop a containerised engine with docker instead of refusing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A `docker run` engine without a user namespace puts root's process behind the pid the dashboard scans, so the SIGTERM/SIGKILL that works for a native engine raised PermissionError and Stop answered "process is root-owned — stop it where it was started (docker/systemd)". The operator was usually in the docker group at that very moment: the dashboard had the right tool and handed the job back instead. Stop now asks docker when the process cannot be signalled. container_id() reads /proc//cgroup for the pid that was clicked — the request still carries a pid and nothing else, so the button stays an engine stop and not a "stop any container" endpoint. `docker stop --time 15` is also the better primitive for an engine: it releases the GPU instead of being SIGKILLed mid-request. When the pid is not a container, or docker cannot be reached, the old honest message still comes back (reworded to 'systemd?', since docker is no longer the unhandled case). The worker branch routes through the same helper. Verified against a real root-owned container, not just mocks: an alpine container's host pid (owner root) went through stop(), hit the genuine PermissionError path, resolved its container id from /proc, ran a genuine `docker stop`, and the container reached `exited`. The serving engine was left alone. Six tests in tests/test_engine_stop.py: docker is asked with the pid-derived id, a docker failure is reported instead of claimed as success, missing docker falls back to the old message, a non-container root process never triggers a docker call, the container handle can only come from the clicked pid, and the worker branch reaches the helper too. The process-group half is marked POSIX-only (os.getpgid has no Windows twin). 333 passed. --- app/live_engines.py | 56 ++++++++++++++- tests/test_engine_stop.py | 140 ++++++++++++++++++++++++++++++++++++++ web/dashboard.html | 2 +- web/js/dashboard.js | 3 +- 4 files changed, 198 insertions(+), 3 deletions(-) create mode 100644 tests/test_engine_stop.py diff --git a/app/live_engines.py b/app/live_engines.py index 1974678..f9a9d2a 100644 --- a/app/live_engines.py +++ b/app/live_engines.py @@ -34,6 +34,11 @@ from . import procs MIN_GPU_MIB = 1024 # "over 1 GB of GPU memory" per spec +# A containerised engine's inner process belongs to root, so the dashboard cannot +# signal it; `docker stop` is the primitive that can. Grace is generous enough for +# an engine to release the GPU cleanly, the timeout is a hard ceiling on the CLI. +DOCKER_STOP_GRACE_S = 15 +DOCKER_STOP_TIMEOUT_S = 90 _SCAN_TTL = 5.0 # argv tokens that mean "this process IS the server" (matched exactly, # case-insensitive: argv0 basename or a --flag) @@ -370,6 +375,48 @@ def scan(self, force: bool = False) -> list[dict]: self._cache = (now, out) return out + def _stop_container(self, pid: int) -> dict | None: + """Stop a containerised engine whose process we are not allowed to signal. + + `docker run` without a user namespace puts root's process behind the pid we + scan, so killpg raises PermissionError for a dashboard running as a normal + user — even one whose operator is in the `docker` group, which is the case + that matters. Docker has the right primitive and `docker stop` lets the + engine let go of the GPU instead of being SIGKILLed mid-request. + + The container identity comes ONLY from /proc//cgroup for the pid the + operator clicked; the request carries a pid and nothing else, so this stays + an engine-stop button and not a "stop any container" endpoint. Returns None + when the pid is not a container or docker cannot be reached, so the caller + still gets the honest 'stop it where it was started' answer. + """ + try: + from . import docker_recipe + cid = docker_recipe.container_id(pid) + except Exception: # noqa: BLE001 — no docker, no perms, weird cgroup: old answer + return None + if not cid: + return None + name = "" + try: # cosmetic label only; failure must not block the stop + name = subprocess.run(["docker", "inspect", "-f", "{{.Name}}", cid], + capture_output=True, text=True, + timeout=DOCKER_STOP_TIMEOUT_S).stdout.strip().lstrip("/") + except Exception: # noqa: BLE001 + pass + try: + r = subprocess.run(["docker", "stop", "--time", str(DOCKER_STOP_GRACE_S), cid], + capture_output=True, text=True, timeout=DOCKER_STOP_TIMEOUT_S) + except (OSError, subprocess.SubprocessError): + return None # docker missing / not permitted for this service user + if r.returncode != 0: + detail = (r.stderr or r.stdout or "").strip()[:200] + return {"ok": False, "error": f"docker stop failed: {detail or 'unknown error'}"} + self._last_by_pid.pop(pid, None) + self.scan(force=True) + return {"ok": True, "killed_pid": pid, "stopped_container": name or cid[:12], + "via": "docker stop"} + def stop(self, pid) -> dict: """SIGTERM→KILL an engine pid with guardrails (port rows refuse).""" if pid is None: @@ -417,6 +464,9 @@ def stop(self, pid) -> dict: try: procs.kill_tree(pid) except PermissionError: + stopped = self._stop_container(pid) + if stopped is not None: + return stopped return {"ok": False, "error": "process belongs to another user/admin — stop it where it was started"} self._last_by_pid.pop(pid, None) @@ -425,8 +475,12 @@ def stop(self, pid) -> dict: try: os.killpg(pgid, signal.SIGTERM) except PermissionError: + # a container the CLI never supervised: ask docker, which can + stopped = self._stop_container(pid) + if stopped is not None: + return stopped return {"ok": False, - "error": "process is root-owned — stop it where it was started (docker/systemd)"} + "error": "process is root-owned — stop it where it was started (systemd?)"} except ProcessLookupError: return {"ok": False, "error": "process vanished"} deadline = time.time() + 10 diff --git a/tests/test_engine_stop.py b/tests/test_engine_stop.py new file mode 100644 index 0000000..46a6d08 --- /dev/null +++ b/tests/test_engine_stop.py @@ -0,0 +1,140 @@ +"""Stopping a containerised engine. + +A `docker run` engine puts root's process behind the pid the dashboard scanned, so the +kill that works for a native engine raises PermissionError. The operator is usually in +the `docker` group, so docker itself can stop it — and `docker stop` is also the *better* +primitive: the engine releases the GPU instead of being SIGKILLed mid-request. + +The container handle must come from /proc//cgroup for the pid that was clicked, +never from the request body, or an engine-stop button becomes "stop any container". +""" +import os +import subprocess +import time + +import pytest + +from app import docker_recipe, live_engines, procs + +# the killpg / os.getpgid half of stop() is POSIX-only; the worker branch is not +_POSIX = hasattr(os, "getpgid") +posix_only = pytest.mark.skipif(not _POSIX, reason="POSIX process groups (os.getpgid)") + +CID = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + + +def _stub(monkeypatch, pid=4242, classify="vLLM"): + """A LiveEngines that believes `pid` is a live engine, without scanning the box.""" + le = live_engines.LiveEngines() + monkeypatch.setattr(live_engines.procs, "HAS_PGRP", True) + if _POSIX: # the worker test runs on Windows too, where os.getpgid doesn't exist + monkeypatch.setattr(live_engines.os, "getpgid", + lambda p: 99999 if p == 0 else pid) # never our own group + monkeypatch.setattr(live_engines.procs, "alive", lambda p: True) + monkeypatch.setattr(live_engines, "_cmdline", lambda p: "/usr/bin/vllm serve /models/x") + monkeypatch.setattr(live_engines, "_classify", lambda p: classify) + monkeypatch.setattr(live_engines, "_gpu_holders", lambda: {}) + le._last_by_pid[pid] = (time.time(), classify) + monkeypatch.setattr(le, "scan", lambda force=False: []) + return le, pid + + +def _deny_killpg(monkeypatch): + def boom(pgid, sig): + raise PermissionError(1, "Operation not permitted") + monkeypatch.setattr(live_engines.os, "killpg", boom) + + +def _fake_docker(monkeypatch, rc=0, err=""): + calls = [] + + class R: + def __init__(self, returncode, stdout="", stderr=""): + self.returncode, self.stdout, self.stderr = returncode, stdout, stderr + + def run(cmd, **kw): + calls.append(list(cmd)) + if cmd[1] == "inspect": + return R(rc, "/limcars-engine-probe\n") + return R(rc, "", err) + + monkeypatch.setattr(live_engines.subprocess, "run", run) + return calls + + +@posix_only +def test_a_root_owned_container_is_stopped_through_docker(monkeypatch): + le, pid = _stub(monkeypatch) + _deny_killpg(monkeypatch) + monkeypatch.setattr(docker_recipe, "container_id", lambda p: CID) + calls = _fake_docker(monkeypatch) + out = le.stop(pid) + assert out["ok"] is True, out + assert out["stopped_container"] == "limcars-engine-probe", out + assert out["via"] == "docker stop" + stop_calls = [c for c in calls if "stop" in c] + assert stop_calls[0][:2] == ["docker", "stop"], stop_calls + assert stop_calls[0][-1] == CID, "must address the container id derived from the pid" + + +@posix_only +def test_docker_failure_is_reported_verbatim_instead_of_claiming_success(monkeypatch): + le, pid = _stub(monkeypatch) + _deny_killpg(monkeypatch) + monkeypatch.setattr(docker_recipe, "container_id", lambda p: CID) + _fake_docker(monkeypatch, rc=1, err="Cannot connect to the Docker daemon") + out = le.stop(pid) + assert out["ok"] is False and "Cannot connect to the Docker daemon" in out["error"], out + + +@posix_only +def test_no_docker_binary_falls_back_to_the_honest_message(monkeypatch): + le, pid = _stub(monkeypatch) + _deny_killpg(monkeypatch) + monkeypatch.setattr(docker_recipe, "container_id", lambda p: CID) + + def missing(cmd, **kw): + raise FileNotFoundError("docker") + monkeypatch.setattr(live_engines.subprocess, "run", missing) + out = le.stop(pid) + assert out["ok"] is False and "root-owned" in out["error"], out + + +@posix_only +def test_a_native_root_process_still_says_stop_it_where_it_was_started(monkeypatch): + """systemd-owned, not containerised: docker cannot help and must not be tried.""" + le, pid = _stub(monkeypatch) + _deny_killpg(monkeypatch) + monkeypatch.setattr(docker_recipe, "container_id", lambda p: None) + calls = _fake_docker(monkeypatch) + out = le.stop(pid) + assert out["ok"] is False and "systemd" in out["error"], out + assert not [c for c in calls if c[1] == "stop"], "no docker call for a non-container pid" + + +@posix_only +def test_the_container_handle_never_comes_from_the_request(monkeypatch): + """Only the pid crosses the wire; container_id() is the sole source of the handle.""" + seen = {} + le, pid = _stub(monkeypatch) + _deny_killpg(monkeypatch) + monkeypatch.setattr(docker_recipe, "container_id", lambda p: seen.setdefault("pid", p) and CID) + calls = _fake_docker(monkeypatch) + out = le.stop(pid) + assert out["ok"] is True + assert seen["pid"] == pid, "the handle must be derived from the clicked pid" + for c in calls: + assert str(pid) not in c[2:], f"pid must not be usable as a docker argument: {c}" + + +def test_the_worker_branch_also_reaches_the_container(monkeypatch): + """A worker pid has no own process group; its PermissionError must route too.""" + le, pid = _stub(monkeypatch) + monkeypatch.setattr(live_engines.procs, "HAS_PGRP", False) + monkeypatch.setattr(live_engines.procs, "ancestors", lambda p: []) + monkeypatch.setattr(live_engines.procs, "kill_tree", + lambda p: (_ for _ in ()).throw(PermissionError(1, "nope"))) + monkeypatch.setattr(docker_recipe, "container_id", lambda p: CID) + _fake_docker(monkeypatch) + out = le.stop(pid) + assert out["ok"] is True and out["via"] == "docker stop", out diff --git a/web/dashboard.html b/web/dashboard.html index 9096a18..ee7ce6c 100644 --- a/web/dashboard.html +++ b/web/dashboard.html @@ -156,6 +156,6 @@

Charts · last 15 min · sampled - + diff --git a/web/js/dashboard.js b/web/js/dashboard.js index aea5452..b38d6c4 100644 --- a/web/js/dashboard.js +++ b/web/js/dashboard.js @@ -1989,12 +1989,13 @@ async function loadEngines() { const row = b.closest('.eng-row'); const pid = row.dataset.pid; const label = row.querySelector('.rec-name').textContent; - if (!(await confirmDialog(`Stop ${label} (pid ${pid})?\nThis SIGTERMs → SIGKILLs its whole process group.`, '■ Stop'))) return; + if (!(await confirmDialog(`Stop ${label} (pid ${pid})?\nThis SIGTERMs → SIGKILLs its whole process group.\nA containerised engine is stopped with \u2018docker stop\u2019 so it can release the GPU cleanly.`, '■ Stop'))) return; b.disabled = true; b.textContent = 'stopping…'; const res = await authFetch(`/api/engines-live/${pid}/stop`, { method: 'POST' }, '🔒 Stopping an engine is password-protected') .then(r => r.json()).catch(err => ({ ok: false, error: String(err) })); if (res.ok === false) { b.disabled = false; b.textContent = '■ Stop'; toast('⚠ ' + (res.error || 'stop failed'), 'err'); } + else if (res.stopped_container) toast('■ stopped ' + res.stopped_container + ' (docker stop)'); loadEngines(); }); }