From a17f2b502cba14a919d9e5a1c271b0c0aff08c25 Mon Sep 17 00:00:00 2001 From: neil Date: Wed, 4 Nov 2026 18:28:21 -0800 Subject: [PATCH] Proxmox nodes: install in an LXC container instead of Docker on the node Run on a Proxmox VE node (pct and /etc/pve present), the installers now default to INSTALL_MODE=lxc: create or reuse (by tag netmon-hub / netmon-probe) an unprivileged Debian LXC on vmbr0 with nesting and onboot, push the installer into it (rebuilt from its own functions) and run it there in native mode. LXC_* variables override ID, storage, template storage, bridge, IP and size. Docker on a node now needs an explicit INSTALL_MODE=docker and prints a warning; an earlier Docker install is pointed out with removal steps. Ping setup inside an unprivileged container stays within the mapped group range, which the kernel requires. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 9 ++- README.md | 65 +++++++++++----- app/static/js/views/probes.js | 2 +- install-probe.sh | 140 +++++++++++++++++++++++++++++++-- install.sh | 141 ++++++++++++++++++++++++++++++++-- scripts/build-installers.sh | 11 ++- tests/test_installers.py | 52 +++++++++++++ 7 files changed, 382 insertions(+), 38 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c9bfab1..dd1fa1a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,6 +26,7 @@ Remote: `https://git.neilbantoc.dev/services/network-monitor.git` (Gitea). The r | Mode | How it runs | Update command | Logs | |---|---|---|---| +| lxc (Proxmox node) | A container made by the installer; inside it, the same as native Linux. | `pct exec -- -update` | `pct exec -- journalctl -u -f` | | 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 ` | | native, Linux | `/opt/` is the git checkout plus `.venv/`, `data/`, `.env`, `.native`. A systemd unit `.service` runs `native/run.sh` as user `netmon`. | `sudo -update` | `journalctl -u -f` | | native, macOS | Same layout. The LaunchDaemon `/Library/LaunchDaemons/dev.neilbantoc..plist` runs as the installing user. | `-update` (no sudo; it calls sudo for `launchctl kickstart`) | `/opt//data/service.log` | @@ -37,7 +38,9 @@ Remote: `https://git.neilbantoc.dev/services/network-monitor.git` (Gitea). The r The mode is stored as `INSTALL_MODE` in `/opt//.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. +- **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 `. + - 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. Both update commands do the same thing: @@ -120,7 +123,7 @@ What has been tested: - re-run keeps `.env` Never run on real hardware yet. Note what you find under "Deployment notes" below: -- an actual Proxmox LXC (unprivileged, nesting) +- an actual Proxmox node: `lxc` mode against real `pct`/`pveam`/`pvesm` (tested with stubs that record the calls), and native mode inside a real unprivileged LXC, including the ping range limited to the container's mapped groups - 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) @@ -128,4 +131,4 @@ Never run on real hardware yet. Note what you find under "Deployment notes" belo Add environment-specific findings here (machine, date, what happened, fix). -- (none yet) +- **gmktec-g9 (Proxmox VE node), 2026-11-05:** the installer run on the node picked Docker mode, because `lxc` mode didn't exist yet, and installed Docker on the node. Fixed: Proxmox nodes now default to `lxc` mode. To clean up, see the README section "Removing a Docker install from a Proxmox node". diff --git a/README.md b/README.md index 0ad8aaf..258c9f6 100644 --- a/README.md +++ b/README.md @@ -38,20 +38,21 @@ It has two parts, built from this one repo and one Docker image: ## 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: +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. Where it installs depends on the machine (`INSTALL_MODE`): | Mode | What it is | Default on | |---|---|---| -| `docker` | The app in a container (compose), Docker installed if missing | Linux hosts (VMs, bare metal) | +| `lxc` | Creates a small Debian LXC container (or reuses the one it made before) and installs natively inside it. The node itself gets no Docker and no packages. | Proxmox VE nodes | | `native` | A Python virtualenv plus a boot service: systemd on Linux, launchd on macOS | macOS, and inside LXC containers | +| `docker` | The app in a container (compose), Docker installed if missing | other Linux hosts (VMs, bare metal) | -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. +Pass `INSTALL_MODE=...` to choose another mode. Outside Proxmox, 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). +- **Proxmox VE nodes:** run the installer on the node as root. It creates an LXC container for the hub or probe and installs inside it. Don't use Docker on the node itself: Docker changes the host firewall, and with the Proxmox firewall on that can cut traffic to guests. - **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. @@ -95,26 +96,52 @@ The probe's test server listens on port 8765 (`PROBE_PORT`) on all interfaces. **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 +### Proxmox: what the installer does on a node -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`: +Run the same commands as above on the node, as root. The installer: + +1. **Finds or creates a container**, tagged `netmon-hub` or `netmon-probe`. Re-running finds it again, so it never makes a second one. A new container is: + - unprivileged Debian 12 or 13, from the newest template in `local`, downloaded if missing + - 1 core, 512 MB, 4 GB on `local-lvm` (or `local-zfs`, or the first storage that holds containers) + - `nesting=1`, start on boot + - on `vmbr0` with DHCP + - named `netmon-hub` or `netmon-probe-` +2. **Starts it** and waits for network. +3. **Copies the installer in** and runs it in native mode. It installs Python, sets up ping and creates the systemd service. +4. **Prints the container's IP** and the `pct exec` commands to update it, read its logs and edit its settings. + +To change the defaults, set these before `bash`: + +| Variable | Default | +|---|---| +| `LXC_ID` | the next free ID | +| `LXC_STORAGE` | `local-lvm`, else `local-zfs`, else the first container storage | +| `LXC_TEMPLATE_STORAGE` | `local` | +| `LXC_BRIDGE` | `vmbr0` | +| `LXC_IP` | `dhcp`; a static address looks like `192.168.68.50/24` together with `LXC_GW=192.168.68.1` | +| `LXC_CORES`, `LXC_MEMORY`, `LXC_DISK` | `1`, `512`, `4` (GB) | + +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. +- **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. + +#### Removing a Docker install from a Proxmox node + +An earlier version of the installer used Docker when run directly on a node. To undo that, as root on the node: ```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 http://:8000/install-probe.sh | HUB_URL=http://:8000 PROBE_TOKEN=... bash +cd /opt/network-monitor && docker compose down -v --rmi all; cd / && rm -rf /opt/network-monitor # same for network-probe +apt-get purge -y $(dpkg-query -W -f='${binary:Package}\n' 'docker-*' containerd.io 2>/dev/null) +rm -rf /var/lib/docker /var/lib/containerd /etc/apt/sources.list.d/docker.* /etc/apt/keyrings/docker.* ``` -- **`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. +Docker also changes the firewall: its rules and a `DROP` policy on the `FORWARD` chain stay until the next reboot. +- **Check:** `iptables -S FORWARD | head -1`. +- **Fix:** if it says `-P FORWARD DROP` and guests have trouble talking to each other or the internet, run `iptables -P FORWARD ACCEPT`, or reboot the node when convenient. ### Mac mini diff --git a/app/static/js/views/probes.js b/app/static/js/views/probes.js index e6fdef5..1d43ef4 100644 --- a/app/static/js/views/probes.js +++ b/app/static/js/views/probes.js @@ -88,7 +88,7 @@ function list(root, ctx) { 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; on Linux that needs root, so outside an LXC put sudo env before HUB_URL. If the git repo is private, the installer asks for a read-only token.'), + el('p', { style: 'margin:0' }, 'Run this on the machine that will be the probe. It starts on boot and keeps running. On a Proxmox node it creates a small LXC container for the probe. On macOS and inside LXC containers it installs as a system service. On other Linux hosts it uses Docker. On Linux it needs root: if you aren't root, put sudo env before HUB_URL. If the git repo is private, the installer asks for a read-only token.'), 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')] }); diff --git a/install-probe.sh b/install-probe.sh index ddbaeb4..a39b126 100755 --- a/install-probe.sh +++ b/install-probe.sh @@ -15,10 +15,13 @@ # Private repo over https: add GIT_TOKEN, read without echoing it: # read -rsp 'Git token: ' GIT_TOKEN && export GIT_TOKEN && curl -fsSL -H "Authorization: token $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. +# Where it installs (INSTALL_MODE): +# lxc On a Proxmox VE node: creates (or reuses) a small Debian LXC container, tagged +# netmon-probe, on the node's bridge, and installs natively inside it. Default on +# Proxmox nodes, so the node itself gets no Docker and no packages. +# docker The probe in a container with host networking. Default on other 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). +# Default on macOS and inside LXC containers. # 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: @@ -34,6 +37,8 @@ # 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) +# Proxmox (lxc mode): LXC_ID, LXC_STORAGE, LXC_TEMPLATE_STORAGE, LXC_BRIDGE, LXC_IP, LXC_GW, +# LXC_CORES, LXC_MEMORY, LXC_DISK (see install.sh) # # Everything is inside main(), so a partial download runs nothing. bash 3.2 compatible (macOS). @@ -64,12 +69,14 @@ main() { SUDO=sudo fi + CALLER_MODE=${INSTALL_MODE:-} 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 + if [ "$MODE" = lxc ]; then lxc_install; return; fi step "prerequisites" install_packages @@ -112,14 +119,34 @@ is_lxc() { grep -qa 'container=lxc' /proc/1/environ 2>/dev/null } +is_pve_host() { + [ "$OS" = Linux ] && command -v pct >/dev/null 2>&1 && [ -d "${NETMON_PVE_DIR:-/etc/pve}" ] +} + choose_mode() { MODE=${INSTALL_MODE:-auto} + if is_pve_host; then + # On a Proxmox node only an explicit INSTALL_MODE counts; a mode saved in .env does not. + MODE=${CALLER_MODE:-auto} + [ "$MODE" != auto ] || MODE=lxc + warn_existing_docker_install + fi 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 + case $MODE in docker|native|lxc) ;; *) die "INSTALL_MODE must be docker, native or lxc, not '$MODE'" ;; esac + if [ "$MODE" = lxc ]; then + is_pve_host || die "INSTALL_MODE=lxc only works on a Proxmox VE node (needs pct)" + [ "$(id -u)" = 0 ] || die "on a Proxmox node, run the installer as root" + log "mode: lxc (Proxmox node: the $ROLE goes in its own container, installed natively inside)" + return + fi + if is_pve_host && [ "$MODE" = docker ]; then + log "warning: installing Docker on a Proxmox node changes its firewall and can break guest networking." + log " Leave INSTALL_MODE unset to install in an LXC container instead." + fi 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 @@ -134,6 +161,103 @@ choose_mode() { log "mode: $MODE" } +# An earlier run on this Proxmox node may have installed with Docker. Say how to remove it. +warn_existing_docker_install() { + [ "${CALLER_MODE:-}" != docker ] || return 0 + local found= + [ -f "$INSTALL_DIR/compose.yml" ] && found=1 + command -v docker >/dev/null 2>&1 && docker inspect "$NAME" >/dev/null 2>&1 && found=1 + [ -n "$found" ] || return 0 + log "note: this node has a Docker install of $NAME from an earlier run. To remove it:" + log " cd $INSTALL_DIR && docker compose -f $COMPOSE_FILE down -v --rmi all && cd / && rm -rf $INSTALL_DIR" + log " The README (Proxmox section) shows how to remove Docker from the node." +} + +# ---------- Proxmox: create (or reuse) an LXC container and install inside it ---------- + +lxc_install() { + local tag="netmon-$ROLE" ctname script ip k port=${!PORT_KEY} + if [ "$ROLE" = hub ]; then ctname=netmon-hub; else ctname="netmon-probe-$(hostname -s | tr -c 'a-zA-Z0-9-\n' '-')"; fi + step "proxmox container" + CTID=$(find_ct "$tag") + if [ -n "$CTID" ]; then log "reusing container $CTID (tagged $tag)"; else create_ct "$ctname" "$tag"; fi + pct status "$CTID" | grep -q running || pct start "$CTID" + wait_ct_network + + step "install inside container $CTID" + # This installer re-assembled from its own functions, so nothing is downloaded again. + script=$(mktemp) + { 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 + for k in $KEYS; do + if [ "$k" != INSTALL_MODE ] && [ -n "${!k:-}" ]; then set -- "$@" "$k=${!k}"; fi + done + pct exec "$CTID" -- "$@" bash /root/netmon-install.sh + pct exec "$CTID" -- rm -f /root/netmon-install.sh + + ip=$(pct exec "$CTID" -- hostname -I 2>/dev/null | cut -d' ' -f1) + 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 " 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" + echo " settings: pct exec $CTID -- nano /opt/$NAME/.env (then: pct exec $CTID -- systemctl restart $NAME)" + echo " shell inside: pct enter $CTID" + echo " upgrade: run this installer on the node again (it reuses container $CTID)" + echo " uninstall: pct stop $CTID && pct destroy $CTID" +} + +# The container this installer made before, found by its tag. +find_ct() { + local id + for id in $(pct list 2>/dev/null | awk 'NR > 1 { print $1 }'); do + if pct config "$id" 2>/dev/null | grep -Eq "^tags: (.*[;, ])?$1([;, ]|\$)"; then echo "$id"; return; fi + done +} + +create_ct() { + local ctname=$1 tag=$2 tstore=${LXC_TEMPLATE_STORAGE:-local} storage=${LXC_STORAGE:-} tmpl name + CTID=${LXC_ID:-$(pvesh get /cluster/nextid)} + tmpl=$(pveam list "$tstore" 2>/dev/null | awk '{ print $1 }' | grep -E 'vztmpl/debian-1[23]-standard' | sort -V | tail -1 || true) + if [ -z "$tmpl" ]; then + log "downloading a Debian template to $tstore" + pveam update >/dev/null 2>&1 || true + name=$(pveam available --section system 2>/dev/null | awk '{ print $2 }' | grep -E '^debian-1[23]-standard' | sort -V | tail -1 || true) + [ -n "$name" ] || die "no Debian 12/13 template available from pveam" + pveam download "$tstore" "$name" >/dev/null || die "could not download $name to $tstore (set LXC_TEMPLATE_STORAGE)" + tmpl="$tstore:vztmpl/$name" + fi + if [ -z "$storage" ]; then + local avail + avail=$(pvesm status --content rootdir --enabled 1 2>/dev/null | awk 'NR > 1 && $3 == "active" { print $1 }') + for name in local-lvm local-zfs $avail; do + if echo "$avail" | grep -qx "$name"; then storage=$name; break; fi + done + [ -n "$storage" ] || die "no active storage for containers found; set LXC_STORAGE" + fi + log "creating container $CTID ($ctname) from $tmpl on $storage, bridge ${LXC_BRIDGE:-vmbr0}" + pct create "$CTID" "$tmpl" --hostname "$ctname" --cores "${LXC_CORES:-1}" --memory "${LXC_MEMORY:-512}" --swap 256 \ + --rootfs "$storage:${LXC_DISK:-4}" \ + --net0 "name=eth0,bridge=${LXC_BRIDGE:-vmbr0},ip=${LXC_IP:-dhcp}${LXC_GW:+,gw=$LXC_GW}" \ + --unprivileged 1 --features nesting=1 --onboot 1 --tags "$tag" \ + --description "Network Monitor $ROLE, created by the $NAME installer" >/dev/null || die "pct create failed" +} + +wait_ct_network() { + log "waiting for container $CTID to get network" + local i=0 + while [ "$i" -lt 90 ]; do + if pct exec "$CTID" -- sh -c 'ip -4 route show default | grep -q . && getent hosts deb.debian.org >/dev/null' 2>/dev/null; then + log "container $CTID is online"; return + fi + sleep 1; i=$((i + 1)) + done + die "container $CTID has no network after 90 s (bridge ${LXC_BRIDGE:-vmbr0}, ip ${LXC_IP:-dhcp}); check: pct exec $CTID -- ip addr" +} + 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" @@ -181,9 +305,13 @@ install_docker() { # 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 + local want="0 2147483647" cur tmp top + # In an unprivileged container (user namespace), the range must stay within the mapped + # groups (usually 0-65535) or the kernel rejects it. + top=$(awk 'NR == 1 { print $1 + $3 - 1 }' /proc/self/gid_map 2>/dev/null || true) + if [ -n "$top" ] && [ "$top" -lt 2147483647 ] 2>/dev/null; then want="0 $top"; fi 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 + if [ "$cur" = "$want" ] || [ "$cur" = "0 2147483647" ]; 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" diff --git a/install.sh b/install.sh index b72950e..79c6ca9 100755 --- a/install.sh +++ b/install.sh @@ -10,10 +10,13 @@ # 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: token $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. +# Where it installs (INSTALL_MODE): +# lxc On a Proxmox VE node: creates (or reuses) a small Debian LXC container, tagged +# netmon-hub, and installs natively inside it. Default on Proxmox nodes, so the +# node itself gets no Docker and no packages. LXC_* settings below. +# docker The app in a container (compose). Default on other 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). +# Default on macOS and inside LXC containers. # 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 @@ -27,6 +30,9 @@ # 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) +# Proxmox (lxc mode): LXC_ID (default: next free), LXC_STORAGE (default: local-lvm, local-zfs +# or the first active), LXC_TEMPLATE_STORAGE (local), LXC_BRIDGE (vmbr0), LXC_IP (dhcp, +# or 192.168.1.50/24 with LXC_GW), LXC_CORES (1), LXC_MEMORY (512), LXC_DISK (4 GB) # # 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). @@ -58,12 +64,14 @@ main() { SUDO=sudo fi + CALLER_MODE=${INSTALL_MODE:-} 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 + if [ "$MODE" = lxc ]; then lxc_install; return; fi step "prerequisites" install_packages @@ -106,14 +114,34 @@ is_lxc() { grep -qa 'container=lxc' /proc/1/environ 2>/dev/null } +is_pve_host() { + [ "$OS" = Linux ] && command -v pct >/dev/null 2>&1 && [ -d "${NETMON_PVE_DIR:-/etc/pve}" ] +} + choose_mode() { MODE=${INSTALL_MODE:-auto} + if is_pve_host; then + # On a Proxmox node only an explicit INSTALL_MODE counts; a mode saved in .env does not. + MODE=${CALLER_MODE:-auto} + [ "$MODE" != auto ] || MODE=lxc + warn_existing_docker_install + fi 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 + case $MODE in docker|native|lxc) ;; *) die "INSTALL_MODE must be docker, native or lxc, not '$MODE'" ;; esac + if [ "$MODE" = lxc ]; then + is_pve_host || die "INSTALL_MODE=lxc only works on a Proxmox VE node (needs pct)" + [ "$(id -u)" = 0 ] || die "on a Proxmox node, run the installer as root" + log "mode: lxc (Proxmox node: the $ROLE goes in its own container, installed natively inside)" + return + fi + if is_pve_host && [ "$MODE" = docker ]; then + log "warning: installing Docker on a Proxmox node changes its firewall and can break guest networking." + log " Leave INSTALL_MODE unset to install in an LXC container instead." + fi 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 @@ -128,6 +156,103 @@ choose_mode() { log "mode: $MODE" } +# An earlier run on this Proxmox node may have installed with Docker. Say how to remove it. +warn_existing_docker_install() { + [ "${CALLER_MODE:-}" != docker ] || return 0 + local found= + [ -f "$INSTALL_DIR/compose.yml" ] && found=1 + command -v docker >/dev/null 2>&1 && docker inspect "$NAME" >/dev/null 2>&1 && found=1 + [ -n "$found" ] || return 0 + log "note: this node has a Docker install of $NAME from an earlier run. To remove it:" + log " cd $INSTALL_DIR && docker compose -f $COMPOSE_FILE down -v --rmi all && cd / && rm -rf $INSTALL_DIR" + log " The README (Proxmox section) shows how to remove Docker from the node." +} + +# ---------- Proxmox: create (or reuse) an LXC container and install inside it ---------- + +lxc_install() { + local tag="netmon-$ROLE" ctname script ip k port=${!PORT_KEY} + if [ "$ROLE" = hub ]; then ctname=netmon-hub; else ctname="netmon-probe-$(hostname -s | tr -c 'a-zA-Z0-9-\n' '-')"; fi + step "proxmox container" + CTID=$(find_ct "$tag") + if [ -n "$CTID" ]; then log "reusing container $CTID (tagged $tag)"; else create_ct "$ctname" "$tag"; fi + pct status "$CTID" | grep -q running || pct start "$CTID" + wait_ct_network + + step "install inside container $CTID" + # This installer re-assembled from its own functions, so nothing is downloaded again. + script=$(mktemp) + { 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 + for k in $KEYS; do + if [ "$k" != INSTALL_MODE ] && [ -n "${!k:-}" ]; then set -- "$@" "$k=${!k}"; fi + done + pct exec "$CTID" -- "$@" bash /root/netmon-install.sh + pct exec "$CTID" -- rm -f /root/netmon-install.sh + + ip=$(pct exec "$CTID" -- hostname -I 2>/dev/null | cut -d' ' -f1) + 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 " 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" + echo " settings: pct exec $CTID -- nano /opt/$NAME/.env (then: pct exec $CTID -- systemctl restart $NAME)" + echo " shell inside: pct enter $CTID" + echo " upgrade: run this installer on the node again (it reuses container $CTID)" + echo " uninstall: pct stop $CTID && pct destroy $CTID" +} + +# The container this installer made before, found by its tag. +find_ct() { + local id + for id in $(pct list 2>/dev/null | awk 'NR > 1 { print $1 }'); do + if pct config "$id" 2>/dev/null | grep -Eq "^tags: (.*[;, ])?$1([;, ]|\$)"; then echo "$id"; return; fi + done +} + +create_ct() { + local ctname=$1 tag=$2 tstore=${LXC_TEMPLATE_STORAGE:-local} storage=${LXC_STORAGE:-} tmpl name + CTID=${LXC_ID:-$(pvesh get /cluster/nextid)} + tmpl=$(pveam list "$tstore" 2>/dev/null | awk '{ print $1 }' | grep -E 'vztmpl/debian-1[23]-standard' | sort -V | tail -1 || true) + if [ -z "$tmpl" ]; then + log "downloading a Debian template to $tstore" + pveam update >/dev/null 2>&1 || true + name=$(pveam available --section system 2>/dev/null | awk '{ print $2 }' | grep -E '^debian-1[23]-standard' | sort -V | tail -1 || true) + [ -n "$name" ] || die "no Debian 12/13 template available from pveam" + pveam download "$tstore" "$name" >/dev/null || die "could not download $name to $tstore (set LXC_TEMPLATE_STORAGE)" + tmpl="$tstore:vztmpl/$name" + fi + if [ -z "$storage" ]; then + local avail + avail=$(pvesm status --content rootdir --enabled 1 2>/dev/null | awk 'NR > 1 && $3 == "active" { print $1 }') + for name in local-lvm local-zfs $avail; do + if echo "$avail" | grep -qx "$name"; then storage=$name; break; fi + done + [ -n "$storage" ] || die "no active storage for containers found; set LXC_STORAGE" + fi + log "creating container $CTID ($ctname) from $tmpl on $storage, bridge ${LXC_BRIDGE:-vmbr0}" + pct create "$CTID" "$tmpl" --hostname "$ctname" --cores "${LXC_CORES:-1}" --memory "${LXC_MEMORY:-512}" --swap 256 \ + --rootfs "$storage:${LXC_DISK:-4}" \ + --net0 "name=eth0,bridge=${LXC_BRIDGE:-vmbr0},ip=${LXC_IP:-dhcp}${LXC_GW:+,gw=$LXC_GW}" \ + --unprivileged 1 --features nesting=1 --onboot 1 --tags "$tag" \ + --description "Network Monitor $ROLE, created by the $NAME installer" >/dev/null || die "pct create failed" +} + +wait_ct_network() { + log "waiting for container $CTID to get network" + local i=0 + while [ "$i" -lt 90 ]; do + if pct exec "$CTID" -- sh -c 'ip -4 route show default | grep -q . && getent hosts deb.debian.org >/dev/null' 2>/dev/null; then + log "container $CTID is online"; return + fi + sleep 1; i=$((i + 1)) + done + die "container $CTID has no network after 90 s (bridge ${LXC_BRIDGE:-vmbr0}, ip ${LXC_IP:-dhcp}); check: pct exec $CTID -- ip addr" +} + 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" @@ -175,9 +300,13 @@ install_docker() { # 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 + local want="0 2147483647" cur tmp top + # In an unprivileged container (user namespace), the range must stay within the mapped + # groups (usually 0-65535) or the kernel rejects it. + top=$(awk 'NR == 1 { print $1 + $3 - 1 }' /proc/self/gid_map 2>/dev/null || true) + if [ -n "$top" ] && [ "$top" -lt 2147483647 ] 2>/dev/null; then want="0 $top"; fi 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 + if [ "$cur" = "$want" ] || [ "$cur" = "0 2147483647" ]; 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" diff --git a/scripts/build-installers.sh b/scripts/build-installers.sh index e70670e..40578bf 100755 --- a/scripts/build-installers.sh +++ b/scripts/build-installers.sh @@ -26,10 +26,13 @@ out=install-probe.sh # Private repo over https: add GIT_TOKEN, read without echoing it: # read -rsp 'Git token: ' GIT_TOKEN && export GIT_TOKEN && curl -fsSL -H "Authorization: token \$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. +# Where it installs (INSTALL_MODE): +# lxc On a Proxmox VE node: creates (or reuses) a small Debian LXC container, tagged +# netmon-probe, on the node's bridge, and installs natively inside it. Default on +# Proxmox nodes, so the node itself gets no Docker and no packages. +# docker The probe in a container with host networking. Default on other 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). +# Default on macOS and inside LXC containers. # 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: @@ -45,6 +48,8 @@ out=install-probe.sh # 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) +# Proxmox (lxc mode): LXC_ID, LXC_STORAGE, LXC_TEMPLATE_STORAGE, LXC_BRIDGE, LXC_IP, LXC_GW, +# LXC_CORES, LXC_MEMORY, LXC_DISK (see install.sh) # # Everything is inside main(), so a partial download runs nothing. bash 3.2 compatible (macOS). diff --git a/tests/test_installers.py b/tests/test_installers.py index bb6d13e..c485365 100644 --- a/tests/test_installers.py +++ b/tests/test_installers.py @@ -58,3 +58,55 @@ def test_choose_mode(tmp_path): 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 + + +def test_proxmox_node_creates_container_and_installs_inside(tmp_path): + """On a Proxmox node (pct present) the installer makes an LXC and runs itself inside it.""" + fake = tmp_path / "bin" + fake.mkdir() + log = tmp_path / "calls.log" + pushed = tmp_path / "pushed.sh" + + def stub(name, body): + (fake / name).write_text(f'#!/bin/bash\necho "{name} $*" >> {log}\n{body}') + (fake / name).chmod(0o755) + stub("pct", f'''case $1 in + list) printf 'VMID Status Lock Name\\n100 running other\\n'; [ -f {pushed}.created ] && echo "105 running netmon-hub" ; true ;; + create) touch {pushed}.created ;; + config) [ "$2" = 100 ] && echo "tags: web" ; [ "$2" = 105 ] && printf 'hostname: netmon-hub\\ntags: netmon-hub\\n' ; true ;; + status) echo "status: stopped" ;; + push) cp "$3" {pushed} ;; + exec) shift 3; [ "$1" = hostname ] && echo "192.168.68.50 " ; true ;; +esac''') + stub("pvesh", 'echo 105') + stub("pveam", '[ "$1" = available ] && printf "system debian-12-standard_12.7-1_amd64.tar.zst\\nsystem debian-12-standard_12.12-1_amd64.tar.zst\\n"; true') + stub("pvesm", 'printf "Name Type Status Total\\nlocal dir active 1\\nlocal-lvm lvmthin active 2\\n"') + stub("sleep", "true") + pve = tmp_path / "pve" + pve.mkdir() + env = {"PATH": f"{fake}:{os.environ['PATH']}", "NETMON_PVE_DIR": str(pve), "INSTALL_DIR": str(tmp_path / "opt"), "HOST_PORT": "8000"} + r = subprocess.run(["bash", "install.sh"], cwd=ROOT, capture_output=True, text=True, env={**os.environ, **env}, timeout=60, + input="") + if os.geteuid() != 0: + assert r.returncode != 0 and "run the installer as root" in r.stderr + return + assert r.returncode == 0, r.stdout + r.stderr + calls = log.read_text() + assert "pveam download local debian-12-standard_12.12-1_amd64.tar.zst" in calls + create = next(line for line in calls.splitlines() if line.startswith("pct create")) + for part in ("pct create 105 local:vztmpl/debian-12-standard_12.12-1_amd64.tar.zst", "--hostname netmon-hub", + "--rootfs local-lvm:4", "bridge=vmbr0,ip=dhcp", "--unprivileged 1", "--features nesting=1", + "--onboot 1", "--tags netmon-hub"): + 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 + # 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 "$@"') + assert subprocess.run(["bash", "-n", str(pushed)]).returncode == 0 + # A second run finds the tagged container instead of creating another. + log.write_text("") + r = subprocess.run(["bash", "install.sh"], cwd=ROOT, capture_output=True, text=True, env={**os.environ, **env}, timeout=60) + assert r.returncode == 0 and "reusing container 105" in r.stdout and "pct create" not in log.read_text()