Probes log locally only while the hub is unreachable; the hub confirms silences with that log
Probe: no access log, nothing written while reports get through. When the hub can't be reached, failed reports go to data/outage.jsonl and unsent results to data/backlog.jsonl (survives restarts). The first report that gets through uploads both and they are deleted. Hub: a probe that misses reports gets a "Not reporting" incident. When it reports again, the runs from its outage log become confirmed "Hub unreachable" incidents; the rest of the silence (probe off or restarting) is dropped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
462525b1e2
commit
be727949c1
13 changed files with 449 additions and 32 deletions
|
|
@ -49,6 +49,16 @@ CREATE TABLE IF NOT EXISTS devices (
|
|||
notes TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS d_ip ON devices(ip);
|
||||
CREATE TABLE IF NOT EXISTS probe_outages ( -- see outages.py
|
||||
id INTEGER PRIMARY KEY,
|
||||
probe_id INTEGER NOT NULL,
|
||||
start_ts REAL NOT NULL,
|
||||
end_ts REAL, -- NULL while the probe is still silent
|
||||
confirmed INTEGER NOT NULL DEFAULT 0, -- 1 = backed by the probe's outage log
|
||||
failures INTEGER, -- failed reports the probe logged
|
||||
error TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS po_probe ON probe_outages(probe_id, end_ts);
|
||||
CREATE TABLE IF NOT EXISTS ip_mac (
|
||||
ip TEXT PRIMARY KEY,
|
||||
mac TEXT NOT NULL,
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ from collections import defaultdict
|
|||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
|
||||
from app.hub import settings
|
||||
from app.hub import outages, settings
|
||||
from app.hub.db import db
|
||||
from app.hub.probes import is_online
|
||||
|
||||
|
|
@ -136,7 +136,8 @@ def _uptime(buckets) -> float | 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."""
|
||||
"""Runs of failed or slow measurements, merged per probe → target when they are close together,
|
||||
plus stretches when a probe didn't report (see outages.py)."""
|
||||
since, until, _, _ = _range(range, until)
|
||||
s = settings.get()
|
||||
gap = s.probe_interval * 2.5 + 5
|
||||
|
|
@ -147,6 +148,7 @@ def incidents(range: str = "24h", probe: int | None = None, until: float | None
|
|||
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()
|
||||
silent = outages.incidents(con, probes, since, until, probe)
|
||||
found, cur = [], None
|
||||
for r in rows:
|
||||
if r["probe_id"] not in probes:
|
||||
|
|
@ -177,6 +179,7 @@ def incidents(range: str = "24h", probe: int | None = None, until: float | None
|
|||
i["ongoing"] = now - i["end"] < gap
|
||||
i["duration"] = i["end"] - i["start"] + s.probe_interval
|
||||
out.append(i)
|
||||
out += silent
|
||||
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}}
|
||||
|
|
@ -212,4 +215,6 @@ def series(probe: int, range: str = "24h", until: float | None = None) -> dict:
|
|||
|
||||
|
||||
def prune(con, retention_days: float) -> int:
|
||||
return con.execute("DELETE FROM measurements WHERE ts < ?", (time.time() - retention_days * 86400,)).rowcount
|
||||
n = con.execute("DELETE FROM measurements WHERE ts < ?", (time.time() - retention_days * 86400,)).rowcount
|
||||
outages.prune(con, retention_days)
|
||||
return n
|
||||
|
|
|
|||
74
app/hub/outages.py
Normal file
74
app/hub/outages.py
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
"""Probes that stop reporting.
|
||||
|
||||
When a probe misses its reports, the hub opens a "not reporting" incident (unconfirmed). When
|
||||
the probe reports again, it sends its local outage log: runs of reports it tried to send but
|
||||
couldn't get through. Those runs replace the hub's incident as confirmed outages. Whatever the
|
||||
log doesn't cover is dropped: a probe that was switched off or restarting logged nothing."""
|
||||
|
||||
import time
|
||||
|
||||
from app.hub import settings
|
||||
|
||||
|
||||
def threshold() -> float:
|
||||
"""Silence after which a probe counts as not reporting (matches probes.is_online)."""
|
||||
return settings.get().probe_interval * 3 + 10
|
||||
|
||||
|
||||
def open_silences(con, now: float | None = None) -> int:
|
||||
"""Open an incident for every probe that has gone quiet and doesn't have one yet."""
|
||||
now = now or time.time()
|
||||
rows = con.execute(
|
||||
"""SELECT id, last_seen FROM probes WHERE last_seen IS NOT NULL AND last_seen < ?
|
||||
AND id NOT IN (SELECT probe_id FROM probe_outages WHERE end_ts IS NULL)""", (now - threshold(),)).fetchall()
|
||||
con.executemany("INSERT INTO probe_outages(probe_id, start_ts, confirmed) VALUES (?, ?, 0)",
|
||||
[(r["id"], r["last_seen"]) for r in rows])
|
||||
return len(rows)
|
||||
|
||||
|
||||
def resolve(con, probe_id: int, last_seen: float | None, runs: list[dict], now: float | None = None) -> None:
|
||||
"""A report arrived. Settle the silence before it (if any) against the probe's outage log."""
|
||||
now = now or time.time()
|
||||
open_rows = con.execute("SELECT * FROM probe_outages WHERE probe_id = ? AND end_ts IS NULL", (probe_id,)).fetchall()
|
||||
starts = [r["start_ts"] for r in open_rows]
|
||||
if last_seen and now - last_seen > threshold():
|
||||
starts.append(last_seen) # e.g. the hub itself was down and never got to open one
|
||||
if not starts:
|
||||
return
|
||||
gap_start = min(starts)
|
||||
con.execute("DELETE FROM probe_outages WHERE probe_id = ? AND end_ts IS NULL", (probe_id,))
|
||||
interval = settings.get().probe_interval
|
||||
for run in sorted(runs, key=lambda r: r["start"]):
|
||||
if run["end"] < gap_start or run["start"] > now:
|
||||
continue
|
||||
# The first failed report came up to one interval after the outage began. A run that
|
||||
# lasted until this report ended now; one that stopped earlier ended with the probe.
|
||||
start = max(gap_start, run["start"] - interval)
|
||||
end = now if now - run["end"] <= interval * 2 + 15 else run["end"]
|
||||
con.execute("INSERT INTO probe_outages(probe_id, start_ts, end_ts, confirmed, failures, error) VALUES (?, ?, ?, 1, ?, ?)",
|
||||
(probe_id, start, end, run["failures"], run["error"] or None))
|
||||
|
||||
|
||||
def incidents(con, probes: dict, since: float, until: float, probe: int | None = None) -> list[dict]:
|
||||
"""Rows shaped like health incidents (kind "report", target "hub")."""
|
||||
now = time.time()
|
||||
rows = con.execute(
|
||||
"SELECT * FROM probe_outages WHERE start_ts < ? AND (end_ts IS NULL OR end_ts >= ?)" + (" AND probe_id = ?" if probe else ""),
|
||||
(until, since, probe) if probe else (until, since)).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
if r["probe_id"] not in probes:
|
||||
continue
|
||||
end = r["end_ts"] or now
|
||||
out.append({
|
||||
"probe_id": r["probe_id"], "probe": probes[r["probe_id"]]["name"], "target": "hub", "label": "Reports to the hub",
|
||||
"kind": "report", "start": r["start_ts"], "end": end, "duration": end - r["start_ts"], "ongoing": r["end_ts"] is None,
|
||||
"type": "down", "confirmed": bool(r["confirmed"]), "samples": r["failures"] or 0, "failed": r["failures"] or 0,
|
||||
"methods": [], "max_latency": None, "error": r["error"],
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def prune(con, retention_days: float) -> int:
|
||||
return con.execute("DELETE FROM probe_outages WHERE end_ts IS NOT NULL AND end_ts < ?",
|
||||
(time.time() - retention_days * 86400,)).rowcount
|
||||
|
|
@ -8,7 +8,7 @@ import time
|
|||
from fastapi import APIRouter, Header, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.hub import devices, settings
|
||||
from app.hub import devices, outages, settings
|
||||
from app.hub.db import db
|
||||
|
||||
router = APIRouter()
|
||||
|
|
@ -44,6 +44,14 @@ class Neighbor(BaseModel):
|
|||
mac: str = Field(max_length=32)
|
||||
|
||||
|
||||
class OutageRun(BaseModel):
|
||||
"""A run of reports the probe couldn't get through (from its local outage log)."""
|
||||
start: float
|
||||
end: float
|
||||
failures: int = Field(ge=1)
|
||||
error: str | None = Field(default=None, max_length=300)
|
||||
|
||||
|
||||
class Report(BaseModel):
|
||||
version: str | None = Field(default=None, max_length=40)
|
||||
hostname: str | None = Field(default=None, max_length=255)
|
||||
|
|
@ -52,6 +60,7 @@ class Report(BaseModel):
|
|||
icmp: bool | None = None
|
||||
measurements: list[Measurement] = Field(default_factory=list, max_length=MAX_BATCH)
|
||||
neighbors: list[Neighbor] = Field(default_factory=list, max_length=4096)
|
||||
outages: list[OutageRun] = Field(default_factory=list, max_length=1000)
|
||||
|
||||
|
||||
def is_online(row, now: float | None = None) -> bool:
|
||||
|
|
@ -132,6 +141,7 @@ def delete_probe(probe_id: int, keep_history: bool = False) -> None:
|
|||
with db() as con:
|
||||
_get(con, probe_id)
|
||||
con.execute("DELETE FROM probes WHERE id = ?", (probe_id,))
|
||||
con.execute("DELETE FROM probe_outages WHERE probe_id = ?", (probe_id,))
|
||||
if not keep_history:
|
||||
con.execute("DELETE FROM measurements WHERE probe_id = ?", (probe_id,))
|
||||
|
||||
|
|
@ -171,6 +181,7 @@ def report(body: Report, request: Request, authorization: str = Header(default="
|
|||
row = con.execute("SELECT * FROM probes WHERE token = ?", (token,)).fetchone() if token else None
|
||||
if not row:
|
||||
raise HTTPException(401, "Unknown probe token. Add the probe on the hub and use its install command.")
|
||||
outages.resolve(con, row["id"], row["last_seen"], [o.model_dump() for o in body.outages], now)
|
||||
address = row["address"]
|
||||
if not row["address_locked"]:
|
||||
address = (body.advertise_addr or "").strip() or _client_ip(request) or address
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ from fastapi import APIRouter, FastAPI, HTTPException, Request
|
|||
from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse, Response
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from app.hub import adguard, db, dns, health, probes, settings
|
||||
from app.hub import adguard, db, dns, health, outages, probes, settings
|
||||
from app.version import VERSION
|
||||
|
||||
log = logging.getLogger("hub")
|
||||
|
|
@ -34,11 +34,24 @@ async def _retention_loop() -> None:
|
|||
await asyncio.sleep(3600)
|
||||
|
||||
|
||||
async def _silence_loop() -> None:
|
||||
"""Open a "not reporting" incident for probes that went quiet."""
|
||||
while True:
|
||||
try:
|
||||
def run():
|
||||
with db.db() as con:
|
||||
return outages.open_silences(con)
|
||||
await asyncio.to_thread(run)
|
||||
except Exception:
|
||||
log.exception("silence check failed")
|
||||
await asyncio.sleep(15)
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
# Startup work happens here, not at import: `update` imports app.main as a check.
|
||||
db.init()
|
||||
tasks = [asyncio.create_task(_retention_loop())]
|
||||
tasks = [asyncio.create_task(_retention_loop()), asyncio.create_task(_silence_loop())]
|
||||
if settings.get().adguard_configured:
|
||||
tasks.append(asyncio.create_task(dns.discovery_loop()))
|
||||
try:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue