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
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"})
|
||||
Loading…
Add table
Add a link
Reference in a new issue