diff --git a/CLAUDE.md b/CLAUDE.md index dd1fa1a..887b413 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,6 +39,9 @@ The mode is stored as `INSTALL_MODE` in `/opt//.env`. The intended topology: - **Proxmox VE nodes:** `lxc` mode, the default when `pct` and `/etc/pve` exist. Running the installer on the node as root creates (or reuses, found by tag `netmon-hub` / `netmon-probe`) an unprivileged Debian LXC on `vmbr0`. It then `pct push`es itself into the container (re-assembled from its own functions with `declare -f`) and runs there in native mode. `LXC_*` variables override ID, storage, bridge, IP and size. Day to day: `pct exec -- network-probe-update`, `pct enter `. + - **Names and port:** in an LXC (lxc mode, or native mode where `systemd-detect-virt -c` says lxc), `native/setup.sh` installs avahi-daemon, which announces `.local`. It comments out `rlimit-nproc` in `avahi-daemon.conf`, because the stock value stops avahi-daemon from starting in unprivileged containers. The hub defaults to `HOST_PORT=80` there, granted by `AmbientCapabilities=CAP_NET_BIND_SERVICE`, unless `HOST_PORT` is passed. + - **Inner run:** lxc mode runs the inner installer with `LANG/LC_ALL=C.UTF-8` (the node's locale may not exist in the container) and `NETMON_NESTED=1`, which shortens the inner summary. + - **Probe commands:** Linux probes usually can't resolve `.local`. When the UI is opened by a `.local` name, the Add probe command uses `hub_lan_url` (the hub's own IP, native installs only) as `HUB_URL`. - 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. - The first real deploy (gmktec-g9, 2026-11-05) predates `lxc` mode and installed the hub with Docker on the node. The README section "Removing a Docker install from a Proxmox node" covers cleanup. - **Mac mini:** native probe. diff --git a/README.md b/README.md index 19c38b2..ceba886 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,8 @@ To change the defaults, set these before `bash`: For example: `curl -fsSL .../install.sh | LXC_IP=192.168.68.50/24 LXC_GW=192.168.68.1 bash`. Notes: -- **Fixed IP for the hub:** give its container a DHCP reservation or a static IP. Probes report to it, and the Add probe command contains its address. +- **`.local` names:** the installer runs Avahi in the container, so it answers at `.local`. The hub's container is `netmon-hub`, so `http://netmon-hub.local`. The hub has the container to itself and listens on port 80, so no port is needed; pass `HOST_PORT` to choose another. Native installs inside an LXC you made yourself work the same way. +- **Fixed IP for the hub:** give its container a DHCP reservation or a static IP. Probes report to it, and the Add probe command contains its address. Opened at `netmon-hub.local`, the hub puts its IP in the command anyway, because Linux probes usually can't resolve `.local` names. - **What the probe measures:** the container sits on the node's bridge, so its traffic leaves through the node's NIC, and the probe measures that node's link. - **Neighbors:** a probe in a container sees only the devices it has talked to, not everything the node sees. AdGuard is the main source of the client list, so this rarely matters. - **Ping:** inside an unprivileged container, the ping setting is limited to the container's mapped groups (0–65535). The installer handles that. diff --git a/app/hub/probes.py b/app/hub/probes.py index b6469f2..0860ef9 100644 --- a/app/hub/probes.py +++ b/app/hub/probes.py @@ -1,6 +1,7 @@ """Probe management (UI) and the probe report endpoint (probes, token auth).""" import ipaddress +import os import secrets import time @@ -68,13 +69,26 @@ def probe_out(row, *, with_token: bool = False) -> dict: return out +def _lan_url(request: Request) -> str: + """The hub's own address, for probe install commands when the UI was opened by a .local + name: Linux probes (in LXCs or Docker) usually can't resolve .local. Only meaningful for + native installs; in Docker this would be the container's bridge address.""" + if (os.environ.get("INSTALL_MODE") or "docker") != "native": + return "" + host, port = (request.scope.get("server") or (None, None)) + if not host or host.startswith("127.") or host == "::1": + return "" + host = f"[{host}]" if ":" in host else host + return f"http://{host}" + ("" if port in (80, None) else f":{port}") + + @router.get("/probes") -def list_probes() -> dict: +def list_probes(request: Request) -> 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} + "install_url": s.probe_install_url, "hub_url": s.hub_public_url, "hub_lan_url": _lan_url(request)} @router.post("/probes", status_code=201) diff --git a/app/static/js/views/probes.js b/app/static/js/views/probes.js index 1d43ef4..be399b1 100644 --- a/app/static/js/views/probes.js +++ b/app/static/js/views/probes.js @@ -12,7 +12,9 @@ export function mount(root, ctx) { } function installCommand(info, token) { - const hub = info.hub_url || location.origin; + // A .local name works in browsers but usually not inside Linux probes: use the hub's IP then. + const viaMdns = location.hostname.endsWith('.local'); + const hub = info.hub_url || (viaMdns && info.hub_lan_url) || location.origin; const url = info.install_url || `${hub}/install-probe.sh`; return `curl -fsSL ${url} | HUB_URL=${hub} PROBE_TOKEN=${token} bash`; } diff --git a/install-probe.sh b/install-probe.sh index 95fad4f..05b20d6 100755 --- a/install-probe.sh +++ b/install-probe.sh @@ -70,12 +70,19 @@ main() { fi CALLER_MODE=${INSTALL_MODE:-} + CALLER_PORT=${!PORT_KEY:-} 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 + # In an LXC the hub is the only service on its "machine": serve it on port 80 so + # http://.local works without a port (Avahi announces the name). + if [ "$ROLE" = hub ] && [ -z "$CALLER_PORT" ] && uses_lan_name; then + HOST_PORT=80 + in_list HOST_PORT "$PASSED" || PASSED="${PASSED}HOST_PORT " + fi if [ "$MODE" = lxc ]; then lxc_install; return; fi step "prerequisites" @@ -96,7 +103,9 @@ main() { 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" + AVAHI=0 + if uses_lan_name; then AVAHI=1; fi + NAME=$NAME ROLE=$ROLE INSTALL_DIR=$INSTALL_DIR AVAHI=$AVAHI bash "$INSTALL_DIR/native/setup.sh" fi wait_healthy @@ -119,6 +128,13 @@ is_lxc() { grep -qa 'container=lxc' /proc/1/environ 2>/dev/null } +# One service per (virtual) machine: an LXC, or the container lxc mode creates. There the +# install announces .local with Avahi, and the hub takes port 80. +uses_lan_name() { + [ "${NETMON_LAN_NAME:-}" = 1 ] && return 0 + [ "$MODE" = lxc ] || { [ "$MODE" = native ] && is_lxc; } +} + is_pve_host() { [ "$OS" = Linux ] && command -v pct >/dev/null 2>&1 && [ -d "${NETMON_PVE_DIR:-/etc/pve}" ] } @@ -191,7 +207,8 @@ lxc_install() { { printf '#!/usr/bin/env bash\nNETMON_ROLE=%s\n' "$ROLE"; declare -f; printf 'main "$@"\n'; } > "$script" pct push "$CTID" "$script" /root/netmon-install.sh --perms 0700 rm -f "$script" - set -- env INSTALL_MODE=native + # C.UTF-8 exists in every Debian container; the node's own LANG may not. + set -- env LANG=C.UTF-8 LC_ALL=C.UTF-8 NETMON_NESTED=1 INSTALL_MODE=native for k in $KEYS; do if [ "$k" != INSTALL_MODE ] && [ -n "${!k:-}" ]; then set -- "$@" "$k=${!k}"; fi done @@ -199,9 +216,14 @@ lxc_install() { pct exec "$CTID" -- rm -f /root/netmon-install.sh ip=$(pct exec "$CTID" -- hostname -I 2>/dev/null | cut -d' ' -f1) + local host suffix= + host=$(pct config "$CTID" | sed -n 's/^hostname: //p') + [ "$port" = 80 ] || suffix=":$port" step "done" - echo "$NAME runs in Proxmox container $CTID ($(pct config "$CTID" | sed -n 's/^hostname: //p')), IP ${ip:-unknown}." - if [ "$ROLE" = hub ]; then echo " open the web UI: http://${ip:-}:$port"; fi + echo "$NAME runs in Proxmox container $CTID ($host), IP ${ip:-unknown}." + if [ "$ROLE" = hub ]; then + echo " open the web UI: http://$host.local$suffix (or http://${ip:-}$suffix)" + fi echo " give it a fixed IP: a DHCP reservation, or pct set $CTID --net0 name=eth0,bridge=...,ip=/,gw=" echo " deploy a new commit: pct exec $CTID -- $NAME-update" echo " logs: pct exec $CTID -- journalctl -u $NAME -f" @@ -486,6 +508,8 @@ my_ip() { finish_message() { local port=${!PORT_KEY} deploy logs remove + # Run inside a container by lxc mode: the outer installer prints the summary. + if [ -n "${NETMON_NESTED:-}" ]; then echo "$NAME ($MODE) is running at $(health_version) on port $port."; return; fi 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" @@ -498,7 +522,8 @@ finish_message() { 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" + if [ "$port" = 80 ]; then echo " open the web UI: http://$(my_ip)"; else echo " open the web UI: http://$(my_ip):$port"; fi + if uses_lan_name; then echo " http://$(hostname -s).local$([ "$port" = 80 ] || echo ":$port")"; fi 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." diff --git a/install.sh b/install.sh index 193db8a..1aad39e 100755 --- a/install.sh +++ b/install.sh @@ -65,12 +65,19 @@ main() { fi CALLER_MODE=${INSTALL_MODE:-} + CALLER_PORT=${!PORT_KEY:-} 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 + # In an LXC the hub is the only service on its "machine": serve it on port 80 so + # http://.local works without a port (Avahi announces the name). + if [ "$ROLE" = hub ] && [ -z "$CALLER_PORT" ] && uses_lan_name; then + HOST_PORT=80 + in_list HOST_PORT "$PASSED" || PASSED="${PASSED}HOST_PORT " + fi if [ "$MODE" = lxc ]; then lxc_install; return; fi step "prerequisites" @@ -91,7 +98,9 @@ main() { 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" + AVAHI=0 + if uses_lan_name; then AVAHI=1; fi + NAME=$NAME ROLE=$ROLE INSTALL_DIR=$INSTALL_DIR AVAHI=$AVAHI bash "$INSTALL_DIR/native/setup.sh" fi wait_healthy @@ -114,6 +123,13 @@ is_lxc() { grep -qa 'container=lxc' /proc/1/environ 2>/dev/null } +# One service per (virtual) machine: an LXC, or the container lxc mode creates. There the +# install announces .local with Avahi, and the hub takes port 80. +uses_lan_name() { + [ "${NETMON_LAN_NAME:-}" = 1 ] && return 0 + [ "$MODE" = lxc ] || { [ "$MODE" = native ] && is_lxc; } +} + is_pve_host() { [ "$OS" = Linux ] && command -v pct >/dev/null 2>&1 && [ -d "${NETMON_PVE_DIR:-/etc/pve}" ] } @@ -186,7 +202,8 @@ lxc_install() { { printf '#!/usr/bin/env bash\nNETMON_ROLE=%s\n' "$ROLE"; declare -f; printf 'main "$@"\n'; } > "$script" pct push "$CTID" "$script" /root/netmon-install.sh --perms 0700 rm -f "$script" - set -- env INSTALL_MODE=native + # C.UTF-8 exists in every Debian container; the node's own LANG may not. + set -- env LANG=C.UTF-8 LC_ALL=C.UTF-8 NETMON_NESTED=1 INSTALL_MODE=native for k in $KEYS; do if [ "$k" != INSTALL_MODE ] && [ -n "${!k:-}" ]; then set -- "$@" "$k=${!k}"; fi done @@ -194,9 +211,14 @@ lxc_install() { pct exec "$CTID" -- rm -f /root/netmon-install.sh ip=$(pct exec "$CTID" -- hostname -I 2>/dev/null | cut -d' ' -f1) + local host suffix= + host=$(pct config "$CTID" | sed -n 's/^hostname: //p') + [ "$port" = 80 ] || suffix=":$port" step "done" - echo "$NAME runs in Proxmox container $CTID ($(pct config "$CTID" | sed -n 's/^hostname: //p')), IP ${ip:-unknown}." - if [ "$ROLE" = hub ]; then echo " open the web UI: http://${ip:-}:$port"; fi + echo "$NAME runs in Proxmox container $CTID ($host), IP ${ip:-unknown}." + if [ "$ROLE" = hub ]; then + echo " open the web UI: http://$host.local$suffix (or http://${ip:-}$suffix)" + fi echo " give it a fixed IP: a DHCP reservation, or pct set $CTID --net0 name=eth0,bridge=...,ip=/,gw=" echo " deploy a new commit: pct exec $CTID -- $NAME-update" echo " logs: pct exec $CTID -- journalctl -u $NAME -f" @@ -481,6 +503,8 @@ my_ip() { finish_message() { local port=${!PORT_KEY} deploy logs remove + # Run inside a container by lxc mode: the outer installer prints the summary. + if [ -n "${NETMON_NESTED:-}" ]; then echo "$NAME ($MODE) is running at $(health_version) on port $port."; return; fi 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" @@ -493,7 +517,8 @@ finish_message() { 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" + if [ "$port" = 80 ]; then echo " open the web UI: http://$(my_ip)"; else echo " open the web UI: http://$(my_ip):$port"; fi + if uses_lan_name; then echo " http://$(hostname -s).local$([ "$port" = 80 ] || echo ":$port")"; fi 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." diff --git a/native/setup.sh b/native/setup.sh index c803005..2a02f4f 100755 --- a/native/setup.sh +++ b/native/setup.sh @@ -3,8 +3,10 @@ # 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 +# AVAHI=1 also announce .local with Avahi (Linux; set by the installer in LXCs) set -euo pipefail : "${NAME:?}" "${ROLE:?}" "${INSTALL_DIR:?}" +AVAHI=${AVAHI:-0} . "$INSTALL_DIR/native/lib.sh" SVC_USER_LINUX=netmon MIN_PY=11 @@ -106,6 +108,8 @@ ExecStart=/bin/bash $INSTALL_DIR/native/run.sh Restart=always RestartSec=5 NoNewPrivileges=yes +# Lets the hub listen on port 80 in an LXC (http://.local) without running as root. +AmbientCapabilities=CAP_NET_BIND_SERVICE [Install] WantedBy=multi-user.target @@ -141,4 +145,33 @@ PLIST as_root launchctl bootstrap system "/Library/LaunchDaemons/$SERVICE.plist" as_root launchctl enable "system/$SERVICE" >/dev/null 2>&1 || true fi +if [ "$PLATFORM" = systemd ] && [ "$AVAHI" = 1 ]; then + native_log "avahi: announcing $(hostname -s).local" + if ! command -v avahi-daemon >/dev/null 2>&1; then + if command -v apt-get >/dev/null 2>&1; then + DEBIAN_FRONTEND=noninteractive apt-get install -y -qq avahi-daemon >/dev/null + elif command -v dnf >/dev/null 2>&1; then dnf install -y -q avahi + elif command -v apk >/dev/null 2>&1; then apk add -q avahi + fi + fi + if [ -f /etc/avahi/avahi-daemon.conf ]; then + # The stock rlimit-nproc=3 stops avahi-daemon from starting in unprivileged LXC containers. + sed -i 's/^rlimit-nproc=/#rlimit-nproc=/' /etc/avahi/avahi-daemon.conf + port=$(. "$INSTALL_DIR/native/lib.sh"; load_dotenv "$INSTALL_DIR/.env"; ROLE=$ROLE app_port) + mkdir -p /etc/avahi/services + # Also list the web UI in Bonjour/DNS-SD browsers. + cat > "/etc/avahi/services/$NAME.service" < + + + Network Monitor ($ROLE) on %h + _http._tcp$port + +SVC + systemctl enable avahi-daemon >/dev/null 2>&1 || true + systemctl restart avahi-daemon || native_log "warning: avahi-daemon did not start; check: journalctl -u avahi-daemon" + else + native_log "warning: could not install avahi-daemon; .local will not be announced" + fi +fi native_log "setup done ($PLATFORM service $SERVICE, user $SVC_USER)" diff --git a/tests/test_installers.py b/tests/test_installers.py index b73f7ee..70f06b4 100644 --- a/tests/test_installers.py +++ b/tests/test_installers.py @@ -84,7 +84,8 @@ export -f pct pvesh pveam pvesm sleep id ''' pve = tmp_path / "pve" pve.mkdir() - env = {**os.environ, "NETMON_PVE_DIR": str(pve), "INSTALL_DIR": str(tmp_path / "opt"), "HOST_PORT": "8000"} + env = {k: v for k, v in os.environ.items() if k != "HOST_PORT"} + env.update({"NETMON_PVE_DIR": str(pve), "INSTALL_DIR": str(tmp_path / "opt"), "LANG": "en_US.UTF-8"}) run = lambda: subprocess.run(["bash", "-c", stubs + "bash install.sh"], cwd=ROOT, capture_output=True, text=True, env=env, timeout=60) r = run() assert r.returncode == 0, r.stdout + r.stderr @@ -97,8 +98,10 @@ export -f pct pvesh pveam pvesm sleep id assert part in create, part assert "pct start 105" in calls inner = next(line for line in calls.splitlines() if "netmon-install.sh" in line and "exec 105 -- env" in line) - assert "INSTALL_MODE=native" in inner and "HOST_PORT=8000" in inner - assert "http://192.168.68.50:8000" in r.stdout + # Native inside, port 80 for the .local name, a locale the container has, one summary. + for part in ("INSTALL_MODE=native", "HOST_PORT=80", "LC_ALL=C.UTF-8", "LANG=C.UTF-8", "NETMON_NESTED=1"): + assert part in inner, part + assert "http://netmon-hub.local (or http://192.168.68.50)" in r.stdout # The pushed script is a complete installer for the same role. text = pushed.read_text() assert "NETMON_ROLE=hub" in text and text.rstrip().endswith('main "$@"') @@ -139,3 +142,10 @@ export -f pct pvecm pvesm id r = subprocess.run(["bash", "-c", stubs + "bash install.sh"], cwd=ROOT, capture_output=True, text=True, env=env, timeout=60) assert r.returncode != 0 and "without quorum" in r.stderr and "pvecm expected 1" in r.stderr assert not (tmp_path / "calls").exists() # stopped before touching pct or storage + + +def test_explicit_port_wins_over_lan_default(tmp_path): + base = FUNCS + 'KEYS="INSTALL_MODE HOST_PORT"; PASSED=" "; log() { :; }; is_lxc() { return 0; }; id() { echo 0; }; ROLE=hub; PORT_KEY=HOST_PORT; ' + pick = 'CALLER_MODE=; choose_mode; if [ "$ROLE" = hub ] && [ -z "$CALLER_PORT" ] && uses_lan_name; then HOST_PORT=80; fi; echo "$MODE $HOST_PORT"' + assert bash(base + 'CALLER_PORT=; HOST_PORT=8000; ' + pick, INSTALLER="install.sh").stdout.strip() == "native 80" + assert bash(base + 'CALLER_PORT=9000; HOST_PORT=9000; ' + pick, INSTALLER="install.sh").stdout.strip() == "native 9000" diff --git a/tests/test_probes.py b/tests/test_probes.py index 3568806..c1f632e 100644 --- a/tests/test_probes.py +++ b/tests/test_probes.py @@ -86,3 +86,9 @@ def test_arp_neighbors_become_clients(hub): 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"] + + +def test_hub_lan_url_for_native_installs(hub, monkeypatch): + assert hub.get("/api/probes").json()["hub_lan_url"] == "" # docker: the server address is the bridge's + monkeypatch.setenv("INSTALL_MODE", "native") + assert hub.get("/api/probes").json()["hub_lan_url"] == "http://testserver"