From 6b0b1fb81a3a1a91b6ee5d4e8dfe574c2a0ac8bf Mon Sep 17 00:00:00 2001 From: Gerrrt Date: Sun, 22 Nov 2026 17:40:07 -0800 Subject: [PATCH 1/3] feat(range): build gandalf's power-off timer (ADR-0124) scripts/range-poweroff.sh powers gandalf off six hours after boot or after the last range-extend (1 to 12 hours). It warns every shell at 30 and 5 minutes, and waits while dpkg holds its lock. systemd/range/ runs it every five minutes. build-the-playground.md section 7 installs it from Hicks (range-extend 6 first, so an install on a long-up box doesn't power it off at once), and the read-back checks the timer is enabled and active. Its 18-fixture --self-test is discovered by self-tests.sh. It passed locally and under gandalf's bash, and each of three deliberate breaks failed it. Not installed on gandalf yet. Refs #1647. Co-Authored-By: Claude Opus 5.5 --- docs/changelog.md | 21 ++ docs/roadmap.md | 8 +- docs/runbooks/build-the-playground.md | 66 +++++- scripts/README.md | 1 + scripts/range-poweroff.sh | 224 +++++++++++++++++++ scripts/self-tests.sh | 3 + systemd/README.md | 3 +- systemd/range/homelab-range-poweroff.service | 38 ++++ systemd/range/homelab-range-poweroff.timer | 19 ++ 9 files changed, 375 insertions(+), 8 deletions(-) create mode 100755 scripts/range-poweroff.sh create mode 100644 systemd/range/homelab-range-poweroff.service create mode 100644 systemd/range/homelab-range-poweroff.timer diff --git a/docs/changelog.md b/docs/changelog.md index 710e9abd..3e6b4e56 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -19,6 +19,27 @@ docstring gives: it is a record, not a claim about now. ## 2026-11-22 +- **`gandalf`'s power-off timer is built, not installed + ([#1647](https://github.com/Gerrrt/HomeLab/issues/1647)).** This builds + ADR-0124 in the repository. `scripts/range-poweroff.sh` holds the deadline + under `/run`, sends the 30- and 5-minute `wall` warnings, waits while `dpkg` + holds its lock, and powers off. Linked as `range-extend`, it sets the + deadline 1 to 12 hours from now. `systemd/range/` runs it every five + minutes. `build-the-playground.md` §7 gains *The power-off timer*, which + installs it from Hicks with a `range-extend 6` first, so an install on a box + already up six hours does not power it off five minutes later. The + read-back checks the timer is enabled and active. + - The `--self-test` has 18 fixtures, and `self-tests.sh` runs it in CI. + - Each of three deliberate breaks failed at least one fixture: no `dpkg` + wait, no extension cap, no 5-minute warning. + - It passed under `gandalf`'s own bash, run from standard input without + installing anything. + - `systemd-analyze verify` on `gandalf` reported only that the script was + not installed yet. + + Nothing is installed on `gandalf`, and the one-power-off proof in §7 has + not been run. + - **`gandalf` will power itself off on a timer ([ADR-0124](adr/0124-power-gandalf-off-on-a-timer.md)).** Both audits of `gandalf` found it left on for days, `ragnarok` included, against the diff --git a/docs/roadmap.md b/docs/roadmap.md index 8a8ee897..36c76e39 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -42,9 +42,11 @@ Closes when it is empty. - **[#1647](https://github.com/Gerrrt/HomeLab/issues/1647) Power `gandalf` off on a timer.** Decided by - [ADR-0124](adr/0124-power-gandalf-off-on-a-timer.md). No gate. Until it is - built, the range's "off between sessions" rests on the operator, and two - audits found it left on. + [ADR-0124](adr/0124-power-gandalf-off-on-a-timer.md). No gate. The script + and its units are in the repository. Left: install them on `gandalf` and + prove one power-off, both in `build-the-playground.md` §7. Until then the + range's "off between sessions" rests on the operator, and two audits found + it left on. - **[#1226](https://github.com/Gerrrt/HomeLab/issues/1226) The HomePods in Home Assistant, for control.** Decided by [ADR-0099](adr/0099-control-the-homepods-from-home-assistant-and-leave-their-audio-out.md). diff --git a/docs/runbooks/build-the-playground.md b/docs/runbooks/build-the-playground.md index 2cb6ee7c..891037d7 100644 --- a/docs/runbooks/build-the-playground.md +++ b/docs/runbooks/build-the-playground.md @@ -1080,13 +1080,14 @@ Two audits found the box left on for days anyway (2026-11-13 and 2026-11-22). [ADR-0124](../adr/0124-power-gandalf-off-on-a-timer.md) takes the backstop off the person: a timer on the host powers it off six hours after boot, or after the last `range-extend`, with a warning on every shell 30 and 5 minutes -before. **It is decided and not built yet** -([#1647](https://github.com/Gerrrt/HomeLab/issues/1647)). Until it is, the -power-off at the end below is still yours alone. Once it is built, this -section installs it and the read-back checks it is enabled. +before ([#1647](https://github.com/Gerrrt/HomeLab/issues/1647)). The +power-off at the end below is still the plan. The timer is what happens when +the plan is forgotten. **Not yet installed on `gandalf`.** ```text on → read the firewall back → revert every target to `clean` → work → revert → off + ↑ + 6 h after boot or the last range-extend → off, by itself ``` **Read the firewall back before anything else.** The collector and the alerts @@ -1106,6 +1107,11 @@ print `1`. Anything else means the session does not start until §2's lines have been rerun and checked in `/etc/network/interfaces`. `ls /etc/apt/sources.list.d/` should list Debian's and Proxmox's sources only (§4, *Nothing else on `gandalf`*). +`systemctl is-enabled homelab-range-poweroff.timer; systemctl is-active +homelab-range-poweroff.timer` should read `enabled` and `active`, and +`homelab-range-poweroff status` should show a deadline in the future. A +disabled timer puts the range back on discipline alone (ADR-0124), so the +session does not start until *The power-off timer* above has been rerun. **Then check Proxmox's own updates.** `unattended-upgrades` covers Debian's packages only (§4, *Services on `gandalf`*). `apt update && apt list @@ -1116,6 +1122,58 @@ installed a `proxmox-kernel-*` package, or `/run/reboot-required` exists, reboot and start this section again from the top. The firewall read-back runs again too, since a reboot is a fresh power-on. +### The power-off timer + +Install it once, from a Hicks workstation in a checkout of this repository. +It is three files and a symlink, and nothing else on the host changes: + +```bash +G=root@10.0.30.30 +ssh "$G" 'install -d -m 0755 /usr/local/sbin' +scp scripts/range-poweroff.sh "$G":/usr/local/sbin/homelab-range-poweroff +scp systemd/range/homelab-range-poweroff.service systemd/range/homelab-range-poweroff.timer "$G":/etc/systemd/system/ +ssh "$G" 'chmod 0755 /usr/local/sbin/homelab-range-poweroff && + chmod 0644 /etc/systemd/system/homelab-range-poweroff.* && + ln -sf /usr/local/sbin/homelab-range-poweroff /usr/local/sbin/range-extend && + homelab-range-poweroff --self-test >/dev/null && echo self-test-ok && + range-extend 6 && + systemd-analyze verify /etc/systemd/system/homelab-range-poweroff.service && + systemctl daemon-reload && systemctl enable --now homelab-range-poweroff.timer && + homelab-range-poweroff status' +``` + +**You should see** `self-test-ok`, no output from `systemd-analyze`, and a +deadline six hours from now. The `range-extend 6` before the enable is +deliberate. Without it the deadline is six hours after *this* boot, and on a +box that has been up longer than that, the first run powers it off five +minutes after the install. The self-test exercises every branch with +fakes, so it can run on the host without powering anything off. + +Running it, as root on `gandalf`: + +| | | +| --- | --- | +| `homelab-range-poweroff status` | The deadline and the minutes left | +| `range-extend 3` | Set the deadline three hours from now. 1 to 12. It can also bring the deadline closer | +| `journalctl -t homelab-range-poweroff` | Every warning, extension, wait and power-off | + +At 30 minutes and again at 5, every shell on the host gets a `wall` message +that says how to extend. Past the deadline the next run powers off, unless +`dpkg` holds its lock. Then it waits for the run after that. Nothing reaches +the Proxmox web UI, so a session driven only from `8006` gets no warning. +Check `status` from a shell when you start one. + +**Prove it once after installing**, with a session you can afford to lose: + +1. `range-extend 1`, then check `status` reads about 60 minutes. +2. Keep an SSH session open. The 30- and 5-minute `wall` messages should + reach it. +3. Start one guest. At the deadline the box should power itself off, and + `journalctl -t homelab-range-poweroff -b -1` at the next power-on should + end with `powering gandalf off`. + +Record the result here. **Not yet run on `gandalf`.** + --- ## 8. Check the four properties diff --git a/scripts/README.md b/scripts/README.md index 0eaf30c8..a8592230 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -162,6 +162,7 @@ They need the running estate, so CI cannot run them. Timers do. | `capture-screenshots.sh` | `screenshots` | Renders the dashboards into [`docs/images/`](../docs/images/README.md) | | `packer-smoke.sh` | — | Clones a Packer template, boots it, checks it and destroys it ([`packer/`](../packer/README.md)) | | `finish-attack-vm.sh` | — | Finishes the range's attack VM, `ragnarok`, after `tofu/` makes it on `gandalf` from 902 ([ADR-0116](../docs/adr/0116-build-the-range-attack-vm-with-opentofu-and-prove-it-with-a-script.md)): writes `99-no-forward.conf` and ADR-0014's outbound scope as an nftables policy, at the IP stack and at `eth0`'s egress for raw Ethernet, and proves it neither forwards, NATs nor reaches past `10.0.30.0/24` and the range, over SSH checked against a host key read through the guest agent ([`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §5) | +| `range-poweroff.sh` | — | Powers `gandalf` off six hours after boot or after the last `range-extend`, warning on every shell at 30 and 5 minutes, and never while `dpkg` holds its lock ([ADR-0124](../docs/adr/0124-power-gandalf-off-on-a-timer.md)). Installed with [`systemd/range/`](../systemd/range) by [`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §7. Its `--self-test` is the only test of the deadline logic: a real run powers the range host off | | `stage-agent-msis.sh` | — | Stages the Wazuh and Velociraptor MSIs the lab pipeline installs, and the two Debian packages `garuda` installs, into `${SOC_DATA_DIR}/agent-msi` on `odin`, which the SOC stack's Caddy serves. The vendor packages are checked against their pins; the Velociraptor `.deb` is built by the server and its hash printed ([#1068](https://github.com/Gerrrt/HomeLab/issues/1068), [ADR-0092](../docs/adr/0092-enrol-garuda-in-odins-soc-with-debian-packages-staged-on-odin.md)) | | `lab-known-hosts.sh` | — | Reads the lab domain's SSH host keys through the guest agent into `ansible/.known_hosts`, after any rebuild ([ADR-0085](../docs/adr/0085-check-the-lab-domains-host-keys-against-keys-read-through-the-guest-agent.md)) | | `gen_population.py` | — | The lab domain's users, into `ansible/population/` | diff --git a/scripts/range-poweroff.sh b/scripts/range-poweroff.sh new file mode 100755 index 00000000..d49e20b5 --- /dev/null +++ b/scripts/range-poweroff.sh @@ -0,0 +1,224 @@ +#!/usr/bin/env bash +# Power gandalf off at a deadline, so the range is never left running +# (ADR-0124, #1647). +# +# Usage: +# homelab-range-poweroff check what the timer runs: warn, or power off +# homelab-range-poweroff status print the deadline and the time left +# homelab-range-poweroff extend H set the deadline H hours from now (1-12) +# range-extend H the same as `extend H` (a symlink to this) +# scripts/range-poweroff.sh --self-test +# +# THE DEADLINE is six hours after boot, or the time the last `extend` set. +# It lives under /run, which a boot clears, so every boot starts the six +# hours again and an extension never outlives the session that asked for +# it. One extension is capped at twelve hours, so a typo or a "just leave +# it" cannot quietly switch the backstop off. +# +# THE WARNINGS go to every shell through `wall`: once at 30 minutes or +# less, once at 5 or less. The timer runs this every five minutes, so +# exactly one run falls inside the last five. A warning is recorded +# against the deadline it was for, so an extension re-arms both without +# clearing anything. +# +# IT NEVER POWERS OFF IN THE MIDDLE OF A PACKAGE INSTALL. While something +# holds dpkg's lock, a run past the deadline logs that it is waiting and +# exits. The next run checks again. Cutting dpkg off half way leaves a +# hypervisor that may not boot, which is worse than a range left on for +# five more minutes. +# +# THE POWER-OFF is the ordinary `systemctl poweroff`. pve-guests.service's +# ExecStop runs Proxmox's stopall, which shuts every guest down and forces +# any that ignore ACPI, as Mr-Robot does. Reverting the targets to `clean` +# is build-the-playground.md §7's first step at the next power-on. +set -euo pipefail + +HOURS=6 +MAX_EXTEND=12 +STATE_DIR="${RANGE_STATE_DIR:-/run/homelab-range-poweroff}" + +# Each of these is replaced by the self-test, which is the only reason they +# are functions. +now() { date +%s; } +boot_time() { awk '/^btime /{print $2}' /proc/stat; } +dpkg_busy() { fuser -s /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock 2>/dev/null; } +say() { logger -t homelab-range-poweroff -- "$*" 2>/dev/null || true; printf '%s\n' "$*"; } +warn_all() { wall -- "$*" 2>/dev/null || true; } +power_off() { systemctl poweroff; } + +is_uint() { [[ "$1" =~ ^[0-9]+$ ]]; } + +read_state() { + # One integer per file. Anything else reads as absent. + local f="${STATE_DIR}/$1" v="" + [[ -f "${f}" ]] && v="$(head -c 32 "${f}" 2>/dev/null | tr -d '[:space:]')" + is_uint "${v}" && printf '%s' "${v}" + return 0 +} + +write_state() { + # Write then rename, so a reader never sees half a number. + mkdir -p "${STATE_DIR}" + printf '%s\n' "$2" > "${STATE_DIR}/$1.tmp" + mv -f "${STATE_DIR}/$1.tmp" "${STATE_DIR}/$1" +} + +deadline() { + local d + d="$(read_state deadline)" + if [[ -n "${d}" ]]; then printf '%s' "${d}"; return; fi + printf '%s' "$(( $(boot_time) + HOURS * 3600 ))" +} + +minutes_left() { printf '%s' "$(( ($1 + 59) / 60 ))"; } + +fmt_time() { date -d "@$1" '+%Y-%m-%d %H:%M' 2>/dev/null || date -r "$1" '+%Y-%m-%d %H:%M'; } + +cmd_check() { + local t d left mins + t="$(now)" + d="$(deadline)" + left=$(( d - t )) + if (( left <= 0 )); then + if dpkg_busy; then + say "deadline $(fmt_time "${d}") has passed, but dpkg's lock is held; waiting for the next run" + return 0 + fi + say "deadline $(fmt_time "${d}") has passed; powering gandalf off" + warn_all "gandalf: the range deadline has passed (ADR-0124). Powering off now." + power_off + return 0 + fi + mins="$(minutes_left "${left}")" + if (( left <= 300 )); then + if [[ "$(read_state warned-5)" != "${d}" ]]; then + warn_all "gandalf powers off in ${mins} min (ADR-0124). To keep it on: range-extend " + write_state warned-5 "${d}" + write_state warned-30 "${d}" + say "warned: ${mins} min to the deadline" + fi + elif (( left <= 1800 )); then + if [[ "$(read_state warned-30)" != "${d}" ]]; then + warn_all "gandalf powers off in ${mins} min (ADR-0124). To keep it on: range-extend " + write_state warned-30 "${d}" + say "warned: ${mins} min to the deadline" + fi + fi + return 0 +} + +cmd_extend() { + local h="${1:-}" t d + if ! is_uint "${h}" || (( 10#${h} < 1 || 10#${h} > MAX_EXTEND )); then + printf 'usage: range-extend , a whole number from 1 to %d\n' "${MAX_EXTEND}" >&2 + return 2 + fi + h=$(( 10#${h} )) + t="$(now)" + d=$(( t + h * 3600 )) + write_state deadline "${d}" + say "deadline set to $(fmt_time "${d}"), ${h} h from now, by ${SUDO_USER:-${USER:-root}}" + return 0 +} + +cmd_status() { + local t d left + t="$(now)" + d="$(deadline)" + left=$(( d - t )) + if [[ -n "$(read_state deadline)" ]]; then + printf 'deadline %s (set by range-extend)\n' "$(fmt_time "${d}")" + else + printf 'deadline %s (%d h after boot)\n' "$(fmt_time "${d}")" "${HOURS}" + fi + if (( left > 0 )); then + printf '%d min left\n' "$(minutes_left "${left}")" + else + printf 'passed %d min ago; the next run powers off unless dpkg is busy\n' "$(( -left / 60 ))" + fi + return 0 +} + +self_test() { + local passed=0 failed=0 tmp + tmp="$(mktemp -d)" + trap 'rm -rf "${tmp}"' RETURN + STATE_DIR="${tmp}/state" + + # Fakes. BOOT is fixed; NOW, BUSY and the logs are set per fixture. + local BOOT=1800000000 NOW=0 BUSY=1 WALL_LOG="${tmp}/wall" OFF_LOG="${tmp}/off" + now() { printf '%s' "${NOW}"; } + boot_time() { printf '%s' "${BOOT}"; } + dpkg_busy() { return "${BUSY}"; } + say() { :; } + warn_all() { printf '%s\n' "$*" >> "${WALL_LOG}"; } + power_off() { printf 'off\n' >> "${OFF_LOG}"; } + + reset() { rm -rf "${STATE_DIR}" "${WALL_LOG}" "${OFF_LOG}"; BUSY=1; } + walls() { [[ -f "${WALL_LOG}" ]] && wc -l < "${WALL_LOG}" | tr -d ' ' || printf 0; } + offs() { [[ -f "${OFF_LOG}" ]] && wc -l < "${OFF_LOG}" | tr -d ' ' || printf 0; } + check() { + local name="$1" got="$2" expect="$3" + if [[ "${got}" == "${expect}" ]]; then + printf '\033[0;32m PASS\033[0m %s\n' "${name}"; passed=$((passed + 1)) + else + printf '\033[0;31m FAIL\033[0m %s\n got %s\n expected %s\n' "${name}" "${got}" "${expect}" + failed=$((failed + 1)) + fi + } + + local H=3600 + reset; NOW=$((BOOT + 60)); cmd_check + check "a fresh boot neither warns nor powers off" "$(walls)/$(offs)" "0/0" + + reset; NOW=$((BOOT + 6 * H - 1700)); cmd_check; cmd_check + check "under 30 min warns once, not on every run" "$(walls)/$(offs)" "1/0" + + reset; NOW=$((BOOT + 6 * H - 1700)); cmd_check; NOW=$((BOOT + 6 * H - 200)); cmd_check; cmd_check + check "under 5 min warns a second time, once" "$(walls)/$(offs)" "2/0" + + reset; NOW=$((BOOT + 6 * H - 200)); cmd_check; NOW=$((BOOT + 6 * H - 100)); cmd_check + check "a first run inside 5 min sends one warning, not two" "$(walls)/$(offs)" "1/0" + + reset; NOW=$((BOOT + 6 * H)); cmd_check + check "at the deadline it powers off" "$(offs)" "1" + + reset; NOW=$((BOOT + 6 * H + 10)); BUSY=0; cmd_check + check "past the deadline with dpkg busy it waits" "$(offs)" "0" + BUSY=1; cmd_check + check "and powers off on the next run once dpkg is done" "$(offs)" "1" + + reset; NOW=$((BOOT + 5 * H)); cmd_extend 3 >/dev/null; NOW=$((BOOT + 6 * H + 60)); cmd_check + check "an extension moves the deadline past six hours" "$(offs)" "0" + NOW=$((BOOT + 8 * H)); cmd_check + check "and the extended deadline is enforced" "$(offs)" "1" + + reset; NOW=$((BOOT + 6 * H - 1700)); cmd_check; cmd_extend 1 >/dev/null; NOW=$((NOW + H - 1700)); cmd_check + check "an extension re-arms the 30-minute warning" "$(walls)" "2" + + reset; NOW=$((BOOT + H)) + check "extend refuses 0" "$(cmd_extend 0 2>/dev/null; printf '%s' "$?")" "2" + check "extend refuses 13 (the cap is 12)" "$(cmd_extend 13 2>/dev/null; printf '%s' "$?")" "2" + check "extend refuses a non-number" "$(cmd_extend 2h 2>/dev/null; printf '%s' "$?")" "2" + check "extend refuses nothing at all" "$(cmd_extend 2>/dev/null; printf '%s' "$?")" "2" + check "a refused extend leaves no deadline behind" "$(read_state deadline)" "" + check "extend accepts 12" "$(cmd_extend 12 >/dev/null; read_state deadline)" "$((NOW + 12 * H))" + check "extend reads 08 as eight, not as octal" "$(cmd_extend 08 >/dev/null; read_state deadline)" "$((NOW + 8 * H))" + + reset; mkdir -p "${STATE_DIR}"; printf 'garbage\n' > "${STATE_DIR}/deadline" + check "an unreadable deadline file falls back to six hours after boot" "$(deadline)" "$((BOOT + 6 * H))" + + ((failed == 0)) +} + +case "$(basename "$0")" in + range-extend) cmd_extend "$@"; exit $? ;; +esac + +case "${1:-}" in + --self-test) self_test ;; + check) cmd_check ;; + status) cmd_status ;; + extend) shift; cmd_extend "$@" ;; + *) printf 'usage: %s check|status|extend |--self-test\n' "$0" >&2; exit 2 ;; +esac diff --git a/scripts/self-tests.sh b/scripts/self-tests.sh index 8881351b..dee64436 100755 --- a/scripts/self-tests.sh +++ b/scripts/self-tests.sh @@ -75,6 +75,9 @@ # tree, a non-fast-forward, red CI. None can be # staged on a deployment host, and each was tested # only by never having fired (#854) +# range-poweroff.sh the deadline, the two warnings and the dpkg wait; +# a real run powers gandalf off, so the fixtures are +# the only way to see each branch before it fires # backup-volumes.sh a real backup of a throwaway volume with real age: # the set opens with either recipient's key and not # a third's (#835), and the refusals refuse (#854) diff --git a/systemd/README.md b/systemd/README.md index a7e701c7..9dc782dc 100644 --- a/systemd/README.md +++ b/systemd/README.md @@ -23,7 +23,7 @@ Times are the host's local time. The full procedure, and what to do when a job goes stale, is [`docs/runbooks/schedule-maintenance.md`](../docs/runbooks/schedule-maintenance.md). -## The four directories +## The five directories | Directory | Host | Installed by | Runs through | | --- | --- | --- | --- | @@ -31,6 +31,7 @@ job goes stale, is | [`sensitive/`](sensitive) | `trinity` | `make install-timers ARGS="--profile sensitive"` | the same, with `@DEPLOY_ROOT@` and `@RUN_USER@` filled in at install | | [`agent/`](agent) | each agent host, by what it can run | `make install-agent-collectors AGENT=user@host` | a collector copied to `/usr/local/bin`; an agent host has no checkout | | [`host/`](host) | `prometheus` | `make install-host-units` | nothing: boot ordering, not a schedule. Docker waits for `10.0.99.20` ([ADR-0105](../docs/adr/0105-hold-docker-until-the-monitoring-hosts-address-exists.md)) | +| [`range/`](range) | `gandalf` | by hand, [`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §7 | `scripts/range-poweroff.sh`, copied to `/usr/local/sbin`. The range's power-off backstop, every 5 min ([ADR-0124](../docs/adr/0124-power-gandalf-off-on-a-timer.md)); it reports nothing, by ADR-0017 | The estate's units name the deployment checkout's absolute path, because the live stack runs from that checkout and nowhere else, and `install-timers.sh diff --git a/systemd/range/homelab-range-poweroff.service b/systemd/range/homelab-range-poweroff.service new file mode 100644 index 00000000..12839975 --- /dev/null +++ b/systemd/range/homelab-range-poweroff.service @@ -0,0 +1,38 @@ +# The range's power-off backstop (ADR-0124, #1647). It runs on gandalf only, +# which has no checkout of this repository and no agent, so this unit calls +# the script directly, the way systemd/agent/ units do. Nothing reports its +# outcome to Prometheus: ADR-0017 gives the range no monitoring, and +# build-the-playground.md §7's read-back is what checks the timer is on. +# +# RUNS AS ROOT because powering off and writing to every terminal need it. +# The state directory under /run is the only path it writes. The directory +# is kept when the unit stops, because the deadline and the warnings +# already sent have to survive from one run to the next. +# +# The script is installed at /usr/local/sbin/homelab-range-poweroff by +# build-the-playground.md §7, which also installs this file. +[Unit] +Description=HomeLab: power gandalf off at the range deadline (ADR-0124) +Documentation=https://github.com/Gerrrt/HomeLab/blob/main/docs/runbooks/build-the-playground.md + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/homelab-range-poweroff check +TimeoutStartSec=60 +Restart=no +RuntimeDirectory=homelab-range-poweroff +RuntimeDirectoryPreserve=yes +NoNewPrivileges=true +RestrictSUIDSGID=true +LockPersonality=true +RestrictRealtime=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true +RestrictAddressFamilies=AF_UNIX +StandardOutput=journal +StandardError=journal +SyslogIdentifier=homelab-range-poweroff diff --git a/systemd/range/homelab-range-poweroff.timer b/systemd/range/homelab-range-poweroff.timer new file mode 100644 index 00000000..8b98c0ef --- /dev/null +++ b/systemd/range/homelab-range-poweroff.timer @@ -0,0 +1,19 @@ +[Unit] +Description=HomeLab: power gandalf off at the range deadline (ADR-0124) +Documentation=https://github.com/Gerrrt/HomeLab/blob/main/docs/runbooks/build-the-playground.md + +[Timer] +Unit=homelab-range-poweroff.service +# Every five minutes from five minutes after boot. The script decides; the +# timer only asks. Five minutes puts exactly one run inside the last five +# before the deadline, which is what the 5-minute warning relies on, and it +# is the most the power-off can lag the deadline by. +# +# No Persistent=: a run missed while the box was off has nothing to catch +# up on, because the deadline is counted from this boot. +OnBootSec=5min +OnUnitActiveSec=5min +AccuracySec=30s + +[Install] +WantedBy=timers.target From 3b73c45e3ee23443ebe291cf21fe81b2005d75f6 Mon Sep 17 00:00:00 2001 From: Gerrrt Date: Sun, 22 Nov 2026 17:44:35 -0800 Subject: [PATCH 2/3] docs(range): record the power-off timer installed on gandalf Installed 2026-11-22 17:44 from this branch by section 7's commands. The self-test passed, the deadline was 23:44, a run by hand succeeded, and the timer is enabled and active. The one-power-off proof is not yet run. Refs #1647. Co-Authored-By: Claude Opus 5.5 --- docs/changelog.md | 6 ++++-- docs/roadmap.md | 4 ++-- docs/runbooks/build-the-playground.md | 10 ++++++++-- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/docs/changelog.md b/docs/changelog.md index 1bb1cb2c..011f6571 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -37,8 +37,10 @@ docstring gives: it is a record, not a claim about now. - `systemd-analyze verify` on `gandalf` reported only that the script was not installed yet. - Nothing is installed on `gandalf`, and the one-power-off proof in §7 has - not been run. + It was installed on `gandalf` the same evening at 17:44, from this + branch, by §7's commands: `self-test-ok`, a deadline of 23:44, and a run + by hand ending `Result=success`. The timer read `enabled` and `active`. + The one-power-off proof in §7 has not been run. - **`gandalf` will power itself off on a timer ([ADR-0124](adr/0124-power-gandalf-off-on-a-timer.md)).** Both audits of diff --git a/docs/roadmap.md b/docs/roadmap.md index 36c76e39..b25ff6f0 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -43,8 +43,8 @@ Closes when it is empty. - **[#1647](https://github.com/Gerrrt/HomeLab/issues/1647) Power `gandalf` off on a timer.** Decided by [ADR-0124](adr/0124-power-gandalf-off-on-a-timer.md). No gate. The script - and its units are in the repository. Left: install them on `gandalf` and - prove one power-off, both in `build-the-playground.md` §7. Until then the + and its units are in the repository and installed on `gandalf`. Left: prove + one power-off, `build-the-playground.md` §7. Until then the range's "off between sessions" rests on the operator, and two audits found it left on. - **[#1226](https://github.com/Gerrrt/HomeLab/issues/1226) The HomePods in diff --git a/docs/runbooks/build-the-playground.md b/docs/runbooks/build-the-playground.md index 92402158..d8d23fed 100644 --- a/docs/runbooks/build-the-playground.md +++ b/docs/runbooks/build-the-playground.md @@ -1083,7 +1083,7 @@ after boot by default or what the last `range-extend` set (1 to 12 hours ahead), with a warning on every shell 30 and 5 minutes before ([#1647](https://github.com/Gerrrt/HomeLab/issues/1647)). The power-off at the end below is still the plan. The timer is what happens when the plan is -forgotten. **Not yet installed on `gandalf`.** +forgotten. Installed on `gandalf` on 2026-11-22, below. ```text on → read the firewall back → revert every target to `clean` → work → revert → off @@ -1173,7 +1173,13 @@ Check `status` from a shell when you start one. `journalctl -t homelab-range-poweroff -b -1` at the next power-on should end with `powering gandalf off`. -Record the result here. **Not yet run on `gandalf`.** +> **Installed on `gandalf` 2026-11-22 at 17:44**, from #1649's branch +> before it merged, by the commands above. The output was `self-test-ok`, +> nothing from `systemd-analyze`, and a deadline of 23:44. A run of the +> service by hand ended `Result=success`. The timer read `enabled` and +> `active`, with its next run five minutes out. + +Record the proof's result here. **Not yet run on `gandalf`.** --- From 79c66168f83732501c6b448021d95c755bc3588a Mon Sep 17 00:00:00 2001 From: Gerrrt Date: Sun, 22 Nov 2026 17:52:23 -0800 Subject: [PATCH 3/3] fix(range): lock check and extend, and run the power-off check every minute Review on #1649 caught two problems: - Without a lock, a check that had read the old deadline could power off after range-extend reported success, and two extensions shared one temporary file. check and extend now hold one flock for the whole operation, and the temporary file is unique. - A five-minute timer equals the five-minute warning window, so a late run could skip the last warning. The timer now runs every minute with AccuracySec=5s. Two fixtures prove the lock's interleavings. They skip where there is no flock (macOS) and both fail with the lock removed. The self-test has 21 fixtures and passed under gandalf's bash. Reinstalled on gandalf. Refs #1647. Co-Authored-By: Claude Opus 5.5 --- docs/changelog.md | 22 +++--- docs/runbooks/build-the-playground.md | 9 ++- scripts/README.md | 2 +- scripts/range-poweroff.sh | 78 +++++++++++++++++++--- systemd/README.md | 2 +- systemd/range/homelab-range-poweroff.timer | 19 ++++-- 6 files changed, 103 insertions(+), 29 deletions(-) diff --git a/docs/changelog.md b/docs/changelog.md index 011f6571..6022b8ed 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -24,14 +24,18 @@ docstring gives: it is a record, not a claim about now. ADR-0124 in the repository. `scripts/range-poweroff.sh` holds the deadline under `/run`, sends the 30- and 5-minute `wall` warnings, waits while `dpkg` holds its lock, and powers off. Linked as `range-extend`, it sets the - deadline 1 to 12 hours from now. `systemd/range/` runs it every five - minutes. `build-the-playground.md` §7 gains *The power-off timer*, which - installs it from Hicks with a `range-extend 6` first, so an install on a box - already up six hours does not power it off five minutes later. The - read-back checks the timer is enabled and active. - - The `--self-test` has 18 fixtures, and `self-tests.sh` runs it in CI. - - Each of three deliberate breaks failed at least one fixture: no `dpkg` - wait, no extension cap, no 5-minute warning. + deadline 1 to 12 hours from now. `systemd/range/` runs it every + minute. `check` and `extend` hold one lock, so a check never acts on a + deadline an extension has just replaced. Review on the PR caught both: a + five-minute timer could skip the last warning, and the unlocked version + could act on a replaced deadline. `build-the-playground.md` §7 gains *The + power-off timer*, which installs it from Hicks with a `range-extend 6` + first, so an install on a box already up six hours does not power it off a + minute later. The read-back checks the timer is enabled and active. + - The `--self-test` has 21 fixtures, and `self-tests.sh` runs it in CI. + The two lock interleavings skip where there is no `flock`, as on macOS. + - Four deliberate breaks each failed at least one fixture: no `dpkg` wait, + no extension cap, no 5-minute warning, and no lock. - It passed under `gandalf`'s own bash, run from standard input without installing anything. - `systemd-analyze verify` on `gandalf` reported only that the script was @@ -40,6 +44,8 @@ docstring gives: it is a record, not a claim about now. It was installed on `gandalf` the same evening at 17:44, from this branch, by §7's commands: `self-test-ok`, a deadline of 23:44, and a run by hand ending `Result=success`. The timer read `enabled` and `active`. + The every-minute timer and the lock were reinstalled the same way after + review. The one-power-off proof in §7 has not been run. - **`gandalf` will power itself off on a timer diff --git a/docs/runbooks/build-the-playground.md b/docs/runbooks/build-the-playground.md index 041ae690..49f78ea2 100644 --- a/docs/runbooks/build-the-playground.md +++ b/docs/runbooks/build-the-playground.md @@ -1146,8 +1146,8 @@ ssh "$G" 'chmod 0755 /usr/local/sbin/homelab-range-poweroff && **You should see** `self-test-ok`, no output from `systemd-analyze`, and a deadline six hours from now. The `range-extend 6` before the enable is deliberate. Without it the deadline is six hours after *this* boot, and on a -box that has been up longer than that, the first run powers it off five -minutes after the install. The self-test exercises every branch with +box that has been up longer than that, the first run powers it off a +minute after the install. The self-test exercises every branch with fakes, so it can run on the host without powering anything off. Running it, as root on `gandalf`: @@ -1177,7 +1177,10 @@ Check `status` from a shell when you start one. > before it merged, by the commands above. The output was `self-test-ok`, > nothing from `systemd-analyze`, and a deadline of 23:44. A run of the > service by hand ended `Result=success`. The timer read `enabled` and -> `active`, with its next run five minutes out. +> `active`, with its next run five minutes out. That install had the first +> timer, every five minutes. Review on #1649 moved it to every minute and +> added the lock. The new files were reinstalled the same way, and the +> self-test ran 21 fixtures on the box. Record the proof's result here. **Not yet run on `gandalf`.** diff --git a/scripts/README.md b/scripts/README.md index a8592230..bd833c01 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -162,7 +162,7 @@ They need the running estate, so CI cannot run them. Timers do. | `capture-screenshots.sh` | `screenshots` | Renders the dashboards into [`docs/images/`](../docs/images/README.md) | | `packer-smoke.sh` | — | Clones a Packer template, boots it, checks it and destroys it ([`packer/`](../packer/README.md)) | | `finish-attack-vm.sh` | — | Finishes the range's attack VM, `ragnarok`, after `tofu/` makes it on `gandalf` from 902 ([ADR-0116](../docs/adr/0116-build-the-range-attack-vm-with-opentofu-and-prove-it-with-a-script.md)): writes `99-no-forward.conf` and ADR-0014's outbound scope as an nftables policy, at the IP stack and at `eth0`'s egress for raw Ethernet, and proves it neither forwards, NATs nor reaches past `10.0.30.0/24` and the range, over SSH checked against a host key read through the guest agent ([`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §5) | -| `range-poweroff.sh` | — | Powers `gandalf` off six hours after boot or after the last `range-extend`, warning on every shell at 30 and 5 minutes, and never while `dpkg` holds its lock ([ADR-0124](../docs/adr/0124-power-gandalf-off-on-a-timer.md)). Installed with [`systemd/range/`](../systemd/range) by [`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §7. Its `--self-test` is the only test of the deadline logic: a real run powers the range host off | +| `range-poweroff.sh` | — | Powers `gandalf` off at a deadline, six hours after boot or what the last `range-extend` set (1 to 12 hours ahead), checked every minute under one lock, warning on every shell at 30 and 5 minutes, and never while `dpkg` holds its lock ([ADR-0124](../docs/adr/0124-power-gandalf-off-on-a-timer.md)). Installed with [`systemd/range/`](../systemd/range) by [`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §7. Its `--self-test` is the only test of the deadline logic: a real run powers the range host off | | `stage-agent-msis.sh` | — | Stages the Wazuh and Velociraptor MSIs the lab pipeline installs, and the two Debian packages `garuda` installs, into `${SOC_DATA_DIR}/agent-msi` on `odin`, which the SOC stack's Caddy serves. The vendor packages are checked against their pins; the Velociraptor `.deb` is built by the server and its hash printed ([#1068](https://github.com/Gerrrt/HomeLab/issues/1068), [ADR-0092](../docs/adr/0092-enrol-garuda-in-odins-soc-with-debian-packages-staged-on-odin.md)) | | `lab-known-hosts.sh` | — | Reads the lab domain's SSH host keys through the guest agent into `ansible/.known_hosts`, after any rebuild ([ADR-0085](../docs/adr/0085-check-the-lab-domains-host-keys-against-keys-read-through-the-guest-agent.md)) | | `gen_population.py` | — | The lab domain's users, into `ansible/population/` | diff --git a/scripts/range-poweroff.sh b/scripts/range-poweroff.sh index d49e20b5..af7b449b 100755 --- a/scripts/range-poweroff.sh +++ b/scripts/range-poweroff.sh @@ -16,10 +16,17 @@ # it" cannot quietly switch the backstop off. # # THE WARNINGS go to every shell through `wall`: once at 30 minutes or -# less, once at 5 or less. The timer runs this every five minutes, so -# exactly one run falls inside the last five. A warning is recorded -# against the deadline it was for, so an extension re-arms both without -# clearing anything. +# less, once at 5 or less. The timer runs this every minute, well inside +# the five-minute window, so a late run cannot skip the last warning (at +# five minutes it could: review on #1649). A warning is recorded against the +# deadline it was for, so an extension re-arms both without clearing +# anything. +# +# ONE LOCK. `check` and `extend` each hold an flock on the state +# directory's lock file for the whole operation, the power-off request +# included. Without it, a check that had read the old deadline could power +# off after `range-extend` reported success, and two extensions could race +# on one temporary file (review on #1649). # # IT NEVER POWERS OFF IN THE MIDDLE OF A PACKAGE INSTALL. While something # holds dpkg's lock, a run past the deadline logs that it is waiting and @@ -42,6 +49,7 @@ STATE_DIR="${RANGE_STATE_DIR:-/run/homelab-range-poweroff}" now() { date +%s; } boot_time() { awk '/^btime /{print $2}' /proc/stat; } dpkg_busy() { fuser -s /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock 2>/dev/null; } +take_lock() { flock -w 30 9; } say() { logger -t homelab-range-poweroff -- "$*" 2>/dev/null || true; printf '%s\n' "$*"; } warn_all() { wall -- "$*" 2>/dev/null || true; } power_off() { systemctl poweroff; } @@ -58,9 +66,22 @@ read_state() { write_state() { # Write then rename, so a reader never sees half a number. + # The temporary name is unique, so two writers never share one. + local tmp + mkdir -p "${STATE_DIR}" + tmp="$(mktemp "${STATE_DIR}/.$1.XXXXXX")" + printf '%s\n' "$2" > "${tmp}" + mv -f "${tmp}" "${STATE_DIR}/$1" +} + +with_lock() { + # Run "$@" holding the lock. fd 9 closes when the group ends, which + # releases it, so nothing outlives the operation. mkdir -p "${STATE_DIR}" - printf '%s\n' "$2" > "${STATE_DIR}/$1.tmp" - mv -f "${STATE_DIR}/$1.tmp" "${STATE_DIR}/$1" + { + take_lock || { say "could not take ${STATE_DIR}/lock in 30 s"; return 1; } + "$@" + } 9>"${STATE_DIR}/lock" } deadline() { @@ -74,7 +95,9 @@ minutes_left() { printf '%s' "$(( ($1 + 59) / 60 ))"; } fmt_time() { date -d "@$1" '+%Y-%m-%d %H:%M' 2>/dev/null || date -r "$1" '+%Y-%m-%d %H:%M'; } -cmd_check() { +cmd_check() { with_lock check_locked; } + +check_locked() { local t d left mins t="$(now)" d="$(deadline)" @@ -108,12 +131,16 @@ cmd_check() { } cmd_extend() { - local h="${1:-}" t d + local h="${1:-}" if ! is_uint "${h}" || (( 10#${h} < 1 || 10#${h} > MAX_EXTEND )); then printf 'usage: range-extend , a whole number from 1 to %d\n' "${MAX_EXTEND}" >&2 return 2 fi - h=$(( 10#${h} )) + with_lock extend_locked "$(( 10#${h} ))" +} + +extend_locked() { + local h="$1" t d t="$(now)" d=$(( t + h * 3600 )) write_state deadline "${d}" @@ -153,6 +180,11 @@ self_test() { say() { :; } warn_all() { printf '%s\n' "$*" >> "${WALL_LOG}"; } power_off() { printf 'off\n' >> "${OFF_LOG}"; } + local HAVE_FLOCK=1 + if ! command -v flock >/dev/null 2>&1; then + HAVE_FLOCK=0 + take_lock() { :; } + fi reset() { rm -rf "${STATE_DIR}" "${WALL_LOG}" "${OFF_LOG}"; BUSY=1; } walls() { [[ -f "${WALL_LOG}" ]] && wc -l < "${WALL_LOG}" | tr -d ' ' || printf 0; } @@ -208,6 +240,34 @@ self_test() { reset; mkdir -p "${STATE_DIR}"; printf 'garbage\n' > "${STATE_DIR}/deadline" check "an unreadable deadline file falls back to six hours after boot" "$(deadline)" "$((BOOT + 6 * H))" + # The two interleavings the lock exists for. The test holds the lock on + # fd 8, starts the other operation in the background, does what the + # lock's holder would do, and lets go. + if ((HAVE_FLOCK)); then + local pid + reset; mkdir -p "${STATE_DIR}"; NOW=$((BOOT + 6 * H + 10)) + exec 8>"${STATE_DIR}/lock"; flock 8 + # 8>&-: the child must not inherit the test's hold on the lock, or it + # waits on itself until the timeout. + cmd_check 8>&- & pid=$! + sleep 0.3 + write_state deadline "$((NOW + H))" + exec 8>&- + wait "${pid}" + check "a check waiting on the lock reads the deadline the extension wrote" "$(offs)" "0" + + reset; mkdir -p "${STATE_DIR}"; NOW=$((BOOT + H)) + exec 8>"${STATE_DIR}/lock"; flock 8 + cmd_extend 2 >/dev/null 8>&- & pid=$! + sleep 0.3 + check "an extension waits while a check holds the lock" "$(read_state deadline)" "" + exec 8>&- + wait "${pid}" + check "and writes its deadline once the check lets go" "$(read_state deadline)" "$((NOW + 2 * H))" + else + printf '\033[0;33m SKIP\033[0m the two lock interleavings: no flock on this host\n' + fi + ((failed == 0)) } diff --git a/systemd/README.md b/systemd/README.md index 9dc782dc..09185cdc 100644 --- a/systemd/README.md +++ b/systemd/README.md @@ -31,7 +31,7 @@ job goes stale, is | [`sensitive/`](sensitive) | `trinity` | `make install-timers ARGS="--profile sensitive"` | the same, with `@DEPLOY_ROOT@` and `@RUN_USER@` filled in at install | | [`agent/`](agent) | each agent host, by what it can run | `make install-agent-collectors AGENT=user@host` | a collector copied to `/usr/local/bin`; an agent host has no checkout | | [`host/`](host) | `prometheus` | `make install-host-units` | nothing: boot ordering, not a schedule. Docker waits for `10.0.99.20` ([ADR-0105](../docs/adr/0105-hold-docker-until-the-monitoring-hosts-address-exists.md)) | -| [`range/`](range) | `gandalf` | by hand, [`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §7 | `scripts/range-poweroff.sh`, copied to `/usr/local/sbin`. The range's power-off backstop, every 5 min ([ADR-0124](../docs/adr/0124-power-gandalf-off-on-a-timer.md)); it reports nothing, by ADR-0017 | +| [`range/`](range) | `gandalf` | by hand, [`build-the-playground.md`](../docs/runbooks/build-the-playground.md) §7 | `scripts/range-poweroff.sh`, copied to `/usr/local/sbin`. The range's power-off backstop, every minute ([ADR-0124](../docs/adr/0124-power-gandalf-off-on-a-timer.md)); it reports nothing, by ADR-0017 | The estate's units name the deployment checkout's absolute path, because the live stack runs from that checkout and nowhere else, and `install-timers.sh diff --git a/systemd/range/homelab-range-poweroff.timer b/systemd/range/homelab-range-poweroff.timer index 8b98c0ef..452aad7e 100644 --- a/systemd/range/homelab-range-poweroff.timer +++ b/systemd/range/homelab-range-poweroff.timer @@ -4,16 +4,21 @@ Documentation=https://github.com/Gerrrt/HomeLab/blob/main/docs/runbooks/build-th [Timer] Unit=homelab-range-poweroff.service -# Every five minutes from five minutes after boot. The script decides; the -# timer only asks. Five minutes puts exactly one run inside the last five -# before the deadline, which is what the 5-minute warning relies on, and it -# is the most the power-off can lag the deadline by. +# Every minute from a minute after boot. The script decides; the timer only +# asks. The period has to sit well inside the five-minute warning window. +# At five minutes, a run that came a little late could land past the +# deadline having skipped the window, and power off with no last warning +# (review on #1649). A minute is also about how far the power-off lags the +# deadline. A run is a few reads of /run and costs nothing. +# +# AccuracySec is tight for the same reason. systemd's default of a minute +# would let a run slip by a whole period. # # No Persistent=: a run missed while the box was off has nothing to catch # up on, because the deadline is counted from this boot. -OnBootSec=5min -OnUnitActiveSec=5min -AccuracySec=30s +OnBootSec=1min +OnUnitActiveSec=1min +AccuracySec=5s [Install] WantedBy=timers.target