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/probe/__init__.py
Normal file
0
app/probe/__init__.py
Normal file
208
app/probe/checks.py
Normal file
208
app/probe/checks.py
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
"""The probe's measurements. Each returns a measurement dict the hub stores as is."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from icmplib import async_ping
|
||||
from icmplib.exceptions import ICMPLibError, SocketPermissionError
|
||||
|
||||
PROC_NET = os.environ.get("PROC_NET", "/proc/net")
|
||||
|
||||
|
||||
def m(target, label, kind, method, ok, latency=None, loss=None, mbps=None, error=None) -> dict:
|
||||
r = lambda v, d=2: None if v is None else round(v, d)
|
||||
return {"ts": time.time(), "target": target, "label": label, "kind": kind, "method": method, "ok": bool(ok),
|
||||
"latency": r(latency), "loss": r(loss, 3), "mbps": r(mbps), "error": (error or None) and str(error)[:300]}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- ICMP
|
||||
|
||||
ICMP_STATE = {"ok": None} # None = untried, True = works, False = not permitted on this host
|
||||
ICMP_HINT = "ICMP not permitted: set net.ipv4.ping_group_range on the host (install-probe.sh does this)"
|
||||
|
||||
|
||||
async def icmp(host: str, target: str, label: str, kind: str, count: int = 4) -> dict | None:
|
||||
if ICMP_STATE["ok"] is False:
|
||||
return None
|
||||
try:
|
||||
h = await async_ping(host, count=count, interval=0.2, timeout=1.5, privileged=False)
|
||||
except SocketPermissionError:
|
||||
ICMP_STATE["ok"] = False
|
||||
return None
|
||||
except (ICMPLibError, OSError) as e:
|
||||
return m(target, label, kind, "icmp", False, loss=1.0, error=f"{e.__class__.__name__}: {e}")
|
||||
ICMP_STATE["ok"] = True
|
||||
if not h.is_alive:
|
||||
return m(target, label, kind, "icmp", False, loss=1.0, error="no reply")
|
||||
return m(target, label, kind, "icmp", True, latency=h.avg_rtt, loss=h.packet_loss)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- HTTP
|
||||
|
||||
async def http(client: httpx.AsyncClient, url: str, target: str, label: str, kind: str) -> dict:
|
||||
t = time.perf_counter()
|
||||
try:
|
||||
r = await client.get(url, headers={"Cache-Control": "no-cache"})
|
||||
ms = (time.perf_counter() - t) * 1000
|
||||
if r.status_code >= 400:
|
||||
return m(target, label, kind, "http", False, latency=ms, error=f"HTTP {r.status_code}")
|
||||
return m(target, label, kind, "http", True, latency=ms)
|
||||
except httpx.HTTPError as e:
|
||||
return m(target, label, kind, "http", False, error=_err(e))
|
||||
|
||||
|
||||
async def throughput(client: httpx.AsyncClient, base: str, n_bytes: int, target: str, label: str) -> dict:
|
||||
t = time.perf_counter()
|
||||
got = 0
|
||||
try:
|
||||
async with client.stream("GET", f"{base}/probe/blob", params={"bytes": n_bytes}, timeout=60) as r:
|
||||
r.raise_for_status()
|
||||
async for chunk in r.aiter_bytes():
|
||||
got += len(chunk)
|
||||
secs = time.perf_counter() - t
|
||||
return m(target, label, "lan", "throughput", True, latency=secs * 1000, mbps=got * 8 / secs / 1e6)
|
||||
except httpx.HTTPError as e:
|
||||
return m(target, label, "lan", "throughput", False, error=_err(e))
|
||||
|
||||
|
||||
def _err(e: Exception) -> str:
|
||||
name = e.__class__.__name__
|
||||
text = str(e)
|
||||
return f"{name}: {text}" if text else name
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- DNS (one A query over UDP)
|
||||
|
||||
def dns_query_packet(name: str, qid: int) -> bytes:
|
||||
header = struct.pack("!HHHHHH", qid, 0x0100, 1, 0, 0, 0) # recursion desired
|
||||
qname = b"".join(bytes([len(p)]) + p.encode() for p in name.strip(".").split(".")) + b"\0"
|
||||
return header + qname + struct.pack("!HH", 1, 1) # A, IN
|
||||
|
||||
|
||||
RCODES = {1: "FORMERR", 2: "SERVFAIL", 3: "NXDOMAIN", 4: "NOTIMP", 5: "REFUSED"}
|
||||
|
||||
|
||||
async def dns(server: str, name: str, target: str, label: str, kind: str, timeout: float = 2.0, port: int = 53) -> dict:
|
||||
loop = asyncio.get_running_loop()
|
||||
qid = random.randrange(65536)
|
||||
fut = loop.create_future()
|
||||
|
||||
class Proto(asyncio.DatagramProtocol):
|
||||
def datagram_received(self, data, addr):
|
||||
if len(data) >= 12 and struct.unpack("!H", data[:2])[0] == qid and not fut.done():
|
||||
fut.set_result(data)
|
||||
|
||||
def error_received(self, exc):
|
||||
if not fut.done():
|
||||
fut.set_exception(exc)
|
||||
|
||||
family = socket.AF_INET6 if ":" in server else socket.AF_INET
|
||||
t = time.perf_counter()
|
||||
transport = None
|
||||
try:
|
||||
transport, _ = await loop.create_datagram_endpoint(Proto, remote_addr=(server, port), family=family)
|
||||
transport.sendto(dns_query_packet(name, qid))
|
||||
data = await asyncio.wait_for(fut, timeout)
|
||||
ms = (time.perf_counter() - t) * 1000
|
||||
flags, _, ancount = struct.unpack("!HHH", data[2:8])
|
||||
rcode = flags & 0xF
|
||||
if rcode:
|
||||
return m(target, label, kind, "dns", False, latency=ms, error=RCODES.get(rcode, f"rcode {rcode}"))
|
||||
if not ancount:
|
||||
return m(target, label, kind, "dns", False, latency=ms, error="empty answer")
|
||||
return m(target, label, kind, "dns", True, latency=ms)
|
||||
except TimeoutError:
|
||||
return m(target, label, kind, "dns", False, error="timeout")
|
||||
except OSError as e:
|
||||
return m(target, label, kind, "dns", False, error=f"{e.__class__.__name__}: {e}")
|
||||
finally:
|
||||
if transport:
|
||||
transport.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- host network facts
|
||||
# Linux reads /proc/net (host networking, LXC or bare metal). macOS has no /proc, so it asks
|
||||
# `route` and `arp` instead.
|
||||
|
||||
def _run(*cmd: str) -> str:
|
||||
try:
|
||||
return subprocess.run(cmd, capture_output=True, text=True, timeout=5, check=False).stdout
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return ""
|
||||
|
||||
|
||||
def default_gateway() -> str | None:
|
||||
if sys.platform == "darwin":
|
||||
return parse_route_get(_run("/sbin/route", "-n", "get", "default"))
|
||||
try:
|
||||
with open(f"{PROC_NET}/route") as f:
|
||||
next(f)
|
||||
for line in f:
|
||||
parts = line.split()
|
||||
if len(parts) > 3 and parts[1] == "00000000" and int(parts[3], 16) & 2:
|
||||
return socket.inet_ntoa(struct.pack("<L", int(parts[2], 16)))
|
||||
except (OSError, ValueError, StopIteration):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def parse_route_get(text: str) -> str | None:
|
||||
"""`route -n get default` on macOS: a line like ' gateway: 192.168.1.1'."""
|
||||
for line in text.splitlines():
|
||||
key, _, value = line.strip().partition(":")
|
||||
if key == "gateway" and value.strip():
|
||||
return value.strip()
|
||||
return None
|
||||
|
||||
|
||||
# Container, VM and VPN interfaces: their neighbors are containers or tunnels, not devices on the network.
|
||||
VIRTUAL_IFACES = ("docker", "br-", "veth", "virbr", "cni", "flannel", "cali", "lxc", "vnet", "tun", "tap", "wg", "zt",
|
||||
"tailscale", "utun", "bridge", "vmenet", "awdl", "llw", "anpi", "ap1")
|
||||
|
||||
|
||||
def neighbors() -> list[dict]:
|
||||
"""Complete ARP entries on physical interfaces."""
|
||||
if sys.platform == "darwin":
|
||||
return parse_arp_an(_run("/usr/sbin/arp", "-an"))
|
||||
out = []
|
||||
try:
|
||||
with open(f"{PROC_NET}/arp") as f:
|
||||
next(f)
|
||||
for line in f:
|
||||
p = line.split()
|
||||
if len(p) >= 6 and p[5].startswith(VIRTUAL_IFACES):
|
||||
continue
|
||||
if len(p) >= 4 and p[2] != "0x0" and p[3] != "00:00:00:00:00:00":
|
||||
out.append({"ip": p[0], "mac": p[3].lower()})
|
||||
except (OSError, StopIteration):
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
_ARP_LINE = re.compile(r"\((?P<ip>[0-9.]+)\) at (?P<mac>[0-9a-fA-F:]+) on (?P<iface>\S+)")
|
||||
|
||||
|
||||
def parse_arp_an(text: str) -> list[dict]:
|
||||
"""`arp -an` on macOS: '? (192.168.1.1) at 0:11:32:a:b:c on en0 ifscope [ethernet]'.
|
||||
macOS drops leading zeros in MAC octets, so they are padded back."""
|
||||
out = []
|
||||
for line in text.splitlines():
|
||||
m = _ARP_LINE.search(line)
|
||||
if not m or m["iface"].startswith(VIRTUAL_IFACES) or "permanent" in line:
|
||||
continue
|
||||
octets = m["mac"].split(":")
|
||||
if len(octets) != 6:
|
||||
continue
|
||||
mac = ":".join(o.zfill(2) for o in octets).lower()
|
||||
if mac in ("00:00:00:00:00:00", "ff:ff:ff:ff:ff:ff") or m["ip"].endswith(".255") or m["ip"].startswith(("224.", "239.")):
|
||||
continue
|
||||
out.append({"ip": m["ip"], "mac": mac})
|
||||
return out
|
||||
210
app/probe/server.py
Normal file
210
app/probe/server.py
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
"""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
|
||||
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(),
|
||||
}
|
||||
|
||||
|
||||
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) -> dict | None:
|
||||
"""Send buffered measurements (oldest first, in batches). Returns the hub's config, or None."""
|
||||
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 []}
|
||||
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
|
||||
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."""
|
||||
e = env()
|
||||
state["hub_url"] = e["hub_url"]
|
||||
buffer: deque = deque(maxlen=BUFFER_MAX)
|
||||
cfg = load_config() or DEFAULT_CONFIG
|
||||
state["config"] = load_config()
|
||||
await asyncio.sleep(random.uniform(0, 5)) # spread probes out
|
||||
cycle = 0
|
||||
async with httpx.AsyncClient(timeout=10) as hub:
|
||||
while True:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
buffer.extend(await run_checks(cfg, cycle))
|
||||
except Exception as ex:
|
||||
log.exception("checks failed")
|
||||
state["last_error"] = f"checks failed: {ex}"
|
||||
try:
|
||||
new = await report(hub, e, buffer, cycle)
|
||||
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
|
||||
state["last_report"] = time.time()
|
||||
state["last_error"] = None
|
||||
except (httpx.HTTPError, RuntimeError, ValueError) as ex:
|
||||
state["last_error"] = f"report to hub failed: {checks._err(ex)}"
|
||||
log.warning(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):
|
||||
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"],
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue