"""The probe: a tiny HTTP server other probes test against, plus a loop that measures the mesh and the ISP link and reports to the hub. With no HUB_URL it only serves (e.g. on a VPS).""" import asyncio import contextlib import json import logging import os import random import socket import time from collections import deque from pathlib import Path import httpx from fastapi import FastAPI, Query from fastapi.responses import StreamingResponse from app.probe import checks, outage from app.version import VERSION log = logging.getLogger("probe") BUFFER_MAX = 20000 # measurements kept while the hub is unreachable (hours at the default interval) SEND_BATCH = 2000 state = { "hub_url": "", "registered": None, "last_report": None, "last_error": None, "cycles": 0, "buffered": 0, "config": None, "started": time.time(), "hub_unreachable_since": None, } def env() -> dict: return { "hub_url": os.environ.get("HUB_URL", "").strip().rstrip("/"), "token": os.environ.get("PROBE_TOKEN", "").strip(), "port": int(os.environ.get("PORT", "8765")), "advertise": os.environ.get("ADVERTISE_ADDR", "").strip(), } async def run_checks(cfg: dict, cycle: int) -> list[dict]: jobs = [] async with httpx.AsyncClient(timeout=4, follow_redirects=False) as client: for p in cfg.get("peers", []): target, label = f"probe:{p['id']}", p["name"] jobs.append(checks.icmp(p["host"], target, label, "lan")) base = f"http://{_hostport(p['host'], p['port'])}" jobs.append(checks.http(client, f"{base}/probe/ping", target, label, "lan")) gw = checks.default_gateway() if gw: jobs.append(checks.icmp(gw, "gateway", f"Gateway {gw}", "lan")) for d in cfg.get("dns", []): target = f"dns:{d['server']}" jobs.append(checks.dns(d["server"], cfg.get("dns_name", "example.com"), target, d["label"], d["kind"])) jobs.append(checks.icmp(d["server"], target, d["label"], d["kind"])) for h in cfg.get("http", []): jobs.append(checks.http(client, h["url"], h["target"], h["label"], h["kind"])) results = [r for r in await asyncio.gather(*jobs) if r] # Throughput runs after the latency checks, one peer at a time, so it doesn't skew them. every = cfg.get("throughput_every") or 0 if every and cycle % every == 0: for p in cfg.get("peers", []): base = f"http://{_hostport(p['host'], p['port'])}" results.append(await checks.throughput(client, base, cfg.get("throughput_bytes", 4_000_000), f"probe:{p['id']}", p["name"])) return results 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, 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 [], "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() if not buffer: break return config DEFAULT_CONFIG = { "interval": 30, "peers": [], "http": [], "dns_name": "example.com", "dns": [{"server": "1.1.1.1", "label": "DNS 1.1.1.1", "kind": "wan"}], } def _config_file(): return Path(os.environ.get("DATA_DIR", "data")) / "probe-config.json" def load_config() -> dict | None: try: return json.loads(_config_file().read_text()) except (OSError, ValueError): return None def save_config(cfg: dict) -> None: try: _config_file().parent.mkdir(parents=True, exist_ok=True) _config_file().write_text(json.dumps(cfg)) except OSError: pass 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. 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(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: 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: 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"] = last_logged = None except (httpx.HTTPError, RuntimeError, ValueError) as 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))) @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"]: task = asyncio.create_task(probe_loop()) elif e["hub_url"] or e["token"]: state["last_error"] = "set both HUB_URL and PROBE_TOKEN to report to a hub" try: yield finally: if task: task.cancel() with contextlib.suppress(asyncio.CancelledError): await task app = FastAPI(title="Network Monitor probe", version=VERSION, lifespan=lifespan, docs_url=None, redoc_url=None) @app.get("/healthz") def healthz() -> dict: return {"status": "ok", "version": VERSION, "role": "probe"} @app.get("/probe/ping") def ping() -> dict: return {"ok": True, "t": time.time()} CHUNK = b"\0" * 65536 @app.get("/probe/blob") def blob(bytes: int = Query(1_000_000, ge=1, le=50_000_000)) -> StreamingResponse: def gen(): left = bytes while left > 0: n = min(left, len(CHUNK)) yield CHUNK[:n] left -= n return StreamingResponse(gen(), media_type="application/octet-stream", headers={"Content-Length": str(bytes), "Cache-Control": "no-store"}) @app.get("/") def status() -> dict: cfg = state["config"] or {} return { "role": "probe", "version": VERSION, "hub_url": state["hub_url"] or None, "mode": "reporting" if state["hub_url"] else "serve only", "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"], "hub_unreachable_since": state["hub_unreachable_since"], "outage_log": outage.active(), }