"""Network health from probe measurements: the live matrix, status strips, incidents, series.""" import time from collections import defaultdict from fastapi import APIRouter, HTTPException, Query from app.hub import settings from app.hub.db import db from app.hub.probes import is_online router = APIRouter() RANGES = {"1h": (3600, 60), "6h": (6 * 3600, 72), "24h": (86400, 96), "7d": (7 * 86400, 84), "30d": (30 * 86400, 90)} def _sev_sql() -> tuple[str, dict]: """Severity per measurement: 2 = failed, 1 = slow or lossy, 0 = fine.""" s = settings.get() sql = """CASE WHEN ok = 0 THEN 2 WHEN (loss IS NOT NULL AND loss >= 0.3) OR latency > (CASE WHEN method = 'dns' THEN :slow_dns WHEN kind = 'lan' THEN :slow_lan ELSE :slow_wan END) THEN 1 ELSE 0 END""" return sql, {"slow_dns": s.slow_dns_ms, "slow_lan": s.slow_lan_ms, "slow_wan": s.slow_wan_ms} def bucket_status(n: int, down: int, slow: int) -> str: if not n: return "nodata" if down * 2 >= n: return "down" if (down + slow) * 5 >= n: return "degraded" return "ok" RANK = {"nodata": 0, "ok": 1, "degraded": 2, "down": 3} def _range(range_: str, until: float | None): if range_ not in RANGES: raise HTTPException(400, f"range must be one of {', '.join(RANGES)}") span, buckets = RANGES[range_] until = until or time.time() return until - span, until, span / buckets, buckets def _probe_names(con) -> dict[int, dict]: return {r["id"]: {"id": r["id"], "name": r["name"], "online": is_online(r), "last_seen": r["last_seen"], "icmp": r["icmp"]} for r in con.execute("SELECT * FROM probes ORDER BY name COLLATE NOCASE")} def _target_order(target: str, kind: str) -> tuple: group = 0 if target.startswith("probe:") else 1 if target == "gateway" else 2 if kind == "lan" else 3 return (group, target) @router.get("/health/matrix") def matrix(window: int = Query(300, ge=60, le=3600)) -> dict: """Per probe and target, over the last `window` seconds.""" sev, params = _sev_sql() since = time.time() - window with db() as con: probes = _probe_names(con) rows = con.execute(f""" SELECT probe_id, target, method, MAX(label) label, MAX(kind) kind, COUNT(*) n, SUM(sev = 2) down, SUM(sev = 1) slow, AVG(CASE WHEN ok THEN latency END) latency, AVG(loss) loss, MAX(ts) last, (SELECT error FROM measurements e WHERE e.probe_id = m.probe_id AND e.target = m.target AND e.method = m.method AND e.ok = 0 AND e.ts >= :since ORDER BY ts DESC LIMIT 1) error FROM (SELECT *, {sev} sev FROM measurements WHERE ts >= :since AND method != 'throughput') m GROUP BY probe_id, target, method""", {**params, "since": since}).fetchall() cells: dict = defaultdict(lambda: {"methods": {}, "status": "nodata"}) targets: dict = {} for r in rows: if r["probe_id"] not in probes: continue key = (r["probe_id"], r["target"]) st = bucket_status(r["n"], r["down"], r["slow"]) c = cells[key] c["methods"][r["method"]] = {"status": st, "n": r["n"], "down": r["down"], "slow": r["slow"], "latency": r["latency"], "loss": r["loss"], "last": r["last"], "error": r["error"]} if RANK[st] > RANK[c["status"]]: c["status"] = st targets.setdefault(r["target"], {"target": r["target"], "label": r["label"], "kind": r["kind"]}) for t in targets.values(): if t["target"].startswith("probe:"): pid = int(t["target"].split(":", 1)[1]) if pid in probes: t["label"] = probes[pid]["name"] return { "window": window, "probes": list(probes.values()), "targets": sorted(targets.values(), key=lambda t: _target_order(t["target"], t["kind"])), "cells": [{"probe_id": k[0], "target": k[1], **v} for k, v in cells.items()], } @router.get("/health/strips") def strips(range: str = "24h", probe: int | None = None, until: float | None = None) -> dict: """Status per time bucket for every probe → target pair.""" since, until, width, n_buckets = _range(range, until) sev, params = _sev_sql() where = "ts >= :since AND ts < :until AND method != 'throughput'" + (" AND probe_id = :probe" if probe else "") with db() as con: probes = _probe_names(con) rows = con.execute(f""" SELECT probe_id, target, MAX(label) label, MAX(kind) kind, CAST((ts - :since) / :width AS INTEGER) b, COUNT(*) n, SUM(sev = 2) down, SUM(sev = 1) slow, AVG(CASE WHEN ok THEN latency END) latency FROM (SELECT *, {sev} sev FROM measurements WHERE {where}) GROUP BY probe_id, target, b""", {**params, "since": since, "until": until, "width": width, "probe": probe}).fetchall() series: dict = {} for r in rows: if r["probe_id"] not in probes or not 0 <= r["b"] < n_buckets: continue key = (r["probe_id"], r["target"]) if key not in series: label = r["label"] if r["target"].startswith("probe:"): label = probes.get(int(r["target"].split(":", 1)[1]), {}).get("name", label) series[key] = {"probe_id": r["probe_id"], "target": r["target"], "label": label, "kind": r["kind"], "buckets": [None] * n_buckets} series[key]["buckets"][r["b"]] = {"s": bucket_status(r["n"], r["down"], r["slow"]), "n": r["n"], "down": r["down"], "slow": r["slow"], "latency": round(r["latency"], 1) if r["latency"] is not None else None} out = sorted(series.values(), key=lambda x: (probes[x["probe_id"]]["name"].lower(), _target_order(x["target"], x["kind"]))) for s in out: s["uptime"] = _uptime(s["buckets"]) return {"since": since, "until": until, "width": width, "buckets": n_buckets, "probes": list(probes.values()), "series": out} def _uptime(buckets) -> float | None: n = sum(b["n"] for b in buckets if b) down = sum(b["down"] for b in buckets if b) return round(100 * (n - down) / n, 2) if n else None @router.get("/health/incidents") def incidents(range: str = "24h", probe: int | None = None, until: float | None = None, limit: int = Query(200, ge=1, le=1000)) -> dict: """Runs of failed or slow measurements, merged per probe → target when they are close together.""" since, until, _, _ = _range(range, until) s = settings.get() gap = s.probe_interval * 2.5 + 5 sev, params = _sev_sql() where = "ts >= :since AND ts < :until AND method != 'throughput'" + (" AND probe_id = :probe" if probe else "") with db() as con: probes = _probe_names(con) rows = con.execute(f"""SELECT * FROM (SELECT ts, probe_id, target, label, kind, method, ok, latency, loss, error, {sev} sev FROM measurements WHERE {where}) WHERE sev > 0 ORDER BY probe_id, target, ts""", {**params, "since": since, "until": until, "probe": probe}).fetchall() found, cur = [], None for r in rows: if r["probe_id"] not in probes: continue if cur and cur["probe_id"] == r["probe_id"] and cur["target"] == r["target"] and r["ts"] - cur["end"] <= gap: cur["end"] = r["ts"] else: cur = {"probe_id": r["probe_id"], "probe": probes[r["probe_id"]]["name"], "target": r["target"], "label": r["label"], "kind": r["kind"], "start": r["ts"], "end": r["ts"], "samples": 0, "failed": 0, "methods": set(), "max_latency": None, "error": None} found.append(cur) cur["samples"] += 1 cur["failed"] += r["sev"] == 2 cur["methods"].add(r["method"]) if r["latency"] is not None and r["ok"]: cur["max_latency"] = max(cur["max_latency"] or 0, r["latency"]) if r["error"]: cur["error"] = r["error"] now = time.time() out = [] for i in found: if not i["failed"] and i["samples"] < 2: continue # one slow sample is noise if i["target"].startswith("probe:"): i["label"] = probes.get(int(i["target"].split(":", 1)[1]), {}).get("name", i["label"]) i["type"] = "down" if i["failed"] else "degraded" i["methods"] = sorted(i["methods"]) i["ongoing"] = now - i["end"] < gap i["duration"] = i["end"] - i["start"] + s.probe_interval out.append(i) out.sort(key=lambda i: -i["start"]) return {"since": since, "until": until, "incidents": out[:limit], "total": len(out), "thresholds": {"lan_ms": s.slow_lan_ms, "wan_ms": s.slow_wan_ms, "dns_ms": s.slow_dns_ms, "loss": 0.3}} @router.get("/health/series") def series(probe: int, range: str = "24h", until: float | None = None) -> dict: """Latency, loss and throughput per target and method for one probe, bucketed.""" since, until, width, n_buckets = _range(range, until) with db() as con: probes = _probe_names(con) if probe not in probes: raise HTTPException(404, "No probe with that id") rows = con.execute(""" SELECT target, method, MAX(label) label, MAX(kind) kind, CAST((ts - :since) / :width AS INTEGER) b, COUNT(*) n, SUM(ok = 0) failed, AVG(CASE WHEN ok THEN latency END) avg, MAX(CASE WHEN ok THEN latency END) max, AVG(loss) loss, AVG(mbps) mbps FROM measurements WHERE probe_id = :probe AND ts >= :since AND ts < :until GROUP BY target, method, b""", {"since": since, "until": until, "width": width, "probe": probe}).fetchall() out: dict = {} for r in rows: if not 0 <= r["b"] < n_buckets: continue t = out.setdefault(r["target"], {"target": r["target"], "label": r["label"], "kind": r["kind"], "methods": {}}) if r["target"].startswith("probe:"): t["label"] = probes.get(int(r["target"].split(":", 1)[1]), {}).get("name", t["label"]) m = t["methods"].setdefault(r["method"], [None] * n_buckets) rnd = lambda v, d=1: None if v is None else round(v, d) m[r["b"]] = {"n": r["n"], "failed": r["failed"], "avg": rnd(r["avg"]), "max": rnd(r["max"]), "loss": rnd(r["loss"], 3), "mbps": rnd(r["mbps"])} targets = sorted(out.values(), key=lambda t: _target_order(t["target"], t["kind"])) return {"since": since, "until": until, "width": width, "buckets": n_buckets, "probe": probes[probe], "targets": targets} def prune(con, retention_days: float) -> int: return con.execute("DELETE FROM measurements WHERE ts < ?", (time.time() - retention_days * 86400,)).rowcount