network-monitor/CLAUDE.md
neil 54a765510a 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>
2026-11-04 18:10:29 -08:00

8.9 KiB

CLAUDE.md

Shared context for Claude Code sessions working on this repo. This file is read on the dev machine and on each machine that runs a hub or probe (Proxmox nodes, LXCs, a Mac mini). Keep it current: when you learn something about a deployment environment, add it under "Deployment notes", and commit it.

What this is

A home network monitor with two roles, built from one repo:

  • Hub (ROLE=hub, port 8000). FastAPI app, web UI and API.

    • Stores probe measurements and client devices in SQLite.
    • Reads DNS data from AdGuard Home's /control/* API (HTTP basic auth).
  • Probe (ROLE=probe, port 8765). Every PROBE_INTERVAL (30 s), it:

    1. tests every other probe (ping, HTTP, a timed download), the gateway, LAN and public DNS, internet URLs and an optional VPS
    2. POSTs the results plus its ARP neighbors to the hub's /api/probe/report with a per-probe bearer token
    3. receives its config (peers, targets) back in the response; that's the only control channel

    While the hub is unreachable, results queue in memory and upload later. With no HUB_URL it is serve-only, e.g. on a VPS.

Remote: https://git.neilbantoc.dev/services/network-monitor.git (Gitea). The installers are fetched from https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/<file>. That raw URL pattern is an assumption about this Gitea instance; if curl gets a 404, fix it in install.sh, scripts/build-installers.sh, app/hub/settings.py (DEFAULT_PROBE_INSTALL_URL) and the README.

Deployment modes

Mode How it runs Update command Logs
docker compose.yml (hub, bridge, port 8000) / compose.probe.yml (probe, network_mode: host). The image is runtime only; the source is cloned into a volume. docker exec network-monitor update / docker exec network-probe update docker logs -f <name>
native, Linux /opt/<name> is the git checkout plus .venv/, data/, .env, .native. A systemd unit <name>.service runs native/run.sh as user netmon. sudo <name>-update journalctl -u <name> -f
native, macOS Same layout. The LaunchDaemon /Library/LaunchDaemons/dev.neilbantoc.<name>.plist runs as the installing user. <name>-update (no sudo; it calls sudo for launchctl kickstart) /opt/<name>/data/service.log

<name> is network-monitor (hub) or network-probe. Mode defaults:

  • native on macOS and inside LXC (detected with systemd-detect-virt -c)
  • docker elsewhere

The mode is stored as INSTALL_MODE in /opt/<name>/.env.

The intended topology:

  • Proxmox VE nodes: an unprivileged Debian 12 LXC per node (native mode) running a probe, on vmbr0. The hub runs in an LXC too. Do not install Docker on a PVE node itself: Docker changes the host firewall, and with the Proxmox firewall on that can break guest networking.
  • Mac mini: native probe.

Both update commands do the same thing:

  1. fetch and check out the commit
  2. reinstall requirements if they changed
  3. check that import app.main works
  4. restart, and wait for /healthz to report the new short SHA

Any failure rolls back to the previous commit. --check, --rollback and <ref> work for both. Settings live in /opt/<name>/.env; they are re-read on restart and update and never committed.

Repo map

app/main.py            picks the hub or probe app by ROLE; shared lifespan (creates DATA_DIR)
app/hub/server.py      FastAPI app, optional UI_PASSWORD basic auth, SPA fallback, /api/info
app/hub/probes.py      probe CRUD + POST /api/probe/report (token auth) → returns probe config
app/hub/health.py      matrix / strips / incidents / series from the measurements table
app/hub/dns.py         clients, query log, domains, blocked; background AdGuard discovery (60 s)
app/hub/devices.py     device merge logic (MAC key, ip: fallback, IP→MAC folding)
app/hub/adguard.py     AdGuard client (httpx; tests swap TRANSPORT), query log paging, base_domain
app/hub/settings.py    all hub settings from env, read per call
app/hub/db.py          SQLite schema (idempotent), one connection per unit of work
app/probe/server.py    probe app: /probe/ping, /probe/blob, / (status JSON), the report loop
app/probe/checks.py    icmp (icmplib, unprivileged), http, dns (hand-built UDP query), throughput,
                       gateway + ARP (Linux /proc/net, macOS route/arp)
