network-monitor/install-probe.sh
neil 54a765510a Network monitor: hub, probes, Docker and native installers
Hub (FastAPI + no-build web UI):
- Network health: live probe/target matrix, status strips, incidents
- Probes: add (with install command), rename, remove, latency and throughput charts
- Clients merged from AdGuard, DHCP, query log and probe ARP tables; names,
  categories, suspicious flag, notes, per-client DNS requests
- Query log, domain detail (clients, related subdomains), blocked domains via
  the AdGuard Home /control API

Probe: tests peers (ping, HTTP, throughput), gateway, LAN and public DNS,
internet URLs and an optional VPS; buffers results while the hub is down.
Gateway and ARP from /proc/net on Linux, route/arp on macOS.

Install: install.sh (hub) and install-probe.sh (generated from it), each in
docker mode (compose; default on Linux hosts) or native mode (venv + systemd
or launchd; default on macOS and in LXC). Both modes deploy with an update
command that checks the new commit and rolls back on failure.

CLAUDE.md carries shared context for Claude Code sessions on each machine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 18:10:29 -08:00

365 lines
17 KiB
Bash
Executable file

#!/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 "$@"