network-monitor/tests/test_installers.py
neil a17f2b502c 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 <noreply@anthropic.com>
2026-11-04 18:28:21 -08:00

112 lines
6.3 KiB
Python

"""The installers: generated probe installer in sync, and .env handling per mode."""
import os
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
def bash(script: str, **env) -> subprocess.CompletedProcess:
return subprocess.run(["bash", "-c", script], capture_output=True, text=True, cwd=ROOT,
env={**os.environ, **env}, timeout=30)
def test_probe_installer_is_generated_from_install_sh():
r = bash("bash scripts/build-installers.sh --check")
assert r.returncode == 0, r.stderr
for f in ("install.sh", "install-probe.sh", "native/setup.sh", "native/update.sh", "native/run.sh", "native/lib.sh"):
assert bash(f"bash -n {f}").returncode == 0, f
# Load the installer's functions without running main (its last line).
FUNCS = "source <(sed '$d' \"$INSTALLER\"); set -euo pipefail; OS=Linux; SUDO=; "
def test_write_env_new_and_rerun(tmp_path):
d = tmp_path / "opt"
d.mkdir()
(d / ".env.probe.example").write_text((ROOT / ".env.probe.example").read_text())
setup = FUNCS + f'''NETMON_ROLE=probe; ROLE=probe; INSTALL_DIR={d}; ENV_EXAMPLE=.env.probe.example; MODE=native
KEYS="REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY INSTALL_MODE HUB_URL PROBE_TOKEN PROBE_PORT ADVERTISE_ADDR"
install() {{ cp "${{@: -2:1}}" "${{@: -1}}"; }} # no chown in tests
'''
r = bash(setup + 'PASSED=" "; REPO_URL=git://x/r.git; REPO_REF=main; HUB_URL=http://hub:8000; PROBE_TOKEN=abc; PROBE_PORT=8765; INSTALL_MODE=native; write_env',
INSTALLER="install-probe.sh")
assert r.returncode == 0, r.stderr
env = (d / ".env").read_text()
for line in ("REPO_URL=git://x/r.git", "HUB_URL=http://hub:8000", "PROBE_TOKEN=abc", "INSTALL_MODE=native", "PROBE_PORT=8765"):
assert line + "\n" in env
# Re-run passing one key: the rest is kept, comments too.
r = bash(setup + 'PASSED=" ADVERTISE_ADDR "; ADVERTISE_ADDR=10.0.0.9; write_env', INSTALLER="install-probe.sh")
assert r.returncode == 0, r.stderr
env2 = (d / ".env").read_text()
assert "ADVERTISE_ADDR=10.0.0.9\n" in env2 and "PROBE_TOKEN=abc\n" in env2 and "# The hub this probe reports to" in env2
# And load_existing_env reads the saved mode back.
r = bash(setup + 'INSTALL_MODE=; HUB_URL=; load_existing_env >/dev/null; echo "$INSTALL_MODE $HUB_URL"', INSTALLER="install-probe.sh")
assert r.stdout.strip() == "native http://hub:8000", r.stderr
def test_choose_mode(tmp_path):
base = FUNCS + 'KEYS="INSTALL_MODE"; PASSED=" "; log() { :; }; is_lxc() { return 1; }; '
run = lambda s: bash(base + s, INSTALLER="install.sh")
assert run('INSTALL_MODE=; choose_mode; echo $MODE').stdout.strip() == "docker"
assert run('is_lxc() { return 0; }; id() { echo 0; }; INSTALL_MODE=; choose_mode; echo $MODE').stdout.strip() == "native"
assert run('OS=Darwin; id() { echo 501; }; INSTALL_MODE=; choose_mode; echo $MODE').stdout.strip() == "native"
r = run('OS=Darwin; id() { echo 501; }; INSTALL_MODE=docker; choose_mode')
assert r.returncode != 0 and "INSTALL_MODE=native" in r.stderr
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()