app/static/            no-build frontend: house.css/ui.js/shell.js (vendored house style, don't
                       edit), app.css, charts.js (SVG), common.js, views/*.js (one per page)
install.sh             THE installer (both roles via NETMON_ROLE, both modes). Edit this one.
install-probe.sh       GENERATED: run scripts/build-installers.sh after editing install.sh
native/                setup.sh (venv, netmon user, systemd/launchd), run.sh, update.sh, lib.sh
container/             Dockerfile, entrypoint (supervisor), update.sh, lib.sh (Docker mode)
tests/                 pytest: hub API, health maths, fake AdGuard, probe checks, installers

Working on it

  • Run the tests in a container. Python 3.14 in the image, code supports 3.11+: docker run --rm -v "$PWD":/src:ro -w /src python:3.14-slim sh -c 'pip install -q -r requirements.txt -r requirements-dev.txt && python -m pytest -q -p no:cacheprovider'
  • Dev server: docker compose -f compose.yml -f compose.dev.yml up --build (hub on 127.0.0.1:8000, reload on save).
  • After editing install.sh: run bash scripts/build-installers.sh. A test fails if install-probe.sh is stale.
  • Keep shell scripts bash 3.2 compatible (install.sh, native/*.sh), because macOS runs them with /bin/bash 3.2:
    • no mapfile, no ${x,,}, no associative arrays
    • no "${arr[@]}" on possibly-empty arrays under set -u
    • don't source <(...)
    • check with docker run --rm -v "$PWD":/src:ro bash:3.2 bash -n /src/install.sh
  • No build step. Plain ES modules and CSS. Vendor any library into app/static/vendor/ with its version noted.
  • Frontend style. Follow the house style: toolbar → content → status bar per screen, house classes/tokens, sentence-case copy. Put user and API strings into the DOM with textContent only (el() does this). Never replaceChildren(null); use fill() from common.js.
  • Startup work goes in lifespan, never at import. update imports app.main as a pre-flight check.
  • Don't remove DATA_DIR.mkdir(parents=True, exist_ok=True) in app/main.py. The scaffold's verify.sh patches that exact line to simulate a startup crash.
  • New settings: add to app/hub/settings.py and .env.example, or for probes .env.probe.example (and KEYS in install.sh if the installer should accept them).
  • New dependencies: pin ==X.Y.* in requirements.txt. Prefer pure-Python wheels: native mode installs them on Debian 12/13 and macOS.

Debugging a deployment

Start with these:

  • Probe status: curl -s http://127.0.0.1:8765/. It shows registered, peers, icmp, gateway, last_error and buffered.
  • Hub health: curl -s http://127.0.0.1:8000/healthz
  • Hub config as the UI sees it: curl -s http://127.0.0.1:8000/api/info

Common problems:

  • icmp: false on Linux: sysctl net.ipv4.ping_group_range must include the service's group, e.g. 0 2147483647. Re-run the installer as root; it writes /etc/sysctl.d/60-network-probe-ping.conf.
  • registered: false: the token is unknown to the hub (the probe was removed there). Add the probe again and re-run its install command.
  • Peers time out:
    • Check that the address the hub recorded is the probe's LAN IP. A probe reaching the hub through a NAT or proxy may report the wrong one; set ADVERTISE_ADDR in the probe's .env, or the address on its page in the UI.
    • Check firewalls on 8765/tcp.
  • Native service won't start: systemctl status <name>, journalctl -u <name> -n 100. On macOS: sudo launchctl print system/dev.neilbantoc.<name> and data/service.log.
  • Python too old for native mode: needs 3.11+. Debian 11 / Ubuntu 22.04 are too old; use Docker mode or a newer template.
  • AdGuard pages show an error: check ADGUARD_URL (the web UI address, e.g. http://ip:3000 or :80) and credentials, then restart the hub.

Status and what is untested

What has been tested:

  • The tests and the scaffold's verify.sh (Docker mode: build, install, update, refuse, rollback) pass.
  • End to end on Linux Docker: hub + two probes + a stand-in AdGuard.
  • Native mode on Debian 12 under systemd, simulating an LXC (Python 3.11):
    • installs
    • ping fixed by the sysctl
    • update, refuse, rollback
    • survives a reboot
    • re-run keeps .env

Never run on real hardware yet. Note what you find under "Deployment notes" below:

  • an actual Proxmox LXC (unprivileged, nesting)
  • macOS: launchd, Homebrew Python, route/arp parsing on a live system, the application firewall
  • a real AdGuard Home (only tested against a stand-in built from its API docs)

Deployment notes

Add environment-specific findings here (machine, date, what happened, fix).

  • (none yet)