Files
harbour-server/server/statusd.py
T
Carlo Baratto edc8a8b4ed repo autosufficiente: collector server/ (statusd, unit systemd, firewall, install)
Il lato server era rimasto fuori dalla repo. Ora c'e' tutto sotto server/:
collector statusd.py (schema status/1), README con il contratto, regola
nftables LAN+VPN, unit systemd utente con percorsi %h e install.sh per una
macchina nuova.
2026-10-28 09:16:43 +01:00

318 lines
10 KiB
Python

#!/usr/bin/env python3
"""statusd — collector + server read-only di parametri host (schema status/1).
Prototipo. Nessuna dipendenza esterna, sola lettura, nessun comando che
modifichi lo stato. Due modalità:
statusd.py collect [--out FILE] # raccoglie e scrive il JSON
statusd.py serve [--file FILE] [--port N] [--token-file F]
statusd.py once # stampa il JSON su stdout
L'app non sa nulla di questo host: consuma solo lo schema status/1.
"""
from __future__ import annotations
import json
import os
import shutil
import socket
import subprocess
import sys
import time
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
SCHEMA = "status/1"
DEFAULT_OUT = "/run/statusd/status.json"
DEFAULT_PORT = 8792
# ── helper ────────────────────────────────────────────────────────────────
def run(cmd: list[str], timeout: float = 4.0) -> str:
"""Esegue un comando read-only e torna stdout (stringa vuota se fallisce)."""
try:
p = subprocess.run(
cmd, capture_output=True, text=True, timeout=timeout, check=False
)
return p.stdout if p.returncode == 0 else ""
except (OSError, subprocess.SubprocessError):
return ""
def pct(used: float, total: float) -> float:
return round(100.0 * used / total, 1) if total > 0 else 0.0
def iso(ts: float | None) -> str | None:
if not ts:
return None
return datetime.fromtimestamp(ts, timezone.utc).isoformat(timespec="seconds")
# ── collectors ────────────────────────────────────────────────────────────
def host_info() -> dict:
up = float(Path("/proc/uptime").read_text().split()[0])
load = os.getloadavg()
return {
"hostname": socket.gethostname(),
"kernel": os.uname().release,
"uptime_s": int(up),
"boot_time": iso(time.time() - up),
"load": [round(v, 2) for v in load],
}
def _cpu_ticks() -> tuple[int, int]:
f = Path("/proc/stat").read_text().splitlines()[0].split()
vals = [int(v) for v in f[1:]]
idle = vals[3] + (vals[4] if len(vals) > 4 else 0)
return idle, sum(vals)
def cpu_info(sample: float = 0.1) -> dict:
i0, t0 = _cpu_ticks()
time.sleep(sample)
i1, t1 = _cpu_ticks()
dt, di = t1 - t0, i1 - i0
percent = max(0.0, min(100.0, 100.0 * (dt - di) / dt)) if dt > 0 else 0.0
temps = []
for zone in sorted(Path("/sys/class/thermal").glob("thermal_zone*/temp")):
try:
temps.append(int(zone.read_text().strip()) / 1000.0)
except (OSError, ValueError):
continue
return {
"percent": round(percent, 1),
"temp_c": round(max(temps), 1) if temps else None,
"cores": os.cpu_count(),
}
def memory_info() -> dict:
mem = {}
for line in Path("/proc/meminfo").read_text().splitlines():
k, _, v = line.partition(":")
mem[k] = int(v.split()[0]) * 1024
total, avail = mem.get("MemTotal", 0), mem.get("MemAvailable", 0)
swap_total = mem.get("SwapTotal", 0)
swap_used = swap_total - mem.get("SwapFree", 0)
return {
"total_bytes": total,
"used_bytes": total - avail,
"percent": pct(total - avail, total),
"swap_total_bytes": swap_total,
"swap_used_bytes": swap_used,
}
def disks_info() -> list[dict]:
out = []
seen = set()
for mount in ("/", "/home"):
try:
u = shutil.disk_usage(mount)
except OSError:
continue
if u.total in seen:
continue
seen.add(u.total)
out.append(
{
"mount": mount,
"used_bytes": u.used,
"total_bytes": u.total,
"percent": pct(u.used, u.total),
}
)
return out
def services_info() -> dict:
raw = run(["systemctl", "list-units", "--state=failed", "--no-legend", "--plain"])
failed = []
for line in raw.splitlines():
parts = line.split(None, 4)
if parts:
failed.append({"unit": parts[0], "description": parts[4] if len(parts) > 4 else ""})
return {"failed": failed}
def containers_info() -> dict:
raw = run(["docker", "ps", "--format", "{{.Names}}\t{{.Status}}"], timeout=6)
items = []
for line in raw.splitlines():
name, _, status = line.partition("\t")
if name:
items.append(
{
"name": name,
"status": status,
"ok": "unhealthy" not in status.lower() and "restarting" not in status.lower(),
}
)
return {"running": items, "available": bool(raw) or _docker_present()}
def _docker_present() -> bool:
return shutil.which("docker") is not None
def backups_info() -> dict:
"""Stato dell'ultimo giro borg.timer (system unit), senza privilegi."""
out = run(
[
"systemctl",
"show",
"borg.service",
"-p",
"Result",
"-p",
"ActiveEnterTimestamp",
"-p",
"InactiveEnterTimestamp",
"-p",
"ActiveExitTimestamp",
"-p",
"ExecMainStatus",
]
)
info = dict(
line.split("=", 1) for line in out.splitlines() if "=" in line
)
# borg.service è oneshot: quando è "dead" ActiveEnterTimestamp è vuoto e
# l'ultimo giro si legge da InactiveEnterTimestamp (fine esecuzione).
age_h = None
stamp = info.get("ActiveEnterTimestamp") or info.get("InactiveEnterTimestamp", "")
if stamp:
try:
dt = datetime.strptime(stamp, "%a %Y-%m-%d %H:%M:%S %Z")
age_h = round((datetime.now() - dt).total_seconds() / 3600.0, 1)
except ValueError:
pass
return {
"name": "borg",
"last_run": stamp or None,
"result": info.get("Result") or None,
"exit_code": int(info["ExecMainStatus"]) if info.get("ExecMainStatus") else None,
"age_hours": age_h,
}
def access_info() -> dict:
raw = run(
["journalctl", "-u", "sshd", "--since", "24 hours ago", "--no-pager", "-o", "cat"],
timeout=8,
)
failed = sum(1 for line in raw.splitlines() if "Failed password" in line)
return {"ssh_failed_24h": failed}
def updates_info() -> dict:
raw = run(["apt", "list", "--upgradable"], timeout=20)
lines = [l for l in raw.splitlines() if "upgradable" in l and "/" in l]
security = sum(1 for l in lines if "-security" in l or "Security" in l)
return {"total": len(lines), "security": security}
def vpn_info() -> dict:
links = [p.name for p in Path("/sys/class/net").iterdir()]
wg = [n for n in links if n.startswith(("wg", "tun", "tap"))]
return {"interfaces": wg, "up": bool(wg)}
def collect() -> dict:
errors: list[str] = []
data: dict = {"schema": SCHEMA, "collected_at": iso(time.time())}
for name, fn in (
("host", host_info),
("cpu", cpu_info),
("memory", memory_info),
("disks", disks_info),
("services", services_info),
("containers", containers_info),
("backups", backups_info),
("access", access_info),
("updates", updates_info),
("net", vpn_info),
):
try:
data[name] = fn()
except Exception as exc: # un collector rotto non azzera il resto
data[name] = None
errors.append(f"{name}: {type(exc).__name__}: {exc}")
data["errors"] = errors
return data
# ── modalità ──────────────────────────────────────────────────────────────
def write_out(out: str) -> None:
path = Path(out)
path.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps(collect(), ensure_ascii=False, indent=1)
tmp = path.with_suffix(".tmp")
tmp.write_text(payload, encoding="utf-8")
os.replace(tmp, path)
def serve(file: str, port: int, token_file: str | None) -> None:
token = Path(token_file).read_text().strip() if token_file else None
src = Path(file)
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_args): # niente log: il token non deve finire su disco
return
def _send(self, code: int, body: bytes, ctype: str = "application/json") -> None:
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def do_GET(self): # noqa: N802
if self.path.split("?")[0] not in ("/v1/status", "/v1/status/"):
return self._send(404, b'{"error":"not found"}')
if token and self.headers.get("X-Status-Token", "") != token:
return self._send(401, b'{"error":"unauthorized"}')
try:
body = src.read_bytes()
except OSError:
return self._send(503, b'{"error":"no snapshot"}')
self._send(200, body)
ThreadingHTTPServer(("0.0.0.0", port), Handler).serve_forever()
def main(argv: list[str]) -> int:
mode = argv[1] if len(argv) > 1 else "once"
arg = dict(
(a.lstrip("-"), argv[i + 1])
for i, a in enumerate(argv)
if a.startswith("--") and i + 1 < len(argv)
)
if mode == "once":
print(json.dumps(collect(), ensure_ascii=False, indent=1))
return 0
if mode == "collect":
write_out(arg.get("out", DEFAULT_OUT))
return 0
if mode == "serve":
serve(
arg.get("file", DEFAULT_OUT),
int(arg.get("port", DEFAULT_PORT)),
arg.get("token-file"),
)
return 0
print(f"uso: {argv[0]} [once|collect|serve] [--out F] [--file F] [--port N]", file=sys.stderr)
return 2
if __name__ == "__main__":
raise SystemExit(main(sys.argv))