feat: server stats readers
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
1 parent
65843aa958
commit
32f8c288be
4 files changed
+688
No files matched your search
+152
@@ -0,0 +1,152 @@
|
||||
[
|
||||
{
|
||||
"Names": [
|
||||
"/apod-test"
|
||||
],
|
||||
"Image": "apod-test",
|
||||
"State": "exited",
|
||||
"Status": "Exited (0) 36 minutes ago",
|
||||
"Labels": {}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/coolify"
|
||||
],
|
||||
"Image": "docker.io/coollabsio/coolify:4.4.7",
|
||||
"State": "running",
|
||||
"Status": "Up 11 hours (healthy)",
|
||||
"Labels": {
|
||||
"com.docker.compose.service": "coolify"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/coolify-db"
|
||||
],
|
||||
"Image": "postgres:15-alpine",
|
||||
"State": "running",
|
||||
"Status": "Up 11 hours (healthy)",
|
||||
"Labels": {
|
||||
"com.docker.compose.service": "postgres"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/coolify-redis"
|
||||
],
|
||||
"Image": "redis:7-alpine",
|
||||
"State": "running",
|
||||
"Status": "Up 11 hours (healthy)",
|
||||
"Labels": {
|
||||
"com.docker.compose.service": "redis"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/coolify-sentinel"
|
||||
],
|
||||
"Image": "docker.io/coollabsio/sentinel:1.1.2",
|
||||
"State": "running",
|
||||
"Status": "Up 22 hours (healthy)",
|
||||
"Labels": {}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/gitea-xj97t0yzdnfmqxlfkz9mekot"
|
||||
],
|
||||
"Image": "gitea/gitea:latest",
|
||||
"State": "running",
|
||||
"Status": "Up 12 hours (healthy)",
|
||||
"Labels": {
|
||||
"com.docker.compose.service": "gitea"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/jn5mdu87ituoxzyojk84ugdj-20261018T132559"
|
||||
],
|
||||
"Image": "jn5mdu87ituoxzyojk84ugdj:1833c2f1bf67cbe93e579ed6d9b569fe3cd3b668",
|
||||
"State": "running",
|
||||
"Status": "Up 3 days",
|
||||
"Labels": {
|
||||
"com.docker.compose.service": "jn5mdu87ituoxzyojk84ugdj-20261018T132559"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/task-runners-ebe62bdjbp9f755kwh59lv8d"
|
||||
],
|
||||
"Image": "n8nio/runners:2.22.3",
|
||||
"State": "running",
|
||||
"Status": "Up 3 days (healthy)",
|
||||
"Labels": {
|
||||
"com.docker.compose.service": "task-runners"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/n8n-ebe62bdjbp9f755kwh59lv8d"
|
||||
],
|
||||
"Image": "n8nio/n8n:next",
|
||||
"State": "running",
|
||||
"Status": "Up 3 days (healthy)",
|
||||
"Labels": {
|
||||
"com.docker.compose.service": "n8n"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/plex-z0qh1wrbuzxo0jsfiazc3evc"
|
||||
],
|
||||
"Image": "lscr.io/linuxserver/plex:latest",
|
||||
"State": "running",
|
||||
"Status": "Up 3 days (healthy)",
|
||||
"Labels": {
|
||||
"com.docker.compose.service": "plex"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/ntfy-x1aokzlzorj1eo05a0xbraln"
|
||||
],
|
||||
"Image": "binwiederhier/ntfy",
|
||||
"State": "running",
|
||||
"Status": "Up 3 days (healthy)",
|
||||
"Labels": {
|
||||
"com.docker.compose.service": "ntfy"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/coolify-proxy"
|
||||
],
|
||||
"Image": "traefik:v3.7",
|
||||
"State": "running",
|
||||
"Status": "Up 3 days (healthy)",
|
||||
"Labels": {
|
||||
"com.docker.compose.service": "traefik"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/screen-pe28mpghgqnxaz12vyfyijrg-151725872213"
|
||||
],
|
||||
"Image": "pe28mpghgqnxaz12vyfyijrg_screen:3ad6dc696346485bfc5d7fff001aded38b60579c",
|
||||
"State": "running",
|
||||
"Status": "Up 3 days",
|
||||
"Labels": {
|
||||
"com.docker.compose.service": "screen"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Names": [
|
||||
"/pump-monitor-qhcmhuhweydfg4tzbci4xxzt-093246425801"
|
||||
],
|
||||
"Image": "qhcmhuhweydfg4tzbci4xxzt_pump-monitor:9d7179308fd58d8d6582ce00d716844c3786360b",
|
||||
"State": "running",
|
||||
"Status": "Up 3 days (healthy)",
|
||||
"Labels": {
|
||||
"com.docker.compose.service": "pump-monitor"
|
||||
}
|
||||
}
|
||||
]
|
||||
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
MemTotal: 16147480 kB
|
||||
MemFree: 542768 kB
|
||||
MemAvailable: 13909124 kB
|
||||
Buffers: 1120732 kB
|
||||
Cached: 11485884 kB
|
||||
SwapCached: 44 kB
|
||||
Active: 2844728 kB
|
||||
Inactive: 10869760 kB
|
||||
Active(anon): 1362912 kB
|
||||
Inactive(anon): 2048 kB
|
||||
Active(file): 1481816 kB
|
||||
Inactive(file): 10867712 kB
|
||||
Unevictable: 27284 kB
|
||||
Mlocked: 27160 kB
|
||||
SwapTotal: 4194300 kB
|
||||
SwapFree: 4193532 kB
|
||||
Zswap: 0 kB
|
||||
Zswapped: 0 kB
|
||||
Dirty: 936 kB
|
||||
Writeback: 0 kB
|
||||
AnonPages: 1135056 kB
|
||||
Mapped: 1020564 kB
|
||||
Shmem: 249388 kB
|
||||
KReclaimable: 1353512 kB
|
||||
Slab: 1597868 kB
|
||||
SReclaimable: 1353512 kB
|
||||
SUnreclaim: 244356 kB
|
||||
KernelStack: 12088 kB
|
||||
PageTables: 26740 kB
|
||||
SecPageTables: 0 kB
|
||||
NFS_Unstable: 0 kB
|
||||
Bounce: 0 kB
|
||||
WritebackTmp: 0 kB
|
||||
CommitLimit: 12268040 kB
|
||||
Committed_AS: 6849128 kB
|
||||
VmallocTotal: 34359738367 kB
|
||||
VmallocUsed: 51616 kB
|
||||
VmallocChunk: 0 kB
|
||||
Percpu: 29568 kB
|
||||
HardwareCorrupted: 0 kB
|
||||
AnonHugePages: 0 kB
|
||||
ShmemHugePages: 0 kB
|
||||
ShmemPmdMapped: 0 kB
|
||||
FileHugePages: 0 kB
|
||||
FilePmdMapped: 0 kB
|
||||
Unaccepted: 0 kB
|
||||
HugePages_Total: 0
|
||||
HugePages_Free: 0
|
||||
HugePages_Rsvd: 0
|
||||
HugePages_Surp: 0
|
||||
Hugepagesize: 2048 kB
|
||||
Hugetlb: 0 kB
|
||||
DirectMap4k: 223920 kB
|
||||
DirectMap2M: 10031104 kB
|
||||
DirectMap1G: 6291456 kB
|
||||
@@ -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 == ()
|
||||
Reference in new issue
Block a user