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:
commit
54a765510a
63 changed files with 6464 additions and 0 deletions
0
app/hub/__init__.py
Normal file
0
app/hub/__init__.py
Normal file
149
app/hub/adguard.py
Normal file
149
app/hub/adguard.py
Normal 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:])
|
||||
86
app/hub/db.py
Normal file
86
app/hub/db.py
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
"""SQLite storage under $DATA_DIR. One short-lived connection per unit of work."""
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS probes (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
token TEXT NOT NULL UNIQUE,
|
||||
address TEXT, -- set by the hub from the report, or ADVERTISE_ADDR, or by hand
|
||||
address_locked INTEGER NOT NULL DEFAULT 0,
|
||||
port INTEGER,
|
||||
hostname TEXT,
|
||||
version TEXT,
|
||||
icmp INTEGER, -- 1/0: whether ICMP works on that probe
|
||||
created REAL NOT NULL,
|
||||
last_seen REAL,
|
||||
last_error TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS measurements (
|
||||
ts REAL NOT NULL,
|
||||
probe_id INTEGER NOT NULL,
|
||||
target TEXT NOT NULL, -- probe:<id>, gateway, dns:<ip>, vps, web:<url>
|
||||
label TEXT,
|
||||
kind TEXT NOT NULL, -- lan | wan
|
||||
method TEXT NOT NULL, -- icmp | http | dns | throughput
|
||||
ok INTEGER NOT NULL,
|
||||
latency REAL, -- ms
|
||||
loss REAL, -- 0..1 (icmp)
|
||||
mbps REAL, -- throughput
|
||||
error TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS m_ts ON measurements(ts);
|
||||
CREATE INDEX IF NOT EXISTS m_series ON measurements(probe_id, target, method, ts);
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
key TEXT PRIMARY KEY, -- MAC when known, else ip:<address>
|
||||
mac TEXT,
|
||||
ip TEXT,
|
||||
hostname TEXT,
|
||||
sources TEXT NOT NULL DEFAULT '',
|
||||
first_seen REAL NOT NULL,
|
||||
last_seen REAL, -- last activity (DNS query or ARP); NULL = only listed somewhere
|
||||
name TEXT,
|
||||
category TEXT,
|
||||
suspicious INTEGER NOT NULL DEFAULT 0,
|
||||
notes TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS d_ip ON devices(ip);
|
||||
CREATE TABLE IF NOT EXISTS ip_mac (
|
||||
ip TEXT PRIMARY KEY,
|
||||
mac TEXT NOT NULL,
|
||||
last_seen REAL NOT NULL
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def path() -> Path:
|
||||
return Path(os.environ.get("DATA_DIR", "data")) / "hub.sqlite3"
|
||||
|
||||
|
||||
def connect() -> sqlite3.Connection:
|
||||
con = sqlite3.connect(path(), timeout=15)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA journal_mode=WAL")
|
||||
con.execute("PRAGMA synchronous=NORMAL")
|
||||
return con
|
||||
|
||||
|
||||
@contextmanager
|
||||
def db():
|
||||
"""A connection whose work commits on success and rolls back on error."""
|
||||
con = connect()
|
||||
try:
|
||||
with con:
|
||||
yield con
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def init() -> None:
|
||||
path().parent.mkdir(parents=True, exist_ok=True)
|
||||
with db() as con:
|
||||
con.executescript(SCHEMA)
|
||||
96
app/hub/devices.py
Normal file
96
app/hub/devices.py
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
"""Client devices: merged from AdGuard (clients, DHCP leases, query log) and probe ARP tables.
|
||||
A device is keyed by MAC address when one is known, else by IP (ip:<address>)."""
|
||||
|
||||
import re
|
||||
import time
|
||||
|
||||
MAC_RE = re.compile(r"^[0-9a-f]{2}(:[0-9a-f]{2}){5}$")
|
||||
USER_FIELDS = ("name", "category", "suspicious", "notes")
|
||||
|
||||
|
||||
def norm_mac(mac: str | None) -> str | None:
|
||||
if not mac:
|
||||
return None
|
||||
m = mac.strip().lower().replace("-", ":")
|
||||
if not MAC_RE.match(m) or m == "00:00:00:00:00:00":
|
||||
return None
|
||||
return m
|
||||
|
||||
|
||||
def _merge_into(con, src_key: str, dst_key: str) -> None:
|
||||
"""Fold the IP-keyed device into the MAC-keyed one, keeping the user's labels."""
|
||||
src = con.execute("SELECT * FROM devices WHERE key = ?", (src_key,)).fetchone()
|
||||
dst = con.execute("SELECT * FROM devices WHERE key = ?", (dst_key,)).fetchone()
|
||||
if not src or not dst:
|
||||
return
|
||||
updates = {f: src[f] for f in USER_FIELDS if src[f] and not dst[f]}
|
||||
sources = ",".join(sorted(set(filter(None, (dst["sources"] + "," + src["sources"]).split(",")))))
|
||||
updates["sources"] = sources
|
||||
updates["first_seen"] = min(src["first_seen"], dst["first_seen"])
|
||||
if src["last_seen"] and (not dst["last_seen"] or src["last_seen"] > dst["last_seen"]):
|
||||
updates["last_seen"] = src["last_seen"]
|
||||
if not dst["hostname"] and src["hostname"]:
|
||||
updates["hostname"] = src["hostname"]
|
||||
sets = ", ".join(f"{k} = ?" for k in updates)
|
||||
con.execute(f"UPDATE devices SET {sets} WHERE key = ?", (*updates.values(), dst_key))
|
||||
con.execute("DELETE FROM devices WHERE key = ?", (src_key,))
|
||||
|
||||
|
||||
def sighting(con, *, ip: str | None = None, mac: str | None = None, hostname: str | None = None,
|
||||
source: str, seen: float | None = None, now: float | None = None) -> str | None:
|
||||
"""Record that a device exists. `seen` is a time of real activity; None means it was only listed."""
|
||||
now = now or time.time()
|
||||
ip = (ip or "").strip() or None
|
||||
mac = norm_mac(mac)
|
||||
if not ip and not mac:
|
||||
return None
|
||||
if ip and mac:
|
||||
prev = con.execute("SELECT mac FROM ip_mac WHERE ip = ?", (ip,)).fetchone()
|
||||
con.execute("INSERT INTO ip_mac(ip, mac, last_seen) VALUES (?, ?, ?) ON CONFLICT(ip) DO UPDATE SET mac = excluded.mac, last_seen = excluded.last_seen",
|
||||
(ip, mac, now))
|
||||
if not prev or prev["mac"] != mac:
|
||||
# The address moved to this device: other devices no longer hold it.
|
||||
con.execute("UPDATE devices SET ip = NULL WHERE ip = ? AND key != ?", (ip, mac))
|
||||
elif ip:
|
||||
row = con.execute("SELECT mac FROM ip_mac WHERE ip = ?", (ip,)).fetchone()
|
||||
mac = row["mac"] if row else None
|
||||
key = mac or f"ip:{ip}"
|
||||
exists = con.execute("SELECT key FROM devices WHERE key = ?", (key,)).fetchone()
|
||||
if not exists:
|
||||
con.execute("INSERT INTO devices(key, mac, ip, hostname, sources, first_seen, last_seen) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
(key, mac, ip, hostname or None, source, seen or now, seen))
|
||||
else:
|
||||
con.execute(
|
||||
"""UPDATE devices SET
|
||||
ip = COALESCE(?, ip),
|
||||
hostname = COALESCE(NULLIF(?, ''), hostname),
|
||||
sources = CASE WHEN (',' || sources || ',') LIKE ? THEN sources
|
||||
WHEN sources = '' THEN ? ELSE sources || ',' || ? END,
|
||||
last_seen = CASE WHEN ? IS NOT NULL AND (last_seen IS NULL OR ? > last_seen) THEN ? ELSE last_seen END
|
||||
WHERE key = ?""",
|
||||
(ip, hostname or "", f"%,{source},%", source, source, seen, seen, seen, key),
|
||||
)
|
||||
if mac and ip:
|
||||
_merge_into(con, f"ip:{ip}", mac)
|
||||
return key
|
||||
|
||||
|
||||
def ip_index(con) -> dict[str, dict]:
|
||||
"""ip -> {key, name, suspicious} for linking query log rows to devices."""
|
||||
out = {}
|
||||
for r in con.execute("SELECT key, ip, name, hostname, suspicious, category FROM devices WHERE ip IS NOT NULL"):
|
||||
out[r["ip"]] = {"key": r["key"], "name": r["name"] or r["hostname"] or "", "suspicious": bool(r["suspicious"]), "category": r["category"] or ""}
|
||||
return out
|
||||
|
||||
|
||||
def ips_for(con, key: str) -> list[str]:
|
||||
"""Addresses to search the query log for: the current one plus others recently tied to its MAC."""
|
||||
row = con.execute("SELECT mac, ip FROM devices WHERE key = ?", (key,)).fetchone()
|
||||
if not row:
|
||||
return []
|
||||
ips = [row["ip"]] if row["ip"] else []
|
||||
if row["mac"]:
|
||||
ips += [r["ip"] for r in con.execute("SELECT ip FROM ip_mac WHERE mac = ? ORDER BY last_seen DESC LIMIT 4", (row["mac"],)) if r["ip"] not in ips]
|
||||
if not ips and key.startswith("ip:"):
|
||||
ips = [key[3:]]
|
||||
return ips
|
||||
319
app/hub/dns.py
Normal file
319
app/hub/dns.py
Normal file
|
|
@ -0,0 +1,319 @@
|
|||
"""Clients, DNS query log, domain detail and blocked domains, all backed by AdGuard Home."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from collections import Counter, defaultdict
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.hub import adguard, devices, settings
|
||||
from app.hub.db import db
|
||||
|
||||
log = logging.getLogger("hub.dns")
|
||||
router = APIRouter()
|
||||
|
||||
CATEGORIES = ["Computer", "Mobile", "Tablet", "IoT", "Server", "Network", "Media", "Gaming", "Other"]
|
||||
ONLINE_SECONDS = 600
|
||||
|
||||
|
||||
def _decorate(rows: list[dict], index: dict) -> list[dict]:
|
||||
for r in rows:
|
||||
d = index.get(r["client"])
|
||||
r["device"] = d
|
||||
return rows
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- status
|
||||
|
||||
@router.get("/dns/status")
|
||||
async def dns_status() -> dict:
|
||||
s = settings.get()
|
||||
if not s.adguard_configured:
|
||||
return {"configured": False, "ok": False, "message": "Set ADGUARD_URL in the hub's .env to see clients and DNS queries."}
|
||||
try:
|
||||
st = await adguard.get("/control/status")
|
||||
except adguard.AdGuardError as e:
|
||||
return {"configured": True, "ok": False, "url": s.adguard_url, "message": str(e)}
|
||||
return {"configured": True, "ok": True, "url": s.adguard_url, "version": st.get("version", ""),
|
||||
"protection_enabled": st.get("protection_enabled"), "running": st.get("running")}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- clients
|
||||
|
||||
class DeviceMeta(BaseModel):
|
||||
name: str | None = Field(default=None, max_length=80)
|
||||
category: str | None = Field(default=None, max_length=40)
|
||||
suspicious: bool | None = None
|
||||
notes: str | None = Field(default=None, max_length=2000)
|
||||
|
||||
|
||||
def device_out(r, counts: dict | None = None, now: float | None = None, epoch: float | None = None) -> dict:
|
||||
"""epoch: when the hub first saw any device. Devices from that first day aren't "new"."""
|
||||
now = now or time.time()
|
||||
return {
|
||||
"key": r["key"], "mac": r["mac"], "ip": r["ip"], "hostname": r["hostname"] or "",
|
||||
"name": r["name"] or "", "display": r["name"] or r["hostname"] or r["ip"] or r["mac"],
|
||||
"category": r["category"] or "", "suspicious": bool(r["suspicious"]), "notes": r["notes"] or "",
|
||||
"sources": [x for x in r["sources"].split(",") if x], "first_seen": r["first_seen"], "last_seen": r["last_seen"],
|
||||
"online": bool(r["last_seen"]) and now - r["last_seen"] < ONLINE_SECONDS,
|
||||
"new": now - r["first_seen"] < 86400 and (epoch is None or r["first_seen"] - epoch > 86400),
|
||||
"queries": (counts or {}).get(r["ip"]) if r["ip"] else None,
|
||||
}
|
||||
|
||||
|
||||
async def _client_counts() -> dict:
|
||||
if not settings.get().adguard_configured:
|
||||
return {}
|
||||
try:
|
||||
return dict(adguard.top_list((await adguard.stats()).get("top_clients")))
|
||||
except adguard.AdGuardError:
|
||||
return {}
|
||||
|
||||
|
||||
@router.get("/clients")
|
||||
async def list_clients() -> dict:
|
||||
counts = await _client_counts()
|
||||
with db() as con:
|
||||
rows = con.execute("SELECT * FROM devices ORDER BY COALESCE(name, hostname, ip, mac) COLLATE NOCASE").fetchall()
|
||||
epoch = min((r["first_seen"] for r in rows), default=None)
|
||||
return {"clients": [device_out(r, counts, epoch=epoch) for r in rows], "categories": CATEGORIES,
|
||||
"adguard": settings.get().adguard_configured}
|
||||
|
||||
|
||||
def _device(con, key: str):
|
||||
row = con.execute("SELECT * FROM devices WHERE key = ?", (key,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "No client with that id")
|
||||
return row
|
||||
|
||||
|
||||
@router.get("/clients/{key}")
|
||||
async def get_client(key: str) -> dict:
|
||||
counts = await _client_counts()
|
||||
with db() as con:
|
||||
row = _device(con, key)
|
||||
ips = devices.ips_for(con, key)
|
||||
out = device_out(row, counts)
|
||||
out["ips"] = ips
|
||||
out["categories"] = CATEGORIES
|
||||
return out
|
||||
|
||||
|
||||
@router.put("/clients/{key}")
|
||||
def update_client(key: str, body: DeviceMeta) -> dict:
|
||||
with db() as con:
|
||||
_device(con, key)
|
||||
fields = body.model_dump(exclude_unset=True)
|
||||
if "suspicious" in fields:
|
||||
fields["suspicious"] = int(bool(fields["suspicious"]))
|
||||
for k in ("name", "category", "notes"):
|
||||
if k in fields:
|
||||
fields[k] = (fields[k] or "").strip() or None
|
||||
if fields:
|
||||
con.execute(f"UPDATE devices SET {', '.join(f'{k} = ?' for k in fields)} WHERE key = ?", (*fields.values(), key))
|
||||
return device_out(_device(con, key))
|
||||
|
||||
|
||||
@router.delete("/clients/{key}", status_code=204)
|
||||
def forget_client(key: str) -> None:
|
||||
with db() as con:
|
||||
_device(con, key)
|
||||
con.execute("DELETE FROM devices WHERE key = ?", (key,))
|
||||
|
||||
|
||||
@router.get("/clients/{key}/summary")
|
||||
async def client_summary(key: str, sample: int = Query(1000, ge=50, le=5000)) -> dict:
|
||||
with db() as con:
|
||||
_device(con, key)
|
||||
ips = devices.ips_for(con, key)
|
||||
if not ips:
|
||||
return {"ips": [], "sample": 0, "top": [], "blocked_top": [], "blocked": 0, "since": None}
|
||||
wanted = set(ips)
|
||||
res = await adguard.collect(search=ips[0] if len(ips) == 1 else "", want=sample, keep=lambda r: r["client"] in wanted, max_rows=sample * 5)
|
||||
rows = res["rows"]
|
||||
top = Counter(r["domain"] for r in rows)
|
||||
blocked = Counter(r["domain"] for r in rows if r["blocked"])
|
||||
return {
|
||||
"ips": ips, "sample": len(rows), "blocked": sum(blocked.values()),
|
||||
"since": min((r["ts"] for r in rows), default=None),
|
||||
"top": [{"domain": d, "count": c, "blocked": blocked.get(d, 0)} for d, c in top.most_common(25)],
|
||||
"blocked_top": [{"domain": d, "count": c} for d, c in blocked.most_common(10)],
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- query log
|
||||
|
||||
@router.get("/dns/queries")
|
||||
async def queries(search: str = "", status: str = Query("all", pattern="^(all|blocked|allowed)$"),
|
||||
client: str = "", ip: str = "", domain: str = "", older_than: str = "",
|
||||
limit: int = Query(100, ge=1, le=500)) -> dict:
|
||||
"""The AdGuard query log, newest first. `client` is a client id, `ip` a comma list of exact addresses."""
|
||||
with db() as con:
|
||||
ips = {x.strip() for x in ip.split(",") if x.strip()}
|
||||
if client:
|
||||
ips.update(devices.ips_for(con, client) or ["-"])
|
||||
index = devices.ip_index(con)
|
||||
domain = domain.strip().lower()
|
||||
|
||||
def keep(r):
|
||||
if ips and r["client"] not in ips:
|
||||
return False
|
||||
if domain and r["domain"] != domain:
|
||||
return False
|
||||
if status == "allowed" and r["blocked"]:
|
||||
return False
|
||||
return True
|
||||
|
||||
ag_search = search.strip() or domain or (next(iter(ips)) if len(ips) == 1 else "")
|
||||
res = await adguard.collect(search=ag_search, status="blocked" if status == "blocked" else "all",
|
||||
older_than=older_than, want=limit, keep=keep, max_rows=limit * 20)
|
||||
res["rows"] = _decorate(res["rows"], index)
|
||||
return res
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- domains
|
||||
|
||||
@router.get("/domains")
|
||||
async def top_domains() -> dict:
|
||||
st = await adguard.stats()
|
||||
return {
|
||||
"top_queried": [{"domain": d, "count": c} for d, c in adguard.top_list(st.get("top_queried_domains"))],
|
||||
"top_blocked": [{"domain": d, "count": c} for d, c in adguard.top_list(st.get("top_blocked_domains"))],
|
||||
"num_queries": st.get("num_dns_queries"), "num_blocked": st.get("num_blocked_filtering"),
|
||||
"time_units": st.get("time_units"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/domains/{name}")
|
||||
async def domain_detail(name: str, sample: int = Query(3000, ge=100, le=10000)) -> dict:
|
||||
name = name.strip().rstrip(".").lower()
|
||||
if not name or len(name) > 253:
|
||||
raise HTTPException(400, "Give a domain name, like example.com")
|
||||
base = adguard.base_domain(name)
|
||||
res = await adguard.collect(search=base, want=sample, max_rows=sample,
|
||||
keep=lambda r: r["domain"] == base or r["domain"].endswith("." + base))
|
||||
rows = res["rows"]
|
||||
exact = [r for r in rows if r["domain"] == name]
|
||||
with db() as con:
|
||||
index = devices.ip_index(con)
|
||||
|
||||
clients = defaultdict(lambda: {"count": 0, "blocked": 0, "last": 0.0, "name": ""})
|
||||
for r in exact:
|
||||
c = clients[r["client"]]
|
||||
c["count"] += 1
|
||||
c["blocked"] += r["blocked"]
|
||||
c["last"] = max(c["last"], r["ts"])
|
||||
c["name"] = c["name"] or r["client_name"]
|
||||
related = Counter(r["domain"] for r in rows if r["domain"] != name)
|
||||
related_blocked = Counter(r["domain"] for r in rows if r["domain"] != name and r["blocked"])
|
||||
|
||||
now = time.time()
|
||||
hours = [0] * 24
|
||||
blocked_hours = [0] * 24
|
||||
for r in exact:
|
||||
age = int((now - r["ts"]) // 3600)
|
||||
if 0 <= age < 24:
|
||||
hours[23 - age] += 1
|
||||
blocked_hours[23 - age] += r["blocked"]
|
||||
lat = [r["elapsed_ms"] for r in exact if r["elapsed_ms"] is not None]
|
||||
|
||||
st = {}
|
||||
try:
|
||||
st = await adguard.stats()
|
||||
except adguard.AdGuardError:
|
||||
pass
|
||||
stats_count = dict(adguard.top_list(st.get("top_queried_domains"))).get(name)
|
||||
stats_blocked = dict(adguard.top_list(st.get("top_blocked_domains"))).get(name)
|
||||
|
||||
return {
|
||||
"domain": name, "base": base, "sample_rows": len(rows), "scanned": res["scanned"], "complete": res["done"],
|
||||
"since": min((r["ts"] for r in rows), default=None),
|
||||
"count": len(exact), "blocked": sum(r["blocked"] for r in exact),
|
||||
"first": min((r["ts"] for r in exact), default=None), "last": max((r["ts"] for r in exact), default=None),
|
||||
"avg_ms": round(sum(lat) / len(lat), 2) if lat else None,
|
||||
"types": Counter(r["type"] for r in exact).most_common(),
|
||||
"reasons": Counter(r["reason"] for r in exact).most_common(),
|
||||
"rules": Counter(r["rule"] for r in exact if r["rule"]).most_common(5),
|
||||
"stats_count": stats_count, "stats_blocked": stats_blocked,
|
||||
"hours": hours, "blocked_hours": blocked_hours,
|
||||
"clients": sorted(({"ip": ip, **v, "device": index.get(ip)} for ip, v in clients.items()), key=lambda x: -x["count"]),
|
||||
"related": [{"domain": d, "count": c, "blocked": related_blocked.get(d, 0)} for d, c in related.most_common(50)],
|
||||
"recent": _decorate(exact[:50], index),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/dns/blocked")
|
||||
async def blocked(sample: int = Query(1000, ge=50, le=5000)) -> dict:
|
||||
st = await adguard.stats()
|
||||
res = await adguard.collect(status="blocked", want=sample, max_rows=sample, keep=lambda r: r["blocked"])
|
||||
with db() as con:
|
||||
index = devices.ip_index(con)
|
||||
agg = defaultdict(lambda: {"count": 0, "clients": set(), "last": 0.0, "rule": "", "reason": ""})
|
||||
for r in res["rows"]:
|
||||
a = agg[r["domain"]]
|
||||
a["count"] += 1
|
||||
a["clients"].add(r["client"])
|
||||
a["last"] = max(a["last"], r["ts"])
|
||||
a["rule"] = a["rule"] or r["rule"]
|
||||
a["reason"] = a["reason"] or r["reason"]
|
||||
recent = [
|
||||
{"domain": d, "count": a["count"], "last": a["last"], "rule": a["rule"], "reason": a["reason"],
|
||||
"clients": [{"ip": ip, "device": index.get(ip)} for ip in sorted(a["clients"])]}
|
||||
for d, a in sorted(agg.items(), key=lambda kv: -kv[1]["count"])
|
||||
]
|
||||
return {
|
||||
"top": [{"domain": d, "count": c} for d, c in adguard.top_list(st.get("top_blocked_domains"))],
|
||||
"num_blocked": st.get("num_blocked_filtering"), "num_queries": st.get("num_dns_queries"),
|
||||
"recent": recent, "sample": len(res["rows"]), "since": min((r["ts"] for r in res["rows"]), default=None),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- discovery (background)
|
||||
|
||||
async def discover_once() -> int:
|
||||
"""Pull client lists, DHCP leases and recent queries from AdGuard into the device table."""
|
||||
if not settings.get().adguard_configured:
|
||||
return 0
|
||||
found: list[dict] = []
|
||||
clients = await adguard.get("/control/clients")
|
||||
for c in clients.get("clients") or []:
|
||||
ids = c.get("ids") or []
|
||||
macs = [i for i in ids if devices.norm_mac(i)]
|
||||
ips = [i for i in ids if i.replace(".", "").isdigit() or (":" in i and not devices.norm_mac(i) and "/" not in i)]
|
||||
for ip in ips or [None]:
|
||||
found.append({"ip": ip, "mac": macs[0] if macs else None, "hostname": c.get("name"), "source": "adguard"})
|
||||
for c in clients.get("auto_clients") or []:
|
||||
found.append({"ip": c.get("ip"), "hostname": c.get("name"), "source": f"adguard-{(c.get('source') or 'auto').lower()}"})
|
||||
try:
|
||||
dhcp = await adguard.get("/control/dhcp/status")
|
||||
for lease in (dhcp.get("leases") or []) + (dhcp.get("static_leases") or []):
|
||||
found.append({"ip": lease.get("ip"), "mac": lease.get("mac"), "hostname": lease.get("hostname"), "source": "dhcp"})
|
||||
except adguard.AdGuardError:
|
||||
pass # DHCP not in use
|
||||
recent = await adguard.collect(want=adguard.PAGE, max_rows=adguard.PAGE)
|
||||
last: dict[str, tuple[float, str]] = {}
|
||||
for r in recent["rows"]:
|
||||
if r["client"] and r["ts"] > last.get(r["client"], (0, ""))[0]:
|
||||
last[r["client"]] = (r["ts"], r["client_name"])
|
||||
|
||||
def write():
|
||||
with db() as con:
|
||||
for f in found:
|
||||
devices.sighting(con, ip=f["ip"], mac=f.get("mac"), hostname=f.get("hostname"), source=f["source"])
|
||||
for ip, (ts, name) in last.items():
|
||||
devices.sighting(con, ip=ip, hostname=name or None, source="dns", seen=ts)
|
||||
await asyncio.to_thread(write)
|
||||
return len(found) + len(last)
|
||||
|
||||
|
||||
async def discovery_loop(every: float = 60) -> None:
|
||||
while True:
|
||||
try:
|
||||
await discover_once()
|
||||
except (adguard.AdGuardError, adguard.NotConfigured) as e:
|
||||
log.warning("client discovery: %s", e)
|
||||
except Exception:
|
||||
log.exception("client discovery failed")
|
||||
await asyncio.sleep(every)
|
||||
215
app/hub/health.py
Normal file
215
app/hub/health.py
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
"""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
|
||||
174
app/hub/probes.py
Normal file
174
app/hub/probes.py
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
"""Probe management (UI) and the probe report endpoint (probes, token auth)."""
|
||||
|
||||
import ipaddress
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.hub import devices, settings
|
||||
from app.hub.db import db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
MAX_BATCH = 5000
|
||||
|
||||
|
||||
class ProbeCreate(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=60)
|
||||
|
||||
|
||||
class ProbeUpdate(BaseModel):
|
||||
name: str | None = Field(default=None, min_length=1, max_length=60)
|
||||
address: str | None = Field(default=None, max_length=255) # "" = detect again from reports
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
|
||||
|
||||
class Measurement(BaseModel):
|
||||
ts: float
|
||||
target: str = Field(max_length=300)
|
||||
label: str | None = Field(default=None, max_length=200)
|
||||
kind: str = Field(pattern="^(lan|wan)$")
|
||||
method: str = Field(pattern="^(icmp|http|dns|throughput)$")
|
||||
ok: bool
|
||||
latency: float | None = None
|
||||
loss: float | None = None
|
||||
mbps: float | None = None
|
||||
error: str | None = Field(default=None, max_length=300)
|
||||
|
||||
|
||||
class Neighbor(BaseModel):
|
||||
ip: str = Field(max_length=64)
|
||||
mac: str = Field(max_length=32)
|
||||
|
||||
|
||||
class Report(BaseModel):
|
||||
version: str | None = Field(default=None, max_length=40)
|
||||
hostname: str | None = Field(default=None, max_length=255)
|
||||
port: int = Field(default=8765, ge=1, le=65535)
|
||||
advertise_addr: str | None = Field(default=None, max_length=255)
|
||||
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)
|
||||
|
||||
|
||||
def is_online(row, now: float | None = None) -> bool:
|
||||
now = now or time.time()
|
||||
return bool(row["last_seen"]) and now - row["last_seen"] < settings.get().probe_interval * 3 + 10
|
||||
|
||||
|
||||
def probe_out(row, *, with_token: bool = False) -> dict:
|
||||
out = {k: row[k] for k in ("id", "name", "address", "port", "hostname", "version", "created", "last_seen", "last_error")}
|
||||
out["address_locked"] = bool(row["address_locked"])
|
||||
out["icmp"] = None if row["icmp"] is None else bool(row["icmp"])
|
||||
out["online"] = is_online(row)
|
||||
if with_token:
|
||||
out["token"] = row["token"]
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/probes")
|
||||
def list_probes() -> dict:
|
||||
with db() as con:
|
||||
rows = con.execute("SELECT * FROM probes ORDER BY name COLLATE NOCASE").fetchall()
|
||||
s = settings.get()
|
||||
return {"probes": [probe_out(r) for r in rows], "interval": s.probe_interval,
|
||||
"install_url": s.probe_install_url, "hub_url": s.hub_public_url}
|
||||
|
||||
|
||||
@router.post("/probes", status_code=201)
|
||||
def create_probe(body: ProbeCreate) -> dict:
|
||||
token = secrets.token_urlsafe(24)
|
||||
with db() as con:
|
||||
cur = con.execute("INSERT INTO probes(name, token, created) VALUES (?, ?, ?)", (body.name.strip(), token, time.time()))
|
||||
row = con.execute("SELECT * FROM probes WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return probe_out(row, with_token=True)
|
||||
|
||||
|
||||
def _get(con, probe_id: int):
|
||||
row = con.execute("SELECT * FROM probes WHERE id = ?", (probe_id,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "No probe with that id")
|
||||
return row
|
||||
|
||||
|
||||
@router.get("/probes/{probe_id}")
|
||||
def get_probe(probe_id: int) -> dict:
|
||||
with db() as con:
|
||||
return probe_out(_get(con, probe_id), with_token=True)
|
||||
|
||||
|
||||
@router.patch("/probes/{probe_id}")
|
||||
def update_probe(probe_id: int, body: ProbeUpdate) -> dict:
|
||||
with db() as con:
|
||||
_get(con, probe_id)
|
||||
if body.name is not None:
|
||||
con.execute("UPDATE probes SET name = ? WHERE id = ?", (body.name.strip(), probe_id))
|
||||
if body.address is not None:
|
||||
addr = body.address.strip()
|
||||
con.execute("UPDATE probes SET address = ?, address_locked = ? WHERE id = ?", (addr or None, int(bool(addr)), probe_id))
|
||||
if body.port is not None:
|
||||
con.execute("UPDATE probes SET port = ? WHERE id = ?", (body.port, probe_id))
|
||||
return probe_out(_get(con, probe_id), with_token=True)
|
||||
|
||||
|
||||
@router.delete("/probes/{probe_id}", status_code=204)
|
||||
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,))
|
||||
if not keep_history:
|
||||
con.execute("DELETE FROM measurements WHERE probe_id = ?", (probe_id,))
|
||||
|
||||
|
||||
def probe_config(con, row) -> dict:
|
||||
"""What a probe should test, returned on every report."""
|
||||
s = settings.get()
|
||||
peers = [
|
||||
{"id": p["id"], "name": p["name"], "host": p["address"], "port": p["port"] or 8765}
|
||||
for p in con.execute("SELECT * FROM probes WHERE id != ? AND address IS NOT NULL ORDER BY id", (row["id"],))
|
||||
]
|
||||
dns = [{"server": d, "label": "LAN DNS" if len(s.lan_dns_servers) == 1 else f"LAN DNS {d}", "kind": "lan"} for d in s.lan_dns_servers]
|
||||
dns += [{"server": d, "label": f"DNS {d}", "kind": "wan"} for d in s.dns_servers]
|
||||
http = [{"url": u, "label": u.split("//", 1)[-1].split("/", 1)[0], "kind": "wan", "target": f"web:{u}"} for u in s.wan_http_urls]
|
||||
if s.vps_url:
|
||||
http.append({"url": f"{s.vps_url}/probe/ping", "label": "VPS", "kind": "wan", "target": "vps"})
|
||||
return {
|
||||
"probe_id": row["id"], "name": row["name"], "interval": s.probe_interval, "peers": peers,
|
||||
"dns": dns, "dns_name": s.dns_query_name, "http": http,
|
||||
"throughput_every": s.throughput_every, "throughput_bytes": s.throughput_bytes,
|
||||
}
|
||||
|
||||
|
||||
def _client_ip(request: Request) -> str | None:
|
||||
host = request.client.host if request.client else None
|
||||
try:
|
||||
return str(ipaddress.ip_address(host)) if host else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
@router.post("/probe/report")
|
||||
def report(body: Report, request: Request, authorization: str = Header(default="")) -> dict:
|
||||
token = authorization.removeprefix("Bearer ").strip()
|
||||
now = time.time()
|
||||
with db() as con:
|
||||
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.")
|
||||
address = row["address"]
|
||||
if not row["address_locked"]:
|
||||
address = (body.advertise_addr or "").strip() or _client_ip(request) or address
|
||||
con.execute(
|
||||
"UPDATE probes SET address = ?, port = ?, hostname = ?, version = ?, icmp = ?, last_seen = ?, last_error = NULL WHERE id = ?",
|
||||
(address, body.port, body.hostname, body.version, None if body.icmp is None else int(body.icmp), now, row["id"]),
|
||||
)
|
||||
con.executemany(
|
||||
"INSERT INTO measurements(ts, probe_id, target, label, kind, method, ok, latency, loss, mbps, error) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
|
||||
[(m.ts, row["id"], m.target, m.label, m.kind, m.method, int(m.ok), m.latency, m.loss, m.mbps, m.error) for m in body.measurements],
|
||||
)
|
||||
for n in body.neighbors:
|
||||
devices.sighting(con, ip=n.ip, mac=n.mac, source="arp", seen=now)
|
||||
row = con.execute("SELECT * FROM probes WHERE id = ?", (row["id"],)).fetchone()
|
||||
return probe_config(con, row)
|
||||
131
app/hub/server.py
Normal file
131
app/hub/server.py
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
"""The hub: web UI, JSON API for it, the probe report endpoint and background jobs."""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import contextlib
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, FastAPI, HTTPException, Request
|
||||
from fastapi.responses import FileResponse, JSONResponse, Response
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from app.hub import adguard, db, dns, health, probes, settings
|
||||
from app.version import VERSION
|
||||
|
||||
log = logging.getLogger("hub")
|
||||
STATIC = Path(__file__).resolve().parent.parent / "static"
|
||||
|
||||
|
||||
async def _retention_loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
def run():
|
||||
with db.db() as con:
|
||||
return health.prune(con, settings.get().retention_days)
|
||||
n = await asyncio.to_thread(run)
|
||||
if n:
|
||||
log.info("pruned %d old measurements", n)
|
||||
except Exception:
|
||||
log.exception("retention job failed")
|
||||
await asyncio.sleep(3600)
|
||||
|
||||
|
||||
@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())]
|
||||
if settings.get().adguard_configured:
|
||||
tasks.append(asyncio.create_task(dns.discovery_loop()))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for t in tasks:
|
||||
t.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
|
||||
app = FastAPI(title="Network Monitor", version=VERSION, lifespan=lifespan,
|
||||
docs_url="/api/docs", redoc_url=None, openapi_url="/api/openapi.json")
|
||||
|
||||
|
||||
@app.exception_handler(adguard.NotConfigured)
|
||||
async def _not_configured(_req, exc):
|
||||
return JSONResponse({"detail": str(exc), "code": "adguard_not_configured"}, status_code=503)
|
||||
|
||||
|
||||
@app.exception_handler(adguard.AdGuardError)
|
||||
async def _adguard_error(_req, exc):
|
||||
return JSONResponse({"detail": str(exc), "code": "adguard_error"}, status_code=502)
|
||||
|
||||
|
||||
OPEN_PATHS = ("/healthz", "/api/probe/report")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def password(request: Request, call_next):
|
||||
"""Optional HTTP basic auth for the UI and its API (UI_PASSWORD). Probes use their own tokens."""
|
||||
pw = settings.get().ui_password
|
||||
if pw and not request.url.path.startswith(OPEN_PATHS):
|
||||
given = ""
|
||||
auth = request.headers.get("authorization", "")
|
||||
if auth.lower().startswith("basic "):
|
||||
try:
|
||||
given = base64.b64decode(auth[6:]).decode().split(":", 1)[-1]
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
given = ""
|
||||
if not secrets.compare_digest(given.encode(), pw.encode()):
|
||||
return Response("Password required", status_code=401, headers={"WWW-Authenticate": 'Basic realm="network monitor"'})
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
api = APIRouter()
|
||||
|
||||
|
||||
@api.get("/info")
|
||||
def info() -> dict:
|
||||
s = settings.get()
|
||||
return {"name": "Network Monitor", "role": "hub", "version": VERSION, "adguard": s.adguard_configured,
|
||||
"probe_interval": s.probe_interval, "retention_days": s.retention_days,
|
||||
"thresholds": {"lan_ms": s.slow_lan_ms, "wan_ms": s.slow_wan_ms, "dns_ms": s.slow_dns_ms},
|
||||
"dns_servers": s.dns_servers, "lan_dns_servers": s.lan_dns_servers, "dns_query_name": s.dns_query_name,
|
||||
"wan_http_urls": s.wan_http_urls, "vps_url": s.vps_url, "throughput_every": s.throughput_every,
|
||||
"throughput_bytes": s.throughput_bytes, "password": bool(s.ui_password),
|
||||
"install_mode": os.environ.get("INSTALL_MODE") or "docker",
|
||||
"update_command": os.environ.get("UPDATE_COMMAND") or "docker exec network-monitor update",
|
||||
"env_file": f"{os.environ.get('INSTALL_DIR') or '/opt/network-monitor'}/.env"}
|
||||
|
||||
|
||||
api.include_router(probes.router)
|
||||
api.include_router(health.router)
|
||||
api.include_router(dns.router)
|
||||
app.include_router(api, prefix="/api")
|
||||
|
||||
|
||||
@app.get("/healthz", include_in_schema=False)
|
||||
def healthz() -> dict:
|
||||
return {"status": "ok", "version": VERSION, "role": "hub"}
|
||||
|
||||
|
||||
class Assets(StaticFiles):
|
||||
"""Browsers revalidate on every load (cheap 304s), so an update shows up at once."""
|
||||
|
||||
async def get_response(self, path, scope):
|
||||
response = await super().get_response(path, scope)
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
return response
|
||||
|
||||
|
||||
app.mount("/static", Assets(directory=STATIC), name="static")
|
||||
|
||||
|
||||
@app.get("/{path:path}", include_in_schema=False)
|
||||
def spa(path: str) -> FileResponse:
|
||||
"""Every app path gets the shell; the client-side router picks the view."""
|
||||
if path.startswith(("api/", "static/")):
|
||||
raise HTTPException(404, "Not found")
|
||||
return FileResponse(STATIC / "index.html", headers={"Cache-Control": "no-cache"})
|
||||
69
app/hub/settings.py
Normal file
69
app/hub/settings.py
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
"""Hub settings, read from the environment (.env) on each call so tests can change them."""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from urllib.parse import urlparse
|
||||
|
||||
DEFAULT_PROBE_INSTALL_URL = "https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install-probe.sh"
|
||||
|
||||
|
||||
def _list(name: str, default: str) -> list[str]:
|
||||
return [x.strip() for x in os.environ.get(name, default).split(",") if x.strip()]
|
||||
|
||||
|
||||
def _num(name: str, default: float) -> float:
|
||||
try:
|
||||
return float(os.environ.get(name, "") or default)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
ui_password: str
|
||||
adguard_url: str
|
||||
adguard_username: str
|
||||
adguard_password: str
|
||||
probe_interval: int
|
||||
retention_days: float
|
||||
dns_servers: list[str]
|
||||
lan_dns_servers: list[str]
|
||||
dns_query_name: str
|
||||
wan_http_urls: list[str]
|
||||
vps_url: str
|
||||
slow_lan_ms: float
|
||||
slow_wan_ms: float
|
||||
slow_dns_ms: float
|
||||
throughput_every: int
|
||||
throughput_bytes: int
|
||||
probe_install_url: str
|
||||
hub_public_url: str
|
||||
|
||||
@property
|
||||
def adguard_configured(self) -> bool:
|
||||
return bool(self.adguard_url)
|
||||
|
||||
|
||||
def get() -> Settings:
|
||||
adguard_url = os.environ.get("ADGUARD_URL", "").strip().rstrip("/")
|
||||
lan_default = urlparse(adguard_url).hostname or "" if adguard_url else ""
|
||||
return Settings(
|
||||
ui_password=os.environ.get("UI_PASSWORD", ""),
|
||||
adguard_url=adguard_url,
|
||||
adguard_username=os.environ.get("ADGUARD_USERNAME", ""),
|
||||
adguard_password=os.environ.get("ADGUARD_PASSWORD", ""),
|
||||
probe_interval=max(5, int(_num("PROBE_INTERVAL", 30))),
|
||||
retention_days=max(1.0, _num("RETENTION_DAYS", 14)),
|
||||
dns_servers=_list("DNS_SERVERS", "1.1.1.1,8.8.8.8,9.9.9.9"),
|
||||
lan_dns_servers=_list("LAN_DNS_SERVERS", lan_default),
|
||||
dns_query_name=os.environ.get("DNS_QUERY_NAME", "example.com").strip() or "example.com",
|
||||
wan_http_urls=_list("WAN_HTTP_URLS", "http://connectivitycheck.gstatic.com/generate_204"),
|
||||
vps_url=os.environ.get("VPS_URL", "").strip().rstrip("/"),
|
||||
slow_lan_ms=_num("SLOW_LAN_MS", 100),
|
||||
slow_wan_ms=_num("SLOW_WAN_MS", 200),
|
||||
slow_dns_ms=_num("SLOW_DNS_MS", 250),
|
||||
throughput_every=max(0, int(_num("THROUGHPUT_EVERY", 10))),
|
||||
throughput_bytes=int(min(_num("THROUGHPUT_BYTES", 4_000_000), 50_000_000)),
|
||||
probe_install_url=os.environ.get("PROBE_INSTALL_URL", DEFAULT_PROBE_INSTALL_URL).strip(),
|
||||
hub_public_url=os.environ.get("HUB_PUBLIC_URL", "").strip().rstrip("/"),
|
||||
)
|
||||
Loading…
Add table
Add a link
Reference in a new issue