Files
menzeljandClaude Opus 5 09bed274eb
CI / check (push) Successful in 7m4s
CI / build-and-push (push) Successful in 1m47s
Lock stacks during compose runs, cache stats, persist runtime state (0.47.0)
F7 — Nothing stopped two compose operations landing on the same stack. There
was a busy flag, but is_busy() was only ever read to colour the status column;
no lifecycle handler consulted it before acting. Two tabs, or auto-update
picking up a stack somebody had just clicked, both ran pull + up -d against the
same project and raced over recreating containers.

Lifecycle calls, the two deploy WebSockets and the auto-update pass now take a
real lock; a second caller gets 409 (or an error frame and close 4409) and
auto-update skips and retries next cycle. The lock is a row rather than a set
in one worker's memory, so it holds across workers and across a restart, and it
carries an expiry — a worker killed mid-deploy would otherwise strand the stack
with no fix short of editing the database.

F10 — /api/stacks/stats sampled every running container on every call, one
blocking daemon request each, and both the dashboard and the stacks list poll
it every five seconds. Two tabs on a 40-container host meant a sustained ~16
samples a second. Cached for 4s behind a lock so concurrent callers share one
sweep, the same shape dashboard_service already used for its fleet aggregate.

F11 — Three module dicts assumed exactly one uvicorn worker without saying so
and were lost on restart. The busy set is the lock above. The image update
cache is now mirrored to SQLite, so a restart shows the badges immediately
instead of blanking them for up to an hour, and the already-notified marks come
back with them rather than re-announcing the same updates. The login rate
limiter is a table, so it cannot be cleared by getting the process to restart
and no longer multiplies by the worker count.

The constraint that shaped this: compose_service and update_service are shared
with the agent, which has no database. Neither may import one. So the lock is a
separate service the central app enforces at its own entry points, and update
persistence is an opt-in callback the central app registers in its lifespan —
the agent registers nothing and behaves exactly as before. A test asserts
update_service never imports the database, since that is the kind of thing a
later change breaks silently.

Both new nets were checked by reverting the fix: dropping the lock from
_lifecycle fails six tests, removing the stats cache fails the one that names
the behaviour.

Also wires up cache pruning in the same sweep — without it both the dict and
the table grew one entry per image tag ever run, for the life of the install.

31 new tests (729 total).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dk43rmEeRfYi5wsLDbmfyG
2026-08-31 13:43:39 +02:00

143 lines
5.0 KiB
Python

"""Live CPU/memory stats for running containers, aggregated per compose stack.
Reads a one-shot ``docker stats`` sample per running container (the daemon
includes ``precpu_stats`` so a single read yields a usable CPU delta) and sums
them by ``com.docker.compose.project`` label, which equals the stack id.
Sampling is not free: it is one blocking call to the daemon *per running
container*, and the dashboard and the stacks list both poll this every five
seconds. Two open tabs on a 40-container host meant a sustained ~16 samples a
second. Results are therefore cached for :data:`CACHE_TTL`, the same shape
``dashboard_service`` already uses for its fleet aggregate — one sweep serves
every reader in the window, and the numbers stay well inside what a
five-second poll can show.
"""
from __future__ import annotations
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from docker_client import DockerError, get_client, safe_call
COMPOSE_PROJECT_LABEL = "com.docker.compose.project"
#: Slightly under the frontend's 5s poll, so a refresh usually gets fresh
#: numbers while concurrent readers still share one sweep.
CACHE_TTL = 4.0
_cache: dict = {"data": None, "ts": 0.0}
# Held across the sample so N simultaneous callers trigger one sweep, not N.
_lock = threading.Lock()
def _container_stats(container) -> dict | None:
try:
s = container.stats(stream=False)
except Exception: # noqa: BLE001 - skip containers that fail to report
return None
cpu = s.get("cpu_stats", {}) or {}
pre = s.get("precpu_stats", {}) or {}
cpu_delta = cpu.get("cpu_usage", {}).get("total_usage", 0) - pre.get("cpu_usage", {}).get(
"total_usage", 0
)
sys_delta = cpu.get("system_cpu_usage", 0) - pre.get("system_cpu_usage", 0)
online = (
cpu.get("online_cpus")
or len(cpu.get("cpu_usage", {}).get("percpu_usage") or [])
or 1
)
cores_used = (cpu_delta / sys_delta) * online if sys_delta > 0 and cpu_delta > 0 else 0.0
mem = s.get("memory_stats", {}) or {}
usage = mem.get("usage", 0) or 0
detail = mem.get("stats", {}) or {}
# Match `docker stats`: exclude reclaimable page cache from "used".
inactive = detail.get("inactive_file") or detail.get("total_inactive_file") or 0
mem_used = max(usage - inactive, 0)
hc = container.attrs.get("HostConfig", {}) or {}
nano = hc.get("NanoCpus") or 0
quota = hc.get("CpuQuota") or 0
period = hc.get("CpuPeriod") or 0
if nano:
cpu_limit = nano / 1e9
elif quota and period:
cpu_limit = quota / period
else:
cpu_limit = None
mem_limit = hc.get("Memory") or 0
return {
"project": (container.labels or {}).get(COMPOSE_PROJECT_LABEL),
"cores_used": cores_used,
"cpu_limit": cpu_limit,
"mem_used": mem_used,
"mem_limit": mem_limit or None,
}
def stack_stats(refresh: bool = False) -> dict:
"""Return {stack_id: {cpu_used, cpu_limit, mem_used, mem_limit, containers}}.
Limits are the summed assigned limits across the stack's containers, or null
when none of them have that limit set. Served from a short-lived cache
unless ``refresh`` is set.
"""
if not refresh and _cache["data"] is not None:
if time.monotonic() - _cache["ts"] < CACHE_TTL:
return _cache["data"]
with _lock:
# Somebody may have refreshed it while we waited for the lock.
if not refresh and _cache["data"] is not None:
if time.monotonic() - _cache["ts"] < CACHE_TTL:
return _cache["data"]
data = _sample()
_cache["data"] = data
_cache["ts"] = time.monotonic()
return data
def _sample() -> dict:
"""One full sweep across every running container."""
try:
client = get_client()
containers = safe_call(client.containers.list) # running only
except DockerError:
return {}
with ThreadPoolExecutor(max_workers=8) as pool:
samples = list(pool.map(_container_stats, containers))
agg: dict[str, dict] = {}
for st in samples:
if not st or not st["project"]:
continue
a = agg.setdefault(
st["project"],
{"cpu_used": 0.0, "cpu_limit": 0.0, "has_cpu": False,
"mem_used": 0, "mem_limit": 0, "has_mem": False, "containers": 0},
)
a["cpu_used"] += st["cores_used"]
a["mem_used"] += st["mem_used"]
a["containers"] += 1
if st["cpu_limit"]:
a["cpu_limit"] += st["cpu_limit"]
a["has_cpu"] = True
if st["mem_limit"]:
a["mem_limit"] += st["mem_limit"]
a["has_mem"] = True
return {
proj: {
"cpu_used": round(a["cpu_used"], 3),
"cpu_limit": round(a["cpu_limit"], 3) if a["has_cpu"] else None,
"mem_used": a["mem_used"],
"mem_limit": a["mem_limit"] if a["has_mem"] else None,
"containers": a["containers"],
}
for proj, a in agg.items()
}