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
+240
@@ -0,0 +1,240 @@
|
|||||||
|
"""Server stats from the host's /proc, /sys, root filesystem and the Docker socket (no drawing)."""
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
from collections import defaultdict
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
TOP_PROCESSES = 5
|
||||||
|
CPU_SENSOR_TYPES = ("x86_pkg_temp", "coretemp", "cpu_thermal", "cpu-thermal")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Container:
|
||||||
|
name: str # short, readable
|
||||||
|
state: str # docker state: running, restarting, exited, ...
|
||||||
|
health: str | None # healthy, unhealthy, starting, or None without a healthcheck
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Proc:
|
||||||
|
name: str
|
||||||
|
cpu_pct: float # share of the whole machine's CPU capacity
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Stats:
|
||||||
|
cpu_pct: float | None
|
||||||
|
mem_pct: float | None
|
||||||
|
disk_pct: float | None
|
||||||
|
load: tuple[float, float, float] | None
|
||||||
|
temp_c: float | None
|
||||||
|
uptime_s: float | None
|
||||||
|
containers: tuple[Container, ...] | None # None: Docker unavailable
|
||||||
|
procs: tuple[Proc, ...]
|
||||||
|
|
||||||
|
|
||||||
|
# --- names and labels ---------------------------------------------------------
|
||||||
|
|
||||||
|
# Coolify appends a random 24 character id (and sometimes a deploy timestamp) to container names.
|
||||||
|
_SUFFIX = r"(?:-\d+(?:T\d+)?)?"
|
||||||
|
_HASHED = re.compile(rf"^(.+)-[a-z0-9]{{24}}{_SUFFIX}$")
|
||||||
|
_HASH_ONLY = re.compile(rf"^[a-z0-9]{{24}}{_SUFFIX}$")
|
||||||
|
|
||||||
|
|
||||||
|
def short_name(name: str, labels: dict[str, str], image: str) -> str:
|
||||||
|
"""A readable name: Coolify's random suffix stripped, else compose service label, else image, else hash start."""
|
||||||
|
match = _HASHED.match(name)
|
||||||
|
if match:
|
||||||
|
return match.group(1)
|
||||||
|
if not _HASH_ONLY.match(name):
|
||||||
|
return name
|
||||||
|
image_name = image.rsplit("/", 1)[-1].split(":")[0]
|
||||||
|
for candidate in (labels.get("com.docker.compose.service", ""), image_name):
|
||||||
|
if candidate and not _HASH_ONLY.match(candidate):
|
||||||
|
return candidate
|
||||||
|
return name[:8]
|
||||||
|
|
||||||
|
|
||||||
|
def status_label(c: Container) -> str:
|
||||||
|
if c.state == "running":
|
||||||
|
return {"healthy": "OK", "unhealthy": "UNHEALTHY"}.get(c.health, "UP")
|
||||||
|
return "RESTART" if c.state == "restarting" else "EXITED"
|
||||||
|
|
||||||
|
|
||||||
|
# --- parsers -------------------------------------------------------------------
|
||||||
|
|
||||||
|
def parse_cpu_times(proc_stat_text: str) -> tuple[int, int]:
|
||||||
|
"""(busy, total) jiffies from the aggregate `cpu ` line."""
|
||||||
|
for line in proc_stat_text.splitlines():
|
||||||
|
if line.startswith("cpu "):
|
||||||
|
fields = [int(x) for x in line.split()[1:]]
|
||||||
|
total = sum(fields[:8])
|
||||||
|
return total - fields[3] - fields[4], total
|
||||||
|
raise ValueError("no cpu line in /proc/stat")
|
||||||
|
|
||||||
|
|
||||||
|
def cpu_pct(prev: tuple[int, int] | None, cur: tuple[int, int]) -> float | None:
|
||||||
|
if prev is None or cur[1] - prev[1] <= 0:
|
||||||
|
return None
|
||||||
|
return (cur[0] - prev[0]) / (cur[1] - prev[1]) * 100
|
||||||
|
|
||||||
|
|
||||||
|
def parse_mem_pct(meminfo_text: str) -> float:
|
||||||
|
values = {}
|
||||||
|
for line in meminfo_text.splitlines():
|
||||||
|
key, _, rest = line.partition(":")
|
||||||
|
if key in ("MemTotal", "MemAvailable"):
|
||||||
|
values[key] = int(rest.split()[0])
|
||||||
|
return (1 - values["MemAvailable"] / values["MemTotal"]) * 100
|
||||||
|
|
||||||
|
|
||||||
|
def parse_pid_stat(text: str) -> tuple[str, int]:
|
||||||
|
"""(command name, utime + stime) from /proc/<pid>/stat; the name may contain spaces and parentheses."""
|
||||||
|
head, _, tail = text.rpartition(")")
|
||||||
|
name = head.partition("(")[2]
|
||||||
|
fields = tail.split()
|
||||||
|
return name, int(fields[11]) + int(fields[12])
|
||||||
|
|
||||||
|
|
||||||
|
# --- docker --------------------------------------------------------------------
|
||||||
|
|
||||||
|
class _UnixHTTPConnection(http.client.HTTPConnection):
|
||||||
|
def __init__(self, path: str, timeout: float) -> None:
|
||||||
|
super().__init__("localhost", timeout=timeout)
|
||||||
|
self._path = path
|
||||||
|
|
||||||
|
def connect(self) -> None:
|
||||||
|
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
|
self.sock.settimeout(self.timeout)
|
||||||
|
self.sock.connect(self._path)
|
||||||
|
|
||||||
|
|
||||||
|
_HEALTH = re.compile(r"\((healthy|unhealthy|health: starting)\)")
|
||||||
|
|
||||||
|
|
||||||
|
def list_containers(sock_path: str, timeout: float = 3.0) -> tuple[Container, ...]:
|
||||||
|
conn = _UnixHTTPConnection(sock_path, timeout)
|
||||||
|
try:
|
||||||
|
conn.request("GET", "/containers/json?all=1")
|
||||||
|
response = conn.getresponse()
|
||||||
|
if response.status != 200:
|
||||||
|
raise OSError(f"docker answered {response.status}")
|
||||||
|
payload = json.loads(response.read())
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
containers = []
|
||||||
|
for c in payload:
|
||||||
|
name = ((c.get("Names") or ["?"])[0]).lstrip("/")
|
||||||
|
health = _HEALTH.search(c.get("Status", ""))
|
||||||
|
containers.append(Container(
|
||||||
|
name=short_name(name, c.get("Labels") or {}, c.get("Image", "")),
|
||||||
|
state=c.get("State", "unknown"),
|
||||||
|
health={"health: starting": "starting"}.get(health.group(1), health.group(1)) if health else None,
|
||||||
|
))
|
||||||
|
return tuple(containers)
|
||||||
|
|
||||||
|
|
||||||
|
# --- reader --------------------------------------------------------------------
|
||||||
|
|
||||||
|
class StatsReader:
|
||||||
|
def __init__(self, proc_root: str = "/host/proc", sys_root: str = "/host/sys", disk_path: str = "/host/root",
|
||||||
|
docker_sock: str = "/var/run/docker.sock", docker_timeout: float = 3.0) -> None:
|
||||||
|
self._proc = Path(proc_root)
|
||||||
|
self._sys = Path(sys_root)
|
||||||
|
self._disk = disk_path
|
||||||
|
self._sock = docker_sock
|
||||||
|
self._docker_timeout = docker_timeout
|
||||||
|
self._prev_cpu: tuple[int, int] | None = None
|
||||||
|
self._prev_ticks: dict[int, int] = {}
|
||||||
|
self._failing: set[str] = set()
|
||||||
|
|
||||||
|
def _try(self, section: str, fn, default=None):
|
||||||
|
"""Run one section; a failure yields `default` and is logged once per failure streak."""
|
||||||
|
try:
|
||||||
|
value = fn()
|
||||||
|
except Exception as exc:
|
||||||
|
if section not in self._failing:
|
||||||
|
self._failing.add(section)
|
||||||
|
log.warning("stats: %s unavailable: %s", section, exc)
|
||||||
|
return default
|
||||||
|
if section in self._failing:
|
||||||
|
self._failing.discard(section)
|
||||||
|
log.info("stats: %s recovered", section)
|
||||||
|
return value
|
||||||
|
|
||||||
|
def read(self) -> Stats:
|
||||||
|
total_delta = None
|
||||||
|
cpu = None
|
||||||
|
try:
|
||||||
|
cur = parse_cpu_times((self._proc / "stat").read_text())
|
||||||
|
if self._prev_cpu is not None:
|
||||||
|
total_delta = cur[1] - self._prev_cpu[1]
|
||||||
|
cpu = cpu_pct(self._prev_cpu, cur)
|
||||||
|
self._prev_cpu = cur
|
||||||
|
except Exception as exc:
|
||||||
|
if "cpu" not in self._failing:
|
||||||
|
self._failing.add("cpu")
|
||||||
|
log.warning("stats: cpu unavailable: %s", exc)
|
||||||
|
else:
|
||||||
|
self._failing.discard("cpu")
|
||||||
|
|
||||||
|
return Stats(
|
||||||
|
cpu_pct=cpu,
|
||||||
|
mem_pct=self._try("memory", lambda: parse_mem_pct((self._proc / "meminfo").read_text())),
|
||||||
|
disk_pct=self._try("disk", self._disk_pct),
|
||||||
|
load=self._try("load", self._load),
|
||||||
|
temp_c=self._try("temperature", self._temperature),
|
||||||
|
uptime_s=self._try("uptime", lambda: float((self._proc / "uptime").read_text().split()[0])),
|
||||||
|
containers=self._try("docker", lambda: list_containers(self._sock, self._docker_timeout)),
|
||||||
|
procs=self._try("processes", lambda: self._processes(total_delta), ()),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _disk_pct(self) -> float:
|
||||||
|
st = os.statvfs(self._disk)
|
||||||
|
used = st.f_blocks - st.f_bfree
|
||||||
|
return used / (used + st.f_bavail) * 100
|
||||||
|
|
||||||
|
def _load(self) -> tuple[float, float, float]:
|
||||||
|
a, b, c = (self._proc / "loadavg").read_text().split()[:3]
|
||||||
|
return float(a), float(b), float(c)
|
||||||
|
|
||||||
|
def _temperature(self) -> float | None:
|
||||||
|
readings = [] # (is_cpu_sensor, celsius)
|
||||||
|
for zone in sorted((self._sys / "class" / "thermal").glob("thermal_zone*")):
|
||||||
|
try:
|
||||||
|
kind = (zone / "type").read_text().strip()
|
||||||
|
readings.append((kind in CPU_SENSOR_TYPES, int((zone / "temp").read_text()) / 1000))
|
||||||
|
except (OSError, ValueError):
|
||||||
|
continue # some zones exist but have no reading
|
||||||
|
if not readings:
|
||||||
|
return None
|
||||||
|
cpu_zones = [c for is_cpu, c in readings if is_cpu]
|
||||||
|
return max(cpu_zones or [c for _, c in readings])
|
||||||
|
|
||||||
|
def _processes(self, total_delta: int | None) -> tuple[Proc, ...]:
|
||||||
|
ticks: dict[int, int] = {}
|
||||||
|
names: dict[int, str] = {}
|
||||||
|
for entry in os.scandir(self._proc):
|
||||||
|
if not entry.name.isdigit():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
name, t = parse_pid_stat((Path(entry.path) / "stat").read_text())
|
||||||
|
except (OSError, ValueError, IndexError):
|
||||||
|
continue # the process exited while we were reading
|
||||||
|
ticks[int(entry.name)], names[int(entry.name)] = t, name
|
||||||
|
previous, self._prev_ticks = self._prev_ticks, ticks
|
||||||
|
if not total_delta or total_delta <= 0 or not previous:
|
||||||
|
return ()
|
||||||
|
per_name: dict[str, float] = defaultdict(float)
|
||||||
|
for pid, t in ticks.items():
|
||||||
|
if pid in previous and t > previous[pid]:
|
||||||
|
per_name[names[pid]] += (t - previous[pid]) / total_delta * 100
|
||||||
|
ranked = sorted(per_name.items(), key=lambda kv: kv[1], reverse=True)[:TOP_PROCESSES]
|
||||||
|
return tuple(Proc(name, pct) for name, pct in ranked)
|
||||||
+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