feat: server stats readers

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
rickzkmandClaude Sonnet 5.5 committed 2026-10-22 13:21:56 +02:00
1 parent 65843aa958
commit 32f8c288be
4 files changed
+688

No files matched your search

+241
View File
@@ -0,0 +1,241 @@
import json
import socketserver
import threading
import time
from pathlib import Path
import pytest
import stats_data
from stats_data import (Container, StatsReader, cpu_pct, list_containers, parse_cpu_times,
parse_mem_pct, parse_pid_stat, short_name, status_label)
FIXTURES = Path(__file__).parent / "fixtures"
# --- pure parsers -----------------------------------------------------------
def test_parse_cpu_times_and_pct():
first = parse_cpu_times("cpu 100 0 50 800 50 0 0 0 0 0\ncpu0 1 2 3 4 5 6 7 8 9 10\n")
second = parse_cpu_times("cpu 200 0 100 1600 100 0 0 0 0 0\n")
assert first == (150, 1000) # busy = total - idle - iowait
assert second == (300, 2000)
assert cpu_pct(first, second) == pytest.approx(15.0)
def test_cpu_pct_none_without_previous():
assert cpu_pct(None, (300, 2000)) is None
def test_cpu_pct_none_on_zero_delta():
assert cpu_pct((300, 2000), (300, 2000)) is None
def test_parse_mem_pct_real_fixture():
# fixture: MemTotal 16147480 kB, MemAvailable 13909124 kB (home server)
assert parse_mem_pct((FIXTURES / "meminfo").read_text()) == pytest.approx(13.86, abs=0.01)
def test_parse_pid_stat_with_parens_and_spaces():
text = "4242 (my (odd) proc) S 1 4242 4242 0 -1 4194304 100 0 0 0 70 30 0 0 20 0 1 0 12345 1 2"
assert parse_pid_stat(text) == ("my (odd) proc", 100)
@pytest.mark.parametrize("name, expected", [
("n8n-ebe62bdjbp9f755kwh59lv8d", "n8n"),
("screen-pe28mpghgqnxaz12vyfyijrg-151725872213", "screen"),
("task-runners-ebe62bdjbp9f755kwh59lv8d", "task-runners"),
("plex-z0qh1wrbuzxo0jsfiazc3evc", "plex"),
("coolify-db", "coolify-db"),
])
def test_short_name_strips_coolify_suffix(name, expected):
assert short_name(name, {}, "x/y:1") == expected
def test_short_name_hash_only_uses_label_then_image_then_hash():
hashed = "jn5mdu87ituoxzyojk84ugdj-20261018T132559"
assert short_name(hashed, {"com.docker.compose.service": "web"}, "a/b:1") == "web"
assert short_name(hashed, {}, "ghcr.io/acme/tool:1.2") == "tool"
# the real container on the server: hash in name, label and image
assert short_name(hashed, {"com.docker.compose.service": hashed},
"jn5mdu87ituoxzyojk84ugdj:1833c2f1bf67cbe93e579ed6d9b569fe3cd3b668") == "jn5mdu87"
@pytest.mark.parametrize("state, health, expected", [
("running", "healthy", "OK"),
("running", None, "UP"),
("running", "starting", "UP"),
("running", "unhealthy", "UNHEALTHY"),
("restarting", None, "RESTART"),
("exited", None, "EXITED"),
])
def test_status_label_cases(state, health, expected):
assert status_label(Container("x", state, health)) == expected
# --- docker over a unix socket ---------------------------------------------
class FakeDocker:
"""Tiny HTTP server on a unix socket (relative path: macOS limits socket paths to ~100 chars)."""
def __init__(self, path: str, body: bytes = b"[]", hang: bool = False):
self.release = threading.Event()
outer = self
class Handler(socketserver.StreamRequestHandler):
def handle(self):
while self.rfile.readline() not in (b"\r\n", b""):
pass
if hang:
outer.release.wait(5)
return
self.wfile.write(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
+ f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n".encode() + body)
self.server = socketserver.ThreadingUnixStreamServer(path, Handler)
self.server.daemon_threads = True
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
def close(self):
self.release.set()
self.server.shutdown()
self.server.server_close()
@pytest.fixture
def docker_in(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
servers = []
def make(body=b"[]", hang=False):
s = FakeDocker("d.sock", body, hang)
servers.append(s)
return "d.sock"
yield make
for s in servers:
s.close()
def test_list_containers_parses_fixture(docker_in):
sock = docker_in((FIXTURES / "docker_containers.json").read_bytes())
containers = {c.name: c for c in list_containers(sock)}
assert containers["coolify"] == Container("coolify", "running", "healthy")
assert containers["n8n"].health == "healthy"
assert containers["screen"] == Container("screen", "running", None)
assert containers["apod-test"].state == "exited"
assert "jn5mdu87" in containers
def test_list_containers_missing_socket_raises(tmp_path):
with pytest.raises(OSError):
list_containers(str(tmp_path / "nope.sock"))
# --- reader on a fake /proc tree ---------------------------------------------
def write_proc(root: Path, cpu: str, procs: dict[int, str]):
root.mkdir(parents=True, exist_ok=True)
(root / "stat").write_text(cpu + "\n")
(root / "meminfo").write_text((FIXTURES / "meminfo").read_text())
(root / "loadavg").write_text("0.60 0.52 0.44 3/777 3724104\n")
(root / "uptime").write_text("934423.99 5265468.77\n")
for pid, stat in procs.items():
(root / str(pid)).mkdir(exist_ok=True)
(root / str(pid) / "stat").write_text(stat)
def pid_line(pid, name, ticks):
return f"{pid} ({name}) S 1 {pid} {pid} 0 -1 4194304 0 0 0 0 {ticks} 0 0 0 20 0 1 0 1 1 1\n"
def thermal(sys_root: Path, zones: dict[str, tuple[str, int]]):
for zone, (kind, milli) in zones.items():
z = sys_root / "class" / "thermal" / zone
z.mkdir(parents=True)
(z / "type").write_text(kind + "\n")
(z / "temp").write_text(f"{milli}\n")
def make_reader(tmp_path, docker_sock="missing.sock", **kw):
proc, sys_root = tmp_path / "proc", tmp_path / "sys"
thermal(sys_root, {"thermal_zone0": ("acpitz", 30000), "thermal_zone1": ("x86_pkg_temp", 41000)})
write_proc(proc, "cpu 100 0 50 800 50 0 0 0 0 0", {10: pid_line(10, "postgres", 0), 11: pid_line(11, "postgres", 0),
12: pid_line(12, "node", 0)})
return StatsReader(proc_root=str(proc), sys_root=str(sys_root), disk_path=str(tmp_path),
docker_sock=docker_sock, **kw), proc
def test_reader_first_read_has_no_cpu_pct(tmp_path):
reader, _ = make_reader(tmp_path)
s = reader.read()
assert s.cpu_pct is None and s.procs == ()
assert s.mem_pct == pytest.approx(13.86, abs=0.01)
assert s.load == (0.60, 0.52, 0.44)
assert s.uptime_s == pytest.approx(934423.99)
assert 0 <= s.disk_pct <= 100
def test_reader_second_read_has_cpu_and_grouped_processes(tmp_path):
reader, proc = make_reader(tmp_path)
reader.read()
write_proc(proc, "cpu 200 0 100 1600 100 0 0 0 0 0",
{10: pid_line(10, "postgres", 60), 11: pid_line(11, "postgres", 40), 12: pid_line(12, "node", 20)})
s = reader.read()
assert s.cpu_pct == pytest.approx(15.0)
names = [(p.name, round(p.cpu_pct, 1)) for p in s.procs]
assert names == [("postgres", 10.0), ("node", 2.0)] # share of total jiffies delta (1000), grouped by name
def test_reader_prefers_cpu_package_temperature(tmp_path):
reader, _ = make_reader(tmp_path)
assert reader.read().temp_c == 41.0
def test_reader_temperature_falls_back_to_hottest_zone(tmp_path):
reader, _ = make_reader(tmp_path)
for z in (tmp_path / "sys" / "class" / "thermal").glob("thermal_zone1"):
(z / "type").write_text("other\n")
assert reader.read().temp_c == 41.0
def test_reader_survives_vanished_process(tmp_path):
reader, proc = make_reader(tmp_path)
reader.read()
(proc / "12" / "stat").unlink() # directory still listed, file gone: the process exited mid-read
write_proc(proc, "cpu 200 0 100 1600 100 0 0 0 0 0", {10: pid_line(10, "postgres", 10)})
s = reader.read()
assert s.cpu_pct == pytest.approx(15.0)
assert [p.name for p in s.procs] == ["postgres"]
def test_reader_docker_down_still_returns_other_stats(tmp_path):
reader, _ = make_reader(tmp_path, docker_sock=str(tmp_path / "nope.sock"))
s = reader.read()
assert s.containers is None
assert s.mem_pct is not None
def test_reader_reads_containers(tmp_path, docker_in):
sock = docker_in((FIXTURES / "docker_containers.json").read_bytes())
reader, _ = make_reader(tmp_path, docker_sock=sock)
s = reader.read()
assert s.containers is not None and any(c.name == "n8n" for c in s.containers)
def test_reader_docker_hang_times_out(tmp_path, docker_in):
sock = docker_in(hang=True)
reader, _ = make_reader(tmp_path, docker_sock=sock, docker_timeout=0.3)
start = time.monotonic()
s = reader.read()
assert time.monotonic() - start < 2.0
assert s.containers is None and s.mem_pct is not None
def test_reader_missing_proc_files_give_none_not_error(tmp_path):
reader = StatsReader(proc_root=str(tmp_path / "nothing"), sys_root=str(tmp_path / "nothing"),
disk_path=str(tmp_path / "nothing"), docker_sock="missing.sock")
s = reader.read()
assert (s.cpu_pct, s.mem_pct, s.disk_pct, s.load, s.temp_c, s.uptime_s, s.containers) == (None,) * 7
assert s.procs == ()