network-monitor/README.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

252 lines
15 KiB
Markdown

# Network Monitor
Watch a home network from one page: how healthy the mesh and the internet link are, which devices are on the network, and what they look up in DNS.
It has two parts, built from this one repo and one Docker image:
- **The hub** (`install.sh`). The web UI and API. It stores probe results in SQLite and reads DNS data from AdGuard Home.
- **Probes** (`install-probe.sh`). Small containers on machines around the house. Each one serves a test endpoint, tests every other probe (ping, HTTP and a timed download), the gateway, the LAN DNS server, public DNS servers and the internet, then reports to the hub. A probe can also run on a VPS in serve-only mode, so the others measure the ISP link against it.
```
┌──────────── report every 30 s (token) ────────────┐
│ ▼
probe A ◄─┼── ping / HTTP / download ──► probe B ──────────► hub ──► AdGuard Home /control API
│ │ │ │
└── gateway, LAN DNS, 1.1.1.1, 8.8.8.8, VPS ┘ └── web UI :8000
```
## What you get
- **Network health** (home page)
- A matrix of every probe against every target over the last 5 minutes.
- Status strips over 1 h to 30 d showing OK, degraded, down or no data.
- A list of incidents. Failed or slow checks are merged into one outage per probe and target.
- **Probes**. Add a probe, which gives you its install command. Remove a probe, or set the address its peers use. Each probe has a page with latency and throughput charts per target.
- **Clients**. Every device seen on the network, merged from several sources:
- AdGuard Home's client list
- DHCP leases
- the query log
- the probes' ARP tables
A device is keyed by MAC address when one is known. You can name a device, give it a category (Computer, Mobile, IoT, Server…), mark it suspicious, and keep notes. Each client has a page with its top domains and its DNS requests.
- **Query log**. Search AdGuard's log, filter to blocked or allowed, or filter by client.
- **Domains**. For any domain:
- how many requests, how many were blocked, and which clients asked
- requests per hour over 24 h
- other names under the same registrable domain, such as `api.` and `cdn.`
- **Blocked domains**. What AdGuard blocked, how often, by which rule, and for whom.
## Install
Both installers are one pasted line. They work on Linux and macOS. Settings can be passed as environment variables; the top of `install.sh` lists them. There are two ways to run:
| Mode | What it is | Default on |
|---|---|---|
| `docker` | The app in a container (compose), Docker installed if missing | Linux hosts (VMs, bare metal) |
| `native` | A Python virtualenv plus a boot service: systemd on Linux, launchd on macOS | macOS, and inside LXC containers |
Pass `INSTALL_MODE=docker` or `INSTALL_MODE=native` to choose. The mode is saved in `.env`, so re-runs keep it. Native mode needs Python 3.11+ (Debian 12, Ubuntu 24.04 or newer; the installer installs it with apt or Homebrew). On Linux it runs as root and creates a `netmon` system user for the service.
Either way, the service starts on boot and restarts if it crashes.
### Which machine gets what
- **Proxmox VE nodes:** don't install Docker on the node itself. Docker changes the host firewall, and with the Proxmox firewall on that can cut traffic to guests. Run the hub and the probes in small LXC containers instead (below).
- **Mac mini:** native mode. Docker Desktop runs containers in a Linux VM, so a probe there would measure the VM, and it only starts at login. The installer refuses Docker on macOS.
- **Other Linux machines or VMs:** Docker mode (the default), or `INSTALL_MODE=native` if you prefer no Docker.
### 1. The hub
```bash
curl -fsSL https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install.sh | bash
```
Inside an LXC you are root, so that's it. On another Linux machine in native mode, use `| sudo env INSTALL_MODE=native bash`.
Then connect AdGuard Home in `/opt/network-monitor/.env`:
```bash
ADGUARD_URL=http://192.168.1.2:3000 # AdGuard Home's web UI address
ADGUARD_USERNAME=admin
ADGUARD_PASSWORD=...
```
and restart the hub: `docker restart network-monitor` (Docker) or `systemctl restart network-monitor` (native).
Open `http://<hub-ip>:8000`. The hub listens on the LAN (`HOST_BIND=0.0.0.0`) because probes report to it. Set `UI_PASSWORD` in `.env` to put a password on the UI.
### 2. Probes
On the hub, open **Probes → Add probe** and give the probe a name. The hub shows a command with that probe's token. Open the hub at its LAN address, not `localhost`, so the command has a `HUB_URL` the probe can reach. Run it on the probe machine:
```bash
# Linux host (Docker), or an LXC as root (native, detected automatically)
curl -fsSL https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install-probe.sh | HUB_URL=http://192.168.1.10:8000 PROBE_TOKEN=... bash
# Linux, native, not root
curl -fsSL https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install-probe.sh | sudo env HUB_URL=http://192.168.1.10:8000 PROBE_TOKEN=... bash
# macOS: as your own user (it asks for sudo when it needs it)
curl -fsSL https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install-probe.sh | HUB_URL=http://192.168.1.10:8000 PROBE_TOKEN=... bash
```
The probe's test server listens on port 8765 (`PROBE_PORT`) on all interfaces.
**Ping on Linux.** Linux needs unprivileged ping allowed (`net.ipv4.ping_group_range`). The installer sets it and persists it in `/etc/sysctl.d/60-network-probe-ping.conf`. That needs root. Without it, the probe skips ping and keeps its HTTP, DNS and throughput checks.
**Docker probes** use host networking, so they measure the machine's real link and see its ARP table.
### Proxmox: hub and probes in LXC containers
Create one small unprivileged Debian 12 container per node for the probe, and one anywhere for the hub. Put each on the node's LAN bridge, so its traffic leaves through the node's NIC and measures that node's link. For example, on node `pve1`:
```bash
pveam update && pveam available --section system | grep debian-12 # find the template name
pveam download local debian-12-standard_12.12-1_amd64.tar.zst # use the name from above
pct create 210 local:vztmpl/debian-12-standard_12.12-1_amd64.tar.zst \
--hostname probe-pve1 --cores 1 --memory 512 --swap 256 --rootfs local-lvm:4 \
--net0 name=eth0,bridge=vmbr0,ip=dhcp --unprivileged 1 --features nesting=1 --onboot 1
pct start 210 && pct enter 210
apt update && apt install -y curl # if the template lacks curl
curl -fsSL https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install-probe.sh | HUB_URL=http://<hub-ip>:8000 PROBE_TOKEN=... bash
```
- **`nesting=1`:** Debian 12's systemd needs it in an unprivileged container. New containers get it by default on recent Proxmox.
- **Detection:** the installer sees it is in an LXC and uses native mode; no Docker inside.
- **Docker instead:** if you'd rather run Docker inside the LXC, add `keyctl=1` to the features and pass `INSTALL_MODE=docker`.
- **Neighbors:** a probe in an LXC sees only the devices that container has talked to, not everything the node sees. AdGuard is the main source of the client list, so this rarely matters.
- **Reserved addresses:** give the containers DHCP reservations or static IPs, so the matrix stays readable and peers keep finding each other.
### Mac mini
1. Run the probe command above as your user. It needs the Xcode Command Line Tools (`xcode-select --install`) and Python 3.11+. If Python is missing, it installs `python@3.13` with Homebrew.
2. It installs a LaunchDaemon (`/Library/LaunchDaemons/dev.neilbantoc.network-probe.plist`) that runs as your user from boot, with no login needed.
3. Logs go to `/opt/network-probe/data/service.log`.
4. Keep the Mac awake. In System Settings → Energy, turn on "Prevent automatic sleeping", or the probe stops while the Mac sleeps.
### Optional: a VPS as an internet reference
On the VPS, run `install-probe.sh` with no `HUB_URL` or `PROBE_TOKEN`, and open 8765/tcp in its firewall. Then set `VPS_URL=http://<vps>:8765` in the hub's `.env`. Every probe then tests the VPS too.
### Private repo
If the repo is private, both installers ask for a read-only token. To avoid echoing it or saving it in shell history:
```bash
read -rsp 'Git token: ' GIT_TOKEN && export GIT_TOKEN && curl -fsSL -H "Authorization: Bearer $GIT_TOKEN" https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install-probe.sh | HUB_URL=... PROBE_TOKEN=... bash
```
## Deploy changes
```bash
git push # from your machine
docker exec network-monitor update # hub, Docker
sudo network-monitor-update # hub, native Linux (macOS: network-monitor-update)
docker exec network-probe update # probe, Docker
sudo network-probe-update # probe, native Linux (macOS: network-probe-update)
```
Both forms work the same way, with no rebuild:
- fetch the commit and check it out
- install requirements if they changed
- check that the app imports
- restart the app and wait for `/healthz` to report the new commit
If any step fails, they put the previous commit back. Other forms:
- `--check` shows what an update would bring in.
- `--rollback` returns to the commit before the last update.
- `<ref>` deploys a specific tag, branch or commit.
Re-run the installer when `container/` (Docker) or `native/setup.sh` (native) changes. It keeps `.env`.
## Uninstall
The installer prints the uninstall command at the end. In short:
| Install | Command |
|---|---|
| Docker | `cd /opt/<name> && docker compose -f <compose.yml or compose.probe.yml> down -v`, then `rm -rf /opt/<name>` |
| Native Linux | `systemctl disable --now <name> && rm -rf /opt/<name> /etc/systemd/system/<name>.service /usr/local/bin/<name>-update` |
| macOS | `sudo launchctl bootout system/dev.neilbantoc.<name>; sudo rm -rf /opt/<name> /Library/LaunchDaemons/dev.neilbantoc.<name>.plist /usr/local/bin/<name>-update` |
`<name>` is `network-monitor` (hub) or `network-probe`.
## Settings
The hub's settings live in `/opt/network-monitor/.env`; `.env.example` lists them all. The **Settings** page shows the current values and the exact restart command for this install. Settings are re-read on every restart and update.
| Variable | Default | Meaning |
|---|---|---|
| `ADGUARD_URL`, `ADGUARD_USERNAME`, `ADGUARD_PASSWORD` | empty | AdGuard Home web address and admin login (HTTP basic auth on `/control/*`). |
| `UI_PASSWORD` | empty | Password for the web UI. Any username works. |
| `HOST_BIND`, `HOST_PORT` | `0.0.0.0`, `8000` | Where the hub listens. |
| `PROBE_INTERVAL` | `30` | Seconds between probe reports. |
| `LAN_DNS_SERVERS` | the AdGuard host | DNS servers tested as LAN. |
| `DNS_SERVERS` | `1.1.1.1,8.8.8.8,9.9.9.9` | DNS servers tested as internet. |
| `WAN_HTTP_URLS` | gstatic `generate_204` | Internet HTTP checks. |
| `VPS_URL` | empty | A serve-only probe on a VPS. |
| `THROUGHPUT_EVERY`, `THROUGHPUT_BYTES` | `10`, `4000000` | Timed download from each peer every N reports. `0` turns it off. |
| `SLOW_LAN_MS`, `SLOW_WAN_MS`, `SLOW_DNS_MS` | `100`, `200`, `250` | When a check counts as slow. |
| `RETENTION_DAYS` | `14` | How long measurements are kept. |
| `HUB_PUBLIC_URL` | browser address | The hub URL shown in probe install commands. |
Probe settings live in `/opt/network-probe/.env`; `.env.probe.example` lists them:
| Variable | Meaning |
|---|---|
| `HUB_URL` | The hub to report to. |
| `PROBE_TOKEN` | This probe's token, from the Add probe dialog. |
| `PROBE_PORT` | Port of the probe's test server. Default 8765. |
| `ADVERTISE_ADDR` | The address peers should use for this probe. By default the hub uses the address it sees. |
## How it works
- **One codebase, two roles, two modes.** `app/main.py` picks the app by `ROLE`.
- Docker: `compose.yml` runs the hub and `compose.probe.yml` runs a probe (host networking), both from the same image.
- Native: `native/setup.sh` creates `.venv` and a systemd unit or launchd daemon that runs `native/run.sh`.
- **Probe loop** (`app/probe/server.py`). Each cycle, the probe:
1. runs its checks in parallel: ICMP through unprivileged sockets (`icmplib`), HTTP, a hand-built DNS A query over UDP, and the default gateway from `/proc/net/route`
2. runs the throughput download, one peer at a time
3. posts the results and its ARP neighbors to `/api/probe/report`. On Linux the gateway and neighbors come from `/proc/net`; on macOS from `route` and `arp`.
The hub's reply is the probe's configuration: its peers and targets. The probe caches that reply in `/data`. While the hub is unreachable, results queue in memory, up to 20,000 measurements (hours of data), and upload once the hub is back. Outages are therefore recorded from the probe's side even when the hub can't hear it.
- **Health maths** (`app/hub/health.py`). Each check is OK, slow or failed. Slow means over the threshold, or 30% or more ping loss. A time slice is:
- **down** when at least half its checks failed
- **degraded** when at least a fifth were slow or failed
Failed or slow checks for the same probe and target are merged into one incident when they are less than 2.5 report intervals apart. A single slow sample on its own is ignored.
- **Clients** (`app/hub/devices.py`).
- Every source reports sightings. When an IP becomes linked to a MAC, the IP-only entry is merged into the MAC entry, and your labels carry over.
- An IP moving to a new MAC is released from the old device.
- ARP entries on Docker, VM and VPN interfaces are ignored.
- **AdGuard** (`app/hub/adguard.py`). Detail pages read pages of `/control/querylog` with `search` and `older_than`, and filter exactly on the hub. The status bar says how much of the log a page is based on. Top lists come from `/control/stats`.
## Develop
The host needs only Docker and git.
```bash
docker compose -f compose.yml -f compose.dev.yml up --build # hub at http://127.0.0.1:8000, reloads on save
docker compose -f compose.yml -f compose.dev.yml run --rm app pytest
```
The frontend is plain HTML, CSS and ES modules in `app/static/`, with no build step. It uses the house UI kit (`css/house.css`, `js/ui.js`, `js/shell.js`), project styles in `css/app.css`, and one module per page in `js/views/`. The charts are inline SVG (`js/charts.js`).
```
app/main.py picks the hub or the probe by ROLE
app/hub/ server, probes, health, dns (AdGuard views), devices, adguard client, db
app/probe/ server (test endpoints + report loop), checks
app/static/ the web UI
tests/ pytest (fake AdGuard through httpx.MockTransport)
install.sh the installer (hub); the only one to edit
install-probe.sh generated from install.sh by scripts/build-installers.sh
container/ Docker mode: Dockerfile, entrypoint (setup + supervisor), update script
native/ native mode: setup.sh (venv + service), run.sh, update.sh, lib.sh
```
## Data
- The hub's data is `hub.sqlite3`. Back it up to keep client names and history.
- Docker: in the `network-monitor_data` volume.
- Native: in `/opt/network-monitor/data/`.
- Probes keep only their last config, in `network-probe_data` (Docker) or `/opt/network-probe/data/` (native).