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

99 lines
4.2 KiB
Bash

# 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
}