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:
neil 2026-11-04 20:50:30 -08:00
parent 462525b1e2
commit be727949c1
13 changed files with 449 additions and 32 deletions

View file

@ -14,7 +14,12 @@ A home network monitor with two roles, built from one repo:
2. POSTs the results plus its ARP neighbors to the hub's `/api/probe/report` with a per-probe bearer token
3. receives its config (peers, targets) back in the response; that's the only control channel
While the hub is unreachable, results queue in memory and upload later. With no `HUB_URL` it is serve-only, e.g. on a VPS.
While reports get through, the probe writes nothing to disk except `data/probe-config.json` when its config changes (uvicorn's access log is off). While the hub can't be reached (no connection, timeout, 5xx), it writes a local outage log, `app/probe/outage.py`:
- `data/outage.jsonl`: one line per failed report
- `data/backlog.jsonl`: the unsent measurements, so a restart doesn't lose them
The first report that gets through uploads the backlog and sends the failures as runs (`outages` in the report body), then both files are deleted. With no `HUB_URL` it is serve-only, e.g. on a VPS.
- **Probe silences** (`app/hub/outages.py`, table `probe_outages`): when a probe misses reports for `3 × interval + 10` s, the hub opens an unconfirmed "Not reporting" incident. When the probe reports again, its outage runs replace that incident as confirmed "Hub unreachable" incidents; any part of the silence the log doesn't cover (the probe was off or restarting) is dropped. Probes older than this change send no runs, so their silences are always dropped: update them.
Remote: `https://git.neilbantoc.dev/services/network-monitor.git` (Gitea). The repo is public, so anonymous clone and fetch work and installs need no token.
@ -61,12 +66,14 @@ app/main.py picks the hub or probe app by ROLE; shared lifespan (crea
app/hub/server.py FastAPI app, optional UI_PASSWORD basic auth, SPA fallback, /api/info
app/hub/probes.py probe CRUD + POST /api/probe/report (token auth) → returns probe config
app/hub/health.py matrix / strips / incidents / series from the measurements table
app/hub/outages.py probe silences: open "not reporting" incidents, settle them with the probe's outage log
app/hub/dns.py clients, query log, domains, blocked; background AdGuard discovery (60 s)
app/hub/devices.py device merge logic (MAC key, ip: fallback, IP→MAC folding)
app/hub/adguard.py AdGuard client (httpx; tests swap TRANSPORT), query log paging, base_domain
app/hub/settings.py all hub settings from env, read per call
app/hub/db.py SQLite schema (idempotent), one connection per unit of work
app/probe/server.py probe app: /probe/ping, /probe/blob, / (status JSON), the report loop
app/probe/outage.py the probe's local outage log (written only while the hub can't be reached)
app/probe/checks.py icmp (icmplib, unprivileged), http, dns (hand-built UDP query), throughput,
gateway + ARP (Linux /proc/net, macOS route/arp)
app/static/ no-build frontend: house.css/ui.js/shell.js (vendored house style, don't

View file

@ -240,7 +240,9 @@ Probe settings live in `/opt/network-probe/.env`; `.env.probe.example` lists the
2. runs the throughput download, one peer at a time
3. posts the results and its ARP neighbors to `/api/probe/report`. On Linux the gateway and neighbors come from `/proc/net`; on macOS from `route` and `arp`.
The hub's reply is the probe's configuration: its peers and targets. The probe caches that reply in `/data`. While the hub is unreachable, results queue in memory, up to 20,000 measurements (hours of data), and upload once the hub is back. Outages are therefore recorded from the probe's side even when the hub can't hear it.
The hub's reply is the probe's configuration: its peers and targets. The probe caches that reply in `/data`. While reports get through, the probe writes nothing else to disk. While the hub can't be reached, it keeps a local outage log in its data folder: each failed report, and the results it couldn't send (up to 20,000 measurements, hours of data), so a restart doesn't lose them. Once the hub answers, the probe uploads the results and the log, then deletes both.
When a probe goes quiet, the hub lists it as "Not reporting". When it reports again, the hub checks its outage log. The parts of the silence the log covers become "Hub unreachable" incidents. The rest is dropped, because the probe was off or restarting rather than cut off.
- **Health maths** (`app/hub/health.py`). Each check is OK, slow or failed. Slow means over the threshold, or 30% or more ping loss. A time slice is:
- **down** when at least half its checks failed
- **degraded** when at least a fifth were slow or failed

View file

@ -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,

View file

@ -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
View 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

View file

@ -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

View file

@ -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:

101
app/probe/outage.py Normal file
View file

@ -0,0 +1,101 @@
"""The probe's local outage log, in $DATA_DIR. Nothing is written while reports reach the hub.
When a report fails because the hub can't be reached (no connection, timeout, or a 5xx), the
probe appends the failure to outage.jsonl and the measurements it couldn't send to backlog.jsonl,
so a restart during the outage loses neither. The next report that gets through carries the
failures, merged into runs, and the hub uses them to confirm or drop the "not reporting" incident
it opened. A probe that was switched off has no runs to send, so the hub drops that incident."""
import json
import os
import time
from pathlib import Path
import httpx
OUTAGE = "outage.jsonl"
BACKLOG = "backlog.jsonl"
def _dir() -> Path:
return Path(os.environ.get("DATA_DIR", "data"))
def is_outage(ex: Exception) -> bool:
"""True when the hub didn't answer, as opposed to answering with a refusal (401, 422)."""
if isinstance(ex, httpx.HTTPStatusError):
return ex.response.status_code >= 500
return isinstance(ex, httpx.TransportError)
def active() -> bool:
return (_dir() / OUTAGE).exists()
def record_failure(error: str, ts: float | None = None) -> None:
_append(OUTAGE, [{"ts": ts or time.time(), "error": error[:300]}])
def runs(gap: float) -> list[dict]:
"""Logged failures merged into runs: failures less than `gap` seconds apart belong together.
A longer pause between failures means the probe wasn't running in between."""
out: list[dict] = []
for f in sorted(_read(OUTAGE), key=lambda f: f.get("ts", 0)):
ts = f.get("ts")
if not isinstance(ts, (int, float)):
continue
if out and ts - out[-1]["end"] <= gap:
out[-1].update(end=ts, failures=out[-1]["failures"] + 1, error=f.get("error") or out[-1]["error"])
else:
out.append({"start": ts, "end": ts, "failures": 1, "error": f.get("error") or ""})
return out[-1000:]
def clear_failures() -> None:
(_dir() / OUTAGE).unlink(missing_ok=True)
def append_backlog(items: list[dict]) -> None:
if items:
_append(BACKLOG, items)
def load_backlog() -> list[dict]:
return [m for m in _read(BACKLOG) if isinstance(m, dict)]
def save_backlog(items) -> None:
"""Rewrite the backlog as exactly `items`; no file when there is nothing left to send."""
path = _dir() / BACKLOG
if not items:
path.unlink(missing_ok=True)
return
try:
tmp = path.with_suffix(".tmp")
tmp.write_text("".join(json.dumps(m) + "\n" for m in items))
tmp.replace(path)
except OSError:
pass
def _append(name: str, rows: list[dict]) -> None:
try:
_dir().mkdir(parents=True, exist_ok=True)
with open(_dir() / name, "a") as f:
f.write("".join(json.dumps(r) + "\n" for r in rows))
except OSError:
pass
def _read(name: str) -> list:
try:
lines = (_dir() / name).read_text().splitlines()
except OSError:
return []
out = []
for line in lines:
try:
out.append(json.loads(line))
except ValueError:
continue # a line cut short by a power loss
return out

View file

@ -16,7 +16,7 @@ import httpx
from fastapi import FastAPI, Query
from fastapi.responses import StreamingResponse
from app.probe import checks
from app.probe import checks, outage
from app.version import VERSION
log = logging.getLogger("probe")
@ -25,7 +25,7 @@ SEND_BATCH = 2000
state = {
"hub_url": "", "registered": None, "last_report": None, "last_error": None, "cycles": 0,
"buffered": 0, "config": None, "started": time.time(),
"buffered": 0, "config": None, "started": time.time(), "hub_unreachable_since": None,
}
@ -69,20 +69,25 @@ def _hostport(host: str, port: int) -> str:
return f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
async def report(client: httpx.AsyncClient, e: dict, buffer: deque, cycle: int) -> dict | None:
"""Send buffered measurements (oldest first, in batches). Returns the hub's config, or None."""
async def report(client: httpx.AsyncClient, e: dict, buffer: deque, cycle: int, outages: list | None = None) -> dict | None:
"""Send buffered measurements (oldest first, in batches). Returns the hub's config, or None.
`outages` (the local outage log as runs) goes with the first batch; once the hub has taken
it, the log is deleted."""
config = None
for _ in range(10):
batch = [buffer[i] for i in range(min(SEND_BATCH, len(buffer)))]
body = {"version": VERSION, "hostname": socket.gethostname(), "port": e["port"],
"advertise_addr": e["advertise"] or None, "icmp": checks.ICMP_STATE["ok"],
"measurements": batch, "neighbors": checks.neighbors() if cycle % 2 == 0 and config is None else []}
"measurements": batch, "neighbors": checks.neighbors() if cycle % 2 == 0 and config is None else [],
"outages": outages if config is None and outages else []}
r = await client.post(f"{e['hub_url']}/api/probe/report", json=body, headers={"Authorization": f"Bearer {e['token']}"})
if r.status_code == 401:
state["registered"] = False
raise RuntimeError("the hub doesn't know this probe's token (removed on the hub?)")
r.raise_for_status()
state["registered"] = True
if config is None and outages:
outage.clear_failures()
config = r.json()
for _ in batch:
buffer.popleft()
@ -118,35 +123,65 @@ def save_config(cfg: dict) -> None:
async def probe_loop() -> None:
"""Measure, then report; the hub's reply says what to measure next time. The last reply is
cached on disk so a probe that restarts while the hub is down keeps testing its peers."""
cached on disk so a probe that restarts while the hub is down keeps testing its peers.
While reports get through, nothing else is written. While the hub can't be reached, the
failures and the unsent measurements go to the local outage log (see outage.py)."""
e = env()
state["hub_url"] = e["hub_url"]
buffer: deque = deque(maxlen=BUFFER_MAX)
buffer: deque = deque(outage.load_backlog(), maxlen=BUFFER_MAX)
spooled = len(buffer) # measurements in backlog.jsonl
unreachable = outage.active() # restarted during an outage
cfg = load_config() or DEFAULT_CONFIG
state["config"] = load_config()
await asyncio.sleep(random.uniform(0, 5)) # spread probes out
cycle = 0
last_logged = None
async with httpx.AsyncClient(timeout=10) as hub:
while True:
started = time.monotonic()
fresh: list[dict] = []
try:
buffer.extend(await run_checks(cfg, cycle))
fresh = await run_checks(cfg, cycle)
buffer.extend(fresh)
except Exception as ex:
log.exception("checks failed")
state["last_error"] = f"checks failed: {ex}"
try:
new = await report(hub, e, buffer, cycle)
runs = outage.runs(gap=cfg.get("interval", 30) * 2 + 15) if unreachable else []
new = await report(hub, e, buffer, cycle, runs)
if new:
if new != state["config"]:
if state["config"] is None:
log.info("registered with %s as %r (probe %s)", e["hub_url"], new.get("name"), new.get("probe_id"))
save_config(new)
cfg = state["config"] = new
if unreachable:
log.info("the hub answers again; sent %d logged failed reports", sum(r["failures"] for r in runs))
unreachable = False
state["hub_unreachable_since"] = None
if spooled:
outage.save_backlog(buffer)
spooled = len(buffer)
state["last_report"] = time.time()
state["last_error"] = None
state["last_error"] = last_logged = None
except (httpx.HTTPError, RuntimeError, ValueError) as ex:
state["last_error"] = f"report to hub failed: {checks._err(ex)}"
err = checks._err(ex)
state["last_error"] = f"report to hub failed: {err}"
if outage.is_outage(ex):
outage.record_failure(err)
if unreachable and spooled and spooled + len(fresh) <= BUFFER_MAX + SEND_BATCH:
outage.append_backlog(fresh)
spooled += len(fresh)
else: # first failure, or the file outgrew the buffer: write what's unsent
outage.save_backlog(buffer)
spooled = len(buffer)
if not unreachable:
state["hub_unreachable_since"] = time.time()
log.warning("can't reach the hub (%s); logging locally until it answers", err)
unreachable = True
elif state["last_error"] != last_logged:
log.warning(state["last_error"])
last_logged = state["last_error"]
state["buffered"] = len(buffer)
state["cycles"] = cycle = cycle + 1
await asyncio.sleep(max(1.0, cfg.get("interval", 30) - (time.monotonic() - started)))
@ -154,6 +189,9 @@ async def probe_loop() -> None:
@contextlib.asynccontextmanager
async def lifespan(_app: FastAPI):
# Peers request /probe/ping every round; logging each request would write to disk
# (journal, docker log, or service.log on macOS) all the time for no benefit.
logging.getLogger("uvicorn.access").disabled = True
task = None
e = env()
if e["hub_url"] and e["token"]:
@ -206,5 +244,6 @@ def status() -> dict:
"name": cfg.get("name"), "probe_id": cfg.get("probe_id"), "registered": state["registered"],
"peers": len(cfg.get("peers", [])), "icmp": checks.ICMP_STATE["ok"], "gateway": checks.default_gateway(),
"last_report": state["last_report"], "last_error": state["last_error"], "buffered": state["buffered"],
"cycles": state["cycles"],
"cycles": state["cycles"], "hub_unreachable_since": state["hub_unreachable_since"],
"outage_log": outage.active(),
}

View file

@ -1,5 +1,6 @@
// Shared bits for the views.
import { el } from './ui.js';
import { ms } from './fmt.js';
/** The screen frame: toolbar, scrolling pane, status bar. Returns the parts. */
export function screen(root, toolbarItems) {
@ -73,3 +74,30 @@ export function every(ms, fn) {
const t = setInterval(() => { if (!document.hidden) fn(); }, ms);
return () => clearInterval(t);
}
// Incident cells, shared by Network health and a probe's page. kind "report" rows are stretches
// when a probe didn't report; the probe's local outage log confirms them when it reports again.
const METHOD_NAMES = { icmp: 'Ping', http: 'HTTP', dns: 'DNS' };
export function incidentTarget(i) {
if (i.kind === 'report') return el('span', {}, i.label);
return el('span', {}, i.label, el('span.muted.small', {}, ` ${i.methods.map((m) => METHOD_NAMES[m] || m).join(', ')}`));
}
export function incidentTypeText(i) {
if (i.kind !== 'report') return undefined;
return i.confirmed ? 'Hub unreachable' : 'Not reporting';
}
export function incidentChecks(i) {
if (i.kind === 'report') return i.confirmed ? `${i.failed} failed reports` : 'No reports';
return i.failed ? `${i.failed}/${i.samples} failed` : `${i.samples} slow`;
}
export function incidentDetail(i) {
if (i.kind === 'report') {
if (i.confirmed) return `The probe logged that it couldn’t reach the hub${i.error ? `: ${i.error}` : ''}`;
return 'Kept if the probe’s log shows it couldn’t reach the hub, removed if it was off';
}
return i.error || (i.max_latency ? `peak ${ms(i.max_latency)}` : '');
}

View file

@ -3,7 +3,7 @@ import { el, segmented, store } from '../ui.js';
import { get } from '../api.js';
import { STATUS, statusChip, statusLegend, strip, tipRow, tipTitle, hideTip, showTip } from '../charts.js';
import { axisTime, dur, ms, pct, when } from '../fmt.js';
import { RANGES, SPANS, every, errorBox, screen, section, table, fill } from '../common.js';
import { RANGES, SPANS, every, errorBox, screen, section, table, fill, incidentChecks, incidentDetail, incidentTarget, incidentTypeText } from '../common.js';
const METHOD = { icmp: 'Ping', http: 'HTTP', dns: 'DNS' };
@ -53,7 +53,7 @@ export function mount(root, ctx) {
section('Timeline', `${range} in ${st.buckets} slices of ${dur(st.width)}. A slice is down when half its checks fail, degraded when a fifth are slow or failing.`),
statusLegend(),
strips(st),
section('Incidents', `Slow means over ${inc.thresholds.lan_ms} ms on the LAN, ${inc.thresholds.wan_ms} ms to the internet, ${inc.thresholds.dns_ms} ms for DNS, or ${pct(inc.thresholds.loss)}+ ping loss.`),
section('Incidents', `Slow means over ${inc.thresholds.lan_ms} ms on the LAN, ${inc.thresholds.wan_ms} ms to the internet, ${inc.thresholds.dns_ms} ms for DNS, or ${pct(inc.thresholds.loss)}+ ping loss. A probe that stops reporting is kept as an incident only if its own log shows it couldn’t reach the hub.`),
incidents(inc.incidents),
);
}
@ -132,10 +132,10 @@ export function mount(root, ctx) {
el('td.nowrap', { title: when(i.start) }, when(i.start)),
el('td.nowrap', {}, i.ongoing ? el('span.chip.danger', {}, `Ongoing · ${dur(i.duration)}`) : dur(i.duration)),
el('td', {}, el('a', { href: `/probes/${i.probe_id}` }, i.probe)),
el('td', {}, i.label, el('span.muted.small', {}, ` ${i.methods.map((m) => METHOD[m] || m).join(', ')}`)),
el('td', {}, statusChip(i.type)),
el('td.num', {}, i.failed ? `${i.failed}/${i.samples} failed` : `${i.samples} slow`),
el('td.small', {}, i.error || (i.max_latency ? `peak ${ms(i.max_latency)}` : '')),
el('td', {}, incidentTarget(i)),
el('td', {}, statusChip(i.type, incidentTypeText(i))),
el('td.num', {}, incidentChecks(i)),
el('td.small', {}, incidentDetail(i)),
)), { empty: `No incidents in the last ${range}.` });
}

View file

@ -3,7 +3,7 @@ import { confirmDialog, copyText, el, modal, segmented, store, toast } from '../
import { del, get, patch, post } from '../api.js';
import { lineChart, seriesLegend, statusChip, statusLegend, strip, tipRow, tipTitle, hideTip, STATUS } from '../charts.js';
import { ago, axisTime, dur, mbps, ms, pct, when } from '../fmt.js';
import { RANGES, SPANS, every, errorBox, screen, section, table, fill } from '../common.js';
import { RANGES, SPANS, every, errorBox, screen, section, table, fill, incidentChecks, incidentDetail, incidentTarget, incidentTypeText } from '../common.js';
const METHOD = { icmp: 'Ping', http: 'HTTP', dns: 'DNS', throughput: 'Throughput' };
@ -173,10 +173,10 @@ function detail(root, ctx, id) {
table(['Started', 'Lasted', 'Target', 'Type', 'Checks', 'Detail'], inc.incidents.map((i) => el('tr', {},
el('td.nowrap', {}, when(i.start)),
el('td.nowrap', {}, i.ongoing ? el('span.chip.danger', {}, `Ongoing · ${dur(i.duration)}`) : dur(i.duration)),
el('td', {}, i.label, el('span.muted.small', {}, ` ${i.methods.map((m) => METHOD[m] || m).join(', ')}`)),
el('td', {}, statusChip(i.type)),
el('td.num', {}, i.failed ? `${i.failed}/${i.samples} failed` : `${i.samples} slow`),
el('td.small', {}, i.error || (i.max_latency ? `peak ${ms(i.max_latency)}` : '')))), { empty: `No incidents in the last ${range}.` }),
el('td', {}, incidentTarget(i)),
el('td', {}, statusChip(i.type, incidentTypeText(i))),
el('td.num', {}, incidentChecks(i)),
el('td.small', {}, incidentDetail(i)))), { empty: `No incidents in the last ${range}.` }),
);
}

127
tests/test_outages.py Normal file
View file

@ -0,0 +1,127 @@
"""Probes that stop reporting: the hub opens an incident, the probe's outage log settles it."""
import asyncio
import time
import httpx
from app.hub import outages
from app.hub.db import db
from tests.test_probes import add, send
def go_quiet(probe_id, seconds):
"""Pretend the probe last reported `seconds` ago and let the hub notice."""
with db() as con:
con.execute("UPDATE probes SET last_seen = ? WHERE id = ?", (time.time() - seconds, probe_id))
outages.open_silences(con)
def report_incidents(hub, probe_id):
inc = hub.get("/api/health/incidents", params={"range": "24h", "probe": probe_id}).json()["incidents"]
return [i for i in inc if i["kind"] == "report"]
def test_silent_probe_is_an_ongoing_incident_then_dropped_when_it_was_off(hub):
p = add(hub, "attic")
send(hub, p["token"])
go_quiet(p["id"], 3600)
[i] = report_incidents(hub, p["id"])
assert i["ongoing"] and not i["confirmed"] and i["type"] == "down"
with db() as con:
assert outages.open_silences(con) == 0 # one per silence, not one per check
send(hub, p["token"]) # back, with no outage log: it was switched off
assert report_incidents(hub, p["id"]) == []
def test_outage_log_confirms_the_logged_part_only(hub):
p = add(hub, "attic")
send(hub, p["token"])
go_quiet(p["id"], 3600)
now = time.time()
# Failed reports for 20 minutes, then the probe was off, then up and failing until now.
runs = [{"start": now - 3500, "end": now - 2300, "failures": 40, "error": "timeout"},
{"start": now - 600, "end": now - 30, "failures": 20, "error": "connection refused"}]
send(hub, p["token"], outages=runs)
inc = sorted(report_incidents(hub, p["id"]), key=lambda i: i["start"])
assert len(inc) == 2 and all(i["confirmed"] and not i["ongoing"] for i in inc)
assert inc[0]["start"] == now - 3530 and inc[0]["end"] == now - 2300 and inc[0]["failed"] == 40
assert inc[1]["end"] >= now and inc[1]["error"] == "connection refused"
def test_hub_restart_gap_is_settled_without_an_open_incident(hub):
p = add(hub, "attic")
send(hub, p["token"])
with db() as con: # the hub was down too, so it never opened an incident
con.execute("UPDATE probes SET last_seen = ? WHERE id = ?", (time.time() - 900, p["id"]))
now = time.time()
send(hub, p["token"], outages=[{"start": now - 880, "end": now - 25, "failures": 29, "error": "timeout"}])
[i] = report_incidents(hub, p["id"])
assert i["confirmed"] and i["failed"] == 29
def test_short_hiccup_is_not_an_incident(hub):
p = add(hub, "attic")
send(hub, p["token"])
now = time.time()
send(hub, p["token"], outages=[{"start": now - 20, "end": now - 20, "failures": 1, "error": "timeout"}])
assert report_incidents(hub, p["id"]) == []
def test_deleting_a_probe_removes_its_outages(hub):
p = add(hub, "attic")
send(hub, p["token"])
go_quiet(p["id"], 3600)
assert hub.delete(f"/api/probes/{p['id']}").status_code == 204
with db() as con:
assert con.execute("SELECT COUNT(*) FROM probe_outages").fetchone()[0] == 0
def test_probe_writes_nothing_while_the_hub_answers_and_logs_while_it_doesnt(tmp_path, monkeypatch):
from app.probe import outage, server
monkeypatch.setattr(server, "state", dict(server.state)) # probe_loop writes module state
calls = {"n": 0, "bodies": []}
plan = ["ok", "down", "down", "ok", "ok"]
def handler(request):
i = calls["n"]
calls["n"] += 1
if plan[min(i, len(plan) - 1)] == "down":
raise httpx.ConnectError("no route to host")
calls["bodies"].append(request.read())
return httpx.Response(200, json={"interval": 5, "peers": [], "dns": [], "http": []})
real_client = httpx.AsyncClient
monkeypatch.setattr(server.httpx, "AsyncClient", lambda **kw: real_client(transport=httpx.MockTransport(handler), **kw)
if kw.get("timeout") == 10 else real_client(**kw))
async def fake_checks(cfg, cycle):
return [{"ts": time.time(), "target": "gateway", "label": "gw", "kind": "lan", "method": "icmp", "ok": True}]
monkeypatch.setattr(server, "run_checks", fake_checks)
monkeypatch.setattr(server.random, "uniform", lambda a, b: 0)
seen = []
async def fake_sleep(_):
files = sorted(p.name for p in tmp_path.iterdir())
seen.append(files)
if len(seen) > len(plan):
raise asyncio.CancelledError
monkeypatch.setattr(server.asyncio, "sleep", fake_sleep)
monkeypatch.setenv("HUB_URL", "http://hub")
monkeypatch.setenv("PROBE_TOKEN", "t")
try:
asyncio.run(server.probe_loop())
except asyncio.CancelledError:
pass
# seen[0] is the start-up delay; then one entry per round, after its report.
assert seen[1] == ["probe-config.json"] # ok: only the config cache
assert seen[2] == seen[3] == ["backlog.jsonl", "outage.jsonl", "probe-config.json"]
assert seen[4] == seen[5] == ["probe-config.json"] # delivered and cleaned up
import json
first_back = json.loads(calls["bodies"][1])
assert len(first_back["measurements"]) == 3 # nothing lost
[run] = first_back["outages"]
assert run["failures"] == 2 and "no route" in run["error"]
assert json.loads(calls["bodies"][2])["outages"] == []
assert not outage.active()