Network monitor: hub, probes, Docker and native installers

Hub (FastAPI + no-build web UI):
- Network health: live probe/target matrix, status strips, incidents
- Probes: add (with install command), rename, remove, latency and throughput charts
- Clients merged from AdGuard, DHCP, query log and probe ARP tables; names,
  categories, suspicious flag, notes, per-client DNS requests
- Query log, domain detail (clients, related subdomains), blocked domains via
  the AdGuard Home /control API

Probe: tests peers (ping, HTTP, throughput), gateway, LAN and public DNS,
internet URLs and an optional VPS; buffers results while the hub is down.
Gateway and ARP from /proc/net on Linux, route/arp on macOS.

Install: install.sh (hub) and install-probe.sh (generated from it), each in
docker mode (compose; default on Linux hosts) or native mode (venv + systemd
or launchd; default on macOS and in LXC). Both modes deploy with an update
command that checks the new commit and rolls back on failure.

CLAUDE.md carries shared context for Claude Code sessions on each machine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
neil 2026-11-04 18:10:29 -08:00
commit 54a765510a
63 changed files with 6464 additions and 0 deletions

149
app/hub/adguard.py Normal file
View file

@ -0,0 +1,149 @@
"""AdGuard Home API client (/control/*, HTTP basic auth) and query log helpers."""
import re
import time
from datetime import datetime
import httpx
from app.hub import settings
# Tests swap this for an httpx.MockTransport.
TRANSPORT: httpx.AsyncBaseTransport | None = None
BLOCKED_REASONS = {"FilteredBlackList", "FilteredBlockedService", "FilteredParental", "FilteredSafeBrowsing", "FilteredInvalid"}
PAGE = 500
class NotConfigured(Exception):
pass
class AdGuardError(Exception):
pass
def _client() -> httpx.AsyncClient:
s = settings.get()
if not s.adguard_configured:
raise NotConfigured("Set ADGUARD_URL (and ADGUARD_USERNAME / ADGUARD_PASSWORD) in the hub's .env")
auth = (s.adguard_username, s.adguard_password) if s.adguard_username else None
return httpx.AsyncClient(base_url=s.adguard_url, auth=auth, timeout=15, transport=TRANSPORT)
async def get(path: str, params: dict | None = None):
try:
async with _client() as c:
r = await c.get(path, params=params)
except httpx.HTTPError as e:
raise AdGuardError(f"AdGuard Home unreachable: {e.__class__.__name__}: {e}") from e
if r.status_code in (401, 403):
raise AdGuardError("AdGuard Home rejected the login. Check ADGUARD_USERNAME and ADGUARD_PASSWORD.")
if r.status_code >= 400:
raise AdGuardError(f"AdGuard Home returned {r.status_code} for {path}")
try:
return r.json()
except ValueError as e:
raise AdGuardError(f"AdGuard Home sent a non-JSON reply for {path}. Is ADGUARD_URL the web UI address?") from e
_FRAC = re.compile(r"(\.\d{6})\d+")
def parse_time(value: str) -> float:
try:
return datetime.fromisoformat(_FRAC.sub(r"\1", value.replace("Z", "+00:00"))).timestamp()
except (ValueError, AttributeError):
return 0.0
def normalize(row: dict) -> dict:
q = row.get("question") or {}
info = row.get("client_info") or {}
rules = row.get("rules") or []
reason = row.get("reason", "")
try:
elapsed = round(float(row.get("elapsedMs") or 0), 2)
except ValueError:
elapsed = None
return {
"time": row.get("time", ""),
"ts": parse_time(row.get("time", "")),
"client": row.get("client", ""),
"client_name": info.get("name") or "",
"domain": (q.get("name") or q.get("host") or "").rstrip(".").lower(),
"type": q.get("type", ""),
"status": row.get("status", ""),
"reason": reason,
"blocked": reason in BLOCKED_REASONS,
"rule": (rules[0].get("text") if rules else row.get("rule")) or "",
"elapsed_ms": elapsed,
"upstream": row.get("upstream", ""),
"cached": bool(row.get("cached")),
}
async def collect(*, search: str = "", status: str = "all", older_than: str = "", want: int = 200,
keep=None, max_rows: int = 5000) -> dict:
"""Page through the query log, newest first, until `want` rows pass `keep` or `max_rows`
have been read. Returns {rows, oldest, done}: pass `oldest` back as older_than for more."""
rows, scanned, done = [], 0, False
cursor = older_than
while len(rows) < want and scanned < max_rows:
params = {"limit": PAGE, "response_status": status}
if search:
params["search"] = search
if cursor:
params["older_than"] = cursor
data = await get("/control/querylog", params)
page = data.get("data") or []
scanned += len(page)
for raw in page:
r = normalize(raw)
if keep is None or keep(r):
rows.append(r)
if len(rows) >= want:
cursor = raw.get("time", cursor)
break
else:
cursor = data.get("oldest") or (page[-1].get("time") if page else "")
if len(page) < PAGE or not cursor:
done = True
break
return {"rows": rows, "oldest": "" if done else cursor, "done": done, "scanned": scanned}
def top_list(items) -> list[tuple[str, int]]:
"""AdGuard returns top lists as [{"name": count}, ...]."""
out = []
for it in items or []:
if isinstance(it, dict):
out.extend((str(k), int(v)) for k, v in it.items())
return out
_stats_cache: dict = {"at": 0.0, "data": None}
async def stats(max_age: float = 60) -> dict:
if _stats_cache["data"] is not None and time.time() - _stats_cache["at"] < max_age:
return _stats_cache["data"]
data = await get("/control/stats")
_stats_cache.update(at=time.time(), data=data)
return data
MULTI_PART_SUFFIXES = {
"co.uk", "org.uk", "ac.uk", "gov.uk", "me.uk", "com.au", "net.au", "org.au", "co.nz", "co.jp", "ne.jp",
"com.br", "com.cn", "com.mx", "co.in", "co.za", "com.tr", "com.sg", "com.ph", "com.hk", "com.tw", "co.kr",
"com.ar", "com.my", "co.id", "com.vn", "com.pk", "com.ng", "com.eg", "com.sa", "co.il", "com.ua",
}
def base_domain(name: str) -> str:
"""Registrable domain, approximately (no full public suffix list): a.b.example.co.uk -> example.co.uk."""
labels = name.lower().rstrip(".").split(".")
if len(labels) <= 2 or all(x.isdigit() for x in labels):
return ".".join(labels)
n = 3 if ".".join(labels[-2:]) in MULTI_PART_SUFFIXES else 2
return ".".join(labels[-n:])