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
3
.dockerignore
Normal file
3
.dockerignore
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
# The image is built from container/ only; the source reaches the container through git.
|
||||||
|
*
|
||||||
|
!container/
|
||||||
57
.env.example
Normal file
57
.env.example
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
# install.sh writes .env from this file on the server (see README).
|
||||||
|
# Gitignored. The container reads it at startup and on every `update`, so edits apply on the
|
||||||
|
# next update or restart; no rebuild. Plain KEY=value lines; quotes optional; not executed.
|
||||||
|
|
||||||
|
# The remote the container pulls the source from, and the branch/tag it follows.
|
||||||
|
REPO_URL=https://git.neilbantoc.dev/services/network-monitor.git
|
||||||
|
REPO_REF=main
|
||||||
|
|
||||||
|
# Private repo over https: a read-only access token (GitHub fine-grained token with
|
||||||
|
# Contents: read, GitLab deploy token, ...). Leave empty for a public repo.
|
||||||
|
GIT_USERNAME=
|
||||||
|
GIT_TOKEN=
|
||||||
|
|
||||||
|
# Or private repo over SSH: an ssh REPO_URL (git@host:owner/repo.git) and a read-only deploy
|
||||||
|
# key, base64-encoded on one line: base64 -w0 deploy_key
|
||||||
|
GIT_SSH_KEY=
|
||||||
|
|
||||||
|
# docker or native (systemd / launchd). Set by the installer; see install.sh.
|
||||||
|
INSTALL_MODE=
|
||||||
|
|
||||||
|
# The port the hub listens on.
|
||||||
|
HOST_PORT=8000
|
||||||
|
|
||||||
|
# App settings go below; the app sees them as environment variables.
|
||||||
|
# Bind address for HOST_PORT. Probes on other machines report here, so the LAN default is
|
||||||
|
# 0.0.0.0. Use 127.0.0.1 if a reverse proxy on this machine fronts the hub.
|
||||||
|
HOST_BIND=0.0.0.0
|
||||||
|
|
||||||
|
# Optional password for the web UI (HTTP basic auth; any username). Probes use their own tokens.
|
||||||
|
UI_PASSWORD=
|
||||||
|
|
||||||
|
# AdGuard Home: its web UI address and an admin login. Leave ADGUARD_URL empty to skip DNS features.
|
||||||
|
ADGUARD_URL=
|
||||||
|
ADGUARD_USERNAME=
|
||||||
|
ADGUARD_PASSWORD=
|
||||||
|
|
||||||
|
# What probes test. Every probe also tests every other probe and its default gateway.
|
||||||
|
PROBE_INTERVAL=30
|
||||||
|
# DNS servers queried as "LAN" (default: the AdGuard host) and as "internet".
|
||||||
|
LAN_DNS_SERVERS=
|
||||||
|
DNS_SERVERS=1.1.1.1,8.8.8.8,9.9.9.9
|
||||||
|
DNS_QUERY_NAME=example.com
|
||||||
|
WAN_HTTP_URLS=http://connectivitycheck.gstatic.com/generate_204
|
||||||
|
# A VPS running a probe in serve-only mode (install-probe.sh with no HUB_URL), e.g. http://vps.example.com:8765
|
||||||
|
VPS_URL=
|
||||||
|
# Timed download between probes: every N reports, N bytes from each peer. 0 turns it off.
|
||||||
|
THROUGHPUT_EVERY=10
|
||||||
|
THROUGHPUT_BYTES=4000000
|
||||||
|
|
||||||
|
# When a check counts as slow (ms), and how long measurements are kept.
|
||||||
|
SLOW_LAN_MS=100
|
||||||
|
SLOW_WAN_MS=200
|
||||||
|
SLOW_DNS_MS=250
|
||||||
|
RETENTION_DAYS=14
|
||||||
|
|
||||||
|
# The hub address shown in probe install commands (default: the address in your browser).
|
||||||
|
HUB_PUBLIC_URL=
|
||||||
27
.env.probe.example
Normal file
27
.env.probe.example
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
# install-probe.sh writes .env from this file on each probe machine (see README).
|
||||||
|
# Gitignored. The container reads it at startup and on every `update`; no rebuild needed.
|
||||||
|
|
||||||
|
# The remote the container pulls the source from, and the branch/tag it follows.
|
||||||
|
REPO_URL=https://git.neilbantoc.dev/services/network-monitor.git
|
||||||
|
REPO_REF=main
|
||||||
|
|
||||||
|
# Private repo over https: a read-only access token. Leave empty for a public repo.
|
||||||
|
GIT_USERNAME=
|
||||||
|
GIT_TOKEN=
|
||||||
|
|
||||||
|
# Or private repo over SSH: an ssh REPO_URL and a base64 deploy key (base64 -w0 deploy_key).
|
||||||
|
GIT_SSH_KEY=
|
||||||
|
|
||||||
|
# docker or native (systemd / launchd). Set by the installer; see install-probe.sh.
|
||||||
|
INSTALL_MODE=
|
||||||
|
|
||||||
|
# The hub this probe reports to, and the token from the hub's "Add probe" dialog.
|
||||||
|
# Leave both empty for a serve-only probe (a VPS the others test against).
|
||||||
|
HUB_URL=
|
||||||
|
PROBE_TOKEN=
|
||||||
|
|
||||||
|
# Port of the probe's test server, on all interfaces (host networking).
|
||||||
|
PROBE_PORT=8765
|
||||||
|
|
||||||
|
# The address other probes should use to reach this one. Empty = what the hub sees.
|
||||||
|
ADVERTISE_ADDR=
|
||||||
10
.gitignore
vendored
Normal file
10
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
.env
|
||||||
|
deploy_key*
|
||||||
|
__pycache__/
|
||||||
|
.venv/
|
||||||
|
.pytest_cache/
|
||||||
|
data/
|
||||||
|
.native
|
||||||
|
.native-update.sh
|
||||||
|
.native-update.sh.new
|
||||||
|
.native-state/
|
||||||
127
CLAUDE.md
Normal file
127
CLAUDE.md
Normal file
|
|
@ -0,0 +1,127 @@
|
||||||
|
# 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)
|
||||||
252
README.md
Normal file
252
README.md
Normal file
|
|
@ -0,0 +1,252 @@
|
||||||
|
# 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).
|
||||||
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/hub/__init__.py
Normal file
0
app/hub/__init__.py
Normal file
149
app/hub/adguard.py
Normal file
149
app/hub/adguard.py
Normal file
|
|
@ -0,0 +1,149 @@
|
||||||
|
"""AdGuard Home API client (/control/*, HTTP basic auth) and query log helpers."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.hub import settings
|
||||||
|
|
||||||
|
# Tests swap this for an httpx.MockTransport.
|
||||||
|
TRANSPORT: httpx.AsyncBaseTransport | None = None
|
||||||
|
|
||||||
|
BLOCKED_REASONS = {"FilteredBlackList", "FilteredBlockedService", "FilteredParental", "FilteredSafeBrowsing", "FilteredInvalid"}
|
||||||
|
PAGE = 500
|
||||||
|
|
||||||
|
|
||||||
|
class NotConfigured(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class AdGuardError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _client() -> httpx.AsyncClient:
|
||||||
|
s = settings.get()
|
||||||
|
if not s.adguard_configured:
|
||||||
|
raise NotConfigured("Set ADGUARD_URL (and ADGUARD_USERNAME / ADGUARD_PASSWORD) in the hub's .env")
|
||||||
|
auth = (s.adguard_username, s.adguard_password) if s.adguard_username else None
|
||||||
|
return httpx.AsyncClient(base_url=s.adguard_url, auth=auth, timeout=15, transport=TRANSPORT)
|
||||||
|
|
||||||
|
|
||||||
|
async def get(path: str, params: dict | None = None):
|
||||||
|
try:
|
||||||
|
async with _client() as c:
|
||||||
|
r = await c.get(path, params=params)
|
||||||
|
except httpx.HTTPError as e:
|
||||||
|
raise AdGuardError(f"AdGuard Home unreachable: {e.__class__.__name__}: {e}") from e
|
||||||
|
if r.status_code in (401, 403):
|
||||||
|
raise AdGuardError("AdGuard Home rejected the login. Check ADGUARD_USERNAME and ADGUARD_PASSWORD.")
|
||||||
|
if r.status_code >= 400:
|
||||||
|
raise AdGuardError(f"AdGuard Home returned {r.status_code} for {path}")
|
||||||
|
try:
|
||||||
|
return r.json()
|
||||||
|
except ValueError as e:
|
||||||
|
raise AdGuardError(f"AdGuard Home sent a non-JSON reply for {path}. Is ADGUARD_URL the web UI address?") from e
|
||||||
|
|
||||||
|
|
||||||
|
_FRAC = re.compile(r"(\.\d{6})\d+")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_time(value: str) -> float:
|
||||||
|
try:
|
||||||
|
return datetime.fromisoformat(_FRAC.sub(r"\1", value.replace("Z", "+00:00"))).timestamp()
|
||||||
|
except (ValueError, AttributeError):
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def normalize(row: dict) -> dict:
|
||||||
|
q = row.get("question") or {}
|
||||||
|
info = row.get("client_info") or {}
|
||||||
|
rules = row.get("rules") or []
|
||||||
|
reason = row.get("reason", "")
|
||||||
|
try:
|
||||||
|
elapsed = round(float(row.get("elapsedMs") or 0), 2)
|
||||||
|
except ValueError:
|
||||||
|
elapsed = None
|
||||||
|
return {
|
||||||
|
"time": row.get("time", ""),
|
||||||
|
"ts": parse_time(row.get("time", "")),
|
||||||
|
"client": row.get("client", ""),
|
||||||
|
"client_name": info.get("name") or "",
|
||||||
|
"domain": (q.get("name") or q.get("host") or "").rstrip(".").lower(),
|
||||||
|
"type": q.get("type", ""),
|
||||||
|
"status": row.get("status", ""),
|
||||||
|
"reason": reason,
|
||||||
|
"blocked": reason in BLOCKED_REASONS,
|
||||||
|
"rule": (rules[0].get("text") if rules else row.get("rule")) or "",
|
||||||
|
"elapsed_ms": elapsed,
|
||||||
|
"upstream": row.get("upstream", ""),
|
||||||
|
"cached": bool(row.get("cached")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def collect(*, search: str = "", status: str = "all", older_than: str = "", want: int = 200,
|
||||||
|
keep=None, max_rows: int = 5000) -> dict:
|
||||||
|
"""Page through the query log, newest first, until `want` rows pass `keep` or `max_rows`
|
||||||
|
have been read. Returns {rows, oldest, done}: pass `oldest` back as older_than for more."""
|
||||||
|
rows, scanned, done = [], 0, False
|
||||||
|
cursor = older_than
|
||||||
|
while len(rows) < want and scanned < max_rows:
|
||||||
|
params = {"limit": PAGE, "response_status": status}
|
||||||
|
if search:
|
||||||
|
params["search"] = search
|
||||||
|
if cursor:
|
||||||
|
params["older_than"] = cursor
|
||||||
|
data = await get("/control/querylog", params)
|
||||||
|
page = data.get("data") or []
|
||||||
|
scanned += len(page)
|
||||||
|
for raw in page:
|
||||||
|
r = normalize(raw)
|
||||||
|
if keep is None or keep(r):
|
||||||
|
rows.append(r)
|
||||||
|
if len(rows) >= want:
|
||||||
|
cursor = raw.get("time", cursor)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
cursor = data.get("oldest") or (page[-1].get("time") if page else "")
|
||||||
|
if len(page) < PAGE or not cursor:
|
||||||
|
done = True
|
||||||
|
break
|
||||||
|
return {"rows": rows, "oldest": "" if done else cursor, "done": done, "scanned": scanned}
|
||||||
|
|
||||||
|
|
||||||
|
def top_list(items) -> list[tuple[str, int]]:
|
||||||
|
"""AdGuard returns top lists as [{"name": count}, ...]."""
|
||||||
|
out = []
|
||||||
|
for it in items or []:
|
||||||
|
if isinstance(it, dict):
|
||||||
|
out.extend((str(k), int(v)) for k, v in it.items())
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
_stats_cache: dict = {"at": 0.0, "data": None}
|
||||||
|
|
||||||
|
|
||||||
|
async def stats(max_age: float = 60) -> dict:
|
||||||
|
if _stats_cache["data"] is not None and time.time() - _stats_cache["at"] < max_age:
|
||||||
|
return _stats_cache["data"]
|
||||||
|
data = await get("/control/stats")
|
||||||
|
_stats_cache.update(at=time.time(), data=data)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
MULTI_PART_SUFFIXES = {
|
||||||
|
"co.uk", "org.uk", "ac.uk", "gov.uk", "me.uk", "com.au", "net.au", "org.au", "co.nz", "co.jp", "ne.jp",
|
||||||
|
"com.br", "com.cn", "com.mx", "co.in", "co.za", "com.tr", "com.sg", "com.ph", "com.hk", "com.tw", "co.kr",
|
||||||
|
"com.ar", "com.my", "co.id", "com.vn", "com.pk", "com.ng", "com.eg", "com.sa", "co.il", "com.ua",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def base_domain(name: str) -> str:
|
||||||
|
"""Registrable domain, approximately (no full public suffix list): a.b.example.co.uk -> example.co.uk."""
|
||||||
|
labels = name.lower().rstrip(".").split(".")
|
||||||
|
if len(labels) <= 2 or all(x.isdigit() for x in labels):
|
||||||
|
return ".".join(labels)
|
||||||
|
n = 3 if ".".join(labels[-2:]) in MULTI_PART_SUFFIXES else 2
|
||||||
|
return ".".join(labels[-n:])
|
||||||
86
app/hub/db.py
Normal file
86
app/hub/db.py
Normal file
|
|
@ -0,0 +1,86 @@
|
||||||
|
"""SQLite storage under $DATA_DIR. One short-lived connection per unit of work."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
SCHEMA = """
|
||||||
|
CREATE TABLE IF NOT EXISTS probes (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
token TEXT NOT NULL UNIQUE,
|
||||||
|
address TEXT, -- set by the hub from the report, or ADVERTISE_ADDR, or by hand
|
||||||
|
address_locked INTEGER NOT NULL DEFAULT 0,
|
||||||
|
port INTEGER,
|
||||||
|
hostname TEXT,
|
||||||
|
version TEXT,
|
||||||
|
icmp INTEGER, -- 1/0: whether ICMP works on that probe
|
||||||
|
created REAL NOT NULL,
|
||||||
|
last_seen REAL,
|
||||||
|
last_error TEXT
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS measurements (
|
||||||
|
ts REAL NOT NULL,
|
||||||
|
probe_id INTEGER NOT NULL,
|
||||||
|
target TEXT NOT NULL, -- probe:<id>, gateway, dns:<ip>, vps, web:<url>
|
||||||
|
label TEXT,
|
||||||
|
kind TEXT NOT NULL, -- lan | wan
|
||||||
|
method TEXT NOT NULL, -- icmp | http | dns | throughput
|
||||||
|
ok INTEGER NOT NULL,
|
||||||
|
latency REAL, -- ms
|
||||||
|
loss REAL, -- 0..1 (icmp)
|
||||||
|
mbps REAL, -- throughput
|
||||||
|
error TEXT
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS m_ts ON measurements(ts);
|
||||||
|
CREATE INDEX IF NOT EXISTS m_series ON measurements(probe_id, target, method, ts);
|
||||||
|
CREATE TABLE IF NOT EXISTS devices (
|
||||||
|
key TEXT PRIMARY KEY, -- MAC when known, else ip:<address>
|
||||||
|
mac TEXT,
|
||||||
|
ip TEXT,
|
||||||
|
hostname TEXT,
|
||||||
|
sources TEXT NOT NULL DEFAULT '',
|
||||||
|
first_seen REAL NOT NULL,
|
||||||
|
last_seen REAL, -- last activity (DNS query or ARP); NULL = only listed somewhere
|
||||||
|
name TEXT,
|
||||||
|
category TEXT,
|
||||||
|
suspicious INTEGER NOT NULL DEFAULT 0,
|
||||||
|
notes TEXT
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS d_ip ON devices(ip);
|
||||||
|
CREATE TABLE IF NOT EXISTS ip_mac (
|
||||||
|
ip TEXT PRIMARY KEY,
|
||||||
|
mac TEXT NOT NULL,
|
||||||
|
last_seen REAL NOT NULL
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def path() -> Path:
|
||||||
|
return Path(os.environ.get("DATA_DIR", "data")) / "hub.sqlite3"
|
||||||
|
|
||||||
|
|
||||||
|
def connect() -> sqlite3.Connection:
|
||||||
|
con = sqlite3.connect(path(), timeout=15)
|
||||||
|
con.row_factory = sqlite3.Row
|
||||||
|
con.execute("PRAGMA journal_mode=WAL")
|
||||||
|
con.execute("PRAGMA synchronous=NORMAL")
|
||||||
|
return con
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def db():
|
||||||
|
"""A connection whose work commits on success and rolls back on error."""
|
||||||
|
con = connect()
|
||||||
|
try:
|
||||||
|
with con:
|
||||||
|
yield con
|
||||||
|
finally:
|
||||||
|
con.close()
|
||||||
|
|
||||||
|
|
||||||
|
def init() -> None:
|
||||||
|
path().parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with db() as con:
|
||||||
|
con.executescript(SCHEMA)
|
||||||
96
app/hub/devices.py
Normal file
96
app/hub/devices.py
Normal file
|
|
@ -0,0 +1,96 @@
|
||||||
|
"""Client devices: merged from AdGuard (clients, DHCP leases, query log) and probe ARP tables.
|
||||||
|
A device is keyed by MAC address when one is known, else by IP (ip:<address>)."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
|
MAC_RE = re.compile(r"^[0-9a-f]{2}(:[0-9a-f]{2}){5}$")
|
||||||
|
USER_FIELDS = ("name", "category", "suspicious", "notes")
|
||||||
|
|
||||||
|
|
||||||
|
def norm_mac(mac: str | None) -> str | None:
|
||||||
|
if not mac:
|
||||||
|
return None
|
||||||
|
m = mac.strip().lower().replace("-", ":")
|
||||||
|
if not MAC_RE.match(m) or m == "00:00:00:00:00:00":
|
||||||
|
return None
|
||||||
|
return m
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_into(con, src_key: str, dst_key: str) -> None:
|
||||||
|
"""Fold the IP-keyed device into the MAC-keyed one, keeping the user's labels."""
|
||||||
|
src = con.execute("SELECT * FROM devices WHERE key = ?", (src_key,)).fetchone()
|
||||||
|
dst = con.execute("SELECT * FROM devices WHERE key = ?", (dst_key,)).fetchone()
|
||||||
|
if not src or not dst:
|
||||||
|
return
|
||||||
|
updates = {f: src[f] for f in USER_FIELDS if src[f] and not dst[f]}
|
||||||
|
sources = ",".join(sorted(set(filter(None, (dst["sources"] + "," + src["sources"]).split(",")))))
|
||||||
|
updates["sources"] = sources
|
||||||
|
updates["first_seen"] = min(src["first_seen"], dst["first_seen"])
|
||||||
|
if src["last_seen"] and (not dst["last_seen"] or src["last_seen"] > dst["last_seen"]):
|
||||||
|
updates["last_seen"] = src["last_seen"]
|
||||||
|
if not dst["hostname"] and src["hostname"]:
|
||||||
|
updates["hostname"] = src["hostname"]
|
||||||
|
sets = ", ".join(f"{k} = ?" for k in updates)
|
||||||
|
con.execute(f"UPDATE devices SET {sets} WHERE key = ?", (*updates.values(), dst_key))
|
||||||
|
con.execute("DELETE FROM devices WHERE key = ?", (src_key,))
|
||||||
|
|
||||||
|
|
||||||
|
def sighting(con, *, ip: str | None = None, mac: str | None = None, hostname: str | None = None,
|
||||||
|
source: str, seen: float | None = None, now: float | None = None) -> str | None:
|
||||||
|
"""Record that a device exists. `seen` is a time of real activity; None means it was only listed."""
|
||||||
|
now = now or time.time()
|
||||||
|
ip = (ip or "").strip() or None
|
||||||
|
mac = norm_mac(mac)
|
||||||
|
if not ip and not mac:
|
||||||
|
return None
|
||||||
|
if ip and mac:
|
||||||
|
prev = con.execute("SELECT mac FROM ip_mac WHERE ip = ?", (ip,)).fetchone()
|
||||||
|
con.execute("INSERT INTO ip_mac(ip, mac, last_seen) VALUES (?, ?, ?) ON CONFLICT(ip) DO UPDATE SET mac = excluded.mac, last_seen = excluded.last_seen",
|
||||||
|
(ip, mac, now))
|
||||||
|
if not prev or prev["mac"] != mac:
|
||||||
|
# The address moved to this device: other devices no longer hold it.
|
||||||
|
con.execute("UPDATE devices SET ip = NULL WHERE ip = ? AND key != ?", (ip, mac))
|
||||||
|
elif ip:
|
||||||
|
row = con.execute("SELECT mac FROM ip_mac WHERE ip = ?", (ip,)).fetchone()
|
||||||
|
mac = row["mac"] if row else None
|
||||||
|
key = mac or f"ip:{ip}"
|
||||||
|
exists = con.execute("SELECT key FROM devices WHERE key = ?", (key,)).fetchone()
|
||||||
|
if not exists:
|
||||||
|
con.execute("INSERT INTO devices(key, mac, ip, hostname, sources, first_seen, last_seen) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
(key, mac, ip, hostname or None, source, seen or now, seen))
|
||||||
|
else:
|
||||||
|
con.execute(
|
||||||
|
"""UPDATE devices SET
|
||||||
|
ip = COALESCE(?, ip),
|
||||||
|
hostname = COALESCE(NULLIF(?, ''), hostname),
|
||||||
|
sources = CASE WHEN (',' || sources || ',') LIKE ? THEN sources
|
||||||
|
WHEN sources = '' THEN ? ELSE sources || ',' || ? END,
|
||||||
|
last_seen = CASE WHEN ? IS NOT NULL AND (last_seen IS NULL OR ? > last_seen) THEN ? ELSE last_seen END
|
||||||
|
WHERE key = ?""",
|
||||||
|
(ip, hostname or "", f"%,{source},%", source, source, seen, seen, seen, key),
|
||||||
|
)
|
||||||
|
if mac and ip:
|
||||||
|
_merge_into(con, f"ip:{ip}", mac)
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
def ip_index(con) -> dict[str, dict]:
|
||||||
|
"""ip -> {key, name, suspicious} for linking query log rows to devices."""
|
||||||
|
out = {}
|
||||||
|
for r in con.execute("SELECT key, ip, name, hostname, suspicious, category FROM devices WHERE ip IS NOT NULL"):
|
||||||
|
out[r["ip"]] = {"key": r["key"], "name": r["name"] or r["hostname"] or "", "suspicious": bool(r["suspicious"]), "category": r["category"] or ""}
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def ips_for(con, key: str) -> list[str]:
|
||||||
|
"""Addresses to search the query log for: the current one plus others recently tied to its MAC."""
|
||||||
|
row = con.execute("SELECT mac, ip FROM devices WHERE key = ?", (key,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return []
|
||||||
|
ips = [row["ip"]] if row["ip"] else []
|
||||||
|
if row["mac"]:
|
||||||
|
ips += [r["ip"] for r in con.execute("SELECT ip FROM ip_mac WHERE mac = ? ORDER BY last_seen DESC LIMIT 4", (row["mac"],)) if r["ip"] not in ips]
|
||||||
|
if not ips and key.startswith("ip:"):
|
||||||
|
ips = [key[3:]]
|
||||||
|
return ips
|
||||||
319
app/hub/dns.py
Normal file
319
app/hub/dns.py
Normal file
|
|
@ -0,0 +1,319 @@
|
||||||
|
"""Clients, DNS query log, domain detail and blocked domains, all backed by AdGuard Home."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from collections import Counter, defaultdict
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from app.hub import adguard, devices, settings
|
||||||
|
from app.hub.db import db
|
||||||
|
|
||||||
|
log = logging.getLogger("hub.dns")
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
CATEGORIES = ["Computer", "Mobile", "Tablet", "IoT", "Server", "Network", "Media", "Gaming", "Other"]
|
||||||
|
ONLINE_SECONDS = 600
|
||||||
|
|
||||||
|
|
||||||
|
def _decorate(rows: list[dict], index: dict) -> list[dict]:
|
||||||
|
for r in rows:
|
||||||
|
d = index.get(r["client"])
|
||||||
|
r["device"] = d
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- status
|
||||||
|
|
||||||
|
@router.get("/dns/status")
|
||||||
|
async def dns_status() -> dict:
|
||||||
|
s = settings.get()
|
||||||
|
if not s.adguard_configured:
|
||||||
|
return {"configured": False, "ok": False, "message": "Set ADGUARD_URL in the hub's .env to see clients and DNS queries."}
|
||||||
|
try:
|
||||||
|
st = await adguard.get("/control/status")
|
||||||
|
except adguard.AdGuardError as e:
|
||||||
|
return {"configured": True, "ok": False, "url": s.adguard_url, "message": str(e)}
|
||||||
|
return {"configured": True, "ok": True, "url": s.adguard_url, "version": st.get("version", ""),
|
||||||
|
"protection_enabled": st.get("protection_enabled"), "running": st.get("running")}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- clients
|
||||||
|
|
||||||
|
class DeviceMeta(BaseModel):
|
||||||
|
name: str | None = Field(default=None, max_length=80)
|
||||||
|
category: str | None = Field(default=None, max_length=40)
|
||||||
|
suspicious: bool | None = None
|
||||||
|
notes: str | None = Field(default=None, max_length=2000)
|
||||||
|
|
||||||
|
|
||||||
|
def device_out(r, counts: dict | None = None, now: float | None = None, epoch: float | None = None) -> dict:
|
||||||
|
"""epoch: when the hub first saw any device. Devices from that first day aren't "new"."""
|
||||||
|
now = now or time.time()
|
||||||
|
return {
|
||||||
|
"key": r["key"], "mac": r["mac"], "ip": r["ip"], "hostname": r["hostname"] or "",
|
||||||
|
"name": r["name"] or "", "display": r["name"] or r["hostname"] or r["ip"] or r["mac"],
|
||||||
|
"category": r["category"] or "", "suspicious": bool(r["suspicious"]), "notes": r["notes"] or "",
|
||||||
|
"sources": [x for x in r["sources"].split(",") if x], "first_seen": r["first_seen"], "last_seen": r["last_seen"],
|
||||||
|
"online": bool(r["last_seen"]) and now - r["last_seen"] < ONLINE_SECONDS,
|
||||||
|
"new": now - r["first_seen"] < 86400 and (epoch is None or r["first_seen"] - epoch > 86400),
|
||||||
|
"queries": (counts or {}).get(r["ip"]) if r["ip"] else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def _client_counts() -> dict:
|
||||||
|
if not settings.get().adguard_configured:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
return dict(adguard.top_list((await adguard.stats()).get("top_clients")))
|
||||||
|
except adguard.AdGuardError:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/clients")
|
||||||
|
async def list_clients() -> dict:
|
||||||
|
counts = await _client_counts()
|
||||||
|
with db() as con:
|
||||||
|
rows = con.execute("SELECT * FROM devices ORDER BY COALESCE(name, hostname, ip, mac) COLLATE NOCASE").fetchall()
|
||||||
|
epoch = min((r["first_seen"] for r in rows), default=None)
|
||||||
|
return {"clients": [device_out(r, counts, epoch=epoch) for r in rows], "categories": CATEGORIES,
|
||||||
|
"adguard": settings.get().adguard_configured}
|
||||||
|
|
||||||
|
|
||||||
|
def _device(con, key: str):
|
||||||
|
row = con.execute("SELECT * FROM devices WHERE key = ?", (key,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, "No client with that id")
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/clients/{key}")
|
||||||
|
async def get_client(key: str) -> dict:
|
||||||
|
counts = await _client_counts()
|
||||||
|
with db() as con:
|
||||||
|
row = _device(con, key)
|
||||||
|
ips = devices.ips_for(con, key)
|
||||||
|
out = device_out(row, counts)
|
||||||
|
out["ips"] = ips
|
||||||
|
out["categories"] = CATEGORIES
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/clients/{key}")
|
||||||
|
def update_client(key: str, body: DeviceMeta) -> dict:
|
||||||
|
with db() as con:
|
||||||
|
_device(con, key)
|
||||||
|
fields = body.model_dump(exclude_unset=True)
|
||||||
|
if "suspicious" in fields:
|
||||||
|
fields["suspicious"] = int(bool(fields["suspicious"]))
|
||||||
|
for k in ("name", "category", "notes"):
|
||||||
|
if k in fields:
|
||||||
|
fields[k] = (fields[k] or "").strip() or None
|
||||||
|
if fields:
|
||||||
|
con.execute(f"UPDATE devices SET {', '.join(f'{k} = ?' for k in fields)} WHERE key = ?", (*fields.values(), key))
|
||||||
|
return device_out(_device(con, key))
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/clients/{key}", status_code=204)
|
||||||
|
def forget_client(key: str) -> None:
|
||||||
|
with db() as con:
|
||||||
|
_device(con, key)
|
||||||
|
con.execute("DELETE FROM devices WHERE key = ?", (key,))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/clients/{key}/summary")
|
||||||
|
async def client_summary(key: str, sample: int = Query(1000, ge=50, le=5000)) -> dict:
|
||||||
|
with db() as con:
|
||||||
|
_device(con, key)
|
||||||
|
ips = devices.ips_for(con, key)
|
||||||
|
if not ips:
|
||||||
|
return {"ips": [], "sample": 0, "top": [], "blocked_top": [], "blocked": 0, "since": None}
|
||||||
|
wanted = set(ips)
|
||||||
|
res = await adguard.collect(search=ips[0] if len(ips) == 1 else "", want=sample, keep=lambda r: r["client"] in wanted, max_rows=sample * 5)
|
||||||
|
rows = res["rows"]
|
||||||
|
top = Counter(r["domain"] for r in rows)
|
||||||
|
blocked = Counter(r["domain"] for r in rows if r["blocked"])
|
||||||
|
return {
|
||||||
|
"ips": ips, "sample": len(rows), "blocked": sum(blocked.values()),
|
||||||
|
"since": min((r["ts"] for r in rows), default=None),
|
||||||
|
"top": [{"domain": d, "count": c, "blocked": blocked.get(d, 0)} for d, c in top.most_common(25)],
|
||||||
|
"blocked_top": [{"domain": d, "count": c} for d, c in blocked.most_common(10)],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- query log
|
||||||
|
|
||||||
|
@router.get("/dns/queries")
|
||||||
|
async def queries(search: str = "", status: str = Query("all", pattern="^(all|blocked|allowed)$"),
|
||||||
|
client: str = "", ip: str = "", domain: str = "", older_than: str = "",
|
||||||
|
limit: int = Query(100, ge=1, le=500)) -> dict:
|
||||||
|
"""The AdGuard query log, newest first. `client` is a client id, `ip` a comma list of exact addresses."""
|
||||||
|
with db() as con:
|
||||||
|
ips = {x.strip() for x in ip.split(",") if x.strip()}
|
||||||
|
if client:
|
||||||
|
ips.update(devices.ips_for(con, client) or ["-"])
|
||||||
|
index = devices.ip_index(con)
|
||||||
|
domain = domain.strip().lower()
|
||||||
|
|
||||||
|
def keep(r):
|
||||||
|
if ips and r["client"] not in ips:
|
||||||
|
return False
|
||||||
|
if domain and r["domain"] != domain:
|
||||||
|
return False
|
||||||
|
if status == "allowed" and r["blocked"]:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
ag_search = search.strip() or domain or (next(iter(ips)) if len(ips) == 1 else "")
|
||||||
|
res = await adguard.collect(search=ag_search, status="blocked" if status == "blocked" else "all",
|
||||||
|
older_than=older_than, want=limit, keep=keep, max_rows=limit * 20)
|
||||||
|
res["rows"] = _decorate(res["rows"], index)
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- domains
|
||||||
|
|
||||||
|
@router.get("/domains")
|
||||||
|
async def top_domains() -> dict:
|
||||||
|
st = await adguard.stats()
|
||||||
|
return {
|
||||||
|
"top_queried": [{"domain": d, "count": c} for d, c in adguard.top_list(st.get("top_queried_domains"))],
|
||||||
|
"top_blocked": [{"domain": d, "count": c} for d, c in adguard.top_list(st.get("top_blocked_domains"))],
|
||||||
|
"num_queries": st.get("num_dns_queries"), "num_blocked": st.get("num_blocked_filtering"),
|
||||||
|
"time_units": st.get("time_units"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/domains/{name}")
|
||||||
|
async def domain_detail(name: str, sample: int = Query(3000, ge=100, le=10000)) -> dict:
|
||||||
|
name = name.strip().rstrip(".").lower()
|
||||||
|
if not name or len(name) > 253:
|
||||||
|
raise HTTPException(400, "Give a domain name, like example.com")
|
||||||
|
base = adguard.base_domain(name)
|
||||||
|
res = await adguard.collect(search=base, want=sample, max_rows=sample,
|
||||||
|
keep=lambda r: r["domain"] == base or r["domain"].endswith("." + base))
|
||||||
|
rows = res["rows"]
|
||||||
|
exact = [r for r in rows if r["domain"] == name]
|
||||||
|
with db() as con:
|
||||||
|
index = devices.ip_index(con)
|
||||||
|
|
||||||
|
clients = defaultdict(lambda: {"count": 0, "blocked": 0, "last": 0.0, "name": ""})
|
||||||
|
for r in exact:
|
||||||
|
c = clients[r["client"]]
|
||||||
|
c["count"] += 1
|
||||||
|
c["blocked"] += r["blocked"]
|
||||||
|
c["last"] = max(c["last"], r["ts"])
|
||||||
|
c["name"] = c["name"] or r["client_name"]
|
||||||
|
related = Counter(r["domain"] for r in rows if r["domain"] != name)
|
||||||
|
related_blocked = Counter(r["domain"] for r in rows if r["domain"] != name and r["blocked"])
|
||||||
|
|
||||||
|
now = time.time()
|
||||||
|
hours = [0] * 24
|
||||||
|
blocked_hours = [0] * 24
|
||||||
|
for r in exact:
|
||||||
|
age = int((now - r["ts"]) // 3600)
|
||||||
|
if 0 <= age < 24:
|
||||||
|
hours[23 - age] += 1
|
||||||
|
blocked_hours[23 - age] += r["blocked"]
|
||||||
|
lat = [r["elapsed_ms"] for r in exact if r["elapsed_ms"] is not None]
|
||||||
|
|
||||||
|
st = {}
|
||||||
|
try:
|
||||||
|
st = await adguard.stats()
|
||||||
|
except adguard.AdGuardError:
|
||||||
|
pass
|
||||||
|
stats_count = dict(adguard.top_list(st.get("top_queried_domains"))).get(name)
|
||||||
|
stats_blocked = dict(adguard.top_list(st.get("top_blocked_domains"))).get(name)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"domain": name, "base": base, "sample_rows": len(rows), "scanned": res["scanned"], "complete": res["done"],
|
||||||
|
"since": min((r["ts"] for r in rows), default=None),
|
||||||
|
"count": len(exact), "blocked": sum(r["blocked"] for r in exact),
|
||||||
|
"first": min((r["ts"] for r in exact), default=None), "last": max((r["ts"] for r in exact), default=None),
|
||||||
|
"avg_ms": round(sum(lat) / len(lat), 2) if lat else None,
|
||||||
|
"types": Counter(r["type"] for r in exact).most_common(),
|
||||||
|
"reasons": Counter(r["reason"] for r in exact).most_common(),
|
||||||
|
"rules": Counter(r["rule"] for r in exact if r["rule"]).most_common(5),
|
||||||
|
"stats_count": stats_count, "stats_blocked": stats_blocked,
|
||||||
|
"hours": hours, "blocked_hours": blocked_hours,
|
||||||
|
"clients": sorted(({"ip": ip, **v, "device": index.get(ip)} for ip, v in clients.items()), key=lambda x: -x["count"]),
|
||||||
|
"related": [{"domain": d, "count": c, "blocked": related_blocked.get(d, 0)} for d, c in related.most_common(50)],
|
||||||
|
"recent": _decorate(exact[:50], index),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/dns/blocked")
|
||||||
|
async def blocked(sample: int = Query(1000, ge=50, le=5000)) -> dict:
|
||||||
|
st = await adguard.stats()
|
||||||
|
res = await adguard.collect(status="blocked", want=sample, max_rows=sample, keep=lambda r: r["blocked"])
|
||||||
|
with db() as con:
|
||||||
|
index = devices.ip_index(con)
|
||||||
|
agg = defaultdict(lambda: {"count": 0, "clients": set(), "last": 0.0, "rule": "", "reason": ""})
|
||||||
|
for r in res["rows"]:
|
||||||
|
a = agg[r["domain"]]
|
||||||
|
a["count"] += 1
|
||||||
|
a["clients"].add(r["client"])
|
||||||
|
a["last"] = max(a["last"], r["ts"])
|
||||||
|
a["rule"] = a["rule"] or r["rule"]
|
||||||
|
a["reason"] = a["reason"] or r["reason"]
|
||||||
|
recent = [
|
||||||
|
{"domain": d, "count": a["count"], "last": a["last"], "rule": a["rule"], "reason": a["reason"],
|
||||||
|
"clients": [{"ip": ip, "device": index.get(ip)} for ip in sorted(a["clients"])]}
|
||||||
|
for d, a in sorted(agg.items(), key=lambda kv: -kv[1]["count"])
|
||||||
|
]
|
||||||
|
return {
|
||||||
|
"top": [{"domain": d, "count": c} for d, c in adguard.top_list(st.get("top_blocked_domains"))],
|
||||||
|
"num_blocked": st.get("num_blocked_filtering"), "num_queries": st.get("num_dns_queries"),
|
||||||
|
"recent": recent, "sample": len(res["rows"]), "since": min((r["ts"] for r in res["rows"]), default=None),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- discovery (background)
|
||||||
|
|
||||||
|
async def discover_once() -> int:
|
||||||
|
"""Pull client lists, DHCP leases and recent queries from AdGuard into the device table."""
|
||||||
|
if not settings.get().adguard_configured:
|
||||||
|
return 0
|
||||||
|
found: list[dict] = []
|
||||||
|
clients = await adguard.get("/control/clients")
|
||||||
|
for c in clients.get("clients") or []:
|
||||||
|
ids = c.get("ids") or []
|
||||||
|
macs = [i for i in ids if devices.norm_mac(i)]
|
||||||
|
ips = [i for i in ids if i.replace(".", "").isdigit() or (":" in i and not devices.norm_mac(i) and "/" not in i)]
|
||||||
|
for ip in ips or [None]:
|
||||||
|
found.append({"ip": ip, "mac": macs[0] if macs else None, "hostname": c.get("name"), "source": "adguard"})
|
||||||
|
for c in clients.get("auto_clients") or []:
|
||||||
|
found.append({"ip": c.get("ip"), "hostname": c.get("name"), "source": f"adguard-{(c.get('source') or 'auto').lower()}"})
|
||||||
|
try:
|
||||||
|
dhcp = await adguard.get("/control/dhcp/status")
|
||||||
|
for lease in (dhcp.get("leases") or []) + (dhcp.get("static_leases") or []):
|
||||||
|
found.append({"ip": lease.get("ip"), "mac": lease.get("mac"), "hostname": lease.get("hostname"), "source": "dhcp"})
|
||||||
|
except adguard.AdGuardError:
|
||||||
|
pass # DHCP not in use
|
||||||
|
recent = await adguard.collect(want=adguard.PAGE, max_rows=adguard.PAGE)
|
||||||
|
last: dict[str, tuple[float, str]] = {}
|
||||||
|
for r in recent["rows"]:
|
||||||
|
if r["client"] and r["ts"] > last.get(r["client"], (0, ""))[0]:
|
||||||
|
last[r["client"]] = (r["ts"], r["client_name"])
|
||||||
|
|
||||||
|
def write():
|
||||||
|
with db() as con:
|
||||||
|
for f in found:
|
||||||
|
devices.sighting(con, ip=f["ip"], mac=f.get("mac"), hostname=f.get("hostname"), source=f["source"])
|
||||||
|
for ip, (ts, name) in last.items():
|
||||||
|
devices.sighting(con, ip=ip, hostname=name or None, source="dns", seen=ts)
|
||||||
|
await asyncio.to_thread(write)
|
||||||
|
return len(found) + len(last)
|
||||||
|
|
||||||
|
|
||||||
|
async def discovery_loop(every: float = 60) -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await discover_once()
|
||||||
|
except (adguard.AdGuardError, adguard.NotConfigured) as e:
|
||||||
|
log.warning("client discovery: %s", e)
|
||||||
|
except Exception:
|
||||||
|
log.exception("client discovery failed")
|
||||||
|
await asyncio.sleep(every)
|
||||||
215
app/hub/health.py
Normal file
215
app/hub/health.py
Normal file
|
|
@ -0,0 +1,215 @@
|
||||||
|
"""Network health from probe measurements: the live matrix, status strips, incidents, series."""
|
||||||
|
|
||||||
|
import time
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
|
||||||
|
from app.hub import settings
|
||||||
|
from app.hub.db import db
|
||||||
|
from app.hub.probes import is_online
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
RANGES = {"1h": (3600, 60), "6h": (6 * 3600, 72), "24h": (86400, 96), "7d": (7 * 86400, 84), "30d": (30 * 86400, 90)}
|
||||||
|
|
||||||
|
|
||||||
|
def _sev_sql() -> tuple[str, dict]:
|
||||||
|
"""Severity per measurement: 2 = failed, 1 = slow or lossy, 0 = fine."""
|
||||||
|
s = settings.get()
|
||||||
|
sql = """CASE WHEN ok = 0 THEN 2
|
||||||
|
WHEN (loss IS NOT NULL AND loss >= 0.3)
|
||||||
|
OR latency > (CASE WHEN method = 'dns' THEN :slow_dns WHEN kind = 'lan' THEN :slow_lan ELSE :slow_wan END) THEN 1
|
||||||
|
ELSE 0 END"""
|
||||||
|
return sql, {"slow_dns": s.slow_dns_ms, "slow_lan": s.slow_lan_ms, "slow_wan": s.slow_wan_ms}
|
||||||
|
|
||||||
|
|
||||||
|
def bucket_status(n: int, down: int, slow: int) -> str:
|
||||||
|
if not n:
|
||||||
|
return "nodata"
|
||||||
|
if down * 2 >= n:
|
||||||
|
return "down"
|
||||||
|
if (down + slow) * 5 >= n:
|
||||||
|
return "degraded"
|
||||||
|
return "ok"
|
||||||
|
|
||||||
|
|
||||||
|
RANK = {"nodata": 0, "ok": 1, "degraded": 2, "down": 3}
|
||||||
|
|
||||||
|
|
||||||
|
def _range(range_: str, until: float | None):
|
||||||
|
if range_ not in RANGES:
|
||||||
|
raise HTTPException(400, f"range must be one of {', '.join(RANGES)}")
|
||||||
|
span, buckets = RANGES[range_]
|
||||||
|
until = until or time.time()
|
||||||
|
return until - span, until, span / buckets, buckets
|
||||||
|
|
||||||
|
|
||||||
|
def _probe_names(con) -> dict[int, dict]:
|
||||||
|
return {r["id"]: {"id": r["id"], "name": r["name"], "online": is_online(r), "last_seen": r["last_seen"], "icmp": r["icmp"]}
|
||||||
|
for r in con.execute("SELECT * FROM probes ORDER BY name COLLATE NOCASE")}
|
||||||
|
|
||||||
|
|
||||||
|
def _target_order(target: str, kind: str) -> tuple:
|
||||||
|
group = 0 if target.startswith("probe:") else 1 if target == "gateway" else 2 if kind == "lan" else 3
|
||||||
|
return (group, target)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health/matrix")
|
||||||
|
def matrix(window: int = Query(300, ge=60, le=3600)) -> dict:
|
||||||
|
"""Per probe and target, over the last `window` seconds."""
|
||||||
|
sev, params = _sev_sql()
|
||||||
|
since = time.time() - window
|
||||||
|
with db() as con:
|
||||||
|
probes = _probe_names(con)
|
||||||
|
rows = con.execute(f"""
|
||||||
|
SELECT probe_id, target, method, MAX(label) label, MAX(kind) kind, COUNT(*) n,
|
||||||
|
SUM(sev = 2) down, SUM(sev = 1) slow,
|
||||||
|
AVG(CASE WHEN ok THEN latency END) latency, AVG(loss) loss, MAX(ts) last,
|
||||||
|
(SELECT error FROM measurements e WHERE e.probe_id = m.probe_id AND e.target = m.target
|
||||||
|
AND e.method = m.method AND e.ok = 0 AND e.ts >= :since ORDER BY ts DESC LIMIT 1) error
|
||||||
|
FROM (SELECT *, {sev} sev FROM measurements WHERE ts >= :since AND method != 'throughput') m
|
||||||
|
GROUP BY probe_id, target, method""", {**params, "since": since}).fetchall()
|
||||||
|
cells: dict = defaultdict(lambda: {"methods": {}, "status": "nodata"})
|
||||||
|
targets: dict = {}
|
||||||
|
for r in rows:
|
||||||
|
if r["probe_id"] not in probes:
|
||||||
|
continue
|
||||||
|
key = (r["probe_id"], r["target"])
|
||||||
|
st = bucket_status(r["n"], r["down"], r["slow"])
|
||||||
|
c = cells[key]
|
||||||
|
c["methods"][r["method"]] = {"status": st, "n": r["n"], "down": r["down"], "slow": r["slow"],
|
||||||
|
"latency": r["latency"], "loss": r["loss"], "last": r["last"], "error": r["error"]}
|
||||||
|
if RANK[st] > RANK[c["status"]]:
|
||||||
|
c["status"] = st
|
||||||
|
targets.setdefault(r["target"], {"target": r["target"], "label": r["label"], "kind": r["kind"]})
|
||||||
|
for t in targets.values():
|
||||||
|
if t["target"].startswith("probe:"):
|
||||||
|
pid = int(t["target"].split(":", 1)[1])
|
||||||
|
if pid in probes:
|
||||||
|
t["label"] = probes[pid]["name"]
|
||||||
|
return {
|
||||||
|
"window": window, "probes": list(probes.values()),
|
||||||
|
"targets": sorted(targets.values(), key=lambda t: _target_order(t["target"], t["kind"])),
|
||||||
|
"cells": [{"probe_id": k[0], "target": k[1], **v} for k, v in cells.items()],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health/strips")
|
||||||
|
def strips(range: str = "24h", probe: int | None = None, until: float | None = None) -> dict:
|
||||||
|
"""Status per time bucket for every probe → target pair."""
|
||||||
|
since, until, width, n_buckets = _range(range, until)
|
||||||
|
sev, params = _sev_sql()
|
||||||
|
where = "ts >= :since AND ts < :until AND method != 'throughput'" + (" AND probe_id = :probe" if probe else "")
|
||||||
|
with db() as con:
|
||||||
|
probes = _probe_names(con)
|
||||||
|
rows = con.execute(f"""
|
||||||
|
SELECT probe_id, target, MAX(label) label, MAX(kind) kind, CAST((ts - :since) / :width AS INTEGER) b,
|
||||||
|
COUNT(*) n, SUM(sev = 2) down, SUM(sev = 1) slow, AVG(CASE WHEN ok THEN latency END) latency
|
||||||
|
FROM (SELECT *, {sev} sev FROM measurements WHERE {where}) GROUP BY probe_id, target, b""",
|
||||||
|
{**params, "since": since, "until": until, "width": width, "probe": probe}).fetchall()
|
||||||
|
series: dict = {}
|
||||||
|
for r in rows:
|
||||||
|
if r["probe_id"] not in probes or not 0 <= r["b"] < n_buckets:
|
||||||
|
continue
|
||||||
|
key = (r["probe_id"], r["target"])
|
||||||
|
if key not in series:
|
||||||
|
label = r["label"]
|
||||||
|
if r["target"].startswith("probe:"):
|
||||||
|
label = probes.get(int(r["target"].split(":", 1)[1]), {}).get("name", label)
|
||||||
|
series[key] = {"probe_id": r["probe_id"], "target": r["target"], "label": label, "kind": r["kind"],
|
||||||
|
"buckets": [None] * n_buckets}
|
||||||
|
series[key]["buckets"][r["b"]] = {"s": bucket_status(r["n"], r["down"], r["slow"]), "n": r["n"],
|
||||||
|
"down": r["down"], "slow": r["slow"],
|
||||||
|
"latency": round(r["latency"], 1) if r["latency"] is not None else None}
|
||||||
|
out = sorted(series.values(), key=lambda x: (probes[x["probe_id"]]["name"].lower(), _target_order(x["target"], x["kind"])))
|
||||||
|
for s in out:
|
||||||
|
s["uptime"] = _uptime(s["buckets"])
|
||||||
|
return {"since": since, "until": until, "width": width, "buckets": n_buckets, "probes": list(probes.values()), "series": out}
|
||||||
|
|
||||||
|
|
||||||
|
def _uptime(buckets) -> float | None:
|
||||||
|
n = sum(b["n"] for b in buckets if b)
|
||||||
|
down = sum(b["down"] for b in buckets if b)
|
||||||
|
return round(100 * (n - down) / n, 2) if n else None
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health/incidents")
|
||||||
|
def incidents(range: str = "24h", probe: int | None = None, until: float | None = None, limit: int = Query(200, ge=1, le=1000)) -> dict:
|
||||||
|
"""Runs of failed or slow measurements, merged per probe → target when they are close together."""
|
||||||
|
since, until, _, _ = _range(range, until)
|
||||||
|
s = settings.get()
|
||||||
|
gap = s.probe_interval * 2.5 + 5
|
||||||
|
sev, params = _sev_sql()
|
||||||
|
where = "ts >= :since AND ts < :until AND method != 'throughput'" + (" AND probe_id = :probe" if probe else "")
|
||||||
|
with db() as con:
|
||||||
|
probes = _probe_names(con)
|
||||||
|
rows = con.execute(f"""SELECT * FROM (SELECT ts, probe_id, target, label, kind, method, ok, latency, loss, error, {sev} sev
|
||||||
|
FROM measurements WHERE {where}) WHERE sev > 0 ORDER BY probe_id, target, ts""",
|
||||||
|
{**params, "since": since, "until": until, "probe": probe}).fetchall()
|
||||||
|
found, cur = [], None
|
||||||
|
for r in rows:
|
||||||
|
if r["probe_id"] not in probes:
|
||||||
|
continue
|
||||||
|
if cur and cur["probe_id"] == r["probe_id"] and cur["target"] == r["target"] and r["ts"] - cur["end"] <= gap:
|
||||||
|
cur["end"] = r["ts"]
|
||||||
|
else:
|
||||||
|
cur = {"probe_id": r["probe_id"], "probe": probes[r["probe_id"]]["name"], "target": r["target"],
|
||||||
|
"label": r["label"], "kind": r["kind"], "start": r["ts"], "end": r["ts"], "samples": 0,
|
||||||
|
"failed": 0, "methods": set(), "max_latency": None, "error": None}
|
||||||
|
found.append(cur)
|
||||||
|
cur["samples"] += 1
|
||||||
|
cur["failed"] += r["sev"] == 2
|
||||||
|
cur["methods"].add(r["method"])
|
||||||
|
if r["latency"] is not None and r["ok"]:
|
||||||
|
cur["max_latency"] = max(cur["max_latency"] or 0, r["latency"])
|
||||||
|
if r["error"]:
|
||||||
|
cur["error"] = r["error"]
|
||||||
|
now = time.time()
|
||||||
|
out = []
|
||||||
|
for i in found:
|
||||||
|
if not i["failed"] and i["samples"] < 2:
|
||||||
|
continue # one slow sample is noise
|
||||||
|
if i["target"].startswith("probe:"):
|
||||||
|
i["label"] = probes.get(int(i["target"].split(":", 1)[1]), {}).get("name", i["label"])
|
||||||
|
i["type"] = "down" if i["failed"] else "degraded"
|
||||||
|
i["methods"] = sorted(i["methods"])
|
||||||
|
i["ongoing"] = now - i["end"] < gap
|
||||||
|
i["duration"] = i["end"] - i["start"] + s.probe_interval
|
||||||
|
out.append(i)
|
||||||
|
out.sort(key=lambda i: -i["start"])
|
||||||
|
return {"since": since, "until": until, "incidents": out[:limit], "total": len(out),
|
||||||
|
"thresholds": {"lan_ms": s.slow_lan_ms, "wan_ms": s.slow_wan_ms, "dns_ms": s.slow_dns_ms, "loss": 0.3}}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health/series")
|
||||||
|
def series(probe: int, range: str = "24h", until: float | None = None) -> dict:
|
||||||
|
"""Latency, loss and throughput per target and method for one probe, bucketed."""
|
||||||
|
since, until, width, n_buckets = _range(range, until)
|
||||||
|
with db() as con:
|
||||||
|
probes = _probe_names(con)
|
||||||
|
if probe not in probes:
|
||||||
|
raise HTTPException(404, "No probe with that id")
|
||||||
|
rows = con.execute("""
|
||||||
|
SELECT target, method, MAX(label) label, MAX(kind) kind, CAST((ts - :since) / :width AS INTEGER) b,
|
||||||
|
COUNT(*) n, SUM(ok = 0) failed, AVG(CASE WHEN ok THEN latency END) avg, MAX(CASE WHEN ok THEN latency END) max,
|
||||||
|
AVG(loss) loss, AVG(mbps) mbps
|
||||||
|
FROM measurements WHERE probe_id = :probe AND ts >= :since AND ts < :until
|
||||||
|
GROUP BY target, method, b""", {"since": since, "until": until, "width": width, "probe": probe}).fetchall()
|
||||||
|
out: dict = {}
|
||||||
|
for r in rows:
|
||||||
|
if not 0 <= r["b"] < n_buckets:
|
||||||
|
continue
|
||||||
|
t = out.setdefault(r["target"], {"target": r["target"], "label": r["label"], "kind": r["kind"], "methods": {}})
|
||||||
|
if r["target"].startswith("probe:"):
|
||||||
|
t["label"] = probes.get(int(r["target"].split(":", 1)[1]), {}).get("name", t["label"])
|
||||||
|
m = t["methods"].setdefault(r["method"], [None] * n_buckets)
|
||||||
|
rnd = lambda v, d=1: None if v is None else round(v, d)
|
||||||
|
m[r["b"]] = {"n": r["n"], "failed": r["failed"], "avg": rnd(r["avg"]), "max": rnd(r["max"]),
|
||||||
|
"loss": rnd(r["loss"], 3), "mbps": rnd(r["mbps"])}
|
||||||
|
targets = sorted(out.values(), key=lambda t: _target_order(t["target"], t["kind"]))
|
||||||
|
return {"since": since, "until": until, "width": width, "buckets": n_buckets, "probe": probes[probe], "targets": targets}
|
||||||
|
|
||||||
|
|
||||||
|
def prune(con, retention_days: float) -> int:
|
||||||
|
return con.execute("DELETE FROM measurements WHERE ts < ?", (time.time() - retention_days * 86400,)).rowcount
|
||||||
174
app/hub/probes.py
Normal file
174
app/hub/probes.py
Normal file
|
|
@ -0,0 +1,174 @@
|
||||||
|
"""Probe management (UI) and the probe report endpoint (probes, token auth)."""
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
|
import secrets
|
||||||
|
import time
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, HTTPException, Request
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from app.hub import devices, settings
|
||||||
|
from app.hub.db import db
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
MAX_BATCH = 5000
|
||||||
|
|
||||||
|
|
||||||
|
class ProbeCreate(BaseModel):
|
||||||
|
name: str = Field(min_length=1, max_length=60)
|
||||||
|
|
||||||
|
|
||||||
|
class ProbeUpdate(BaseModel):
|
||||||
|
name: str | None = Field(default=None, min_length=1, max_length=60)
|
||||||
|
address: str | None = Field(default=None, max_length=255) # "" = detect again from reports
|
||||||
|
port: int | None = Field(default=None, ge=1, le=65535)
|
||||||
|
|
||||||
|
|
||||||
|
class Measurement(BaseModel):
|
||||||
|
ts: float
|
||||||
|
target: str = Field(max_length=300)
|
||||||
|
label: str | None = Field(default=None, max_length=200)
|
||||||
|
kind: str = Field(pattern="^(lan|wan)$")
|
||||||
|
method: str = Field(pattern="^(icmp|http|dns|throughput)$")
|
||||||
|
ok: bool
|
||||||
|
latency: float | None = None
|
||||||
|
loss: float | None = None
|
||||||
|
mbps: float | None = None
|
||||||
|
error: str | None = Field(default=None, max_length=300)
|
||||||
|
|
||||||
|
|
||||||
|
class Neighbor(BaseModel):
|
||||||
|
ip: str = Field(max_length=64)
|
||||||
|
mac: str = Field(max_length=32)
|
||||||
|
|
||||||
|
|
||||||
|
class Report(BaseModel):
|
||||||
|
version: str | None = Field(default=None, max_length=40)
|
||||||
|
hostname: str | None = Field(default=None, max_length=255)
|
||||||
|
port: int = Field(default=8765, ge=1, le=65535)
|
||||||
|
advertise_addr: str | None = Field(default=None, max_length=255)
|
||||||
|
icmp: bool | None = None
|
||||||
|
measurements: list[Measurement] = Field(default_factory=list, max_length=MAX_BATCH)
|
||||||
|
neighbors: list[Neighbor] = Field(default_factory=list, max_length=4096)
|
||||||
|
|
||||||
|
|
||||||
|
def is_online(row, now: float | None = None) -> bool:
|
||||||
|
now = now or time.time()
|
||||||
|
return bool(row["last_seen"]) and now - row["last_seen"] < settings.get().probe_interval * 3 + 10
|
||||||
|
|
||||||
|
|
||||||
|
def probe_out(row, *, with_token: bool = False) -> dict:
|
||||||
|
out = {k: row[k] for k in ("id", "name", "address", "port", "hostname", "version", "created", "last_seen", "last_error")}
|
||||||
|
out["address_locked"] = bool(row["address_locked"])
|
||||||
|
out["icmp"] = None if row["icmp"] is None else bool(row["icmp"])
|
||||||
|
out["online"] = is_online(row)
|
||||||
|
if with_token:
|
||||||
|
out["token"] = row["token"]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/probes")
|
||||||
|
def list_probes() -> dict:
|
||||||
|
with db() as con:
|
||||||
|
rows = con.execute("SELECT * FROM probes ORDER BY name COLLATE NOCASE").fetchall()
|
||||||
|
s = settings.get()
|
||||||
|
return {"probes": [probe_out(r) for r in rows], "interval": s.probe_interval,
|
||||||
|
"install_url": s.probe_install_url, "hub_url": s.hub_public_url}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/probes", status_code=201)
|
||||||
|
def create_probe(body: ProbeCreate) -> dict:
|
||||||
|
token = secrets.token_urlsafe(24)
|
||||||
|
with db() as con:
|
||||||
|
cur = con.execute("INSERT INTO probes(name, token, created) VALUES (?, ?, ?)", (body.name.strip(), token, time.time()))
|
||||||
|
row = con.execute("SELECT * FROM probes WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||||
|
return probe_out(row, with_token=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _get(con, probe_id: int):
|
||||||
|
row = con.execute("SELECT * FROM probes WHERE id = ?", (probe_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, "No probe with that id")
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/probes/{probe_id}")
|
||||||
|
def get_probe(probe_id: int) -> dict:
|
||||||
|
with db() as con:
|
||||||
|
return probe_out(_get(con, probe_id), with_token=True)
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/probes/{probe_id}")
|
||||||
|
def update_probe(probe_id: int, body: ProbeUpdate) -> dict:
|
||||||
|
with db() as con:
|
||||||
|
_get(con, probe_id)
|
||||||
|
if body.name is not None:
|
||||||
|
con.execute("UPDATE probes SET name = ? WHERE id = ?", (body.name.strip(), probe_id))
|
||||||
|
if body.address is not None:
|
||||||
|
addr = body.address.strip()
|
||||||
|
con.execute("UPDATE probes SET address = ?, address_locked = ? WHERE id = ?", (addr or None, int(bool(addr)), probe_id))
|
||||||
|
if body.port is not None:
|
||||||
|
con.execute("UPDATE probes SET port = ? WHERE id = ?", (body.port, probe_id))
|
||||||
|
return probe_out(_get(con, probe_id), with_token=True)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/probes/{probe_id}", status_code=204)
|
||||||
|
def delete_probe(probe_id: int, keep_history: bool = False) -> None:
|
||||||
|
with db() as con:
|
||||||
|
_get(con, probe_id)
|
||||||
|
con.execute("DELETE FROM probes WHERE id = ?", (probe_id,))
|
||||||
|
if not keep_history:
|
||||||
|
con.execute("DELETE FROM measurements WHERE probe_id = ?", (probe_id,))
|
||||||
|
|
||||||
|
|
||||||
|
def probe_config(con, row) -> dict:
|
||||||
|
"""What a probe should test, returned on every report."""
|
||||||
|
s = settings.get()
|
||||||
|
peers = [
|
||||||
|
{"id": p["id"], "name": p["name"], "host": p["address"], "port": p["port"] or 8765}
|
||||||
|
for p in con.execute("SELECT * FROM probes WHERE id != ? AND address IS NOT NULL ORDER BY id", (row["id"],))
|
||||||
|
]
|
||||||
|
dns = [{"server": d, "label": "LAN DNS" if len(s.lan_dns_servers) == 1 else f"LAN DNS {d}", "kind": "lan"} for d in s.lan_dns_servers]
|
||||||
|
dns += [{"server": d, "label": f"DNS {d}", "kind": "wan"} for d in s.dns_servers]
|
||||||
|
http = [{"url": u, "label": u.split("//", 1)[-1].split("/", 1)[0], "kind": "wan", "target": f"web:{u}"} for u in s.wan_http_urls]
|
||||||
|
if s.vps_url:
|
||||||
|
http.append({"url": f"{s.vps_url}/probe/ping", "label": "VPS", "kind": "wan", "target": "vps"})
|
||||||
|
return {
|
||||||
|
"probe_id": row["id"], "name": row["name"], "interval": s.probe_interval, "peers": peers,
|
||||||
|
"dns": dns, "dns_name": s.dns_query_name, "http": http,
|
||||||
|
"throughput_every": s.throughput_every, "throughput_bytes": s.throughput_bytes,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _client_ip(request: Request) -> str | None:
|
||||||
|
host = request.client.host if request.client else None
|
||||||
|
try:
|
||||||
|
return str(ipaddress.ip_address(host)) if host else None
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/probe/report")
|
||||||
|
def report(body: Report, request: Request, authorization: str = Header(default="")) -> dict:
|
||||||
|
token = authorization.removeprefix("Bearer ").strip()
|
||||||
|
now = time.time()
|
||||||
|
with db() as con:
|
||||||
|
row = con.execute("SELECT * FROM probes WHERE token = ?", (token,)).fetchone() if token else None
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(401, "Unknown probe token. Add the probe on the hub and use its install command.")
|
||||||
|
address = row["address"]
|
||||||
|
if not row["address_locked"]:
|
||||||
|
address = (body.advertise_addr or "").strip() or _client_ip(request) or address
|
||||||
|
con.execute(
|
||||||
|
"UPDATE probes SET address = ?, port = ?, hostname = ?, version = ?, icmp = ?, last_seen = ?, last_error = NULL WHERE id = ?",
|
||||||
|
(address, body.port, body.hostname, body.version, None if body.icmp is None else int(body.icmp), now, row["id"]),
|
||||||
|
)
|
||||||
|
con.executemany(
|
||||||
|
"INSERT INTO measurements(ts, probe_id, target, label, kind, method, ok, latency, loss, mbps, error) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
|
||||||
|
[(m.ts, row["id"], m.target, m.label, m.kind, m.method, int(m.ok), m.latency, m.loss, m.mbps, m.error) for m in body.measurements],
|
||||||
|
)
|
||||||
|
for n in body.neighbors:
|
||||||
|
devices.sighting(con, ip=n.ip, mac=n.mac, source="arp", seen=now)
|
||||||
|
row = con.execute("SELECT * FROM probes WHERE id = ?", (row["id"],)).fetchone()
|
||||||
|
return probe_config(con, row)
|
||||||
131
app/hub/server.py
Normal file
131
app/hub/server.py
Normal file
|
|
@ -0,0 +1,131 @@
|
||||||
|
"""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, Response
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
||||||
|
from app.hub import adguard, db, dns, health, 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)
|
||||||
|
|
||||||
|
|
||||||
|
@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())]
|
||||||
|
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")
|
||||||
|
|
||||||
|
|
||||||
|
@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")
|
||||||
|
|
||||||
|
|
||||||
|
@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"})
|
||||||
69
app/hub/settings.py
Normal file
69
app/hub/settings.py
Normal file
|
|
@ -0,0 +1,69 @@
|
||||||
|
"""Hub settings, read from the environment (.env) on each call so tests can change them."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
DEFAULT_PROBE_INSTALL_URL = "https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install-probe.sh"
|
||||||
|
|
||||||
|
|
||||||
|
def _list(name: str, default: str) -> list[str]:
|
||||||
|
return [x.strip() for x in os.environ.get(name, default).split(",") if x.strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def _num(name: str, default: float) -> float:
|
||||||
|
try:
|
||||||
|
return float(os.environ.get(name, "") or default)
|
||||||
|
except ValueError:
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Settings:
|
||||||
|
ui_password: str
|
||||||
|
adguard_url: str
|
||||||
|
adguard_username: str
|
||||||
|
adguard_password: str
|
||||||
|
probe_interval: int
|
||||||
|
retention_days: float
|
||||||
|
dns_servers: list[str]
|
||||||
|
lan_dns_servers: list[str]
|
||||||
|
dns_query_name: str
|
||||||
|
wan_http_urls: list[str]
|
||||||
|
vps_url: str
|
||||||
|
slow_lan_ms: float
|
||||||
|
slow_wan_ms: float
|
||||||
|
slow_dns_ms: float
|
||||||
|
throughput_every: int
|
||||||
|
throughput_bytes: int
|
||||||
|
probe_install_url: str
|
||||||
|
hub_public_url: str
|
||||||
|
|
||||||
|
@property
|
||||||
|
def adguard_configured(self) -> bool:
|
||||||
|
return bool(self.adguard_url)
|
||||||
|
|
||||||
|
|
||||||
|
def get() -> Settings:
|
||||||
|
adguard_url = os.environ.get("ADGUARD_URL", "").strip().rstrip("/")
|
||||||
|
lan_default = urlparse(adguard_url).hostname or "" if adguard_url else ""
|
||||||
|
return Settings(
|
||||||
|
ui_password=os.environ.get("UI_PASSWORD", ""),
|
||||||
|
adguard_url=adguard_url,
|
||||||
|
adguard_username=os.environ.get("ADGUARD_USERNAME", ""),
|
||||||
|
adguard_password=os.environ.get("ADGUARD_PASSWORD", ""),
|
||||||
|
probe_interval=max(5, int(_num("PROBE_INTERVAL", 30))),
|
||||||
|
retention_days=max(1.0, _num("RETENTION_DAYS", 14)),
|
||||||
|
dns_servers=_list("DNS_SERVERS", "1.1.1.1,8.8.8.8,9.9.9.9"),
|
||||||
|
lan_dns_servers=_list("LAN_DNS_SERVERS", lan_default),
|
||||||
|
dns_query_name=os.environ.get("DNS_QUERY_NAME", "example.com").strip() or "example.com",
|
||||||
|
wan_http_urls=_list("WAN_HTTP_URLS", "http://connectivitycheck.gstatic.com/generate_204"),
|
||||||
|
vps_url=os.environ.get("VPS_URL", "").strip().rstrip("/"),
|
||||||
|
slow_lan_ms=_num("SLOW_LAN_MS", 100),
|
||||||
|
slow_wan_ms=_num("SLOW_WAN_MS", 200),
|
||||||
|
slow_dns_ms=_num("SLOW_DNS_MS", 250),
|
||||||
|
throughput_every=max(0, int(_num("THROUGHPUT_EVERY", 10))),
|
||||||
|
throughput_bytes=int(min(_num("THROUGHPUT_BYTES", 4_000_000), 50_000_000)),
|
||||||
|
probe_install_url=os.environ.get("PROBE_INSTALL_URL", DEFAULT_PROBE_INSTALL_URL).strip(),
|
||||||
|
hub_public_url=os.environ.get("HUB_PUBLIC_URL", "").strip().rstrip("/"),
|
||||||
|
)
|
||||||
28
app/main.py
Normal file
28
app/main.py
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
"""Entry point for both roles. ROLE=hub (the default) serves the web UI and API;
|
||||||
|
ROLE=probe runs a network probe. `update` imports this module as its pre-flight check."""
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
if os.environ.get("ROLE", "hub").strip().lower() == "probe":
|
||||||
|
from app.probe.server import app
|
||||||
|
else:
|
||||||
|
from app.hub.server import app
|
||||||
|
|
||||||
|
DATA_DIR = Path(os.environ.get("DATA_DIR", "data"))
|
||||||
|
_role_lifespan = app.router.lifespan_context
|
||||||
|
|
||||||
|
|
||||||
|
@contextlib.asynccontextmanager
|
||||||
|
async def lifespan(a):
|
||||||
|
# Startup work goes here, not at import time: `update` imports this module as a check
|
||||||
|
# before restarting. Shared by both roles; each role's own startup runs inside.
|
||||||
|
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
async with _role_lifespan(a):
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
app.router.lifespan_context = lifespan
|
||||||
|
|
||||||
|
__all__ = ["app"]
|
||||||
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"],
|
||||||
|
}
|
||||||
109
app/static/css/app.css
Normal file
109
app/static/css/app.css
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
/* Network monitor: project rules on top of house.css. Chart colors come from the dataviz
|
||||||
|
reference palette (status steps + categorical slots 1-2), stepped for each theme. */
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--viz-ok: #0ca30c;
|
||||||
|
--viz-warn: #fab219;
|
||||||
|
--viz-down: #d03b3b;
|
||||||
|
--viz-none: var(--surface-2);
|
||||||
|
--viz-1: #2a78d6;
|
||||||
|
--viz-2: #eb6834;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root:not([data-theme='light']) { --viz-1: #3987e5; --viz-2: #d95926; }
|
||||||
|
}
|
||||||
|
:root[data-theme='dark'] { --viz-1: #3987e5; --viz-2: #d95926; }
|
||||||
|
|
||||||
|
/* ---------- layout bits ---------- */
|
||||||
|
.pane.fill { flex: 1; }
|
||||||
|
.content { max-width: 1280px; padding: var(--space-4) var(--space-5) var(--space-10); }
|
||||||
|
.content > .section-head:first-child, .content > .section-title:first-child { margin-top: 0; }
|
||||||
|
.section-head { display: flex; align-items: baseline; gap: var(--space-3); flex-wrap: wrap; margin: var(--space-6) 0 var(--space-2); }
|
||||||
|
.section-head .section-title { margin: 0; }
|
||||||
|
.section-head .hint { font-size: var(--text-xs); color: var(--fg-muted); }
|
||||||
|
.lede { margin: 0 0 var(--space-3); color: var(--fg-muted); }
|
||||||
|
.cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 380px), 1fr)); gap: var(--space-5); }
|
||||||
|
.cols > * { min-width: 0; }
|
||||||
|
.kv { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px var(--space-4); margin: 0; font-size: var(--text-sm); }
|
||||||
|
.kv dt { color: var(--fg-muted); }
|
||||||
|
.kv dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
|
||||||
|
.facts { display: flex; flex-wrap: wrap; gap: var(--space-2) var(--space-6); margin: var(--space-2) 0 var(--space-4); }
|
||||||
|
.fact { display: grid; gap: 2px; }
|
||||||
|
.fact .label { font-size: var(--text-2xs); }
|
||||||
|
.fact strong { font-size: var(--text-lg); font-weight: var(--weight-semibold); }
|
||||||
|
.title-row { display: flex; align-items: center; gap: var(--space-2); flex-wrap: wrap; }
|
||||||
|
.title-row h2 { margin: 0; font-size: var(--text-xl); overflow-wrap: anywhere; }
|
||||||
|
.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 220px), 1fr)); gap: var(--space-3); max-width: 760px; }
|
||||||
|
.form-grid .wide { grid-column: 1 / -1; }
|
||||||
|
.cmd { display: flex; gap: var(--space-2); align-items: stretch; }
|
||||||
|
.cmd pre { flex: 1; min-width: 0; margin: 0; padding: var(--space-2) var(--space-3); border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--code-bg); font: var(--text-sm)/1.5 var(--font-mono); white-space: pre-wrap; word-break: break-all; }
|
||||||
|
.more { display: flex; justify-content: center; padding: var(--space-3); }
|
||||||
|
.toolbar .input { width: 220px; height: var(--control-h); padding: 0 10px; }
|
||||||
|
.table a { color: inherit; text-decoration: none; }
|
||||||
|
.table a:hover { color: var(--accent-text); text-decoration: underline; }
|
||||||
|
.table td.mono, .table .mono { font-size: var(--text-xs); }
|
||||||
|
.table .domain { overflow-wrap: anywhere; }
|
||||||
|
.table tr.flagged td:first-child { box-shadow: inset 3px 0 0 var(--danger); }
|
||||||
|
.chips { display: inline-flex; flex-wrap: wrap; gap: 4px; vertical-align: middle; }
|
||||||
|
.callout { padding: var(--space-3) var(--space-4); border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface-2); font-size: var(--text-sm); }
|
||||||
|
.callout.error { border-color: var(--danger); background: var(--danger-soft); }
|
||||||
|
.stale { opacity: 0.55; transition: opacity var(--dur-base); }
|
||||||
|
|
||||||
|
/* ---------- mesh matrix ---------- */
|
||||||
|
.matrix th.row-head { text-align: left; position: sticky; left: 0; background: var(--surface); z-index: 1; }
|
||||||
|
.matrix td { padding: 4px; }
|
||||||
|
.cell { display: grid; gap: 1px; min-width: 92px; padding: 5px 8px; border-radius: var(--radius-control); background: var(--surface-2); color: var(--fg); text-decoration: none; font-size: var(--text-xs); border-left: 4px solid var(--viz-none); }
|
||||||
|
.cell strong { font-size: var(--text-sm); font-variant-numeric: tabular-nums; }
|
||||||
|
.cell.s-ok { border-left-color: var(--viz-ok); }
|
||||||
|
.cell.s-degraded { border-left-color: var(--viz-warn); }
|
||||||
|
.cell.s-down { border-left-color: var(--viz-down); background: var(--danger-soft); }
|
||||||
|
.cell .muted { font-variant-numeric: tabular-nums; }
|
||||||
|
.cell-empty { color: var(--fg-subtle); text-align: center; font-size: var(--text-xs); }
|
||||||
|
|
||||||
|
/* ---------- status strips ---------- */
|
||||||
|
.strips { display: grid; gap: 6px; }
|
||||||
|
.strip-row { display: grid; grid-template-columns: minmax(120px, 220px) minmax(0, 1fr) 64px; align-items: center; gap: var(--space-3); font-size: var(--text-sm); }
|
||||||
|
.strip-row .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.strip-row .uptime { text-align: right; font-variant-numeric: tabular-nums; color: var(--fg-muted); font-size: var(--text-xs); }
|
||||||
|
.strip-group + .strip-group { margin-top: var(--space-4); }
|
||||||
|
.strip-group h3 { display: flex; align-items: center; gap: var(--space-2); margin: 0 0 6px; font-size: var(--text-sm); }
|
||||||
|
.strip { display: grid; grid-template-columns: repeat(var(--n), minmax(0, 1fr)); gap: 2px; height: 22px; cursor: crosshair; }
|
||||||
|
.strip span { border-radius: 2px; background: var(--viz-none); }
|
||||||
|
.strip .s-ok, .viz-swatch.s-ok { background: var(--viz-ok); }
|
||||||
|
.strip .s-degraded, .viz-swatch.s-degraded { background: var(--viz-warn); }
|
||||||
|
.strip .s-down, .viz-swatch.s-down { background: var(--viz-down); }
|
||||||
|
.strip .s-nodata, .viz-swatch.s-nodata { background: var(--viz-none); box-shadow: inset 0 0 0 1px var(--border); }
|
||||||
|
.strip-axis { display: grid; grid-template-columns: minmax(120px, 220px) minmax(0, 1fr) 64px; gap: var(--space-3); font-size: var(--text-2xs); color: var(--fg-muted); }
|
||||||
|
.strip-axis span:nth-child(2) { display: flex; justify-content: space-between; }
|
||||||
|
|
||||||
|
/* ---------- charts ---------- */
|
||||||
|
.chart { position: relative; width: 100%; }
|
||||||
|
.viz { display: block; overflow: visible; }
|
||||||
|
.viz-grid { stroke: var(--border); stroke-width: 1; }
|
||||||
|
.viz-axis { stroke: var(--border-strong); stroke-width: 1; }
|
||||||
|
.viz-tick { fill: var(--fg-muted); font-size: 11px; font-variant-numeric: tabular-nums; }
|
||||||
|
.viz-label { fill: var(--fg-muted); font-size: 11px; }
|
||||||
|
.viz-cross { stroke: var(--fg-subtle); stroke-width: 1; }
|
||||||
|
.viz-fail { fill: var(--viz-down); }
|
||||||
|
.viz-hit:hover { fill: var(--surface-2); fill-opacity: 0.5; }
|
||||||
|
.multiples { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 420px), 1fr)); gap: var(--space-4); }
|
||||||
|
.multiple { min-width: 0; padding: var(--space-3); border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); }
|
||||||
|
.multiple h4 { display: flex; align-items: center; gap: var(--space-2); margin: 0 0 4px; font-size: var(--text-sm); }
|
||||||
|
.viz-legend { display: flex; flex-wrap: wrap; gap: var(--space-1) var(--space-4); font-size: var(--text-xs); color: var(--fg-muted); }
|
||||||
|
.viz-legend-item { display: inline-flex; align-items: center; gap: 6px; }
|
||||||
|
.viz-swatch { display: inline-block; width: 10px; height: 10px; border-radius: 2px; }
|
||||||
|
.viz-linekey { display: inline-block; width: 14px; height: 2px; border-radius: 1px; }
|
||||||
|
.viz-tip { position: fixed; z-index: var(--z-toast); pointer-events: none; min-width: 140px; max-width: 320px; padding: 8px 10px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); box-shadow: var(--shadow-popover); font-size: var(--text-xs); }
|
||||||
|
.viz-tip-title { margin-bottom: 4px; color: var(--fg-muted); }
|
||||||
|
.viz-tip-row { display: flex; align-items: center; gap: 6px; }
|
||||||
|
.viz-tip-row strong { font-variant-numeric: tabular-nums; }
|
||||||
|
|
||||||
|
@media (max-width: 800px) {
|
||||||
|
.content { padding: var(--space-3) var(--space-3) var(--space-10); }
|
||||||
|
.strip { gap: 1px; }
|
||||||
|
.strip-row, .strip-axis { grid-template-columns: minmax(0, 1fr) 52px; }
|
||||||
|
.strip-row .name { grid-column: 1 / -1; }
|
||||||
|
.strip-row .strip { grid-column: 1; }
|
||||||
|
.strip-axis { display: none; }
|
||||||
|
.toolbar .input { width: 160px; }
|
||||||
|
}
|
||||||
390
app/static/css/house.css
Normal file
390
app/static/css/house.css
Normal file
|
|
@ -0,0 +1,390 @@
|
||||||
|
/* =====================================================================
|
||||||
|
House style: tokens, base and components.
|
||||||
|
Copy into the project as-is (e.g. static/css/house.css) and put project
|
||||||
|
rules in a second file loaded after it (e.g. app.css). Don't edit this
|
||||||
|
copy for one project; override tokens in app.css instead.
|
||||||
|
|
||||||
|
The look: a dense, quiet utility UI. System fonts at 14px, neutral grays,
|
||||||
|
one blue accent, 48px top bar + 216px sidebar, 30px controls, hairline
|
||||||
|
borders instead of shadows. See references/house.md for the rules.
|
||||||
|
|
||||||
|
Allowed per-project override: the accent group (see house.md). Nothing else.
|
||||||
|
===================================================================== */
|
||||||
|
|
||||||
|
:root {
|
||||||
|
/* ---- Neutrals ------------------------------------------------------- */
|
||||||
|
--bg: #f7f7f8;
|
||||||
|
--surface: #ffffff;
|
||||||
|
--surface-2: #f0f1f3; /* wells, hover, segmented track, gutters */
|
||||||
|
--border: #dfe1e5;
|
||||||
|
--border-strong: #c9ccd2;
|
||||||
|
--fg: #1c1e21;
|
||||||
|
--fg-muted: #646a73;
|
||||||
|
--fg-subtle: #8a8f98;
|
||||||
|
|
||||||
|
/* ---- Accent (the one per-project knob) ------------------------------ */
|
||||||
|
--accent: #3b6ef5;
|
||||||
|
--accent-hover: #2f62e6;
|
||||||
|
--accent-fg: #ffffff; /* text on --accent */
|
||||||
|
--accent-soft: #e6edfe; /* active nav, chips, icon tiles */
|
||||||
|
--accent-text: #2f5fe0; /* accent-colored text and links on --bg/--surface */
|
||||||
|
--sel: #dce6ff; /* selected rows */
|
||||||
|
--ring: var(--accent);
|
||||||
|
|
||||||
|
/* ---- Semantic -------------------------------------------------------- */
|
||||||
|
--ok: #1f8a4c; --ok-soft: #e3f4ea;
|
||||||
|
--warn: #a35f00; --warn-soft: #fdf0dc;
|
||||||
|
--danger: #c93a3a; --danger-soft: #fbe6e6;
|
||||||
|
--info: #1b5fd1; --info-soft: #e4ecfb;
|
||||||
|
--on-danger: #ffffff;
|
||||||
|
|
||||||
|
/* ---- Code and syntax ------------------------------------------------- */
|
||||||
|
--code-bg: #f3f4f6;
|
||||||
|
--tok-key: #8a3ab9;
|
||||||
|
--tok-string: #0b7a3e;
|
||||||
|
--tok-number: #1b5fd1;
|
||||||
|
--tok-bool: #b5560b;
|
||||||
|
--tok-null: #8a8f98;
|
||||||
|
|
||||||
|
/* ---- Type ------------------------------------------------------------ */
|
||||||
|
--font-body: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||||
|
--font-display: var(--font-body);
|
||||||
|
--font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace;
|
||||||
|
|
||||||
|
--text-2xs: 11px; /* nav headings, badges, chips */
|
||||||
|
--text-xs: 12px; /* status bar, hints, small buttons */
|
||||||
|
--text-sm: 13px; /* buttons, menus, toasts, mono */
|
||||||
|
--text-base: 14px; /* body */
|
||||||
|
--text-md: 15px; /* brand, prose */
|
||||||
|
--text-lg: 17px; /* modal and section titles */
|
||||||
|
--text-xl: 20px; /* page h2 */
|
||||||
|
--text-2xl: 26px; /* page h1 */
|
||||||
|
--leading: 1.5;
|
||||||
|
--leading-prose: 1.65;
|
||||||
|
--tracking-label: 0.06em;
|
||||||
|
--weight-medium: 500;
|
||||||
|
--weight-semibold: 600;
|
||||||
|
--weight-brand: 650;
|
||||||
|
|
||||||
|
/* ---- Space (4px base) ----------------------------------------------- */
|
||||||
|
--space-1: 4px; --space-2: 8px; --space-3: 12px; --space-4: 16px;
|
||||||
|
--space-5: 20px; --space-6: 24px; --space-8: 32px; --space-10: 40px;
|
||||||
|
--space-12: 48px;
|
||||||
|
|
||||||
|
/* ---- Shape, size, elevation ---------------------------------------- */
|
||||||
|
--radius-sm: 4px; /* chips, mini buttons */
|
||||||
|
--radius-control: 6px; /* buttons, selects, nav */
|
||||||
|
--radius-md: 8px; /* inputs, menus, toasts */
|
||||||
|
--radius-card: 10px; /* cards */
|
||||||
|
--radius-lg: 12px; /* modals */
|
||||||
|
--radius-full: 999px;
|
||||||
|
|
||||||
|
--control-h: 30px;
|
||||||
|
--control-h-sm: 26px;
|
||||||
|
--topbar: 48px;
|
||||||
|
--sidebar: 216px;
|
||||||
|
--content-max: 960px;
|
||||||
|
--prose-max: 820px;
|
||||||
|
|
||||||
|
--shadow-raised: 0 1px 2px rgba(0, 0, 0, 0.12);
|
||||||
|
--shadow-popover: 0 6px 24px rgba(15, 20, 30, 0.12);
|
||||||
|
--shadow-modal: 0 6px 24px rgba(15, 20, 30, 0.12);
|
||||||
|
--backdrop: rgba(0, 0, 0, 0.45);
|
||||||
|
--scrim: rgba(0, 0, 0, 0.35);
|
||||||
|
|
||||||
|
/* ---- Motion and layers ---------------------------------------------- */
|
||||||
|
--ease-out: cubic-bezier(0.2, 0.7, 0.2, 1);
|
||||||
|
--dur-fast: 120ms;
|
||||||
|
--dur-base: 180ms;
|
||||||
|
--dur-slow: 300ms;
|
||||||
|
--z-sticky: 10; --z-scrim: 20; --z-drawer: 30; --z-dropdown: 40; --z-toast: 50;
|
||||||
|
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Dark: same tokens, redesigned values. Two blocks so the explicit
|
||||||
|
data-theme toggle wins over the OS setting in both directions. */
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root:not([data-theme='light']) {
|
||||||
|
--bg: #131417;
|
||||||
|
--surface: #1b1d21;
|
||||||
|
--surface-2: #24272c;
|
||||||
|
--border: #33373e;
|
||||||
|
--border-strong: #464b53;
|
||||||
|
--fg: #e6e7e9;
|
||||||
|
--fg-muted: #9aa0a9;
|
||||||
|
--fg-subtle: #7d838c;
|
||||||
|
--accent: #6b93ff;
|
||||||
|
--accent-hover: #82a4ff;
|
||||||
|
--accent-fg: #0d1220;
|
||||||
|
--accent-soft: #232f4d;
|
||||||
|
--accent-text: #7fa2ff;
|
||||||
|
--sel: #2a3a63;
|
||||||
|
--ok: #5fd08f; --ok-soft: #1c3527;
|
||||||
|
--warn: #f0b45a; --warn-soft: #3a2e1a;
|
||||||
|
--danger: #ff7b7b; --danger-soft: #3d2224;
|
||||||
|
--info: #82aaff; --info-soft: #222f4a;
|
||||||
|
--on-danger: #1b0d0d;
|
||||||
|
--code-bg: #24272c;
|
||||||
|
--tok-key: #d39cf5;
|
||||||
|
--tok-string: #8bd49c;
|
||||||
|
--tok-number: #82aaff;
|
||||||
|
--tok-bool: #f4a85e;
|
||||||
|
--tok-null: #8a8f98;
|
||||||
|
--shadow-raised: 0 1px 2px rgba(0, 0, 0, 0.4);
|
||||||
|
--shadow-popover: 0 6px 24px rgba(0, 0, 0, 0.45);
|
||||||
|
--shadow-modal: 0 6px 24px rgba(0, 0, 0, 0.45);
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
:root[data-theme='dark'] {
|
||||||
|
--bg: #131417;
|
||||||
|
--surface: #1b1d21;
|
||||||
|
--surface-2: #24272c;
|
||||||
|
--border: #33373e;
|
||||||
|
--border-strong: #464b53;
|
||||||
|
--fg: #e6e7e9;
|
||||||
|
--fg-muted: #9aa0a9;
|
||||||
|
--fg-subtle: #7d838c;
|
||||||
|
--accent: #6b93ff;
|
||||||
|
--accent-hover: #82a4ff;
|
||||||
|
--accent-fg: #0d1220;
|
||||||
|
--accent-soft: #232f4d;
|
||||||
|
--accent-text: #7fa2ff;
|
||||||
|
--sel: #2a3a63;
|
||||||
|
--ok: #5fd08f; --ok-soft: #1c3527;
|
||||||
|
--warn: #f0b45a; --warn-soft: #3a2e1a;
|
||||||
|
--danger: #ff7b7b; --danger-soft: #3d2224;
|
||||||
|
--info: #82aaff; --info-soft: #222f4a;
|
||||||
|
--on-danger: #1b0d0d;
|
||||||
|
--code-bg: #24272c;
|
||||||
|
--tok-key: #d39cf5;
|
||||||
|
--tok-string: #8bd49c;
|
||||||
|
--tok-number: #82aaff;
|
||||||
|
--tok-bool: #f4a85e;
|
||||||
|
--tok-null: #8a8f98;
|
||||||
|
--shadow-raised: 0 1px 2px rgba(0, 0, 0, 0.4);
|
||||||
|
--shadow-popover: 0 6px 24px rgba(0, 0, 0, 0.45);
|
||||||
|
--shadow-modal: 0 6px 24px rgba(0, 0, 0, 0.45);
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- base ---------- */
|
||||||
|
*, *::before, *::after { box-sizing: border-box; }
|
||||||
|
html, body { height: 100%; margin: 0; }
|
||||||
|
html { -webkit-text-size-adjust: 100%; text-size-adjust: 100%; }
|
||||||
|
body { background: var(--bg); color: var(--fg); font: var(--text-base)/var(--leading) var(--font-body); -webkit-font-smoothing: antialiased; }
|
||||||
|
h1, h2, h3, h4 { font-family: var(--font-display); text-wrap: balance; }
|
||||||
|
a { color: var(--accent-text); }
|
||||||
|
button, input, select, textarea { font: inherit; color: inherit; }
|
||||||
|
img, svg, video, canvas { max-width: 100%; }
|
||||||
|
[hidden] { display: none !important; }
|
||||||
|
::selection { background: var(--sel); }
|
||||||
|
:focus-visible { outline: 2px solid var(--ring); outline-offset: 1px; }
|
||||||
|
textarea { tab-size: 4; }
|
||||||
|
|
||||||
|
.mono { font-family: var(--font-mono); font-size: var(--text-sm); }
|
||||||
|
.muted { color: var(--fg-muted); }
|
||||||
|
.small { font-size: var(--text-xs); }
|
||||||
|
.strong { font-weight: var(--weight-semibold); }
|
||||||
|
.nowrap { white-space: nowrap; }
|
||||||
|
.num { font-variant-numeric: tabular-nums; }
|
||||||
|
.spacer { flex: 1; }
|
||||||
|
.error-text { color: var(--danger); }
|
||||||
|
.ok-text { color: var(--ok); }
|
||||||
|
.label, .section-title { font-size: var(--text-xs); font-weight: var(--weight-semibold); letter-spacing: var(--tracking-label); text-transform: uppercase; color: var(--fg-muted); }
|
||||||
|
.section-title { margin: var(--space-4) 0 6px; }
|
||||||
|
|
||||||
|
/* ---------- shell ---------- */
|
||||||
|
.shell {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: var(--sidebar) minmax(0, 1fr);
|
||||||
|
grid-template-rows: var(--topbar) minmax(0, 1fr);
|
||||||
|
grid-template-areas: 'top top' 'side main';
|
||||||
|
height: 100vh;
|
||||||
|
height: 100dvh;
|
||||||
|
}
|
||||||
|
.shell.bare { grid-template-columns: minmax(0, 1fr); grid-template-areas: 'top' 'main'; }
|
||||||
|
.shell.bare .sidebar, .shell.bare .menu-btn, .shell.bare .scrim { display: none !important; }
|
||||||
|
|
||||||
|
.topbar { grid-area: top; display: flex; align-items: center; gap: 10px; padding: 0 var(--space-3); background: var(--surface); border-bottom: 1px solid var(--border); }
|
||||||
|
.brand { display: flex; align-items: center; gap: var(--space-2); color: var(--fg); text-decoration: none; font-weight: var(--weight-brand); font-size: var(--text-md); white-space: nowrap; }
|
||||||
|
.brand-mark { display: grid; place-items: center; width: 26px; height: 26px; border-radius: 7px; background: var(--accent); color: var(--accent-fg); font-size: var(--text-base); }
|
||||||
|
.topbar-title { color: var(--fg-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
|
||||||
|
.topbar-title:not(:empty)::before { content: '/'; margin-right: 10px; opacity: 0.5; }
|
||||||
|
.icon-btn { display: inline-grid; place-items: center; width: 34px; height: 34px; border: 1px solid transparent; border-radius: var(--radius-md); background: transparent; color: var(--fg); cursor: pointer; font-size: 16px; }
|
||||||
|
.icon-btn:hover { background: var(--surface-2); }
|
||||||
|
.menu-btn { display: none; position: relative; }
|
||||||
|
.menu-btn.has-badge::after { content: ''; position: absolute; top: 6px; right: 6px; width: 8px; height: 8px; border-radius: 50%; background: var(--danger); }
|
||||||
|
|
||||||
|
.sidebar { grid-area: side; overflow-y: auto; padding: var(--space-3) 10px; background: var(--surface); border-right: 1px solid var(--border); }
|
||||||
|
.nav-filter { width: 100%; padding: 7px 10px; margin-bottom: 10px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--bg); }
|
||||||
|
.nav-group { margin-top: 14px; }
|
||||||
|
.nav-heading { padding: 0 var(--space-2) var(--space-1); font-size: var(--text-2xs); font-weight: var(--weight-semibold); letter-spacing: var(--tracking-label); text-transform: uppercase; color: var(--fg-muted); }
|
||||||
|
.nav-item { display: flex; align-items: center; gap: 10px; padding: 6px var(--space-2); border-radius: var(--radius-control); color: var(--fg); text-decoration: none; }
|
||||||
|
.nav-item:hover { background: var(--surface-2); }
|
||||||
|
.nav-item.active { background: var(--accent-soft); color: var(--accent-text); font-weight: var(--weight-semibold); }
|
||||||
|
.nav-icon { display: inline-grid; place-items: center; min-width: 26px; height: 22px; padding: 0 3px; border-radius: 5px; background: var(--surface-2); font: var(--weight-semibold) var(--text-2xs) var(--font-mono); color: var(--fg-muted); }
|
||||||
|
.nav-item.active .nav-icon { background: var(--accent); color: var(--accent-fg); }
|
||||||
|
.nav-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.scrim { display: none; }
|
||||||
|
|
||||||
|
.view { grid-area: main; min-width: 0; min-height: 0; overflow: auto; }
|
||||||
|
.loading, .empty { padding: var(--space-12) var(--space-6); text-align: center; color: var(--fg-muted); }
|
||||||
|
.empty .btn { margin-top: var(--space-2); }
|
||||||
|
|
||||||
|
/* ---------- pages (home, settings, anything that scrolls as a document) ---------- */
|
||||||
|
.page { max-width: var(--content-max); margin: 0 auto; padding: var(--space-8) var(--space-6) var(--space-12); }
|
||||||
|
.page h1 { margin: 0 0 var(--space-1); font-size: var(--text-2xl); }
|
||||||
|
.page h2 { margin: var(--space-8) 0 var(--space-2); font-size: var(--text-xl); }
|
||||||
|
.page-filter { width: 100%; max-width: 380px; margin: 18px 0 var(--space-5); padding: 9px var(--space-3); border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); }
|
||||||
|
.page > p + .card-grid, .page > h1 + .card-grid { margin-top: var(--space-5); }
|
||||||
|
.card-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: var(--space-3); }
|
||||||
|
.card-link { display: flex; gap: 14px; padding: var(--space-4); border: 1px solid var(--border); border-radius: var(--radius-card); background: var(--surface); color: var(--fg); text-decoration: none; transition: border-color var(--dur-fast), transform var(--dur-fast); }
|
||||||
|
.card-link:hover { border-color: var(--accent); transform: translateY(-1px); }
|
||||||
|
.card-link-icon { flex: none; display: grid; place-items: center; width: 42px; height: 42px; border-radius: 9px; background: var(--accent-soft); color: var(--accent-text); font: 700 var(--text-base) var(--font-mono); }
|
||||||
|
.card-link-name { font-weight: var(--weight-semibold); margin-bottom: 2px; }
|
||||||
|
.card-link-desc { color: var(--fg-muted); font-size: var(--text-sm); }
|
||||||
|
.card { padding: var(--space-4); border: 1px solid var(--border); border-radius: var(--radius-card); background: var(--surface); }
|
||||||
|
|
||||||
|
/* ---------- screen chrome: toolbar / pane / statusbar ---------- */
|
||||||
|
.screen { display: flex; flex-direction: column; height: 100%; min-height: 0; }
|
||||||
|
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: var(--space-2) var(--space-3); background: var(--surface); border-bottom: 1px solid var(--border); }
|
||||||
|
.divider { width: 1px; height: 22px; margin: 0 var(--space-1); background: var(--border); }
|
||||||
|
.pane { min-width: 0; min-height: 0; overflow: auto; background: var(--surface); }
|
||||||
|
.pane-body { flex: 1; min-height: 0; overflow: auto; padding: var(--space-4); display: flex; flex-direction: column; gap: var(--space-2); }
|
||||||
|
.statusbar { display: flex; align-items: center; gap: var(--space-1); padding: 5px var(--space-3); border-top: 1px solid var(--border); background: var(--surface); font-size: var(--text-xs); min-height: 28px; }
|
||||||
|
.statusbar.ok { color: var(--ok); }
|
||||||
|
.statusbar.error { color: var(--danger); }
|
||||||
|
|
||||||
|
/* Two panes side by side; data-mode='a' or 'b' shows one. */
|
||||||
|
.split { flex: 1; min-height: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 1px; background: var(--border); }
|
||||||
|
.split[data-mode='a'], .split[data-mode='b'] { grid-template-columns: 1fr; }
|
||||||
|
.split[data-mode='a'] > :nth-child(2), .split[data-mode='b'] > :nth-child(1) { display: none; }
|
||||||
|
|
||||||
|
/* ---------- controls ---------- */
|
||||||
|
.btn {
|
||||||
|
display: inline-flex; align-items: center; gap: 6px; height: var(--control-h); padding: 0 11px;
|
||||||
|
border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--surface); color: var(--fg);
|
||||||
|
cursor: pointer; text-decoration: none; font-size: var(--text-sm); white-space: nowrap;
|
||||||
|
}
|
||||||
|
.btn:hover { background: var(--surface-2); }
|
||||||
|
.btn:disabled { opacity: 0.6; cursor: default; }
|
||||||
|
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-fg); font-weight: var(--weight-semibold); }
|
||||||
|
.btn.primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
|
||||||
|
.btn.danger { color: var(--danger); }
|
||||||
|
.btn.small { height: var(--control-h-sm); padding: 0 var(--space-2); font-size: var(--text-xs); }
|
||||||
|
.select { height: var(--control-h); padding: 0 6px; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--surface); font-size: var(--text-sm); }
|
||||||
|
.input, .textarea { width: 100%; padding: 7px 10px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); outline: none; }
|
||||||
|
.input:focus, .textarea:focus { border-color: var(--accent); }
|
||||||
|
.input[aria-invalid='true'], .textarea[aria-invalid='true'] { border-color: var(--danger); }
|
||||||
|
.textarea { padding: var(--space-3) 14px; line-height: var(--leading); resize: vertical; }
|
||||||
|
.textarea.code { font-family: var(--font-mono); font-size: var(--text-sm); white-space: pre; overflow: auto; }
|
||||||
|
.field { display: grid; gap: var(--space-1); }
|
||||||
|
.field > label { font-size: var(--text-sm); font-weight: var(--weight-medium); }
|
||||||
|
.field > .hint { font-size: var(--text-xs); color: var(--fg-muted); }
|
||||||
|
.field > .error { font-size: var(--text-xs); color: var(--danger); }
|
||||||
|
.check { display: inline-flex; align-items: center; gap: 6px; font-size: var(--text-sm); white-space: nowrap; cursor: pointer; }
|
||||||
|
.segmented { display: inline-flex; padding: 2px; border-radius: 7px; background: var(--surface-2); }
|
||||||
|
.segmented button { height: var(--control-h-sm); padding: 0 var(--space-3); border: 0; border-radius: 5px; background: transparent; color: var(--fg-muted); cursor: pointer; font-size: var(--text-sm); }
|
||||||
|
.segmented button[aria-checked='true'] { background: var(--surface); color: var(--fg); font-weight: var(--weight-semibold); box-shadow: var(--shadow-raised); }
|
||||||
|
.linklike { padding: 0; border: 0; background: none; color: inherit; font-weight: var(--weight-semibold); text-decoration: underline; cursor: pointer; }
|
||||||
|
.mini { width: 22px; height: 20px; padding: 0; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--surface); color: var(--fg-muted); cursor: pointer; line-height: 1; }
|
||||||
|
.mini:hover { color: var(--fg); }
|
||||||
|
|
||||||
|
/* ---------- lists and tables ---------- */
|
||||||
|
.list-item { display: flex; align-items: center; gap: var(--space-3); padding: 6px 10px; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--surface); }
|
||||||
|
.list-item + .list-item { margin-top: 6px; }
|
||||||
|
.table-wrap { overflow-x: auto; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); }
|
||||||
|
.table { width: 100%; border-collapse: collapse; font-size: var(--text-sm); }
|
||||||
|
.table th { position: sticky; top: 0; padding: 6px var(--space-3); background: var(--surface-2); border-bottom: 1px solid var(--border); color: var(--fg-muted); font-weight: var(--weight-semibold); text-align: left; white-space: nowrap; }
|
||||||
|
.table td { padding: 6px var(--space-3); border-bottom: 1px solid var(--border); vertical-align: top; }
|
||||||
|
.table tr:last-child td { border-bottom: 0; }
|
||||||
|
.table tbody tr:hover { background: var(--surface-2); }
|
||||||
|
.table tr.selected { background: var(--sel); }
|
||||||
|
.table .num { text-align: right; }
|
||||||
|
|
||||||
|
/* ---------- badges, chips ---------- */
|
||||||
|
.badge { min-width: 20px; height: 20px; padding: 0 6px; border-radius: 10px; background: var(--danger); color: var(--on-danger); font: var(--weight-semibold) var(--text-2xs)/20px var(--font-body); text-align: center; }
|
||||||
|
.chip { display: inline-block; padding: 1px 7px; border-radius: 9px; background: var(--surface-2); color: var(--fg-muted); font-size: var(--text-2xs); font-weight: var(--weight-semibold); }
|
||||||
|
.chip.new, .chip.accent { background: var(--accent-soft); color: var(--accent-text); }
|
||||||
|
.chip.ok { background: var(--ok-soft); color: var(--ok); }
|
||||||
|
.chip.warn { background: var(--warn-soft); color: var(--warn); }
|
||||||
|
.chip.danger { background: var(--danger-soft); color: var(--danger); }
|
||||||
|
|
||||||
|
/* ---------- toasts ---------- */
|
||||||
|
.toasts { position: fixed; right: var(--space-4); bottom: var(--space-4); z-index: var(--z-toast); display: flex; flex-direction: column; gap: var(--space-2); align-items: flex-end; pointer-events: none; }
|
||||||
|
.toast { max-width: min(420px, calc(100vw - 32px)); padding: 9px 14px; border-radius: var(--radius-md); background: var(--fg); color: var(--bg); box-shadow: var(--shadow-popover); font-size: var(--text-sm); animation: toast-in 0.15s ease-out; transition: opacity var(--dur-slow), transform var(--dur-slow); }
|
||||||
|
.toast.error { background: var(--danger); color: var(--on-danger); }
|
||||||
|
.toast.out { opacity: 0; transform: translateY(6px); }
|
||||||
|
@keyframes toast-in { from { opacity: 0; transform: translateY(6px); } }
|
||||||
|
|
||||||
|
/* ---------- dropdown menu ---------- */
|
||||||
|
.dropdown { position: relative; display: inline-flex; }
|
||||||
|
.caret { font-size: 10px; opacity: 0.7; }
|
||||||
|
.menu { position: absolute; top: calc(100% + 4px); right: 0; z-index: var(--z-dropdown); min-width: 200px; padding: var(--space-1); border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); box-shadow: var(--shadow-popover); }
|
||||||
|
.menu-item { display: flex; align-items: center; gap: 10px; width: 100%; padding: 7px var(--space-2); border: 0; border-radius: 5px; background: none; color: var(--fg); text-align: left; cursor: pointer; font-size: var(--text-sm); }
|
||||||
|
.menu-item:hover, .menu-item:focus-visible { background: var(--surface-2); outline: none; }
|
||||||
|
|
||||||
|
/* ---------- modal ---------- */
|
||||||
|
.modal { width: min(560px, calc(100vw - 32px)); max-height: calc(100dvh - 48px); padding: 0; border: 1px solid var(--border); border-radius: var(--radius-lg); background: var(--surface); color: var(--fg); box-shadow: var(--shadow-modal); }
|
||||||
|
.modal.wide { width: min(980px, calc(100vw - 32px)); }
|
||||||
|
.modal::backdrop { background: var(--backdrop); }
|
||||||
|
.modal[open] { display: flex; flex-direction: column; }
|
||||||
|
.modal-head { display: flex; align-items: center; padding: var(--space-3) var(--space-3) var(--space-3) var(--space-5); border-bottom: 1px solid var(--border); }
|
||||||
|
.modal-head h2 { flex: 1; margin: 0; font-size: var(--text-lg); }
|
||||||
|
.modal-body { overflow: auto; padding: var(--space-4) var(--space-5) var(--space-5); }
|
||||||
|
.modal-foot { display: flex; justify-content: flex-end; gap: var(--space-2); padding: var(--space-3) var(--space-5); border-top: 1px solid var(--border); }
|
||||||
|
|
||||||
|
/* ---------- prose (rendered Markdown, help text, long-form) ---------- */
|
||||||
|
.prose { font-size: var(--text-md); line-height: var(--leading-prose); overflow-wrap: break-word; }
|
||||||
|
.prose > :first-child { margin-top: 0; }
|
||||||
|
.prose h1, .prose h2, .prose h3, .prose h4 { margin: 1.4em 0 0.5em; line-height: 1.25; }
|
||||||
|
.prose h1 { font-size: 1.9em; padding-bottom: 0.25em; border-bottom: 1px solid var(--border); }
|
||||||
|
.prose h2 { font-size: 1.45em; padding-bottom: 0.2em; border-bottom: 1px solid var(--border); }
|
||||||
|
.prose h3 { font-size: 1.2em; }
|
||||||
|
.prose p, .prose ul, .prose ol, .prose blockquote, .prose pre, .prose table { margin: 0 0 1em; }
|
||||||
|
.prose ul, .prose ol { padding-left: 1.6em; }
|
||||||
|
.prose li + li { margin-top: 0.25em; }
|
||||||
|
.prose li > input[type='checkbox'] { margin: 0 0.4em 0 -1.3em; vertical-align: middle; }
|
||||||
|
.prose li:has(> input[type='checkbox']) { list-style: none; }
|
||||||
|
.prose code { padding: 0.15em 0.35em; border-radius: var(--radius-sm); background: var(--code-bg); font: 0.88em var(--font-mono); }
|
||||||
|
.prose pre { padding: var(--space-3) 14px; border-radius: var(--radius-md); background: var(--code-bg); overflow: auto; }
|
||||||
|
.prose pre code { padding: 0; background: none; font-size: var(--text-sm); }
|
||||||
|
.prose blockquote { padding: 0 1em; border-left: 3px solid var(--border); color: var(--fg-muted); }
|
||||||
|
.prose table { border-collapse: collapse; display: block; overflow-x: auto; }
|
||||||
|
.prose th, .prose td { padding: 6px var(--space-3); border: 1px solid var(--border); }
|
||||||
|
.prose th { background: var(--surface-2); }
|
||||||
|
.prose img { max-width: 100%; }
|
||||||
|
.prose hr { border: 0; border-top: 1px solid var(--border); margin: 2em 0; }
|
||||||
|
|
||||||
|
/* ---------- code view with line numbers ---------- */
|
||||||
|
.code-view { flex: 1; min-height: 0; display: flex; overflow: auto; background: var(--surface); font: var(--text-sm)/20px var(--font-mono); }
|
||||||
|
.code-lines { flex: none; padding: var(--space-3) 10px var(--space-10); background: var(--surface-2); color: var(--fg-muted); text-align: right; white-space: pre; user-select: none; position: sticky; left: 0; }
|
||||||
|
.code-text { flex: 1; margin: 0; padding: var(--space-3) 14px var(--space-10); font: inherit; white-space: pre; }
|
||||||
|
.code-view.wrap .code-text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||||
|
.code-view.wrap .code-lines { display: none; }
|
||||||
|
.t-key { color: var(--tok-key); }
|
||||||
|
.t-string { color: var(--tok-string); }
|
||||||
|
.t-number { color: var(--tok-number); }
|
||||||
|
.t-boolean { color: var(--tok-bool); }
|
||||||
|
.t-null { color: var(--tok-null); }
|
||||||
|
|
||||||
|
/* ---------- narrow screens ---------- */
|
||||||
|
@media (max-width: 800px) {
|
||||||
|
.shell { grid-template-columns: minmax(0, 1fr); grid-template-areas: 'top' 'main'; }
|
||||||
|
.menu-btn { display: inline-grid; }
|
||||||
|
.sidebar { position: fixed; z-index: var(--z-drawer); top: var(--topbar); bottom: 0; left: 0; width: min(280px, 85vw); transform: translateX(-100%); transition: transform var(--dur-base) ease-out; box-shadow: var(--shadow-popover); }
|
||||||
|
.drawer-open .sidebar { transform: none; }
|
||||||
|
.drawer-open .scrim { display: block; position: fixed; inset: var(--topbar) 0 0 0; z-index: var(--z-scrim); background: var(--scrim); }
|
||||||
|
/* one row that scrolls sideways, so the work area keeps the screen */
|
||||||
|
.toolbar { padding: var(--space-2); flex-wrap: nowrap; overflow-x: auto; scrollbar-width: none; }
|
||||||
|
.toolbar > * { flex: none; }
|
||||||
|
.toolbar > .spacer { flex: 1 0 8px; }
|
||||||
|
.page { padding: var(--space-5) var(--space-4) var(--space-10); }
|
||||||
|
.split:not([data-mode='a']):not([data-mode='b']) { grid-template-columns: 1fr; grid-template-rows: 1fr 1fr; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
*, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; }
|
||||||
|
}
|
||||||
1
app/static/favicon.svg
Normal file
1
app/static/favicon.svg
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><!-- House favicon: the brand tile. Set fill to the project's --accent. --><rect width="32" height="32" rx="7" fill="#3b6ef5"/><text x="16" y="16" dy="0.35em" text-anchor="middle" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" font-size="18" font-weight="700" fill="#fff">◎</text></svg>
|
||||||
|
After Width: | Height: | Size: 373 B |
32
app/static/index.html
Normal file
32
app/static/index.html
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
<!doctype html>
|
||||||
|
<!-- House shell: see references/house.md ("Starting a project") for the placeholders. -->
|
||||||
|
<html lang="en" data-app="network-monitor">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="color-scheme" content="light dark">
|
||||||
|
<title>network monitor</title>
|
||||||
|
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
|
||||||
|
<link rel="stylesheet" href="/static/css/house.css">
|
||||||
|
<link rel="stylesheet" href="/static/css/app.css">
|
||||||
|
<script type="module" src="/static/js/main.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="shell">
|
||||||
|
<header class="topbar">
|
||||||
|
<button class="icon-btn menu-btn" id="menu-btn" type="button" aria-label="Menu" aria-expanded="false">☰</button>
|
||||||
|
<a href="/" class="brand"><span class="brand-mark" aria-hidden="true">◎</span> network monitor</a>
|
||||||
|
<span class="topbar-title" id="topbar-title"></span>
|
||||||
|
<span class="spacer"></span>
|
||||||
|
<button class="icon-btn" id="theme-btn" type="button" aria-label="Theme" title="Theme: auto"></button>
|
||||||
|
</header>
|
||||||
|
<nav class="sidebar" id="sidebar" aria-label="Main">
|
||||||
|
<input type="search" id="nav-filter" class="nav-filter" placeholder="Find… /" aria-label="Find a page">
|
||||||
|
<div id="nav-list"></div>
|
||||||
|
</nav>
|
||||||
|
<div class="scrim" id="scrim"></div>
|
||||||
|
<main id="view" class="view"></main>
|
||||||
|
</div>
|
||||||
|
<div class="toasts" id="toasts" aria-live="polite"></div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
24
app/static/js/api.js
Normal file
24
app/static/js/api.js
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
// Small fetch wrapper: JSON in, JSON out, errors carry the server's message.
|
||||||
|
export async function request(path, { method = 'GET', body, params } = {}) {
|
||||||
|
const url = new URL(path, location.origin);
|
||||||
|
for (const [k, v] of Object.entries(params || {})) if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, v);
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method,
|
||||||
|
headers: { Accept: 'application/json', ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) },
|
||||||
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
let detail = res.statusText;
|
||||||
|
try { const j = await res.json(); detail = typeof j.detail === 'string' ? j.detail : JSON.stringify(j.detail ?? j); } catch {}
|
||||||
|
const err = new Error(detail || `HTTP ${res.status}`);
|
||||||
|
err.status = res.status;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
return res.status === 204 ? null : res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const get = (path, params) => request(path, { params });
|
||||||
|
export const post = (path, body) => request(path, { method: 'POST', body });
|
||||||
|
export const put = (path, body) => request(path, { method: 'PUT', body });
|
||||||
|
export const patch = (path, body) => request(path, { method: 'PATCH', body });
|
||||||
|
export const del = (path, params) => request(path, { method: 'DELETE', params });
|
||||||
214
app/static/js/charts.js
Normal file
214
app/static/js/charts.js
Normal file
|
|
@ -0,0 +1,214 @@
|
||||||
|
// Inline SVG / HTML charts on the house tokens: status strips, line charts, stacked bars,
|
||||||
|
// plus one shared tooltip. Labels go in with textContent only.
|
||||||
|
import { el } from './ui.js';
|
||||||
|
|
||||||
|
const NS = 'http://www.w3.org/2000/svg';
|
||||||
|
export function s(tag, attrs = {}, ...kids) {
|
||||||
|
const n = document.createElementNS(NS, tag);
|
||||||
|
for (const [k, v] of Object.entries(attrs)) if (v != null) n.setAttribute(k, v);
|
||||||
|
for (const c of kids.flat()) if (c != null) n.append(c);
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- status ----------
|
||||||
|
|
||||||
|
export const STATUS = {
|
||||||
|
ok: { label: 'OK', chip: 'ok' },
|
||||||
|
degraded: { label: 'Degraded', chip: 'warn' },
|
||||||
|
down: { label: 'Down', chip: 'danger' },
|
||||||
|
nodata: { label: 'No data', chip: '' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export function statusChip(st, text) {
|
||||||
|
const x = STATUS[st] || STATUS.nodata;
|
||||||
|
return el(`span.chip${x.chip ? `.${x.chip}` : ''}`, {}, text || x.label);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function statusLegend() {
|
||||||
|
return el('div.viz-legend', { 'aria-label': 'Legend' },
|
||||||
|
...['ok', 'degraded', 'down', 'nodata'].map((k) => el('span.viz-legend-item', {}, el(`span.viz-swatch.s-${k}`), STATUS[k].label)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function seriesLegend(items, kind = 'line') {
|
||||||
|
return el('div.viz-legend', {},
|
||||||
|
...items.map((it) => el('span.viz-legend-item', {}, el(`span.${kind === 'line' ? 'viz-linekey' : 'viz-swatch'}`, { style: `background:${it.color}` }), it.name)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- tooltip ----------
|
||||||
|
|
||||||
|
let tip;
|
||||||
|
export function showTip(x, y, content) {
|
||||||
|
if (!tip) {
|
||||||
|
tip = el('div.viz-tip', { role: 'tooltip', hidden: true });
|
||||||
|
document.body.append(tip);
|
||||||
|
}
|
||||||
|
tip.replaceChildren(...content.filter(Boolean));
|
||||||
|
tip.hidden = false;
|
||||||
|
const r = tip.getBoundingClientRect();
|
||||||
|
let left = x + 14;
|
||||||
|
if (left + r.width > innerWidth - 8) left = x - 14 - r.width;
|
||||||
|
let top = y + 14;
|
||||||
|
if (top + r.height > innerHeight - 8) top = y - 14 - r.height;
|
||||||
|
tip.style.left = `${Math.max(8, left)}px`;
|
||||||
|
tip.style.top = `${Math.max(8, top)}px`;
|
||||||
|
}
|
||||||
|
export function hideTip() { if (tip) tip.hidden = true; }
|
||||||
|
export const tipTitle = (t) => el('div.viz-tip-title', {}, t);
|
||||||
|
export const tipRow = (value, label, color, kind = 'line') =>
|
||||||
|
el('div.viz-tip-row', {}, color ? el(`span.${kind === 'line' ? 'viz-linekey' : 'viz-swatch'}`, { style: `background:${color}` }) : null,
|
||||||
|
el('strong', {}, value), label ? el('span.muted', {}, label) : null);
|
||||||
|
|
||||||
|
function hover(target, describe) {
|
||||||
|
target.addEventListener('pointermove', (e) => { const c = describe(e); if (c) showTip(e.clientX, e.clientY, c); else hideTip(); });
|
||||||
|
target.addEventListener('pointerleave', hideTip);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- status strip: one cell per time bucket ----------
|
||||||
|
|
||||||
|
/** buckets: [{s, n, down, slow, latency} | null]; describe(i, bucket) -> tooltip nodes */
|
||||||
|
export function strip(buckets, describe) {
|
||||||
|
const n = buckets.length;
|
||||||
|
const wrap = el('div.strip', { style: `--n:${n}` });
|
||||||
|
for (const b of buckets) wrap.append(el(`span.s-${b ? b.s : 'nodata'}`));
|
||||||
|
hover(wrap, (e) => {
|
||||||
|
const r = wrap.getBoundingClientRect();
|
||||||
|
const i = Math.min(n - 1, Math.max(0, Math.floor(((e.clientX - r.left) / r.width) * n)));
|
||||||
|
return describe(i, buckets[i]);
|
||||||
|
});
|
||||||
|
return wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- responsive SVG helper ----------
|
||||||
|
|
||||||
|
function responsive(draw, height) {
|
||||||
|
const box = el('div.chart', { style: `height:${height}px` });
|
||||||
|
let last = 0;
|
||||||
|
const ro = new ResizeObserver(() => {
|
||||||
|
const w = Math.floor(box.clientWidth);
|
||||||
|
if (w && w !== last) { last = w; box.replaceChildren(draw(w)); }
|
||||||
|
});
|
||||||
|
ro.observe(box);
|
||||||
|
return box;
|
||||||
|
}
|
||||||
|
|
||||||
|
function niceMax(v) {
|
||||||
|
if (!(v > 0)) return 1;
|
||||||
|
const p = 10 ** Math.floor(Math.log10(v));
|
||||||
|
for (const m of [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) if (v <= m * p) return m * p;
|
||||||
|
return 10 * p;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- line chart ----------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* lineChart({ n, xLabel(i), series: [{name, color, values}], marks: [count per bucket],
|
||||||
|
* fmt(v), height, describe(i) -> extra tooltip nodes })
|
||||||
|
* Gaps (null) break the line. `marks` draws failure ticks along the baseline.
|
||||||
|
*/
|
||||||
|
export function lineChart(o) {
|
||||||
|
const H = o.height || 150;
|
||||||
|
return responsive((W) => {
|
||||||
|
const padL = 48, padR = o.series.length > 1 ? 64 : 14, padT = 10, padB = 24;
|
||||||
|
const iw = Math.max(10, W - padL - padR), ih = H - padT - padB;
|
||||||
|
const n = o.n;
|
||||||
|
const all = o.series.flatMap((x) => x.values).filter((v) => v != null);
|
||||||
|
const max = niceMax(Math.max(0, ...all));
|
||||||
|
const x = (i) => padL + ((i + 0.5) / n) * iw;
|
||||||
|
const y = (v) => padT + ih - (v / max) * ih;
|
||||||
|
const g = s('svg', { width: W, height: H, viewBox: `0 0 ${W} ${H}`, class: 'viz', role: 'img', 'aria-label': o.label || 'Chart' });
|
||||||
|
|
||||||
|
for (const t of [0, max / 2, max]) {
|
||||||
|
g.append(s('line', { x1: padL, x2: padL + iw, y1: y(t), y2: y(t), class: t === 0 ? 'viz-axis' : 'viz-grid' }));
|
||||||
|
g.append(s('text', { x: padL - 6, y: y(t), dy: '0.32em', 'text-anchor': 'end', class: 'viz-tick' }, o.fmt(t)));
|
||||||
|
}
|
||||||
|
for (const i of [0, Math.floor((n - 1) / 2), n - 1]) {
|
||||||
|
g.append(s('text', { x: x(i), y: H - 6, 'text-anchor': i === 0 ? 'start' : i === n - 1 ? 'end' : 'middle', class: 'viz-tick' }, o.xLabel(i)));
|
||||||
|
}
|
||||||
|
(o.marks || []).forEach((m, i) => {
|
||||||
|
if (m) g.append(s('rect', { x: x(i) - 1.5, y: padT + ih - 7, width: 3, height: 7, rx: 1, class: 'viz-fail' }));
|
||||||
|
});
|
||||||
|
|
||||||
|
const labels = [];
|
||||||
|
for (const ser of o.series) {
|
||||||
|
let d = '';
|
||||||
|
ser.values.forEach((v, i) => {
|
||||||
|
if (v == null) return;
|
||||||
|
const prev = ser.values[i - 1];
|
||||||
|
d += `${prev == null ? 'M' : 'L'}${x(i).toFixed(1)},${y(v).toFixed(1)}`;
|
||||||
|
const next = ser.values[i + 1];
|
||||||
|
if (prev == null && next == null) g.append(s('circle', { cx: x(i), cy: y(v), r: 2.5, fill: ser.color }));
|
||||||
|
});
|
||||||
|
if (d) g.append(s('path', { d, fill: 'none', stroke: ser.color, 'stroke-width': 2, 'stroke-linejoin': 'round', 'stroke-linecap': 'round' }));
|
||||||
|
const li = ser.values.findLastIndex((v) => v != null);
|
||||||
|
if (o.series.length > 1 && li >= 0) labels.push({ y: y(ser.values[li]), text: ser.name, x: x(li) });
|
||||||
|
}
|
||||||
|
// Direct end labels; skip any that would collide (the legend still names it).
|
||||||
|
labels.sort((a, b) => a.y - b.y);
|
||||||
|
let lastY = -99;
|
||||||
|
for (const l of labels) {
|
||||||
|
if (l.y - lastY < 13) continue;
|
||||||
|
lastY = l.y;
|
||||||
|
g.append(s('text', { x: padL + iw + 6, y: l.y, dy: '0.32em', class: 'viz-label' }, l.text));
|
||||||
|
}
|
||||||
|
|
||||||
|
const cross = s('line', { y1: padT, y2: padT + ih, class: 'viz-cross', visibility: 'hidden' });
|
||||||
|
const hit = s('rect', { x: padL, y: 0, width: iw, height: H, fill: 'transparent' });
|
||||||
|
g.append(cross, hit);
|
||||||
|
hit.addEventListener('pointermove', (e) => {
|
||||||
|
const r = hit.getBoundingClientRect();
|
||||||
|
const i = Math.min(n - 1, Math.max(0, Math.floor(((e.clientX - r.left) / r.width) * n)));
|
||||||
|
cross.setAttribute('x1', x(i)); cross.setAttribute('x2', x(i)); cross.setAttribute('visibility', 'visible');
|
||||||
|
showTip(e.clientX, e.clientY, [tipTitle(o.xLabel(i, true)),
|
||||||
|
...o.series.map((ser) => tipRow(ser.values[i] == null ? 'no data' : o.fmt(ser.values[i]), o.series.length > 1 ? ser.name : '', ser.color)),
|
||||||
|
...(o.describe ? o.describe(i) : [])]);
|
||||||
|
});
|
||||||
|
hit.addEventListener('pointerleave', () => { cross.setAttribute('visibility', 'hidden'); hideTip(); });
|
||||||
|
return g;
|
||||||
|
}, H);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- stacked bars ----------
|
||||||
|
|
||||||
|
function topRounded(x, y, w, h, r) {
|
||||||
|
r = Math.min(r, h, w / 2);
|
||||||
|
return `M${x},${y + h}V${y + r}Q${x},${y} ${x + r},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + h}Z`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** stackedBars({ n, xLabel(i), series: [{name, color, values}], height }) – bottom series first. */
|
||||||
|
export function stackedBars(o) {
|
||||||
|
const H = o.height || 150;
|
||||||
|
return responsive((W) => {
|
||||||
|
const padL = 40, padR = 10, padT = 10, padB = 24;
|
||||||
|
const iw = Math.max(10, W - padL - padR), ih = H - padT - padB;
|
||||||
|
const n = o.n;
|
||||||
|
const totals = Array.from({ length: n }, (_, i) => o.series.reduce((a, ser) => a + (ser.values[i] || 0), 0));
|
||||||
|
const max = niceMax(Math.max(1, ...totals));
|
||||||
|
const slot = iw / n, bw = Math.min(24, slot * 0.7);
|
||||||
|
const y = (v) => padT + ih - (v / max) * ih;
|
||||||
|
const g = s('svg', { width: W, height: H, viewBox: `0 0 ${W} ${H}`, class: 'viz', role: 'img', 'aria-label': o.label || 'Chart' });
|
||||||
|
for (const t of [0, max / 2, max]) {
|
||||||
|
g.append(s('line', { x1: padL, x2: padL + iw, y1: y(t), y2: y(t), class: t === 0 ? 'viz-axis' : 'viz-grid' }));
|
||||||
|
g.append(s('text', { x: padL - 6, y: y(t), dy: '0.32em', 'text-anchor': 'end', class: 'viz-tick' }, Math.round(t).toLocaleString()));
|
||||||
|
}
|
||||||
|
for (const i of [0, Math.floor((n - 1) / 2), n - 1]) {
|
||||||
|
g.append(s('text', { x: padL + slot * (i + 0.5), y: H - 6, 'text-anchor': i === 0 ? 'start' : i === n - 1 ? 'end' : 'middle', class: 'viz-tick' }, o.xLabel(i)));
|
||||||
|
}
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const bx = padL + slot * i + (slot - bw) / 2;
|
||||||
|
let acc = 0;
|
||||||
|
const segs = o.series.map((ser) => ({ ser, v: ser.values[i] || 0 })).filter((x) => x.v > 0);
|
||||||
|
segs.forEach((seg, k) => {
|
||||||
|
const y0 = y(acc), y1 = y(acc + seg.v);
|
||||||
|
const gap = k > 0 ? 2 : 0;
|
||||||
|
const h = Math.max(0, y0 - y1 - gap);
|
||||||
|
const top = k === segs.length - 1;
|
||||||
|
g.append(top ? s('path', { d: topRounded(bx, y1, bw, h, 4), fill: seg.ser.color }) : s('rect', { x: bx, y: y1, width: bw, height: h, fill: seg.ser.color }));
|
||||||
|
acc += seg.v;
|
||||||
|
});
|
||||||
|
const hit = s('rect', { x: padL + slot * i, y: padT, width: slot, height: ih, fill: 'transparent', class: 'viz-hit' });
|
||||||
|
hover(hit, () => [tipTitle(o.xLabel(i, true)), ...o.series.map((ser) => tipRow((ser.values[i] || 0).toLocaleString(), ser.name, ser.color, 'box'))]);
|
||||||
|
g.append(hit);
|
||||||
|
}
|
||||||
|
return g;
|
||||||
|
}, H);
|
||||||
|
}
|
||||||
75
app/static/js/common.js
Normal file
75
app/static/js/common.js
Normal file
|
|
@ -0,0 +1,75 @@
|
||||||
|
// Shared bits for the views.
|
||||||
|
import { el } from './ui.js';
|
||||||
|
|
||||||
|
/** The screen frame: toolbar, scrolling pane, status bar. Returns the parts. */
|
||||||
|
export function screen(root, toolbarItems) {
|
||||||
|
const toolbar = el('div.toolbar', {}, ...toolbarItems);
|
||||||
|
const body = el('div.content');
|
||||||
|
const pane = el('div.pane.fill', {}, body);
|
||||||
|
const status = el('div.statusbar', {}, 'Loading…');
|
||||||
|
root.append(el('div.screen', {}, toolbar, pane, status));
|
||||||
|
return {
|
||||||
|
toolbar, body, pane, status,
|
||||||
|
setStatus(text, kind = '') { status.textContent = text; status.className = `statusbar${kind ? ` ${kind}` : ''}`; },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** replaceChildren without the "null" text nodes the DOM makes from empty slots. */
|
||||||
|
export function fill(node, ...children) {
|
||||||
|
node.replaceChildren(...children.flat().filter((c) => c != null && c !== false));
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const section = (title, hint, ...extra) =>
|
||||||
|
el('div.section-head', {}, el('h2.section-title', {}, title), hint ? el('span.hint', {}, hint) : null, ...extra);
|
||||||
|
|
||||||
|
export function table(headers, rows, { empty = 'Nothing to show.' } = {}) {
|
||||||
|
if (!rows.length) return el('div.callout', {}, empty);
|
||||||
|
return el('div.table-wrap', {},
|
||||||
|
el('table.table', {},
|
||||||
|
el('thead', {}, el('tr', {}, ...headers.map((h) => (typeof h === 'string' ? el('th', {}, h) : el('th', h.props || {}, h.text))))),
|
||||||
|
el('tbody', {}, ...rows)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function errorBox(err, hint) {
|
||||||
|
return el('div.callout.error', { role: 'alert' }, err.message || String(err), hint ? el('div.small.muted', {}, hint) : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A notice for AdGuard-backed views when it isn't set up or reachable. */
|
||||||
|
export function adguardProblem(err) {
|
||||||
|
if (err.status === 503) {
|
||||||
|
return el('div.empty', {},
|
||||||
|
el('p', {}, 'AdGuard Home isn’t connected yet.'),
|
||||||
|
el('p.small', {}, 'Set ADGUARD_URL, ADGUARD_USERNAME and ADGUARD_PASSWORD in the hub’s .env, then restart the hub. Settings shows where that file is.'),
|
||||||
|
el('a.btn', { href: '/settings' }, 'Open settings'));
|
||||||
|
}
|
||||||
|
return errorBox(err, err.status === 502 ? 'Check that AdGuard Home is running and the hub’s .env points at its web address.' : '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export const domainLink = (d) => el('a.domain', { href: `/domains/${encodeURIComponent(d)}` }, d);
|
||||||
|
|
||||||
|
export function clientLink(ip, device, fallbackName) {
|
||||||
|
const name = device?.name || fallbackName || ip;
|
||||||
|
const href = device ? `/clients/${encodeURIComponent(device.key)}` : `/queries?ip=${encodeURIComponent(ip)}`;
|
||||||
|
return el('span.chips', {},
|
||||||
|
el('a', { href, title: ip }, name),
|
||||||
|
name !== ip ? el('span.muted.small', {}, ip) : null,
|
||||||
|
device?.suspicious ? el('span.chip.danger', {}, 'Suspicious') : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resultChip(r) {
|
||||||
|
if (r.blocked) return el('span.chip.danger', { title: r.rule || r.reason }, 'Blocked');
|
||||||
|
if (r.reason?.startsWith('Rewrite') || r.reason === 'FilteredSafeSearch') return el('span.chip.accent', { title: r.reason }, 'Rewritten');
|
||||||
|
if (r.reason === 'NotFilteredWhiteList') return el('span.chip.ok', { title: r.rule }, 'Allowed by rule');
|
||||||
|
if (r.status && r.status !== 'NOERROR') return el('span.chip.warn', {}, r.status);
|
||||||
|
return el('span.chip', {}, 'OK');
|
||||||
|
}
|
||||||
|
|
||||||
|
export const RANGES = [['1h', '1 h'], ['6h', '6 h'], ['24h', '24 h'], ['7d', '7 d'], ['30d', '30 d']];
|
||||||
|
export const SPANS = { '1h': 3600, '6h': 21600, '24h': 86400, '7d': 604800, '30d': 2592000 };
|
||||||
|
|
||||||
|
/** Re-run fn every `ms` while the tab is visible; returns a stop function. */
|
||||||
|
export function every(ms, fn) {
|
||||||
|
const t = setInterval(() => { if (!document.hidden) fn(); }, ms);
|
||||||
|
return () => clearInterval(t);
|
||||||
|
}
|
||||||
32
app/static/js/fmt.js
Normal file
32
app/static/js/fmt.js
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
// Formatting for times, durations and measurements.
|
||||||
|
export const dash = '—';
|
||||||
|
|
||||||
|
export function ago(ts) {
|
||||||
|
if (!ts) return dash;
|
||||||
|
const s = Date.now() / 1000 - ts;
|
||||||
|
if (s < 45) return 'just now';
|
||||||
|
if (s < 3600) return `${Math.round(s / 60)} min ago`;
|
||||||
|
if (s < 86400) return `${Math.round(s / 3600)} h ago`;
|
||||||
|
return `${Math.round(s / 86400)} d ago`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const clock = (ts) => new Date(ts * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||||
|
export const hm = (ts) => new Date(ts * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||||
|
export const when = (ts) => (ts ? new Date(ts * 1000).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : dash);
|
||||||
|
export const day = (ts) => new Date(ts * 1000).toLocaleDateString([], { month: 'short', day: 'numeric' });
|
||||||
|
|
||||||
|
export function dur(s) {
|
||||||
|
if (s == null) return dash;
|
||||||
|
if (s < 60) return `${Math.round(s)} s`;
|
||||||
|
if (s < 3600) return `${Math.round(s / 60)} min`;
|
||||||
|
if (s < 86400) return `${(s / 3600).toFixed(1)} h`;
|
||||||
|
return `${(s / 86400).toFixed(1)} d`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ms = (v) => (v == null ? dash : v < 10 ? `${v.toFixed(1)} ms` : `${Math.round(v).toLocaleString()} ms`);
|
||||||
|
export const pct = (v, digits = 0) => (v == null ? dash : `${(v * 100).toFixed(digits)}%`);
|
||||||
|
export const num = (n) => (n == null ? dash : Number(n).toLocaleString());
|
||||||
|
export const mbps = (v) => (v == null ? dash : `${v < 10 ? v.toFixed(1) : Math.round(v)} Mbps`);
|
||||||
|
|
||||||
|
/** A time label fitting the span: clock for short ranges, date + hour for long ones. */
|
||||||
|
export const axisTime = (span) => (ts) => (span > 2 * 86400 ? `${day(ts)} ${hm(ts)}` : hm(ts));
|
||||||
38
app/static/js/main.js
Normal file
38
app/static/js/main.js
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
// Plain ES modules, no bundler.
|
||||||
|
import { startShell } from './shell.js';
|
||||||
|
import { get } from './api.js';
|
||||||
|
|
||||||
|
let offline = 0;
|
||||||
|
|
||||||
|
startShell({
|
||||||
|
name: 'network monitor',
|
||||||
|
categories: ['Network', 'DNS', 'Hub'],
|
||||||
|
views: [
|
||||||
|
{ id: 'health', name: 'Network health', path: '/', category: 'Network', icon: '◎',
|
||||||
|
description: 'Mesh and internet health as the probes see it: now, over time, and every outage.', load: () => import('./views/health.js') },
|
||||||
|
{ id: 'probes', name: 'Probes', path: '/probes', category: 'Network', icon: 'P',
|
||||||
|
description: 'Add, place and remove the machines that test the network.', load: () => import('./views/probes.js'),
|
||||||
|
badge: () => offline },
|
||||||
|
{ id: 'clients', name: 'Clients', path: '/clients', category: 'DNS', icon: '▣',
|
||||||
|
description: 'Every device seen on the network, with your names, categories and flags.', load: () => import('./views/clients.js') },
|
||||||
|
{ id: 'queries', name: 'Query log', path: '/queries', category: 'DNS', icon: 'Q?',
|
||||||
|
description: 'Sift through DNS requests from AdGuard Home.', load: () => import('./views/queries.js') },
|
||||||
|
{ id: 'domains', name: 'Domains', path: '/domains', category: 'DNS', icon: '.com',
|
||||||
|
description: 'Most requested domains, and who asks for each one.', load: () => import('./views/domains.js') },
|
||||||
|
{ id: 'blocked', name: 'Blocked domains', path: '/blocked', category: 'DNS', icon: '⊘',
|
||||||
|
description: 'What AdGuard Home blocked, how often, and for whom.', load: () => import('./views/blocked.js') },
|
||||||
|
{ id: 'settings', name: 'Settings', path: '/settings', category: 'Hub', icon: '⚙',
|
||||||
|
description: 'What the hub tests, its thresholds and its AdGuard connection.', load: () => import('./views/settings.js') },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Offline probes show as a count on the Probes nav item.
|
||||||
|
async function pollProbes() {
|
||||||
|
try {
|
||||||
|
const { probes } = await get('/api/probes');
|
||||||
|
offline = probes.filter((p) => !p.online).length;
|
||||||
|
window.dispatchEvent(new Event('app:badges'));
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
pollProbes();
|
||||||
|
setInterval(pollProbes, 60000);
|
||||||
278
app/static/js/shell.js
Normal file
278
app/static/js/shell.js
Normal file
|
|
@ -0,0 +1,278 @@
|
||||||
|
// House app shell: top bar, sidebar nav (a drawer on phones), theme toggle,
|
||||||
|
// "/" to find a view, client-side routing and a home grid, all built from one
|
||||||
|
// list of views. Copy into the project (e.g. static/js/shell.js) unchanged and
|
||||||
|
// call startShell() from the project's own main.js. Expects the markup in
|
||||||
|
// index.html (ids: view, nav-list, nav-filter, topbar-title, theme-btn,
|
||||||
|
// menu-btn, scrim, sidebar).
|
||||||
|
//
|
||||||
|
// A view: {
|
||||||
|
// id, name, path, // path '/x' owns /x and everything under /x/
|
||||||
|
// category, icon, // sidebar group; 1-3 character monogram ('{ }', 'M↓', '⎘')
|
||||||
|
// description, // home card text and nav search
|
||||||
|
// load: () => import('./views/x.js'), // module exports mount(root, ctx)
|
||||||
|
// badge?: () => number, // count on the nav item; dispatch 'app:badges' on window when it changes
|
||||||
|
// }
|
||||||
|
// mount(root, ctx) may return a cleanup function. ctx = {
|
||||||
|
// rest, // path after the view's own, e.g. "abc123" for /paste/abc123
|
||||||
|
// query, // URLSearchParams of the current URL
|
||||||
|
// navigate, // navigate('/x/abc'): client-side navigation
|
||||||
|
// setTitle, // setTitle('abc123'): extra text in the top bar and tab title
|
||||||
|
// }
|
||||||
|
// A view with path '/' replaces the home grid.
|
||||||
|
import { el, store } from './ui.js';
|
||||||
|
|
||||||
|
const $ = (id) => document.getElementById(id);
|
||||||
|
let cfg, cleanup = null, routeSeq = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* startShell({
|
||||||
|
* name: 'tools', // shown in the tab title
|
||||||
|
* views: [...],
|
||||||
|
* categories: ['Text', 'Data'], // sidebar order; unknown ones go last, alphabetically
|
||||||
|
* home: { title, intro }, // the home page heading and one-line description
|
||||||
|
* sidebar: true, // false: top bar only (single-screen apps)
|
||||||
|
* passthrough: ['/api/', '/static/'], // same-origin links the router must leave alone
|
||||||
|
* })
|
||||||
|
*/
|
||||||
|
export function startShell(options) {
|
||||||
|
cfg = { categories: [], sidebar: true, passthrough: ['/api/', '/static/'], home: {}, ...options };
|
||||||
|
setupTheme();
|
||||||
|
if (cfg.sidebar) setupNav();
|
||||||
|
else document.querySelector('.shell')?.classList.add('bare');
|
||||||
|
setupLinks();
|
||||||
|
route();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- theme: auto → light → dark, remembered per browser ----------
|
||||||
|
|
||||||
|
const THEMES = ['auto', 'light', 'dark'];
|
||||||
|
const svg = (d) => `<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${d}</svg>`;
|
||||||
|
const THEME_ICON = {
|
||||||
|
auto: svg('<circle cx="12" cy="12" r="9"/><path d="M12 3v18" /><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor"/>'),
|
||||||
|
light: svg('<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>'),
|
||||||
|
dark: svg('<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/>'),
|
||||||
|
};
|
||||||
|
|
||||||
|
function setupTheme() {
|
||||||
|
const btn = $('theme-btn');
|
||||||
|
let theme = store.get('theme', 'auto');
|
||||||
|
const apply = (t) => {
|
||||||
|
if (t === 'auto') delete document.documentElement.dataset.theme;
|
||||||
|
else document.documentElement.dataset.theme = t;
|
||||||
|
if (btn) {
|
||||||
|
btn.innerHTML = THEME_ICON[t];
|
||||||
|
btn.title = `Theme: ${t}`;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
apply(theme);
|
||||||
|
btn?.addEventListener('click', () => {
|
||||||
|
theme = THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length];
|
||||||
|
store.set('theme', theme);
|
||||||
|
apply(theme);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- navigation ----------
|
||||||
|
|
||||||
|
function grouped(views) {
|
||||||
|
const groups = new Map();
|
||||||
|
for (const v of views) {
|
||||||
|
const c = v.category || 'Other';
|
||||||
|
if (!groups.has(c)) groups.set(c, []);
|
||||||
|
groups.get(c).push(v);
|
||||||
|
}
|
||||||
|
const rank = (c) => (cfg.categories.includes(c) ? cfg.categories.indexOf(c) : 999);
|
||||||
|
return [...groups].sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
function matches(v, q) {
|
||||||
|
q = q.trim().toLowerCase();
|
||||||
|
return !q || `${v.name} ${v.description || ''} ${v.category || ''}`.toLowerCase().includes(q);
|
||||||
|
}
|
||||||
|
|
||||||
|
const listed = () => cfg.views.filter((v) => v.path !== '/');
|
||||||
|
|
||||||
|
function renderNav() {
|
||||||
|
const q = $('nav-filter').value;
|
||||||
|
const homeView = cfg.views.find((v) => v.path === '/');
|
||||||
|
$('nav-list').replaceChildren(
|
||||||
|
el('a.nav-item', { href: '/', dataset: { path: '/' } },
|
||||||
|
el('span.nav-icon', {}, homeView?.icon || '⌂'), el('span.nav-label', {}, homeView?.name || 'Home')),
|
||||||
|
...grouped(listed().filter((v) => matches(v, q))).map(([cat, views]) =>
|
||||||
|
el('div.nav-group', {},
|
||||||
|
el('div.nav-heading', {}, cat),
|
||||||
|
views.map((v) => el('a.nav-item', { href: v.path, dataset: { path: v.path, view: v.id } },
|
||||||
|
el('span.nav-icon', {}, v.icon), el('span.nav-label', {}, v.name), v.badge ? el('span.badge', { hidden: true }) : null)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
markActive();
|
||||||
|
updateBadges();
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateBadges() {
|
||||||
|
if (!cfg.sidebar) return;
|
||||||
|
let total = 0;
|
||||||
|
for (const v of cfg.views) {
|
||||||
|
if (!v.badge) continue;
|
||||||
|
let n = 0;
|
||||||
|
try { n = v.badge() || 0; } catch {}
|
||||||
|
total += n;
|
||||||
|
const b = $('nav-list').querySelector(`.nav-item[data-view="${v.id}"] .badge`);
|
||||||
|
if (b) {
|
||||||
|
b.hidden = !n;
|
||||||
|
b.textContent = n > 99 ? '99+' : String(n);
|
||||||
|
b.title = `${n} new`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$('menu-btn')?.classList.toggle('has-badge', total > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function markActive() {
|
||||||
|
if (!cfg.sidebar) return;
|
||||||
|
const view = findView(location.pathname);
|
||||||
|
for (const a of $('nav-list').querySelectorAll('.nav-item')) {
|
||||||
|
const on = view ? a.dataset.path === view.path : a.dataset.path === '/';
|
||||||
|
a.classList.toggle('active', on);
|
||||||
|
if (on) a.setAttribute('aria-current', 'page');
|
||||||
|
else a.removeAttribute('aria-current');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setDrawer(open) {
|
||||||
|
document.body.classList.toggle('drawer-open', open);
|
||||||
|
$('menu-btn')?.setAttribute('aria-expanded', String(open));
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupNav() {
|
||||||
|
const filter = $('nav-filter');
|
||||||
|
filter.addEventListener('input', renderNav);
|
||||||
|
filter.addEventListener('keydown', (e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
const first = listed().find((v) => matches(v, filter.value));
|
||||||
|
if (first) {
|
||||||
|
filter.value = '';
|
||||||
|
renderNav();
|
||||||
|
setDrawer(false);
|
||||||
|
navigate(first.path);
|
||||||
|
}
|
||||||
|
} else if (e.key === 'Escape') {
|
||||||
|
filter.value = '';
|
||||||
|
renderNav();
|
||||||
|
filter.blur();
|
||||||
|
setDrawer(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
document.addEventListener('keydown', (e) => {
|
||||||
|
const a = document.activeElement;
|
||||||
|
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(a?.tagName) || a?.isContentEditable;
|
||||||
|
if (e.key === '/' && !typing && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
setDrawer(true);
|
||||||
|
filter.focus();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
$('menu-btn')?.addEventListener('click', () => setDrawer(!document.body.classList.contains('drawer-open')));
|
||||||
|
$('scrim')?.addEventListener('click', () => setDrawer(false));
|
||||||
|
window.addEventListener('app:badges', updateBadges);
|
||||||
|
window.addEventListener('storage', (e) => { if (!e.key || e.key.startsWith(store.prefix)) updateBadges(); }); // other tabs
|
||||||
|
setInterval(updateBadges, 60000);
|
||||||
|
renderNav();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- routing ----------
|
||||||
|
|
||||||
|
function findView(pathname) {
|
||||||
|
return cfg.views.find((v) => (v.path === '/' ? pathname === '/' : pathname === v.path || pathname.startsWith(`${v.path}/`)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function navigate(path, { replace = false } = {}) {
|
||||||
|
if (path === location.pathname + location.search) return;
|
||||||
|
history[replace ? 'replaceState' : 'pushState']({}, '', path);
|
||||||
|
route();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupLinks() {
|
||||||
|
document.addEventListener('click', (e) => {
|
||||||
|
const a = e.target.closest('a[href]');
|
||||||
|
if (!a || a.target || a.hasAttribute('download') || e.defaultPrevented) return;
|
||||||
|
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
||||||
|
const url = new URL(a.href, location.href);
|
||||||
|
if (url.origin !== location.origin || cfg.passthrough.some((p) => url.pathname.startsWith(p))) return;
|
||||||
|
if (url.pathname === location.pathname && url.search === location.search && url.hash) return; // in-page anchor
|
||||||
|
e.preventDefault();
|
||||||
|
setDrawer(false);
|
||||||
|
navigate(url.pathname + url.search);
|
||||||
|
});
|
||||||
|
window.addEventListener('popstate', route);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setTitle(view, extra) {
|
||||||
|
const isHome = !view || view.path === '/';
|
||||||
|
const t = $('topbar-title');
|
||||||
|
if (t) t.textContent = isHome ? '' : [view.name, extra].filter(Boolean).join(' · ');
|
||||||
|
document.title = isHome ? cfg.name : `${[extra, view.name].filter(Boolean).join(' · ')} — ${cfg.name}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function route() {
|
||||||
|
const seq = ++routeSeq;
|
||||||
|
if (cleanup) {
|
||||||
|
try { cleanup(); } catch (err) { console.error(err); }
|
||||||
|
cleanup = null;
|
||||||
|
}
|
||||||
|
markActive();
|
||||||
|
const root = $('view');
|
||||||
|
const view = findView(location.pathname);
|
||||||
|
document.body.dataset.view = view ? view.id : 'home';
|
||||||
|
if (!view) {
|
||||||
|
if (location.pathname !== '/') history.replaceState({}, '', '/');
|
||||||
|
setTitle(null);
|
||||||
|
renderHome(root);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setTitle(view);
|
||||||
|
root.replaceChildren(el('div.loading', {}, 'Loading…'));
|
||||||
|
try {
|
||||||
|
const mod = await view.load();
|
||||||
|
if (seq !== routeSeq) return; // navigated away while loading
|
||||||
|
root.replaceChildren();
|
||||||
|
const ctx = {
|
||||||
|
rest: view.path === '/' ? '' : location.pathname.slice(view.path.length).replace(/^\//, ''),
|
||||||
|
query: new URLSearchParams(location.search),
|
||||||
|
navigate,
|
||||||
|
setTitle: (extra) => setTitle(view, extra),
|
||||||
|
};
|
||||||
|
cleanup = (await mod.mount(root, ctx)) || null;
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
if (seq === routeSeq) root.replaceChildren(el('div.empty', {}, `Couldn't load ${view.name}: ${err.message}`));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderHome(root) {
|
||||||
|
const filter = el('input.page-filter', { type: 'search', placeholder: 'Find…', 'aria-label': 'Filter' });
|
||||||
|
const grid = el('div.card-grid');
|
||||||
|
const draw = () =>
|
||||||
|
grid.replaceChildren(
|
||||||
|
...listed().filter((v) => matches(v, filter.value)).map((v) =>
|
||||||
|
el('a.card-link', { href: v.path },
|
||||||
|
el('div.card-link-icon', { 'aria-hidden': 'true' }, v.icon),
|
||||||
|
el('div', {}, el('div.card-link-name', {}, v.name), el('div.card-link-desc', {}, v.description || '')),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
filter.addEventListener('input', draw);
|
||||||
|
filter.addEventListener('keydown', (e) => {
|
||||||
|
const first = e.key === 'Enter' && grid.querySelector('a');
|
||||||
|
if (first) navigate(new URL(first.href).pathname);
|
||||||
|
});
|
||||||
|
draw();
|
||||||
|
root.replaceChildren(
|
||||||
|
el('div.page', {},
|
||||||
|
el('h1', {}, cfg.home.title || cfg.name),
|
||||||
|
cfg.home.intro ? el('p.muted', {}, cfg.home.intro) : null,
|
||||||
|
listed().length > 6 ? filter : null,
|
||||||
|
grid,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
253
app/static/js/ui.js
Normal file
253
app/static/js/ui.js
Normal file
|
|
@ -0,0 +1,253 @@
|
||||||
|
// House UI helpers. Plain ES module, no dependencies; pairs with house.css.
|
||||||
|
// Copy into the project (e.g. static/js/ui.js) unchanged.
|
||||||
|
//
|
||||||
|
// Per-browser storage is namespaced by <html data-app="<slug>"> so projects
|
||||||
|
// on the same origin don't collide.
|
||||||
|
|
||||||
|
const NS = (document.documentElement.dataset.app || 'app') + ':';
|
||||||
|
|
||||||
|
/** el('button.primary', {onclick}, 'Save'): tag with optional .classes, props/attrs, children.
|
||||||
|
* String values become attributes; set innerHTML with Object.assign (and only on sanitized HTML). */
|
||||||
|
export function el(spec, props = {}, ...children) {
|
||||||
|
const [tag, ...classes] = spec.split('.');
|
||||||
|
const node = document.createElement(tag || 'div');
|
||||||
|
if (classes.length) node.className = classes.join(' ');
|
||||||
|
for (const [k, v] of Object.entries(props || {})) {
|
||||||
|
if (v == null || v === false) continue;
|
||||||
|
if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);
|
||||||
|
else if (k === 'dataset') Object.assign(node.dataset, v);
|
||||||
|
else if (k in node && typeof v !== 'string') node[k] = v;
|
||||||
|
else node.setAttribute(k, v === true ? '' : v);
|
||||||
|
}
|
||||||
|
for (const c of children.flat()) if (c != null && c !== false) node.append(c);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A short confirmation in the corner: toast('Copied'), toast('Upload failed: too large', 'error'). */
|
||||||
|
export function toast(message, kind = 'info') {
|
||||||
|
let box = document.getElementById('toasts');
|
||||||
|
if (!box) {
|
||||||
|
box = el('div.toasts', { id: 'toasts', 'aria-live': 'polite' });
|
||||||
|
document.body.append(box);
|
||||||
|
}
|
||||||
|
const t = el(`div.toast.${kind}`, { role: kind === 'error' ? 'alert' : 'status' }, message);
|
||||||
|
box.append(t);
|
||||||
|
setTimeout(() => t.classList.add('out'), kind === 'error' ? 5000 : 2200);
|
||||||
|
setTimeout(() => t.remove(), kind === 'error' ? 5400 : 2600);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function copyText(text, what = 'Copied') {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
} catch {
|
||||||
|
const ta = el('textarea', { value: text, style: 'position:fixed;opacity:0' });
|
||||||
|
document.body.append(ta);
|
||||||
|
ta.select();
|
||||||
|
document.execCommand('copy');
|
||||||
|
ta.remove();
|
||||||
|
}
|
||||||
|
toast(what);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Copies HTML as rich text (with a plain-text alternative) for pasting into docs and chat apps. */
|
||||||
|
export async function copyRich(html, text, what = 'Copied') {
|
||||||
|
try {
|
||||||
|
if (!window.ClipboardItem || !navigator.clipboard?.write) throw new Error('no async clipboard');
|
||||||
|
await navigator.clipboard.write([new ClipboardItem({
|
||||||
|
'text/html': new Blob([html], { type: 'text/html' }),
|
||||||
|
'text/plain': new Blob([text], { type: 'text/plain' }),
|
||||||
|
})]);
|
||||||
|
} catch {
|
||||||
|
// Older browsers / insecure origins: select a rendered copy and use the legacy copy command.
|
||||||
|
const holder = el('div', { contenteditable: 'true', style: 'position:fixed;left:-9999px;top:0' });
|
||||||
|
holder.innerHTML = html;
|
||||||
|
document.body.append(holder);
|
||||||
|
const range = document.createRange();
|
||||||
|
range.selectNodeContents(holder);
|
||||||
|
const sel = getSelection();
|
||||||
|
sel.removeAllRanges();
|
||||||
|
sel.addRange(range);
|
||||||
|
document.execCommand('copy');
|
||||||
|
sel.removeAllRanges();
|
||||||
|
holder.remove();
|
||||||
|
}
|
||||||
|
toast(what);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function downloadText(text, filename, type = 'text/plain') {
|
||||||
|
const url = URL.createObjectURL(new Blob([text], { type: `${type};charset=utf-8` }));
|
||||||
|
const a = el('a', { href: url, download: filename });
|
||||||
|
document.body.append(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Opens a file picker and resolves with {name, text}, or null if cancelled. */
|
||||||
|
export function openTextFile(accept = '') {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const input = el('input', { type: 'file', accept });
|
||||||
|
input.addEventListener('change', async () => {
|
||||||
|
const f = input.files[0];
|
||||||
|
resolve(f ? { name: f.name, text: await f.text() } : null);
|
||||||
|
});
|
||||||
|
input.addEventListener('cancel', () => resolve(null));
|
||||||
|
input.click();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// localStorage can be missing or throw (private windows, blocked storage); never let that break the page.
|
||||||
|
export const store = {
|
||||||
|
prefix: NS,
|
||||||
|
get(key, fallback = null) {
|
||||||
|
try {
|
||||||
|
const v = localStorage.getItem(NS + key);
|
||||||
|
return v == null ? fallback : JSON.parse(v);
|
||||||
|
} catch {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
set(key, value) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(NS + key, JSON.stringify(value));
|
||||||
|
} catch {}
|
||||||
|
},
|
||||||
|
remove(key) {
|
||||||
|
try {
|
||||||
|
localStorage.removeItem(NS + key);
|
||||||
|
} catch {}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export function formatBytes(n) {
|
||||||
|
if (n < 1024) return `${n} B`;
|
||||||
|
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||||
|
return `${(n / 1024 / 1024).toFixed(2)} MB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Debounced fn; .flush() runs a pending call now (e.g. before the page unloads). */
|
||||||
|
export function debounce(fn, ms) {
|
||||||
|
let t, pending;
|
||||||
|
const d = (...args) => {
|
||||||
|
clearTimeout(t);
|
||||||
|
pending = args;
|
||||||
|
t = setTimeout(d.flush, ms);
|
||||||
|
};
|
||||||
|
d.flush = () => {
|
||||||
|
clearTimeout(t);
|
||||||
|
if (pending) {
|
||||||
|
const args = pending;
|
||||||
|
pending = null;
|
||||||
|
fn(...args);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs fn when the page is hidden/unloaded; returns a function that removes the listener. */
|
||||||
|
export function onLeave(fn) {
|
||||||
|
window.addEventListener('pagehide', fn);
|
||||||
|
return () => window.removeEventListener('pagehide', fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A segmented control: segmented([['edit','Edit'],...], current, onChange, 'View'). Has .set(value). */
|
||||||
|
export function segmented(options, current, onChange, label = '') {
|
||||||
|
const wrap = el('div.segmented', { role: 'radiogroup', 'aria-label': label });
|
||||||
|
const buttons = options.map(([value, text, title]) =>
|
||||||
|
el('button', {
|
||||||
|
type: 'button',
|
||||||
|
role: 'radio',
|
||||||
|
title: title || text,
|
||||||
|
'aria-checked': String(value === current),
|
||||||
|
onclick: () => set(value, true),
|
||||||
|
}, text),
|
||||||
|
);
|
||||||
|
function set(value, fire) {
|
||||||
|
options.forEach(([v], i) => buttons[i].setAttribute('aria-checked', String(v === value)));
|
||||||
|
if (fire) onChange(value);
|
||||||
|
}
|
||||||
|
wrap.append(...buttons);
|
||||||
|
wrap.set = (v) => set(v, false);
|
||||||
|
return wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Makes Tab / Shift+Tab indent and outdent in a textarea instead of moving focus. */
|
||||||
|
export function tabIndent(ta, unit = ' ') {
|
||||||
|
ta.addEventListener('keydown', (e) => {
|
||||||
|
if (e.key !== 'Tab' || e.ctrlKey || e.metaKey || e.altKey) return;
|
||||||
|
e.preventDefault();
|
||||||
|
const { selectionStart: s, selectionEnd: end, value } = ta;
|
||||||
|
const lineStart = value.lastIndexOf('\n', s - 1) + 1;
|
||||||
|
if (s === end && !e.shiftKey) {
|
||||||
|
document.execCommand('insertText', false, unit) || ta.setRangeText(unit, s, end, 'end');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const lines = value.slice(lineStart, end).split('\n');
|
||||||
|
const out = e.shiftKey
|
||||||
|
? lines.map((l) => (l.startsWith(unit) ? l.slice(unit.length) : l.replace(/^\t| {1,2}/, '')))
|
||||||
|
: lines.map((l) => unit + l);
|
||||||
|
ta.setSelectionRange(lineStart, end);
|
||||||
|
document.execCommand('insertText', false, out.join('\n')) || ta.setRangeText(out.join('\n'), lineStart, end, 'select');
|
||||||
|
ta.setSelectionRange(lineStart, lineStart + out.join('\n').length);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A modal dialog: modal('Title', body, {wide, footer}). Returns the <dialog>; it removes itself when closed. */
|
||||||
|
export function modal(title, body, { wide = false, footer = null } = {}) {
|
||||||
|
const dlg = el(`dialog.modal${wide ? '.wide' : ''}`, { 'aria-label': title },
|
||||||
|
el('div.modal-head', {},
|
||||||
|
el('h2', {}, title),
|
||||||
|
el('button.icon-btn', { type: 'button', 'aria-label': 'Close', onclick: () => dlg.close() }, '✕'),
|
||||||
|
),
|
||||||
|
el('div.modal-body', {}, body),
|
||||||
|
footer ? el('div.modal-foot', {}, footer) : null,
|
||||||
|
);
|
||||||
|
dlg.addEventListener('click', (e) => {
|
||||||
|
if (e.target === dlg) dlg.close(); // click on the backdrop
|
||||||
|
});
|
||||||
|
dlg.addEventListener('close', () => dlg.remove());
|
||||||
|
document.body.append(dlg);
|
||||||
|
dlg.showModal();
|
||||||
|
return dlg;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolves true/false: await confirmDialog('Delete project?', 'This cannot be undone.', 'Delete project'). */
|
||||||
|
export function confirmDialog(title, message, confirmLabel = 'Confirm', { danger = true } = {}) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
let ok = false;
|
||||||
|
const yes = el(`button.btn.${danger ? 'danger' : 'primary'}`, { type: 'button', onclick: () => { ok = true; dlg.close(); } }, confirmLabel);
|
||||||
|
const no = el('button.btn', { type: 'button', onclick: () => dlg.close() }, 'Cancel');
|
||||||
|
const dlg = modal(title, el('p', {}, message), { footer: [no, yes] });
|
||||||
|
dlg.addEventListener('close', () => resolve(ok));
|
||||||
|
yes.focus();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A button that opens a menu: dropdown('Open in', [{label, icon?, onSelect}]). */
|
||||||
|
export function dropdown(label, items) {
|
||||||
|
const menu = el('div.menu', { role: 'menu', hidden: true });
|
||||||
|
const btn = el('button.btn', { type: 'button', 'aria-haspopup': 'menu', 'aria-expanded': 'false', onclick: (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
toggle(menu.hidden);
|
||||||
|
} }, label, el('span.caret', { 'aria-hidden': 'true' }, '▾'));
|
||||||
|
for (const it of items) {
|
||||||
|
menu.append(el('button.menu-item', { type: 'button', role: 'menuitem', onclick: () => { toggle(false); it.onSelect(); } },
|
||||||
|
it.icon ? el('span.nav-icon', {}, it.icon) : null, it.label));
|
||||||
|
}
|
||||||
|
const outside = (e) => { if (!wrap.contains(e.target)) toggle(false); };
|
||||||
|
const onKey = (e) => { if (e.key === 'Escape') { toggle(false); btn.focus(); } };
|
||||||
|
function toggle(open) {
|
||||||
|
menu.hidden = !open;
|
||||||
|
btn.setAttribute('aria-expanded', String(open));
|
||||||
|
if (open) {
|
||||||
|
document.addEventListener('click', outside);
|
||||||
|
document.addEventListener('keydown', onKey);
|
||||||
|
menu.querySelector('button')?.focus();
|
||||||
|
} else {
|
||||||
|
document.removeEventListener('click', outside);
|
||||||
|
document.removeEventListener('keydown', onKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const wrap = el('div.dropdown', {}, btn, menu);
|
||||||
|
return wrap;
|
||||||
|
}
|
||||||
35
app/static/js/views/blocked.js
Normal file
35
app/static/js/views/blocked.js
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
// Blocked domains: AdGuard's top blocked list plus what was blocked recently, and for whom.
|
||||||
|
import { el } from '../ui.js';
|
||||||
|
import { get } from '../api.js';
|
||||||
|
import { ago, num, pct, when } from '../fmt.js';
|
||||||
|
import { adguardProblem, clientLink, domainLink, screen, section, table, fill } from '../common.js';
|
||||||
|
|
||||||
|
export function mount(root) {
|
||||||
|
const ui = screen(root, [el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'), el('span.spacer'), el('a.btn', { href: '/queries?status=blocked' }, 'Blocked queries in the log')]);
|
||||||
|
async function load() {
|
||||||
|
ui.setStatus('Loading…');
|
||||||
|
try {
|
||||||
|
const b = await get('/api/dns/blocked');
|
||||||
|
fill(ui.body,
|
||||||
|
el('p.lede', {}, b.num_queries ? `AdGuard Home blocked ${num(b.num_blocked)} of ${num(b.num_queries)} queries (${pct(b.num_blocked / b.num_queries, 1)}) in its stats period.` : 'No AdGuard stats yet.'),
|
||||||
|
el('div.cols', {},
|
||||||
|
el('div', {}, section('Recently blocked', b.since ? `${num(b.sample)} blocked queries since ${when(b.since)}` : ''),
|
||||||
|
table(['Domain', { text: 'Times', props: { class: 'num' } }, 'Clients', 'Last'],
|
||||||
|
b.recent.map((r) => el('tr', {},
|
||||||
|
el('td', {}, domainLink(r.domain), r.rule ? el('div.small.muted.mono', {}, r.rule) : null),
|
||||||
|
el('td.num', {}, num(r.count)),
|
||||||
|
el('td', {}, el('div', { style: 'display:grid;gap:2px' }, ...r.clients.slice(0, 4).map((c) => clientLink(c.ip, c.device)),
|
||||||
|
r.clients.length > 4 ? el('span.small.muted', {}, `+${r.clients.length - 4} more`) : null)),
|
||||||
|
el('td.nowrap', {}, ago(r.last)))), { empty: 'Nothing blocked recently.' })),
|
||||||
|
el('div', {}, section('Most blocked', 'AdGuard stats period'),
|
||||||
|
table(['Domain', { text: 'Times', props: { class: 'num' } }],
|
||||||
|
b.top.map((r) => el('tr', {}, el('td', {}, domainLink(r.domain)), el('td.num', {}, num(r.count)))), { empty: 'Nothing yet.' }))),
|
||||||
|
);
|
||||||
|
ui.setStatus(`${b.recent.length} domains blocked recently`);
|
||||||
|
} catch (err) {
|
||||||
|
fill(ui.body, adguardProblem(err));
|
||||||
|
ui.setStatus(err.message, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
load();
|
||||||
|
}
|
||||||
200
app/static/js/views/clients.js
Normal file
200
app/static/js/views/clients.js
Normal file
|
|
@ -0,0 +1,200 @@
|
||||||
|
// Clients: every device seen, your labels for it, and one client's DNS activity.
|
||||||
|
import { confirmDialog, debounce, el, store, toast } from '../ui.js';
|
||||||
|
import { del, get, put } from '../api.js';
|
||||||
|
import { ago, ms, num, when } from '../fmt.js';
|
||||||
|
import { adguardProblem, domainLink, errorBox, resultChip, screen, section, table, fill } from '../common.js';
|
||||||
|
|
||||||
|
const SOURCE = { arp: 'Probe ARP', dhcp: 'DHCP lease', dns: 'DNS queries', adguard: 'AdGuard client' };
|
||||||
|
const sourceName = (s) => SOURCE[s] || (s.startsWith('adguard-') ? `AdGuard ${s.slice(8)}` : s);
|
||||||
|
|
||||||
|
export function mount(root, ctx) {
|
||||||
|
return ctx.rest ? detail(root, ctx, decodeURIComponent(ctx.rest)) : list(root, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
function list(root) {
|
||||||
|
const f = store.get('client-filters', { q: '', cat: '', sus: false, online: false });
|
||||||
|
const q = el('input.input', { type: 'search', value: f.q, placeholder: 'Name, IP or MAC', 'aria-label': 'Search clients' });
|
||||||
|
const cat = el('select.select', { 'aria-label': 'Category' }, el('option', { value: '' }, 'All categories'));
|
||||||
|
const sus = el('input', { type: 'checkbox', checked: f.sus });
|
||||||
|
const online = el('input', { type: 'checkbox', checked: f.online });
|
||||||
|
const ui = screen(root, [
|
||||||
|
q, cat,
|
||||||
|
el('label.check', {}, sus, 'Suspicious only'),
|
||||||
|
el('label.check', {}, online, 'Active now'),
|
||||||
|
el('span.spacer'),
|
||||||
|
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||||
|
]);
|
||||||
|
let data = null;
|
||||||
|
|
||||||
|
const save = () => store.set('client-filters', { q: q.value, cat: cat.value, sus: sus.checked, online: online.checked });
|
||||||
|
const redraw = debounce(() => { save(); draw(); }, 120);
|
||||||
|
for (const c of [q, cat, sus, online]) c.addEventListener('input', redraw);
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
data = await get('/api/clients');
|
||||||
|
if (cat.options.length === 1) {
|
||||||
|
cat.append(...data.categories.map((c) => el('option', { value: c }, c)), el('option', { value: '-' }, 'No category'));
|
||||||
|
cat.value = f.cat;
|
||||||
|
}
|
||||||
|
draw();
|
||||||
|
} catch (err) {
|
||||||
|
fill(ui.body, errorBox(err));
|
||||||
|
ui.setStatus(err.message, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw() {
|
||||||
|
const needle = q.value.trim().toLowerCase();
|
||||||
|
const rows = data.clients.filter((c) =>
|
||||||
|
(!needle || [c.display, c.hostname, c.ip, c.mac, c.name].some((v) => v && v.toLowerCase().includes(needle))) &&
|
||||||
|
(!cat.value || (cat.value === '-' ? !c.category : c.category === cat.value)) &&
|
||||||
|
(!sus.checked || c.suspicious) && (!online.checked || c.online));
|
||||||
|
rows.sort((a, b) => (b.suspicious - a.suspicious) || ((b.queries || 0) - (a.queries || 0)) || a.display.localeCompare(b.display));
|
||||||
|
const empty = data.clients.length
|
||||||
|
? 'No clients match these filters.'
|
||||||
|
: data.adguard ? 'No clients yet. They appear within a minute of AdGuard Home or a probe seeing them.'
|
||||||
|
: 'No clients yet. Connect AdGuard Home (ADGUARD_URL in the hub’s .env) or add a probe; probes report the devices in their ARP table.';
|
||||||
|
fill(ui.body, table(
|
||||||
|
['Client', 'Category', 'IP', 'MAC', { text: 'Queries', props: { class: 'num', title: 'AdGuard Home stats period' } }, 'Last active', 'Seen by'],
|
||||||
|
rows.map((c) => el(`tr${c.suspicious ? '.flagged' : ''}`, {},
|
||||||
|
el('td', {}, el('span.chips', {},
|
||||||
|
el('a', { href: `/clients/${encodeURIComponent(c.key)}` }, el('strong', {}, c.display)),
|
||||||
|
c.name && c.hostname && c.name !== c.hostname ? el('span.muted.small', {}, c.hostname) : null,
|
||||||
|
c.suspicious ? el('span.chip.danger', {}, 'Suspicious') : null,
|
||||||
|
c.new ? el('span.chip.new', { title: `First seen ${when(c.first_seen)}` }, 'New') : null)),
|
||||||
|
el('td', {}, c.category || el('span.muted', {}, '—')),
|
||||||
|
el('td.mono', {}, c.ip || '—'),
|
||||||
|
el('td.mono', {}, c.mac || '—'),
|
||||||
|
el('td.num', {}, num(c.queries)),
|
||||||
|
el('td.nowrap', { title: when(c.last_seen) }, c.online ? el('span.chip.ok', {}, 'Active') : ago(c.last_seen)),
|
||||||
|
el('td.small.muted', {}, c.sources.map(sourceName).join(', ')))),
|
||||||
|
{ empty }));
|
||||||
|
const n = data.clients;
|
||||||
|
ui.setStatus(`${rows.length} of ${n.length} clients · ${n.filter((c) => c.online).length} active in the last 10 min · ${n.filter((c) => c.suspicious).length} suspicious`);
|
||||||
|
}
|
||||||
|
|
||||||
|
load();
|
||||||
|
const t = setInterval(() => { if (!document.hidden) load(); }, 60000);
|
||||||
|
return () => { clearInterval(t); redraw.flush(); };
|
||||||
|
}
|
||||||
|
|
||||||
|
function detail(root, ctx, key) {
|
||||||
|
const ui = screen(root, [
|
||||||
|
el('button.btn.primary', { type: 'submit', form: 'client-form' }, 'Save changes'),
|
||||||
|
el('a.btn', { href: `/queries?client=${encodeURIComponent(key)}` }, 'Open in query log'),
|
||||||
|
el('span.spacer'),
|
||||||
|
el('button.btn.danger', { type: 'button', onclick: () => forget() }, 'Forget client'),
|
||||||
|
]);
|
||||||
|
let c = null;
|
||||||
|
let cursor = '';
|
||||||
|
const qbody = el('tbody');
|
||||||
|
const more = el('button.btn', { type: 'button', onclick: () => loadQueries() }, 'Load older');
|
||||||
|
const qwrap = el('div');
|
||||||
|
const summary = el('div');
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
c = await get(`/api/clients/${encodeURIComponent(key)}`);
|
||||||
|
ctx.setTitle(c.display);
|
||||||
|
render();
|
||||||
|
ui.setStatus(`${c.online ? 'Active now' : `Last active ${ago(c.last_seen)}`} · first seen ${when(c.first_seen)}`);
|
||||||
|
loadSummary();
|
||||||
|
loadQueries(true);
|
||||||
|
} catch (err) {
|
||||||
|
fill(ui.body, err.status === 404 ? el('div.empty', {}, 'No client with this id. It may have been merged into another entry once its MAC address was learned.', el('div', {}, el('a.btn', { href: '/clients' }, 'All clients'))) : errorBox(err));
|
||||||
|
ui.setStatus(err.message, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
const name = el('input.input', { id: 'c-name', value: c.name, maxlength: 80, placeholder: c.hostname || c.ip || '' });
|
||||||
|
const category = el('select.select', { id: 'c-cat' }, el('option', { value: '' }, 'No category'), ...c.categories.map((x) => el('option', { value: x }, x)));
|
||||||
|
if (c.category && !c.categories.includes(c.category)) category.append(el('option', { value: c.category }, c.category));
|
||||||
|
category.value = c.category;
|
||||||
|
const suspicious = el('input', { type: 'checkbox', id: 'c-sus', checked: c.suspicious });
|
||||||
|
const notes = el('textarea.textarea', { id: 'c-notes', rows: 3, maxlength: 2000, placeholder: 'Who owns it, why it is flagged…' });
|
||||||
|
notes.value = c.notes;
|
||||||
|
const form = el('form.form-grid', { id: 'client-form', onsubmit: async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
try {
|
||||||
|
c = { ...c, ...(await put(`/api/clients/${encodeURIComponent(key)}`, { name: name.value, category: category.value, suspicious: suspicious.checked, notes: notes.value })) };
|
||||||
|
ctx.setTitle(c.display);
|
||||||
|
title.replaceWith(title = titleRow());
|
||||||
|
toast('Changes saved');
|
||||||
|
} catch (ex) { toast(ex.message, 'error'); }
|
||||||
|
} },
|
||||||
|
el('div.field', {}, el('label', { for: 'c-name' }, 'Name'), name, el('div.hint', {}, 'Shown everywhere instead of the hostname.')),
|
||||||
|
el('div.field', {}, el('label', { for: 'c-cat' }, 'Category'), category),
|
||||||
|
el('div.field.wide', {}, el('label.check', {}, suspicious, 'Suspicious: highlight this client in lists and query results')),
|
||||||
|
el('div.field.wide', {}, el('label', { for: 'c-notes' }, 'Notes'), notes));
|
||||||
|
const titleRow = () => el('div.title-row', {}, el('h2', {}, c.display),
|
||||||
|
c.suspicious ? el('span.chip.danger', {}, 'Suspicious') : null, c.category ? el('span.chip', {}, c.category) : null,
|
||||||
|
c.online ? el('span.chip.ok', {}, 'Active') : null);
|
||||||
|
let title = titleRow();
|
||||||
|
fill(ui.body,
|
||||||
|
title,
|
||||||
|
el('div.cols', { style: 'margin-top:12px' },
|
||||||
|
el('dl.kv', {},
|
||||||
|
el('dt', {}, 'IP address'), el('dd.mono', {}, c.ips.join(', ') || '—'),
|
||||||
|
el('dt', {}, 'MAC address'), el('dd.mono', {}, c.mac || 'Unknown (no probe or DHCP lease has seen it)'),
|
||||||
|
el('dt', {}, 'Hostname'), el('dd', {}, c.hostname || '—'),
|
||||||
|
el('dt', {}, 'Queries'), el('dd', {}, c.queries == null ? '—' : `${num(c.queries)} in AdGuard’s stats period`),
|
||||||
|
el('dt', {}, 'Seen by'), el('dd', {}, c.sources.map(sourceName).join(', ') || '—'),
|
||||||
|
el('dt', {}, 'First seen'), el('dd', {}, when(c.first_seen)),
|
||||||
|
el('dt', {}, 'Last active'), el('dd', {}, c.last_seen ? `${ago(c.last_seen)} (${when(c.last_seen)})` : '—')),
|
||||||
|
form),
|
||||||
|
summary,
|
||||||
|
section('DNS requests', 'Newest first'),
|
||||||
|
qwrap,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadSummary() {
|
||||||
|
summary.replaceChildren(section('Most requested domains'), el('div.loading', {}, 'Reading the query log…'));
|
||||||
|
try {
|
||||||
|
const s = await get(`/api/clients/${encodeURIComponent(key)}/summary`);
|
||||||
|
summary.replaceChildren(
|
||||||
|
section('Most requested domains', s.sample ? `From its last ${num(s.sample)} queries${s.since ? `, since ${when(s.since)}` : ''} · ${num(s.blocked)} blocked` : ''),
|
||||||
|
table(['Domain', { text: 'Requests', props: { class: 'num' } }, { text: 'Blocked', props: { class: 'num' } }],
|
||||||
|
s.top.map((d) => el('tr', {}, el('td', {}, domainLink(d.domain)), el('td.num', {}, num(d.count)), el('td.num', {}, d.blocked ? num(d.blocked) : '')),
|
||||||
|
), { empty: 'No DNS queries from this client in the AdGuard query log.' }));
|
||||||
|
} catch (err) {
|
||||||
|
summary.replaceChildren(section('Most requested domains'), adguardProblem(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadQueries(reset = false) {
|
||||||
|
if (reset) { cursor = ''; qbody.replaceChildren(); }
|
||||||
|
more.disabled = true;
|
||||||
|
try {
|
||||||
|
const r = await get('/api/dns/queries', { client: key, older_than: cursor, limit: 100 });
|
||||||
|
cursor = r.oldest;
|
||||||
|
qbody.append(...r.rows.map((q) => el(`tr${q.blocked ? '.flagged' : ''}`, {},
|
||||||
|
el('td.nowrap', { title: q.time }, `${when(q.ts)}`),
|
||||||
|
el('td.domain', {}, domainLink(q.domain)),
|
||||||
|
el('td.mono', {}, q.type),
|
||||||
|
el('td', {}, resultChip(q)),
|
||||||
|
el('td.num', {}, ms(q.elapsed_ms)))));
|
||||||
|
if (!qbody.children.length) qwrap.replaceChildren(el('div.callout', {}, 'No DNS queries from this client in the AdGuard query log.'));
|
||||||
|
else if (reset || !qwrap.querySelector('table')) qwrap.replaceChildren(
|
||||||
|
el('div.table-wrap', {}, el('table.table', {}, el('thead', {}, el('tr', {}, ...['Time', 'Domain', 'Type', 'Result', 'Response'].map((h) => el('th', {}, h)))), qbody)),
|
||||||
|
el('div.more', {}, more));
|
||||||
|
more.hidden = r.done || !cursor;
|
||||||
|
} catch (err) {
|
||||||
|
qwrap.replaceChildren(adguardProblem(err));
|
||||||
|
} finally {
|
||||||
|
more.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function forget() {
|
||||||
|
if (!c) return;
|
||||||
|
const ok = await confirmDialog(`Forget ${c.display}?`, 'Its name, category, flag and notes are deleted. If the device is still on the network it comes back as a new client.', 'Forget client');
|
||||||
|
if (!ok) return;
|
||||||
|
try { await del(`/api/clients/${encodeURIComponent(key)}`); toast(`Forgot ${c.display}`); ctx.navigate('/clients'); }
|
||||||
|
catch (e) { toast(e.message, 'error'); }
|
||||||
|
}
|
||||||
|
|
||||||
|
load();
|
||||||
|
}
|
||||||
107
app/static/js/views/domains.js
Normal file
107
app/static/js/views/domains.js
Normal file
|
|
@ -0,0 +1,107 @@
|
||||||
|
// Domains: the most requested and most blocked, and one domain's detail.
|
||||||
|
import { el } from '../ui.js';
|
||||||
|
import { get } from '../api.js';
|
||||||
|
import { seriesLegend, stackedBars, hideTip } from '../charts.js';
|
||||||
|
import { ago, hm, ms, num, pct, when } from '../fmt.js';
|
||||||
|
import { adguardProblem, clientLink, domainLink, resultChip, screen, section, table, fill } from '../common.js';
|
||||||
|
|
||||||
|
export function mount(root, ctx) {
|
||||||
|
return ctx.rest ? detail(root, ctx, decodeURIComponent(ctx.rest)) : overview(root, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openBox(ctx) {
|
||||||
|
const input = el('input.input', { type: 'search', placeholder: 'example.com', 'aria-label': 'Domain to open' });
|
||||||
|
const form = el('form', { style: 'display:contents', onsubmit: (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const d = input.value.trim().toLowerCase().replace(/^https?:\/\//, '').split('/')[0];
|
||||||
|
if (d) ctx.navigate(`/domains/${encodeURIComponent(d)}`);
|
||||||
|
} }, input, el('button.btn', { type: 'submit' }, 'Open domain'));
|
||||||
|
return form;
|
||||||
|
}
|
||||||
|
|
||||||
|
function overview(root, ctx) {
|
||||||
|
const ui = screen(root, [openBox(ctx), el('span.spacer'), el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh')]);
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
const d = await get('/api/domains');
|
||||||
|
const list = (rows) => table(['Domain', { text: 'Requests', props: { class: 'num' } }],
|
||||||
|
rows.map((r) => el('tr', {}, el('td', {}, domainLink(r.domain)), el('td.num', {}, num(r.count)))), { empty: 'Nothing yet.' });
|
||||||
|
fill(ui.body, el('div.cols', {},
|
||||||
|
el('div', {}, section('Most requested'), list(d.top_queried)),
|
||||||
|
el('div', {}, section('Most blocked'), list(d.top_blocked))));
|
||||||
|
ui.setStatus(`${num(d.num_queries)} queries · ${num(d.num_blocked)} blocked in AdGuard’s stats period`);
|
||||||
|
} catch (err) {
|
||||||
|
fill(ui.body, adguardProblem(err));
|
||||||
|
ui.setStatus(err.message, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
load();
|
||||||
|
}
|
||||||
|
|
||||||
|
function detail(root, ctx, name) {
|
||||||
|
ctx.setTitle(name);
|
||||||
|
const ui = screen(root, [
|
||||||
|
openBox(ctx),
|
||||||
|
el('a.btn', { href: `/queries?domain=${encodeURIComponent(name)}` }, 'Open in query log'),
|
||||||
|
el('span.spacer'),
|
||||||
|
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||||
|
]);
|
||||||
|
async function load() {
|
||||||
|
ui.body.classList.add('stale');
|
||||||
|
ui.setStatus('Reading the query log…');
|
||||||
|
try {
|
||||||
|
const d = await get(`/api/domains/${encodeURIComponent(name)}`);
|
||||||
|
render(d);
|
||||||
|
ui.setStatus(`Based on ${num(d.sample_rows)} queries for *.${d.base}${d.since ? ` since ${when(d.since)}` : ''}${d.complete ? ' (the whole AdGuard log)' : ''}`);
|
||||||
|
} catch (err) {
|
||||||
|
fill(ui.body, adguardProblem(err));
|
||||||
|
ui.setStatus(err.message, 'error');
|
||||||
|
} finally {
|
||||||
|
ui.body.classList.remove('stale');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(d) {
|
||||||
|
const now = Date.now() / 1000;
|
||||||
|
const hourLabel = (i, full) => {
|
||||||
|
const t = now - (23 - i) * 3600;
|
||||||
|
return full ? `${hm(t - 3600)} – ${hm(t)}` : i === 23 ? 'now' : `${23 - i} h ago`;
|
||||||
|
};
|
||||||
|
fill(ui.body,
|
||||||
|
el('div.title-row', {}, el('h2', {}, d.domain),
|
||||||
|
d.blocked ? el('span.chip.danger', {}, d.blocked === d.count ? 'Always blocked' : 'Sometimes blocked') : d.count ? el('span.chip.ok', {}, 'Allowed') : null,
|
||||||
|
d.domain !== d.base ? el('a.chip', { href: `/domains/${encodeURIComponent(d.base)}` }, `part of ${d.base}`) : null),
|
||||||
|
el('div.facts', {},
|
||||||
|
fact('Requests', num(d.count), 'in the sample below'),
|
||||||
|
fact('Blocked', d.count ? `${num(d.blocked)} (${pct(d.blocked / d.count)})` : '—'),
|
||||||
|
fact('Clients', num(d.clients.length)),
|
||||||
|
fact('Avg response', ms(d.avg_ms)),
|
||||||
|
fact('Last request', d.last ? ago(d.last) : '—'),
|
||||||
|
d.stats_count != null ? fact('AdGuard stats', num(d.stats_count), 'top-domain count for its stats period') : null),
|
||||||
|
d.count ? el('div', {},
|
||||||
|
section('Last 24 hours', 'Requests per hour'),
|
||||||
|
seriesLegend([{ name: 'Allowed', color: 'var(--viz-1)' }, { name: 'Blocked', color: 'var(--viz-2)' }], 'box'),
|
||||||
|
stackedBars({ n: 24, xLabel: hourLabel, height: 150, label: `Requests per hour for ${d.domain}`,
|
||||||
|
series: [{ name: 'Allowed', color: 'var(--viz-1)', values: d.hours.map((h, i) => h - d.blocked_hours[i]) },
|
||||||
|
{ name: 'Blocked', color: 'var(--viz-2)', values: d.blocked_hours }] })) : el('div.callout', { style: 'margin-top:12px' }, `No requests for ${d.domain} in the sample. Related domains under ${d.base} are below.`),
|
||||||
|
el('div.cols', {},
|
||||||
|
el('div', {}, section('Clients requesting it'),
|
||||||
|
table(['Client', { text: 'Requests', props: { class: 'num' } }, { text: 'Blocked', props: { class: 'num' } }, 'Last'],
|
||||||
|
d.clients.map((c) => el(`tr${c.device?.suspicious ? '.flagged' : ''}`, {},
|
||||||
|
el('td', {}, clientLink(c.ip, c.device, c.name)), el('td.num', {}, num(c.count)), el('td.num', {}, c.blocked ? num(c.blocked) : ''),
|
||||||
|
el('td.nowrap', {}, ago(c.last)))), { empty: 'No clients in the sample.' })),
|
||||||
|
el('div', {}, section(`Other names under ${d.base}`, 'Same domain, different subdomains'),
|
||||||
|
table(['Domain', { text: 'Requests', props: { class: 'num' } }, { text: 'Blocked', props: { class: 'num' } }],
|
||||||
|
d.related.map((r) => el('tr', {}, el('td', {}, domainLink(r.domain)), el('td.num', {}, num(r.count)), el('td.num', {}, r.blocked ? num(r.blocked) : ''))),
|
||||||
|
{ empty: 'No other names under this domain in the sample.' }))),
|
||||||
|
d.rules.length ? el('div', {}, section('Matching rules'), el('ul.mono', {}, ...d.rules.map(([r, n]) => el('li', {}, `${r} ×${n}`)))) : null,
|
||||||
|
section('Recent requests'),
|
||||||
|
table(['Time', 'Client', 'Type', 'Result', { text: 'Response', props: { class: 'num' } }],
|
||||||
|
d.recent.map((q) => el('tr', {}, el('td.nowrap', {}, when(q.ts)), el('td', {}, clientLink(q.client, q.device, q.client_name)),
|
||||||
|
el('td.mono', {}, q.type), el('td', {}, resultChip(q)), el('td.num', {}, ms(q.elapsed_ms)))), { empty: 'None in the sample.' }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const fact = (label, value, title) => el('div.fact', { title: title || '' }, el('span.label', {}, label), el('strong', {}, value));
|
||||||
|
load();
|
||||||
|
return hideTip;
|
||||||
|
}
|
||||||
130
app/static/js/views/health.js
Normal file
130
app/static/js/views/health.js
Normal file
|
|
@ -0,0 +1,130 @@
|
||||||
|
// Network health: the live mesh matrix, status strips over time and the incident list.
|
||||||
|
import { el, segmented, store } from '../ui.js';
|
||||||
|
import { get } from '../api.js';
|
||||||
|
import { STATUS, statusChip, statusLegend, strip, tipRow, tipTitle, hideTip, showTip } from '../charts.js';
|
||||||
|
import { axisTime, dur, ms, pct, when } from '../fmt.js';
|
||||||
|
import { RANGES, SPANS, every, errorBox, screen, section, table, fill } from '../common.js';
|
||||||
|
|
||||||
|
const METHOD = { icmp: 'Ping', http: 'HTTP', dns: 'DNS' };
|
||||||
|
|
||||||
|
export function mount(root, ctx) {
|
||||||
|
let range = store.get('health-range', '24h');
|
||||||
|
const seg = segmented(RANGES, range, (v) => { range = v; store.set('health-range', v); load(); }, 'Time range');
|
||||||
|
const ui = screen(root, [
|
||||||
|
seg,
|
||||||
|
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||||
|
el('span.spacer'),
|
||||||
|
el('a.btn', { href: '/probes' }, 'Manage probes'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
ui.body.classList.add('stale');
|
||||||
|
try {
|
||||||
|
const [mx, st, inc] = await Promise.all([
|
||||||
|
get('/api/health/matrix', { window: 300 }),
|
||||||
|
get('/api/health/strips', { range }),
|
||||||
|
get('/api/health/incidents', { range }),
|
||||||
|
]);
|
||||||
|
render(mx, st, inc);
|
||||||
|
const online = mx.probes.filter((p) => p.online).length;
|
||||||
|
const ongoing = inc.incidents.filter((i) => i.ongoing).length;
|
||||||
|
ui.setStatus(`${online} of ${mx.probes.length} probes reporting · ${inc.total} incidents in ${range}${ongoing ? ` · ${ongoing} ongoing` : ''} · updated ${new Date().toLocaleTimeString()}`,
|
||||||
|
ongoing ? 'error' : '');
|
||||||
|
} catch (err) {
|
||||||
|
fill(ui.body, errorBox(err));
|
||||||
|
ui.setStatus(`Couldn't load health: ${err.message}`, 'error');
|
||||||
|
} finally {
|
||||||
|
ui.body.classList.remove('stale');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(mx, st, inc) {
|
||||||
|
if (!mx.probes.length) {
|
||||||
|
fill(ui.body, el('div.empty', {},
|
||||||
|
el('p', {}, 'No probes yet. Probes are small containers on machines around the house that test the mesh and the internet link.'),
|
||||||
|
el('a.btn.primary', { href: '/probes?add=1' }, 'Add a probe')));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fill(ui.body,
|
||||||
|
section('Right now', 'Last 5 minutes, per probe and target. Select a probe for its charts.'),
|
||||||
|
matrix(mx),
|
||||||
|
section('Timeline', `${range} in ${st.buckets} slices of ${dur(st.width)}. A slice is down when half its checks fail, degraded when a fifth are slow or failing.`),
|
||||||
|
statusLegend(),
|
||||||
|
strips(st),
|
||||||
|
section('Incidents', `Slow means over ${inc.thresholds.lan_ms} ms on the LAN, ${inc.thresholds.wan_ms} ms to the internet, ${inc.thresholds.dns_ms} ms for DNS, or ${pct(inc.thresholds.loss)}+ ping loss.`),
|
||||||
|
incidents(inc.incidents),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function matrix(mx) {
|
||||||
|
if (!mx.targets.length) return el('div.callout', {}, 'No measurements in the last 5 minutes. Probes report every 30 seconds or so; check that they are running.');
|
||||||
|
const byKey = new Map(mx.cells.map((c) => [`${c.probe_id}|${c.target}`, c]));
|
||||||
|
const rows = mx.probes.map((p) => el('tr', {},
|
||||||
|
el('th.row-head', {}, el('span.chips', {}, el('a', { href: `/probes/${p.id}` }, p.name), p.online ? null : el('span.chip.danger', {}, 'Offline'))),
|
||||||
|
...mx.targets.map((t) => {
|
||||||
|
const c = byKey.get(`${p.id}|${t.target}`);
|
||||||
|
if (!c) return el('td', {}, el('div.cell-empty', {}, t.target === `probe:${p.id}` ? 'self' : '—'));
|
||||||
|
const main = c.methods.icmp || c.methods.http || c.methods.dns;
|
||||||
|
const loss = c.methods.icmp?.loss;
|
||||||
|
const node = el(`a.cell.s-${c.status}`, { href: `/probes/${p.id}`, 'aria-label': `${p.name} to ${t.label}: ${STATUS[c.status].label}` },
|
||||||
|
el('strong', {}, main?.latency != null ? ms(main.latency) : STATUS[c.status].label),
|
||||||
|
el('span.muted', {}, [loss != null ? `${pct(loss)} loss` : null, c.status !== 'ok' ? STATUS[c.status].label : null].filter(Boolean).join(' · ') || 'OK'));
|
||||||
|
const tip = () => [tipTitle(`${p.name} → ${t.label}`),
|
||||||
|
...Object.entries(c.methods).map(([m, v]) => tipRow(v.latency != null ? ms(v.latency) : 'failed',
|
||||||
|
`${METHOD[m] || m} · ${STATUS[v.status].label}${v.down ? ` · ${v.down}/${v.n} failed` : ''}${v.loss ? ` · ${pct(v.loss)} loss` : ''}`)),
|
||||||
|
...Object.values(c.methods).filter((v) => v.error).slice(0, 1).map((v) => el('div.small.error-text', {}, v.error))];
|
||||||
|
node.addEventListener('pointerenter', (e) => showTip(e.clientX, e.clientY, tip()));
|
||||||
|
node.addEventListener('pointermove', (e) => showTip(e.clientX, e.clientY, tip()));
|
||||||
|
node.addEventListener('pointerleave', hideTip);
|
||||||
|
node.addEventListener('focus', () => { const r = node.getBoundingClientRect(); showTip(r.right, r.bottom, tip()); });
|
||||||
|
node.addEventListener('blur', hideTip);
|
||||||
|
return el('td', {}, node);
|
||||||
|
})));
|
||||||
|
return el('div.table-wrap', {}, el('table.table.matrix', {},
|
||||||
|
el('thead', {}, el('tr', {}, el('th', {}, 'From ↓ / to →'), ...mx.targets.map((t) => el('th', { title: t.target }, t.label)))),
|
||||||
|
el('tbody', {}, ...rows)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function strips(st) {
|
||||||
|
if (!st.series.length) return el('div.callout', {}, `No measurements in the last ${range}.`);
|
||||||
|
const xt = axisTime(SPANS[range]);
|
||||||
|
const groups = new Map();
|
||||||
|
for (const s of st.series) {
|
||||||
|
if (!groups.has(s.probe_id)) groups.set(s.probe_id, []);
|
||||||
|
groups.get(s.probe_id).push(s);
|
||||||
|
}
|
||||||
|
const probe = new Map(st.probes.map((p) => [p.id, p]));
|
||||||
|
const describe = (s) => (i, b) => {
|
||||||
|
const t0 = st.since + i * st.width;
|
||||||
|
return [tipTitle(`${when(t0)} – ${xt(t0 + st.width)}`),
|
||||||
|
el('div', {}, el('strong', {}, `${probe.get(s.probe_id)?.name} → ${s.label}`)),
|
||||||
|
b ? tipRow(STATUS[b.s].label, `${b.n} checks${b.down ? ` · ${b.down} failed` : ''}${b.slow ? ` · ${b.slow} slow` : ''}`)
|
||||||
|
: tipRow('No data', 'no checks reported'),
|
||||||
|
b?.latency != null ? tipRow(ms(b.latency), 'average') : null];
|
||||||
|
};
|
||||||
|
return el('div.strips', {},
|
||||||
|
el('div.strip-axis', { 'aria-hidden': 'true' }, el('span'), el('span', {}, el('span', {}, xt(st.since)), el('span', {}, 'now')), el('span')),
|
||||||
|
...[...groups].map(([pid, list]) => el('div.strip-group', {},
|
||||||
|
el('h3', {}, el('a', { href: `/probes/${pid}` }, probe.get(pid)?.name || `Probe ${pid}`), probe.get(pid)?.online ? null : el('span.chip.danger', {}, 'Offline')),
|
||||||
|
...list.map((s) => el('div.strip-row', {},
|
||||||
|
el('span.name', { title: s.target }, s.label),
|
||||||
|
strip(s.buckets, describe(s)),
|
||||||
|
el('span.uptime', { title: 'Share of checks that succeeded' }, s.uptime == null ? '—' : `${s.uptime}%`))))));
|
||||||
|
}
|
||||||
|
|
||||||
|
function incidents(list) {
|
||||||
|
return table(['Started', 'Lasted', 'Probe', 'Target', 'Type', 'Checks', 'Detail'], list.map((i) => el('tr', {},
|
||||||
|
el('td.nowrap', { title: when(i.start) }, when(i.start)),
|
||||||
|
el('td.nowrap', {}, i.ongoing ? el('span.chip.danger', {}, `Ongoing · ${dur(i.duration)}`) : dur(i.duration)),
|
||||||
|
el('td', {}, el('a', { href: `/probes/${i.probe_id}` }, i.probe)),
|
||||||
|
el('td', {}, i.label, el('span.muted.small', {}, ` ${i.methods.map((m) => METHOD[m] || m).join(', ')}`)),
|
||||||
|
el('td', {}, statusChip(i.type)),
|
||||||
|
el('td.num', {}, i.failed ? `${i.failed}/${i.samples} failed` : `${i.samples} slow`),
|
||||||
|
el('td.small', {}, i.error || (i.max_latency ? `peak ${ms(i.max_latency)}` : '')),
|
||||||
|
)), { empty: `No incidents in the last ${range}.` });
|
||||||
|
}
|
||||||
|
|
||||||
|
load();
|
||||||
|
const stop = every(30000, load);
|
||||||
|
return () => { stop(); hideTip(); };
|
||||||
|
}
|
||||||
253
app/static/js/views/probes.js
Normal file
253
app/static/js/views/probes.js
Normal file
|
|
@ -0,0 +1,253 @@
|
||||||
|
// Probes: the list, adding one (with its install command), and one probe's detail and charts.
|
||||||
|
import { confirmDialog, copyText, el, modal, segmented, store, toast } from '../ui.js';
|
||||||
|
import { del, get, patch, post } from '../api.js';
|
||||||
|
import { lineChart, seriesLegend, statusChip, statusLegend, strip, tipRow, tipTitle, hideTip, STATUS } from '../charts.js';
|
||||||
|
import { ago, axisTime, dur, mbps, ms, pct, when } from '../fmt.js';
|
||||||
|
import { RANGES, SPANS, every, errorBox, screen, section, table, fill } from '../common.js';
|
||||||
|
|
||||||
|
const METHOD = { icmp: 'Ping', http: 'HTTP', dns: 'DNS', throughput: 'Throughput' };
|
||||||
|
|
||||||
|
export function mount(root, ctx) {
|
||||||
|
return ctx.rest ? detail(root, ctx, Number(ctx.rest)) : list(root, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
function installCommand(info, token) {
|
||||||
|
const hub = info.hub_url || location.origin;
|
||||||
|
return `curl -fsSL ${info.install_url} | HUB_URL=${hub} PROBE_TOKEN=${token} bash`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function commandBlock(cmd) {
|
||||||
|
const loopback = /^(localhost|127\.|\[::1\])/.test(location.hostname) && cmd.includes(location.origin);
|
||||||
|
return el('div', { style: 'display:grid;gap:6px' },
|
||||||
|
el('div.cmd', {}, el('pre', {}, cmd), el('button.btn', { type: 'button', onclick: () => copyText(cmd, 'Install command copied') }, 'Copy')),
|
||||||
|
loopback ? el('div.callout.error', {}, `You opened this page at ${location.host}, which other machines can't reach. Replace HUB_URL with the hub's LAN address, or set HUB_PUBLIC_URL in the hub's .env.`) : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onlineChip(p) {
|
||||||
|
if (!p.last_seen) return el('span.chip', {}, 'Never reported');
|
||||||
|
return p.online ? el('span.chip.ok', {}, 'Reporting') : el('span.chip.danger', {}, 'Offline');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- list
|
||||||
|
|
||||||
|
function list(root, ctx) {
|
||||||
|
const ui = screen(root, [
|
||||||
|
el('button.btn.primary', { type: 'button', onclick: () => addProbe() }, 'Add probe'),
|
||||||
|
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||||
|
]);
|
||||||
|
let info = null;
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
info = await get('/api/probes');
|
||||||
|
const rows = info.probes.map((p) => el('tr', {},
|
||||||
|
el('td', {}, el('a', { href: `/probes/${p.id}` }, el('strong', {}, p.name))),
|
||||||
|
el('td', {}, onlineChip(p)),
|
||||||
|
el('td.mono', {}, p.address ? `${p.address}:${p.port || 8765}` : '—'),
|
||||||
|
el('td', {}, p.hostname || '—'),
|
||||||
|
el('td', {}, p.icmp == null ? '—' : p.icmp ? 'Yes' : el('span.chip.warn', { title: 'Run install-probe.sh again on that machine to enable ping' }, 'Not permitted')),
|
||||||
|
el('td.mono', {}, p.version || '—'),
|
||||||
|
el('td.nowrap', { title: when(p.last_seen) }, ago(p.last_seen)),
|
||||||
|
));
|
||||||
|
fill(ui.body,
|
||||||
|
el('p.lede', {}, 'Each probe tests every other probe (ping, HTTP and throughput), the gateway, DNS servers and the internet, then reports here.'),
|
||||||
|
table(['Name', 'Status', 'Address', 'Host', 'Ping', 'Version', 'Last report'], rows,
|
||||||
|
{ empty: 'No probes yet. Add one, then run its install command on a machine on the network.' }),
|
||||||
|
);
|
||||||
|
const off = info.probes.filter((p) => !p.online).length;
|
||||||
|
ui.setStatus(`${info.probes.length} probes · ${off} not reporting · they report every ${info.interval} s`, off ? 'error' : '');
|
||||||
|
} catch (err) {
|
||||||
|
fill(ui.body, errorBox(err));
|
||||||
|
ui.setStatus(err.message, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addProbe() {
|
||||||
|
const name = el('input.input', { id: 'probe-name', required: true, maxlength: 60, placeholder: 'Living room', autocomplete: 'off' });
|
||||||
|
const err = el('div.error', { hidden: true });
|
||||||
|
const submit = el('button.btn.primary', { type: 'submit', form: 'add-probe' }, 'Add probe');
|
||||||
|
const form = el('form.field', { id: 'add-probe', onsubmit: async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
submit.disabled = true;
|
||||||
|
try {
|
||||||
|
const p = await post('/api/probes', { name: name.value.trim() });
|
||||||
|
dlg.close();
|
||||||
|
showInstall(p);
|
||||||
|
load();
|
||||||
|
} catch (ex) {
|
||||||
|
err.textContent = ex.message; err.hidden = false; name.setAttribute('aria-invalid', 'true');
|
||||||
|
submit.disabled = false;
|
||||||
|
}
|
||||||
|
} }, el('label', { for: 'probe-name' }, 'Name'), name,
|
||||||
|
el('div.hint', {}, 'Where it sits, so the matrix reads well: Office, Garage, Upstairs AP.'), err);
|
||||||
|
const dlg = modal('Add a probe', form, { footer: [el('button.btn', { type: 'button', onclick: () => dlg.close() }, 'Cancel'), submit] });
|
||||||
|
name.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
function showInstall(p) {
|
||||||
|
const cmd = installCommand(info, p.token);
|
||||||
|
const dlg = modal(`Install “${p.name}”`, el('div', { style: 'display:grid;gap:12px' },
|
||||||
|
el('p', { style: 'margin:0' }, 'Run this on the machine that will be the probe. It starts on boot and keeps running. On Linux hosts it uses Docker (installed if needed). On macOS and inside Proxmox LXC containers it installs natively as a system service; there, Linux needs root: put sudo env before HUB_URL.'),
|
||||||
|
commandBlock(cmd),
|
||||||
|
el('p.small.muted', { style: 'margin:0' }, `The probe reports to ${info.hub_url || location.origin}. If that address isn't reachable from the probe, change HUB_URL in the command. The command is also on the probe's page.`),
|
||||||
|
), { wide: true, footer: [el('a.btn', { href: `/probes/${p.id}`, onclick: () => dlg.close() }, 'Open probe'), el('button.btn.primary', { type: 'button', onclick: () => dlg.close() }, 'Done')] });
|
||||||
|
}
|
||||||
|
|
||||||
|
load();
|
||||||
|
if (ctx.query.get('add')) { history.replaceState({}, '', '/probes'); setTimeout(addProbe, 0); }
|
||||||
|
return every(30000, load);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- detail
|
||||||
|
|
||||||
|
function detail(root, ctx, id) {
|
||||||
|
let range = store.get('probe-range', '24h');
|
||||||
|
const seg = segmented(RANGES, range, (v) => { range = v; store.set('probe-range', v); load(); }, 'Time range');
|
||||||
|
const ui = screen(root, [
|
||||||
|
seg,
|
||||||
|
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||||
|
el('span.spacer'),
|
||||||
|
el('button.btn', { type: 'button', onclick: () => rename() }, 'Rename'),
|
||||||
|
el('button.btn.danger', { type: 'button', onclick: () => remove() }, 'Remove probe'),
|
||||||
|
]);
|
||||||
|
let probe = null, listInfo = null;
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
ui.body.classList.add('stale');
|
||||||
|
try {
|
||||||
|
const [p, li, st, ser, inc] = await Promise.all([
|
||||||
|
get(`/api/probes/${id}`), get('/api/probes'),
|
||||||
|
get('/api/health/strips', { range, probe: id }), get('/api/health/series', { probe: id, range }),
|
||||||
|
get('/api/health/incidents', { range, probe: id, limit: 50 }),
|
||||||
|
]);
|
||||||
|
probe = p; listInfo = li;
|
||||||
|
ctx.setTitle(p.name);
|
||||||
|
render(st, ser, inc);
|
||||||
|
ui.setStatus(`${p.online ? 'Reporting' : 'Not reporting'} · last report ${ago(p.last_seen)} · ${inc.total} incidents in ${range}`, p.online ? '' : 'error');
|
||||||
|
} catch (err) {
|
||||||
|
fill(ui.body, err.status === 404 ? el('div.empty', {}, 'This probe was removed.', el('div', {}, el('a.btn', { href: '/probes' }, 'All probes'))) : errorBox(err));
|
||||||
|
ui.setStatus(err.message, 'error');
|
||||||
|
} finally {
|
||||||
|
ui.body.classList.remove('stale');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(st, ser, inc) {
|
||||||
|
const p = probe;
|
||||||
|
const addr = el('input.input', { value: p.address_locked ? p.address : '', placeholder: p.address ? `${p.address} (detected)` : 'detected from reports', 'aria-label': 'Address other probes use', style: 'max-width:260px' });
|
||||||
|
const saveAddr = el('button.btn.small', { type: 'button', onclick: async () => {
|
||||||
|
try { probe = await patch(`/api/probes/${id}`, { address: addr.value.trim() }); toast(addr.value.trim() ? 'Address saved' : 'Address will be detected again'); load(); }
|
||||||
|
catch (e) { toast(e.message, 'error'); }
|
||||||
|
} }, 'Save');
|
||||||
|
fill(ui.body,
|
||||||
|
el('div.title-row', {}, el('h2', {}, p.name), onlineChip(p)),
|
||||||
|
el('div.cols', {},
|
||||||
|
el('dl.kv', {},
|
||||||
|
el('dt', {}, 'Address'), el('dd', {}, el('span.chips', {}, addr, saveAddr)),
|
||||||
|
el('dt', {}, 'Port'), el('dd.mono', {}, String(p.port || 8765)),
|
||||||
|
el('dt', {}, 'Host'), el('dd', {}, p.hostname || '—'),
|
||||||
|
el('dt', {}, 'Ping'), el('dd', {}, p.icmp == null ? '—' : p.icmp ? 'Works' : 'Not permitted on this host. Run install-probe.sh again, which sets net.ipv4.ping_group_range.'),
|
||||||
|
el('dt', {}, 'Version'), el('dd.mono', {}, p.version || '—'),
|
||||||
|
el('dt', {}, 'Added'), el('dd', {}, when(p.created)),
|
||||||
|
el('dt', {}, 'Last report'), el('dd', {}, `${ago(p.last_seen)}${p.last_seen ? ` (${when(p.last_seen)})` : ''}`),
|
||||||
|
),
|
||||||
|
el('div', {},
|
||||||
|
el('div.label', { style: 'margin-bottom:6px' }, 'Install or reinstall'),
|
||||||
|
commandBlock(installCommand(listInfo, p.token)),
|
||||||
|
el('p.small.muted', {}, 'Leave Address empty to use what the probe reports. Set it when other probes must reach this one at a different address.')),
|
||||||
|
),
|
||||||
|
section('Timeline', `${range} in slices of ${dur(st.width)}`),
|
||||||
|
statusLegend(),
|
||||||
|
stripsFor(st),
|
||||||
|
section('Latency', 'Average per slice. Red ticks mark slices with failed checks.'),
|
||||||
|
seriesLegend([{ name: 'Ping', color: 'var(--viz-1)' }, { name: 'HTTP or DNS', color: 'var(--viz-2)' }]),
|
||||||
|
multiples(ser),
|
||||||
|
throughputChart(ser),
|
||||||
|
section('Incidents'),
|
||||||
|
table(['Started', 'Lasted', 'Target', 'Type', 'Checks', 'Detail'], inc.incidents.map((i) => el('tr', {},
|
||||||
|
el('td.nowrap', {}, when(i.start)),
|
||||||
|
el('td.nowrap', {}, i.ongoing ? el('span.chip.danger', {}, `Ongoing · ${dur(i.duration)}`) : dur(i.duration)),
|
||||||
|
el('td', {}, i.label, el('span.muted.small', {}, ` ${i.methods.map((m) => METHOD[m] || m).join(', ')}`)),
|
||||||
|
el('td', {}, statusChip(i.type)),
|
||||||
|
el('td.num', {}, i.failed ? `${i.failed}/${i.samples} failed` : `${i.samples} slow`),
|
||||||
|
el('td.small', {}, i.error || (i.max_latency ? `peak ${ms(i.max_latency)}` : '')))), { empty: `No incidents in the last ${range}.` }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripsFor(st) {
|
||||||
|
if (!st.series.length) return el('div.callout', {}, `No measurements in the last ${range}.`);
|
||||||
|
const xt = axisTime(SPANS[range]);
|
||||||
|
return el('div.strips', {},
|
||||||
|
el('div.strip-axis', { 'aria-hidden': 'true' }, el('span'), el('span', {}, el('span', {}, xt(st.since)), el('span', {}, 'now')), el('span')),
|
||||||
|
...st.series.map((s) => el('div.strip-row', {},
|
||||||
|
el('span.name', { title: s.target }, s.label),
|
||||||
|
strip(s.buckets, (i, b) => [tipTitle(`${when(st.since + i * st.width)} – ${xt(st.since + (i + 1) * st.width)}`),
|
||||||
|
b ? tipRow(STATUS[b.s].label, `${b.n} checks${b.down ? ` · ${b.down} failed` : ''}${b.slow ? ` · ${b.slow} slow` : ''}`) : tipRow('No data', ''),
|
||||||
|
b?.latency != null ? tipRow(ms(b.latency), 'average') : null]),
|
||||||
|
el('span.uptime', {}, s.uptime == null ? '—' : `${s.uptime}%`))));
|
||||||
|
}
|
||||||
|
|
||||||
|
function multiples(ser) {
|
||||||
|
const xt = axisTime(SPANS[range]);
|
||||||
|
const xLabel = (i, full) => (full ? `${when(ser.since + i * ser.width)} – ${xt(ser.since + (i + 1) * ser.width)}` : xt(ser.since + (i + 0.5) * ser.width));
|
||||||
|
const cards = ser.targets.filter((t) => t.methods.icmp || t.methods.http || t.methods.dns).map((t) => {
|
||||||
|
const second = t.methods.http || t.methods.dns;
|
||||||
|
const series = [];
|
||||||
|
if (t.methods.icmp) series.push({ name: 'Ping', color: 'var(--viz-1)', values: t.methods.icmp.map((b) => b?.avg ?? null) });
|
||||||
|
if (second) series.push({ name: t.methods.http ? 'HTTP' : 'DNS', color: 'var(--viz-2)', values: second.map((b) => b?.avg ?? null) });
|
||||||
|
const methods = Object.entries(t.methods).filter(([m]) => m !== 'throughput');
|
||||||
|
const marks = Array.from({ length: ser.buckets }, (_, i) => methods.reduce((a, [, arr]) => a + (arr[i]?.failed || 0), 0));
|
||||||
|
return el('div.multiple', {},
|
||||||
|
el('h4', {}, t.label, el('span.chip', {}, t.kind === 'lan' ? 'LAN' : 'Internet')),
|
||||||
|
lineChart({ n: ser.buckets, xLabel, series, marks, fmt: ms, height: 140, label: `Latency to ${t.label}`,
|
||||||
|
describe: (i) => {
|
||||||
|
const out = [];
|
||||||
|
for (const [m, arr] of methods) {
|
||||||
|
const b = arr[i];
|
||||||
|
if (b?.failed) out.push(el('div.small.error-text', {}, `${METHOD[m]}: ${b.failed} of ${b.n} failed`));
|
||||||
|
if (m === 'icmp' && b?.loss) out.push(el('div.small', {}, `Ping loss ${pct(b.loss)}`));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
} }));
|
||||||
|
});
|
||||||
|
return cards.length ? el('div.multiples', {}, ...cards) : el('div.callout', {}, `No latency data in the last ${range}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function throughputChart(ser) {
|
||||||
|
const tp = ser.targets.filter((t) => t.methods.throughput);
|
||||||
|
if (!tp.length) return null;
|
||||||
|
const xt = axisTime(SPANS[range]);
|
||||||
|
const xLabel = (i, full) => (full ? when(ser.since + i * ser.width) : xt(ser.since + (i + 0.5) * ser.width));
|
||||||
|
return el('div', {},
|
||||||
|
section('Throughput to other probes', 'A timed download from each peer, every few minutes.'),
|
||||||
|
el('div.multiples', {}, ...tp.map((t) => el('div.multiple', {},
|
||||||
|
el('h4', {}, t.label),
|
||||||
|
lineChart({ n: ser.buckets, xLabel, fmt: mbps, height: 120, label: `Throughput from ${t.label}`,
|
||||||
|
series: [{ name: 'Throughput', color: 'var(--viz-1)', values: t.methods.throughput.map((b) => b?.mbps ?? null) }],
|
||||||
|
marks: t.methods.throughput.map((b) => b?.failed || 0) })))));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function rename() {
|
||||||
|
const input = el('input.input', { value: probe?.name || '', maxlength: 60, 'aria-label': 'Name' });
|
||||||
|
const save = el('button.btn.primary', { type: 'button', onclick: async () => {
|
||||||
|
try { await patch(`/api/probes/${id}`, { name: input.value.trim() }); dlg.close(); toast('Renamed'); load(); }
|
||||||
|
catch (e) { toast(e.message, 'error'); }
|
||||||
|
} }, 'Save name');
|
||||||
|
const dlg = modal('Rename probe', input, { footer: [el('button.btn', { type: 'button', onclick: () => dlg.close() }, 'Cancel'), save] });
|
||||||
|
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') save.click(); });
|
||||||
|
input.select();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove() {
|
||||||
|
if (!probe) return;
|
||||||
|
const ok = await confirmDialog(`Remove ${probe.name}?`,
|
||||||
|
'Its history is deleted and its token stops working. The probe keeps running on its machine until you uninstall it there; the installer printed the uninstall command, and the README lists it.', 'Remove probe');
|
||||||
|
if (!ok) return;
|
||||||
|
try { await del(`/api/probes/${id}`); toast(`Removed ${probe.name}`); ctx.navigate('/probes'); }
|
||||||
|
catch (e) { toast(e.message, 'error'); }
|
||||||
|
}
|
||||||
|
|
||||||
|
load();
|
||||||
|
const stop = every(30000, load);
|
||||||
|
return () => { stop(); hideTip(); };
|
||||||
|
}
|
||||||
67
app/static/js/views/queries.js
Normal file
67
app/static/js/views/queries.js
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
// The DNS query log from AdGuard Home, with search, result filter and client filter.
|
||||||
|
import { debounce, el, segmented } from '../ui.js';
|
||||||
|
import { get } from '../api.js';
|
||||||
|
import { ms, when } from '../fmt.js';
|
||||||
|
import { adguardProblem, clientLink, domainLink, resultChip, screen, fill } from '../common.js';
|
||||||
|
|
||||||
|
export function mount(root, ctx) {
|
||||||
|
const params = ctx.query;
|
||||||
|
let status = params.get('status') || 'all';
|
||||||
|
const client = params.get('client') || '';
|
||||||
|
const ip = params.get('ip') || '';
|
||||||
|
const domain = params.get('domain') || '';
|
||||||
|
const search = el('input.input', { type: 'search', value: params.get('q') || '', placeholder: 'Domain or client', 'aria-label': 'Search queries' });
|
||||||
|
const seg = segmented([['all', 'All'], ['blocked', 'Blocked'], ['allowed', 'Allowed']], status, (v) => { status = v; sync(); load(true); }, 'Result');
|
||||||
|
const filterChip = client || ip || domain
|
||||||
|
? el('span.chip.accent', {}, `${client ? 'Client' : ip ? 'IP' : 'Domain'}: ${client || ip || domain} `,
|
||||||
|
el('a', { href: '/queries', 'aria-label': 'Clear filter', style: 'color:inherit;text-decoration:none' }, '✕'))
|
||||||
|
: null;
|
||||||
|
const ui = screen(root, [search, seg, filterChip, el('span.spacer'), el('button.btn', { type: 'button', onclick: () => load(true) }, 'Refresh')]);
|
||||||
|
const tbody = el('tbody');
|
||||||
|
const more = el('button.btn', { type: 'button', onclick: () => load() }, 'Load older');
|
||||||
|
let cursor = '', count = 0, seq = 0;
|
||||||
|
|
||||||
|
function sync() {
|
||||||
|
const u = new URLSearchParams(location.search);
|
||||||
|
search.value ? u.set('q', search.value) : u.delete('q');
|
||||||
|
status !== 'all' ? u.set('status', status) : u.delete('status');
|
||||||
|
history.replaceState({}, '', `/queries${u.size ? `?${u}` : ''}`);
|
||||||
|
}
|
||||||
|
search.addEventListener('input', debounce(() => { sync(); load(true); }, 350));
|
||||||
|
|
||||||
|
async function load(reset = false) {
|
||||||
|
const my = ++seq;
|
||||||
|
if (reset) { cursor = ''; count = 0; }
|
||||||
|
more.disabled = true;
|
||||||
|
ui.setStatus('Loading…');
|
||||||
|
try {
|
||||||
|
const r = await get('/api/dns/queries', { search: search.value.trim(), status, client, ip, domain, older_than: cursor, limit: 100 });
|
||||||
|
if (my !== seq) return;
|
||||||
|
if (reset) tbody.replaceChildren();
|
||||||
|
cursor = r.oldest;
|
||||||
|
count += r.rows.length;
|
||||||
|
tbody.append(...r.rows.map((q) => el(`tr${q.device?.suspicious ? '.flagged' : ''}`, {},
|
||||||
|
el('td.nowrap', { title: q.time }, when(q.ts)),
|
||||||
|
el('td', {}, clientLink(q.client, q.device, q.client_name)),
|
||||||
|
el('td.domain', {}, domainLink(q.domain)),
|
||||||
|
el('td.mono', {}, q.type),
|
||||||
|
el('td', {}, resultChip(q)),
|
||||||
|
el('td.num', {}, ms(q.elapsed_ms)))));
|
||||||
|
if (!ui.body.querySelector('table')) {
|
||||||
|
fill(ui.body, el('div.table-wrap', {}, el('table.table', {},
|
||||||
|
el('thead', {}, el('tr', {}, ...['Time', 'Client', 'Domain', 'Type', 'Result', { t: 'Response', c: 'num' }].map((h) => el('th', h.c ? { class: h.c } : {}, h.t || h)))), tbody)),
|
||||||
|
el('div.more', {}, more));
|
||||||
|
}
|
||||||
|
if (!count) fill(ui.body, el('div.empty', {}, 'No queries match.'));
|
||||||
|
more.hidden = r.done || !cursor;
|
||||||
|
ui.setStatus(`${count} queries${r.done ? ' · end of the AdGuard log' : ''}`);
|
||||||
|
} catch (err) {
|
||||||
|
if (my !== seq) return;
|
||||||
|
fill(ui.body, adguardProblem(err));
|
||||||
|
ui.setStatus(err.message, 'error');
|
||||||
|
} finally {
|
||||||
|
more.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
load(true);
|
||||||
|
}
|
||||||
42
app/static/js/views/settings.js
Normal file
42
app/static/js/views/settings.js
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
// Settings: what the hub is configured to do. Values live in the hub's .env.
|
||||||
|
import { el } from '../ui.js';
|
||||||
|
import { get } from '../api.js';
|
||||||
|
import { num } from '../fmt.js';
|
||||||
|
|
||||||
|
export async function mount(root) {
|
||||||
|
const intro = el('p.muted', {}, 'These come from the hub’s .env file.');
|
||||||
|
const page = el('div.page', {}, el('h1', {}, 'Settings'), intro);
|
||||||
|
root.append(page);
|
||||||
|
try {
|
||||||
|
const [i, dns] = await Promise.all([get('/api/info'), get('/api/dns/status')]);
|
||||||
|
intro.textContent = `These come from ${i.env_file} on the hub (${i.install_mode} install). Edit that file, then restart the hub to apply: ${i.install_mode === 'docker' ? 'docker restart network-monitor' : 'sudo systemctl restart network-monitor (macOS: sudo launchctl kickstart -k system/dev.neilbantoc.network-monitor)'}. Deploy new code with ${i.update_command}.`;
|
||||||
|
const row = (k, v, env) => [el('dt', {}, k), el('dd', {}, v, env ? el('span.muted.small.mono', {}, ` ${env}`) : null)];
|
||||||
|
const list = (xs) => (xs.length ? xs.join(', ') : 'none');
|
||||||
|
page.append(
|
||||||
|
el('h2', {}, 'AdGuard Home'),
|
||||||
|
el('dl.kv', {},
|
||||||
|
...row('Status', dns.ok ? el('span.chip.ok', {}, `Connected · ${dns.version}`) : el('span.chip.danger', {}, dns.configured ? 'Not reachable' : 'Not set up')),
|
||||||
|
...(dns.url ? row('Address', dns.url, 'ADGUARD_URL') : []),
|
||||||
|
...(dns.ok ? [] : row('Problem', dns.message))),
|
||||||
|
el('h2', {}, 'Probes'),
|
||||||
|
el('dl.kv', {},
|
||||||
|
...row('Report every', `${i.probe_interval} s`, 'PROBE_INTERVAL'),
|
||||||
|
...row('LAN DNS servers', list(i.lan_dns_servers), 'LAN_DNS_SERVERS'),
|
||||||
|
...row('Public DNS servers', list(i.dns_servers), 'DNS_SERVERS'),
|
||||||
|
...row('DNS test name', i.dns_query_name, 'DNS_QUERY_NAME'),
|
||||||
|
...row('Internet HTTP checks', list(i.wan_http_urls), 'WAN_HTTP_URLS'),
|
||||||
|
...row('VPS', i.vps_url || 'none', 'VPS_URL'),
|
||||||
|
...row('Throughput test', i.throughput_every ? `${num(i.throughput_bytes / 1e6)} MB from each peer every ${i.throughput_every} reports` : 'off', 'THROUGHPUT_EVERY, THROUGHPUT_BYTES')),
|
||||||
|
el('h2', {}, 'Thresholds and storage'),
|
||||||
|
el('dl.kv', {},
|
||||||
|
...row('Slow on the LAN', `over ${i.thresholds.lan_ms} ms`, 'SLOW_LAN_MS'),
|
||||||
|
...row('Slow to the internet', `over ${i.thresholds.wan_ms} ms`, 'SLOW_WAN_MS'),
|
||||||
|
...row('Slow DNS', `over ${i.thresholds.dns_ms} ms`, 'SLOW_DNS_MS'),
|
||||||
|
...row('Keep measurements', `${i.retention_days} days`, 'RETENTION_DAYS'),
|
||||||
|
...row('Password', i.password ? 'On' : 'Off: anyone on the network can open this page', 'UI_PASSWORD'),
|
||||||
|
...row('Version', i.version)),
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
page.append(el('div.callout.error', {}, err.message));
|
||||||
|
}
|
||||||
|
}
|
||||||
0
app/static/vendor/.gitkeep
vendored
Normal file
0
app/static/vendor/.gitkeep
vendored
Normal file
3
app/version.py
Normal file
3
app/version.py
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
import os
|
||||||
|
|
||||||
|
VERSION = os.environ.get("APP_VERSION", "dev")
|
||||||
13
compose.dev.yml
Normal file
13
compose.dev.yml
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
# Local development: the source is this folder, bind-mounted, and uvicorn reloads on save.
|
||||||
|
# docker compose -f compose.yml -f compose.dev.yml up --build
|
||||||
|
# docker compose -f compose.yml -f compose.dev.yml run --rm app pytest
|
||||||
|
# `update` is disabled in dev; use git on the host. Separate project name = separate volumes.
|
||||||
|
name: network-monitor-dev
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
container_name: network-monitor-dev
|
||||||
|
environment:
|
||||||
|
DEV: "1"
|
||||||
|
CONTAINER_NAME: network-monitor-dev
|
||||||
|
volumes:
|
||||||
|
- .:/srv/src
|
||||||
40
compose.probe.yml
Normal file
40
compose.probe.yml
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
# A probe. install-probe.sh sets this up on each machine (see README); by hand it is:
|
||||||
|
# clone into /opt/network-probe, write .env from .env.probe.example,
|
||||||
|
# docker compose -f compose.probe.yml up -d --build
|
||||||
|
# Deploys after that: docker exec network-probe update
|
||||||
|
#
|
||||||
|
# Host networking on purpose: the probe must measure the machine's real link (not Docker's
|
||||||
|
# bridge), serve its test endpoint on the LAN, and read the host's ARP table and gateway.
|
||||||
|
name: network-probe
|
||||||
|
services:
|
||||||
|
probe:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: container/Dockerfile
|
||||||
|
image: network-monitor:latest
|
||||||
|
container_name: network-probe
|
||||||
|
restart: unless-stopped
|
||||||
|
network_mode: host
|
||||||
|
environment:
|
||||||
|
ROLE: probe
|
||||||
|
CONTAINER_NAME: network-probe
|
||||||
|
PORT: ${PROBE_PORT:-8765}
|
||||||
|
volumes:
|
||||||
|
- runtime:/srv # source checkout, venv, update state
|
||||||
|
- data:/data # last config from the hub, so it keeps testing while the hub is down
|
||||||
|
- ./.env:/run/config/app.env:ro
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 192m
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: 10m
|
||||||
|
max-file: "3"
|
||||||
|
volumes:
|
||||||
|
runtime:
|
||||||
|
data:
|
||||||
42
compose.yml
Normal file
42
compose.yml
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
# The hub (web UI + API). install.sh sets this up on a server (see README); by hand it is:
|
||||||
|
# clone into /opt/network-monitor, write .env from .env.example, docker compose up -d --build
|
||||||
|
# Deploys after that: docker exec network-monitor update
|
||||||
|
name: network-monitor
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: container/Dockerfile
|
||||||
|
image: network-monitor:latest
|
||||||
|
container_name: network-monitor
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
ROLE: hub
|
||||||
|
CONTAINER_NAME: network-monitor
|
||||||
|
# Only a reverse proxy at these addresses may set X-Forwarded-For.
|
||||||
|
FORWARDED_ALLOW_IPS: ${FORWARDED_ALLOW_IPS:-127.0.0.1}
|
||||||
|
# Probes on other machines report here, so .env sets HOST_BIND=0.0.0.0 (LAN). Use
|
||||||
|
# HOST_BIND=127.0.0.1 behind a reverse proxy.
|
||||||
|
ports:
|
||||||
|
- "${HOST_BIND:-127.0.0.1}:${HOST_PORT:-8000}:8000"
|
||||||
|
volumes:
|
||||||
|
- runtime:/srv # source checkout, venv, update state
|
||||||
|
- data:/data # the app's persistent data
|
||||||
|
# Repo URL, credentials and app settings, read on every start and every update.
|
||||||
|
# Not env_file: a mounted file can change without recreating the container.
|
||||||
|
- ./.env:/run/config/app.env:ro
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 256m
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: 10m
|
||||||
|
max-file: "3"
|
||||||
|
volumes:
|
||||||
|
runtime:
|
||||||
|
data:
|
||||||
35
container/Dockerfile
Normal file
35
container/Dockerfile
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
# The image is the runtime only: Python, git and the scripts in this folder. The app's
|
||||||
|
# source is cloned into the /srv volume on first start and updated in place by `update`,
|
||||||
|
# so a rebuild is needed only when this folder or the Python version changes.
|
||||||
|
ARG PYTHON_VERSION=3.14
|
||||||
|
FROM python:${PYTHON_VERSION}-slim
|
||||||
|
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends git openssh-client tini \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
ARG UID=1000
|
||||||
|
ARG GID=1000
|
||||||
|
RUN groupadd --gid "$GID" app \
|
||||||
|
&& useradd --uid "$UID" --gid app --create-home --shell /usr/sbin/nologin app \
|
||||||
|
&& mkdir -p /srv/src /srv/venv /srv/state /data \
|
||||||
|
&& chown -R app:app /srv /data \
|
||||||
|
&& git config --system --add safe.directory '*'
|
||||||
|
|
||||||
|
COPY container/lib.sh /usr/local/lib/app/lib.sh
|
||||||
|
COPY --chmod=755 container/entrypoint.sh /usr/local/bin/entrypoint
|
||||||
|
COPY --chmod=755 container/update.sh /usr/local/bin/update
|
||||||
|
|
||||||
|
ENV PATH=/srv/venv/bin:$PATH \
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
PIP_NO_CACHE_DIR=1 \
|
||||||
|
DATA_DIR=/data \
|
||||||
|
PORT=8000
|
||||||
|
|
||||||
|
USER app
|
||||||
|
WORKDIR /srv/src
|
||||||
|
EXPOSE 8000
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
|
||||||
|
CMD python3 -c "import os, urllib.request; urllib.request.urlopen(f'http://127.0.0.1:{os.environ[\"PORT\"]}/healthz', timeout=3)"
|
||||||
|
ENTRYPOINT ["tini", "--", "entrypoint"]
|
||||||
58
container/entrypoint.sh
Executable file
58
container/entrypoint.sh
Executable file
|
|
@ -0,0 +1,58 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Container entrypoint (runs under tini). Gets the source and venv ready, then supervises
|
||||||
|
# uvicorn: SIGHUP restarts the app on the current checkout (that's how `update` swaps code
|
||||||
|
# in without restarting the container); SIGTERM stops it. If the app dies on its own, the
|
||||||
|
# container exits and Docker's restart policy takes over.
|
||||||
|
#
|
||||||
|
# With arguments, it runs them in the source dir after setup instead, e.g.
|
||||||
|
# docker compose run --rm app pytest
|
||||||
|
set -uo pipefail
|
||||||
|
. /usr/local/lib/app/lib.sh
|
||||||
|
|
||||||
|
load_env
|
||||||
|
ensure_source || exit 1
|
||||||
|
sync_deps || die "installing requirements failed"
|
||||||
|
cd "$SRC"
|
||||||
|
|
||||||
|
if [ $# -gt 0 ]; then
|
||||||
|
export PATH="$VENV/bin:$PATH"
|
||||||
|
exec "$@"
|
||||||
|
fi
|
||||||
|
|
||||||
|
child=
|
||||||
|
stopping=0
|
||||||
|
restart=0
|
||||||
|
trap 'stopping=1; [ -n "$child" ] && kill -TERM "$child" 2>/dev/null' TERM INT
|
||||||
|
trap 'restart=1; [ -n "$child" ] && kill -TERM "$child" 2>/dev/null' HUP
|
||||||
|
echo $$ > "$PIDFILE"
|
||||||
|
|
||||||
|
start_app() {
|
||||||
|
local args=(app.main:app --host 0.0.0.0 --port "$PORT"
|
||||||
|
--proxy-headers --forwarded-allow-ips "${FORWARDED_ALLOW_IPS:-127.0.0.1}"
|
||||||
|
--no-server-header --timeout-graceful-shutdown 10)
|
||||||
|
[ "${DEV:-}" = 1 ] && args+=(--reload)
|
||||||
|
export APP_VERSION
|
||||||
|
APP_VERSION=$(current_version)
|
||||||
|
log "starting app at $APP_VERSION"
|
||||||
|
env "${APP_ENV_UNSET[@]}" "$VENV/bin/uvicorn" "${args[@]}" &
|
||||||
|
child=$!
|
||||||
|
}
|
||||||
|
|
||||||
|
while :; do
|
||||||
|
start_app
|
||||||
|
wait "$child"; rc=$?
|
||||||
|
# A trapped signal interrupts `wait` while the child is still shutting down.
|
||||||
|
while kill -0 "$child" 2>/dev/null; do wait "$child"; rc=$?; done
|
||||||
|
[ "$stopping" = 1 ] && exit 0
|
||||||
|
if [ "$restart" = 1 ]; then restart=0; continue; fi
|
||||||
|
log "app exited with status $rc"
|
||||||
|
# New code that crashes at startup must not take the container down mid-update, or
|
||||||
|
# `update` dies with it and can't roll back. Wait for its restart signal instead.
|
||||||
|
if ! flock -n /tmp/app-update.lock true; then
|
||||||
|
log "an update is running; waiting for it to restart the app"
|
||||||
|
while [ "$restart" = 0 ] && [ "$stopping" = 0 ]; do sleep 1 & wait $!; done
|
||||||
|
[ "$stopping" = 1 ] && exit 0
|
||||||
|
restart=0; continue
|
||||||
|
fi
|
||||||
|
exit "$rc"
|
||||||
|
done
|
||||||
122
container/lib.sh
Normal file
122
container/lib.sh
Normal file
|
|
@ -0,0 +1,122 @@
|
||||||
|
# Shared by entrypoint and update. Installed at /usr/local/lib/app/lib.sh.
|
||||||
|
# Config: the project .env, mounted at /run/config/app.env, read by load_env.
|
||||||
|
# Layout inside the container:
|
||||||
|
# /srv/src git checkout of the app (cloned from REPO_URL on first start, or bind-mounted in dev)
|
||||||
|
# /srv/venv virtualenv built from requirements.txt (rebuilt when requirements or Python change)
|
||||||
|
# /srv/state update bookkeeping (previous commit, ssh known_hosts)
|
||||||
|
# /data the app's own persistent data
|
||||||
|
# /srv is one named volume, so source, venv and state survive container recreation.
|
||||||
|
|
||||||
|
SRC=${SRC:-/srv/src}
|
||||||
|
VENV=${VENV:-/srv/venv}
|
||||||
|
STATE=${STATE:-/srv/state}
|
||||||
|
PORT=${PORT:-8000}
|
||||||
|
PIDFILE=/tmp/app-supervisor.pid
|
||||||
|
ENV_FILE=${ENV_FILE:-/run/config/app.env}
|
||||||
|
|
||||||
|
log() { echo "[$(basename "$0")] $*" >&2; }
|
||||||
|
die() { log "error: $*"; exit 1; }
|
||||||
|
|
||||||
|
# Read the project's .env (bind-mounted read-only at $ENV_FILE). It runs on every start
|
||||||
|
# and every update, so a new URL or rotated token takes effect without a rebuild.
|
||||||
|
# Plain KEY=value lines only; it is parsed, not executed. Values never get printed.
|
||||||
|
load_env() {
|
||||||
|
[ -e "$ENV_FILE" ] || return 0
|
||||||
|
[ -f "$ENV_FILE" ] || die "$ENV_FILE is not a file (create .env before 'docker compose up'; Docker made a directory in its place)"
|
||||||
|
[ -r "$ENV_FILE" ] || die "$ENV_FILE is not readable by uid $(id -u): chown $(id -u) .env && chmod 600 .env on the host"
|
||||||
|
local line key val
|
||||||
|
while IFS= read -r line || [ -n "$line" ]; do
|
||||||
|
line=${line%$'\r'}
|
||||||
|
[[ $line =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue
|
||||||
|
key=${BASH_REMATCH[2]} val=${BASH_REMATCH[3]}
|
||||||
|
if [[ $val =~ ^\"(.*)\"$ || $val =~ ^\'(.*)\'$ ]]; then val=${BASH_REMATCH[1]}; fi
|
||||||
|
export "$key=$val"
|
||||||
|
done < "$ENV_FILE"
|
||||||
|
setup_git_auth
|
||||||
|
}
|
||||||
|
|
||||||
|
# Credentials for REPO_URL, from the environment only. Nothing is written into the checkout:
|
||||||
|
# https: GIT_TOKEN (+ GIT_USERNAME, default x-access-token) answered by a credential helper
|
||||||
|
# ssh: GIT_SSH_KEY, the private key base64-encoded (base64 -w0 deploy_key)
|
||||||
|
setup_git_auth() {
|
||||||
|
if [ -n "${GIT_TOKEN:-}" ]; then
|
||||||
|
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=credential.helper
|
||||||
|
export GIT_CONFIG_VALUE_0='!f() { [ "$1" = get ] || exit 0; echo "username=${GIT_USERNAME:-x-access-token}"; echo "password=$GIT_TOKEN"; }; f'
|
||||||
|
fi
|
||||||
|
local ssh="ssh -o UserKnownHostsFile=$STATE/known_hosts -o StrictHostKeyChecking=accept-new"
|
||||||
|
if [ -n "${GIT_SSH_KEY:-}" ]; then
|
||||||
|
local key=/tmp/git-deploy-key
|
||||||
|
(umask 077; printf '%s' "$GIT_SSH_KEY" | base64 -d > "$key") || die "GIT_SSH_KEY is not valid base64"
|
||||||
|
ssh="$ssh -i $key -o IdentitiesOnly=yes"
|
||||||
|
fi
|
||||||
|
export GIT_SSH_COMMAND="$ssh" GIT_TERMINAL_PROMPT=0
|
||||||
|
}
|
||||||
|
|
||||||
|
# Hide user:password@ if someone put credentials in the URL anyway.
|
||||||
|
redact() { printf '%s' "$1" | sed -E 's#://[^/@]+@#://***@#'; }
|
||||||
|
|
||||||
|
# The app gets the .env settings but not the repo credentials.
|
||||||
|
APP_ENV_UNSET=(-u GIT_TOKEN -u GIT_USERNAME -u GIT_SSH_KEY -u GIT_CONFIG_COUNT -u GIT_CONFIG_KEY_0 -u GIT_CONFIG_VALUE_0)
|
||||||
|
|
||||||
|
# Clone the source on first start. A bind-mounted checkout (dev) already has .git.
|
||||||
|
ensure_source() {
|
||||||
|
mkdir -p "$STATE"
|
||||||
|
[ -d "$SRC/.git" ] && return 0
|
||||||
|
[ -n "${REPO_URL:-}" ] || die "no source at $SRC and REPO_URL is not set in .env"
|
||||||
|
log "cloning $(redact "$REPO_URL") (${REPO_REF:-main}) into $SRC"
|
||||||
|
# $SRC may exist as an empty dir; clone into it.
|
||||||
|
git clone --quiet --branch "${REPO_REF:-main}" "$REPO_URL" "$SRC"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Follow REPO_URL if .env changed it. Credentials are never part of the stored URL.
|
||||||
|
sync_remote() {
|
||||||
|
[ -n "${REPO_URL:-}" ] || return 0
|
||||||
|
[ "$(git -C "$SRC" remote get-url origin 2>/dev/null)" = "$REPO_URL" ] || git -C "$SRC" remote set-url origin "$REPO_URL"
|
||||||
|
}
|
||||||
|
|
||||||
|
requirement_files() {
|
||||||
|
echo "$SRC/requirements.txt"
|
||||||
|
if [ "${DEV:-}" = 1 ] && [ -f "$SRC/requirements-dev.txt" ]; then echo "$SRC/requirements-dev.txt"; fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Bring the venv in line with the checkout. A no-op when nothing changed.
|
||||||
|
sync_deps() {
|
||||||
|
local py want files
|
||||||
|
py=$(python3 -c 'import sys; print("%d.%d.%d" % sys.version_info[:3])')
|
||||||
|
mapfile -t files < <(requirement_files)
|
||||||
|
want="$py $(cat "${files[@]}" | sha256sum | cut -d' ' -f1)"
|
||||||
|
if [ "$(cat "$VENV/.python" 2>/dev/null)" != "$py" ]; then
|
||||||
|
log "creating venv for Python $py"
|
||||||
|
rm -rf "$VENV"
|
||||||
|
python3 -m venv "$VENV"
|
||||||
|
echo "$py" > "$VENV/.python"
|
||||||
|
fi
|
||||||
|
[ "$(cat "$VENV/.synced" 2>/dev/null)" = "$want" ] && return 0
|
||||||
|
log "installing requirements"
|
||||||
|
local args=()
|
||||||
|
for f in "${files[@]}"; do args+=(-r "$f"); done
|
||||||
|
"$VENV/bin/pip" install --quiet --disable-pip-version-check --no-cache-dir "${args[@]}" || return 1
|
||||||
|
echo "$want" > "$VENV/.synced"
|
||||||
|
}
|
||||||
|
|
||||||
|
# The new code must at least import before it replaces the running app.
|
||||||
|
check_import() {
|
||||||
|
(cd "$SRC" && "$VENV/bin/python" -c 'import app.main') || return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
current_version() { git -C "$SRC" rev-parse --short HEAD 2>/dev/null || echo dev; }
|
||||||
|
|
||||||
|
# Wait until /healthz answers with the expected version (or any version if none given).
|
||||||
|
wait_healthy() {
|
||||||
|
local want=${1:-} timeout=${HEALTH_TIMEOUT:-30} got
|
||||||
|
for _ in $(seq 1 "$timeout"); do
|
||||||
|
got=$(python3 - "$PORT" <<'PY' 2>/dev/null
|
||||||
|
import json, sys, urllib.request
|
||||||
|
r = urllib.request.urlopen(f"http://127.0.0.1:{sys.argv[1]}/healthz", timeout=2)
|
||||||
|
print(json.load(r).get("version", ""))
|
||||||
|
PY
|
||||||
|
) && { [ -z "$want" ] || [ "$got" = "$want" ]; } && return 0
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
81
container/update.sh
Executable file
81
container/update.sh
Executable file
|
|
@ -0,0 +1,81 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Pull the latest source from the remote repo in .env (REPO_URL, REPO_REF and credentials)
|
||||||
|
# into the running container and restart the app on it. No rebuild.
|
||||||
|
# docker exec <container> update # to the tip of REPO_REF
|
||||||
|
# docker exec <container> update <ref> # to a tag, branch or commit
|
||||||
|
# docker exec <container> update --check # show what an update would bring in
|
||||||
|
# docker exec <container> update --rollback # back to the commit before the last update
|
||||||
|
# Steps: fetch, check out, sync requirements, import check, restart, wait for /healthz to
|
||||||
|
# report the new commit. If any step fails, it puts the previous commit back and exits 1.
|
||||||
|
set -euo pipefail
|
||||||
|
. /usr/local/lib/app/lib.sh
|
||||||
|
|
||||||
|
usage() { sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; }
|
||||||
|
|
||||||
|
mode=update force=0 ref=
|
||||||
|
while [ $# -gt 0 ]; do
|
||||||
|
case $1 in
|
||||||
|
--check) mode=check ;;
|
||||||
|
--rollback) mode=rollback ;;
|
||||||
|
--force) force=1 ;;
|
||||||
|
-h|--help) usage ;;
|
||||||
|
-*) usage 1 ;;
|
||||||
|
*) ref=$1 ;;
|
||||||
|
esac
|
||||||
|
shift
|
||||||
|
done
|
||||||
|
|
||||||
|
load_env
|
||||||
|
[ "${DEV:-}" = 1 ] && die "dev mode: the source is bind-mounted from the host; update it with git there"
|
||||||
|
[ -d "$SRC/.git" ] || die "no checkout at $SRC"
|
||||||
|
exec 9>/tmp/app-update.lock
|
||||||
|
flock -n 9 || die "another update is running"
|
||||||
|
cd "$SRC"
|
||||||
|
|
||||||
|
old=$(git rev-parse HEAD)
|
||||||
|
if [ "$mode" = rollback ]; then
|
||||||
|
new=$(cat "$STATE/previous" 2>/dev/null) || die "no previous commit recorded"
|
||||||
|
else
|
||||||
|
sync_remote
|
||||||
|
git fetch --quiet --prune --tags origin
|
||||||
|
target=${ref:-${REPO_REF:-main}}
|
||||||
|
# A branch resolves on the remote; a tag or commit as given.
|
||||||
|
new=$(git rev-parse --verify --quiet "origin/$target^{commit}" || git rev-parse --verify --quiet "$target^{commit}") \
|
||||||
|
|| die "unknown ref: $target"
|
||||||
|
fi
|
||||||
|
short() { git rev-parse --short "$1"; }
|
||||||
|
|
||||||
|
if [ "$mode" = check ]; then
|
||||||
|
if [ "$old" = "$new" ]; then echo "up to date at $(short "$old")"; else
|
||||||
|
echo "$(short "$old") -> $(short "$new")"
|
||||||
|
git log --oneline "$old..$new" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
[ "$old" = "$new" ] && { echo "already at $(short "$new")"; exit 0; }
|
||||||
|
|
||||||
|
if [ "$force" = 0 ] && [ -n "$(git status --porcelain --untracked-files=no)" ]; then
|
||||||
|
die "the checkout has local changes (inspect with: docker exec ${CONTAINER_NAME:-<container>} git -C $SRC status); --force discards them"
|
||||||
|
fi
|
||||||
|
|
||||||
|
restart_app() { kill -HUP "$(cat "$PIDFILE")" || return 1; sleep 1; }
|
||||||
|
apply() { git reset --quiet --hard "$1" && sync_deps && check_import; }
|
||||||
|
|
||||||
|
restarted=0
|
||||||
|
log "updating $(short "$old") -> $(short "$new")"
|
||||||
|
if apply "$new" && restarted=1 && restart_app && wait_healthy "$(short "$new")"; then
|
||||||
|
echo "$old" > "$STATE/previous"
|
||||||
|
git log --oneline "$old..$new" 2>/dev/null | head -20 || true
|
||||||
|
if [ -n "$(git diff --name-only "$old" "$new" -- container/)" ]; then
|
||||||
|
log "note: container/ changed; rebuild the image to pick that up (docker compose up -d --build)"
|
||||||
|
fi
|
||||||
|
echo "updated to $(short "$new")"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "update failed; going back to $(short "$old")"
|
||||||
|
apply "$old" || die "could not restore $(short "$old"): the app may be down, check: docker logs ${CONTAINER_NAME:-<container>}"
|
||||||
|
[ "$restarted" = 1 ] || { log "the running app was never touched"; exit 1; }
|
||||||
|
restart_app && wait_healthy "$(short "$old")" || die "restored $(short "$old") but it is not healthy; check: docker logs ${CONTAINER_NAME:-<container>}"
|
||||||
|
log "running $(short "$old") again"
|
||||||
|
exit 1
|
||||||
365
install-probe.sh
Executable file
365
install-probe.sh
Executable file
|
|
@ -0,0 +1,365 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# GENERATED from install.sh by scripts/build-installers.sh. Edit install.sh, then run that script.
|
||||||
|
#
|
||||||
|
# Install (or upgrade) a Network Monitor PROBE. The hub's "Add probe" dialog prints the exact
|
||||||
|
# command, with this probe's token:
|
||||||
|
#
|
||||||
|
# curl -fsSL https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install-probe.sh | HUB_URL=http://hub:8000 PROBE_TOKEN=... bash
|
||||||
|
#
|
||||||
|
# Native mode on Linux (Proxmox LXC, bare metal) runs as root:
|
||||||
|
# curl -fsSL https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install-probe.sh | sudo env HUB_URL=http://hub:8000 PROBE_TOKEN=... bash
|
||||||
|
#
|
||||||
|
# Serve-only probe (e.g. a VPS the others test against): leave out HUB_URL and PROBE_TOKEN,
|
||||||
|
# and open PROBE_PORT (default 8765/tcp) in its firewall.
|
||||||
|
#
|
||||||
|
# Private repo over https: add GIT_TOKEN, read without echoing it:
|
||||||
|
# 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
|
||||||
|
#
|
||||||
|
# Two ways to run (INSTALL_MODE):
|
||||||
|
# docker The probe in a container with host networking. Default on Linux hosts.
|
||||||
|
# native A Python virtualenv and a boot service: systemd on Linux, launchd on macOS.
|
||||||
|
# Default on macOS and inside LXC containers (e.g. Proxmox LXC).
|
||||||
|
# On Linux it also lets unprivileged processes ping (net.ipv4.ping_group_range, persisted in
|
||||||
|
# /etc/sysctl.d). Re-running is safe: it keeps .env (values you pass replace those keys).
|
||||||
|
# Ordinary deploys:
|
||||||
|
# docker: docker exec network-probe update
|
||||||
|
# native: sudo network-probe-update (macOS: network-probe-update)
|
||||||
|
#
|
||||||
|
# Settings (environment variables, all optional):
|
||||||
|
# HUB_URL, PROBE_TOKEN the hub to report to and this probe's token
|
||||||
|
# PROBE_PORT default 8765 (the probe's test server, on all interfaces)
|
||||||
|
# ADVERTISE_ADDR address other probes use for this one (default: what the hub sees)
|
||||||
|
# INSTALL_MODE docker | native (default: see above)
|
||||||
|
# INSTALL_DIR default /opt/network-probe
|
||||||
|
# REPO_URL, REPO_REF default https://git.neilbantoc.dev/services/network-monitor.git, main
|
||||||
|
# GIT_TOKEN, GIT_USERNAME private repo over https
|
||||||
|
# GIT_SSH_KEY private repo over SSH (base64-encoded deploy key)
|
||||||
|
#
|
||||||
|
# Everything is inside main(), so a partial download runs nothing. bash 3.2 compatible (macOS).
|
||||||
|
|
||||||
|
NETMON_ROLE=probe
|
||||||
|
|
||||||
|
main() {
|
||||||
|
set -euo pipefail
|
||||||
|
ROLE=$NETMON_ROLE
|
||||||
|
if [ "$ROLE" = probe ]; then
|
||||||
|
NAME=network-probe DEFAULT_PORT=8765 PORT_KEY=PROBE_PORT ENV_EXAMPLE=.env.probe.example COMPOSE_FILE=compose.probe.yml
|
||||||
|
KEYS="REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY INSTALL_MODE HUB_URL PROBE_TOKEN PROBE_PORT ADVERTISE_ADDR"
|
||||||
|
else
|
||||||
|
NAME=network-monitor DEFAULT_PORT=8000 PORT_KEY=HOST_PORT ENV_EXAMPLE=.env.example COMPOSE_FILE=compose.yml
|
||||||
|
KEYS="REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY INSTALL_MODE HOST_PORT"
|
||||||
|
fi
|
||||||
|
INSTALL_DIR=${INSTALL_DIR:-/opt/$NAME}
|
||||||
|
local DEFAULT_REPO_URL="https://git.neilbantoc.dev/services/network-monitor.git" DEFAULT_REF="main"
|
||||||
|
# Keys the caller passed explicitly (these replace values in an existing .env).
|
||||||
|
PASSED=" "
|
||||||
|
local k
|
||||||
|
for k in $KEYS; do [ -z "${!k:-}" ] || PASSED="$PASSED$k "; done
|
||||||
|
|
||||||
|
OS=$(uname -s)
|
||||||
|
case $OS in Linux|Darwin) ;; *) die "this installer is for Linux and macOS" ;; esac
|
||||||
|
SUDO=
|
||||||
|
if [ "$(id -u)" != 0 ]; then
|
||||||
|
command -v sudo >/dev/null || die "run as root, or install sudo"
|
||||||
|
SUDO=sudo
|
||||||
|
fi
|
||||||
|
|
||||||
|
step "source"
|
||||||
|
load_existing_env
|
||||||
|
REPO_URL=${REPO_URL:-$DEFAULT_REPO_URL}
|
||||||
|
REPO_REF=${REPO_REF:-$DEFAULT_REF}
|
||||||
|
printf -v "$PORT_KEY" '%s' "${!PORT_KEY:-$DEFAULT_PORT}"
|
||||||
|
choose_mode
|
||||||
|
|
||||||
|
step "prerequisites"
|
||||||
|
install_packages
|
||||||
|
if [ "$MODE" = docker ]; then install_docker; fi
|
||||||
|
if [ "$ROLE" = probe ] && [ "$OS" = Linux ]; then enable_ping; fi
|
||||||
|
|
||||||
|
step "checkout"
|
||||||
|
git_auth
|
||||||
|
check_access
|
||||||
|
checkout
|
||||||
|
|
||||||
|
step "configuration"
|
||||||
|
write_env
|
||||||
|
if [ "$ROLE" = probe ]; then check_hub; fi
|
||||||
|
|
||||||
|
step "service"
|
||||||
|
if [ "$MODE" = docker ]; then
|
||||||
|
(cd "$INSTALL_DIR" && $DOCKER compose -f "$COMPOSE_FILE" up -d --build --remove-orphans)
|
||||||
|
else
|
||||||
|
NAME=$NAME ROLE=$ROLE INSTALL_DIR=$INSTALL_DIR bash "$INSTALL_DIR/native/setup.sh"
|
||||||
|
fi
|
||||||
|
wait_healthy
|
||||||
|
|
||||||
|
step "done"
|
||||||
|
finish_message
|
||||||
|
}
|
||||||
|
|
||||||
|
step() { printf '\n==> %s\n' "$*"; }
|
||||||
|
log() { printf ' %s\n' "$*"; }
|
||||||
|
die() { printf '\nerror: %s\n' "$*" >&2; exit 1; }
|
||||||
|
in_list() { case " $2 " in *" $1 "*) return 0 ;; esac; return 1; }
|
||||||
|
|
||||||
|
# Run a command directly, and only with sudo if that fails (no password prompt when not needed).
|
||||||
|
priv() { "$@" 2>/dev/null || { [ -n "$SUDO" ] && $SUDO "$@"; }; }
|
||||||
|
read_file() { if [ -r "$1" ]; then cat "$1"; else $SUDO cat "$1"; fi; }
|
||||||
|
|
||||||
|
is_lxc() {
|
||||||
|
[ "$OS" = Linux ] || return 1
|
||||||
|
[ "$(systemd-detect-virt -c 2>/dev/null || true)" = lxc ] && return 0
|
||||||
|
grep -qa 'container=lxc' /proc/1/environ 2>/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
choose_mode() {
|
||||||
|
MODE=${INSTALL_MODE:-auto}
|
||||||
|
if [ "$MODE" = auto ]; then
|
||||||
|
if [ "$OS" = Darwin ]; then MODE=native
|
||||||
|
elif is_lxc; then MODE=native; log "LXC container detected: native mode (set INSTALL_MODE=docker for Docker)"
|
||||||
|
else MODE=docker; fi
|
||||||
|
fi
|
||||||
|
case $MODE in docker|native) ;; *) die "INSTALL_MODE must be docker or native, not '$MODE'" ;; esac
|
||||||
|
if [ "$OS" = Darwin ] && [ "$MODE" = docker ]; then
|
||||||
|
die "on macOS use INSTALL_MODE=native: Docker Desktop runs containers in a VM, so a probe would measure the VM's network, and it only starts at login"
|
||||||
|
fi
|
||||||
|
if [ "$OS" = Linux ] && [ "$MODE" = native ] && [ "$(id -u)" != 0 ]; then
|
||||||
|
die "native mode on Linux installs a system service: run as root, e.g. curl -fsSL <installer URL> | sudo env VAR=value ... bash"
|
||||||
|
fi
|
||||||
|
if [ "$OS" = Darwin ] && [ "$(id -u)" = 0 ]; then
|
||||||
|
die "on macOS, run the installer as your own user (it asks for sudo when it needs it)"
|
||||||
|
fi
|
||||||
|
INSTALL_MODE=$MODE
|
||||||
|
in_list INSTALL_MODE "$PASSED" || PASSED="${PASSED}INSTALL_MODE "
|
||||||
|
log "mode: $MODE"
|
||||||
|
}
|
||||||
|
|
||||||
|
install_packages() {
|
||||||
|
if [ "$OS" = Darwin ]; then
|
||||||
|
xcode-select -p >/dev/null 2>&1 || die "git needs the Xcode Command Line Tools: run xcode-select --install, then this installer again"
|
||||||
|
log "git, curl, ssh: present"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
local need=""
|
||||||
|
command -v git >/dev/null || need="$need git"
|
||||||
|
command -v curl >/dev/null || need="$need curl"
|
||||||
|
command -v ssh >/dev/null || need="$need ssh"
|
||||||
|
[ -n "$need" ] || { log "git, curl, ssh: present"; return; }
|
||||||
|
log "installing$need"
|
||||||
|
if command -v apt-get >/dev/null; then
|
||||||
|
$SUDO env DEBIAN_FRONTEND=noninteractive apt-get update -qq
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
$SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq ca-certificates $(echo $need | sed 's/ssh/openssh-client/') >/dev/null
|
||||||
|
elif command -v dnf >/dev/null; then
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
$SUDO dnf install -y -q ca-certificates $(echo $need | sed 's/ssh/openssh-clients/')
|
||||||
|
elif command -v apk >/dev/null; then
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
$SUDO apk add -q ca-certificates $(echo $need | sed 's/ssh/openssh-client/')
|
||||||
|
else
|
||||||
|
die "no apt-get, dnf or apk: install$need yourself and re-run"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
install_docker() {
|
||||||
|
if ! command -v docker >/dev/null; then
|
||||||
|
log "installing Docker Engine + Compose (get.docker.com)"
|
||||||
|
local dlog; dlog=$(mktemp)
|
||||||
|
curl -fsSL https://get.docker.com | $SUDO sh >"$dlog" 2>&1 || { tail -20 "$dlog" >&2; die "Docker install failed (full log: $dlog)"; }
|
||||||
|
rm -f "$dlog"
|
||||||
|
fi
|
||||||
|
if ! docker info >/dev/null 2>&1 && ! $SUDO docker info >/dev/null 2>&1 \
|
||||||
|
&& command -v systemctl >/dev/null && [ -d /run/systemd/system ]; then
|
||||||
|
$SUDO systemctl enable --now docker >/dev/null 2>&1 || true
|
||||||
|
fi
|
||||||
|
if docker info >/dev/null 2>&1; then DOCKER=docker; else DOCKER="$SUDO docker"; fi
|
||||||
|
$DOCKER info >/dev/null 2>&1 || die "Docker is installed but the daemon is not running"
|
||||||
|
$DOCKER compose version >/dev/null 2>&1 || die "the Docker Compose plugin is missing (apt-get install docker-compose-plugin)"
|
||||||
|
log "docker $($DOCKER version --format '{{.Server.Version}}'), compose $($DOCKER compose version --short)"
|
||||||
|
}
|
||||||
|
|
||||||
|
# The probe runs without root or capabilities, so ping needs unprivileged ICMP sockets.
|
||||||
|
# Most distros allow them already (systemd's default); some ship "1 0", which blocks them.
|
||||||
|
enable_ping() {
|
||||||
|
local want="0 2147483647" cur tmp
|
||||||
|
cur=$(sysctl -n net.ipv4.ping_group_range 2>/dev/null | tr -s '[:space:]' ' ' | sed 's/ $//') || cur=
|
||||||
|
if [ "$cur" = "$want" ]; then log "ping: unprivileged ICMP allowed"; return; fi
|
||||||
|
log "ping: allowing unprivileged ICMP (net.ipv4.ping_group_range was '${cur:-unknown}')"
|
||||||
|
tmp=$(mktemp)
|
||||||
|
printf 'net.ipv4.ping_group_range = %s\n' "$want" > "$tmp"
|
||||||
|
if priv install -m 644 "$tmp" /etc/sysctl.d/60-network-probe-ping.conf \
|
||||||
|
&& priv sysctl -q -w "net.ipv4.ping_group_range=$want" >/dev/null; then
|
||||||
|
log "ping: enabled (persisted in /etc/sysctl.d/60-network-probe-ping.conf)"
|
||||||
|
else
|
||||||
|
log "warning: could not set net.ipv4.ping_group_range; the probe will skip ping and use HTTP and DNS checks only"
|
||||||
|
fi
|
||||||
|
rm -f "$tmp"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Values already in .env fill in whatever the caller did not pass.
|
||||||
|
load_existing_env() {
|
||||||
|
local f="$INSTALL_DIR/.env" line key val
|
||||||
|
[ -f "$f" ] || return 0
|
||||||
|
log "keeping existing $f"
|
||||||
|
while IFS= read -r line || [ -n "$line" ]; do
|
||||||
|
line=${line%$'\r'}
|
||||||
|
[[ $line =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue
|
||||||
|
key=${BASH_REMATCH[2]} val=${BASH_REMATCH[3]}
|
||||||
|
if [[ $val =~ ^\"(.*)\"$ || $val =~ ^\'(.*)\'$ ]]; then val=${BASH_REMATCH[1]}; fi
|
||||||
|
if in_list "$key" "$KEYS" && [ -z "${!key:-}" ]; then printf -v "$key" '%s' "$val"; fi
|
||||||
|
done < <(read_file "$f")
|
||||||
|
}
|
||||||
|
|
||||||
|
# Credentials reach git through the environment only; nothing is stored in the checkout.
|
||||||
|
git_auth() {
|
||||||
|
export GIT_TERMINAL_PROMPT=0
|
||||||
|
if [ -n "${GIT_TOKEN:-}" ]; then
|
||||||
|
export GIT_TOKEN GIT_USERNAME="${GIT_USERNAME:-}"
|
||||||
|
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=credential.helper
|
||||||
|
export GIT_CONFIG_VALUE_0='!f() { [ "$1" = get ] || exit 0; echo "username=${GIT_USERNAME:-x-access-token}"; echo "password=$GIT_TOKEN"; }; f'
|
||||||
|
fi
|
||||||
|
local ssh="ssh -o StrictHostKeyChecking=accept-new"
|
||||||
|
if [ -n "${GIT_SSH_KEY:-}" ]; then
|
||||||
|
KEYFILE=$(mktemp); trap 'rm -f "$KEYFILE"' EXIT
|
||||||
|
printf '%s' "$GIT_SSH_KEY" | base64 -d > "$KEYFILE" 2>/dev/null || die "GIT_SSH_KEY is not valid base64 (use: base64 -w0 deploy_key)"
|
||||||
|
ssh="$ssh -i $KEYFILE -o IdentitiesOnly=yes"
|
||||||
|
fi
|
||||||
|
export GIT_SSH_COMMAND="$ssh"
|
||||||
|
}
|
||||||
|
|
||||||
|
check_access() {
|
||||||
|
git ls-remote --exit-code --heads --tags "$REPO_URL" "$REPO_REF" >/dev/null 2>&1 && { log "repo reachable: $(redact "$REPO_URL") ($REPO_REF)"; return; }
|
||||||
|
# Private https repo and no token yet: ask on the terminal (stdin is this script).
|
||||||
|
if [ -z "${GIT_TOKEN:-}" ] && [[ $REPO_URL == https://* ]] && [ -r /dev/tty ]; then
|
||||||
|
printf ' %s needs a token. Git token (read-only): ' "$(redact "$REPO_URL")" > /dev/tty
|
||||||
|
IFS= read -rs GIT_TOKEN < /dev/tty; echo > /dev/tty
|
||||||
|
PASSED="${PASSED}GIT_TOKEN "
|
||||||
|
git_auth
|
||||||
|
git ls-remote --exit-code --heads --tags "$REPO_URL" "$REPO_REF" >/dev/null 2>&1 && { log "repo reachable with token"; return; }
|
||||||
|
fi
|
||||||
|
die "cannot read $REPO_REF from $(redact "$REPO_URL"). Check REPO_URL/REPO_REF, and pass GIT_TOKEN (https) or GIT_SSH_KEY (ssh) for a private repo"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Docker mode: the host checkout holds the compose file and container/ (the image source);
|
||||||
|
# the app runs from the container's own checkout, which `update` manages.
|
||||||
|
# Native mode: the app runs from this checkout, which <name>-update manages.
|
||||||
|
checkout() {
|
||||||
|
if [ ! -d "$INSTALL_DIR/.git" ]; then
|
||||||
|
priv mkdir -p "$INSTALL_DIR"
|
||||||
|
[ -w "$INSTALL_DIR" ] || $SUDO chown "$(id -u):$(id -g)" "$INSTALL_DIR"
|
||||||
|
[ -z "$(ls -A "$INSTALL_DIR" | grep -vx .env || true)" ] || die "$INSTALL_DIR exists and is not a checkout of $NAME"
|
||||||
|
log "new checkout in $INSTALL_DIR"
|
||||||
|
git -C "$INSTALL_DIR" init --quiet
|
||||||
|
git -C "$INSTALL_DIR" remote add origin "$REPO_URL"
|
||||||
|
fi
|
||||||
|
git -C "$INSTALL_DIR" remote set-url origin "$REPO_URL"
|
||||||
|
git -C "$INSTALL_DIR" fetch --quiet --prune --tags origin
|
||||||
|
local target
|
||||||
|
target=$(git -C "$INSTALL_DIR" rev-parse --verify --quiet "origin/$REPO_REF^{commit}" || git -C "$INSTALL_DIR" rev-parse --verify "$REPO_REF^{commit}")
|
||||||
|
git -C "$INSTALL_DIR" reset --quiet --hard "$target"
|
||||||
|
log "at $(git -C "$INSTALL_DIR" log -1 --format='%h %s')"
|
||||||
|
}
|
||||||
|
|
||||||
|
# .env: created from the example file on first install; on re-runs only the keys the caller
|
||||||
|
# passed are replaced. Docker: owned by uid 1000 (the container's user), mode 640.
|
||||||
|
# Native Linux: root, mode 640 (setup gives the service group read access). macOS: you, 600.
|
||||||
|
write_env() {
|
||||||
|
local f="$INSTALL_DIR/.env" src tmp line key seen=" "
|
||||||
|
if [ -f "$f" ]; then src=$f; else
|
||||||
|
src="$INSTALL_DIR/$ENV_EXAMPLE"
|
||||||
|
PASSED=" $KEYS "
|
||||||
|
log "writing $f"
|
||||||
|
fi
|
||||||
|
tmp=$(mktemp)
|
||||||
|
while IFS= read -r line || [ -n "$line" ]; do
|
||||||
|
key=${line%%=*}
|
||||||
|
if [[ $line =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] && in_list "$key" "$PASSED"; then
|
||||||
|
printf '%s=%s\n' "$key" "${!key:-}"; seen="$seen$key "
|
||||||
|
else
|
||||||
|
printf '%s\n' "$line"
|
||||||
|
fi
|
||||||
|
done < <(read_file "$src") > "$tmp"
|
||||||
|
for key in $PASSED; do in_list "$key" "$seen" || printf '%s=%s\n' "$key" "${!key:-}" >> "$tmp"; done
|
||||||
|
if [ "$MODE" = docker ]; then
|
||||||
|
priv install -m 640 -o 1000 -g "$(id -g)" "$tmp" "$f" || die "could not write $f"
|
||||||
|
elif [ "$OS" = Linux ]; then
|
||||||
|
install -m 640 -o 0 -g 0 "$tmp" "$f" || die "could not write $f"
|
||||||
|
else
|
||||||
|
install -m 600 "$tmp" "$f" || die "could not write $f"
|
||||||
|
fi
|
||||||
|
rm -f "$tmp"
|
||||||
|
log "set in .env:$(echo "$PASSED" | sed 's/ \{1,\}/ /g; s/ $//')"
|
||||||
|
}
|
||||||
|
|
||||||
|
check_hub() {
|
||||||
|
if [ -z "${HUB_URL:-}" ]; then
|
||||||
|
[ -z "${PROBE_TOKEN:-}" ] || die "PROBE_TOKEN is set but HUB_URL is not; pass both, or neither for a serve-only probe"
|
||||||
|
log "no HUB_URL: serve-only probe"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
[ -n "${PROBE_TOKEN:-}" ] || die "HUB_URL is set but PROBE_TOKEN is not. Copy the full command from the hub's Add probe dialog"
|
||||||
|
if curl -fsS --max-time 5 "$HUB_URL/healthz" >/dev/null 2>&1; then log "hub reachable at $HUB_URL"
|
||||||
|
else log "warning: can't reach $HUB_URL/healthz right now; the probe will keep measuring and report when it can"; fi
|
||||||
|
}
|
||||||
|
|
||||||
|
health_version() {
|
||||||
|
if [ "$MODE" = docker ] && [ "$ROLE" = hub ]; then
|
||||||
|
$DOCKER exec "$NAME" python3 -c 'import json,urllib.request;print(json.load(urllib.request.urlopen("http://127.0.0.1:8000/healthz",timeout=2))["version"])' 2>/dev/null
|
||||||
|
else
|
||||||
|
curl -fsS --max-time 2 "http://127.0.0.1:${!PORT_KEY}/healthz" 2>/dev/null | sed -n 's/.*"version":"\([^"]*\)".*/\1/p'
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_healthy() {
|
||||||
|
log "waiting for the app (the first start installs requirements)"
|
||||||
|
local i=0
|
||||||
|
while [ "$i" -lt 180 ]; do
|
||||||
|
if [ -n "$(health_version)" ]; then log "healthy at $(health_version)"; return; fi
|
||||||
|
if [ "$MODE" = docker ] && [ "$($DOCKER inspect -f '{{.State.Running}}' "$NAME" 2>/dev/null)" = false ]; then break; fi
|
||||||
|
sleep 1; i=$((i + 1))
|
||||||
|
done
|
||||||
|
if [ "$MODE" = docker ]; then $DOCKER logs --tail 40 "$NAME" >&2 || true
|
||||||
|
elif [ "$OS" = Linux ]; then journalctl -u "$NAME" -n 40 --no-pager >&2 || true
|
||||||
|
else tail -n 40 "$INSTALL_DIR/data/service.log" >&2 || true; fi
|
||||||
|
die "$NAME did not become healthy (logs above)"
|
||||||
|
}
|
||||||
|
|
||||||
|
my_ip() {
|
||||||
|
if [ "$OS" = Darwin ]; then ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || echo this-host
|
||||||
|
else hostname -I 2>/dev/null | cut -d' ' -f1 | grep . || echo this-host; fi
|
||||||
|
}
|
||||||
|
|
||||||
|
finish_message() {
|
||||||
|
local port=${!PORT_KEY} deploy logs remove
|
||||||
|
if [ "$MODE" = docker ]; then
|
||||||
|
deploy="docker exec $NAME update"; logs="docker logs -f $NAME"
|
||||||
|
remove="cd $INSTALL_DIR && docker compose -f $COMPOSE_FILE down -v"
|
||||||
|
elif [ "$OS" = Linux ]; then
|
||||||
|
deploy="sudo $NAME-update"; logs="journalctl -u $NAME -f"
|
||||||
|
remove="sudo systemctl disable --now $NAME && sudo rm -rf $INSTALL_DIR /etc/systemd/system/$NAME.service /usr/local/bin/$NAME-update"
|
||||||
|
else
|
||||||
|
deploy="$NAME-update"; logs="tail -f $INSTALL_DIR/data/service.log"
|
||||||
|
remove="sudo launchctl bootout system/dev.neilbantoc.$NAME; sudo rm -rf $INSTALL_DIR /Library/LaunchDaemons/dev.neilbantoc.$NAME.plist /usr/local/bin/$NAME-update"
|
||||||
|
fi
|
||||||
|
if [ "$ROLE" = hub ]; then
|
||||||
|
echo "$NAME ($MODE) is running at $(health_version) on port $port."
|
||||||
|
echo " open the web UI: http://$(my_ip):$port"
|
||||||
|
echo " add probes from: the Probes page; each one shows its install command"
|
||||||
|
else
|
||||||
|
if [ -n "${HUB_URL:-}" ]; then echo "$NAME ($MODE) is running at $(health_version), reporting to $HUB_URL."
|
||||||
|
else echo "$NAME ($MODE) is running at $(health_version), serve-only: other probes can test against http://$(my_ip):$port"; fi
|
||||||
|
echo " status: curl -s http://127.0.0.1:$port/"
|
||||||
|
fi
|
||||||
|
echo " deploy a new commit: $deploy"
|
||||||
|
echo " see what's new: $deploy --check"
|
||||||
|
echo " undo the last update: $deploy --rollback"
|
||||||
|
echo " logs: $logs"
|
||||||
|
echo " settings: $INSTALL_DIR/.env (re-read on every update)"
|
||||||
|
echo " rebuild/upgrade: run this installer again"
|
||||||
|
echo " uninstall: $remove"
|
||||||
|
if [ "$MODE" = docker ] && [ "$DOCKER" != docker ]; then echo " (prefix docker with sudo, or add yourself to the docker group)"; fi
|
||||||
|
}
|
||||||
|
|
||||||
|
redact() { printf '%s' "$1" | sed -E 's#://[^/@]+@#://***@#'; }
|
||||||
|
|
||||||
|
main "$@"
|
||||||
359
install.sh
Executable file
359
install.sh
Executable file
|
|
@ -0,0 +1,359 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Install (or upgrade) the Network Monitor HUB: the web UI and API that probes report to.
|
||||||
|
# Probes have their own installer, install-probe.sh. Paste one line on the machine:
|
||||||
|
#
|
||||||
|
# curl -fsSL https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install.sh | bash
|
||||||
|
#
|
||||||
|
# Native mode on Linux (Proxmox LXC, bare metal) runs as root:
|
||||||
|
# curl -fsSL https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install.sh | sudo bash
|
||||||
|
#
|
||||||
|
# Private repo over https (the token is asked for, not typed into history):
|
||||||
|
# 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.sh | bash
|
||||||
|
#
|
||||||
|
# Two ways to run (INSTALL_MODE):
|
||||||
|
# docker The app in a container (compose). Default on Linux hosts.
|
||||||
|
# native A Python virtualenv and a boot service: systemd on Linux, launchd on macOS.
|
||||||
|
# Default on macOS and inside LXC containers (e.g. Proxmox LXC).
|
||||||
|
# The mode is saved in .env, so re-runs keep it. Re-running is safe: it keeps .env (values
|
||||||
|
# you pass replace those keys), updates the checkout and restarts. Ordinary deploys:
|
||||||
|
# docker: docker exec network-monitor update
|
||||||
|
# native: sudo network-monitor-update (macOS: network-monitor-update)
|
||||||
|
#
|
||||||
|
# Settings (environment variables, all optional):
|
||||||
|
# INSTALL_MODE docker | native (default: see above)
|
||||||
|
# INSTALL_DIR default /opt/network-monitor
|
||||||
|
# REPO_URL default https://git.neilbantoc.dev/services/network-monitor.git
|
||||||
|
# REPO_REF default main
|
||||||
|
# GIT_TOKEN, GIT_USERNAME private repo over https
|
||||||
|
# GIT_SSH_KEY private repo over SSH (base64-encoded deploy key)
|
||||||
|
# HOST_PORT default 8000 (bound to HOST_BIND from .env: 0.0.0.0 so probes can report)
|
||||||
|
#
|
||||||
|
# install-probe.sh is generated from this file by scripts/build-installers.sh: edit this one.
|
||||||
|
# Everything is inside main(), so a partial download runs nothing. bash 3.2 compatible (macOS).
|
||||||
|
|
||||||
|
NETMON_ROLE=hub
|
||||||
|
|
||||||
|
main() {
|
||||||
|
set -euo pipefail
|
||||||
|
ROLE=$NETMON_ROLE
|
||||||
|
if [ "$ROLE" = probe ]; then
|
||||||
|
NAME=network-probe DEFAULT_PORT=8765 PORT_KEY=PROBE_PORT ENV_EXAMPLE=.env.probe.example COMPOSE_FILE=compose.probe.yml
|
||||||
|
KEYS="REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY INSTALL_MODE HUB_URL PROBE_TOKEN PROBE_PORT ADVERTISE_ADDR"
|
||||||
|
else
|
||||||
|
NAME=network-monitor DEFAULT_PORT=8000 PORT_KEY=HOST_PORT ENV_EXAMPLE=.env.example COMPOSE_FILE=compose.yml
|
||||||
|
KEYS="REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY INSTALL_MODE HOST_PORT"
|
||||||
|
fi
|
||||||
|
INSTALL_DIR=${INSTALL_DIR:-/opt/$NAME}
|
||||||
|
local DEFAULT_REPO_URL="https://git.neilbantoc.dev/services/network-monitor.git" DEFAULT_REF="main"
|
||||||
|
# Keys the caller passed explicitly (these replace values in an existing .env).
|
||||||
|
PASSED=" "
|
||||||
|
local k
|
||||||
|
for k in $KEYS; do [ -z "${!k:-}" ] || PASSED="$PASSED$k "; done
|
||||||
|
|
||||||
|
OS=$(uname -s)
|
||||||
|
case $OS in Linux|Darwin) ;; *) die "this installer is for Linux and macOS" ;; esac
|
||||||
|
SUDO=
|
||||||
|
if [ "$(id -u)" != 0 ]; then
|
||||||
|
command -v sudo >/dev/null || die "run as root, or install sudo"
|
||||||
|
SUDO=sudo
|
||||||
|
fi
|
||||||
|
|
||||||
|
step "source"
|
||||||
|
load_existing_env
|
||||||
|
REPO_URL=${REPO_URL:-$DEFAULT_REPO_URL}
|
||||||
|
REPO_REF=${REPO_REF:-$DEFAULT_REF}
|
||||||
|
printf -v "$PORT_KEY" '%s' "${!PORT_KEY:-$DEFAULT_PORT}"
|
||||||
|
choose_mode
|
||||||
|
|
||||||
|
step "prerequisites"
|
||||||
|
install_packages
|
||||||
|
if [ "$MODE" = docker ]; then install_docker; fi
|
||||||
|
if [ "$ROLE" = probe ] && [ "$OS" = Linux ]; then enable_ping; fi
|
||||||
|
|
||||||
|
step "checkout"
|
||||||
|
git_auth
|
||||||
|
check_access
|
||||||
|
checkout
|
||||||
|
|
||||||
|
step "configuration"
|
||||||
|
write_env
|
||||||
|
if [ "$ROLE" = probe ]; then check_hub; fi
|
||||||
|
|
||||||
|
step "service"
|
||||||
|
if [ "$MODE" = docker ]; then
|
||||||
|
(cd "$INSTALL_DIR" && $DOCKER compose -f "$COMPOSE_FILE" up -d --build --remove-orphans)
|
||||||
|
else
|
||||||
|
NAME=$NAME ROLE=$ROLE INSTALL_DIR=$INSTALL_DIR bash "$INSTALL_DIR/native/setup.sh"
|
||||||
|
fi
|
||||||
|
wait_healthy
|
||||||
|
|
||||||
|
step "done"
|
||||||
|
finish_message
|
||||||
|
}
|
||||||
|
|
||||||
|
step() { printf '\n==> %s\n' "$*"; }
|
||||||
|
log() { printf ' %s\n' "$*"; }
|
||||||
|
die() { printf '\nerror: %s\n' "$*" >&2; exit 1; }
|
||||||
|
in_list() { case " $2 " in *" $1 "*) return 0 ;; esac; return 1; }
|
||||||
|
|
||||||
|
# Run a command directly, and only with sudo if that fails (no password prompt when not needed).
|
||||||
|
priv() { "$@" 2>/dev/null || { [ -n "$SUDO" ] && $SUDO "$@"; }; }
|
||||||
|
read_file() { if [ -r "$1" ]; then cat "$1"; else $SUDO cat "$1"; fi; }
|
||||||
|
|
||||||
|
is_lxc() {
|
||||||
|
[ "$OS" = Linux ] || return 1
|
||||||
|
[ "$(systemd-detect-virt -c 2>/dev/null || true)" = lxc ] && return 0
|
||||||
|
grep -qa 'container=lxc' /proc/1/environ 2>/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
choose_mode() {
|
||||||
|
MODE=${INSTALL_MODE:-auto}
|
||||||
|
if [ "$MODE" = auto ]; then
|
||||||
|
if [ "$OS" = Darwin ]; then MODE=native
|
||||||
|
elif is_lxc; then MODE=native; log "LXC container detected: native mode (set INSTALL_MODE=docker for Docker)"
|
||||||
|
else MODE=docker; fi
|
||||||
|
fi
|
||||||
|
case $MODE in docker|native) ;; *) die "INSTALL_MODE must be docker or native, not '$MODE'" ;; esac
|
||||||
|
if [ "$OS" = Darwin ] && [ "$MODE" = docker ]; then
|
||||||
|
die "on macOS use INSTALL_MODE=native: Docker Desktop runs containers in a VM, so a probe would measure the VM's network, and it only starts at login"
|
||||||
|
fi
|
||||||
|
if [ "$OS" = Linux ] && [ "$MODE" = native ] && [ "$(id -u)" != 0 ]; then
|
||||||
|
die "native mode on Linux installs a system service: run as root, e.g. curl -fsSL <installer URL> | sudo env VAR=value ... bash"
|
||||||
|
fi
|
||||||
|
if [ "$OS" = Darwin ] && [ "$(id -u)" = 0 ]; then
|
||||||
|
die "on macOS, run the installer as your own user (it asks for sudo when it needs it)"
|
||||||
|
fi
|
||||||
|
INSTALL_MODE=$MODE
|
||||||
|
in_list INSTALL_MODE "$PASSED" || PASSED="${PASSED}INSTALL_MODE "
|
||||||
|
log "mode: $MODE"
|
||||||
|
}
|
||||||
|
|
||||||
|
install_packages() {
|
||||||
|
if [ "$OS" = Darwin ]; then
|
||||||
|
xcode-select -p >/dev/null 2>&1 || die "git needs the Xcode Command Line Tools: run xcode-select --install, then this installer again"
|
||||||
|
log "git, curl, ssh: present"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
local need=""
|
||||||
|
command -v git >/dev/null || need="$need git"
|
||||||
|
command -v curl >/dev/null || need="$need curl"
|
||||||
|
command -v ssh >/dev/null || need="$need ssh"
|
||||||
|
[ -n "$need" ] || { log "git, curl, ssh: present"; return; }
|
||||||
|
log "installing$need"
|
||||||
|
if command -v apt-get >/dev/null; then
|
||||||
|
$SUDO env DEBIAN_FRONTEND=noninteractive apt-get update -qq
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
$SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq ca-certificates $(echo $need | sed 's/ssh/openssh-client/') >/dev/null
|
||||||
|
elif command -v dnf >/dev/null; then
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
$SUDO dnf install -y -q ca-certificates $(echo $need | sed 's/ssh/openssh-clients/')
|
||||||
|
elif command -v apk >/dev/null; then
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
$SUDO apk add -q ca-certificates $(echo $need | sed 's/ssh/openssh-client/')
|
||||||
|
else
|
||||||
|
die "no apt-get, dnf or apk: install$need yourself and re-run"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
install_docker() {
|
||||||
|
if ! command -v docker >/dev/null; then
|
||||||
|
log "installing Docker Engine + Compose (get.docker.com)"
|
||||||
|
local dlog; dlog=$(mktemp)
|
||||||
|
curl -fsSL https://get.docker.com | $SUDO sh >"$dlog" 2>&1 || { tail -20 "$dlog" >&2; die "Docker install failed (full log: $dlog)"; }
|
||||||
|
rm -f "$dlog"
|
||||||
|
fi
|
||||||
|
if ! docker info >/dev/null 2>&1 && ! $SUDO docker info >/dev/null 2>&1 \
|
||||||
|
&& command -v systemctl >/dev/null && [ -d /run/systemd/system ]; then
|
||||||
|
$SUDO systemctl enable --now docker >/dev/null 2>&1 || true
|
||||||
|
fi
|
||||||
|
if docker info >/dev/null 2>&1; then DOCKER=docker; else DOCKER="$SUDO docker"; fi
|
||||||
|
$DOCKER info >/dev/null 2>&1 || die "Docker is installed but the daemon is not running"
|
||||||
|
$DOCKER compose version >/dev/null 2>&1 || die "the Docker Compose plugin is missing (apt-get install docker-compose-plugin)"
|
||||||
|
log "docker $($DOCKER version --format '{{.Server.Version}}'), compose $($DOCKER compose version --short)"
|
||||||
|
}
|
||||||
|
|
||||||
|
# The probe runs without root or capabilities, so ping needs unprivileged ICMP sockets.
|
||||||
|
# Most distros allow them already (systemd's default); some ship "1 0", which blocks them.
|
||||||
|
enable_ping() {
|
||||||
|
local want="0 2147483647" cur tmp
|
||||||
|
cur=$(sysctl -n net.ipv4.ping_group_range 2>/dev/null | tr -s '[:space:]' ' ' | sed 's/ $//') || cur=
|
||||||
|
if [ "$cur" = "$want" ]; then log "ping: unprivileged ICMP allowed"; return; fi
|
||||||
|
log "ping: allowing unprivileged ICMP (net.ipv4.ping_group_range was '${cur:-unknown}')"
|
||||||
|
tmp=$(mktemp)
|
||||||
|
printf 'net.ipv4.ping_group_range = %s\n' "$want" > "$tmp"
|
||||||
|
if priv install -m 644 "$tmp" /etc/sysctl.d/60-network-probe-ping.conf \
|
||||||
|
&& priv sysctl -q -w "net.ipv4.ping_group_range=$want" >/dev/null; then
|
||||||
|
log "ping: enabled (persisted in /etc/sysctl.d/60-network-probe-ping.conf)"
|
||||||
|
else
|
||||||
|
log "warning: could not set net.ipv4.ping_group_range; the probe will skip ping and use HTTP and DNS checks only"
|
||||||
|
fi
|
||||||
|
rm -f "$tmp"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Values already in .env fill in whatever the caller did not pass.
|
||||||
|
load_existing_env() {
|
||||||
|
local f="$INSTALL_DIR/.env" line key val
|
||||||
|
[ -f "$f" ] || return 0
|
||||||
|
log "keeping existing $f"
|
||||||
|
while IFS= read -r line || [ -n "$line" ]; do
|
||||||
|
line=${line%$'\r'}
|
||||||
|
[[ $line =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue
|
||||||
|
key=${BASH_REMATCH[2]} val=${BASH_REMATCH[3]}
|
||||||
|
if [[ $val =~ ^\"(.*)\"$ || $val =~ ^\'(.*)\'$ ]]; then val=${BASH_REMATCH[1]}; fi
|
||||||
|
if in_list "$key" "$KEYS" && [ -z "${!key:-}" ]; then printf -v "$key" '%s' "$val"; fi
|
||||||
|
done < <(read_file "$f")
|
||||||
|
}
|
||||||
|
|
||||||
|
# Credentials reach git through the environment only; nothing is stored in the checkout.
|
||||||
|
git_auth() {
|
||||||
|
export GIT_TERMINAL_PROMPT=0
|
||||||
|
if [ -n "${GIT_TOKEN:-}" ]; then
|
||||||
|
export GIT_TOKEN GIT_USERNAME="${GIT_USERNAME:-}"
|
||||||
|
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=credential.helper
|
||||||
|
export GIT_CONFIG_VALUE_0='!f() { [ "$1" = get ] || exit 0; echo "username=${GIT_USERNAME:-x-access-token}"; echo "password=$GIT_TOKEN"; }; f'
|
||||||
|
fi
|
||||||
|
local ssh="ssh -o StrictHostKeyChecking=accept-new"
|
||||||
|
if [ -n "${GIT_SSH_KEY:-}" ]; then
|
||||||
|
KEYFILE=$(mktemp); trap 'rm -f "$KEYFILE"' EXIT
|
||||||
|
printf '%s' "$GIT_SSH_KEY" | base64 -d > "$KEYFILE" 2>/dev/null || die "GIT_SSH_KEY is not valid base64 (use: base64 -w0 deploy_key)"
|
||||||
|
ssh="$ssh -i $KEYFILE -o IdentitiesOnly=yes"
|
||||||
|
fi
|
||||||
|
export GIT_SSH_COMMAND="$ssh"
|
||||||
|
}
|
||||||
|
|
||||||
|
check_access() {
|
||||||
|
git ls-remote --exit-code --heads --tags "$REPO_URL" "$REPO_REF" >/dev/null 2>&1 && { log "repo reachable: $(redact "$REPO_URL") ($REPO_REF)"; return; }
|
||||||
|
# Private https repo and no token yet: ask on the terminal (stdin is this script).
|
||||||
|
if [ -z "${GIT_TOKEN:-}" ] && [[ $REPO_URL == https://* ]] && [ -r /dev/tty ]; then
|
||||||
|
printf ' %s needs a token. Git token (read-only): ' "$(redact "$REPO_URL")" > /dev/tty
|
||||||
|
IFS= read -rs GIT_TOKEN < /dev/tty; echo > /dev/tty
|
||||||
|
PASSED="${PASSED}GIT_TOKEN "
|
||||||
|
git_auth
|
||||||
|
git ls-remote --exit-code --heads --tags "$REPO_URL" "$REPO_REF" >/dev/null 2>&1 && { log "repo reachable with token"; return; }
|
||||||
|
fi
|
||||||
|
die "cannot read $REPO_REF from $(redact "$REPO_URL"). Check REPO_URL/REPO_REF, and pass GIT_TOKEN (https) or GIT_SSH_KEY (ssh) for a private repo"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Docker mode: the host checkout holds the compose file and container/ (the image source);
|
||||||
|
# the app runs from the container's own checkout, which `update` manages.
|
||||||
|
# Native mode: the app runs from this checkout, which <name>-update manages.
|
||||||
|
checkout() {
|
||||||
|
if [ ! -d "$INSTALL_DIR/.git" ]; then
|
||||||
|
priv mkdir -p "$INSTALL_DIR"
|
||||||
|
[ -w "$INSTALL_DIR" ] || $SUDO chown "$(id -u):$(id -g)" "$INSTALL_DIR"
|
||||||
|
[ -z "$(ls -A "$INSTALL_DIR" | grep -vx .env || true)" ] || die "$INSTALL_DIR exists and is not a checkout of $NAME"
|
||||||
|
log "new checkout in $INSTALL_DIR"
|
||||||
|
git -C "$INSTALL_DIR" init --quiet
|
||||||
|
git -C "$INSTALL_DIR" remote add origin "$REPO_URL"
|
||||||
|
fi
|
||||||
|
git -C "$INSTALL_DIR" remote set-url origin "$REPO_URL"
|
||||||
|
git -C "$INSTALL_DIR" fetch --quiet --prune --tags origin
|
||||||
|
local target
|
||||||
|
target=$(git -C "$INSTALL_DIR" rev-parse --verify --quiet "origin/$REPO_REF^{commit}" || git -C "$INSTALL_DIR" rev-parse --verify "$REPO_REF^{commit}")
|
||||||
|
git -C "$INSTALL_DIR" reset --quiet --hard "$target"
|
||||||
|
log "at $(git -C "$INSTALL_DIR" log -1 --format='%h %s')"
|
||||||
|
}
|
||||||
|
|
||||||
|
# .env: created from the example file on first install; on re-runs only the keys the caller
|
||||||
|
# passed are replaced. Docker: owned by uid 1000 (the container's user), mode 640.
|
||||||
|
# Native Linux: root, mode 640 (setup gives the service group read access). macOS: you, 600.
|
||||||
|
write_env() {
|
||||||
|
local f="$INSTALL_DIR/.env" src tmp line key seen=" "
|
||||||
|
if [ -f "$f" ]; then src=$f; else
|
||||||
|
src="$INSTALL_DIR/$ENV_EXAMPLE"
|
||||||
|
PASSED=" $KEYS "
|
||||||
|
log "writing $f"
|
||||||
|
fi
|
||||||
|
tmp=$(mktemp)
|
||||||
|
while IFS= read -r line || [ -n "$line" ]; do
|
||||||
|
key=${line%%=*}
|
||||||
|
if [[ $line =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] && in_list "$key" "$PASSED"; then
|
||||||
|
printf '%s=%s\n' "$key" "${!key:-}"; seen="$seen$key "
|
||||||
|
else
|
||||||
|
printf '%s\n' "$line"
|
||||||
|
fi
|
||||||
|
done < <(read_file "$src") > "$tmp"
|
||||||
|
for key in $PASSED; do in_list "$key" "$seen" || printf '%s=%s\n' "$key" "${!key:-}" >> "$tmp"; done
|
||||||
|
if [ "$MODE" = docker ]; then
|
||||||
|
priv install -m 640 -o 1000 -g "$(id -g)" "$tmp" "$f" || die "could not write $f"
|
||||||
|
elif [ "$OS" = Linux ]; then
|
||||||
|
install -m 640 -o 0 -g 0 "$tmp" "$f" || die "could not write $f"
|
||||||
|
else
|
||||||
|
install -m 600 "$tmp" "$f" || die "could not write $f"
|
||||||
|
fi
|
||||||
|
rm -f "$tmp"
|
||||||
|
log "set in .env:$(echo "$PASSED" | sed 's/ \{1,\}/ /g; s/ $//')"
|
||||||
|
}
|
||||||
|
|
||||||
|
check_hub() {
|
||||||
|
if [ -z "${HUB_URL:-}" ]; then
|
||||||
|
[ -z "${PROBE_TOKEN:-}" ] || die "PROBE_TOKEN is set but HUB_URL is not; pass both, or neither for a serve-only probe"
|
||||||
|
log "no HUB_URL: serve-only probe"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
[ -n "${PROBE_TOKEN:-}" ] || die "HUB_URL is set but PROBE_TOKEN is not. Copy the full command from the hub's Add probe dialog"
|
||||||
|
if curl -fsS --max-time 5 "$HUB_URL/healthz" >/dev/null 2>&1; then log "hub reachable at $HUB_URL"
|
||||||
|
else log "warning: can't reach $HUB_URL/healthz right now; the probe will keep measuring and report when it can"; fi
|
||||||
|
}
|
||||||
|
|
||||||
|
health_version() {
|
||||||
|
if [ "$MODE" = docker ] && [ "$ROLE" = hub ]; then
|
||||||
|
$DOCKER exec "$NAME" python3 -c 'import json,urllib.request;print(json.load(urllib.request.urlopen("http://127.0.0.1:8000/healthz",timeout=2))["version"])' 2>/dev/null
|
||||||
|
else
|
||||||
|
curl -fsS --max-time 2 "http://127.0.0.1:${!PORT_KEY}/healthz" 2>/dev/null | sed -n 's/.*"version":"\([^"]*\)".*/\1/p'
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_healthy() {
|
||||||
|
log "waiting for the app (the first start installs requirements)"
|
||||||
|
local i=0
|
||||||
|
while [ "$i" -lt 180 ]; do
|
||||||
|
if [ -n "$(health_version)" ]; then log "healthy at $(health_version)"; return; fi
|
||||||
|
if [ "$MODE" = docker ] && [ "$($DOCKER inspect -f '{{.State.Running}}' "$NAME" 2>/dev/null)" = false ]; then break; fi
|
||||||
|
sleep 1; i=$((i + 1))
|
||||||
|
done
|
||||||
|
if [ "$MODE" = docker ]; then $DOCKER logs --tail 40 "$NAME" >&2 || true
|
||||||
|
elif [ "$OS" = Linux ]; then journalctl -u "$NAME" -n 40 --no-pager >&2 || true
|
||||||
|
else tail -n 40 "$INSTALL_DIR/data/service.log" >&2 || true; fi
|
||||||
|
die "$NAME did not become healthy (logs above)"
|
||||||
|
}
|
||||||
|
|
||||||
|
my_ip() {
|
||||||
|
if [ "$OS" = Darwin ]; then ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || echo this-host
|
||||||
|
else hostname -I 2>/dev/null | cut -d' ' -f1 | grep . || echo this-host; fi
|
||||||
|
}
|
||||||
|
|
||||||
|
finish_message() {
|
||||||
|
local port=${!PORT_KEY} deploy logs remove
|
||||||
|
if [ "$MODE" = docker ]; then
|
||||||
|
deploy="docker exec $NAME update"; logs="docker logs -f $NAME"
|
||||||
|
remove="cd $INSTALL_DIR && docker compose -f $COMPOSE_FILE down -v"
|
||||||
|
elif [ "$OS" = Linux ]; then
|
||||||
|
deploy="sudo $NAME-update"; logs="journalctl -u $NAME -f"
|
||||||
|
remove="sudo systemctl disable --now $NAME && sudo rm -rf $INSTALL_DIR /etc/systemd/system/$NAME.service /usr/local/bin/$NAME-update"
|
||||||
|
else
|
||||||
|
deploy="$NAME-update"; logs="tail -f $INSTALL_DIR/data/service.log"
|
||||||
|
remove="sudo launchctl bootout system/dev.neilbantoc.$NAME; sudo rm -rf $INSTALL_DIR /Library/LaunchDaemons/dev.neilbantoc.$NAME.plist /usr/local/bin/$NAME-update"
|
||||||
|
fi
|
||||||
|
if [ "$ROLE" = hub ]; then
|
||||||
|
echo "$NAME ($MODE) is running at $(health_version) on port $port."
|
||||||
|
echo " open the web UI: http://$(my_ip):$port"
|
||||||
|
echo " add probes from: the Probes page; each one shows its install command"
|
||||||
|
else
|
||||||
|
if [ -n "${HUB_URL:-}" ]; then echo "$NAME ($MODE) is running at $(health_version), reporting to $HUB_URL."
|
||||||
|
else echo "$NAME ($MODE) is running at $(health_version), serve-only: other probes can test against http://$(my_ip):$port"; fi
|
||||||
|
echo " status: curl -s http://127.0.0.1:$port/"
|
||||||
|
fi
|
||||||
|
echo " deploy a new commit: $deploy"
|
||||||
|
echo " see what's new: $deploy --check"
|
||||||
|
echo " undo the last update: $deploy --rollback"
|
||||||
|
echo " logs: $logs"
|
||||||
|
echo " settings: $INSTALL_DIR/.env (re-read on every update)"
|
||||||
|
echo " rebuild/upgrade: run this installer again"
|
||||||
|
echo " uninstall: $remove"
|
||||||
|
if [ "$MODE" = docker ] && [ "$DOCKER" != docker ]; then echo " (prefix docker with sudo, or add yourself to the docker group)"; fi
|
||||||
|
}
|
||||||
|
|
||||||
|
redact() { printf '%s' "$1" | sed -E 's#://[^/@]+@#://***@#'; }
|
||||||
|
|
||||||
|
main "$@"
|
||||||
99
native/lib.sh
Normal file
99
native/lib.sh
Normal file
|
|
@ -0,0 +1,99 @@
|
||||||
|
# Shared by run.sh, update.sh and setup.sh for native (no Docker) installs.
|
||||||
|
# bash 3.2 compatible (macOS /bin/bash): no mapfile, no associative arrays, no ${x,,}.
|
||||||
|
#
|
||||||
|
# Layout of a native install (INSTALL_DIR, e.g. /opt/network-probe):
|
||||||
|
# <git checkout> the app; update.sh moves it between commits
|
||||||
|
# .venv/ Python virtualenv (rebuilt when requirements or Python change)
|
||||||
|
# data/ the app's data (DATA_DIR), the only place the service writes
|
||||||
|
# .env settings and git credentials (gitignored)
|
||||||
|
# .native written by setup.sh: NAME ROLE PLATFORM SERVICE SVC_USER PYTHON
|
||||||
|
# .native-update.sh copy of update.sh that the <name>-update command runs
|
||||||
|
# .native-state/ update bookkeeping (previous commit)
|
||||||
|
|
||||||
|
native_log() { echo "[$(basename "$0")] $*" >&2; }
|
||||||
|
native_die() { native_log "error: $*"; exit 1; }
|
||||||
|
|
||||||
|
# Parse KEY=value lines from .env into the environment (not executed; values never printed).
|
||||||
|
load_dotenv() {
|
||||||
|
local f=$1 line key val
|
||||||
|
[ -r "$f" ] || return 0
|
||||||
|
while IFS= read -r line || [ -n "$line" ]; do
|
||||||
|
line=${line%$'\r'}
|
||||||
|
[[ $line =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue
|
||||||
|
key=${BASH_REMATCH[2]}
|
||||||
|
val=${BASH_REMATCH[3]}
|
||||||
|
if [[ $val =~ ^\"(.*)\"$ || $val =~ ^\'(.*)\'$ ]]; then val=${BASH_REMATCH[1]}; fi
|
||||||
|
export "$key=$val"
|
||||||
|
done < "$f"
|
||||||
|
}
|
||||||
|
|
||||||
|
# The port and bind address the app listens on, by role.
|
||||||
|
app_port() { if [ "$ROLE" = probe ]; then echo "${PROBE_PORT:-8765}"; else echo "${HOST_PORT:-8000}"; fi; }
|
||||||
|
app_host() { if [ "$ROLE" = probe ]; then echo 0.0.0.0; else echo "${HOST_BIND:-0.0.0.0}"; fi; }
|
||||||
|
|
||||||
|
# Version reported by /healthz, or "" when the app isn't answering.
|
||||||
|
health_version() {
|
||||||
|
curl -fsS --max-time 2 "http://127.0.0.1:$(app_port)/healthz" 2>/dev/null | sed -n 's/.*"version":"\([^"]*\)".*/\1/p'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Wait until /healthz reports the given version (or any, if none given).
|
||||||
|
wait_health() {
|
||||||
|
local want=${1:-} timeout=${2:-40} got i=0
|
||||||
|
while [ "$i" -lt "$timeout" ]; do
|
||||||
|
got=$(health_version)
|
||||||
|
if [ -n "$got" ] && { [ -z "$want" ] || [ "$got" = "$want" ]; }; then return 0; fi
|
||||||
|
sleep 1; i=$((i + 1))
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Git credentials from the environment only; nothing is stored in the checkout.
|
||||||
|
setup_git_auth() {
|
||||||
|
export GIT_TERMINAL_PROMPT=0
|
||||||
|
if [ -n "${GIT_TOKEN:-}" ]; then
|
||||||
|
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=credential.helper
|
||||||
|
export GIT_CONFIG_VALUE_0='!f() { [ "$1" = get ] || exit 0; echo "username=${GIT_USERNAME:-x-access-token}"; echo "password=$GIT_TOKEN"; }; f'
|
||||||
|
fi
|
||||||
|
local ssh="ssh -o StrictHostKeyChecking=accept-new"
|
||||||
|
if [ -n "${GIT_SSH_KEY:-}" ]; then
|
||||||
|
NATIVE_KEYFILE=$(mktemp)
|
||||||
|
chmod 600 "$NATIVE_KEYFILE"
|
||||||
|
printf '%s' "$GIT_SSH_KEY" | base64 -d > "$NATIVE_KEYFILE" 2>/dev/null || native_die "GIT_SSH_KEY is not valid base64"
|
||||||
|
ssh="$ssh -i $NATIVE_KEYFILE -o IdentitiesOnly=yes"
|
||||||
|
fi
|
||||||
|
export GIT_SSH_COMMAND="$ssh"
|
||||||
|
}
|
||||||
|
|
||||||
|
hash_file() {
|
||||||
|
if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Bring the venv in line with requirements.txt. A no-op when nothing changed.
|
||||||
|
sync_venv() {
|
||||||
|
local dir=$1 py=$2 pyv want
|
||||||
|
pyv=$("$py" -c 'import sys; print("%d.%d.%d" % sys.version_info[:3])')
|
||||||
|
want="$pyv $(hash_file "$dir/requirements.txt")"
|
||||||
|
if [ "$(cat "$dir/.venv/.python" 2>/dev/null)" != "$pyv" ]; then
|
||||||
|
native_log "creating virtualenv for Python $pyv"
|
||||||
|
rm -rf "$dir/.venv"
|
||||||
|
"$py" -m venv "$dir/.venv" || return 1
|
||||||
|
echo "$pyv" > "$dir/.venv/.python"
|
||||||
|
fi
|
||||||
|
[ "$(cat "$dir/.venv/.synced" 2>/dev/null)" = "$want" ] && return 0
|
||||||
|
native_log "installing requirements"
|
||||||
|
"$dir/.venv/bin/pip" install --quiet --disable-pip-version-check --no-cache-dir -r "$dir/requirements.txt" || return 1
|
||||||
|
echo "$want" > "$dir/.venv/.synced"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Restart the service: systemd on Linux, launchd on macOS.
|
||||||
|
restart_service() {
|
||||||
|
if [ "$PLATFORM" = launchd ]; then
|
||||||
|
if [ "$(id -u)" = 0 ]; then launchctl kickstart -k "system/$SERVICE"; else sudo launchctl kickstart -k "system/$SERVICE"; fi
|
||||||
|
else
|
||||||
|
systemctl restart "$SERVICE"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
service_logs_hint() {
|
||||||
|
if [ "$PLATFORM" = launchd ]; then echo "tail -n 50 $INSTALL_DIR/data/service.log"; else echo "journalctl -u $SERVICE -n 50"; fi
|
||||||
|
}
|
||||||
17
native/run.sh
Executable file
17
native/run.sh
Executable file
|
|
@ -0,0 +1,17 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Starts the app for a native install. systemd (Linux) or launchd (macOS) runs this as the
|
||||||
|
# service user. It reads .env, keeps the git credentials away from the app, and execs uvicorn.
|
||||||
|
set -euo pipefail
|
||||||
|
INSTALL_DIR=$(cd "$(dirname "$0")/.." && pwd)
|
||||||
|
. "$INSTALL_DIR/native/lib.sh"
|
||||||
|
. "$INSTALL_DIR/.native"
|
||||||
|
cd "$INSTALL_DIR"
|
||||||
|
load_dotenv "$INSTALL_DIR/.env"
|
||||||
|
unset GIT_TOKEN GIT_USERNAME GIT_SSH_KEY
|
||||||
|
APP_VERSION=$(git -c safe.directory="$INSTALL_DIR" -C "$INSTALL_DIR" rev-parse --short HEAD 2>/dev/null || echo dev)
|
||||||
|
PORT=$(app_port)
|
||||||
|
export ROLE APP_VERSION PORT INSTALL_DIR INSTALL_MODE=native DATA_DIR="$INSTALL_DIR/data" PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
|
||||||
|
export UPDATE_COMMAND="sudo $NAME-update"
|
||||||
|
[ "$PLATFORM" = launchd ] && UPDATE_COMMAND="$NAME-update"
|
||||||
|
exec "$INSTALL_DIR/.venv/bin/uvicorn" app.main:app --host "$(app_host)" --port "$PORT" \
|
||||||
|
--no-server-header --timeout-graceful-shutdown 10
|
||||||
144
native/setup.sh
Executable file
144
native/setup.sh
Executable file
|
|
@ -0,0 +1,144 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Native (no Docker) setup, run by install.sh / install-probe.sh after they clone the repo
|
||||||
|
# and write .env. Idempotent. Linux: run as root, needs systemd. macOS: run as the user
|
||||||
|
# who will own the install (uses sudo for the launchd daemon and the update command).
|
||||||
|
# NAME=network-probe ROLE=probe INSTALL_DIR=/opt/network-probe bash native/setup.sh
|
||||||
|
set -euo pipefail
|
||||||
|
: "${NAME:?}" "${ROLE:?}" "${INSTALL_DIR:?}"
|
||||||
|
. "$INSTALL_DIR/native/lib.sh"
|
||||||
|
SVC_USER_LINUX=netmon
|
||||||
|
MIN_PY=11
|
||||||
|
|
||||||
|
as_root() { if [ "$(id -u)" = 0 ]; then "$@"; else sudo "$@"; fi; }
|
||||||
|
|
||||||
|
find_python() {
|
||||||
|
local c v
|
||||||
|
for c in python3.14 python3.13 python3.12 python3.11 python3 \
|
||||||
|
/opt/homebrew/bin/python3 /usr/local/bin/python3 /opt/homebrew/opt/python@3.13/bin/python3.13; do
|
||||||
|
command -v "$c" >/dev/null 2>&1 || continue
|
||||||
|
v=$("$c" -c 'import sys; print(sys.version_info[0] == 3 and sys.version_info[1] >= '"$MIN_PY"')' 2>/dev/null) || continue
|
||||||
|
if [ "$v" = True ] && "$c" -c 'import venv, ensurepip' >/dev/null 2>&1; then command -v "$c"; return 0; fi
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure_python() {
|
||||||
|
PYTHON=$(find_python) && return 0
|
||||||
|
if [ "$PLATFORM" = launchd ]; then
|
||||||
|
if command -v brew >/dev/null 2>&1; then
|
||||||
|
native_log "installing Python 3.13 with Homebrew"
|
||||||
|
brew install python@3.13 >/dev/null
|
||||||
|
else
|
||||||
|
native_die "needs Python 3.$MIN_PY+. Install Homebrew (https://brew.sh) and re-run, or install Python from python.org"
|
||||||
|
fi
|
||||||
|
elif command -v apt-get >/dev/null 2>&1; then
|
||||||
|
native_log "installing python3 and python3-venv"
|
||||||
|
DEBIAN_FRONTEND=noninteractive apt-get update -qq
|
||||||
|
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq python3 python3-venv >/dev/null
|
||||||
|
elif command -v dnf >/dev/null 2>&1; then
|
||||||
|
dnf install -y -q python3
|
||||||
|
elif command -v apk >/dev/null 2>&1; then
|
||||||
|
apk add -q python3
|
||||||
|
fi
|
||||||
|
PYTHON=$(find_python) || native_die "needs Python 3.$MIN_PY+ with venv; this system's python3 is $(python3 --version 2>&1 || echo missing). Use a newer distro (Debian 12+, Ubuntu 24.04+) or INSTALL_MODE=docker"
|
||||||
|
}
|
||||||
|
|
||||||
|
if [ "$(uname -s)" = Darwin ]; then
|
||||||
|
PLATFORM=launchd
|
||||||
|
SERVICE="dev.neilbantoc.$NAME"
|
||||||
|
SVC_USER=$(id -un)
|
||||||
|
[ "$SVC_USER" != root ] || native_die "on macOS, run the installer as your own user, not with sudo"
|
||||||
|
else
|
||||||
|
PLATFORM=systemd
|
||||||
|
SERVICE=$NAME
|
||||||
|
SVC_USER=$SVC_USER_LINUX
|
||||||
|
[ "$(id -u)" = 0 ] || native_die "native mode on Linux runs as root"
|
||||||
|
[ -d /run/systemd/system ] || native_die "native mode on Linux needs systemd (this system has none). Use INSTALL_MODE=docker"
|
||||||
|
fi
|
||||||
|
|
||||||
|
native_log "python"
|
||||||
|
ensure_python
|
||||||
|
native_log "using $PYTHON ($("$PYTHON" --version 2>&1))"
|
||||||
|
sync_venv "$INSTALL_DIR" "$PYTHON" || native_die "installing requirements failed"
|
||||||
|
|
||||||
|
mkdir -p "$INSTALL_DIR/data" "$INSTALL_DIR/.native-state"
|
||||||
|
if [ "$PLATFORM" = systemd ]; then
|
||||||
|
id "$SVC_USER" >/dev/null 2>&1 || useradd --system --user-group --home-dir "$INSTALL_DIR/data" --shell /usr/sbin/nologin "$SVC_USER"
|
||||||
|
chown -R "$SVC_USER:$SVC_USER" "$INSTALL_DIR/data"
|
||||||
|
chown root:"$SVC_USER" "$INSTALL_DIR/.env"
|
||||||
|
chmod 640 "$INSTALL_DIR/.env"
|
||||||
|
else
|
||||||
|
chmod 600 "$INSTALL_DIR/.env"
|
||||||
|
fi
|
||||||
|
|
||||||
|
cat > "$INSTALL_DIR/.native" <<CONF
|
||||||
|
NAME=$NAME
|
||||||
|
ROLE=$ROLE
|
||||||
|
PLATFORM=$PLATFORM
|
||||||
|
SERVICE=$SERVICE
|
||||||
|
SVC_USER=$SVC_USER
|
||||||
|
PYTHON=$PYTHON
|
||||||
|
CONF
|
||||||
|
|
||||||
|
# The <name>-update command runs a copy of update.sh (update replaces the checkout under it).
|
||||||
|
cp "$INSTALL_DIR/native/update.sh" "$INSTALL_DIR/.native-update.sh"
|
||||||
|
chmod 755 "$INSTALL_DIR/.native-update.sh"
|
||||||
|
tmp=$(mktemp)
|
||||||
|
printf '#!/bin/sh\n# Deploy a new commit of %s (native install). See: %s-update --help\nNETMON_DIR=%s exec /bin/bash %s/.native-update.sh "$@"\n' \
|
||||||
|
"$NAME" "$NAME" "$INSTALL_DIR" "$INSTALL_DIR" > "$tmp"
|
||||||
|
as_root mkdir -p /usr/local/bin
|
||||||
|
as_root install -m 755 "$tmp" "/usr/local/bin/$NAME-update"
|
||||||
|
rm -f "$tmp"
|
||||||
|
|
||||||
|
native_log "service"
|
||||||
|
if [ "$PLATFORM" = systemd ]; then
|
||||||
|
cat > "/etc/systemd/system/$SERVICE.service" <<UNIT
|
||||||
|
[Unit]
|
||||||
|
Description=Network Monitor $ROLE ($NAME)
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=$SVC_USER
|
||||||
|
Group=$SVC_USER
|
||||||
|
WorkingDirectory=$INSTALL_DIR
|
||||||
|
ExecStart=/bin/bash $INSTALL_DIR/native/run.sh
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
UNIT
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable "$SERVICE" >/dev/null 2>&1
|
||||||
|
systemctl restart "$SERVICE"
|
||||||
|
else
|
||||||
|
plist=$(mktemp)
|
||||||
|
cat > "$plist" <<PLIST
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>Label</key><string>$SERVICE</string>
|
||||||
|
<key>UserName</key><string>$SVC_USER</string>
|
||||||
|
<key>ProgramArguments</key>
|
||||||
|
<array><string>/bin/bash</string><string>$INSTALL_DIR/native/run.sh</string></array>
|
||||||
|
<key>WorkingDirectory</key><string>$INSTALL_DIR</string>
|
||||||
|
<key>EnvironmentVariables</key>
|
||||||
|
<dict><key>PATH</key><string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string></dict>
|
||||||
|
<key>RunAtLoad</key><true/>
|
||||||
|
<key>KeepAlive</key><true/>
|
||||||
|
<key>ThrottleInterval</key><integer>5</integer>
|
||||||
|
<key>StandardOutPath</key><string>$INSTALL_DIR/data/service.log</string>
|
||||||
|
<key>StandardErrorPath</key><string>$INSTALL_DIR/data/service.log</string>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
|
PLIST
|
||||||
|
as_root install -m 644 -o root -g wheel "$plist" "/Library/LaunchDaemons/$SERVICE.plist"
|
||||||
|
rm -f "$plist"
|
||||||
|
as_root launchctl bootout "system/$SERVICE" >/dev/null 2>&1 || true
|
||||||
|
as_root launchctl bootstrap system "/Library/LaunchDaemons/$SERVICE.plist"
|
||||||
|
as_root launchctl enable "system/$SERVICE" >/dev/null 2>&1 || true
|
||||||
|
fi
|
||||||
|
native_log "setup done ($PLATFORM service $SERVICE, user $SVC_USER)"
|
||||||
87
native/update.sh
Executable file
87
native/update.sh
Executable file
|
|
@ -0,0 +1,87 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Deploy a new commit to a native install, the same way `docker exec <name> update` does in
|
||||||
|
# a container: fetch, check out, sync requirements, check that app.main imports, restart the
|
||||||
|
# service, wait for /healthz to report the new commit; on any failure, go back.
|
||||||
|
# <name>-update to the tip of REPO_REF
|
||||||
|
# <name>-update <ref> to a tag, branch or commit
|
||||||
|
# <name>-update --check what an update would bring in
|
||||||
|
# <name>-update --rollback back to the commit before the last update
|
||||||
|
# Linux: run with sudo (the checkout is root-owned). macOS: run as the installing user.
|
||||||
|
set -euo pipefail
|
||||||
|
INSTALL_DIR=${NETMON_DIR:?run this through the <name>-update command}
|
||||||
|
. "$INSTALL_DIR/native/lib.sh"
|
||||||
|
. "$INSTALL_DIR/.native"
|
||||||
|
|
||||||
|
usage() { sed -n '2,10p' "$0" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; }
|
||||||
|
mode=update ref=
|
||||||
|
while [ $# -gt 0 ]; do
|
||||||
|
case $1 in
|
||||||
|
--check) mode=check ;;
|
||||||
|
--rollback) mode=rollback ;;
|
||||||
|
-h|--help) usage ;;
|
||||||
|
-*) usage 1 ;;
|
||||||
|
*) ref=$1 ;;
|
||||||
|
esac
|
||||||
|
shift
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "$PLATFORM" = systemd ] && [ "$(id -u)" != 0 ]; then native_die "run it with sudo: sudo $NAME-update $*"; fi
|
||||||
|
if [ "$PLATFORM" = launchd ] && [ "$(id -u)" = 0 ] && [ "$SVC_USER" != root ]; then
|
||||||
|
exec sudo -u "$SVC_USER" NETMON_DIR="$INSTALL_DIR" /bin/bash "$0" "$@"
|
||||||
|
fi
|
||||||
|
|
||||||
|
load_dotenv "$INSTALL_DIR/.env"
|
||||||
|
setup_git_auth
|
||||||
|
cd "$INSTALL_DIR"
|
||||||
|
STATE="$INSTALL_DIR/.native-state"
|
||||||
|
mkdir -p "$STATE"
|
||||||
|
LOCK="$STATE/update.lock"
|
||||||
|
if ! mkdir "$LOCK" 2>/dev/null; then native_die "another update is running (or remove $LOCK)"; fi
|
||||||
|
trap 'rmdir "$LOCK" 2>/dev/null; [ -n "${NATIVE_KEYFILE:-}" ] && rm -f "$NATIVE_KEYFILE"' EXIT
|
||||||
|
|
||||||
|
[ -n "${REPO_URL:-}" ] && [ "$(git remote get-url origin 2>/dev/null)" != "$REPO_URL" ] && git remote set-url origin "$REPO_URL"
|
||||||
|
short() { git rev-parse --short "$1"; }
|
||||||
|
old=$(git rev-parse HEAD)
|
||||||
|
if [ "$mode" = rollback ]; then
|
||||||
|
new=$(cat "$STATE/previous" 2>/dev/null) || native_die "no previous commit recorded"
|
||||||
|
else
|
||||||
|
git fetch --quiet --prune --tags origin
|
||||||
|
target=${ref:-${REPO_REF:-main}}
|
||||||
|
new=$(git rev-parse --verify --quiet "origin/$target^{commit}" || git rev-parse --verify --quiet "$target^{commit}") \
|
||||||
|
|| native_die "unknown ref: $target"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$mode" = check ]; then
|
||||||
|
if [ "$old" = "$new" ]; then echo "up to date at $(short "$old")"; else
|
||||||
|
echo "$(short "$old") -> $(short "$new")"; git log --oneline "$old..$new" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
[ "$old" = "$new" ] && { echo "already at $(short "$new")"; exit 0; }
|
||||||
|
|
||||||
|
check_import() { (cd "$INSTALL_DIR" && ROLE="$ROLE" DATA_DIR="$INSTALL_DIR/data" "$INSTALL_DIR/.venv/bin/python" -c 'import app.main'); }
|
||||||
|
apply() { git reset --quiet --hard "$1" && sync_venv "$INSTALL_DIR" "$PYTHON" && check_import; }
|
||||||
|
refresh_self() { # pick up a newer update.sh; rename keeps this running copy intact
|
||||||
|
local tmp="$INSTALL_DIR/.native-update.sh.new"
|
||||||
|
cp "$INSTALL_DIR/native/update.sh" "$tmp" && chmod 755 "$tmp" && mv -f "$tmp" "$INSTALL_DIR/.native-update.sh"
|
||||||
|
}
|
||||||
|
|
||||||
|
native_log "updating $(short "$old") -> $(short "$new")"
|
||||||
|
restarted=0
|
||||||
|
if apply "$new" && restarted=1 && restart_service && wait_health "$(short "$new")" "${HEALTH_TIMEOUT:-40}"; then
|
||||||
|
echo "$old" > "$STATE/previous"
|
||||||
|
git log --oneline "$old..$new" 2>/dev/null | head -20 || true
|
||||||
|
refresh_self || true
|
||||||
|
if [ -n "$(git diff --name-only "$old" "$new" -- native/setup.sh)" ]; then
|
||||||
|
native_log "note: native/setup.sh changed; re-run the installer to apply service changes"
|
||||||
|
fi
|
||||||
|
echo "updated to $(short "$new")"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
native_log "update failed; going back to $(short "$old")"
|
||||||
|
apply "$old" || native_die "could not restore $(short "$old"); check: $(service_logs_hint)"
|
||||||
|
[ "$restarted" = 1 ] || { native_log "the running app was never touched"; exit 1; }
|
||||||
|
restart_service && wait_health "$(short "$old")" "${HEALTH_TIMEOUT:-40}" || native_die "restored $(short "$old") but it is not healthy; check: $(service_logs_hint)"
|
||||||
|
native_log "running $(short "$old") again"
|
||||||
|
exit 1
|
||||||
5
pytest.ini
Normal file
5
pytest.ini
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
[pytest]
|
||||||
|
testpaths = tests
|
||||||
|
pythonpath = .
|
||||||
|
# The source may be a read-only or foreign-owned bind mount; don't write a cache into it.
|
||||||
|
addopts = -p no:cacheprovider
|
||||||
2
requirements-dev.txt
Normal file
2
requirements-dev.txt
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
pytest==9.2.*
|
||||||
|
httpx2==2.16.*
|
||||||
4
requirements.txt
Normal file
4
requirements.txt
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
fastapi==0.162.*
|
||||||
|
uvicorn[standard]==0.54.*
|
||||||
|
httpx==0.28.*
|
||||||
|
icmplib==3.0.*
|
||||||
59
scripts/build-installers.sh
Executable file
59
scripts/build-installers.sh
Executable file
|
|
@ -0,0 +1,59 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Generate install-probe.sh from install.sh. install.sh is the only installer you edit; the
|
||||||
|
# probe installer is the same script with NETMON_ROLE=probe and its own header comment.
|
||||||
|
# tests/test_installers.py fails when install-probe.sh is out of date.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
RAW=https://git.neilbantoc.dev/services/network-monitor/raw/branch/main
|
||||||
|
out=install-probe.sh
|
||||||
|
[ "${1:-}" = --check ] && out=$(mktemp)
|
||||||
|
{
|
||||||
|
cat <<HEADER
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# GENERATED from install.sh by scripts/build-installers.sh. Edit install.sh, then run that script.
|
||||||
|
#
|
||||||
|
# Install (or upgrade) a Network Monitor PROBE. The hub's "Add probe" dialog prints the exact
|
||||||
|
# command, with this probe's token:
|
||||||
|
#
|
||||||
|
# curl -fsSL $RAW/install-probe.sh | HUB_URL=http://hub:8000 PROBE_TOKEN=... bash
|
||||||
|
#
|
||||||
|
# Native mode on Linux (Proxmox LXC, bare metal) runs as root:
|
||||||
|
# curl -fsSL $RAW/install-probe.sh | sudo env HUB_URL=http://hub:8000 PROBE_TOKEN=... bash
|
||||||
|
#
|
||||||
|
# Serve-only probe (e.g. a VPS the others test against): leave out HUB_URL and PROBE_TOKEN,
|
||||||
|
# and open PROBE_PORT (default 8765/tcp) in its firewall.
|
||||||
|
#
|
||||||
|
# Private repo over https: add GIT_TOKEN, read without echoing it:
|
||||||
|
# read -rsp 'Git token: ' GIT_TOKEN && export GIT_TOKEN && curl -fsSL -H "Authorization: Bearer \$GIT_TOKEN" $RAW/install-probe.sh | HUB_URL=... PROBE_TOKEN=... bash
|
||||||
|
#
|
||||||
|
# Two ways to run (INSTALL_MODE):
|
||||||
|
# docker The probe in a container with host networking. Default on Linux hosts.
|
||||||
|
# native A Python virtualenv and a boot service: systemd on Linux, launchd on macOS.
|
||||||
|
# Default on macOS and inside LXC containers (e.g. Proxmox LXC).
|
||||||
|
# On Linux it also lets unprivileged processes ping (net.ipv4.ping_group_range, persisted in
|
||||||
|
# /etc/sysctl.d). Re-running is safe: it keeps .env (values you pass replace those keys).
|
||||||
|
# Ordinary deploys:
|
||||||
|
# docker: docker exec network-probe update
|
||||||
|
# native: sudo network-probe-update (macOS: network-probe-update)
|
||||||
|
#
|
||||||
|
# Settings (environment variables, all optional):
|
||||||
|
# HUB_URL, PROBE_TOKEN the hub to report to and this probe's token
|
||||||
|
# PROBE_PORT default 8765 (the probe's test server, on all interfaces)
|
||||||
|
# ADVERTISE_ADDR address other probes use for this one (default: what the hub sees)
|
||||||
|
# INSTALL_MODE docker | native (default: see above)
|
||||||
|
# INSTALL_DIR default /opt/network-probe
|
||||||
|
# REPO_URL, REPO_REF default https://git.neilbantoc.dev/services/network-monitor.git, main
|
||||||
|
# GIT_TOKEN, GIT_USERNAME private repo over https
|
||||||
|
# GIT_SSH_KEY private repo over SSH (base64-encoded deploy key)
|
||||||
|
#
|
||||||
|
# Everything is inside main(), so a partial download runs nothing. bash 3.2 compatible (macOS).
|
||||||
|
|
||||||
|
HEADER
|
||||||
|
sed -n '/^NETMON_ROLE=hub$/,$p' install.sh | sed '1s/^NETMON_ROLE=hub$/NETMON_ROLE=probe/'
|
||||||
|
} > "$out"
|
||||||
|
if [ "${1:-}" = --check ]; then
|
||||||
|
if cmp -s "$out" install-probe.sh; then rm -f "$out"; echo "install-probe.sh is up to date"; exit 0; fi
|
||||||
|
rm -f "$out"; echo "install-probe.sh is out of date: run scripts/build-installers.sh" >&2; exit 1
|
||||||
|
fi
|
||||||
|
chmod +x install-probe.sh
|
||||||
|
echo "wrote install-probe.sh"
|
||||||
20
tests/conftest.py
Normal file
20
tests/conftest.py
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def isolated(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setenv("DATA_DIR", str(tmp_path))
|
||||||
|
for k in ("ADGUARD_URL", "ADGUARD_USERNAME", "ADGUARD_PASSWORD", "UI_PASSWORD", "VPS_URL", "ROLE"):
|
||||||
|
monkeypatch.delenv(k, raising=False)
|
||||||
|
from app.hub import adguard
|
||||||
|
adguard._stats_cache.update(at=0.0, data=None)
|
||||||
|
monkeypatch.setattr(adguard, "TRANSPORT", None)
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def hub():
|
||||||
|
from app.hub.server import app
|
||||||
|
with TestClient(app) as c:
|
||||||
|
yield c
|
||||||
31
tests/test_app.py
Normal file
31
tests/test_app.py
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_defaults_to_hub():
|
||||||
|
from app.main import app
|
||||||
|
with TestClient(app) as client:
|
||||||
|
r = client.get("/healthz")
|
||||||
|
assert r.status_code == 200 and r.json()["role"] == "hub"
|
||||||
|
|
||||||
|
|
||||||
|
def test_index_assets_and_spa_fallback(hub):
|
||||||
|
page = hub.get("/")
|
||||||
|
assert page.status_code == 200 and "network monitor" in page.text.lower()
|
||||||
|
css = hub.get("/static/css/app.css")
|
||||||
|
assert css.status_code == 200 and css.headers["cache-control"] == "no-cache"
|
||||||
|
assert hub.get("/clients/aa:bb:cc:dd:ee:ff").status_code == 200 # client-side route
|
||||||
|
assert hub.get("/api/nope").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_info(hub):
|
||||||
|
j = hub.get("/api/info").json()
|
||||||
|
assert j["role"] == "hub" and j["adguard"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_password(hub, monkeypatch):
|
||||||
|
monkeypatch.setenv("UI_PASSWORD", "s3cret")
|
||||||
|
assert hub.get("/api/info").status_code == 401
|
||||||
|
assert hub.get("/api/info", auth=("admin", "wrong")).status_code == 401
|
||||||
|
assert hub.get("/api/info", auth=("admin", "s3cret")).status_code == 200
|
||||||
|
assert hub.get("/healthz").status_code == 200
|
||||||
|
assert hub.post("/api/probe/report", json={}).status_code in (401, 422) # token auth, not the password
|
||||||
157
tests/test_dns.py
Normal file
157
tests/test_dns.py
Normal file
|
|
@ -0,0 +1,157 @@
|
||||||
|
"""AdGuard-backed endpoints, against a fake AdGuard Home."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.hub import adguard, dns
|
||||||
|
from app.hub.db import db
|
||||||
|
|
||||||
|
NOW = datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def row(i, client, domain, blocked=False):
|
||||||
|
t = (NOW - timedelta(minutes=i)).isoformat().replace("+00:00", "123Z") # nanosecond-ish like AdGuard
|
||||||
|
return {
|
||||||
|
"time": t, "client": client, "client_info": {"name": f"host-{client.split('.')[-1]}"},
|
||||||
|
"question": {"name": domain, "type": "A", "class": "IN"}, "status": "NOERROR",
|
||||||
|
"reason": "FilteredBlackList" if blocked else "NotFilteredNotFound", "elapsedMs": "1.5",
|
||||||
|
"rules": [{"text": f"||{domain}^", "filter_list_id": 1}] if blocked else [], "upstream": "https://1.1.1.1/dns-query",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LOG = (
|
||||||
|
[row(i, "192.168.1.5", "api.example.com") for i in range(0, 600)]
|
||||||
|
+ [row(i, "192.168.1.50", "www.example.com") for i in range(600, 700)]
|
||||||
|
+ [row(i, "192.168.1.5", "ads.tracker.net", blocked=True) for i in range(700, 760)]
|
||||||
|
+ [row(i, "192.168.1.51", "cdn.example.co.uk") for i in range(760, 770)]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
|
assert request.headers.get("authorization", "").startswith("Basic ")
|
||||||
|
p = request.url.path
|
||||||
|
q = request.url.params
|
||||||
|
if p == "/control/status":
|
||||||
|
return httpx.Response(200, json={"version": "v0.107.99", "running": True, "protection_enabled": True})
|
||||||
|
if p == "/control/querylog":
|
||||||
|
rows = LOG
|
||||||
|
if q.get("search"):
|
||||||
|
rows = [r for r in rows if q["search"] in r["question"]["name"] or q["search"] in r["client"]]
|
||||||
|
if q.get("response_status") == "blocked":
|
||||||
|
rows = [r for r in rows if r["reason"] == "FilteredBlackList"]
|
||||||
|
if q.get("older_than"):
|
||||||
|
cut = adguard.parse_time(q["older_than"])
|
||||||
|
rows = [r for r in rows if adguard.parse_time(r["time"]) < cut]
|
||||||
|
page = rows[: int(q.get("limit", 500))]
|
||||||
|
return httpx.Response(200, json={"data": page, "oldest": page[-1]["time"] if page else ""})
|
||||||
|
if p == "/control/stats":
|
||||||
|
return httpx.Response(200, json={
|
||||||
|
"num_dns_queries": 770, "num_blocked_filtering": 60, "time_units": "hours",
|
||||||
|
"top_queried_domains": [{"api.example.com": 600}, {"www.example.com": 100}],
|
||||||
|
"top_blocked_domains": [{"ads.tracker.net": 60}],
|
||||||
|
"top_clients": [{"192.168.1.5": 660}, {"192.168.1.50": 100}],
|
||||||
|
})
|
||||||
|
if p == "/control/clients":
|
||||||
|
return httpx.Response(200, json={
|
||||||
|
"clients": [{"name": "Neil's laptop", "ids": ["192.168.1.5", "AA:BB:CC:DD:EE:01"]}],
|
||||||
|
"auto_clients": [{"ip": "192.168.1.50", "name": "tv.lan", "source": "rDNS"}],
|
||||||
|
})
|
||||||
|
if p == "/control/dhcp/status":
|
||||||
|
return httpx.Response(200, json={"enabled": True, "leases": [{"mac": "aa:bb:cc:dd:ee:02", "ip": "192.168.1.51", "hostname": "plug"}]})
|
||||||
|
return httpx.Response(404, json={})
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def ag(monkeypatch):
|
||||||
|
monkeypatch.setenv("ADGUARD_URL", "http://adguard.test")
|
||||||
|
monkeypatch.setenv("ADGUARD_USERNAME", "admin")
|
||||||
|
monkeypatch.setenv("ADGUARD_PASSWORD", "pw")
|
||||||
|
monkeypatch.setattr(adguard, "TRANSPORT", httpx.MockTransport(handler))
|
||||||
|
|
||||||
|
|
||||||
|
def test_not_configured(hub):
|
||||||
|
assert hub.get("/api/dns/status").json()["configured"] is False
|
||||||
|
r = hub.get("/api/dns/queries")
|
||||||
|
assert r.status_code == 503 and "ADGUARD_URL" in r.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_status_and_unreachable(hub, ag, monkeypatch):
|
||||||
|
assert hub.get("/api/dns/status").json()["version"] == "v0.107.99"
|
||||||
|
monkeypatch.setattr(adguard, "TRANSPORT", httpx.MockTransport(lambda r: httpx.Response(401)))
|
||||||
|
j = hub.get("/api/dns/status").json()
|
||||||
|
assert j["ok"] is False and "rejected the login" in j["message"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_discovery_merges_sources(hub, ag):
|
||||||
|
asyncio.run(dns.discover_once())
|
||||||
|
clients = {c["key"]: c for c in hub.get("/api/clients").json()["clients"]}
|
||||||
|
laptop = clients["aa:bb:cc:dd:ee:01"]
|
||||||
|
assert laptop["ip"] == "192.168.1.5" and laptop["hostname"] in ("Neil's laptop", "host-5")
|
||||||
|
assert laptop["online"] and laptop["queries"] == 660 and "adguard" in laptop["sources"]
|
||||||
|
assert not laptop["new"] # found on the first day: not flagged as new
|
||||||
|
assert clients["aa:bb:cc:dd:ee:02"]["hostname"] == "plug"
|
||||||
|
assert "ip:192.168.1.50" in clients # no MAC known for the TV
|
||||||
|
assert "ip:192.168.1.5" not in clients # folded into the MAC entry
|
||||||
|
|
||||||
|
|
||||||
|
def test_ip_entry_folds_into_mac_and_keeps_labels(hub, ag):
|
||||||
|
asyncio.run(dns.discover_once())
|
||||||
|
hub.put("/api/clients/ip:192.168.1.50", json={"name": "Living room TV", "category": "Media", "suspicious": True})
|
||||||
|
with db() as con:
|
||||||
|
from app.hub import devices
|
||||||
|
devices.sighting(con, ip="192.168.1.50", mac="aa:bb:cc:dd:ee:50", source="arp")
|
||||||
|
c = hub.get("/api/clients/aa:bb:cc:dd:ee:50").json()
|
||||||
|
assert c["name"] == "Living room TV" and c["category"] == "Media" and c["suspicious"]
|
||||||
|
assert hub.get("/api/clients/ip:192.168.1.50").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_queries_filters_and_paging(hub, ag):
|
||||||
|
asyncio.run(dns.discover_once())
|
||||||
|
r = hub.get("/api/dns/queries", params={"client": "aa:bb:cc:dd:ee:01", "limit": 50}).json()
|
||||||
|
assert len(r["rows"]) == 50 and {x["client"] for x in r["rows"]} == {"192.168.1.5"}
|
||||||
|
assert r["rows"][0]["device"]["key"] == "aa:bb:cc:dd:ee:01"
|
||||||
|
more = hub.get("/api/dns/queries", params={"client": "aa:bb:cc:dd:ee:01", "limit": 50, "older_than": r["oldest"]}).json()
|
||||||
|
assert more["rows"][0]["ts"] < r["rows"][-1]["ts"]
|
||||||
|
blocked = hub.get("/api/dns/queries", params={"status": "blocked"}).json()["rows"]
|
||||||
|
assert blocked and all(x["blocked"] for x in blocked)
|
||||||
|
allowed = hub.get("/api/dns/queries", params={"status": "allowed", "search": "tracker"}).json()
|
||||||
|
assert allowed["rows"] == [] and allowed["done"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_summary(hub, ag):
|
||||||
|
asyncio.run(dns.discover_once())
|
||||||
|
s = hub.get("/api/clients/aa:bb:cc:dd:ee:01/summary").json()
|
||||||
|
assert s["top"][0]["domain"] == "api.example.com" and s["blocked"] == 60
|
||||||
|
|
||||||
|
|
||||||
|
def test_domain_detail(hub, ag):
|
||||||
|
d = hub.get("/api/domains/www.example.com").json()
|
||||||
|
assert d["base"] == "example.com" and d["count"] == 100
|
||||||
|
assert d["clients"][0]["ip"] == "192.168.1.50"
|
||||||
|
assert {"domain": "api.example.com", "count": 600, "blocked": 0} in d["related"]
|
||||||
|
assert d["stats_count"] == 100
|
||||||
|
uk = hub.get("/api/domains/cdn.example.co.uk").json()
|
||||||
|
assert uk["base"] == "example.co.uk" and uk["count"] == 10
|
||||||
|
|
||||||
|
|
||||||
|
def test_blocked_and_top(hub, ag):
|
||||||
|
b = hub.get("/api/dns/blocked").json()
|
||||||
|
assert b["top"] == [{"domain": "ads.tracker.net", "count": 60}]
|
||||||
|
assert b["recent"][0]["domain"] == "ads.tracker.net" and b["recent"][0]["rule"] == "||ads.tracker.net^"
|
||||||
|
t = hub.get("/api/domains").json()
|
||||||
|
assert t["top_queried"][0] == {"domain": "api.example.com", "count": 600}
|
||||||
|
|
||||||
|
|
||||||
|
def test_base_domain():
|
||||||
|
assert adguard.base_domain("a.b.c.example.com") == "example.com"
|
||||||
|
assert adguard.base_domain("x.bbc.co.uk") == "bbc.co.uk"
|
||||||
|
assert adguard.base_domain("localhost") == "localhost"
|
||||||
|
assert adguard.base_domain("1.2.3.4") == "1.2.3.4"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_time_nanoseconds():
|
||||||
|
assert adguard.parse_time("2026-11-04T10:00:00.123456789+02:00") == datetime(2026, 11, 4, 8, 0, 0, 123456, UTC).timestamp()
|
||||||
60
tests/test_installers.py
Normal file
60
tests/test_installers.py
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
"""The installers: generated probe installer in sync, and .env handling per mode."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
|
||||||
|
def bash(script: str, **env) -> subprocess.CompletedProcess:
|
||||||
|
return subprocess.run(["bash", "-c", script], capture_output=True, text=True, cwd=ROOT,
|
||||||
|
env={**os.environ, **env}, timeout=30)
|
||||||
|
|
||||||
|
|
||||||
|
def test_probe_installer_is_generated_from_install_sh():
|
||||||
|
r = bash("bash scripts/build-installers.sh --check")
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
for f in ("install.sh", "install-probe.sh", "native/setup.sh", "native/update.sh", "native/run.sh", "native/lib.sh"):
|
||||||
|
assert bash(f"bash -n {f}").returncode == 0, f
|
||||||
|
|
||||||
|
|
||||||
|
# Load the installer's functions without running main (its last line).
|
||||||
|
FUNCS = "source <(sed '$d' \"$INSTALLER\"); set -euo pipefail; OS=Linux; SUDO=; "
|
||||||
|
|
||||||
|
|
||||||
|
def test_write_env_new_and_rerun(tmp_path):
|
||||||
|
d = tmp_path / "opt"
|
||||||
|
d.mkdir()
|
||||||
|
(d / ".env.probe.example").write_text((ROOT / ".env.probe.example").read_text())
|
||||||
|
setup = FUNCS + f'''NETMON_ROLE=probe; ROLE=probe; INSTALL_DIR={d}; ENV_EXAMPLE=.env.probe.example; MODE=native
|
||||||
|
KEYS="REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY INSTALL_MODE HUB_URL PROBE_TOKEN PROBE_PORT ADVERTISE_ADDR"
|
||||||
|
install() {{ cp "${{@: -2:1}}" "${{@: -1}}"; }} # no chown in tests
|
||||||
|
'''
|
||||||
|
r = bash(setup + 'PASSED=" "; REPO_URL=git://x/r.git; REPO_REF=main; HUB_URL=http://hub:8000; PROBE_TOKEN=abc; PROBE_PORT=8765; INSTALL_MODE=native; write_env',
|
||||||
|
INSTALLER="install-probe.sh")
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
env = (d / ".env").read_text()
|
||||||
|
for line in ("REPO_URL=git://x/r.git", "HUB_URL=http://hub:8000", "PROBE_TOKEN=abc", "INSTALL_MODE=native", "PROBE_PORT=8765"):
|
||||||
|
assert line + "\n" in env
|
||||||
|
# Re-run passing one key: the rest is kept, comments too.
|
||||||
|
r = bash(setup + 'PASSED=" ADVERTISE_ADDR "; ADVERTISE_ADDR=10.0.0.9; write_env', INSTALLER="install-probe.sh")
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
env2 = (d / ".env").read_text()
|
||||||
|
assert "ADVERTISE_ADDR=10.0.0.9\n" in env2 and "PROBE_TOKEN=abc\n" in env2 and "# The hub this probe reports to" in env2
|
||||||
|
# And load_existing_env reads the saved mode back.
|
||||||
|
r = bash(setup + 'INSTALL_MODE=; HUB_URL=; load_existing_env >/dev/null; echo "$INSTALL_MODE $HUB_URL"', INSTALLER="install-probe.sh")
|
||||||
|
assert r.stdout.strip() == "native http://hub:8000", r.stderr
|
||||||
|
|
||||||
|
|
||||||
|
def test_choose_mode(tmp_path):
|
||||||
|
base = FUNCS + 'KEYS="INSTALL_MODE"; PASSED=" "; log() { :; }; is_lxc() { return 1; }; '
|
||||||
|
run = lambda s: bash(base + s, INSTALLER="install.sh")
|
||||||
|
assert run('INSTALL_MODE=; choose_mode; echo $MODE').stdout.strip() == "docker"
|
||||||
|
assert run('is_lxc() { return 0; }; id() { echo 0; }; INSTALL_MODE=; choose_mode; echo $MODE').stdout.strip() == "native"
|
||||||
|
assert run('OS=Darwin; id() { echo 501; }; INSTALL_MODE=; choose_mode; echo $MODE').stdout.strip() == "native"
|
||||||
|
r = run('OS=Darwin; id() { echo 501; }; INSTALL_MODE=docker; choose_mode')
|
||||||
|
assert r.returncode != 0 and "INSTALL_MODE=native" in r.stderr
|
||||||
|
r = run('id() { echo 1000; }; INSTALL_MODE=native; choose_mode')
|
||||||
|
assert r.returncode != 0 and "run as root" in r.stderr
|
||||||
|
assert run('INSTALL_MODE=bogus; choose_mode').returncode != 0
|
||||||
132
tests/test_probe.py
Normal file
132
tests/test_probe.py
Normal file
|
|
@ -0,0 +1,132 @@
|
||||||
|
"""The probe role: its endpoints, its checks and its report loop."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import socket
|
||||||
|
import struct
|
||||||
|
import threading
|
||||||
|
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.probe import checks
|
||||||
|
|
||||||
|
|
||||||
|
def test_probe_endpoints(monkeypatch):
|
||||||
|
monkeypatch.setenv("ROLE", "probe")
|
||||||
|
from app.probe.server import app
|
||||||
|
with TestClient(app) as c:
|
||||||
|
assert c.get("/healthz").json()["role"] == "probe"
|
||||||
|
assert c.get("/probe/ping").json()["ok"]
|
||||||
|
blob = c.get("/probe/blob?bytes=200000")
|
||||||
|
assert len(blob.content) == 200000
|
||||||
|
assert c.get("/").json()["mode"] == "serve only"
|
||||||
|
assert c.get("/probe/blob?bytes=999999999").status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def fake_dns_server(rcode=0, answers=1):
|
||||||
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
s.bind(("127.0.0.1", 0))
|
||||||
|
|
||||||
|
def serve():
|
||||||
|
data, addr = s.recvfrom(512)
|
||||||
|
qid = struct.unpack("!H", data[:2])[0]
|
||||||
|
s.sendto(struct.pack("!HHHHHH", qid, 0x8180 | rcode, 1, answers, 0, 0) + data[12:], addr)
|
||||||
|
s.close()
|
||||||
|
threading.Thread(target=serve, daemon=True).start()
|
||||||
|
return s.getsockname()[1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_dns_check():
|
||||||
|
for rcode, answers, ok, err in [(0, 1, True, None), (3, 0, False, "NXDOMAIN"), (0, 0, False, "empty answer")]:
|
||||||
|
port = fake_dns_server(rcode, answers)
|
||||||
|
r = asyncio.run(checks.dns("127.0.0.1", "example.com", "dns:x", "x", "lan", port=port))
|
||||||
|
assert r["ok"] is ok and r["error"] == err and r["method"] == "dns"
|
||||||
|
|
||||||
|
|
||||||
|
def test_dns_timeout():
|
||||||
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
s.bind(("127.0.0.1", 0)) # bound but silent
|
||||||
|
r = asyncio.run(checks.dns("127.0.0.1", "example.com", "dns:x", "x", "lan", timeout=0.3, port=s.getsockname()[1]))
|
||||||
|
s.close()
|
||||||
|
assert not r["ok"] and r["error"] == "timeout"
|
||||||
|
|
||||||
|
|
||||||
|
def test_proc_net_parsing(tmp_path, monkeypatch):
|
||||||
|
(tmp_path / "route").write_text(
|
||||||
|
"Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n"
|
||||||
|
"eth0\t00000000\t0101A8C0\t0003\t0\t0\t100\t00000000\t0\t0\t0\n"
|
||||||
|
"eth0\t0001A8C0\t00000000\t0001\t0\t0\t100\t00FFFFFF\t0\t0\t0\n")
|
||||||
|
(tmp_path / "arp").write_text(
|
||||||
|
"IP address HW type Flags HW address Mask Device\n"
|
||||||
|
"192.168.1.1 0x1 0x2 AA:bb:cc:dd:ee:ff * eth0\n"
|
||||||
|
"192.168.1.77 0x1 0x0 00:00:00:00:00:00 * eth0\n"
|
||||||
|
"172.18.0.2 0x1 0x2 02:42:ac:12:00:02 * br-1a2b3c\n"
|
||||||
|
"172.17.0.3 0x1 0x2 02:42:ac:11:00:03 * docker0\n")
|
||||||
|
monkeypatch.setattr(checks, "PROC_NET", str(tmp_path))
|
||||||
|
assert checks.default_gateway() == "192.168.1.1"
|
||||||
|
assert checks.neighbors() == [{"ip": "192.168.1.1", "mac": "aa:bb:cc:dd:ee:ff"}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_probe_reports_to_hub(hub, monkeypatch):
|
||||||
|
"""One real cycle: the probe loop measures (with the network stubbed) and reports to the hub."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.probe import server as probe
|
||||||
|
|
||||||
|
pid = hub.post("/api/probes", json={"name": "Kitchen"}).json()
|
||||||
|
monkeypatch.setenv("HUB_URL", "http://hub.test")
|
||||||
|
monkeypatch.setenv("PROBE_TOKEN", pid["token"])
|
||||||
|
|
||||||
|
async def no_icmp(*a, **k):
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def fake_dns(server, name, target, label, kind, **kw):
|
||||||
|
return checks.m(target, label, kind, "dns", True, latency=12.0)
|
||||||
|
monkeypatch.setattr(checks, "icmp", no_icmp)
|
||||||
|
monkeypatch.setattr(checks, "dns", fake_dns)
|
||||||
|
monkeypatch.setattr(checks, "default_gateway", lambda: None)
|
||||||
|
|
||||||
|
def via_hub(request: httpx.Request):
|
||||||
|
r = hub.request(request.method, request.url.path, content=request.content, headers=dict(request.headers))
|
||||||
|
return httpx.Response(r.status_code, content=r.content, headers={"content-type": "application/json"})
|
||||||
|
real_client = httpx.AsyncClient
|
||||||
|
monkeypatch.setattr(probe.httpx, "AsyncClient", lambda **kw: real_client(transport=httpx.MockTransport(via_hub), **kw))
|
||||||
|
|
||||||
|
async def one_cycle():
|
||||||
|
sleeps = []
|
||||||
|
|
||||||
|
async def fake_sleep(s):
|
||||||
|
sleeps.append(s)
|
||||||
|
if len(sleeps) > 2:
|
||||||
|
raise asyncio.CancelledError
|
||||||
|
monkeypatch.setattr(probe.asyncio, "sleep", fake_sleep)
|
||||||
|
try:
|
||||||
|
await probe.probe_loop()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
asyncio.run(one_cycle())
|
||||||
|
assert probe.state["registered"] is True and probe.state["config"]["name"] == "Kitchen"
|
||||||
|
mx = hub.get("/api/health/matrix").json()
|
||||||
|
assert any(c["target"] == "dns:1.1.1.1" and c["status"] == "ok" for c in mx["cells"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_macos_parsers():
|
||||||
|
route = """ route to: default
|
||||||
|
destination: default
|
||||||
|
mask: default
|
||||||
|
gateway: 192.168.68.1
|
||||||
|
interface: en0
|
||||||
|
flags: <UP,GATEWAY,DONE,STATIC,PRCLONING,GLOBAL>
|
||||||
|
"""
|
||||||
|
assert checks.parse_route_get(route) == "192.168.68.1"
|
||||||
|
assert checks.parse_route_get("route: writing to routing socket: not in table\n") is None
|
||||||
|
arp = """? (192.168.68.1) at 0:ef:15:97:fc:1e on en0 ifscope [ethernet]
|
||||||
|
? (192.168.68.20) at e0:51:d8:1c:5f:96 on en0 ifscope [ethernet]
|
||||||
|
? (192.168.68.77) at (incomplete) on en0 ifscope [ethernet]
|
||||||
|
? (192.168.68.255) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet]
|
||||||
|
? (192.168.64.2) at 2a:1:3:4:5:6 on bridge100 ifscope [bridge]
|
||||||
|
? (224.0.0.251) at 1:0:5e:0:0:fb on en0 ifscope permanent [ethernet]
|
||||||
|
"""
|
||||||
|
assert checks.parse_arp_an(arp) == [
|
||||||
|
{"ip": "192.168.68.1", "mac": "00:ef:15:97:fc:1e"},
|
||||||
|
{"ip": "192.168.68.20", "mac": "e0:51:d8:1c:5f:96"},
|
||||||
|
]
|
||||||
88
tests/test_probes.py
Normal file
88
tests/test_probes.py
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
def add(hub, name):
|
||||||
|
r = hub.post("/api/probes", json={"name": name})
|
||||||
|
assert r.status_code == 201
|
||||||
|
return r.json()
|
||||||
|
|
||||||
|
|
||||||
|
def send(hub, token, measurements=(), **extra):
|
||||||
|
return hub.post("/api/probe/report", json={"port": 8765, "measurements": list(measurements), **extra},
|
||||||
|
headers={"Authorization": f"Bearer {token}"})
|
||||||
|
|
||||||
|
|
||||||
|
def meas(target, method="icmp", ok=True, latency=5.0, ts=None, kind="lan", **kw):
|
||||||
|
return {"ts": ts or time.time(), "target": target, "label": target, "kind": kind, "method": method,
|
||||||
|
"ok": ok, "latency": latency if ok else None, **kw}
|
||||||
|
|
||||||
|
|
||||||
|
def test_register_report_and_peers(hub):
|
||||||
|
a, b = add(hub, "Office"), add(hub, "Garage")
|
||||||
|
assert send(hub, "bogus").status_code == 401
|
||||||
|
r = send(hub, a["token"], advertise_addr="192.168.1.10")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.json()["peers"] == [] # Garage hasn't reported an address yet
|
||||||
|
r = send(hub, b["token"], advertise_addr="192.168.1.20")
|
||||||
|
peers = r.json()["peers"]
|
||||||
|
assert peers == [{"id": a["id"], "name": "Office", "host": "192.168.1.10", "port": 8765}]
|
||||||
|
probes = {p["name"]: p for p in hub.get("/api/probes").json()["probes"]}
|
||||||
|
assert probes["Office"]["online"] and probes["Garage"]["address"] == "192.168.1.20"
|
||||||
|
assert "token" not in probes["Office"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_address_override_and_delete(hub):
|
||||||
|
a = add(hub, "Attic")
|
||||||
|
hub.patch(f"/api/probes/{a['id']}", json={"address": "10.0.0.5"})
|
||||||
|
send(hub, a["token"], advertise_addr="192.168.1.99")
|
||||||
|
assert hub.get(f"/api/probes/{a['id']}").json()["address"] == "10.0.0.5" # locked by hand
|
||||||
|
assert hub.delete(f"/api/probes/{a['id']}").status_code == 204
|
||||||
|
assert send(hub, a["token"]).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_health_views(hub):
|
||||||
|
a, b = add(hub, "Office"), add(hub, "Garage")
|
||||||
|
send(hub, b["token"], advertise_addr="192.168.1.20")
|
||||||
|
now = time.time()
|
||||||
|
rows = []
|
||||||
|
for i in range(20): # 10 minutes at 30s
|
||||||
|
ts = now - 600 + i * 30
|
||||||
|
down = 8 <= i <= 11
|
||||||
|
rows.append(meas(f"probe:{b['id']}", "icmp", ok=not down, ts=ts, loss=1.0 if down else 0.0))
|
||||||
|
rows.append(meas(f"probe:{b['id']}", "http", ok=not down, ts=ts, latency=12))
|
||||||
|
rows.append(meas("dns:1.1.1.1", "dns", ts=ts, kind="wan", latency=900 if i >= 17 else 20))
|
||||||
|
rows.append(meas(f"probe:{b['id']}", "throughput", ts=ts, mbps=80.0))
|
||||||
|
assert send(hub, a["token"], rows).status_code == 200
|
||||||
|
|
||||||
|
inc = hub.get("/api/health/incidents?range=1h").json()["incidents"]
|
||||||
|
kinds = {(i["label"], i["type"]) for i in inc}
|
||||||
|
assert ("Garage", "down") in kinds and ("dns:1.1.1.1", "degraded") in kinds
|
||||||
|
down = next(i for i in inc if i["type"] == "down")
|
||||||
|
assert down["methods"] == ["http", "icmp"] and down["failed"] == 8
|
||||||
|
|
||||||
|
strips = hub.get("/api/health/strips?range=1h").json()
|
||||||
|
garage = next(s for s in strips["series"] if s["target"] == f"probe:{b['id']}")
|
||||||
|
assert garage["label"] == "Garage" and len(garage["buckets"]) == 60
|
||||||
|
assert "down" in {x["s"] for x in garage["buckets"] if x}
|
||||||
|
assert 0 < garage["uptime"] < 100
|
||||||
|
|
||||||
|
mx = hub.get("/api/health/matrix?window=120").json()
|
||||||
|
cell = next(c for c in mx["cells"] if c["target"] == "dns:1.1.1.1")
|
||||||
|
assert cell["status"] == "down" or cell["status"] == "degraded"
|
||||||
|
assert [t["target"] for t in mx["targets"]][0] == f"probe:{b['id']}" # peers first
|
||||||
|
|
||||||
|
ser = hub.get(f"/api/health/series?probe={a['id']}&range=1h").json()
|
||||||
|
t = next(t for t in ser["targets"] if t["target"] == f"probe:{b['id']}")
|
||||||
|
assert set(t["methods"]) == {"icmp", "http", "throughput"}
|
||||||
|
assert any(x and x["mbps"] == 80.0 for x in t["methods"]["throughput"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_bad_range(hub):
|
||||||
|
assert hub.get("/api/health/strips?range=2y").status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_arp_neighbors_become_clients(hub):
|
||||||
|
a = add(hub, "Office")
|
||||||
|
send(hub, a["token"], neighbors=[{"ip": "192.168.1.50", "mac": "AA:BB:CC:00:11:22"}])
|
||||||
|
clients = hub.get("/api/clients").json()["clients"]
|
||||||
|
assert clients[0]["key"] == "aa:bb:cc:00:11:22" and clients[0]["online"] and clients[0]["sources"] == ["arp"]
|
||||||
Loading…
Add table
Add a link
Reference in a new issue