Files
felhom.eu/scripts/test_hostinstall.py
T

1043 lines
50 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Behaviour tests for felhom-host-install.sh — the paths that need no Proxmox host.
HOW IT RUNS ANYWHERE. The installer runs as root on a Proxmox host; the CI runner is Alpine + BusyBox +
bash + python3 + git. So each test lifts the functions it needs out of felhom-host-install.sh VERBATIM
(by name, `^name() {` to the first `^}`), runs them under bash in a temp directory, and replaces the
host commands (`systemctl`, `chown`, …) with PATH stubs that record what they were asked. Paths the
functions act on are variables the test points into the temp directory. Nothing touches the real host.
Where behaviour cannot be isolated, a STATIC test checks the wiring (the function is CALLED, from the
right place) — a helper defined and never called is the seam-built-never-wired shape.
Rows: R-275, R-276, R-881 (uninstall residue); R-306 (--preflight-only writes no state); R-130 (lvm minimum wording); R-180 (archive storage outside the ACL set); R-179 (NAS units); R-310 (golden refusal wording, the uninstall's terminal); R-274 (local golden reuse).
Run: python3 scripts/test_hostinstall.py
"""
import json
import os
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import time
HERE = os.path.dirname(os.path.abspath(__file__))
SCRIPT = os.path.join(HERE, "felhom-host-install.sh")
AGENT_OS_APPLY = os.path.join(os.path.dirname(os.path.dirname(HERE)), "felhom-agent", "configs", "felhom-os-apply")
# The root-owned files the agent's config bundle installs (felhom-agent configs/felhom-os-apply
# BUNDLE_FILES, agent v0.147.0). Frozen here so CI (which has no sibling checkout) still checks it;
# where the sibling IS present, test_bundle_list_is_current fails when the bundle gains a file.
BUNDLE_DESTS = [
"/usr/local/sbin/felhom-mkfs-guarded",
"/usr/local/sbin/felhom-selfupdate-guarded",
"/usr/local/sbin/felhom-pbs-apply",
"/usr/local/sbin/felhom-backup-target-apply",
"/usr/local/sbin/felhom-vzdump-partial-clean", # agent v0.156.1 (R-1006)
"/usr/local/sbin/felhom-thin-check", # agent v0.159.0 (R-1012)
"/usr/local/sbin/felhom-internal-place", # agent v0.158.0 (felhom.eu `16` §5)
"/usr/local/sbin/felhom-os-apply",
"/usr/local/sbin/felhom-crash-guard",
"/usr/local/sbin/felhom-priv-apply",
"/var/lib/vz/snippets/felhom-guest-hook.sh",
"/usr/local/sbin/felhom-shared-parent.sh",
"/etc/systemd/system/felhom-shared-parent.service",
"/etc/systemd/system/felhom-crash-guard.service",
"/etc/systemd/system/felhom-crash-guard-check.service",
"/etc/systemd/system/felhom-crash-guard-check.timer",
"/etc/felhom/crash-guard.conf",
"/etc/grub.d/01_felhom_oneshot",
"/etc/grub.d/42_felhom_oneshot",
"/etc/systemd/system/felhom-agent.service",
"/etc/systemd/system/felhom-agent-rollback.service",
"/etc/systemd/system/felhom-agent.service.d/felhom-agent-limits.conf",
"/usr/local/sbin/felhom-mgmt-watchdog",
"/etc/tmpfiles.d/felhom-privsep.conf",
"/etc/systemd/system/felhom-mgmt-watchdog.service",
"/etc/systemd/system/felhom-mgmt-watchdog.timer",
"/etc/systemd/system/felhom-sshd.service",
"/etc/felhom-oob.nft",
"/etc/systemd/system/felhom-oob-nft.service",
"/etc/ssh/sshd_config.d/10-felhom-root-key-only.conf", # R-982, operator ruling D4 (2026-10-22)
"/etc/sudoers.d/felhom-op",
"/etc/sudoers.d/felhom-agent",
]
SRC = open(SCRIPT, encoding="utf-8").read()
def func(name):
m = re.search(r"^%s\(\) \{[^\n]*\n.*?^\}\n" % re.escape(name), SRC, re.S | re.M)
if not m:
raise AssertionError("%s() not found in felhom-host-install.sh" % name)
return m.group(0)
def one_liners():
"""The log_* helpers and die (one-line definitions)."""
out = [l for l in SRC.splitlines() if re.match(r"^(log_\w+|die)\(\)\s+\{.*\}\s*$", l)]
if len(out) < 8:
raise AssertionError("log helpers not found (%d)" % len(out))
return "RED=; GREEN=; YELLOW=; BLUE=; CYAN=; NC=\n" + "\n".join(out) + "\n"
def section(start_re, end_re):
s = re.search(start_re, SRC, re.M)
e = re.search(end_re, SRC, re.M)
if not s or not e or e.start() <= s.start():
raise AssertionError("section %r..%r not found" % (start_re, end_re))
return SRC[s.start():e.start()]
class Sandbox:
"""A temp dir with a stub bin/ first on PATH. Each stub appends its argv to calls.log."""
def __init__(self):
self.root = tempfile.mkdtemp(prefix="hostinstall-test-")
self.bin = os.path.join(self.root, "bin")
os.mkdir(self.bin)
self.calls = os.path.join(self.root, "calls.log")
open(self.calls, "w").close()
def stub(self, name, body="exit 0"):
p = os.path.join(self.bin, name)
with open(p, "w") as f:
f.write('#!/bin/sh\nprintf "%%s\\n" "%s $*" >> "%s"\n%s\n' % (name, self.calls, body))
os.chmod(p, 0o755)
def path(self, *parts):
return os.path.join(self.root, *parts)
def logged(self):
return open(self.calls).read()
def run(self, script):
env = dict(os.environ)
env["PATH"] = self.bin + os.pathsep + env.get("PATH", "")
env["SB"] = self.root
p = subprocess.run(["bash", "-c", script], capture_output=True, text=True, env=env)
return p.returncode, p.stdout + p.stderr
def close(self):
shutil.rmtree(self.root, ignore_errors=True)
def prelude(dry=False):
return one_liners() + ("DRY_RUN=%s\n" % ("true" if dry else "false")) + func("run")
# ── R-275: the agent config and every copy of it ─────────────────────────────────────────────────
# The names measured on demo-hp 2026-08-09; none but the last matched the old `.bak*` glob's intent,
# and the old glob missed even that one's siblings.
DEMO_HP_COPIES = ["agent.json.campaign8-before", "agent.json.campaign9-before", "agent.json.campaign9-prev",
"agent.json.pre-e-target-move", "agent.json.pre-prunegate.bak"]
def test_purge_default_dir_removes_every_copy():
sb = Sandbox()
try:
d = sb.path("etc-felhom-agent")
os.mkdir(d)
for n in ["agent.json", ".hidden-copy"] + DEMO_HP_COPIES:
open(os.path.join(d, n), "w").write("secret")
rc, out = sb.run(prelude() + func("_purge_agent_config") +
'AGENT_CFG_DIR_DEFAULT="$SB/etc-felhom-agent"\n_purge_agent_config "$SB/etc-felhom-agent/agent.json"\n')
assert rc == 0, out
left = os.listdir(d) if os.path.exists(d) else []
assert not os.path.exists(d), "agent config dir survived the uninstall with: %s" % sorted(left)
finally:
sb.close()
def test_purge_custom_path_keeps_foreign_files():
sb = Sandbox()
try:
d = sb.path("shared")
os.mkdir(d)
for n in ["agent.json", "other.conf"] + DEMO_HP_COPIES:
open(os.path.join(d, n), "w").write("x")
rc, out = sb.run(prelude() + func("_purge_agent_config") +
'AGENT_CFG_DIR_DEFAULT="/etc/felhom-agent"\n_purge_agent_config "$SB/shared/agent.json"\n')
assert rc == 0, out
left = sorted(os.listdir(d))
assert left == ["other.conf"], "custom-path purge left/removed the wrong files: %s" % left
finally:
sb.close()
def test_purge_dry_run_touches_nothing():
sb = Sandbox()
try:
d = sb.path("etc-felhom-agent")
os.mkdir(d)
open(os.path.join(d, "agent.json"), "w").write("x")
rc, out = sb.run(prelude(dry=True) + func("_purge_agent_config") +
'AGENT_CFG_DIR_DEFAULT="$SB/etc-felhom-agent"\n_purge_agent_config "$SB/etc-felhom-agent/agent.json"\n')
assert rc == 0, out
assert os.path.exists(os.path.join(d, "agent.json")), "dry-run removed the config"
assert "rm -rf" in out, "dry-run did not print the removal: %s" % out
finally:
sb.close()
def test_seal_makes_old_copies_root_only():
sb = Sandbox()
try:
sb.stub("chown")
d = sb.path("etc-felhom-agent")
os.mkdir(d)
for n in DEMO_HP_COPIES:
p = os.path.join(d, n)
open(p, "w").write("x")
os.chmod(p, 0o644)
rc, out = sb.run(prelude() + func("_seal_old_agent_config") + '_seal_old_agent_config "$SB/etc-felhom-agent"\n')
assert rc == 0, out
log = sb.logged()
for n in DEMO_HP_COPIES:
p = os.path.join(d, n)
assert "chown root:root %s" % p in log, "%s not given to root: %s" % (n, log)
assert stat.S_IMODE(os.stat(p).st_mode) == 0o600, "%s mode %o" % (n, stat.S_IMODE(os.stat(p).st_mode))
assert os.path.exists(p), "seal DELETED %s (it may be an operator's backup)" % n
assert "now root-only" in out
finally:
sb.close()
def test_seal_is_called_when_the_user_is_created():
body = func("step_agent_install")
m = re.search(r'useradd --system[^\n]*"\$AGENT_USER"\n(.*?)\n\s*fi\n', body, re.S)
assert m and '_seal_old_agent_config "$AGENT_CFG_DIR_DEFAULT"' in m.group(1), \
"_seal_old_agent_config is not called right after the service user is created"
def test_uninstall_wiring():
body = func("run_uninstall")
stop = body.find("run systemctl stop felhom-agent")
purge = body.find('_purge_agent_config "$agent_cfg"')
wg = body.find("_teardown_wg_tunnel")
assert purge > 0, "run_uninstall does not call _purge_agent_config"
assert wg > 0, "run_uninstall does not call _teardown_wg_tunnel (R-276)"
assert stop > 0 and stop < wg, "the WireGuard teardown must run after the agent is stopped"
assert '"${agent_cfg}".bak*' not in body, "the old .bak* glob is back"
assert re.search(r'for bak in "\$\{AGENT_SUDOERS\}"\.\*', body), "sudoers copies are not removed"
# ── R-276: the WireGuard tunnel ──────────────────────────────────────────────────────────────────
def _wg_sandbox(active, enabled, conf, sticky=False):
sb = Sandbox()
# systemctl stub: is-active/is-enabled read flag files; disable --now clears them (unless sticky).
sb.stub("systemctl", r'''
case "$1" in
is-active) [ -e "$SB/wg.active" ]; exit $? ;;
is-enabled) [ -e "$SB/wg.enabled" ]; exit $? ;;
disable) rm -f "$SB/wg.enabled"; %s exit 0 ;;
esac
exit 0''' % ("" if sticky else 'rm -f "$SB/wg.active";'))
if active:
open(sb.path("wg.active"), "w").close()
if enabled:
open(sb.path("wg.enabled"), "w").close()
if conf:
open(sb.path("wg-felhom.conf"), "w").write("[Interface]\nPrivateKey = x\n")
return sb
WG_RUN = ('WG_UNIT="wg-quick@wg-felhom"; WG_CONF="$SB/wg-felhom.conf"; _WG_TEARDOWN_NOTE=""; _WG_PRESENT=false\n'
'_teardown_wg_tunnel\necho "PRESENT=$_WG_PRESENT NOTE=$_WG_TEARDOWN_NOTE"\n')
def test_wg_teardown_brings_the_tunnel_down():
sb = _wg_sandbox(active=True, enabled=True, conf=True)
try:
rc, out = sb.run(prelude() + func("_teardown_wg_tunnel") + WG_RUN)
assert rc == 0, out
assert "systemctl disable --now wg-quick@wg-felhom" in sb.logged(), sb.logged()
assert not os.path.exists(sb.path("wg.active")), "tunnel still active"
assert not os.path.exists(sb.path("wg-felhom.conf")), "wg-felhom.conf survived"
assert "PRESENT=true NOTE=\n" in out + "\n", out
assert "is down" in out
finally:
sb.close()
def test_wg_still_active_is_reported_not_claimed_down():
sb = _wg_sandbox(active=True, enabled=True, conf=True, sticky=True)
try:
rc, out = sb.run(prelude() + func("_teardown_wg_tunnel") + WG_RUN)
assert rc == 0, out
assert "STILL active" in out and "is down" not in out, out
assert "NOTE=wg-quick@wg-felhom is STILL active" in out, out
finally:
sb.close()
def test_wg_absent_is_a_noop():
sb = _wg_sandbox(active=False, enabled=False, conf=False)
try:
rc, out = sb.run(prelude() + func("_teardown_wg_tunnel") + WG_RUN)
assert rc == 0, out
assert "disable" not in sb.logged(), sb.logged()
assert "PRESENT=false" in out, out
finally:
sb.close()
def test_wg_dry_run_changes_nothing():
sb = _wg_sandbox(active=True, enabled=True, conf=True)
try:
rc, out = sb.run(prelude(dry=True) + func("_teardown_wg_tunnel") + WG_RUN)
assert rc == 0, out
assert os.path.exists(sb.path("wg-felhom.conf")) and os.path.exists(sb.path("wg.active"))
assert "disable --now wg-quick@wg-felhom" in out, out
finally:
sb.close()
def test_statement_names_the_tunnel_and_the_peer():
sb = Sandbox()
try:
sb.stub("pvesm", "exit 1")
rc, out = sb.run(prelude() + func("_uninstall_statement") +
'vmid=9201; pool_removed=false; _busy_mounts=(); _had_break_glass=false; REMOVE_GOLDEN=false\n'
'PVE_POOL=felhom; ISLAND_BRIDGE=vmbr9; WG_UNIT="wg-quick@wg-felhom"; WG_CONF=/etc/wireguard/wg-felhom.conf\n'
'_WG_PRESENT=true; _WG_TEARDOWN_NOTE=""\n_uninstall_statement full\n')
assert rc == 0, out
wiped, kept = out.split("KEPT", 1)
assert "WireGuard tunnel to the Felhom off-site endpoint" in wiped, out
assert "WireGuard PEER" in kept, out
assert "priv-apply" in wiped, out
finally:
sb.close()
# ── R-881: every file the config bundle installs is removed by the uninstall ─────────────────────
def test_uninstall_removes_every_bundle_file():
usect = section(r"^_guest_drive_note\(\)", r"^# run_adopt_pool")
# the uninstall names some paths through these variables — expand them before searching.
for var, val in [("AGENT_UNIT", "/etc/systemd/system/felhom-agent.service"),
("AGENT_SUDOERS", "/etc/sudoers.d/felhom-agent"),
("AGENT_BIN", "/usr/local/bin/felhom-agent")]:
usect = usect.replace("${%s}" % var, val).replace("$%s" % var, val)
missing = [p for p in BUNDLE_DESTS if p not in usect]
assert not missing, "the uninstall does not remove bundle file(s): %s" % missing
def test_bundle_list_is_current():
if not os.path.exists(AGENT_OS_APPLY):
print(" note: %s absent (CI) — the frozen list is checked, not its currency" % AGENT_OS_APPLY)
return
text = open(AGENT_OS_APPLY, encoding="utf-8").read()
m = re.search(r"^BUNDLE_FILES = \[(.*?)^\]", text, re.S | re.M)
assert m, "BUNDLE_FILES not found in felhom-os-apply"
dests = re.findall(r'^\s*\("(/[^"]+)"', m.group(1), re.M)
assert len(dests) >= 20, "parsed only %d bundle entries" % len(dests)
new = sorted(set(dests) - set(BUNDLE_DESTS))
assert not new, "the agent bundle installs file(s) this test (and maybe the uninstall) does not know: %s" % new
# ── R-306: --preflight-only writes no state ──────────────────────────────────────────────────────
def _state_run(sb, preflight_only, dry=False):
return sb.run(prelude(dry=dry) + func("_state_mark") + func("_state_put") + func("_state_get") +
'PREFLIGHT_ONLY=%s\nSTATE_DIR="$SB/state"; STATE_FILE="$SB/state/state.json"\n'
'_state_put dnsmasq_preexisting yes\n_state_mark preflight\necho "GOT=$(_state_get dnsmasq_preexisting)"\n'
% ("true" if preflight_only else "false"))
def test_preflight_only_writes_no_state():
sb = Sandbox()
try:
rc, out = _state_run(sb, preflight_only=True)
assert rc == 0, out
assert not os.path.exists(sb.path("state", "state.json")), \
"--preflight-only wrote state.json: %s" % open(sb.path("state", "state.json")).read()
assert "GOT=\n" in out + "\n", out
finally:
sb.close()
def test_install_preflight_does_write_state():
# the control: the same helpers DO write on a real install, or the test above proves nothing.
sb = Sandbox()
try:
rc, out = _state_run(sb, preflight_only=False)
assert rc == 0, out
assert "GOT=yes" in out, out
assert '"preflight"' in open(sb.path("state", "state.json")).read()
finally:
sb.close()
def test_state_json_has_no_other_writer():
# every write must go through the two guarded helpers; a direct write would bypass the guard.
bad = [l.strip() for l in SRC.splitlines()
if re.search(r'>\s*"?\$STATE_FILE|json\.dump\(d,open\(f', l)
and not re.match(r"\s*STATE_FILE=\"\$STATE_FILE\" python3 -c", l)]
assert not bad, "state.json written outside _state_mark/_state_put: %s" % bad
body = func("step_preflight")
assert "_state_put dnsmasq_preexisting" in body, "the ownership record no longer goes through _state_put"
# ── R-130: the local-lvm minimum says what it does (it warns; the install continues) ────────────
def test_lvm_minimum_is_named_as_what_it_does():
assert not re.search(r"HARD_MIN_LVM|hard min", SRC), "a 'hard min' that only warns is back"
body = func("step_preflight")
m = re.search(r'^.*RECOMMENDED_MIN_LVM_GIB.*$', body, re.M)
assert m and "log_warn" in m.group(0) and "die" not in m.group(0), "the lvm check is not a warning: %s" % (m and m.group(0))
assert "recommended" in m.group(0) and "continues" in m.group(0), m.group(0)
# ── R-180: the archive storage must be one the agent's token is granted on ─────────────────────
def _granted(storages, archive, target="felhom-backup"):
sb = Sandbox()
try:
rc, out = sb.run(func("_archive_storage_granted") +
'PVE_STORAGES=(%s); ARCHIVE_STORAGE="%s"; BACKUP_TARGET_ID="%s"\n'
'if _archive_storage_granted; then echo GRANTED; else echo REFUSED; fi\n'
% (storages, archive, target))
assert rc == 0, out
return out.strip()
finally:
sb.close()
def test_archive_storage_in_the_acl_set_is_granted():
assert _granted("local local-lvm felhom-pbs", "local") == "GRANTED", "archive storage case ('local local-lvm felhom-pbs', 'local') -> %s, want GRANTED" % _granted("local local-lvm felhom-pbs", "local")
assert _granted("local nvme-scratch", "nvme-scratch") == "GRANTED", "archive storage case ('local nvme-scratch', 'nvme-scratch') -> %s, want GRANTED" % _granted("local nvme-scratch", "nvme-scratch") # --acl-storages adds it
def test_archive_storage_outside_the_acl_set_is_refused():
# the demo-hp 2026-08-03 shape with a storage that is not the backup target
assert _granted("local local-lvm felhom-pbs", "nvme-scratch") == "REFUSED", "archive storage case ('local local-lvm felhom-pbs', 'nvme-scratch') -> %s, want REFUSED" % _granted("local local-lvm felhom-pbs", "nvme-scratch")
assert _granted("local local-lvm felhom-pbs", "local-lvm2") == "REFUSED", "archive storage case ('local local-lvm felhom-pbs', 'local-lvm2') -> %s, want REFUSED" % _granted("local local-lvm felhom-pbs", "local-lvm2") # no prefix match
assert _granted("local local-lvm felhom-pbs", "felhom-backup", target="") == "REFUSED", "archive storage case ('local local-lvm felhom-pbs', 'felhom-backup', target='') -> %s, want REFUSED" % _granted("local local-lvm felhom-pbs", "felhom-backup", target="")
def test_archive_storage_on_the_backup_target_is_granted_in_step_6():
assert _granted("local local-lvm felhom-pbs", "felhom-backup") == "GRANTED", "archive storage case ('local local-lvm felhom-pbs', 'felhom-backup') -> %s, want GRANTED" % _granted("local local-lvm felhom-pbs", "felhom-backup")
def test_archive_storage_check_is_wired_into_preflight():
body = func("step_preflight")
m = re.search(r"archive storage '\$ARCHIVE_STORAGE' present.*?_archive_storage_granted[^\n]*\n[^\n]*\|\| die", body, re.S)
assert m, "step_preflight does not refuse when _archive_storage_granted fails"
# and before anything is minted: the call sits in step_preflight, which runs before step_token.
pre = [m.start() for m in re.finditer(r"^\s*step_preflight\s*$", SRC, re.M)]
tok = re.search(r"^step_token\s*$", SRC, re.M)
assert pre and tok and max(pre) < tok.start(), "preflight no longer runs before the token step"
# ── R-179: the NAS network-storage units ─────────────────────────────────────────────────────────
AGENT_NETMOUNT = os.path.join(os.path.dirname(os.path.dirname(HERE)), "felhom-agent", "internal", "storage", "netmount.go")
NET_MARK = "# Managed by felhom-agent (network storage) — do not edit by hand.\n"
SHARE = r"mnt-felhom\x2ddrives-Felhom\x2dShare"
NET_SYSTEMCTL = """
for u in "$@"; do last="$u"; done
case "$1" in
is-active) [ -e "$SB/active/$last" ]; exit $? ;;
disable) [ -e "$SB/sticky/$last" ] || rm -f "$SB/active/$last"; exit 0 ;;
esac
exit 0"""
def _net_sandbox(sticky=()):
sb = Sandbox()
os.mkdir(sb.path("units")); os.mkdir(sb.path("active")); os.mkdir(sb.path("sticky"))
sb.stub("systemctl", NET_SYSTEMCTL)
units = {SHARE + ".automount": NET_MARK + "[Automount]\n",
SHARE + ".mount": NET_MARK + "[Mount]\n",
r"mnt-felhom\x2ddrives-disk1.mount": "# Managed by felhom-agent — do not edit by hand.\n[Mount]\n",
"mnt-other.mount": "[Mount]\nWhere=/mnt/other\n"}
for n, c in units.items():
open(sb.path("units", n), "w").write(c)
open(sb.path("active", SHARE + ".mount"), "w").close()
for n in sticky:
open(sb.path("sticky", n), "w").close()
return sb
NET_RUN = ('NET_UNIT_DIR="$SB/units"; NET_UNIT_MARKER="Managed by felhom-agent (network storage)"\n'
'_NET_UNITS_REMOVED=(); _NET_UNITS_BUSY=()\n_remove_network_storage_units\n'
'echo "REMOVED=${#_NET_UNITS_REMOVED[@]} BUSY=${_NET_UNITS_BUSY[*]}"\n')
def test_net_units_removed_and_only_ours():
sb = _net_sandbox()
try:
rc, out = sb.run(prelude() + func("_remove_network_storage_units") + NET_RUN)
assert rc == 0, out
left = sorted(os.listdir(sb.path("units")))
assert left == sorted([r"mnt-felhom\x2ddrives-disk1.mount", "mnt-other.mount"]), \
"wrong units left after the uninstall: %s" % left
log = sb.logged()
a = log.find("disable --now -- %s.automount" % SHARE)
m = log.find("disable --now -- %s.mount" % SHARE)
assert a >= 0 and m >= 0 and a < m, "automount must be stopped before its mount:\n%s" % log
assert "disk1" not in log and "mnt-other" not in log, "touched a unit that is not a network share:\n%s" % log
assert "REMOVED=2 BUSY=" in out, out
finally:
sb.close()
def test_net_units_busy_share_is_not_forced():
sb = _net_sandbox(sticky=(SHARE + ".mount",))
try:
rc, out = sb.run(prelude() + func("_remove_network_storage_units") + NET_RUN)
assert rc == 0, out
assert os.path.exists(sb.path("units", SHARE + ".mount")), "a busy share's unit was removed"
assert not os.path.exists(sb.path("units", SHARE + ".automount"))
assert "BUSY=%s.mount" % SHARE in out and "NOT forcing" in out, out
assert "umount" not in sb.logged(), sb.logged()
finally:
sb.close()
def test_net_units_dry_run_changes_nothing():
sb = _net_sandbox()
try:
rc, out = sb.run(prelude(dry=True) + func("_remove_network_storage_units") + NET_RUN)
assert rc == 0, out
assert len(os.listdir(sb.path("units"))) == 4, os.listdir(sb.path("units"))
assert "disable" not in sb.logged(), sb.logged()
finally:
sb.close()
def test_net_units_wired_before_the_umount_loop():
body = func("run_uninstall")
call = body.find("_remove_network_storage_units")
loop = body.find("findmnt -rn -o TARGET")
assert call > 0, "run_uninstall does not call _remove_network_storage_units (R-179)"
assert call < loop, "the share units must be stopped before the drive umount loop"
def test_net_unit_marker_matches_the_agent():
m = re.search(r'^NET_UNIT_MARKER="([^"]+)"', SRC, re.M)
assert m, "NET_UNIT_MARKER not found"
if not os.path.exists(AGENT_NETMOUNT):
print(" note: %s absent (CI) — marker currency not checked" % AGENT_NETMOUNT)
return
a = re.search(r'netUnitMarker\s*=\s*"([^"]+)"', open(AGENT_NETMOUNT, encoding="utf-8").read())
assert a and a.group(1) == m.group(1), "installer marker %r != agent netUnitMarker %r" % (m.group(1), a and a.group(1))
# ── R-310: the golden refusal names the vouched version once; no terminal is a refusal, in words ──
GOLDEN_RUN = """
golden_local_matches_manifest() { GOLDEN_CHECK_WHY="%s"; return 1; }
resolve_artifacts() { :; }
_state_mark() { :; }
GOLDEN_VOLID="local:backup/vzdump-lxc-9100-2026_08_03-07_33_00.tar.zst"; GOLDEN_VOLID_EXPLICIT=true
FORCE_GITEA_GOLDEN=false; ART_GOLDEN_VER="0.213.0"
step_golden
echo REACHED
"""
def _golden_refusal(why):
sb = Sandbox()
try:
rc, out = sb.run(prelude() + func("step_golden") + GOLDEN_RUN % why)
assert rc != 0 and "REACHED" not in out and "refusing the golden you named" in out, out
return out
finally:
sb.close()
def test_golden_refusal_names_the_vouched_version_once():
out = _golden_refusal("it is controller 0.192.0, but the vouched golden is 0.213.0")
assert out.count("0.213.0") == 1, "the vouched version is stated %d times:\n%s" % (out.count("0.213.0"), out)
def test_golden_refusal_still_names_the_version_when_the_reason_does_not():
out = _golden_refusal("the archive could not be resolved to a file on disk")
assert "The vouched golden is 0.213.0." in out, out
def _tty_run(with_tty):
import fcntl
import termios
script = prelude() + func("_require_tty") + '_require_tty "the typed vmid confirmation"\necho PASSED\n'
if not with_tty:
p = subprocess.run(["bash", "-c", script], capture_output=True, text=True, stdin=subprocess.DEVNULL,
start_new_session=True)
return p.returncode, p.stdout + p.stderr
import pty
master, slave = pty.openpty()
def ctty():
os.setsid()
fcntl.ioctl(slave, termios.TIOCSCTTY, 0)
try:
p = subprocess.run(["bash", "-c", script], capture_output=True, text=True, stdin=slave, preexec_fn=ctty)
return p.returncode, p.stdout + p.stderr
finally:
os.close(master); os.close(slave)
def test_require_tty_refuses_in_words_without_a_terminal():
rc, out = _tty_run(False)
assert rc != 0 and "PASSED" not in out, out
assert "needs a terminal" in out and "nothing was destroyed" in out, out
assert "No such device" not in out, out
def test_require_tty_passes_with_a_terminal():
# the control: with a controlling terminal the guard lets the prompt happen.
rc, out = _tty_run(True)
assert rc == 0 and "PASSED" in out, out
def test_require_tty_guards_the_uninstall_prompt():
body = func("run_uninstall")
g = body.find('_require_tty "the typed vmid confirmation"')
r = body.find('read -rp "Type the vmid')
assert g > 0 and g < r, "the vmid confirmation is not guarded by _require_tty"
# ── R-274: a local golden is checked against the manifest, and the disclosure says it is reused ──
def test_local_golden_is_checked_before_use():
body = func("step_golden")
chk = body.find('golden_local_matches_manifest "$GOLDEN_VOLID"')
use = body.find('log_skip " using local golden')
assert 0 < chk < use, "step_golden adopts a local golden without checking it against the manifest"
g = func("golden_local_matches_manifest")
assert "ART_GOLDEN_SHA" in g and "ART_GOLDEN_VER" in g, "the check no longer compares sha256 and version"
def test_byo_disclosure_names_the_golden_reuse():
body = func("_byo_disclosure_ack")
assert re.search(r"reuse:.*golden.*vouched", body, re.S), "the BYO disclosure does not say a local golden is reused (R-274)"
# ── felhom.eu architecture/16 §5, §7 (installer 1.33.0): the data volume by the ruled table; the internal place ───
def test_datavol_follows_the_ruled_table():
sb = Sandbox()
try:
cases = [(53, 50), (113, 50), (299, 50), (300, 100), (349, 100), (799, 100), (800, 130), (1720, 130)]
script = func("felhom_datavol_gib") + "".join('echo "%d $(felhom_datavol_gib %d)"\n' % (p, p) for p, _ in cases)
rc, out = sb.run(script)
assert rc == 0, out
got = dict(tuple(map(int, l.split())) for l in out.split("\n") if l.strip())
assert got == dict(cases), got
finally:
sb.close()
def test_step_grows_sizes_the_data_volume_from_the_pool():
sb = Sandbox()
try:
sb.stub("lvs", 'echo " 349.00"')
rc, out = sb.run(prelude() + func("felhom_datavol_gib") + "_state_mark() { :; }\n" + func("step_grows") +
'ROOTFS_GROW=; DATAVOL_GROW=; SYSDATA_GROW=\nstep_grows\necho "GROW=$DATAVOL_GROW"\n')
assert rc == 0, out
assert "GROW=76" in out, out # 100 GiB data volume = the golden's 24 + 76
finally:
sb.close()
def _internal_place(mode="appliance", helper_out=None, helper_rc=0, guests="", have_helper=True, dry=False):
"""Run step_internal_place with the helper replaced by a stub; returns (rc, out, record or None, helper calls)."""
sb = Sandbox()
try:
helper = sb.path("felhom-internal-place")
if have_helper:
with open(helper, "w") as f:
f.write('#!/bin/sh\necho "helper $*" >> "%s"\n%s\nexit %d\n' % (sb.calls, 'echo "%s"' % helper_out if helper_out else "", helper_rc))
os.chmod(helper, 0o755)
sb.stub("install"); sb.stub("chown")
body = func("step_internal_place").replace("/usr/local/sbin/felhom-internal-place", helper)
assert helper in body, "the step no longer names the helper's path"
script = (prelude(dry) + "_state_mark() { echo \"MARK $1\"; }\nfelhom_guests() { echo '%s'; }\n" % guests + body +
'MODE=%s; AGENT_USER=felhom-agent; AGENT_STATE_DIR="$SB"; ROOTFS_GROW=0; DATAVOL_GROW=76; SYSDATA_GROW=0\n'
'step_internal_place\necho "RC=$?"\n' % mode)
rc, out = sb.run(script)
rec_path = sb.path("internal-place.json")
rec = json.load(open(rec_path)) if os.path.exists(rec_path) else None
calls = [l for l in sb.logged().splitlines() if l.startswith("helper ")]
return rc, out, rec, calls
finally:
sb.close()
def test_internal_place_created_and_recorded():
rc, out, rec, calls = _internal_place(helper_out="created uuid=0b6e4c5a-1d2e-4f3a-9b8c-7d6e5f4a3b2c gib=182")
assert rc == 0 and "RC=0" in out, out
assert calls == ["helper create 132"], calls # 32 rootfs + 24 + 76: the guest's thin space still to come
assert rec and rec["fs_uuid"] == "0b6e4c5a-1d2e-4f3a-9b8c-7d6e5f4a3b2c" and rec["gib"] == 182 and rec["made_by"] == "installer", rec
assert "MARK internal_place" in out, out
def test_internal_place_never_fatal_and_writes_nothing_when_not_made():
for kw in ({"helper_out": "skipped only 7 GiB free for it (pool 53, reserve 16, promised 0, planned 82; needs 20)"},
{"helper_out": "felhom-internal-place: REFUSED: something", "helper_rc": 1},
{"have_helper": False},
{"mode": "byo", "helper_out": "created uuid=0b6e4c5a-1d2e-4f3a-9b8c-7d6e5f4a3b2c gib=182"}):
rc, out, rec, calls = _internal_place(**kw)
assert rc == 0 and "RC=0" in out, (kw, out)
assert rec is None, (kw, rec)
if kw.get("mode") == "byo":
assert calls == [], ("byo: the owner's pool is never touched", calls)
def test_internal_place_counts_an_existing_guest_once():
rc, out, rec, calls = _internal_place(helper_out="existing uuid=0b6e4c5a-1d2e-4f3a-9b8c-7d6e5f4a3b2c gib=182", guests="9201")
assert calls == ["helper create 0"], calls
assert rec and rec["gib"] == 182, rec
def test_internal_place_dry_run_creates_nothing():
rc, out, rec, calls = _internal_place(dry=True, helper_out="plan pool=349 reserve=34 promised=0 planned=132 internal=183 exists=false")
assert rec is None and all(not c.startswith("helper create") for c in calls), (calls, out)
def test_internal_place_runs_after_the_bundle_and_before_provision():
main = SRC[SRC.index("step_token\nstep_grows\n"):]
call = "should_skip internal_place || step_internal_place"
assert call in main, "the internal place step is not called from the main flow"
i_bundle, i_place, i_prov = main.find("step_agent_install"), main.find(call), main.find("step_provision")
assert -1 < i_bundle < i_place < i_prov, (i_bundle, i_place, i_prov)
# ── http_code prints ONE status (found 2026-10-25, attended release run) ─────────────────────────────────────────────
# With `-f`, curl prints -w's code AND exits 22 on a 4xx, so the old `curl -f … || curl …` printed the code twice
# („401401"): the preflight's 401 / 404 / 409 branches never matched and every refusal read „unexpected hub status".
def _http_code_with(status):
sb = Sandbox()
try:
# a curl stub that answers like the real one: -w prints the status; -f makes a 4xx/5xx exit 22
body = ('f=0; for a in "$@"; do case "$a" in --*) ;; -*f*) f=1;; esac; done\n'
'printf "%s" STATUS\n[ "$f" = 1 ] && [ STATUS -ge 400 ] && exit 22\nexit 0').replace("STATUS", status)
sb.stub("curl", body)
rc, out = sb.run(func("http_code") + 'c=$(http_code https://hub.invalid/api/v1/config/x -H "X: y"); printf "[%s]" "$c"')
return out
finally:
sb.close()
def test_http_code_prints_one_status_on_a_refusal():
for status in ("401", "404", "409"):
out = _http_code_with(status)
assert out.endswith("[%s]" % status), "http_code printed %r for a %s (the preflight's case never matches)" % (out, status)
def test_http_code_prints_the_status_on_success():
assert _http_code_with("200").endswith("[200]")
# ── R-1380 (D80): a new box trusts Proxmox by a copy of its own root CA; the pinned certificate is the fallback ──────
# NOT stubs: a real CA, a real leaf for 127.0.0.1 and a real `openssl s_server`, because the proof IS a TLS handshake.
# Skipped (and it says so) where openssl is missing — the CI runner has none; the pre-push run on DooPlex has.
class _PVE:
def __init__(self, sb):
import socket
self.sb, self.proc = sb, None
d = sb.path("pki")
os.mkdir(d)
def sh(*a):
subprocess.run(a, check=True, capture_output=True, cwd=d)
for ca in ("ca", "other"):
sh("openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", ca + ".key", "-out", ca + ".pem", "-days", "30",
"-subj", "/CN=" + ca, "-addext", "basicConstraints=critical,CA:TRUE")
sh("openssl", "req", "-newkey", "rsa:2048", "-nodes", "-keyout", "leaf.key", "-out", "leaf.csr", "-subj", "/CN=node")
open(os.path.join(d, "ext"), "w").write("subjectAltName=IP:127.0.0.1\nbasicConstraints=CA:FALSE\n")
sh("openssl", "x509", "-req", "-in", "leaf.csr", "-CA", "ca.pem", "-CAkey", "ca.key", "-CAcreateserial", "-out", "leaf.pem",
"-days", "30", "-extfile", "ext")
s = socket.socket(); s.bind(("127.0.0.1", 0)); self.port = s.getsockname()[1]; s.close()
self.proc = subprocess.Popen(["openssl", "s_server", "-accept", "127.0.0.1:%d" % self.port, "-cert", "leaf.pem", "-key", "leaf.key",
"-www", "-quiet"], cwd=d, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(50):
try:
socket.create_connection(("127.0.0.1", self.port), timeout=0.2).close(); break
except OSError:
time.sleep(0.1)
self.dir = d
self.leaf_fp = subprocess.run(["openssl", "x509", "-in", "leaf.pem", "-noout", "-fingerprint", "-sha256"], capture_output=True,
text=True, cwd=d).stdout.strip().split("=", 1)[1]
def close(self):
if self.proc:
self.proc.kill(); self.proc.wait()
def _trust_run(source, dry=False, dead_port=False):
"""Run resolve_pve_trust against a real TLS server — under `set -euo pipefail`, as the installer itself runs (line
195 of the script): a function that only works without strict mode proves nothing about the installer.
Returns (ca_file, fp, copy bytes or None, source bytes, output, leaf fp, dst)."""
if not shutil.which("openssl"):
return None
sb = Sandbox()
pve = _PVE(sb)
try:
dst = sb.path("etc-felhom-agent", "pve-root-ca.pem")
src = os.path.join(pve.dir, source)
port = 1 if dead_port else pve.port # port 1: nothing listens → the handshake cannot even start
rc, out = sb.run(prelude(dry) + func("resolve_pve_trust") + 'set -euo pipefail\n'
'PVE_CA_SOURCE="%s" PVE_CA_COPY="%s" PVE_API_ADDR=127.0.0.1:%d\nresolve_pve_trust\n'
'echo "RESULT ca=[$PVE_CA_FILE] fp=[$PVE_TLS_FP]"\n' % (src, dst, port))
assert rc == 0, out
m = re.search(r"RESULT ca=\[(.*?)\] fp=\[(.*?)\]", out)
assert m, out
copy = open(dst, "rb").read() if os.path.exists(dst) else None
return m.group(1), m.group(2), copy, open(src, "rb").read() if os.path.exists(src) else None, out, pve.leaf_fp, dst
finally:
pve.close()
sb.close()
def test_pve_trust_a_new_box_gets_the_ca_copy_and_no_fingerprint():
r = _trust_run("ca.pem")
if r is None:
print(" (skipped: no openssl here)"); return
ca, fp, copy, src, out, _, dst = r
assert ca == dst and fp == "", "the box's own CA verified the handshake, so: ca_file set, NO fingerprint. Got ca=%r fp=%r\n%s" % (ca, fp, out)
assert copy == src, "the copy is not the source, byte for byte"
def test_pve_trust_a_copy_that_does_not_verify_falls_back_to_the_pin():
r = _trust_run("other.pem") # a CA certificate, but not the one that signed the served certificate
if r is None:
print(" (skipped: no openssl here)"); return
ca, fp, _, _, out, leaf_fp, _ = r
assert ca == "" and fp == leaf_fp, "never neither: no proven copy → the served certificate is pinned. Got ca=%r fp=%r\n%s" % (ca, fp, out)
assert "NOT used" in out and "did not verify" in out, out
def test_pve_trust_a_source_that_is_not_a_ca_is_never_copied():
for source, why in (("leaf.pem", "not a CA certificate"), ("leaf.key", "not exactly one certificate"), ("missing.pem", "not readable")):
r = _trust_run(source)
if r is None:
print(" (skipped: no openssl here)"); return
ca, fp, copy, _, out, leaf_fp, _ = r
assert ca == "" and copy is None, "%s: copied although it is %s" % (source, why)
assert fp == leaf_fp, "%s: the fallback pin is missing: %r" % (source, fp)
assert why in out, "%s: the reason is not named:\n%s" % (source, out)
def test_pve_trust_no_answer_from_proxmox_does_not_end_the_installer():
"""Found by review 2026-11-14: under `set -euo pipefail` a failed pipeline inside `fp=$(…)` ended the whole installer at
that line. Proxmox not answering (it restarts) must leave the function running to its end: no CA file (no proof), no
fingerprint, and the two warnings — the run reaches RESULT."""
r = _trust_run("ca.pem", dead_port=True)
if r is None:
print(" (skipped: no openssl here)"); return
ca, fp, _, _, out, _, _ = r
assert ca == "" and fp == "", "nothing answered, so nothing can be proven or pinned. Got ca=%r fp=%r\n%s" % (ca, fp, out)
assert "did not verify" in out and "could not compute TLS fingerprint" in out, out
def test_pve_trust_dry_run_writes_nothing():
r = _trust_run("ca.pem", dry=True)
if r is None:
print(" (skipped: no openssl here)"); return
_, _, copy, _, out, _, _ = r
assert copy is None and "[DRY-RUN]" in out, out
def test_pve_trust_is_wired_into_the_agent_config():
body = func("step_agent_config")
assert re.search(r"^\s+resolve_pve_trust\s*$", body, re.M), "step_agent_config no longer calls resolve_pve_trust"
assert 'fp="$PVE_TLS_FP"' in body and 'PVE_CA_FILE="$PVE_CA_FILE"' in body, "the result does not reach the config writer"
assert "\"ca_file\": os.environ.get('PVE_CA_FILE', '')" in body and "\"fingerprint\": os.environ['FP']" in body, \
"the config writer does not write both keys"
# the agent's root step and the installer name the same two files
wrapper = open(os.path.join(os.path.dirname(SCRIPT), "..", "..", "felhom-agent", "configs", "felhom-os-apply"), encoding="utf-8").read() \
if os.path.exists(os.path.join(os.path.dirname(SCRIPT), "..", "..", "felhom-agent", "configs", "felhom-os-apply")) else None
if wrapper is not None:
for name, path in (("PVE_CA_SOURCE", "/etc/pve/pve-root-ca.pem"), ("PVE_CA_COPY", "/etc/felhom-agent/pve-root-ca.pem")):
assert '%s = "%s"' % (name, path) in wrapper and path in func("resolve_pve_trust"), "the installer and the agent's root step disagree on %s" % name
# ── D83 (R-1370, `16` §14.5): the system disk below 200 GB ───────────────────────────────────────
# The disk is the one under the `pve` volume group; its size is the kernel's sector count. The stubs
# stand for pvs and lsblk, and SYS_BLOCK_DIR for /sys/block — no real disk is read.
GB200_LABEL = 200049647616 # a disk sold as "200 GB"
GIB200 = 200 * 1024 ** 3 # a virtual disk made as "200G"
def _disk_sandbox(disks, pvs_lines=("/dev/sda3",), parent="sda", kind="disk"):
"""disks: {name: bytes}. pvs prints pvs_lines; lsblk says the PV's parent and the parent's type."""
sb = Sandbox()
for name, size in disks.items():
os.makedirs(sb.path("sys", name))
with open(sb.path("sys", name, "size"), "w") as f:
f.write("%d\n" % (size // 512))
sb.stub("pvs", "\n".join('echo " %s"' % l for l in pvs_lines) if pvs_lines else "exit 0")
sb.stub("lsblk", 'case "$*" in *PKNAME*) echo "%s";; *TYPE*) echo "%s";; esac' % (parent, kind))
return sb
def _min_bytes_line():
"""The installer's OWN minimum, read from the script — a test that sets the number itself cannot see it change."""
m = re.search(r"^SYSTEM_DISK_MIN_BYTES=\d+$", SRC, re.M)
assert m, "SYSTEM_DISK_MIN_BYTES not found in the installer"
return m.group(0)
def _disk_run(sb, mode, accept=False):
return sb.run("set -euo pipefail\n" + one_liners() + func("system_disk_bytes") + func("check_system_disk") +
_min_bytes_line() + '; SYS_BLOCK_DIR="$SB/sys"\n'
'MODE="%s"; ACCEPT_SMALL_DISK=%s\ncheck_system_disk\n'
'echo "WENT-ON small=$SMALL_DISK bytes=$SYSTEM_DISK_BYTES"\n' % (mode, "true" if accept else "false"))
def test_small_disk_appliance_is_refused_before_anything_changes():
sb = _disk_sandbox({"sda": 128 * 10 ** 9})
try:
rc, out = _disk_run(sb, "appliance")
assert rc == 1 and "WENT-ON" not in out, "a 128 GB appliance install went on: rc=%s %s" % (rc, out)
assert "This machine's system disk is 128 GB. Felhom needs 200 GB." in out and "Nothing was changed" in out, out
assert "--accept-small-disk" in out, "the refusal does not name the flag: %s" % out
# the check only READS: pvs and lsblk, nothing else was called
called = {l.split()[0] for l in sb.logged().splitlines() if l.strip()}
assert called == {"pvs", "lsblk"}, "the disk check ran more than its two reads: %s" % sorted(called)
finally:
sb.close()
def test_small_disk_the_line_is_200_times_ten_to_the_nine_bytes():
for size, passes in ((GB200_LABEL, True), (200 * 10 ** 9, True), (GIB200, True),
(200 * 10 ** 9 - 512, False), (180 * 10 ** 9, False)):
sb = _disk_sandbox({"sda": size})
try:
rc, out = _disk_run(sb, "appliance")
assert (rc == 0 and "WENT-ON small=false bytes=%d" % size in out) == passes, \
"%d bytes: passes=%s wanted %s: %s" % (size, rc == 0, passes, out)
finally:
sb.close()
def test_small_disk_flag_goes_on_prints_the_cost_and_marks_it():
sb = _disk_sandbox({"sda": 128 * 10 ** 9})
try:
rc, out = _disk_run(sb, "appliance", accept=True)
assert rc == 0 and "WENT-ON small=true bytes=128000000000" in out, out
assert "128 GB" in out and "The cost:" in out and "local copies can stop" in out, "the cost is not printed: %s" % out
finally:
sb.close()
# the flag on a disk that is large enough marks nothing
sb = _disk_sandbox({"sda": GB200_LABEL})
try:
rc, out = _disk_run(sb, "appliance", accept=True)
assert rc == 0 and "WENT-ON small=false" in out, out
finally:
sb.close()
def test_small_disk_byo_host_is_warned_never_refused():
sb = _disk_sandbox({"sda": 128 * 10 ** 9})
try:
rc, out = _disk_run(sb, "byo")
assert rc == 0 and "WENT-ON small=false" in out, "a byo host was stopped: %s" % out
assert "[WARN]" in out and "128 GB" in out and "200 GB" in out, out
finally:
sb.close()
# no --mode (the mode-agnostic --preflight-only): a warning too
sb = _disk_sandbox({"sda": 128 * 10 ** 9})
try:
rc, out = _disk_run(sb, "")
assert rc == 0 and "[WARN]" in out, out
finally:
sb.close()
def test_small_disk_size_that_cannot_be_read_refuses_and_names_the_flag():
cases = {
"no pve volume group": dict(disks={"sda": GB200_LABEL}, pvs_lines=()),
"two physical volumes": dict(disks={"sda": GB200_LABEL, "sdb": GB200_LABEL}, pvs_lines=("/dev/sda3", "/dev/sdb1")),
"a RAID under the group": dict(disks={"md0": GB200_LABEL}, parent="md0", kind="raid1"),
"no parent disk": dict(disks={"sda": GB200_LABEL}, parent=""),
"no size file": dict(disks={"sdb": GB200_LABEL}),
}
for name, kw in cases.items():
sb = _disk_sandbox(**kw)
try:
rc, out = _disk_run(sb, "appliance")
assert rc == 1 and "WENT-ON" not in out, "%s: the install went on: %s" % (name, out)
assert "Cannot read the system disk's size" in out and "--accept-small-disk" in out and "Nothing was changed" in out, "%s: %s" % (name, out)
assert "[ERROR] Cannot read" in out and "system disk is" not in out, "%s: the refusal is not the 'cannot read' one: %s" % (name, out)
rc, out = _disk_run(sb, "appliance", accept=True)
assert rc == 0 and "WENT-ON small=true bytes=unknown" in out, "%s with the flag: %s" % (name, out)
rc, out = _disk_run(sb, "byo")
assert rc == 0 and "[WARN]" in out, "%s on a byo host: %s" % (name, out)
finally:
sb.close()
def test_small_disk_a_large_second_disk_does_not_help():
# the rule reads the SYSTEM disk (the one under `pve`), not the largest disk in the machine
sb = _disk_sandbox({"sda": 128 * 10 ** 9, "sdb": 2000 * 10 ** 9})
try:
rc, out = _disk_run(sb, "appliance")
assert rc == 1 and "128 GB" in out, out
finally:
sb.close()
# and the other way round: a small second disk does not refuse a large system disk
sb = _disk_sandbox({"sda": 512 * 10 ** 9, "sdb": 16 * 10 ** 9})
try:
rc, out = _disk_run(sb, "appliance")
assert rc == 0 and "WENT-ON small=false" in out, out
finally:
sb.close()
def test_small_disk_check_is_wired_first_in_the_preflight_and_recorded():
body = func("step_preflight")
at = body.find("\n check_system_disk\n")
assert at > 0, "step_preflight no longer calls check_system_disk"
for later in ("pveversion | head", "_state_put", "_state_mark", "pvesh get", "systemctl cat", "apt-get", "_byo_disclosure_ack", "mkdir", "curl -"):
first = body.find(later)
assert first == -1 or at < first, "check_system_disk runs AFTER %r — a refused machine may already be changed" % later
assert '_state_put small_disk "${SMALL_DISK:-false}"' in body and '_state_put system_disk_bytes' in body, \
"the preflight does not record small_disk in the install state"
# the flag reaches the variable, and the help names it
assert re.search(r"--accept-small-disk\)\s+ACCEPT_SMALL_DISK=true; shift ;;", SRC), "the flag is not parsed"
assert "# --accept-small-disk" in SRC, "the help does not name the flag"
# the existing pool warning stays as the second check
assert "RECOMMENDED_MIN_LVM_GIB" in body
def _enroll_run(small_state, small_var):
sb = Sandbox()
sb.stub("curl", 'printf \'{"host_id":"h1","api_key":"k1"}\\n201\'')
os.makedirs(sb.path("state"))
with open(sb.path("state", "state.json"), "w") as f:
json.dump({"completed": [], "small_disk": small_state}, f)
rc, out = sb.run("set -euo pipefail\n" + prelude() + func("_state_mark") + func("_state_get") + func("step_enroll") +
'die_live_box() { exit 9; }\nPREFLIGHT_ONLY=false\nSTATE_DIR="$SB/state"; STATE_FILE="$SB/state/state.json"\n'
'HUB_URL=http://hub.invalid; PASSPHRASE=p; CUSTOMER_ID=c1\n%sstep_enroll\n' % small_var)
logged = sb.logged()
sb.close()
return rc, out, logged
def test_small_disk_is_told_to_the_hub_at_the_enrolment():
rc, out, logged = _enroll_run("true", "") # a resume: the flag comes from the state record
assert rc == 0, out
assert '{"customer_id":"c1","small_disk":true}' in logged, "the enrolment does not tell the hub: %s" % logged
rc, out, logged = _enroll_run("false", "SMALL_DISK=true\n") # this run's own check wins
assert rc == 0 and '"small_disk":true' in logged, logged
rc, out, logged = _enroll_run("false", "") # the control: an ordinary box says nothing
assert rc == 0 and '{"customer_id":"c1"}' in logged and "small_disk" not in logged, logged
def main():
tests = [(n, f) for n, f in sorted(globals().items()) if n.startswith("test_") and callable(f)]
fails = 0
for name, f in tests:
try:
f()
print("PASS", name)
except AssertionError as e:
fails += 1
print("FAIL", name, "--", e)
print("%d passed, %d failed" % (len(tests) - fails, fails))
return 1 if fails else 0
if __name__ == "__main__":
sys.exit(main())