diff --git a/README.md b/README.md index bb3108a..f936ff0 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ documentato, quindi funziona con qualunque host che parli lo stesso formato. `GET /v1/status` con header `X-Status-Token: ` → JSON **schema `status/1`**. -Il contratto è descritto nel progetto del collector: `statod/README.md`. +Il contratto è descritto in [`server/README.md`](server/README.md). Il punto fermo: **ogni sezione può essere `null`** (collector fallito) e il client non deve assumere la presenza di un campo. diff --git a/server/53-statusd-lan-vpn.conf b/server/53-statusd-lan-vpn.conf new file mode 100644 index 0000000..0c5466e --- /dev/null +++ b/server/53-statusd-lan-vpn.conf @@ -0,0 +1,15 @@ +#!/usr/bin/env nft -f +# statusd (harbour-server): API read-only tcp/8792 raggiungibile solo dalla +# LAN di casa (192.168.3.0/24) e dalla VPN WireGuard (10.10.10.0/24). +# +# Serve perché il firewall YunoHost ha "policy drop" e apre solo le porte del +# define tcp_ports (22, 25, 53, 80, 443, 587, 993, 5349, 5350): senza questa +# regola il telefono viene scartato e l'app resta muta, pur essendo statusd +# regolarmente in ascolto. +# +# Regola custom: YunoHost non la gestisce, quindi sopravvive a regen e +# aggiornamenti del firewall. Caricata da /etc/nftables.conf via +# include "/etc/nftables.d/*.conf". +# +# Nota: se in futuro si abilita IPv6 pubblico, replicare la regola per ip6. +insert rule inet filter input ip saddr { 192.168.3.0/24, 10.10.10.0/24 } tcp dport { 8792 } ct state new counter accept diff --git a/server/README.md b/server/README.md new file mode 100644 index 0000000..66b4289 --- /dev/null +++ b/server/README.md @@ -0,0 +1,87 @@ +# statod — parametri del server in sola lettura + +Collector che produce uno snapshot JSON dei parametri di un host Linux e lo +serve su HTTP. L'app Sailfish **harbour-server** lo consuma; il contratto è lo +schema descritto qui sotto, quindi qualunque macchina che produca lo stesso +JSON funziona con l'app senza modifiche. + +Nessun comando di scrittura, nessun `sudo`: si leggono `/proc`, `systemctl +show`, `docker ps`, `journalctl` e `apt list`. + +## Installazione (utente, senza root) + +```sh +./install.sh +``` + +Copia il collector in `~/.local/share/statod/`, genera il token in +`~/.config/statusd/token` (0600) e attiva le due unit utente. La sopravvivenza +al logout richiede `loginctl enable-linger `. + +## Esposizione + +`statusd-http.service` ascolta su `0.0.0.0:8792`. Il firewall YunoHost ha +policy `drop`: senza regola la porta è chiusa anche se il servizio è in +ascolto. La regola è `53-statusd-lan-vpn.conf` (LAN `192.168.3.0/24` + VPN +WireGuard `10.10.10.0/24`), sul modello di `53-go2rtc-lan-vpn.conf`: + +```sh +sudo install -m 644 server/53-statusd-lan-vpn.conf /etc/nftables.d/ +sudo nft -f /etc/nftables.d/53-statusd-lan-vpn.conf +``` + +## Protocollo + +``` +GET /v1/status +X-Status-Token: +→ 200 application/json snapshot status/1 +→ 401 token assente o errato +→ 503 snapshot non ancora prodotto +``` + +Nessun log HTTP: il token non finisce su disco. Il server non ha altre rotte. + +## Schema `status/1` + +```jsonc +{ + "schema": "status/1", + "collected_at": "2026-10-27T19:12:21+00:00", + "host": { "hostname": "…", "kernel": "…", "uptime_s": 209666, + "boot_time": "…", "load": [0.3, 0.57, 0.48] }, + "cpu": { "percent": 7.1, "temp_c": 41.0, "cores": 4 }, + "memory": { "total_bytes": 0, "used_bytes": 0, "percent": 0, + "swap_total_bytes": 0, "swap_used_bytes": 0 }, + "disks": [ { "mount": "/", "used_bytes": 0, "total_bytes": 0, "percent": 0 } ], + "containers": { "running": [ { "name": "…", "status": "Up 2 days", "ok": true } ], + "available": true }, + "backups": { "name": "borg", "last_run": "…", "result": "success", + "exit_code": 0, "age_hours": 41.5 }, + "services": { "failed": [ { "unit": "…", "description": "…" } ] }, + "access": { "ssh_failed_24h": 0 }, + "updates": { "total": 0, "security": 0 }, + "net": { "interfaces": ["wg0"], "up": true }, + "errors": [ "collector: motivo" ] +} +``` + +Regole del contratto: + +- **Ogni sezione può essere `null`** se il suo collector è fallito, e il + motivo compare in `errors`. Un client non deve assumere la presenza di un + campo. +- Percentuali in `0..100` con un decimale; bytes come interi. +- `age_hours` è l'età dell'ultimo giro di backup: è il campo che fa scattare + l'allarme, non `result` (un backup mai partito ha `result` assente). +- Aggiungere campi è compatibile; rimuoverli o cambiarne il tipo richiede + `schema: "status/2"`. + +## Note d'ambiente + +- `borg.service` è oneshot: da spento `ActiveEnterTimestamp` è vuoto e + l'ultimo giro si legge da `InactiveEnterTimestamp`. +- La raccolta costa ~0,5 s (dominata da `apt list --upgradable` e + `journalctl`), per questo gira su timer e non a ogni richiesta. +- `smartctl` non è installato: nessun dato SMART. Per aggiungerlo servono i + permessi root (`smartd` o un comando in `sudoers.d`). diff --git a/server/install.sh b/server/install.sh new file mode 100644 index 0000000..9214db1 --- /dev/null +++ b/server/install.sh @@ -0,0 +1,45 @@ +#!/bin/sh +# install.sh — installa il collector statusd come servizio UTENTE (senza root). +# +# Cosa fa: +# 1. copia statusd.py in ~/.local/share/statod/ +# 2. genera il token in ~/.config/statusd/token (0600) se non esiste +# 3. installa le unit systemd utente e le attiva +# +# NON tocca il firewall: la porta 8792 resta chiusa finche' non si applica +# 53-statusd-lan-vpn.conf come root (vedi README.md). +set -eu + +qui=$(cd "$(dirname "$0")" && pwd) +dest="$HOME/.local/share/statod" + +echo "── installazione in $dest" +mkdir -p "$dest" "$HOME/.cache/statusd" "$HOME/.config/statusd" "$HOME/.config/systemd/user" +cp "$qui/statusd.py" "$dest/statusd.py" + +if [ -s "$HOME/.config/statusd/token" ]; then + echo "── token gia' presente, lo lascio com'e'" +else + python3 -c "import secrets; print(secrets.token_urlsafe(24))" > "$HOME/.config/statusd/token" + chmod 600 "$HOME/.config/statusd/token" + echo "── token generato: $HOME/.config/statusd/token" +fi + +cp "$qui/systemd/statusd-collect.service" "$qui/systemd/statusd-collect.timer" \ + "$qui/systemd/statusd-http.service" "$HOME/.config/systemd/user/" + +export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}" +systemctl --user daemon-reload +systemctl --user enable --now statusd-collect.timer statusd-http.service + +echo "── stato" +systemctl --user is-active statusd-collect.timer statusd-http.service + +echo +echo "Token (da incollare nell'app): cat $HOME/.config/statusd/token" +echo "Prova locale: curl -s -H \"X-Status-Token: \$(cat ~/.config/statusd/token)\" \\" +echo " -o /dev/null -w '%{http_code}\\n' http://127.0.0.1:8792/v1/status" +echo +echo "Per l'accesso dal telefono serve la regola firewall (root):" +echo " sudo install -m 644 $qui/53-statusd-lan-vpn.conf /etc/nftables.d/" +echo " sudo nft -f /etc/nftables.d/53-statusd-lan-vpn.conf" diff --git a/server/statusd.py b/server/statusd.py new file mode 100644 index 0000000..7c43895 --- /dev/null +++ b/server/statusd.py @@ -0,0 +1,317 @@ +#!/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)) diff --git a/server/systemd/statusd-collect.service b/server/systemd/statusd-collect.service new file mode 100644 index 0000000..4547010 --- /dev/null +++ b/server/systemd/statusd-collect.service @@ -0,0 +1,10 @@ +[Unit] +Description=statusd — snapshot dei parametri host (schema status/1) +After=network.target + +[Service] +Type=oneshot +WorkingDirectory=%h/.local/share/statod +ExecStart=/usr/bin/python3 %h/.local/share/statod/statusd.py collect --out %h/.cache/statusd/status.json +Nice=10 +IOSchedulingClass=idle diff --git a/server/systemd/statusd-collect.timer b/server/systemd/statusd-collect.timer new file mode 100644 index 0000000..8972590 --- /dev/null +++ b/server/systemd/statusd-collect.timer @@ -0,0 +1,11 @@ +[Unit] +Description=statusd — raccolta periodica parametri host + +[Timer] +OnBootSec=20s +OnUnitActiveSec=60s +AccuracySec=5s +Unit=statusd-collect.service + +[Install] +WantedBy=timers.target diff --git a/server/systemd/statusd-http.service b/server/systemd/statusd-http.service new file mode 100644 index 0000000..0111341 --- /dev/null +++ b/server/systemd/statusd-http.service @@ -0,0 +1,16 @@ +[Unit] +Description=statusd — API read-only status/1 su :8792 (LAN + VPN) +After=network-online.target statusd-collect.timer +Wants=statusd-collect.timer + +[Service] +Type=simple +WorkingDirectory=%h/.local/share/statod +ExecStart=/usr/bin/python3 %h/.local/share/statod/statusd.py serve --file %h/.cache/statusd/status.json --port 8792 --token-file %h/.config/statusd/token +Restart=always +RestartSec=3 +NoNewPrivileges=yes +PrivateTmp=yes + +[Install] +WantedBy=default.target