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
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
|
||||
Loading…
Add table
Add a link
Reference in a new issue