#!/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 # Marcatore scritto dal backup (world-readable): unica fonte che sopravvive ai # riavvii. Creato con una riga di root, vedi README. BORG_MARKER = "/var/lib/borg-last-run" CGROUP_ROOT = Path("/sys/fs/cgroup") # ── 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 _cgroup_anon(path: Path) -> int | None: """Memoria anonima (heap, stack: RAM vera) di un cgroup, in byte.""" try: with open(path / "memory.stat") as fh: for line in fh: if line.startswith("anon "): return int(line.split()[1]) except OSError: return None return None def memory_consumers(limit: int = 12, min_mb: int = 16) -> list[dict]: """Chi occupa la RAM, ordinato dal più grande. /proc è montato con hidepid=invisible: i processi degli altri utenti sono invisibili, quindi il dettaglio per PID non è ottenibile senza root. I cgroup v2 invece sono leggibili e danno la memoria anonima per unità o contenitore. Sottraggo i discendenti, altrimenti un genitore conterebbe anche i figli e la somma sballerebbe. """ anon: dict[str, int] = {} stack = [CGROUP_ROOT] while stack: path = stack.pop() try: stack.extend(p for p in path.iterdir() if p.is_dir()) except OSError: pass value = _cgroup_anon(path) if value: anon[str(path)] = value # system.slice/docker-.scope -> nome del contenitore docker_names = {} for line in run(["docker", "ps", "--format", "{{.ID}} {{.Names}}"]).splitlines(): parts = line.split() if len(parts) >= 2: docker_names[parts[0]] = parts[1] rows = [] for path, value in anon.items(): children = sum( v for p, v in anon.items() if p != path and p.startswith(path + "/") ) exclusive = value - children if exclusive < min_mb * 1024 * 1024: continue leaf = path.rsplit("/", 1)[-1] kind = "service" name = leaf if leaf.startswith("docker-") and leaf.endswith(".scope"): cid = leaf[len("docker-") : -len(".scope")] name = docker_names.get(cid[:12], cid[:12]) kind = "container" elif leaf.endswith(".service"): name = leaf[: -len(".service")] elif leaf.endswith(".scope"): name = leaf[: -len(".scope")] kind = "session" elif leaf.endswith(".slice"): name = leaf[: -len(".slice")] kind = "slice" rows.append({"name": name, "kind": kind, "bytes": exclusive}) rows.sort(key=lambda row: -row["bytes"]) return rows[:limit] 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, "consumers": memory_consumers(), } 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: """Età dell'ultimo giro di backup, da fonti leggibili senza privilegi. Ordine delle fonti, dalla più affidabile: 1. /var/lib/borg-last-run — marcatore scritto dal backup stesso; sopravvive ai riavvii (i timestamp delle unit systemd NO: al boot tornano vuoti, ed è il motivo per cui la card mostrava "—"). 2. timestamp dell'unit borg.service — valido solo nello stesso avvio. 3. niente: age_hours null. Meglio un "—" onesto di un numero inventato. """ path = Path(BORG_MARKER) last_run = None age_h = None source = None try: st = path.stat() last_run = iso(st.st_mtime) age_h = round((time.time() - st.st_mtime) / 3600.0, 1) source = "marker" except OSError: pass 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 ) if age_h is None: # borg.service è oneshot: da spento ActiveEnterTimestamp è vuoto e # l'ultimo giro si legge da InactiveEnterTimestamp (fine esecuzione). 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) last_run = stamp source = "systemd" except ValueError: pass return { "name": "borg", "last_run": last_run, "result": info.get("Result") or None, "exit_code": int(info["ExecMainStatus"]) if info.get("ExecMainStatus") else None, "age_hours": age_h, "source": source, } def ups_info() -> dict | None: """Stato dell'UPS da NUT (upsc). Nessuna scrittura, nessun privilegio.""" names = run(["upsc", "-l"], timeout=5).split() if not names: return None name = names[0] raw = run(["upsc", name], timeout=8) if not raw: return {"name": name, "available": False} vals = {} for line in raw.splitlines(): key, _, value = line.partition(":") if key and value.strip(): vals[key.strip()] = value.strip() def num(key, cast=float): try: return cast(vals[key]) except (KeyError, ValueError): return None return { "name": name, "available": True, "status": vals.get("ups.status"), "charge_pct": num("battery.charge"), "runtime_s": num("battery.runtime"), "load_pct": num("ups.load"), "input_voltage": num("input.voltage"), "battery_voltage": num("battery.voltage"), "input_frequency": num("input.frequency"), "beeper": vals.get("ups.beeper.status"), "driver": vals.get("driver.name"), } 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) packages = [l.split("/")[0].strip() for l in lines][:20] # Quando sono state aggiornate le liste apt. Senza questo dato un "0" non e' # verificabile: un dist-upgrade automatico puo' aver appena svuotato la # lista e sembra che il collector non veda nulla (successo davvero il # 2026-10-28 con bind9-*: Webmin mostrava 3 update, lo snapshot 0). lists_at = None try: stamps = [p.stat().st_mtime for p in Path("/var/lib/apt/lists").glob("*InRelease")] if stamps: lists_at = iso(max(stamps)) except OSError: pass return { "total": len(lines), "security": security, "packages": packages, "lists_updated_at": lists_at, } 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), ("ups", ups_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))