"""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, PlainTextResponse, Response from fastapi.staticfiles import StaticFiles from app.hub import adguard, db, dns, health, outages, 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) 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()), asyncio.create_task(_silence_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", "/install-probe.sh", "/install.sh") @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") ROOT = Path(__file__).resolve().parent.parent.parent @app.get("/install-probe.sh", include_in_schema=False) @app.get("/install.sh", include_in_schema=False) def installer(request: Request) -> PlainTextResponse: """The installers, served from the hub's own checkout so a private repo needs no raw-file access: curl -fsSL http://:8000/install-probe.sh | HUB_URL=... PROBE_TOKEN=... bash""" name = request.url.path.lstrip("/") return PlainTextResponse((ROOT / name).read_text(), media_type="text/x-shellscript", headers={"Cache-Control": "no-cache"}) @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"})