#!/usr/bin/env python3 """ One health snapshot of the core stack host, as JSON on stdout. The daemon does not run on the host it watches, so each health cycle pipes this script to `ssh core python3 - ''` and reads everything back in one round trip: Uptime Kuma's monitors and up/down transitions, disk, memory, kernel OOM kills, container restart counts, boot time and a pending reboot. Judging the snapshot stays in maintainer.py; this only reads. Args (one JSON object in argv[1]): kuma_volume, sqlite_image where kuma.db lives and what reads it event_since Kuma heartbeat id already seen; null = watermark only oom_since unix time to read the kernel log from Stdlib only: it runs on the host's system python3. """ import json import os import re import shutil import subprocess import sys import time KUMA_QUERY = ( "select json_object('latest', (select max(time) from heartbeat), " "'monitors', (select json_group_array(json_object(" "'id', m.id, 'name', m.name, 'type', m.type, 'url', m.url, " "'hostname', m.hostname, 'port', m.port, " "'status', (select h.status from heartbeat h where h.monitor_id=m.id " "order by h.time desc limit 1), " "'msg', (select h.msg from heartbeat h where h.monitor_id=m.id " "order by h.time desc limit 1))) " "from monitor m where m.active=1));" ) # Kuma flags every up/down transition with important=1. This reads those since # a heartbeat id, plus the current max id (watermark), in one shot. KUMA_EVENTS_QUERY = ( "select json_object(" "'watermark', (select max(id) from heartbeat), " "'events', (select json_group_array(json_object(" "'monitor_id', h.monitor_id, 'name', m.name, 'status', h.status, " "'time', h.time, 'msg', h.msg)) " "from heartbeat h join monitor m on m.id = h.monitor_id " "where h.important = 1 {clause} order by h.id));" ) SPLIT = "--8<--" def run(argv, timeout=60): return subprocess.run(argv, capture_output=True, text=True, timeout=timeout) def unnest(data): # A json_group_array inside a subquery can come back as text. return {k: (json.loads(v) if isinstance(v, str) and v[:1] in "[{" else v) for k, v in data.items()} def kuma(args): """Both Kuma queries against one copy of kuma.db, read out of its named volume by a throwaway sqlite container (the file is root-owned).""" since = args.get("event_since") clause = "and 1=0" if since is None else f"and h.id > {int(since)}" script = (f"cp /src/kuma.db /tmp/k.db && sqlite3 /tmp/k.db \"{KUMA_QUERY}\" && " f"echo '{SPLIT}' && sqlite3 /tmp/k.db \"{KUMA_EVENTS_QUERY.format(clause=clause)}\"") out = run(["docker", "run", "--rm", "-v", f"{args['kuma_volume']}:/src:ro", args["sqlite_image"], "sh", "-c", script], timeout=120) if out.returncode != 0: raise RuntimeError(f"kuma read failed: {out.stderr.strip()[:300]}") status, _, events = out.stdout.partition(SPLIT) return unnest(json.loads(status.strip() or "{}")), unnest(json.loads(events.strip() or "{}")) def meminfo_mb(): info = {} with open("/proc/meminfo") as fh: for line in fh: key, _, rest = line.partition(":") info[key] = int(rest.split()[0]) // 1024 return info def boot_time(): with open("/proc/stat") as fh: for line in fh: if line.startswith("btime "): return int(line.split()[1]) return None def reboot_required(): """Packages waiting on a reboot, or None when none is pending.""" if not os.path.exists("/var/run/reboot-required"): return None try: with open("/var/run/reboot-required.pkgs") as fh: return sorted({p.strip() for p in fh if p.strip()}) except OSError: return [] def oom_kills_since(ts): """Kernel OOM-kill lines since ts (needs the adm or systemd-journal group).""" out = run(["journalctl", "-k", "-q", "--no-pager", "-o", "short-iso", "--since", f"@{int(ts)}"]).stdout return [l for l in out.splitlines() if re.search(r"out of memory|oom-kill|killed process", l, re.I)][:10] def container_restarts(): """{container id: [name, restart count, status]} for every container.""" ids = run(["docker", "ps", "-aq", "--no-trunc"]).stdout.split() if not ids: return {} out = run(["docker", "inspect", "-f", "{{.Id}}\t{{.Name}}\t{{.RestartCount}}\t{{.State.Status}}", *ids]).stdout result = {} for line in out.splitlines(): parts = line.split("\t") if len(parts) == 4: result[parts[0]] = [parts[1].lstrip("/"), int(parts[2]), parts[3]] return result def main(): args = json.loads(sys.argv[1]) if len(sys.argv) > 1 else {} snap = {"at": time.time()} def attempt(key, fn): try: snap[key] = fn() except Exception as e: # one blind spot must not blind the rest snap[key + "_error"] = f"{type(e).__name__}: {e}"[:400] if args.get("kuma_volume"): attempt("kuma", lambda: kuma(args)) if "kuma" in snap: snap["kuma"], snap["events"] = snap["kuma"] du = shutil.disk_usage("/") snap["disk"] = {"pct": round(100 * du.used / du.total, 1), "free_gb": du.free // 2**30} attempt("mem", meminfo_mb) attempt("btime", boot_time) attempt("reboot", reboot_required) attempt("ooms", lambda: oom_kills_since(args.get("oom_since") or time.time())) attempt("containers", container_restarts) print(json.dumps(snap)) if __name__ == "__main__": main()