From 11e62209ae9f58aa6dc5e5579d2ef6f98c4fc67f Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:32:44 -0600 Subject: [PATCH 001/112] fix(lint): stop shellcheck re-analysing sourced files; budget every file (#4029) tests/os/selftest-migration-boot.sh sourced the generated CLI and pithead-boot nine times through variable paths, which shellcheck -x resolves and re-analyses per source line: 16.4 GiB and 464 s for one file, OOM-killing the 2.0.3 release-server lint gate and adding about four minutes to every CI Shell lint run. Point those source lines at /dev/null and refuse any file that holds the pinned shellcheck past SHELLCHECK_FILE_BUDGET seconds. Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Code --- Makefile | 4 ++- docs/dev/testing-strategy.md | 7 ++++- scripts/lint/shellcheck-budget.sh | 36 ++++++++++++++++++++++ tests/os/selftest-migration-boot.sh | 9 ++++++ tests/os/selftest-shellcheck-budget.sh | 41 ++++++++++++++++++++++++++ 5 files changed, 95 insertions(+), 2 deletions(-) create mode 100644 scripts/lint/shellcheck-budget.sh create mode 100644 tests/os/selftest-shellcheck-budget.sh diff --git a/Makefile b/Makefile index 8876ecde39..18c75b6529 100644 --- a/Makefile +++ b/Makefile @@ -111,6 +111,8 @@ SHELLCHECK_VERSION := 0.11.0 # is tied to one binary and fails loudly until it matches. SHFMT_VERSION := 3.13.1 +SHELLCHECK_FILE_BUDGET := 120 + print-shellcheck-version: ## Print the pinned shellcheck version (ci.yml's installer reads this) @echo $(SHELLCHECK_VERSION) @@ -148,7 +150,7 @@ lint-sh: pithead ## shellcheck + shfmt over the CLI, build/* + dashboard/ contai os/overlay/pithead-machine-id os/overlay/pithead-media-config os/overlay/pithead-hugepages os/overlay/pithead-address-watch os/overlay/pithead-miner-recovery os/overlay/pithead-serial-port-present \ os/overlay/pithead-journal-persist os/overlay/pithead-boot os/overlay/pithead-boot-stack-health os/overlay/pithead-boot-version \ tests/os/*.sh tests/os/*/*.sh tests/netwatch/*.sh \ - | xargs -0 -n 1 -P 4 shellcheck -x --severity=warning + | xargs -0 -n 1 -P 4 bash scripts/lint/shellcheck-budget.sh $(SHELLCHECK_FILE_BUDGET) # CLI slices are checked through the generated pithead above: their semantic context # depends on concatenation order. Listing them separately duplicates a large analysis # and reports false unused-global warnings. shfmt checks every slice independently. diff --git a/docs/dev/testing-strategy.md b/docs/dev/testing-strategy.md index fbd1e48d8f..be18c8da4b 100644 --- a/docs/dev/testing-strategy.md +++ b/docs/dev/testing-strategy.md @@ -673,7 +673,12 @@ Two host-level constraints apply to the container itself: sampled 2.7 GiB in total. The symptom of a shortfall is a bare `Killed` after the shellcheck line, naming neither memory nor a file, so raise the allocation before running the full `make test` in the container. Every other target measured here fits comfortably; - `test-container` warns when the engine is below the bar. + `test-container` warns when the engine is below the bar. No single file may hold a check past + `SHELLCHECK_FILE_BUDGET` seconds (120): `scripts/lint/shellcheck-budget.sh` kills it at the + budget and names the file (#4026). A test that sources a variable path like `"$ROOT/pithead"` + is followed by `-x` and re-analyses the sourced file once per source line, so such a suite + puts `# shellcheck source=/dev/null` above those lines when the sourced file is linted on + its own. - **The Docker socket.** Tiers 1 (netwatch), 3, `test-compose` and `lint-proto` all shell out to Docker, so the container is given the host's socket. That is host-root-equivalent access by itself; it is the same trust the tiers already need when run directly on the host. diff --git a/scripts/lint/shellcheck-budget.sh b/scripts/lint/shellcheck-budget.sh new file mode 100644 index 0000000000..5d476fae92 --- /dev/null +++ b/scripts/lint/shellcheck-budget.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [ "$#" -lt 2 ]; then + printf 'usage: %s [command ...]\n' "$0" >&2 + exit 2 +fi +budget=$1 +file=$2 +shift 2 +if [[ ! "$budget" =~ ^[1-9][0-9]*$ ]]; then + printf 'shellcheck-budget: budget must be a positive integer of seconds, got [%s]\n' "$budget" >&2 + exit 2 +fi +if [ "$#" -eq 0 ]; then + set -- shellcheck -x --severity=warning "$file" +fi +"$@" & +child=$! +while kill -0 "$child" 2>/dev/null; do + if [ "$SECONDS" -ge "$budget" ]; then + kill "$child" 2>/dev/null || true + waited=0 + while kill -0 "$child" 2>/dev/null && [ "$waited" -lt 300 ]; do + sleep 0.1 + waited=$((waited + 1)) + done + kill -9 "$child" 2>/dev/null || true + wait "$child" 2>/dev/null || true + printf 'lint-sh: %s held the pinned shellcheck past its %s second budget; put "# shellcheck source=/dev/null" above source lines that follow another linted file\n' \ + "$file" "$budget" >&2 + exit 1 + fi + sleep 0.1 +done +wait "$child" diff --git a/tests/os/selftest-migration-boot.sh b/tests/os/selftest-migration-boot.sh index fdbc6c5df9..d1b05811e7 100755 --- a/tests/os/selftest-migration-boot.sh +++ b/tests/os/selftest-migration-boot.sh @@ -125,6 +125,7 @@ ownership_case() ( local dir="$1" slot="$2" block cd "$dir" || exit 99 fixture_env "$dir" "$slot" + # shellcheck source=/dev/null source "$ROOT/os/overlay/pithead-boot" fail_boot() { printf 'fail %s\n' "$*" >>"$dir/calls" @@ -162,9 +163,11 @@ gate_case() ( export RAUC_MARK_BAD_RC="${CASE_MARK_BAD_RC:-0}" export SYNC_FAIL_COMMIT="${CASE_SYNC_FAIL_COMMIT:-0}" export SYNC_FAIL_FLOOR="${CASE_SYNC_FAIL_FLOOR:-0}" + # shellcheck source=/dev/null source "$dir/pithead" # shellcheck disable=SC2034 # read by the extracted production loop migration_fingerprint=$(os_migration_fingerprint) + # shellcheck source=/dev/null PITHEAD_RELEASE_UP_TRIES=1 PITHEAD_RELEASE_UP_PAUSE=0 source "$ROOT/os/overlay/pithead-boot" # shellcheck disable=SC2034 # read by the extracted production loop gate_doctor_ran=0 gate_advisory="" hold_chain="$hold" OS_INFLIGHT="$dir/absent" @@ -224,6 +227,7 @@ set +e ( cd "$EMPTY" || exit 99 fixture_env "$EMPTY" A + # shellcheck source=/dev/null source "$ROOT/os/overlay/pithead-boot" clear_migration_hold '' ) @@ -254,12 +258,14 @@ if [ "$(uname -s)" = Linux ]; then OLD_FINGERPRINT=$( cd "$RACE" || exit 99 fixture_env "$RACE" A + # shellcheck source=/dev/null source "$RACE/pithead" os_migration_fingerprint ) ( cd "$RACE" || exit 99 fixture_env "$RACE" A + # shellcheck source=/dev/null source "$RACE/pithead" exec 8>"$PITHEAD_LOCK_FILE" flock 8 @@ -278,6 +284,7 @@ if [ "$(uname -s)" = Linux ]; then ( cd "$RACE" || exit 99 fixture_env "$RACE" A + # shellcheck source=/dev/null source "$ROOT/os/overlay/pithead-boot" : >cleanup-started restore_data_floor_after_fallback "$OLD_FINGERPRINT" @@ -317,6 +324,7 @@ rig_case() ( cd "$dir" || exit 99 fixture_env "$dir" B printf 'rig\n' >machine-role + # shellcheck source=/dev/null source "$ROOT/os/overlay/pithead-boot" fail_boot() { exit 1; } boot_gate_passed() { printf 'gate-passed\n' >>"$dir/calls"; } @@ -339,6 +347,7 @@ assert_call "$RIG" 'pithead local-miner' ( cd "$RIG" || exit 99 fixture_env "$RIG" B + # shellcheck source=/dev/null source "$RIG/pithead" set +e os_prepare_migration_hold diff --git a/tests/os/selftest-shellcheck-budget.sh b/tests/os/selftest-shellcheck-budget.sh new file mode 100644 index 0000000000..e5f7e53b18 --- /dev/null +++ b/tests/os/selftest-shellcheck-budget.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +: "${TMPDIR:=/tmp}" +T=$(mktemp -d "$TMPDIR/shellcheck-budget.XXXXXX") +trap 'rm -rf "$T"' EXIT + +guard="$ROOT/scripts/lint/shellcheck-budget.sh" +label="$T/slow-file.sh" + +fail() { + printf 'selftest-shellcheck-budget: FAIL: %s\n' "$*" >&2 + exit 1 +} + +bash "$guard" 30 "$label" true || fail 'a command inside the budget must pass through' + +rc=0 +bash "$guard" 30 "$label" sh -c 'exit 3' || rc=$? +[ "$rc" -eq 3 ] || fail "a command failing inside the budget must keep its status, got $rc" + +start=$SECONDS +rc=0 +out=$(bash "$guard" 1 "$label" sleep 45678 2>&1) || rc=$? +elapsed=$((SECONDS - start)) +[ "$rc" -ne 0 ] || fail 'a command past the budget must fail' +[ "$elapsed" -lt 10 ] || fail "a past-budget command was still running after ${elapsed}s" +! pgrep -f 'sleep 45678' >/dev/null || fail 'the past-budget command was not killed' +grep -Fq "$label" <<<"$out" || fail 'the budget failure must name the file' +grep -Fq 'budget' <<<"$out" || fail 'the budget failure must name the budget' +grep -Fq 'source=/dev/null' <<<"$out" || fail 'the budget failure must point at the source hint' + +rc=0 +bash "$guard" 0 "$label" true >/dev/null 2>&1 || rc=$? +[ "$rc" -eq 2 ] || fail "a zero budget must be refused, got $rc" +rc=0 +bash "$guard" "$label" true >/dev/null 2>&1 || rc=$? +[ "$rc" -eq 2 ] || fail "a missing budget must be refused, got $rc" + +printf 'selftest-shellcheck-budget: PASS\n' From de6461085816e72e19089a3ca6dd6a4a24efabcd Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:33:00 -0600 Subject: [PATCH 002/112] Bring the battery and release docs in line with the automated rig legs and the split gate (#4027) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs: bring the battery and release docs in line with the automated rig legs and the split gate rig-battery.md: mark M11's accepted share automated by the rig phase's share leg (#2063), mark M12 manual on develop with the leg that automates it (#3717, on the 2.1.0 line; backport tracked as #3994), and cite the open #3995 for the Keep-everything gap instead of the closed #3961. releasing.md: submit the rig group as the four splits the last three gates actually ran (rig+rigmedia+media; fault+reset; image-upgrade; stack) and put boot plus every split id in the gate e2e after. selftest-release-status-recipe.sh pins the new recipe shape. appliance-release.md: show the data-migration declaration as a per-release choice — migrating true X.Y.Z next to the non-migrating false form — so a copied cut cannot declare a migration it does not run. Closes #3997 Co-Authored-By: Claude Code * docs: clear the closed-issue cites beside the corrected battery rows The verifier pass found two surviving pointers for the Keep-everything and adopt/config-push gaps: docs/appliance.md still owed the M13 proof to closed #3961, and the appliance-release battery summary still tracked M11-M13 on closed #1886 though the live trackers are #3994 and #3995. Name the split group by the three release gates that ran it, the in-repo record, not by nightly config. Refs #3997 Co-Authored-By: Claude Code --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Code --- docs/appliance.md | 2 +- docs/dev/appliance-release.md | 23 ++++---- docs/dev/manual-qa/appliance/rig-battery.md | 28 ++++++---- docs/dev/releasing.md | 52 +++++++++++++------ .../selftest-release-status-recipe.sh | 30 ++++++----- 5 files changed, 85 insertions(+), 50 deletions(-) diff --git a/docs/appliance.md b/docs/appliance.md index fc3bfc58b9..48e9de6b8d 100644 --- a/docs/appliance.md +++ b/docs/appliance.md @@ -547,7 +547,7 @@ boots: rig comes back with the same role, the same `rig.json` and the same access token, starts mining again, and a coordinator that had adopted the rig keeps reading it with no adopting to redo. No leg has run that pass on an adopted coordinated rig - yet: manual QA row M13 is the proof still owed (#3961). + yet: manual QA row M13 is the proof still owed (#3995). - **Running from its USB stick:** re-flash the stick with the newer image. Re-flashing replaces the whole stick, data included, so the rig comes back with a fresh setup and a new token, and the coordinator adopts it again. Delivering image updates to diff --git a/docs/dev/appliance-release.md b/docs/dev/appliance-release.md index 57ccb6dd4d..b2520cdd9b 100644 --- a/docs/dev/appliance-release.md +++ b/docs/dev/appliance-release.md @@ -294,8 +294,9 @@ a new one: ```sh PITHEAD_RAUC_CERT=/os/rauc/certs/cert.pem \ PITHEAD_RAUC_KEY=/os/rauc/certs/key.pem \ -PITHEAD_DATA_MIGRATION=true PITHEAD_MIN_OS_VERSION=2.0.0 \ - os/rauc/mkbundle.sh # no --dev: naming the key IS the signal, so declare the migration fields +PITHEAD_DATA_MIGRATION=false PITHEAD_MIN_OS_VERSION= \ + os/rauc/mkbundle.sh # no --dev: naming the key IS the signal, so declare the migration fields — + # this bundle does not migrate; a migrating one declares true and X.Y.Z ``` Confirm before copying anything, by comparing fingerprints — the target's trusted chain is at @@ -471,9 +472,8 @@ internal disk and answers RigForge without installing, and asserts the rig mines no containers, volatile journald, an unaided reboot returns it mining, and the blank disk stays untouched; it does not touch the bootloader "Set up again" path (#1318), which stays whatever reaches the wizard again from a stick-run rig needs by hand. No bench release e2e scenario for the -rig role exists yet. Converting M11–M13, and naming a bench e2e for what KVM cannot prove, is -tracked as #1886's first gap; the numbering here stays stable so old release records still point -at the same steps once that lands. +rig role exists yet. Converting what is left of M11–M13 is tracked as #3994 and #3995; the +numbering here stays stable so old release records still point at the same steps once those land. **M15 — backup and restore end to end.** On a provisioned machine, record the payout wallet, the dashboard's onion address, and the current time. From **Backup**, create a backup and save @@ -544,11 +544,11 @@ channels share the final cut commit, one version and one GitHub Release. operator-visible change included since prep and set its heading to the current UTC date. `release.sh` publishes that heading verbatim. Every gate, build and tag below uses that final cut commit. Run `make lint && make test`. Do not hand-run the KVM battery on this commit: - submit the four bench-ci `tier4-kvm` jobs on this exact SHA from + submit the seven bench-ci `tier4-kvm` jobs on this exact SHA from [Releasing § Which gates are automated](releasing.md#which-gates-are-automated-and-which-are-not): - the boot and rig groups, the provision job against the seeded baseline and the crossupdate job - from the previous release. Record every job ID in the release issue. Follow the same section for - wallet preparation and the final status-gated e2e leg. An e2e failure must not cancel any KVM + the boot group, the rig group as its four splits, the provision job against the seeded baseline + and the crossupdate job from the previous release. Record every job ID in the release issue. + Follow the same section for wallet preparation and the final status-gated e2e leg. An e2e failure must not cancel any KVM job. Stage 1 requires a green `bench-ci/tier4` status on this SHA. `make lint-sh` refuses to run on any shellcheck but the pinned one and names the version it found alongside the one it wants; `make -s print-shellcheck-version` prints the pin. @@ -573,8 +573,9 @@ channels share the final cut commit, one version and one GitHub Release. export PITHEAD_RAUC_KEYRING=~/.config/pithead-release/rauc-root.pem export PITHEAD_RAUC_CERT=~/.config/pithead-release/rauc-signer.pem export PITHEAD_RAUC_KEY=~/.config/pithead-release/rauc-signer.key - # declare the data-migration contract above, migrating or not (2.0.0: true and 2.0.0) - export PITHEAD_DATA_MIGRATION=true PITHEAD_MIN_OS_VERSION=2.0.0 + # declare the data-migration contract above for this release, migrating or not + # migrating: export PITHEAD_DATA_MIGRATION=true PITHEAD_MIN_OS_VERSION=X.Y.Z + # not migrating: export PITHEAD_DATA_MIGRATION=false PITHEAD_MIN_OS_VERSION= sudo -E os/rauc/mkimage.sh && sudo -E os/rauc/mkbundle.sh ``` diff --git a/docs/dev/manual-qa/appliance/rig-battery.md b/docs/dev/manual-qa/appliance/rig-battery.md index 2996623069..828b250867 100644 --- a/docs/dev/manual-qa/appliance/rig-battery.md +++ b/docs/dev/manual-qa/appliance/rig-battery.md @@ -11,10 +11,11 @@ This file lists the [rig](../README.md#glossary) checks that still need hands on - **Time.** About 2 hours, the Rigs session of the [Run sheet](../README.md#run-sheet). The battery is defined in [appliance-release.md](../../appliance-release.md). The `rig` KVM phase -only proves the [wizard](../README.md#glossary)'s rig card, role select, a submit toward a faked pool listener, volatile -journald, a plain reboot, a power cut, and the A/B update leg — so these three stay hands-on -until #1886's first gap converts what it can and names a bench e2e for the rest. Each row below names the -check that replaces it once that lands. M14 (run-from-USB) no longer needs a hand-run: the +proves the [wizard](../README.md#glossary)'s rig card, role select, a submit toward a faked pool listener, volatile +journald, a plain reboot, a power cut, and the A/B update leg; its share leg (#2063, +`tests/os/rig-share-leg.sh`) boots a second guest as a remote-node coordinator and proves an +accepted share on the appliance channel both ways. Each row below says what is automated and what +a hand must still do. M14 (run-from-USB) no longer needs a hand-run: the `rigmedia` KVM phase (`tests/os/phases/rigmedia.sh`, #2069) covers it — see its row below for what it proves and what it still leaves out. @@ -36,9 +37,13 @@ it proves and what it still leaves out. - `doctor` on the rig reports MSR applied and hugepages reserved. - Hashrate sits within the box's recorded baseline band. -*Replaced by: the accepted-share and `doctor` MSR/hugepages checks #1886's gap 1 still has to add -— the KVM phase fakes the pool listener and never accepts a share, and asserts nothing about MSR or -hugepages.* +*Covered by: the accepted-share check, automated as the `rig` phase's share leg (#2063, +`tests/os/rig-share-leg.sh`) — the phase boots a second guest as a remote-node coordinator, +re-points the already-proven rig at it, and reads the coordinator's own `/api/state` until the +rig's worker and the coordinator's built-in miner each report an accepted share. Stays manual: +`doctor` on real hardware reporting MSR applied and hugepages reserved (a KVM guest cannot take +RandomX MSR writes), hashrate inside the box's recorded baseline band, and the rig card itself on +a real loaner.* **Record:** PASS, FAIL or N/A in the results sheet. @@ -55,8 +60,11 @@ hugepages.* - The change reaches `applied`. - No pool credential was touched. -*Replaced by: a dashboard-driven adopt/config push check, not yet written — a rig serves no -dashboard of its own, so nothing in the KVM `rig` phase exercises this today.* +*Manual on `develop`. The check exists — #3717's adopt leg (`rig_adopt_leg`, run in the `rig` +phase after the share row) adopts a worker from the coordinator's dashboard, pushes one writable +change to `applied`, and checks pool credentials are untouched — but it merged only to +`develop-v2.1.0`, so no KVM row on this branch exercises it. #3994 backports it for 2.0.x; until +that lands, a rig serving no dashboard of its own means this stays a hand-run row.* **Record:** PASS, FAIL or N/A in the results sheet. @@ -82,7 +90,7 @@ dashboard of its own, so nothing in the KVM `rig` phase exercises this today.* return-mining-unaided fact off a real `virsh destroy`, and the phase's existing update leg proves the install/self-commit half. What stays manual is Restore on AC Power Loss itself — a firmware setting a virtual disk cannot show — and the Keep-everything pass itself: no automated leg -reinstalls a rig over its own `/data` yet (#3961).* +reinstalls a rig over its own `/data` yet (#3995).* **Record:** PASS, FAIL or N/A in the results sheet. diff --git a/docs/dev/releasing.md b/docs/dev/releasing.md index 70771c0268..ec9798900d 100644 --- a/docs/dev/releasing.md +++ b/docs/dev/releasing.md @@ -413,11 +413,14 @@ budget can then evict the unprotected baseline. Keep other KVM jobs off that ben reports the pin held, and confirm the image cache still lists the commit right before submitting provision. The cut cannot seed itself: `old_image` needs a strictly older build. -Submit four KVM jobs, each with a 240-minute timeout. A single `phases=["all"]` job exceeds that +Submit seven KVM jobs, each with a 240-minute timeout. A single `phases=["all"]` job exceeds that cap, and so does the boot group with provision. - Boot group: boot, update, install. -- Rig group: the [#1651](https://github.com/p2pool-starter-stack/pithead/issues/1651) phases. +- Rig group: the [#1651](https://github.com/p2pool-starter-stack/pithead/issues/1651) phases as + the four splits the last three release gates ran — rig, rigmedia and media; fault and reset; + image-upgrade; stack. In the 2.0.1 and 2.0.2 gates the combined seven-phase job failed one + phase each time and reran all seven; the splits keep a rerun to its own phase. - Provision: provision and setup-defaults against the seeded baseline, pinned to the seeded bench. - Crossupdate: the update from the previous release, which is the path existing installs take, pinned to a bench that keeps that release's image. @@ -442,9 +445,24 @@ KVM_BOOT_ID=$(jq -n --arg sha "$SHA" --arg ref "$REF" --arg key "$KVM_BOOT_KEY" '{repo:"pithead",commit:$sha,ref:$ref,tier:"tier4-kvm",options:{phases:["boot","update","install"]},timeout_minutes:240,submitted_by:"release/devops",note:"release KVM boot group",idempotency_key:$key}' \ | curl -fsS -X POST "$BENCH_CI_URL/jobs" -H 'Content-Type: application/json' --data-binary @- | jq -er '.job.id') KVM_RIG_KEY=$(uuidgen) -printf 'KVM rig group idempotency key: %s\n' "$KVM_RIG_KEY" +printf 'KVM rig/rigmedia/media split idempotency key: %s\n' "$KVM_RIG_KEY" KVM_RIG_ID=$(jq -n --arg sha "$SHA" --arg ref "$REF" --arg key "$KVM_RIG_KEY" \ - '{repo:"pithead",commit:$sha,ref:$ref,tier:"tier4-kvm",options:{phases:["rig","rigmedia","media","fault","reset","image-upgrade","stack"]},timeout_minutes:240,submitted_by:"release/devops",note:"release KVM rig group",idempotency_key:$key}' \ + '{repo:"pithead",commit:$sha,ref:$ref,tier:"tier4-kvm",options:{phases:["rig","rigmedia","media"]},timeout_minutes:240,submitted_by:"release/devops",note:"release KVM rig split",idempotency_key:$key}' \ + | curl -fsS -X POST "$BENCH_CI_URL/jobs" -H 'Content-Type: application/json' --data-binary @- | jq -er '.job.id') +KVM_FAULT_KEY=$(uuidgen) +printf 'KVM fault/reset split idempotency key: %s\n' "$KVM_FAULT_KEY" +KVM_FAULT_ID=$(jq -n --arg sha "$SHA" --arg ref "$REF" --arg key "$KVM_FAULT_KEY" \ + '{repo:"pithead",commit:$sha,ref:$ref,tier:"tier4-kvm",options:{phases:["fault","reset"]},timeout_minutes:240,submitted_by:"release/devops",note:"release KVM fault/reset split",idempotency_key:$key}' \ + | curl -fsS -X POST "$BENCH_CI_URL/jobs" -H 'Content-Type: application/json' --data-binary @- | jq -er '.job.id') +KVM_IMGUP_KEY=$(uuidgen) +printf 'KVM image-upgrade split idempotency key: %s\n' "$KVM_IMGUP_KEY" +KVM_IMGUP_ID=$(jq -n --arg sha "$SHA" --arg ref "$REF" --arg key "$KVM_IMGUP_KEY" \ + '{repo:"pithead",commit:$sha,ref:$ref,tier:"tier4-kvm",options:{phases:["image-upgrade"]},timeout_minutes:240,submitted_by:"release/devops",note:"release KVM image-upgrade split",idempotency_key:$key}' \ + | curl -fsS -X POST "$BENCH_CI_URL/jobs" -H 'Content-Type: application/json' --data-binary @- | jq -er '.job.id') +KVM_STACK_KEY=$(uuidgen) +printf 'KVM stack split idempotency key: %s\n' "$KVM_STACK_KEY" +KVM_STACK_ID=$(jq -n --arg sha "$SHA" --arg ref "$REF" --arg key "$KVM_STACK_KEY" \ + '{repo:"pithead",commit:$sha,ref:$ref,tier:"tier4-kvm",options:{phases:["stack"]},timeout_minutes:240,submitted_by:"release/devops",note:"release KVM stack split",idempotency_key:$key}' \ | curl -fsS -X POST "$BENCH_CI_URL/jobs" -H 'Content-Type: application/json' --data-binary @- | jq -er '.job.id') KVM_PROV_KEY=$(uuidgen) printf 'KVM provision idempotency key: %s\n' "$KVM_PROV_KEY" @@ -456,18 +474,19 @@ printf 'KVM crossupdate idempotency key: %s\n' "$KVM_CROSS_KEY" KVM_CROSS_ID=$(jq -n --arg sha "$SHA" --arg ref "$REF" --arg key "$KVM_CROSS_KEY" --arg prev "$PREVIOUS_RELEASE_SHA" \ '{repo:"pithead",commit:$sha,ref:$ref,tier:"tier4-kvm",options:{phases:["crossupdate"],old_image_commit:$prev},local_only:true,timeout_minutes:240,submitted_by:"release/devops",note:"release KVM crossupdate",idempotency_key:$key}' \ | curl -fsS -X POST "$CROSSUPDATE_BENCH_URL/jobs" -H 'Content-Type: application/json' --data-binary @- | jq -er '.job.id') -printf 'KVM jobs: %s %s %s %s @%s\n' "$KVM_BOOT_ID" "$KVM_RIG_ID" "$KVM_PROV_ID" "$KVM_CROSS_ID" "$SHA" +printf 'KVM jobs: %s %s %s %s %s %s %s @%s\n' "$KVM_BOOT_ID" "$KVM_RIG_ID" "$KVM_FAULT_ID" \ + "$KVM_IMGUP_ID" "$KVM_STACK_ID" "$KVM_PROV_ID" "$KVM_CROSS_ID" "$SHA" ``` -Read all four completed KVM jobs' full status, logs, artifacts and evidence. Require `success`, zero failed +Read all seven completed KVM jobs' full status, logs, artifacts and evidence. Require `success`, zero failed rows and a reason for every skip. These jobs run before e2e, so an e2e failure cannot cancel their battery proof. A failed KVM group prevents the final e2e gate from running. Every KVM job is bound to the exact tag SHA. `SHA` is the commit that will be tagged; a job whose `commit` differs from it is not evidence for the release, however recently it passed. Any change after the battery, including a digest re-pin or a version bump, makes the whole KVM set stale: -rerun the boot, rig, provision and crossupdate jobs on the new SHA and read them again before -submitting e2e. `release.sh` refuses to publish unless the tag SHA itself carries a successful +rerun the boot group, the four rig-group splits, provision and crossupdate on the new SHA and +read them again before submitting e2e. `release.sh` refuses to publish unless the tag SHA itself carries a successful `bench-ci/tier4` status from the bench-ci App, but that check reads only the status on the release commit and never the KVM jobs' `commit` fields (`require_bench_tier4` in `scripts/release/preflight.sh`). Confirming the rerun before publishing is therefore a @@ -501,9 +520,9 @@ Use `targeted` until the frozen SHA includes the harness fix from [#3026](https://github.com/p2pool-starter-stack/pithead/issues/3026); then set `E2E_MODE=matrix`. Keep the real rig in the run. Only the owner may authorize `no_rig` after reviewing failures confined to rigforge-control harness rows. The final e2e job alone requests the aggregate status, -with the two group jobs in `after`. A bench resolves `after` only against its own jobs, and the -provision and crossupdate jobs belong to their pinned benches, so the block first refuses to -submit unless both of those completed with `success`: +with the boot group and the four rig-group splits in `after`. A bench resolves `after` only +against its own jobs, and the provision and crossupdate jobs belong to their pinned benches, so +the block first refuses to submit unless both of those completed with `success`: ```bash for leg in "$PROVISION_BENCH_URL/jobs/$KVM_PROV_ID" "$CROSSUPDATE_BENCH_URL/jobs/$KVM_CROSS_ID"; do @@ -513,16 +532,17 @@ E2E_MODE=targeted E2E_KEY=$(uuidgen) printf 'e2e idempotency key: %s\n' "$E2E_KEY" jq -n --arg sha "$SHA" --arg ref "$REF" --arg key "$E2E_KEY" --arg mode "$E2E_MODE" \ - --argjson boot "$KVM_BOOT_ID" --argjson rig "$KVM_RIG_ID" \ - '{repo:"pithead",commit:$sha,ref:$ref,tier:"tier4-e2e",options:{mode:$mode},after:[$boot,$rig],status_gate:true,submitted_by:"release/devops",note:"release status gate",idempotency_key:$key}' \ + --argjson boot "$KVM_BOOT_ID" --argjson rig "$KVM_RIG_ID" --argjson fault "$KVM_FAULT_ID" \ + --argjson imgup "$KVM_IMGUP_ID" --argjson stack "$KVM_STACK_ID" \ + '{repo:"pithead",commit:$sha,ref:$ref,tier:"tier4-e2e",options:{mode:$mode},after:[$boot,$rig,$fault,$imgup,$stack],status_gate:true,submitted_by:"release/devops",note:"release status gate",idempotency_key:$key}' \ | curl -fsS -X POST "$BENCH_CI_URL/jobs" -H 'Content-Type: application/json' --data-binary @- | jq -er '.job.id' ``` -Read the completed e2e job's full status, log, artifacts and evidence. All five jobs must carry the same -SHA and ref. A failed or cancelled leg cannot yield a +Read the completed e2e job's full status, log, artifacts and evidence. All eight jobs must carry +the same SHA and ref. A failed or cancelled leg cannot yield a successful aggregate status. Confirm the exact commit's newest `bench-ci/tier4` status is `success` and its creator is the configured bench-ci App before running `release.sh`; record all -five job IDs and the SHA in the release issue. Remove a rehearsal branch after confirming its +eight job IDs and the SHA in the release issue. Remove a rehearsal branch after confirming its status with `git push origin --delete "$REF"`. If a submission is refused, stop and report it to bench-ci; retain its printed idempotency key for a retry. diff --git a/tests/integration/selftest/selftest-release-status-recipe.sh b/tests/integration/selftest/selftest-release-status-recipe.sh index 717c4fad06..4bc2a746aa 100644 --- a/tests/integration/selftest/selftest-release-status-recipe.sh +++ b/tests/integration/selftest/selftest-release-status-recipe.sh @@ -65,33 +65,39 @@ run_recipe() { run_recipe jq -es --arg sha "$RECIPE_TEST_SHA" --arg base "$BASE" --arg prev "$PREV" ' - length == 5 and + length == 8 and all(.[]; .repo == "pithead" and .commit == $sha and .ref == "release/" + $sha) and - (map(.idempotency_key) | unique | length == 5) and - all(.[0:4][]; .tier == "tier4-kvm" and .timeout_minutes == 240 and (.after // []) == [] and (.status_gate // false) == false) and + (map(.idempotency_key) | unique | length == 8) and + all(.[0:7][]; .tier == "tier4-kvm" and .timeout_minutes == 240 and (.after // []) == [] and (.status_gate // false) == false) and (.[0].options.phases == ["boot","update","install"]) and - (.[1].options.phases == ["rig","rigmedia","media","fault","reset","image-upgrade","stack"]) and - (.[2].options == {phases:["provision","setup-defaults"],old_image_commit:$base} and .[2].local_only == true) and - (.[3].options == {phases:["crossupdate"],old_image_commit:$prev} and .[3].local_only == true) and - (.[4].tier == "tier4-e2e" and .[4].status_gate == true and .[4].after == [1,2]) and - (.[4].options.mode == "targeted" and (.[4].options | has("no_rig") | not)) + (.[1].options.phases == ["rig","rigmedia","media"]) and + (.[2].options.phases == ["fault","reset"]) and + (.[3].options.phases == ["image-upgrade"]) and + (.[4].options.phases == ["stack"]) and + (.[5].options == {phases:["provision","setup-defaults"],old_image_commit:$base} and .[5].local_only == true) and + (.[6].options == {phases:["crossupdate"],old_image_commit:$prev} and .[6].local_only == true) and + (.[7].tier == "tier4-e2e" and .[7].status_gate == true and .[7].after == [1,2,3,4,5]) and + (.[7].options.mode == "targeted" and (.[7].options | has("no_rig") | not)) ' "$RECIPE_TEST_DIR/jobs.jsonl" >/dev/null diff -u - "$RECIPE_TEST_DIR/urls" <&2 exit 1 fi -[ "$(wc -l <"$RECIPE_TEST_DIR/jobs.jsonl")" -eq 4 ] || { +[ "$(wc -l <"$RECIPE_TEST_DIR/jobs.jsonl")" -eq 7 ] || { echo 'a failed pinned leg still produced an e2e submission' >&2 exit 1 } From fa7ec5a97122e06a1b1a13acf51a905dd943f31e Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:27:37 -0600 Subject: [PATCH 003/112] test(os): name the boot line that ends the migration release wait (#3957) (#4041) * test(os): name the boot line that ends the migration release wait (#3957) The provision migration leg waited its full 10 minutes and then claimed a hold deadlock even when the candidate boot had already aborted; job 353@b34b109aeb50074469312f65a3f153eb314d147b died 69s into the wait on a signature-verification failure inside a dark bench outage window, and the row recorded nothing about the guest. migration_release_wait now ends on the boot's own terminal journal lines, names that line as the verdict, captures the guest's gate, slot and unit state at every deadline, and is bound above pithead-boot's own about-16-minute gate budget. Co-Authored-By: Claude Code * test(os): scrub control characters from the embedded terminal journal line Co-Authored-By: Claude Code * test(os): read the candidate boot through the fallback and bound the release wait polls (#3957) fail_boot's fallback path reboots the guest before the next poll, so the terminal line lives in the previous (persistent) boot and the deadline dump must show both boots. Polls carry SSH_TIMEOUT=20 per core.sh's polling-loop rule so one black-holed session cannot stretch the wait. Deadline dump: fix the doctor filter to the real fail/warn statuses and strip ESC bytes. Co-Authored-By: Claude Code * test(os): execute the release-wait commands in the selftest and pin bound, timeout, fallback (#3957) The stub now evals the command string it receives against fake journalctl/podman that pick the boot file from -b / -b -1, so removing the previous-boot half of the terminal query, the SSH_TIMEOUT=20 polls or the 240-round default each fails the selftest. Drop the added source comment. Co-Authored-By: Claude Code --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Code --- tests/os/migration-recovery.sh | 57 ++++++++ tests/os/phases/provision-migration.sh | 27 ++-- tests/os/selftest-migration-release-wait.sh | 148 ++++++++++++++++++++ 3 files changed, 214 insertions(+), 18 deletions(-) create mode 100644 tests/os/selftest-migration-release-wait.sh diff --git a/tests/os/migration-recovery.sh b/tests/os/migration-recovery.sh index 188a30a9c6..317323ee83 100644 --- a/tests/os/migration-recovery.sh +++ b/tests/os/migration-recovery.sh @@ -107,3 +107,60 @@ migration_remote_recovery() { sensitive_preview "$(dashboard_config_body "$proposed")" || return 1 result=$(approval_commit "$APPROVAL_REQUEST_ID") && tari_commit_verdict "$result" } + +MIGRATION_RELEASE_WAIT_ROUNDS=${MIGRATION_RELEASE_WAIT_ROUNDS:-240} +MIGRATION_RELEASE_TERMINAL='slot left uncommitted|never became healthy|this is failure|NOT a bad slot|migration marker could not be assigned' +migration_release_early=0 +migration_release_line="" +migration_release_rounds=0 + +# shellcheck disable=SC2034 # migration_release_rounds and migration_release_early are read by the phase leg +migration_release_wait() { + migration_release_early=0 + migration_release_line="" + migration_release_rounds=0 + local _ + for _ in $(seq "$MIGRATION_RELEASE_WAIT_ROUNDS"); do + migration_release_rounds=$_ + if SSH_TIMEOUT=20 _ssh "journalctl -u pithead-boot -b 2>/dev/null | grep -q 'chain services released'"; then + return 0 + fi + migration_release_line=$(SSH_TIMEOUT=20 _ssh "journalctl -u pithead-boot -b -o cat 2>/dev/null | grep -m1 -E '$MIGRATION_RELEASE_TERMINAL' || journalctl -u pithead-boot -b -1 -o cat 2>/dev/null | grep -m1 -E '$MIGRATION_RELEASE_TERMINAL'" | tr -d '[:cntrl:]') + if [ -n "$migration_release_line" ]; then + return 1 + fi + if SSH_TIMEOUT=20 _ssh "podman ps --format '{{.Names}}' 2>/dev/null | grep -qx monerod" && + ! SSH_TIMEOUT=20 _ssh "journalctl -u pithead-boot -b 2>/dev/null | grep -q 'chain services released'"; then + migration_release_early=1 + fi + sleep 5 + done + return 1 +} + +migration_release_deadline_evidence() { + printf ' --- migration release deadline: guest state at the deadline (#3957) ---\n' + SSH_TIMEOUT=60 _ssh "echo '-- boot journal, current boot (last 25) --' + journalctl -u pithead-boot -b -o cat 2>/dev/null | grep -viE 'password|token|secret' | tail -25 + echo '-- boot journal, previous boot — the candidate after an automatic fallback (last 25) --' + journalctl -u pithead-boot -b -1 -o cat 2>/dev/null | grep -viE 'password|token|secret' | tail -25 + echo '-- gate progress --' + journalctl -u pithead-boot -b -o cat 2>/dev/null | grep -E 'still starting|holding chain services|migration marker claimed' | tail -3 + echo '-- last doctor verdict --' + jq -c '[.checks[]? | select(.status == \"fail\" or .status == \"warn\")] | .[0:4]' /run/pithead-boot-doctor.json 2>/dev/null + echo '-- status record (blocking rows) --' + grep -E '✗|⚠' /run/pithead-boot-status.log 2>/dev/null | head -8 + echo '-- slots --' + sed -n 's/.*rauc.slot=\([AB]\).*/booted slot=\1/p' /proc/cmdline + rauc status --detailed --output-format=shell 2>/dev/null | grep -E '^RAUC_(BOOT_PRIMARY|SLOT)' | head -20 + grub-editenv /boot/efi/grub/grubenv list 2>/dev/null | grep -E '_OK=|_TRY_COUNT' | head -8 + echo '-- migration and update state --' + echo marker=\$(cat /data/pithead/.os-migration-pending 2>/dev/null) + echo boot-failures=\$(cat /data/pithead/.boot-gate-failures 2>/dev/null) + cat /data/pithead/data/os-update/in-flight.json 2>/dev/null + echo '-- failed units --' + systemctl --failed --no-legend 2>/dev/null | head -10 + echo '-- containers --' + podman ps -a --format '{{.Names}} {{.Status}}' 2>/dev/null | head -15" 2>/dev/null | + tr -d '\r\033' | sed 's/^/ · /' +} diff --git a/tests/os/phases/provision-migration.sh b/tests/os/phases/provision-migration.sh index c47b02bbe3..6eb9510ab2 100644 --- a/tests/os/phases/provision-migration.sh +++ b/tests/os/phases/provision-migration.sh @@ -129,10 +129,7 @@ _phase_provision_migration() { bad "guest never returned after booting the migration bundle" return 1 } - # Poll through the boot. The release line is logged at the commit boundary, BEFORE the - # post-commit up — so any monerod observed running before that line is a chain service - # beating the fallback decision, the exact ordering this rule exists to forbid. - local chain_ran_early=0 released=0 recovery_allowed=1 candidate_commit + local recovery_allowed=1 candidate_commit candidate_commit=$(_ssh 'cat /opt/pithead/BUILD_COMMIT' | tr -d '\r\n') if [[ "$candidate_commit" =~ ^[0-9a-f]{40}$ ]] && [ "$candidate_commit" = "$(git rev-parse HEAD)" ]; then ok "migration candidate BUILD_COMMIT $candidate_commit matches the tested head" @@ -140,18 +137,7 @@ _phase_provision_migration() { bad "the migration boot did not load the tested candidate source" recovery_allowed=0 fi - for _ in $(seq 120); do - if _ssh "journalctl -u pithead-boot -b 2>/dev/null | grep -q 'chain services released'"; then - released=1 - break - fi - if _ssh "podman ps --format '{{.Names}}' 2>/dev/null | grep -qx monerod" && - ! _ssh "journalctl -u pithead-boot -b 2>/dev/null | grep -q 'chain services released'"; then - chain_ran_early=1 - fi - sleep 5 - done - if [ "$released" = 1 ]; then + if migration_release_wait; then if [ "$(_marker)" = vmig ] && _ssh 'slot=$(sed -n "s/.*rauc.slot=\([AB]\).*/\1/p" /proc/cmdline); test -n "$slot" && grub-editenv /boot/efi/grub/grubenv list | grep -qx "${slot}_OK=1"'; then ok "the migrating slot committed unattended and released the chain services" else @@ -161,10 +147,15 @@ _phase_provision_migration() { # shellcheck disable=SC2154 # pv_user/pv_pass are set by the initial leg (phase-level locals). assert_appliance_hostname_identity fixture-next "A/B update" "$pv_user" "$pv_pass" else - bad "the migrating slot never reached the post-commit release — the hold deadlocked the gate it was built not to" + migration_release_deadline_evidence + if [ -n "$migration_release_line" ]; then + bad "the migrating slot never reached the post-commit release — the boot journal ended the wait at round $migration_release_rounds with [$migration_release_line] — read the guest evidence above before blaming the hold" + else + bad "the migrating slot never reached the post-commit release — the hold deadlocked the gate it was built not to (waited at least $((migration_release_rounds * 5))s of polls for the release line; guest evidence above)" + fi return 1 fi - if [ "$chain_ran_early" = 0 ]; then + if [ "$migration_release_early" = 0 ]; then ok "monerod never ran while the slot was uncommitted" else bad "monerod ran BEFORE the commit — the migration would beat the fallback decision" diff --git a/tests/os/selftest-migration-release-wait.sh b/tests/os/selftest-migration-release-wait.sh new file mode 100644 index 0000000000..a134d0080e --- /dev/null +++ b/tests/os/selftest-migration-release-wait.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +set -euo pipefail +export TMPDIR="${TMPDIR:-${RUNNER_TEMP:-/tmp}}" +HERE=$(cd "$(dirname "$0")" && pwd) +T=$(mktemp -d "${TMPDIR:?}/migration-release-wait.XXXXXX") +trap 'rm -rf "$T"' EXIT +fail() { + echo "FAIL: $*" >&2 + exit 1 +} +SCRIPT_DIR=$HERE +# shellcheck source=tests/os/migration-recovery.sh +source "$HERE/migration-recovery.sh" + +sleep_calls=0 +sleep() { sleep_calls=$((sleep_calls + 1)); } + +journalctl() { + local boot=current + while [ $# -gt 0 ]; do + if [ "$1" = '-b' ]; then + case "${2:-}" in + '-1') boot=prev ;; + esac + fi + shift + done + case $boot in + prev) cat "$T/journal_prev" 2>/dev/null ;; + *) cat "$T/journal" 2>/dev/null ;; + esac + return 0 +} +podman() { + cat "$T/podman" 2>/dev/null + return 0 +} +_ssh() { + case "$1" in + *'-- slots --'*) + [ "${SSH_TIMEOUT:-}" = 60 ] || printf 'deadline dump without SSH_TIMEOUT=60\n' >"$T/violation" + cat "$T/evidence" + ;; + *) + [ "${SSH_TIMEOUT:-}" = 20 ] || printf 'release-wait poll without SSH_TIMEOUT=20: %s\n' "$1" >"$T/violation" + eval "$1" + ;; + esac +} +journal_has() { + printf '%s\n' "$1" >"$T/journal" + : >"$T/journal_prev" +} +journal_prev_has() { printf '%s\n' "$1" >"$T/journal_prev"; } +podman_running() { printf 'monerod\n' >"$T/podman"; } +podman_quiet() { : >"$T/podman"; } + +journal_has 'pithead-boot: slot committed — chain services released, the data migration runs now' +podman_quiet +MIGRATION_RELEASE_WAIT_ROUNDS=240 +sleep_calls=0 +migration_release_early=9 +migration_release_wait || fail 'the release line must end the wait green' +[ "$migration_release_rounds" -eq 1 ] || fail 'the release check must run first in a round' +[ "$migration_release_early" = 0 ] || fail 'monerod beside a released boot is not early' +[ "$sleep_calls" -eq 0 ] || fail 'a released boot must not sleep a round' + +journal_has 'pithead-boot: the stack could not be brought up — slot left uncommitted so A/B fallback stays armed' +podman_running +MIGRATION_RELEASE_WAIT_ROUNDS=240 +sleep_calls=0 +if migration_release_wait; then fail 'a dead boot must not report release'; fi +[ "$migration_release_line" = 'pithead-boot: the stack could not be brought up — slot left uncommitted so A/B fallback stays armed' ] || + fail "the terminal verdict lost the boot's line: $migration_release_line" +[ "$sleep_calls" -eq 0 ] || fail 'a dead boot must end the wait without another round' + +journal_has '' +podman_quiet +MIGRATION_RELEASE_WAIT_ROUNDS=3 +sleep_calls=0 +if migration_release_wait; then fail 'a boot that logs nothing must fail at the bound'; fi +[ "$migration_release_rounds" -eq 3 ] || fail "wait must stop at its round bound, ran $migration_release_rounds" +[ "$sleep_calls" -eq 3 ] || fail 'one sleep per unproductive round' +[ -z "$migration_release_line" ] || fail 'a timeout names no terminal line' + +journal_has 'pithead-boot: the stack never became healthy (serving + doctor + status)' +podman_quiet +MIGRATION_RELEASE_WAIT_ROUNDS=240 +sleep_calls=0 +if migration_release_wait; then fail 'the spent gate must end the wait'; fi +[ "$migration_release_line" = 'pithead-boot: the stack never became healthy (serving + doctor + status)' ] || + fail 'the spent-gate line must be the verdict' + +journal_has '' +podman_running +MIGRATION_RELEASE_WAIT_ROUNDS=2 +sleep_calls=0 +migration_release_wait && fail 'no release line must fail the wait' +[ "$migration_release_early" = 1 ] || fail 'monerod running before the release line must be flagged early' + +journal_has 'pithead-boot: slot committed — chain services released, the data migration runs now' +podman_running +MIGRATION_RELEASE_WAIT_ROUNDS=240 +sleep_calls=0 +migration_release_early=9 +migration_release_wait || fail 'a released boot with monerod up must pass' +[ "$migration_release_early" = 0 ] || fail 'monerod up after the release is not early' + +journal_has '' +journal_prev_has 'pithead-boot: the stack could not be brought up — slot left uncommitted so A/B fallback stays armed' +podman_running +MIGRATION_RELEASE_WAIT_ROUNDS=240 +sleep_calls=0 +if migration_release_wait; then fail 'a fallback reboot must not report release'; fi +[ "$migration_release_line" = 'pithead-boot: the stack could not be brought up — slot left uncommitted so A/B fallback stays armed' ] || + fail 'the wait must name the candidate line from the previous boot after an automatic fallback' +[ "$sleep_calls" -eq 0 ] || fail 'a terminal previous-boot line must end the wait in one round' + +printf 'booted slot=B\nRAUC_BOOT_PRIMARY=A\n' >"$T/evidence" +out=$(migration_release_deadline_evidence) +case $out in +*'migration release deadline'*) ;; +*) fail 'the deadline dump needs its header' ;; +esac +case $out in +*'booted slot=B'*) ;; +*) fail 'the deadline dump must carry the guest slot state' ;; +esac + +( + unset MIGRATION_RELEASE_WAIT_ROUNDS + # shellcheck source=tests/os/migration-recovery.sh + source "$HERE/migration-recovery.sh" + [ "${MIGRATION_RELEASE_WAIT_ROUNDS:-0}" -eq 240 ] +) || fail 'the release wait default must stay 240 rounds (#3957)' + +overlay="$HERE/../../os/overlay/pithead-boot" +for needle in 'slot left uncommitted' 'never became healthy' 'this is failure' 'NOT a bad slot' 'migration marker could not be assigned'; do + grep -qF -- "$needle" "$overlay" || fail "pithead-boot no longer emits [$needle] — the terminal pattern is stale" + case $MIGRATION_RELEASE_TERMINAL in + *"$needle"*) ;; + *) fail "the terminal pattern list dropped [$needle]" ;; + esac +done + +[ ! -e "$T/violation" ] || fail "$(<"$T/violation")" + +echo 'selftest-migration-release-wait: PASS' From d115384e2ba9d6fdf43159b19944a0cd6992e67a Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 07:53:48 -0600 Subject: [PATCH 004/112] fix(os): run dashboard schema migrations only after the booted slot commits (#3998) (#4025) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(os): run dashboard schema migrations only after the booted slot commits (#3998) pithead-boot writes .os-schema-held into the dashboard data dir whenever the booted A/B slot is still uncommitted, and the dashboard defers its one forward-incompatible migration (the 2.0.3 payout identity rebuild) while the marker stands: fresh databases are created in the previous release's shape, the rebuild is skipped, and payouts keep recording through that shape — so a fallback into the previous release finds a schema it can still write. boot_gate_passed (moved to the stack-health sibling for the file budget) releases the hold after mark-good: marker out, dashboard restarted once, the deferred migration runs on a slot no fallback can leave. Unknown verdicts (no rauc.slot, failing/unparseable rauc status, no jq) defer; a marker that cannot be written fails the boot, which is exactly the uncommitted state the marker exists to make safe. Co-Authored-By: Claude Code * chore: drop the added comments from the #3998 hunks per review No behaviour change: comments only (28 lines), directives and pre-existing comments intact. Re-ran shfmt, pinned shellcheck, selftest-schema-hold, selftest-migration-boot, lint-file-budget, ruff check+format, the payout/ storage pytest set, and lint-path-references — all green. Co-Authored-By: Claude Code * test(os): journal the dashboard schema hold arm and release and assert both in leg 4 Co-Authored-By: Claude Code * test(os): assert the schema hold arm and release on leg 5's fallback boot Co-Authored-By: Claude Code * chore: drop the explanatory comments left in the #3998 store and schema hunks Co-Authored-By: Claude Opus 5.5 * test(dashboard): move the schema hold cases into their own module Returns test_storage_schema.py to its 394-line develop size and drops its file-budget row. Co-Authored-By: Claude Opus 5.5 * test(dashboard): prove the previous release records payouts after a held candidate falls back (#3998) Arms the marker with pithead-boot's own schema_hold_arm on an uncommitted slot, opens the head's store under that hold, then runs 2.0.2's wallet-less payout INSERT and reads the row back. Co-Authored-By: Claude Opus 5.5 * test(os): assert leg 5's fault boot kept the schema hold armed, and stop the leg when fallback fails Reads each boot's pithead-boot journal once instead of per grep. Co-Authored-By: Claude Opus 5.5 * test: skip the boot-script join test in the dashboard image and poll leg 5's release with a remote grep Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Code --- CHANGELOG.md | 6 + .../mining_dashboard/service/mining_store.py | 46 +++-- .../service/storage_schema.py | 34 +++- dashboard/tests/service/test_schema_hold.py | 169 ++++++++++++++++++ docs/dev/appliance-release.md | 20 +++ os/overlay/pithead-boot | 3 +- os/overlay/pithead-boot-stack-health | 40 +++++ tests/os/phases/update-dashboard.sh | 11 ++ tests/os/phases/update-healthgate-leg.sh | 18 ++ tests/os/selftest-schema-hold.sh | 130 ++++++++++++++ 10 files changed, 447 insertions(+), 30 deletions(-) create mode 100644 dashboard/tests/service/test_schema_hold.py create mode 100644 tests/os/selftest-schema-hold.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index be762ebcc2..0d86007ad8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,12 @@ per the process in [`docs/dev/releasing.md`](docs/dev/releasing.md). ## [Unreleased] +### Fixed + +- On the appliance, the dashboard's own schema migrations no longer run before the booted A/B slot + commits. `pithead-boot` defers them while the slot is uncommitted, so an update that falls back + leaves the previous release on the schema it understands, still recording payouts (#3998). + ## [2.0.3] - 2026-11-10 Pithead 2.0.3 is a patch release after 2.0.2. It bakes RigForge 1.18.1 into the appliance image, diff --git a/dashboard/mining_dashboard/service/mining_store.py b/dashboard/mining_dashboard/service/mining_store.py index c206c65422..9ee7c8b94e 100644 --- a/dashboard/mining_dashboard/service/mining_store.py +++ b/dashboard/mining_dashboard/service/mining_store.py @@ -28,6 +28,8 @@ def _raffle_wins_max_rows(): class MiningStoreMixin: + _payouts_have_wallet = True + def add_payouts( self, chain: str, wallet_id: str | None, rows: list[dict[str, Any]] ) -> list[dict[str, Any]]: @@ -40,21 +42,25 @@ def add_payouts( return [] with self._conn: for r in rows: - cur = self._conn.execute( - "INSERT OR IGNORE INTO payouts " - "(chain, wallet_id, txid, height, ts, amount_atomic) " - "VALUES (?, ?, ?, ?, ?, ?)", - ( - chain, - wallet_id, - r["txid"], - int(r.get("height", 0) or 0), - float(r.get("ts", 0) or 0), - int(r.get("amount_atomic", 0) or 0), - ), + tail = ( + int(r.get("height", 0) or 0), + float(r.get("ts", 0) or 0), + int(r.get("amount_atomic", 0) or 0), ) - # rowcount == 1 means the row was actually inserted (not an ignored dup), - # so it's a genuinely new payout worth alerting on exactly once. + if self._payouts_have_wallet: + cur = self._conn.execute( + "INSERT OR IGNORE INTO payouts " + "(chain, wallet_id, txid, height, ts, amount_atomic) " + "VALUES (?, ?, ?, ?, ?, ?)", + (chain, wallet_id, r["txid"], *tail), + ) + else: + cur = self._conn.execute( + "INSERT OR IGNORE INTO payouts " + "(chain, txid, height, ts, amount_atomic) " + "VALUES (?, ?, ?, ?, ?)", + (chain, r["txid"], *tail), + ) if cur.rowcount == 1: new_rows.append(r) except (sqlite3.Error, KeyError, ValueError, TypeError) as e: @@ -70,10 +76,11 @@ def get_payouts(self, chain: str, wallet_id: str | None) -> list[dict[str, Any]] if not self._conn: return [] cursor = self._conn.cursor() + where = "chain = ? AND wallet_id = ?" if self._payouts_have_wallet else "chain = ?" cursor.execute( - "SELECT chain, txid, height, ts, amount_atomic FROM payouts " - "WHERE chain = ? AND wallet_id = ? ORDER BY ts DESC", - (chain, wallet_id), + "SELECT chain, txid, height, ts, amount_atomic FROM payouts " # noqa: S608 + f"WHERE {where} ORDER BY ts DESC", + (chain, wallet_id) if self._payouts_have_wallet else (chain,), ) return [dict(row) for row in cursor.fetchall()] except sqlite3.Error as e: @@ -88,9 +95,10 @@ def get_payout_max_height(self, chain: str, wallet_id: str | None) -> int: if not self._conn: return 0 cursor = self._conn.cursor() + where = "chain = ? AND wallet_id = ?" if self._payouts_have_wallet else "chain = ?" cursor.execute( - "SELECT MAX(height) FROM payouts WHERE chain = ? AND wallet_id = ?", - (chain, wallet_id), + f"SELECT MAX(height) FROM payouts WHERE {where}", # noqa: S608 + (chain, wallet_id) if self._payouts_have_wallet else (chain,), ) row = cursor.fetchone() return int(row[0]) if row and row[0] is not None else 0 diff --git a/dashboard/mining_dashboard/service/storage_schema.py b/dashboard/mining_dashboard/service/storage_schema.py index 44f4f74746..0f3e0526b8 100644 --- a/dashboard/mining_dashboard/service/storage_schema.py +++ b/dashboard/mining_dashboard/service/storage_schema.py @@ -44,6 +44,16 @@ # write cycle forever. A transient error (locked, disk full, permissions) is NOT here: those are the # db_unhealthy path — retryable, not a reason to throw away history. _CORRUPTION_MARKERS = ("malformed", "not a database", "image is malformed", "file is encrypted") + +_SCHEMA_HOLD_MARKER = ".os-schema-held" + + +def _schema_hold_active(db_path: str) -> bool: + if db_path == ":memory:": + return False + return os.path.exists(os.path.join(os.path.dirname(db_path) or ".", _SCHEMA_HOLD_MARKER)) + + # How many quarantined copies of a corrupt DB to keep for post-mortem before pruning the oldest. _CORRUPT_KEEP = 3 @@ -67,22 +77,19 @@ class StorageSchemaMixin: - def _apply_schema(self): - """Set pragmas + create/migrate the schema on the open connection. Caller holds ``_db_lock``. + _db_schema_held = False - Split out of ``_init_db`` so the recovery path (#489) can rebuild the schema on a freshly - reconnected DB without re-entering the (non-reentrant) lock via ``_init_db``.""" - # Enable WAL mode for better concurrency + def _apply_schema(self): self._conn.execute("PRAGMA journal_mode=WAL") self._conn.execute("PRAGMA synchronous=NORMAL") + self._db_schema_held = _schema_hold_active(self.db_path) with self._conn: self._create_tables() self._migrate_db() - # Indexes come AFTER migration: idx_ts is on history(timestamp), a column - # _migrate_db adds when upgrading a pre-timestamp DB. Creating it in - # _create_tables would throw "no such column: timestamp" on that old schema - # and abort the whole migration, leaving the DB half-upgraded. self._create_indexes() + cursor = self._conn.cursor() + cursor.execute("PRAGMA table_info(payouts)") + self._payouts_have_wallet = "wallet_id" in {info[1] for info in cursor.fetchall()} def _init_db(self): """Initializes the SQLite database schema and handles migrations. @@ -263,6 +270,13 @@ def _create_indexes(self): self._conn.execute("CREATE INDEX IF NOT EXISTS idx_audit_events_ts ON audit_events(ts)") def _create_payouts_table(self): + if self._db_schema_held: + self._conn.execute( + "CREATE TABLE IF NOT EXISTS payouts " + "(chain TEXT, txid TEXT, height INTEGER, ts REAL, amount_atomic INTEGER, " + "PRIMARY KEY (chain, txid))" + ) + return self._conn.execute( "CREATE TABLE IF NOT EXISTS payouts " "(chain TEXT, wallet_id TEXT NOT NULL, txid TEXT, height INTEGER, ts REAL, " @@ -270,6 +284,8 @@ def _create_payouts_table(self): ) def _migrate_payout_identity(self, cursor): + if self._db_schema_held: + return cursor.execute("PRAGMA table_info(payouts)") if "wallet_id" in {info[1] for info in cursor.fetchall()}: return diff --git a/dashboard/tests/service/test_schema_hold.py b/dashboard/tests/service/test_schema_hold.py new file mode 100644 index 0000000000..a96bbb6e58 --- /dev/null +++ b/dashboard/tests/service/test_schema_hold.py @@ -0,0 +1,169 @@ +import os +import shutil +import sqlite3 +import subprocess +from pathlib import Path + +import pytest + +from mining_dashboard.service.storage_service import StateManager + + +class TestSchemaMigrationHold: + _LEGACY_DDL = ( + "CREATE TABLE payouts " + "(chain TEXT, txid TEXT, height INTEGER, ts REAL, amount_atomic INTEGER, " + "PRIMARY KEY (chain, txid))" + ) + + def _seed_legacy_db(self, db): + conn = sqlite3.connect(db) + conn.execute(self._LEGACY_DDL) + conn.execute( + "INSERT INTO payouts (chain, txid, height, ts, amount_atomic) " + "VALUES ('monero', 'tx-old', 5, 5.0, 1000)" + ) + conn.commit() + conn.close() + + def _payout_columns(self, db): + conn = sqlite3.connect(db) + try: + return {info[1] for info in conn.execute("PRAGMA table_info(payouts)")} + finally: + conn.close() + + def _hold(self, tmp_path): + marker = tmp_path / ".os-schema-held" + marker.write_text("") + return marker + + def test_hold_defers_the_payout_identity_rebuild(self, tmp_path): + db = str(tmp_path / "mining.db") + self._seed_legacy_db(db) + self._hold(tmp_path) + sm = StateManager(db_path=db) + try: + assert sm._payouts_have_wallet is False + assert "wallet_id" not in self._payout_columns(db) + finally: + sm.close() + + def test_hold_releases_the_migration_on_the_next_open(self, tmp_path): + db = str(tmp_path / "mining.db") + self._seed_legacy_db(db) + marker = self._hold(tmp_path) + StateManager(db_path=db).close() + marker.unlink() + sm = StateManager(db_path=db) + try: + assert sm._payouts_have_wallet is True + cols = self._payout_columns(db) + assert "wallet_id" in cols + rows = sm.get_payouts("monero", "unknown") + assert [r["txid"] for r in rows] == ["tx-old"] + finally: + sm.close() + + def test_hold_creates_fresh_databases_in_the_previous_shape(self, tmp_path): + db = str(tmp_path / "mining.db") + self._hold(tmp_path) + sm = StateManager(db_path=db) + try: + assert sm._payouts_have_wallet is False + assert "wallet_id" not in self._payout_columns(db) + finally: + sm.close() + + def test_payouts_keep_recording_on_the_previous_shape(self, tmp_path): + db = str(tmp_path / "mining.db") + self._seed_legacy_db(db) + self._hold(tmp_path) + sm = StateManager(db_path=db) + try: + new = sm.add_payouts( + "monero", + "wallet-alpha", + [{"txid": "tx-new", "height": 9, "ts": 9.0, "amount_atomic": 2000}], + ) + assert [r["txid"] for r in new] == ["tx-new"] + again = sm.add_payouts( + "monero", + "wallet-beta", + [{"txid": "tx-new", "height": 9, "ts": 9.0, "amount_atomic": 2000}], + ) + assert again == [] + rows = sm.get_payouts("monero", "wallet-beta") + assert [r["txid"] for r in rows] == ["tx-new", "tx-old"] + assert sm.get_payout_max_height("monero", "wallet-beta") == 9 + finally: + sm.close() + conn = sqlite3.connect(db) + try: + stored = conn.execute("SELECT chain, txid, amount_atomic FROM payouts").fetchall() + finally: + conn.close() + assert ("monero", "tx-new", 2000) in stored + + +_BOOT = Path(__file__).resolve().parents[3] / "os" / "overlay" / "pithead-boot" + + +@pytest.mark.skipif(not _BOOT.is_file(), reason="needs the repo checkout's os/overlay/pithead-boot") +class TestSchemaHoldAcrossAFailedUpdate: + _PREVIOUS_RELEASE_INSERT = ( + "INSERT OR IGNORE INTO payouts " + "(chain, txid, height, ts, amount_atomic) VALUES (?, ?, ?, ?, ?)" + ) + + def _arm_from_an_uncommitted_candidate(self, tmp_path, data_dir): + run = tmp_path / "run" + bin_dir = tmp_path / "bin" + run.mkdir() + bin_dir.mkdir() + (run / ".env").write_text(f"DASHBOARD_DATA_DIR={data_dir}\n") + cmdline = tmp_path / "cmdline" + cmdline.write_text("rootwait rauc.slot=B\n") + rauc = bin_dir / "rauc" + rauc.write_text( + "#!/usr/bin/env bash\n" + 'echo \'{"slots":{"rootfs":{"B":{"state":"booted",' + '"bootname":"B","boot_status":"bad"}}}}\'\n' + ) + rauc.chmod(0o755) + armed = subprocess.run( # noqa: S603 + [shutil.which("bash"), "-c", 'source "$1" && schema_hold_arm', "arm", str(_BOOT)], + cwd=run, + env={ + **os.environ, + "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", + "PITHEAD_CMDLINE": str(cmdline), + }, + capture_output=True, + text=True, + check=False, + ) + assert armed.returncode == 0, armed.stderr + assert "dashboard schema hold armed" in armed.stdout + + def test_previous_release_records_payouts_after_the_candidate_falls_back(self, tmp_path): + data_dir = tmp_path / "dashboard" + data_dir.mkdir() + db = str(data_dir / "mining_data.db") + TestSchemaMigrationHold()._seed_legacy_db(db) + self._arm_from_an_uncommitted_candidate(tmp_path, data_dir) + StateManager(db_path=db).close() + conn = sqlite3.connect(db) + try: + with conn: + conn.execute( + self._PREVIOUS_RELEASE_INSERT, ("monero", "tx-fallback", 12, 12.0, 3000) + ) + stored = conn.execute( + "SELECT chain, txid, height, ts, amount_atomic FROM payouts " + "WHERE chain = ? ORDER BY ts DESC", + ("monero",), + ).fetchall() + finally: + conn.close() + assert stored[0] == ("monero", "tx-fallback", 12, 12.0, 3000) diff --git a/docs/dev/appliance-release.md b/docs/dev/appliance-release.md index b2520cdd9b..7a6d627614 100644 --- a/docs/dev/appliance-release.md +++ b/docs/dev/appliance-release.md @@ -214,6 +214,26 @@ ignores the slot-qualified marker). A non-migrating install clears any stale mar The `db_schema` field the plan also lists stays out until something reads it — an unread manifest field is a claim, not a contract. +**Where the dashboard's own migrations run (#3998).** The `data_migration` hold covers chain +data only, and every candidate boot can fall back before it commits, migrating or not. So +`pithead-boot` defers the dashboard's SQLite migrations relative to the commit as well. After +rendering, it reads the booted slot's good state from `rauc status --output-format=json`; +until the slot is marked good it writes `.os-schema-held` into the dashboard's data directory. +While that marker stands the dashboard keeps the `payouts` table in the previous release's +shape — created that way on a fresh database, with the payout identity rebuild skipped, and +read and written through that shape — so a fallback into the previous release finds the schema +it can write and keeps recording payouts. When the health gate passes, `mark-good` runs first; +the boot then removes the marker and restarts the dashboard, and the deferred migration runs +there — after the commit, on a slot no fallback can leave. A boot onto a slot that is already +committed removes a stale marker instead. An unknown slot state (no `rauc.slot` boot +argument, a failing or unparseable `rauc status`, no `jq`) defers, a marker that cannot be written +fails the boot with the slot left uncommitted, and a restart that faults after commit logs a `FAULT` +line without uncommitting the slot. This deferral needs no bundle +declaration: it arms on every uncommitted appliance boot. It currently holds one migration, +the 2.0.3 payout identity rebuild; a release that ships a different schema change an earlier +release cannot read safely must add it to the same hold in `storage_schema.py` — additive +changes alone may stay outside it. + ## Development loop Everything runs from the repo root on a Linux box with docker, KVM and libvirt. The diff --git a/os/overlay/pithead-boot b/os/overlay/pithead-boot index eb498c5b10..53f7335c93 100755 --- a/os/overlay/pithead-boot +++ b/os/overlay/pithead-boot @@ -35,7 +35,6 @@ BOOT_FAIL_COUNT=.boot-gate-failures # Where doctor's verdicts land while this gate is looping: /run leaves the last failing check without # wearing /data. A plain variable: the suite points it somewhere writable. BOOT_DOCTOR_JSON=/run/pithead-boot-doctor.json -boot_gate_passed() { rm -f "$BOOT_FAIL_COUNT" .config-reset-good-slot; } fail_boot() { # echo "pithead-boot: $1 — slot left uncommitted so A/B fallback stays armed" >&2 local status_problems @@ -328,7 +327,7 @@ fi /usr/local/sbin/pithead-media-config ./pithead render || fail_boot "the derived config could not be rendered" - +schema_hold_arm || fail_boot "the dashboard schema hold marker could not be written" if [ "$hold_chain" = 1 ]; then PITHEAD_HOLD_CHAIN=1 ./pithead up || boot_up_failed $? else diff --git a/os/overlay/pithead-boot-stack-health b/os/overlay/pithead-boot-stack-health index 2ac1b04660..fb5cf0300c 100644 --- a/os/overlay/pithead-boot-stack-health +++ b/os/overlay/pithead-boot-stack-health @@ -65,3 +65,43 @@ gate_probe_header() { capability=$(printf 'pithead-boot-health-v1:%s' "$(gate_env_val DASHBOARD_AUTH_HASH_B64)" | sha256sum | cut -d' ' -f1) printf 'X-Pithead-Boot-Probe: %s\n' "$capability" } + +boot_gate_passed() { + rm -f "$BOOT_FAIL_COUNT" .config-reset-good-slot + schema_hold_release +} + +SCHEMA_HOLD_NAME=.os-schema-held +booted_slot_committed() { + local slot status + slot=$(tr ' ' '\n' <"${PITHEAD_CMDLINE:-/proc/cmdline}" 2>/dev/null | sed -n 's/^rauc\.slot=\([AB]\)$/\1/p') + [ -n "$slot" ] || return 1 + command -v jq >/dev/null 2>&1 || return 1 + status=$(rauc status --output-format=json 2>/dev/null) || return 1 + jq -e --arg slot "$slot" \ + '[.slots[] | .[] | select(.state == "booted" and .bootname == $slot and .boot_status == "good")] | length == 1' \ + <<<"$status" >/dev/null 2>&1 +} + +schema_hold_arm() { + local dir + dir=$(gate_env_val DASHBOARD_DATA_DIR) + [ -n "$dir" ] || return 0 + if booted_slot_committed; then + rm -f "$dir/$SCHEMA_HOLD_NAME" && sync + return 0 + fi + mkdir -p "$dir" && : >"$dir/$SCHEMA_HOLD_NAME" && sync && + echo "pithead-boot: dashboard schema hold armed — the booted slot is uncommitted, so the dashboard keeps its previous-release database schema until the gate commits" +} + +schema_hold_release() { + local dir + dir=$(gate_env_val DASHBOARD_DATA_DIR) + [ -n "$dir" ] || return 0 + [ -e "$dir/$SCHEMA_HOLD_NAME" ] || return 0 + rm -f "$dir/$SCHEMA_HOLD_NAME" && sync + echo "pithead-boot: dashboard schema hold released — restarting the dashboard to run its deferred database migrations" + ${PITHEAD_DASHBOARD_RESTART_CMD:-docker compose restart dashboard} >/dev/null 2>&1 || + echo "pithead-boot: FAULT — the committed slot could not restart the dashboard to run its deferred database migrations; run 'docker compose restart dashboard' from /data/pithead" >&2 +} diff --git a/tests/os/phases/update-dashboard.sh b/tests/os/phases/update-dashboard.sh index bc9d9a9559..15c833fcf4 100644 --- a/tests/os/phases/update-dashboard.sh +++ b/tests/os/phases/update-dashboard.sh @@ -333,6 +333,17 @@ phase_update_dashboard() { # /dev/null | grep -F 'dashboard schema hold released' >/dev/null" && break + sleep 10 + done + if _ssh "journalctl -u pithead-boot 2>/dev/null | grep -F 'dashboard schema hold armed' >/dev/null" && + _ssh "journalctl -u pithead-boot 2>/dev/null | grep -F 'dashboard schema hold released' >/dev/null"; then + ok "leg 4: pithead-boot's journal armed the dashboard schema hold on the uncommitted boot and released it at the commit" + else + bad "leg 4: pithead-boot's journal lacks the schema hold arm and release lines — the hold never ran on the real boot" + fi if curl -sSk -u "$DASH_USER:$DASH_PASS" "https://$ip/api/state" 2>/dev/null | jq -e '.os_update.verdict.outcome == "updated"' >/dev/null 2>&1; then ok "leg 4: the success banner's verdict reaches /api/state" diff --git a/tests/os/phases/update-healthgate-leg.sh b/tests/os/phases/update-healthgate-leg.sh index 5ed226e0f5..b84e069c17 100644 --- a/tests/os/phases/update-healthgate-leg.sh +++ b/tests/os/phases/update-healthgate-leg.sh @@ -94,6 +94,7 @@ _update_healthgate_leg_body() { ok "leg 5: FALLBACK — the unhealthy dashboard held the gate and the guest fell back to v2" else bad "leg 5: expected the guest back on v2 after the fault boot's gate refusal, got '${fmarker:-none}' (30 min bound)" + return fi if tail -c "+$((fserial_mark + 1))" "$SERIAL" | grep -F 'Pithead is still starting (' | grep -F 'of about 16 minutes). Leave it powered on: if an update never becomes healthy, the machine goes back to the previous version by itself.' >/dev/null; then ok "leg 5: the fault boot's serial console reports health-gate progress and automatic update fallback" @@ -123,6 +124,23 @@ _update_healthgate_leg_body() { else bad "leg 5: the served banner module has no 'Blocked by:' cause" fi + local xjournal fjournal rdeadline=$(($(date +%s) + 1200)) + xjournal=$(_ssh "journalctl -u pithead-boot -b -1 2>/dev/null" 2>/dev/null) + if grep -qF 'dashboard schema hold armed' <<<"$xjournal" && ! grep -qF 'dashboard schema hold released' <<<"$xjournal"; then + ok "leg 5: the failed candidate boot armed the dashboard schema hold and never released it" + else + bad "leg 5: the failed candidate boot's journal does not show the dashboard schema hold armed and left unreleased" + fi + while [ "$(date +%s)" -lt "$rdeadline" ]; do + _ssh "journalctl -u pithead-boot -b 0 2>/dev/null | grep -F 'dashboard schema hold released' >/dev/null" && break + sleep 15 + done + fjournal=$(_ssh "journalctl -u pithead-boot -b 0 2>/dev/null" 2>/dev/null) + if grep -qF 'dashboard schema hold armed' <<<"$fjournal" && grep -qF 'dashboard schema hold released' <<<"$fjournal"; then + ok "leg 5: the fallback boot armed the dashboard schema hold and released it once its own gate committed" + else + bad "leg 5: the fallback boot's journal has no schema hold arm and release lines (20 min bound) — the hold never ran to completion on the surviving boot" + fi } phase_update_healthgate_leg() { diff --git a/tests/os/selftest-schema-hold.sh b/tests/os/selftest-schema-hold.sh new file mode 100644 index 0000000000..7452532f7a --- /dev/null +++ b/tests/os/selftest-schema-hold.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +set -uo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +T=$(mktemp -d) +trap 'rm -rf "$T"' EXIT + +fail() { + echo "FAIL: $1" + exit 1 +} + +mkdir -p "$T/bin" "$T/dash" "$T/run" +cat >"$T/bin/rauc" <<'EOF' +#!/usr/bin/env bash +if [ -n "${RAUC_STATUS_RC:-}" ]; then + exit "$RAUC_STATUS_RC" +fi +cat "$RAUC_STATUS_FILE" +EOF +cat >"$T/bin/docker" <<'EOF' +#!/usr/bin/env bash +echo "[docker] $*" >>"${DOCKER_LOG:-/dev/null}" +exit "${DOCKER_RC:-0}" +EOF +chmod +x "$T/bin/rauc" "$T/bin/docker" +export PATH="$T/bin:$PATH" + +cd "$T/run" || exit 1 +printf 'DASHBOARD_DATA_DIR=%s\n' "$T/dash" >.env +printf 'rootwait rauc.slot=A\n' >"$T/cmdline" +export PITHEAD_CMDLINE="$T/cmdline" + +# shellcheck source=os/overlay/pithead-boot +source "$HERE/../../os/overlay/pithead-boot" || fail "pithead-boot must source" + +printf '%s' '{"slots":{"rootfs":{"A":{"state":"booted","bootname":"A","boot_status":"good"},"B":{"state":"inactive","bootname":"other","boot_status":"good"}}}}' >"$T/good.json" +printf '%s' '{"slots":{"rootfs":{"A":{"state":"booted","bootname":"A","boot_status":"bad"}}}}' >"$T/bad.json" +printf '%s' '{"slots":{"rootfs":{"B":{"state":"booted","bootname":"B","boot_status":"good"}}}}' >"$T/other.json" +printf '%s' 'not json' >"$T/broken.json" +export RAUC_STATUS_FILE="$T/good.json" RAUC_STATUS_RC="" + +marker="$T/dash/.os-schema-held" +: >"$T/docker.log" + +schema_hold_arm +[ ! -e "$marker" ] || fail "a committed slot must leave no marker" + +RAUC_STATUS_FILE="$T/bad.json" +schema_hold_arm >"$T/arm.out" 2>&1 +[ -e "$marker" ] || fail "an uncommitted slot must write the hold marker" +grep -q 'dashboard schema hold armed' "$T/arm.out" || fail "arming the hold must report it" +schema_hold_arm +[ -e "$marker" ] || fail "re-arming must keep the hold marker" +DOCKER_LOG="$T/docker.log" schema_hold_release >"$T/rel.out" 2>&1 || fail "a clean release must not fail the boot" +[ ! -e "$marker" ] || fail "release must remove the marker" +grep -q 'dashboard schema hold released' "$T/rel.out" || fail "releasing the hold must report it" +: >"$T/arm2.out" +RAUC_STATUS_FILE="$T/good.json" +schema_hold_arm >"$T/arm2.out" 2>&1 +grep -q 'dashboard schema hold' "$T/arm2.out" && fail "a committed boot must not report a hold" + +RAUC_STATUS_FILE="$T/other.json" +schema_hold_arm +[ -e "$marker" ] || fail "a good verdict for another slot must defer" +rm -f "$marker" + +RAUC_STATUS_FILE="$T/broken.json" +schema_hold_arm +[ -e "$marker" ] || fail "unparseable rauc status must defer" + +RAUC_STATUS_FILE="$T/good.json" +RAUC_STATUS_RC=3 +rm -f "$marker" +schema_hold_arm +[ -e "$marker" ] || fail "a failing rauc status must defer" +RAUC_STATUS_RC="" +touch "$marker" +RAUC_STATUS_RC=3 +schema_hold_arm +RAUC_STATUS_RC="" +[ -e "$marker" ] || fail "an uncertain verdict must never clear the marker" + +printf 'rootwait quiet\n' >"$T/cmdline" +rm -f "$marker" +schema_hold_arm +[ -e "$marker" ] || fail "an unknown booted slot must defer" +printf 'rootwait rauc.slot=A\n' >"$T/cmdline" +rm -f "$marker" + +mv .env .env.bak +rm -f "$marker" +schema_hold_arm +mv .env.bak .env +[ ! -e "$marker" ] || fail "an unrendered .env cannot arm" + +RAUC_STATUS_FILE="$T/bad.json" +schema_hold_arm +RAUC_STATUS_FILE="$T/good.json" +schema_hold_arm +[ ! -e "$marker" ] || fail "a committed boot must clear the stale marker" + +: >"$T/docker3.log" +restarts() { grep -c 'compose restart dashboard' "$T/docker3.log" || true; } +RAUC_STATUS_FILE="$T/bad.json" +schema_hold_arm +schema_hold_arm +[ "$(restarts)" = 0 ] || fail "arm must never restart" +RAUC_STATUS_FILE="$T/good.json" +DOCKER_LOG="$T/docker3.log" schema_hold_release || fail "release must not fail the boot" +[ ! -e "$marker" ] || fail "release must remove the marker" +[ "$(restarts)" = 1 ] || fail "release must restart the dashboard exactly once" +DOCKER_LOG="$T/docker3.log" schema_hold_release || fail "release without a marker must be a no-op" +[ "$(restarts)" = 1 ] || fail "no marker, no restart" + +RAUC_STATUS_FILE="$T/bad.json" +schema_hold_arm +DOCKER_LOG="$T/docker2.log" DOCKER_RC=1 schema_hold_release >"$T/release2.out" 2>&1 || fail "a faulty restart must stay non-fatal" +[ ! -e "$marker" ] || fail "the marker must drop even when the restart faults" +grep -q 'FAULT' "$T/release2.out" || fail "a faulty restart must alert" + +RAUC_STATUS_FILE="$T/bad.json" +schema_hold_arm +[ -e "$marker" ] || fail "re-arm for the gate-pass wiring check" +: >"$T/docker4.log" +DOCKER_LOG="$T/docker4.log" boot_gate_passed || fail "the gate pass must not fail" +[ ! -e "$marker" ] || fail "boot_gate_passed must release the schema hold" +gate_restarts=$(grep -c 'compose restart dashboard' "$T/docker4.log" || true) +[ "$gate_restarts" = 1 ] || fail "the gate pass must restart the dashboard exactly once" + +printf 'selftest-schema-hold: ok\n' From 741fc404e9b4a2acd107c9a7740649fb31b0cd2a Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 07:53:56 -0600 Subject: [PATCH 005/112] Keep a committed slot committed when Set up again is abandoned (#3960) (#3989) * Commit the booted slot when Set up again opens with no update in flight (#3960) Co-Authored-By: Claude Sonnet 5.5 * Test the abandoned Set up again fallback with the real interrupted verdict (#3960) Co-Authored-By: Claude Sonnet 5.5 * Say which updates Set up again leaves uncommitted (#3960) Co-Authored-By: Claude Sonnet 5.5 * Poll for the set-up-again slot commit instead of reading it once (#3960) Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- docs/appliance.md | 6 ++- lib/pithead/12a-setup-again.sh | 14 +++++++ lib/pithead/12a-wizard-page.sh | 1 + os/overlay/pithead-setup-again.service | 8 ---- tests/os/setup-again-leg.sh | 10 +++++ .../test-appliance-reset-slot-boot.sh | 38 ++++++++++++++++++- 6 files changed, 66 insertions(+), 11 deletions(-) diff --git a/docs/appliance.md b/docs/appliance.md index 48e9de6b8d..d3d465a60d 100644 --- a/docs/appliance.md +++ b/docs/appliance.md @@ -586,7 +586,11 @@ rig mining at a pool as a worker, or a Pithead coordinator. Two choices: - **Keep it** closes the page and starts the machine exactly as it was. Nothing changes, and the same holds for a page you never touch or a machine switched off part way: the - saved settings are replaced only when you accept new ones. + saved settings are replaced only when you accept new ones, and the machine comes back to + the release it was already running. The exception is an update from the dashboard that + has not finished committing: switching off with the page open falls back to the previous + release, exactly as it would have with the page never opened. An update installed with + `pithead os-update` leaves no such record, so opening the page on its first boot commits it. - **Set up again** opens the form filled in with the saved answers and the secrets left out: a stratum password, and for a coordinator the dashboard login and node credentials, are typed again. Accept the form and the machine provisions itself with the new answers. diff --git a/lib/pithead/12a-setup-again.sh b/lib/pithead/12a-setup-again.sh index b4ee132586..3274d3fff3 100644 --- a/lib/pithead/12a-setup-again.sh +++ b/lib/pithead/12a-setup-again.sh @@ -43,3 +43,17 @@ wizard_keep_requested() { # rm -f "$1/keep-role" _console "Setup closed: the saved settings are kept. The machine is starting as it was." } + +setup_again_commit_slot() { + setup_again_mode || return 0 + [ -e config.json ] || [ -e machine-role ] || return 0 + command -v rauc >/dev/null 2>&1 || return 0 + [ ! -e data/os-update/in-flight.json ] || return 0 + local slot state + slot=$(os_booted_slot) || return 1 + case "$slot" in A | B) ;; *) return 1 ;; esac + state=$(grub-editenv "${PITHEAD_GRUBENV:-/boot/efi/grub/grubenv}" list) || return 1 + printf '%s\n' "$state" | grep -qx "${slot}_OK=1" || return 1 + [ "$("$1" inspect --format '{{.State.Running}}' pithead-wizard)" = true ] || return 1 + rauc status mark-good +} diff --git a/lib/pithead/12a-wizard-page.sh b/lib/pithead/12a-wizard-page.sh index f9e19895b1..6889079787 100644 --- a/lib/pithead/12a-wizard-page.sh +++ b/lib/pithead/12a-wizard-page.sh @@ -20,5 +20,6 @@ wizard_start_page() { error "Could not start the wizard container ($engine, $image). Pre-seed config.json or run '$0 firstboot-wizard --cli'." } [ "$installer" -eq 1 ] || reset_slot_restore_good "$engine" || warn "Could not restore the reset slot's good state; reboot may fall back." + [ "$installer" -eq 1 ] || setup_again_commit_slot "$engine" || warn "Could not commit the set-up-again slot; reboot may fall back." wizard_announce_setup "$host_addresses" "$token" "$cert_fp" || error "Could not publish the setup console announcement." } diff --git a/os/overlay/pithead-setup-again.service b/os/overlay/pithead-setup-again.service index 2c09367519..d5c5cc6dfe 100644 --- a/os/overlay/pithead-setup-again.service +++ b/os/overlay/pithead-setup-again.service @@ -6,14 +6,6 @@ Description=Pithead setup wizard beside the saved role (the boot menu's "Set up # PROVISIONED machine, the same two triggering shapes pithead-boot.service keys on: before a role # exists pithead-firstboot owns the boot whatever the cmdline says, so the two units are # mutually exclusive by construction rather than by ordering. -# -# Before pithead-boot: the role's normal boot — the stack, or a rig's miner — waits behind the -# page. "Keep it" ends this unit with nothing on /data touched, and pithead-boot then runs the -# boot the machine would have taken from the default entry. A new role accepted on the page is -# provisioned by the wizard exactly as on a first boot; pithead-boot's pass after it is the same -# idempotent every-boot pass it always is. The booted slot is not committed while the page is -# open, so a freshly updated slot that is never confirmed here falls back exactly as one that -# never served would — that is the A/B promise, not a gap. ConditionKernelCommandLine=pithead.setup=1 ConditionPathExists=|/data/pithead/config.json ConditionPathExists=|/data/pithead/machine-role diff --git a/tests/os/setup-again-leg.sh b/tests/os/setup-again-leg.sh index 9d2c1c0f1b..a95b68f38d 100644 --- a/tests/os/setup-again-leg.sh +++ b/tests/os/setup-again-leg.sh @@ -218,6 +218,16 @@ rig_setup_again_coordinator_leg() { *pithead.setup=1*rauc.slot=B* | *rauc.slot=B*pithead.setup=1*) ok "after the update the setup entry followed the default to slot B" ;; *) bad "the setup entry did not follow the default to slot B — cmdline: $(printf '%s' "$cmd" | cut -c1-160)" ;; esac + n=0 + while [ "$n" -lt 12 ]; do + case "$(_ssh 'grub-editenv /boot/efi/grub/grubenv list' 2>/dev/null | tr -d '\r' | tr '\n' ' ')" in + *"B_OK=1 "*"B_TRY=0"* | *"B_TRY=0"*"B_OK=1"*) break ;; + esac + sleep 5 + n=$((n + 1)) + done + [ "$n" -lt 12 ] && ok "with the page open the updated slot stays committed (B_OK=1 B_TRY=0): abandoning it boots B again (#3960)" || + bad "slot B is not committed 60 s into the set-up-again page — a reboot would fall back to A (#3960)" _setup_again_session || return scode=$(curl -sSk -b "$jar" --data "monero_wallet=$HARNESS_WALLET&tari_wallet=$HARNESS_TARI&pool=mini" "https://$ip/submit" -o /dev/null -w '%{http_code}' 2>/dev/null) [ "$scode" = "200" ] || { diff --git a/tests/stack/appliance/test-appliance-reset-slot-boot.sh b/tests/stack/appliance/test-appliance-reset-slot-boot.sh index 65b6abfe1a..ac66c51f8a 100644 --- a/tests/stack/appliance/test-appliance-reset-slot-boot.sh +++ b/tests/stack/appliance/test-appliance-reset-slot-boot.sh @@ -36,7 +36,9 @@ rb_seed() { printf 'ORDER="B A"\nA_OK=1\nA_TRY=0\nB_OK=1\nB_TRY=0\n' >"$RB/state" printf 'rauc.slot=B\n' >"$RB/cmdline" printf '%040d\n' 1 >"$RB/source" - rm -f "$RB/data/pithead/config.json" "$RB/data/pithead/.config-reset-good-slot" + rm -f "$RB/data/pithead/config.json" "$RB/data/pithead/.config-reset-good-slot" \ + "$RB/data/pithead/machine-role" "$RB/data/pithead/VERSION" + rm -rf "$RB/data/pithead/data" } rb_unit_runs() { # Read triggering OR and ordinary AND conditions from the shipped unit. local path trigger=no trigger_ok=no @@ -53,6 +55,7 @@ rb_unit_runs() { # Read triggering OR and ordinary AND conditions from the shipp [ "$trigger" = no ] || [ "$trigger_ok" = yes ] } rb_boot() { + local rb_entry="${1:-default}" ( # shellcheck disable=SC1091 # generated from the real grub.cfg above source "$RB/state" @@ -60,8 +63,11 @@ rb_boot() { source "$RB/select.sh" printf 'ORDER="%s"\nA_OK=%s\nA_TRY=%s\nB_OK=%s\nB_TRY=%s\n' "$ORDER" "$A_OK" "$A_TRY" "$B_OK" "$B_TRY" >"$RB/state" printf 'rauc.slot=%s\n' "$CURRENT_SLOT" >"$RB/cmdline" + if [ "$rb_entry" = setup-again ]; then printf 'pithead.setup=1\n' >>"$RB/cmdline"; fi ) - if rb_unit_runs pithead-firstboot; then + if grep -qx 'pithead.setup=1' "$RB/cmdline" && rb_unit_runs pithead-setup-again; then + (PITHEAD_SETUP_AGAIN=1 rb_call setup_again_commit_slot engine >/dev/null 2>&1) || true + elif rb_unit_runs pithead-firstboot; then rb_call reset_slot_restore_good engine >/dev/null elif rb_unit_runs pithead-boot; then # Successful provisioned health gate: the real cleanup helper and RAUC adapter. @@ -124,5 +130,33 @@ rm -f "$RB/data/pithead/config.json" printf 'rig\n' >"$RB/data/pithead/machine-role" rb_call reset_slot_restore_good engine assert_contains "retained authority cannot commit a provisioned setup-again rig" "$(cat "$RB/state")" B_TRY=1 +rb_seed +printf 'rig\n' >"$RB/data/pithead/machine-role" +rb_boot setup-again +assert_contains "set up again commits a committed slot before the page (#3960)" "$(cat "$RB/state")" "B_TRY=0" +rb_boot +assert_eq "abandoning set up again boots the same committed slot (#3960)" "$(cat "$RB/cmdline")" rauc.slot=B +assert_contains "the boot after an abandoned page holds it committed (#3960)" "$(cat "$RB/state")" "B_TRY=0" +rb_seed +printf 'rig\n' >"$RB/data/pithead/machine-role" +printf '2.0.2\n' >"$RB/data/pithead/VERSION" +mkdir -p "$RB/data/pithead/data/os-update" +printf '{"from":"2.0.2","to":"2.0.3","gate":"started"}\n' >"$RB/data/pithead/data/os-update/in-flight.json" +rb_boot setup-again +assert_contains "an update in flight keeps the set-up-again slot uncommitted (#3960)" "$(cat "$RB/state")" "B_TRY=1" +rb_boot +assert_eq "abandoning set up again during an update falls back to A (#3960)" "$(cat "$RB/cmdline")" rauc.slot=A +( + cd "$RB/data/pithead" || exit 1 + export OS_INFLIGHT=data/os-update/in-flight.json OS_STATE_DIR=data/control/results + # shellcheck disable=SC1091 # ROOT is the suite's real tree + source "$ROOT/os/overlay/pithead-boot" 2>/dev/null + os_update_rollback_verdict >/dev/null +) +rb_verdict="$RB/data/pithead/data/control/results/os-update-state.json" +assert_eq "the fallback boot records the interrupted verdict (#3960)" \ + "$(jq -r '.verdict.interrupted' "$rb_verdict")" true +assert_eq "and names the unverified update rolled back (#3960)" \ + "$(jq -r '.verdict.outcome' "$rb_verdict")" rolled_back unset RB PITHEAD_APPLIANCE PITHEAD_CMDLINE PITHEAD_BUILD_COMMIT_FILE PITHEAD_GRUBENV unset -f rb_call rb_seed rb_unit_runs rb_boot From 3798407d8ef68290d3928da636b61780f5976fce Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:51:35 -0600 Subject: [PATCH 006/112] =?UTF-8?q?os=20tests:=20fix=20#3943=20=E2=80=94?= =?UTF-8?q?=20remove=20saved=20RAUC=20bundles=20from=20/tmp=20on=20exit=20?= =?UTF-8?q?(#3982)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * os tests: keep saved RAUC bundles under an owned scratch dir removed on exit (#3943) Co-Authored-By: Claude Sonnet 5.5 * os tests: build the floor-fallback bundle tree under the owned scratch dir (#3943) Co-Authored-By: Claude Sonnet 5.5 * os tests: shfmt the scratch-cleanup selftest (#3943) Co-Authored-By: Claude Sonnet 5.5 * os tests: drop explanatory comments from the edited hunks (#3943) Co-Authored-By: Claude Sonnet 5.5 * Re-run checks on a fresh head for #3943 Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- tests/os/data-floor-fallback-leg.sh | 5 +-- tests/os/lib/core.sh | 7 ++-- tests/os/migration-recovery.md | 5 +-- tests/os/migration-same-version-fallback.sh | 6 ++-- tests/os/selftest-migration-snapshot.sh | 38 +++++++++++++++++++++ 5 files changed, 49 insertions(+), 12 deletions(-) diff --git a/tests/os/data-floor-fallback-leg.sh b/tests/os/data-floor-fallback-leg.sh index bc15c7b312..37bb9f8beb 100644 --- a/tests/os/data-floor-fallback-leg.sh +++ b/tests/os/data-floor-fallback-leg.sh @@ -43,8 +43,9 @@ _build_bundle_stamped() { cert="$(cd "$(dirname "$RAUC_CERT")" && pwd -P)/$(basename "$RAUC_CERT")" || return 1 key="$(cd "$(dirname "$RAUC_KEY")" && pwd -P)/$(basename "$RAUC_KEY")" || return 1 keyring="$(cd "$(dirname "$RAUC_KEYRING")" && pwd -P)/$(basename "$RAUC_KEYRING")" || return 1 - wt=$(mktemp -d /tmp/pithead-floor-fallback.XXXXXX) || return 1 - out=/tmp/os-floor-fallback-$marker.raucb + mkdir -p "$HOST_SCRATCH" || return 1 + wt=$(mktemp -d "$HOST_SCRATCH/floor-fallback.XXXXXX") || return 1 + out="$HOST_SCRATCH/os-floor-fallback-$marker.raucb" { git archive HEAD | tar -x -C "$wt" && printf '%s\n' "$version" >"$wt/VERSION" && diff --git a/tests/os/lib/core.sh b/tests/os/lib/core.sh index eb3b260ca6..2ede67e40a 100644 --- a/tests/os/lib/core.sh +++ b/tests/os/lib/core.sh @@ -18,12 +18,8 @@ it_err() { printf ' \033[1;31m!\033[0m %s\n' "$1" >&2; } have() { command -v "$1" >/dev/null 2>&1; } KEY="$HOME/.ssh/pithead-os-test" ip="" -# Overwritten by every _ssh call with that call's stderr (empty on success). Not a log — just the -# LAST attempt's error text, so a caller that just gave up can classify why without another round -# trip. See _ssh_unreachable_reason. SSH_ERR="/tmp/pithead-os-ssh.err" -# A fresh run must not inherit the last run's preserved console: the cleanup copy below is -# no-clobber (the at-assertion copy is the authoritative one), so clear the slate here. +HOST_SCRATCH="${TMPDIR:-/tmp}/pithead-os-scratch.$$" rm -f "$SERIAL.failed" # The wallet every phase submits. It must be checksum-VALID: p2pool refuses a well-formed but # checksum-invalid address at startup with a SIGABRT and crash-loops (#829), which killed the @@ -358,6 +354,7 @@ cleanup() { cp "$SERIAL" "$SERIAL.failed" 2>/dev/null && info "console from the failed run kept at $SERIAL.failed" fi + rm -rf -- "$HOST_SCRATCH" || approval_cleanup_rc=1 case "${IMAGE_UPGRADE_HOST_STAGE:-}" in /tmp/pithead-os-image-upgrade.*) rm -rf -- "$IMAGE_UPGRADE_HOST_STAGE" || approval_cleanup_rc=1 ;; esac diff --git a/tests/os/migration-recovery.md b/tests/os/migration-recovery.md index b77bcec711..5c4b7f89e7 100644 --- a/tests/os/migration-recovery.md +++ b/tests/os/migration-recovery.md @@ -37,8 +37,9 @@ applied through the authenticated configuration flow. A fresh persisted release, direct synchronized RPC, healthy mining services and an increasing hash counter establish recovery. The original local configuration is restored before the same-version and floor-fallback legs. Before building a fault bundle, the battery -retains the good bundle in `TMPDIR` when set, otherwise beside the built bundle -in its job-owned build directory. The retained copy uses a `.saved` suffix so +retains the good bundle in the run's scratch directory, which the battery's exit +cleanup removes with the floor-fallback bundle, so no saved bundle outlives the +run. The retained copy uses a `.saved` suffix so the builder’s `*.raucb` discovery cannot select it instead of a later fault bundle. An unset or empty `TMPDIR` does not prevent the fallback proof. diff --git a/tests/os/migration-same-version-fallback.sh b/tests/os/migration-same-version-fallback.sh index 999035bace..1902ca9867 100644 --- a/tests/os/migration-same-version-fallback.sh +++ b/tests/os/migration-same-version-fallback.sh @@ -1,8 +1,8 @@ # shellcheck shell=bash -# Real equal-version A/B fallback after a migrating candidate fails its health gate. preserve_migration_bundle() { - local saved - saved=$(mktemp "${TMPDIR:-$(dirname -- "$1")}/pithead-migration-good.XXXXXX.saved") || return 1 + local saved dir="${HOST_SCRATCH:-${TMPDIR:-$(dirname -- "$1")}}" + mkdir -p "$dir" || return 1 + saved=$(mktemp "$dir/pithead-migration-good.XXXXXX.saved") || return 1 cp "$1" "$saved" || { rm -f "$saved" return 1 diff --git a/tests/os/selftest-migration-snapshot.sh b/tests/os/selftest-migration-snapshot.sh index 1a9715aafc..74fc18a3fa 100755 --- a/tests/os/selftest-migration-snapshot.sh +++ b/tests/os/selftest-migration-snapshot.sh @@ -47,4 +47,42 @@ for temporary_dir in configured unset empty; do rm "$saved" ) done +( + S="$T/leak" + mkdir -p "$S/fakebin/src/os/rauc" "$S/tmp" + printf '#!/bin/sh\nexit 0\n' >"$S/fakebin/src/os/build-image.sh" + printf '#!/bin/sh\nmkdir -p os/rauc/build && printf bundle >os/rauc/build/update.raucb\n' >"$S/fakebin/src/os/rauc/mkbundle.sh" + chmod +x "$S/fakebin/src/os/build-image.sh" "$S/fakebin/src/os/rauc/mkbundle.sh" + printf '#!/bin/sh\n[ "$1" = archive ] && exec tar -c -C "%s" os\nexit 1\n' "$S/fakebin/src" >"$S/fakebin/git" + chmod +x "$S/fakebin/git" + export PATH="$S/fakebin:$PATH" TMPDIR="$S/tmp" OS_RUN_SUITE=1 SCRIPT_DIR="$HERE" + SERIAL="$S/serial" PASS=0 FAIL=0 KEEP=1 VM=selftest DISK="$S/disk" SSH_ERR="$S/ssh-err" KEY="$S/key" + printf 'pub\n' >"$KEY.pub" + # shellcheck source=tests/os/lib/core.sh + source "$HERE/lib/core.sh" + # shellcheck source=tests/os/data-floor-fallback-leg.sh + source "$HERE/data-floor-fallback-leg.sh" + package_appliance_cleanup() { :; } + approval_fixture_cleanup() { :; } + resolve_signing_material() { RAUC_CERT="$S/cert" RAUC_KEY="$S/key" RAUC_KEYRING="$S/keyring"; } + printf 'good bundle\n' >"$S/update.raucb" + saved=$(preserve_migration_bundle "$S/update.raucb") + stamped=$(_build_bundle_stamped vfail 99.0.0 99.0.0) + for f in "$saved" "$stamped"; do + [ -f "$f" ] || { + echo "FAIL: $f was not created" + exit 1 + } + [[ "$f" == "$HOST_SCRATCH/"* ]] || { + echo "FAIL: $f is outside the owned scratch directory" + exit 1 + } + done + cleanup + [ -z "$(find "$S/tmp" -name 'pithead-migration-*' -o -name 'os-floor-fallback-*')" ] && + [ ! -e "$HOST_SCRATCH" ] || { + echo 'FAIL: cleanup left saved RAUC bundles behind' + exit 1 + } +) echo 'selftest-migration-bundle-preservation: PASS' From 6c9374e6b56d165dcad948790107059e7102041b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:33:01 -0600 Subject: [PATCH 007/112] build(deps): Bump astral-sh/setup-uv from 10.3.2 to 10.3.3 in the actions group (#3999) Bumps the actions group with 1 update: [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv). Updates `astral-sh/setup-uv` from 10.3.2 to 10.3.3 - [Release notes](https://github.com/astral-sh/setup-uv/releases) - [Commits](https://github.com/astral-sh/setup-uv/compare/07a047e608db84b3d8c06cd9a7c7dcc9c355c18e...68559e99cc807c1eb7e9238fd43a15bba460eec2) --- updated-dependencies: - dependency-name: astral-sh/setup-uv dependency-version: 10.3.3 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: actions ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2476791498..36b9152bb8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,7 +42,7 @@ jobs: - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.11" - - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: version: "0.12.13" checksum: 745765a3b6e360ad76743599ae5c42e9278c7edf8bbff9fc76d05bf2623a04dd @@ -346,7 +346,7 @@ jobs: - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.11" - - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: version: "0.12.13" checksum: 745765a3b6e360ad76743599ae5c42e9278c7edf8bbff9fc76d05bf2623a04dd @@ -390,7 +390,7 @@ jobs: - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.11" - - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: version: "0.12.13" checksum: 745765a3b6e360ad76743599ae5c42e9278c7edf8bbff9fc76d05bf2623a04dd @@ -430,7 +430,7 @@ jobs: - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.11" - - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: version: "0.12.13" checksum: 745765a3b6e360ad76743599ae5c42e9278c7edf8bbff9fc76d05bf2623a04dd From ce14b691f3b8ac6ccf1d42eea14a2ab3d78ebc5b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:33:47 -0600 Subject: [PATCH 008/112] build(deps): Bump caddy from 2.11.7 to 2.11.9 in the compose group (#4000) * build(deps): Bump caddy from 2.11.7 to 2.11.9 in the compose group Bumps the compose group with 1 update: caddy. Updates `caddy` from 2.11.7 to 2.11.9 --- updated-dependencies: - dependency-name: caddy dependency-version: 2.11.9 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: compose ... Signed-off-by: dependabot[bot] * build(deps): carry the caddy 2.11.9 digest into the Quadlet units and compose test Co-Authored-By: Claude Sonnet 5.5 --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- docker-compose.yml | 2 +- lib/pithead/36-quadlet-units.sh | 2 +- os/quadlet/caddy.container | 2 +- os/quadlet/local/caddy.container | 2 +- os/quadlet/payout/caddy.container | 2 +- tests/integration/lib/run-state.sh | 2 +- tests/stack/standalone/test_compose.sh | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 2bac9e2757..6f63e4dae8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -998,7 +998,7 @@ services: # Bridges the local 127.0.0.1 application binding to the LAN # Serves HTTPS or HTTP depending on configuration caddy: - image: caddy:2.11.7@sha256:36c24ad91a7ff7bc4c87fe22bfa8df3c4b18da0773d73fc12ee2c52b98c0bb7e + image: caddy:2.11.9@sha256:0c2243efcf437ab7f7a978f1027fcf0d4f9be8a75df27b1b3fbc5dbe0ffa8cf0 container_name: caddy # Memory ceiling (#132 — see monerod). Reverse proxy + local TLS only (~13 MiB observed). mem_limit: 128m diff --git a/lib/pithead/36-quadlet-units.sh b/lib/pithead/36-quadlet-units.sh index 4130a81344..9fdaa42544 100644 --- a/lib/pithead/36-quadlet-units.sh +++ b/lib/pithead/36-quadlet-units.sh @@ -298,7 +298,7 @@ EOF Description=pithead caddy [Container] ContainerName=caddy -Image=docker.io/library/caddy:2.11.7@sha256:36c24ad91a7ff7bc4c87fe22bfa8df3c4b18da0773d73fc12ee2c52b98c0bb7e +Image=docker.io/library/caddy:2.11.9@sha256:0c2243efcf437ab7f7a978f1027fcf0d4f9be8a75df27b1b3fbc5dbe0ffa8cf0 Network=host Volume=$(_qenv QUADLET_CADDYFILE):/etc/caddy/Caddyfile:ro Volume=pithead-caddy-data:/data diff --git a/os/quadlet/caddy.container b/os/quadlet/caddy.container index d32fb57b86..d7494d3679 100644 --- a/os/quadlet/caddy.container +++ b/os/quadlet/caddy.container @@ -2,7 +2,7 @@ Description=pithead caddy [Container] ContainerName=caddy -Image=docker.io/library/caddy:2.11.7@sha256:36c24ad91a7ff7bc4c87fe22bfa8df3c4b18da0773d73fc12ee2c52b98c0bb7e +Image=docker.io/library/caddy:2.11.9@sha256:0c2243efcf437ab7f7a978f1027fcf0d4f9be8a75df27b1b3fbc5dbe0ffa8cf0 Network=host Volume=/opt/pithead/Caddyfile:/etc/caddy/Caddyfile:ro Volume=pithead-caddy-data:/data diff --git a/os/quadlet/local/caddy.container b/os/quadlet/local/caddy.container index d32fb57b86..d7494d3679 100644 --- a/os/quadlet/local/caddy.container +++ b/os/quadlet/local/caddy.container @@ -2,7 +2,7 @@ Description=pithead caddy [Container] ContainerName=caddy -Image=docker.io/library/caddy:2.11.7@sha256:36c24ad91a7ff7bc4c87fe22bfa8df3c4b18da0773d73fc12ee2c52b98c0bb7e +Image=docker.io/library/caddy:2.11.9@sha256:0c2243efcf437ab7f7a978f1027fcf0d4f9be8a75df27b1b3fbc5dbe0ffa8cf0 Network=host Volume=/opt/pithead/Caddyfile:/etc/caddy/Caddyfile:ro Volume=pithead-caddy-data:/data diff --git a/os/quadlet/payout/caddy.container b/os/quadlet/payout/caddy.container index d32fb57b86..d7494d3679 100644 --- a/os/quadlet/payout/caddy.container +++ b/os/quadlet/payout/caddy.container @@ -2,7 +2,7 @@ Description=pithead caddy [Container] ContainerName=caddy -Image=docker.io/library/caddy:2.11.7@sha256:36c24ad91a7ff7bc4c87fe22bfa8df3c4b18da0773d73fc12ee2c52b98c0bb7e +Image=docker.io/library/caddy:2.11.9@sha256:0c2243efcf437ab7f7a978f1027fcf0d4f9be8a75df27b1b3fbc5dbe0ffa8cf0 Network=host Volume=/opt/pithead/Caddyfile:/etc/caddy/Caddyfile:ro Volume=pithead-caddy-data:/data diff --git a/tests/integration/lib/run-state.sh b/tests/integration/lib/run-state.sh index 0f51e74cef..478fef0c0b 100644 --- a/tests/integration/lib/run-state.sh +++ b/tests/integration/lib/run-state.sh @@ -234,7 +234,7 @@ assert_running_state() { # 'ubuntu' user or an explicit useradd, are uid 1000) and tari pins 1000 via the compose # override (the pulled image ships no non-root user of its own). Caddy and the two Docker # socket proxies are the audited exception — verified against the upstream images - # (caddy:2.11.7, tecnativa/docker-socket-proxy:v0.5.0): neither ships a non-root user, so + # (caddy:2.11.9, tecnativa/docker-socket-proxy:v0.5.0): neither ships a non-root user, so # they run as root, mitigated by cap_drop: ALL + read_only rootfs and (the proxies) sitting # off mining_net on host-loopback-only ports (#345) rather than by uid. Pin ALL 9 so a # silent drift either way — a hardened image reverting to root, or an accepted-root service diff --git a/tests/stack/standalone/test_compose.sh b/tests/stack/standalone/test_compose.sh index 7b2206bc87..f38f4c37de 100755 --- a/tests/stack/standalone/test_compose.sh +++ b/tests/stack/standalone/test_compose.sh @@ -147,7 +147,7 @@ expect_min "log rotation on every service" "max-size:" 9 # leaving the other was green. The two would then run different socket-proxy builds, which is exactly # the split the separate-proxy design exists to prevent. expect_min "tecnativa socket-proxy pinned by digest (both proxies)" "tecnativa/docker-socket-proxy:v0.5.0@sha256:1f5038b54f06c3e18422902cf00ba21803d1c97805aae032e5e6673d532d3459" 2 -expect_present "caddy pinned by digest" "caddy:2.11.7@sha256:36c24ad91a7ff7bc4c87fe22bfa8df3c4b18da0773d73fc12ee2c52b98c0bb7e" +expect_present "caddy pinned by digest" "caddy:2.11.9@sha256:0c2243efcf437ab7f7a978f1027fcf0d4f9be8a75df27b1b3fbc5dbe0ffa8cf0" expect_present "tari node pinned by digest" "minotari_node:v6.0.1-pre.0-mainnet@sha256:23ce381b74e48cf67677dfe85c800daf54a155a610c595c94b16db6b186950ec" # Per-service precision checks via the JSON render. From d50facfb940e4062a673ac3fb523f90a3eb846cc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:35:24 -0600 Subject: [PATCH 009/112] build(deps): Bump the python group in /dashboard with 4 updates (#4002) Bumps the python group in /dashboard with 4 updates: [pytest-asyncio](https://github.com/pytest-dev/pytest-asyncio), [diff-cover](https://github.com/Bachmann1234/diff-cover), [hypothesis](https://github.com/HypothesisWorks/hypothesis) and [ruff](https://github.com/astral-sh/ruff). Updates `pytest-asyncio` from 1.4.1 to 1.4.1.post1 - [Release notes](https://github.com/pytest-dev/pytest-asyncio/releases) - [Commits](https://github.com/pytest-dev/pytest-asyncio/compare/v1.4.1...v1.4.1.post1) Updates `diff-cover` from 11.0.0 to 11.0.1 - [Release notes](https://github.com/Bachmann1234/diff-cover/releases) - [Changelog](https://github.com/Bachmann1234/diff_cover/blob/main/CHANGELOG) - [Commits](https://github.com/Bachmann1234/diff-cover/compare/v11.0.0...v11.0.1) Updates `hypothesis` from 6.170.14 to 6.170.15 - [Release notes](https://github.com/HypothesisWorks/hypothesis/releases) - [Commits](https://github.com/HypothesisWorks/hypothesis/compare/v6.170.14...v6.170.15) Updates `ruff` from 0.17.3 to 0.17.4 - [Release notes](https://github.com/astral-sh/ruff/releases) - [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md) - [Commits](https://github.com/astral-sh/ruff/compare/0.17.3...0.17.4) --- updated-dependencies: - dependency-name: pytest-asyncio dependency-version: 1.4.1.post1 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: python - dependency-name: diff-cover dependency-version: 11.0.1 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: python - dependency-name: hypothesis dependency-version: 6.170.15 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: python - dependency-name: ruff dependency-version: 0.17.4 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: python ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- dashboard/pyproject.toml | 2 +- dashboard/uv.lock | 220 +++++++++++++++++++-------------------- 2 files changed, 111 insertions(+), 111 deletions(-) diff --git a/dashboard/pyproject.toml b/dashboard/pyproject.toml index 9603bce84d..6cdf4238e2 100644 --- a/dashboard/pyproject.toml +++ b/dashboard/pyproject.toml @@ -37,7 +37,7 @@ test = [ ] # Developer tooling (Wave 7, #280). Pinned so local, pre-commit, and CI all run the SAME ruff # — lint output is version-sensitive, so a floor would let CI and a contributor disagree. -dev = ["ruff==0.17.3", "pre-commit>=4.6.2"] +dev = ["ruff==0.17.4", "pre-commit>=4.6.2"] [tool.setuptools.packages.find] include = ["mining_dashboard*"] diff --git a/dashboard/uv.lock b/dashboard/uv.lock index d902333668..783f483a66 100644 --- a/dashboard/uv.lock +++ b/dashboard/uv.lock @@ -461,7 +461,7 @@ toml = [ [[package]] name = "diff-cover" -version = "11.0.0" +version = "11.0.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "chardet" }, @@ -469,9 +469,9 @@ dependencies = [ { name = "pluggy" }, { name = "pygments" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f5/95/eed8243dd7c3442661c57297b5b1097d463a9d0fdabad5f42200c7ca7548/diff_cover-11.0.0.tar.gz", hash = "sha256:5450247cc885ac0c252f0d7a4cf91608f454377c6f88e579bc9ead410af50c36", size = 108509, upload-time = "2026-10-27T02:20:48.718Z" } +sdist = { url = "https://files.pythonhosted.org/packages/38/a9/7c3c637f7c4913ee66a40ac5d2821fe1ee3859f54e626954d4f812eb7950/diff_cover-11.0.1.tar.gz", hash = "sha256:18fff3b9df6f28c62953859fb16302d1dec0189d79f3ea437c0bcad5cc60dcf3", size = 110057, upload-time = "2026-11-04T02:31:08.188Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b0/10/97d05eef3876cffab13c3ce3cfd6e51bdd9d0cfb017b46622a9bbfbd91e4/diff_cover-11.0.0-py3-none-any.whl", hash = "sha256:8b0a5b356d525718ee18c14b163ce179c75ccdc5b8d5474ef22ade6a0e1fa65d", size = 63614, upload-time = "2026-10-27T02:20:47.38Z" }, + { url = "https://files.pythonhosted.org/packages/09/e5/a12bcf82fe8930a4faeadba8afd60798010c5a1d9e5e374cd89ca27001ba/diff_cover-11.0.1-py3-none-any.whl", hash = "sha256:40d559e47ee9bcec35194fd9726d408a242608c54fbd0cdab244ae4324c1c7da", size = 63836, upload-time = "2026-11-04T02:31:06.805Z" }, ] [[package]] @@ -660,95 +660,95 @@ wheels = [ [[package]] name = "hypothesis" -version = "6.170.14" +version = "6.170.15" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "sortedcontainers" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d6/0f/10b2076a1314c554eee58c26e1dbe630fd26a32773df2a63bd5dba5d9947/hypothesis-6.170.14.tar.gz", hash = "sha256:8272913eb34c4399a88cf8a9ecdb351c9ef8f621c061f2ac323362d4a66b755d", size = 521490, upload-time = "2026-10-30T06:51:55.943Z" } +sdist = { url = "https://files.pythonhosted.org/packages/96/ec/59f14eb701087710888b66bfef2dc8bee9dd4a364c69a732db0cc1d3d2dc/hypothesis-6.170.15.tar.gz", hash = "sha256:a4a57e5fb106ecb29cad37e22e411d957e20d933bfb9fb029e1999b1deb8a0b6", size = 521997, upload-time = "2026-11-06T09:54:57.339Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c9/d6/eae1191f3398b8cc9f10b20c9b93dd1ceae037565e94ababf521730e59a4/hypothesis-6.170.14-cp311-abi3-macosx_10_12_x86_64.whl", hash = "sha256:b1c4990f9fafad83cdac33bc564d41066f5824a92ddd45ded7e0e84277a3ec0e", size = 800123, upload-time = "2026-10-30T06:50:33.682Z" }, - { url = "https://files.pythonhosted.org/packages/56/78/434915150cecd5b9ba41837106a3da2782f515a9aed583d25860bfa6d71c/hypothesis-6.170.14-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:ab414b45a56853fcdd6b602d9c5033e3c7d127ee8b8e7e3397223b746440b37c", size = 795278, upload-time = "2026-10-30T06:50:22.237Z" }, - { url = "https://files.pythonhosted.org/packages/95/6b/07f5e5e667b4b3e90bea16b4db09367b5bb1dfae63eb75a7152b053b0c50/hypothesis-6.170.14-cp311-abi3-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:cceb1b3c19ea0a146c7bb2fb2b44e3ef231bcecd42c97d95154e5d233e209572", size = 1162031, upload-time = "2026-10-30T06:50:08.828Z" }, - { url = "https://files.pythonhosted.org/packages/22/ba/51e0dc10befcc4ca9b7fb81b76ca6aef4ffc9c7a741191a8b41e878ee2f2/hypothesis-6.170.14-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:376dbf5ffa1e3ad71af2a1af0877176faabe3e63d345324a33c82e408dbfd604", size = 1124181, upload-time = "2026-10-30T06:51:51.244Z" }, - { url = "https://files.pythonhosted.org/packages/ee/37/77834f102b0bca702f723dd519b8f590e83ec6392e59565384cfdc5bbec7/hypothesis-6.170.14-cp311-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:5f0f6f6666fa15ec13ca1d8430f70660fce8b3f4f133e25fdf674be6ad77295e", size = 1154664, upload-time = "2026-10-30T06:51:50.027Z" }, - { url = "https://files.pythonhosted.org/packages/12/76/83edc11f33319a2febd025fb504aa1ed8e245b7e25905da80513615e4b5e/hypothesis-6.170.14-cp311-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:c4ff70fbb94f54cd35045a40e5a77dd8f876d4cc6a39dcdc4ac1af6f8f5cc6fe", size = 1148576, upload-time = "2026-10-30T06:50:18.505Z" }, - { url = "https://files.pythonhosted.org/packages/ce/35/d4086d546c0abe406f0ece17e33eca7051e87dc7501485a696385aed34fd/hypothesis-6.170.14-cp311-abi3-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:8ecec6be3a02e22c70bc7dfb15afeeeb708aeccb994c9d57db438199cad9bfbb", size = 1201336, upload-time = "2026-10-30T06:50:17.221Z" }, - { url = "https://files.pythonhosted.org/packages/dd/85/117b0dde708240854ce0f1ad95d43bc132f59e6bffc82c2a20e76b984020/hypothesis-6.170.14-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3bbf06c4f8e3aab37c144fe3bc1d89a051a2dfbefef8c2a25160b11da854f949", size = 1167592, upload-time = "2026-10-30T06:50:23.393Z" }, - { url = "https://files.pythonhosted.org/packages/29/bb/105ee91bf92e3b7a5bc388827e774b7c5744f39ce36f50f94918b584813c/hypothesis-6.170.14-cp311-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:07869d66bf1e92e39447808fcc1977bfd10bfdff4970d6969a49e89a84cf04a7", size = 1123748, upload-time = "2026-10-30T06:51:07.034Z" }, - { url = "https://files.pythonhosted.org/packages/cd/9b/c60e868ba0f93ff5bc7cec3e413c5e824863bbd9bd45dcc86bc18adb4266/hypothesis-6.170.14-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:0ce9ddf0d0e99c532c2cf00d97b63316830810d18f11c80c7bcf0f771969f3a4", size = 1299121, upload-time = "2026-10-30T06:51:00.068Z" }, - { url = "https://files.pythonhosted.org/packages/e9/f6/a2b9630ddc70aa7642931ac6c353fc57df38c6de655718a50337b5b7d4e0/hypothesis-6.170.14-cp311-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:420b4a77157e94f124498fff639284d514b60926f61925dd7aafb75411e7ce92", size = 1427779, upload-time = "2026-10-30T06:50:15.652Z" }, - { url = "https://files.pythonhosted.org/packages/db/36/b3e7d3fef4ce3f44f70a61399a3549c02a71e430122f688880a24336e9a6/hypothesis-6.170.14-cp311-abi3-musllinux_1_2_i686.whl", hash = "sha256:2a8ed08715a9a27d3a4730f48c99133ef25b3561d8fe992d1eda91e22cf6be99", size = 1381908, upload-time = "2026-10-30T06:50:58.685Z" }, - { url = "https://files.pythonhosted.org/packages/ad/52/b044ccaf1cb9d89f319b737f1fee7cc83e16c2fd086e1bf1ce149092eb44/hypothesis-6.170.14-cp311-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:71081b46714e95e9a10d922bedd08d5a6e49835bbc2ef37a81d30d62f8596829", size = 1277802, upload-time = "2026-10-30T06:51:53.644Z" }, - { url = "https://files.pythonhosted.org/packages/27/2f/989ef755683c7cefd195670861a2fbd72b6b7952c124256152e94660e62c/hypothesis-6.170.14-cp311-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:ce563cb34dedc9163811b03ce05a955eededd6f429db7c80c5c31d5836a9c05a", size = 1293571, upload-time = "2026-10-30T06:50:03.076Z" }, - { url = "https://files.pythonhosted.org/packages/a5/00/7426641c28dfc52e0a0d32748a1e47d3c189f9cf7eef81c0ecb7e90eb4cc/hypothesis-6.170.14-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:06a752e3e879f1b69dda9ea203d4e8e1562cf72f694513f01c8c99d2e5e3f3cc", size = 1333329, upload-time = "2026-10-30T06:50:50.362Z" }, - { url = "https://files.pythonhosted.org/packages/7b/55/88307f535bb0914824b0eb2c6b58aa4a482b483c8d25d8022e7b4f641f8c/hypothesis-6.170.14-cp311-abi3-win32.whl", hash = "sha256:0f418c6bff7cd8a117dd0f526c20f100c32df1ff9f7bc8e01a5eeb3855278039", size = 687305, upload-time = "2026-10-30T06:50:43.079Z" }, - { url = "https://files.pythonhosted.org/packages/25/61/ba5bb3e8593afa9212fad51dc70f219ef6da7527d806c62a42c1cf12247b/hypothesis-6.170.14-cp311-abi3-win_amd64.whl", hash = "sha256:1e9f7619dff3072685e4f36e8ae7b134a0c1ca41074fc54ade81e5355c72cd8c", size = 693378, upload-time = "2026-10-30T06:51:36.729Z" }, - { url = "https://files.pythonhosted.org/packages/ab/72/482a68ae0e94b24acd964196cca830d1dd65efbf3d4821599d1c9527f8e2/hypothesis-6.170.14-cp311-abi3-win_arm64.whl", hash = "sha256:7dbaec9a62b7792b0b04b7ebc933aeafd3ff019b81d67d763c36ebcf4d56f864", size = 691696, upload-time = "2026-10-30T06:50:32.53Z" }, - { url = "https://files.pythonhosted.org/packages/29/ff/fd4163e2ff50de555d8786749dcccaef627bd1133c3af736b95bc0675311/hypothesis-6.170.14-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:6fbe71177ca91a999e8fa644aeaee41622270165c89e4d2b4d02a6ea469de68c", size = 800838, upload-time = "2026-10-30T06:50:20.472Z" }, - { url = "https://files.pythonhosted.org/packages/f8/30/7f83c05cec96188508bb0a94959900cd6053a4512ff7e6c9dcb543544e4e/hypothesis-6.170.14-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:79319231501689666f1bc58a074fe1673b05d57bdaae35a8603d64dc3f88ee00", size = 796531, upload-time = "2026-10-30T06:51:28.996Z" }, - { url = "https://files.pythonhosted.org/packages/3f/63/2d442a1c5f5139ae77fb159488fa153fb358dd00a907ff9f70f652964829/hypothesis-6.170.14-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:61537e5d03fde19b80b3a38ee24ffd1c29f02f049879d3d2b6f48a0fb30f4f54", size = 1125158, upload-time = "2026-10-30T06:51:47.343Z" }, - { url = "https://files.pythonhosted.org/packages/89/da/8e4c5bd28f2ac4eb70c4193dcec87a3f3da936bd745f1d74d1fe52c10d67/hypothesis-6.170.14-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3bf836cb28f07201e0fe7d3cf2ebe1b5f540ab798fd03edb174d98f064bd620a", size = 1167844, upload-time = "2026-10-30T06:50:26.899Z" }, - { url = "https://files.pythonhosted.org/packages/72/06/e46f5bd610c43e4e41ba635542fa1f8a7de3bd64ddaa997ddb4761f46b5f/hypothesis-6.170.14-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:149ceb08170a99b2dca0b7d9906e56711b1e574be185f8c233de850a0e7f19d3", size = 1299890, upload-time = "2026-10-30T06:50:24.558Z" }, - { url = "https://files.pythonhosted.org/packages/cf/55/02de3952f56de807bda512b7c8e12604394c2fa57853f225c218708c9b1b/hypothesis-6.170.14-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:71195a69df8a3c9be3cbf17937db0506eab3a15fbb79863a6e3e299ba6712d71", size = 1333881, upload-time = "2026-10-30T06:51:52.395Z" }, - { url = "https://files.pythonhosted.org/packages/02/14/e588f5d78a3eee5e75a8f362f845dcc216c5e70f921ea405146a4589f6ac/hypothesis-6.170.14-cp311-cp311-win_amd64.whl", hash = "sha256:dde32e1c901e0532e595608f8bcdbb128f6a5ebe73c592983eec43c57ab9b0c4", size = 693485, upload-time = "2026-10-30T06:51:12.132Z" }, - { url = "https://files.pythonhosted.org/packages/8e/41/aa2c8ffc1490f02ec2b0e283e0856a0822c2b0707a83831e286493f888f5/hypothesis-6.170.14-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:76b03ded37a7eb14d01b03edca02b9a6ce6b8ab0ad8d2f9ac5f2e9de6769a33a", size = 801893, upload-time = "2026-10-30T06:51:10.965Z" }, - { url = "https://files.pythonhosted.org/packages/81/45/a82212e5773214d3ad1e0cee626098c1068adc93cdb37449e3c0629aa591/hypothesis-6.170.14-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a6055172afdca41cda869652bd2f2c24ec984005cd16bbec5a8f38483f23b9bc", size = 793892, upload-time = "2026-10-30T06:50:55.958Z" }, - { url = "https://files.pythonhosted.org/packages/8a/cc/1889082d37e946e006845163a91e4091d1cff4f1692e3580729454cb02f4/hypothesis-6.170.14-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b6490c64811a2176a5af9fe5a5d59ab2aa20d35d691328cbb336f6fb398355c4", size = 1123577, upload-time = "2026-10-30T06:50:11.524Z" }, - { url = "https://files.pythonhosted.org/packages/7f/7a/311a4ec14dbde1ce82cbd4d8957665c4d68e9139524b10e0a622db98bc4e/hypothesis-6.170.14-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cde7e98694a9baa1d9761c1b595b3d617467c876200c0798a40f2016a0e85304", size = 1167206, upload-time = "2026-10-30T06:50:05.235Z" }, - { url = "https://files.pythonhosted.org/packages/f5/0d/1afb5e9f470898cf296f10545cfbf76e6b8d4d7025e0c41a491bbe969a22/hypothesis-6.170.14-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7e39d46bdebb3853fb3000aab3c354e4d780705dc8b2674773ffcdfd04fd5122", size = 1298455, upload-time = "2026-10-30T06:51:30.733Z" }, - { url = "https://files.pythonhosted.org/packages/f5/f6/ff7e9568f7a7d9ec375c68636c66e1b1a3baa06f44652535ff434110f6cd/hypothesis-6.170.14-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:1309925a71a2baacb85ed5c20291ddb4b2a4665bd33fb594697463d457374a1b", size = 1332876, upload-time = "2026-10-30T06:50:57.14Z" }, - { url = "https://files.pythonhosted.org/packages/cc/73/fd330eec15026dc30d0ec8c658517c99703774098305632efb3e523b2f38/hypothesis-6.170.14-cp312-cp312-win_amd64.whl", hash = "sha256:ac98e833bdefbcbebb9094180a7431a8946f1acc91a5b779c814aecca71c7345", size = 691003, upload-time = "2026-10-30T06:50:36.624Z" }, - { url = "https://files.pythonhosted.org/packages/88/95/9729cc49645d07211ce8158f0bb51860873b3b99fb1650c2dad78bd2e86c/hypothesis-6.170.14-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:7d5e5affa9e69b8673f15bef86421740945e74f3c31d0817141ba020c7e00705", size = 801888, upload-time = "2026-10-30T06:50:06.456Z" }, - { url = "https://files.pythonhosted.org/packages/6e/ac/687277e019d68b96d2c33b979ad8a955b5747e279891f8c335bbf58cd9bc/hypothesis-6.170.14-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e7ae9ff3220659c4721acb58d34e72227a0af7747fc903ae177dfdb0323796b4", size = 793879, upload-time = "2026-10-30T06:51:09.51Z" }, - { url = "https://files.pythonhosted.org/packages/b2/1a/b46a2959b41ff9409af8b43fd63b07c6ed51958db0e9d314db9ee6012f5a/hypothesis-6.170.14-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:857932ff6bba183af0236f659b042023ab8b4ad58725b9024bcaba941c8cd5d0", size = 1123483, upload-time = "2026-10-30T06:50:47.998Z" }, - { url = "https://files.pythonhosted.org/packages/cb/2a/6735b2edff23d045441b5917f35c01a4c139a186604847ca19bbd63e81e2/hypothesis-6.170.14-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8126e8208acadfc3c92d0aedb8011cf724fb59e5523ceaca3f4612dcc409e632", size = 1167158, upload-time = "2026-10-30T06:51:26.528Z" }, - { url = "https://files.pythonhosted.org/packages/ea/f0/b5b4273568620080db24dda2008236bd6c64599ab03210e46977b44b54d5/hypothesis-6.170.14-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d28ab5c5b08b1de11bc022d576b20f9f585f7e7758778295461f80b9222d7a18", size = 1298440, upload-time = "2026-10-30T06:50:10.195Z" }, - { url = "https://files.pythonhosted.org/packages/2a/c7/38427a9803dac9bdd06581061a84672107d821f6d91b833dec467c37f5d5/hypothesis-6.170.14-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:033aca79fd3f9a6e15402dfddbc988141d43eae38d26a5fc554f6879f7e0e5f9", size = 1332909, upload-time = "2026-10-30T06:51:17.244Z" }, - { url = "https://files.pythonhosted.org/packages/7a/4f/47c060c96d077750c8a7b83b2e50b1add2050b391e77f49126828c125264/hypothesis-6.170.14-cp313-cp313-win_amd64.whl", hash = "sha256:03831d833b161b9b7a32f0b607205293954f3a651196c80138804b9479845d71", size = 690983, upload-time = "2026-10-30T06:51:04.201Z" }, - { url = "https://files.pythonhosted.org/packages/e8/3a/7ce36c91aafb192e08d990b3a8fd632be113eeb43973a94fddaa4172c570/hypothesis-6.170.14-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:a2410c5a6dcc011338e53cd381bd32d979b6f06d799c5cf01d76b923f0a0670b", size = 802098, upload-time = "2026-10-30T06:51:48.445Z" }, - { url = "https://files.pythonhosted.org/packages/c7/dc/17bc4ba00a48976944918bb5d7207519ed206fdf98af0d0319e5ba33afd2/hypothesis-6.170.14-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:dcf6303c65e73acf134b7854cbdfec8f2108cfdc84806fa180de04d7946aab0c", size = 793921, upload-time = "2026-10-30T06:50:07.623Z" }, - { url = "https://files.pythonhosted.org/packages/1c/c3/252db9362dab21e3c3351abb89e715fa1ef598ebaf30abb9c9b1dd3b3aab/hypothesis-6.170.14-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:67d17e8b91d3913e7aa2b1179957df4e0634caea3868b5ba4fe2bf1945334134", size = 1123996, upload-time = "2026-10-30T06:51:05.628Z" }, - { url = "https://files.pythonhosted.org/packages/f8/41/573468979e9579eb6df937e6a96c1a944dfe2765c73624156571e3cc4b34/hypothesis-6.170.14-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:96f9f8a684c88ad2280129b28bc609adb6b31cd63b1b83b397b86d552391e947", size = 1167330, upload-time = "2026-10-30T06:51:23.741Z" }, - { url = "https://files.pythonhosted.org/packages/f6/1c/d1b790ec3247966ceb3d5729bb79f810e24b1684b49b6290c9ad5be05e33/hypothesis-6.170.14-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c42d504d9bc0aef71fa88877c68ce202c02242c84f05791be2785e01e3a8699", size = 1298940, upload-time = "2026-10-30T06:51:27.68Z" }, - { url = "https://files.pythonhosted.org/packages/f6/a3/2fb6f7e825c9d943c5c35e0d9ef968e416267db2ef710e6d2d3cf7f36ab0/hypothesis-6.170.14-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ad84ca98f38e9f385b0f616df04bea4a9c6849333e221ce9289e9566ccd41058", size = 1333102, upload-time = "2026-10-30T06:51:20.993Z" }, - { url = "https://files.pythonhosted.org/packages/49/09/b533e4ac06dc317314d574dd0e3b548bac9cffe05e7e7a32f7b25aa7f052/hypothesis-6.170.14-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:f569bd9745835f9864d53c853e401c2021e796fdbb385497fdae633fe950b6ba", size = 633715, upload-time = "2026-10-30T06:50:25.715Z" }, - { url = "https://files.pythonhosted.org/packages/08/c6/9c47f183e5a8a4059d7c1c39e85f7b140f4416961b5ed0dac5d35dc6e1f7/hypothesis-6.170.14-cp314-cp314-win_amd64.whl", hash = "sha256:31c6a4015c02c45ba0285ff48538f4eb2c2de7e836f313bb8832fd8d86f71d62", size = 690702, upload-time = "2026-10-30T06:50:41.998Z" }, - { url = "https://files.pythonhosted.org/packages/05/47/623b189cc8d9e360bfbb69828fb88ca4d0d4996b3975f3191b49a50f04ce/hypothesis-6.170.14-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:744c587791b2c5e38d1da2eaca617b1a82073832dfcf42975ddb03e93f187919", size = 800266, upload-time = "2026-10-30T06:50:29.462Z" }, - { url = "https://files.pythonhosted.org/packages/ea/af/7ec2697869df2c7f5d1c414b1a0a21746aa0298d41d7358e45fb7ed83992/hypothesis-6.170.14-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:d0daded6c2f3e05f6bd989059bb798e570722802e05eb3543c6f5d7a1e7e6500", size = 792500, upload-time = "2026-10-30T06:50:51.878Z" }, - { url = "https://files.pythonhosted.org/packages/e0/cf/2c7b13b5e56cd42789dbef4948f21e685c4a4db7dd6daffa253f261a9193/hypothesis-6.170.14-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:986eaec8ca5a22710b1086b88734035c7d7ffcdb4ce02341b9f7069cc1bdfc5e", size = 1122469, upload-time = "2026-10-30T06:51:31.981Z" }, - { url = "https://files.pythonhosted.org/packages/63/17/aab31d83a3195edf21ff0b05ea8fabf1fcf723517a6ba7bd1aee3b2713e3/hypothesis-6.170.14-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:44c481115770bb3df5014b0369ea1aaf7319b81b3346a744a9265fc933190c3d", size = 1166369, upload-time = "2026-10-30T06:50:54.572Z" }, - { url = "https://files.pythonhosted.org/packages/8b/ce/88ab370d5c1e06c74b87995381c28f5c1456bcd832db339bb93b6b15cae5/hypothesis-6.170.14-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:261ae20a5573cf59e5dbf931c7fb9abcb012695adccb61fdab108cbba1772ee5", size = 1297198, upload-time = "2026-10-30T06:51:22.283Z" }, - { url = "https://files.pythonhosted.org/packages/06/03/5c8d82f48d3a7adb593d1c141fdae597ef874e27dabd94ede9edd5c36c29/hypothesis-6.170.14-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:833f7e6d93c03f3c00583a126e61f631d6b91a84e157a30da2d1c786ce5658b7", size = 1332114, upload-time = "2026-10-30T06:51:34.61Z" }, - { url = "https://files.pythonhosted.org/packages/25/24/b08d06042af15e1a5fd2fe378feaa2336983f4ecc2bf645b38c6accf7d7d/hypothesis-6.170.14-cp314-cp314t-win_amd64.whl", hash = "sha256:224cad0e7ba8bfc6ef708652a3cc2148161e3157d191eb77ecc85dc5d16afb70", size = 690815, upload-time = "2026-10-30T06:51:43.881Z" }, - { url = "https://files.pythonhosted.org/packages/ee/72/bbd7a5341e23b56759937cef4fe83ea9c907f15ffccee1c2e8e2c8937546/hypothesis-6.170.14-cp315-abi3.abi3t-macosx_10_12_x86_64.whl", hash = "sha256:e76877e7c7a5cf8c4fbf98280dc6582f5d6450a73494490e8b48b7d03fb5e12f", size = 799866, upload-time = "2026-10-30T06:50:12.929Z" }, - { url = "https://files.pythonhosted.org/packages/df/f0/be3b05a4c57bbb91b0048c37a5f3a278accb1ec51e853bb87037379c3f93/hypothesis-6.170.14-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:5a613867bd2675101dda8fda380c3ce6be47842bed5640e1ba7b6b6fd0ffe8a3", size = 792315, upload-time = "2026-10-30T06:50:37.847Z" }, - { url = "https://files.pythonhosted.org/packages/aa/2b/f0a1509d5d4ad2e3b3c834bebd8a4b1f430d01d350710f45338342756b91/hypothesis-6.170.14-cp315-abi3.abi3t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:a2249f2428ea94c47bccceb9fb8beada242c577dd4b3cd2edef5fb7160d1b71b", size = 1158319, upload-time = "2026-10-30T06:50:46.745Z" }, - { url = "https://files.pythonhosted.org/packages/6c/5c/eea759905d4b7d4d9a750b9b61a419120742143288c48c7d0ba633efc5f1/hypothesis-6.170.14-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:20df34cca1265c1683ccdcab5872cf0a023f40235a3092a96d4bd81e4fc57986", size = 1121221, upload-time = "2026-10-30T06:50:28.317Z" }, - { url = "https://files.pythonhosted.org/packages/93/b0/3c90a9e734aa0a4aef0fa9004dd7c2bcd27a6e66bc32a8690647639cba88/hypothesis-6.170.14-cp315-abi3.abi3t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:4a7f8023efbec61296fd20edb35d638ec89ff761d3f9d3dc8128ac8f204652ec", size = 1152108, upload-time = "2026-10-30T06:50:35.02Z" }, - { url = "https://files.pythonhosted.org/packages/63/fd/4b7e7f69ee248547f6fe69475197ffbb5ae9563ab49c1430f020bd1d5493/hypothesis-6.170.14-cp315-abi3.abi3t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:3faa2b45f30320fb57ce1c30f1bf9f08b1fd1cc1c606ae2a3e1efd0256fd7c77", size = 1145869, upload-time = "2026-10-30T06:51:54.841Z" }, - { url = "https://files.pythonhosted.org/packages/15/de/dc96bc0646e8543386e3c539fea154075b2d0f40e6b3fb19022c43058dac/hypothesis-6.170.14-cp315-abi3.abi3t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:5be7a2239adde6c72001eb42cdb924d3c3856b1ee80342049961efdd6c72d064", size = 1199697, upload-time = "2026-10-30T06:51:40.612Z" }, - { url = "https://files.pythonhosted.org/packages/f5/fd/363472210e3ed2a356b7bc6ca8ca405c0dae6531ad43c8f76ca20a946884/hypothesis-6.170.14-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1a7aa883cd30c6c0c7259f34c1e3f37617c0d52fa6718e93c9926cc49b8047d6", size = 1165533, upload-time = "2026-10-30T06:50:14.401Z" }, - { url = "https://files.pythonhosted.org/packages/37/3f/989ab6da164efe574399debdf64370d153f17d4cfda51c8d7e14781dc92b/hypothesis-6.170.14-cp315-abi3.abi3t-manylinux_2_31_riscv64.whl", hash = "sha256:79360d1dd671e602d2327e26fb9179645511adcfb9ec9d28c5d6bda313920aa2", size = 1119844, upload-time = "2026-10-30T06:51:08.317Z" }, - { url = "https://files.pythonhosted.org/packages/5d/c4/7758868c29d3fbcdd0face967a2d7e3af221a1c8d57802c7ac6cb49becd9/hypothesis-6.170.14-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:e4c45885e931a55c5097ebf0a9b65459878ad5e1c69c0448ae37e03fd764ddfc", size = 1296008, upload-time = "2026-10-30T06:50:40.598Z" }, - { url = "https://files.pythonhosted.org/packages/c7/b2/dc88869b6f8508fbfb290c4a9b03328142743d041ae4a144870b904b69bd/hypothesis-6.170.14-cp315-abi3.abi3t-musllinux_1_2_armv7l.whl", hash = "sha256:a6d09601401c019366826effa98ae64393dd149b50d7d6ea202ad472784278a8", size = 1425148, upload-time = "2026-10-30T06:51:18.492Z" }, - { url = "https://files.pythonhosted.org/packages/f2/f2/f6dde97e8a1d017d9663164f48f600f65e9d2ade37c43447421f6a369cbe/hypothesis-6.170.14-cp315-abi3.abi3t-musllinux_1_2_i686.whl", hash = "sha256:05e2a645b94fd43107a3360fe0aaf6db268199c80a43cf375fac5f1f9047745f", size = 1378730, upload-time = "2026-10-30T06:51:16.063Z" }, - { url = "https://files.pythonhosted.org/packages/9b/42/e2aa93586527428b51c019a4cedf28e1d2f10dfec5f9acfa3e1a22cd2e86/hypothesis-6.170.14-cp315-abi3.abi3t-musllinux_1_2_ppc64le.whl", hash = "sha256:cb54946f70ae5008ea8cd58ce9a27b2126506732b53b83a6d117371d7c755362", size = 1274346, upload-time = "2026-10-30T06:51:14.2Z" }, - { url = "https://files.pythonhosted.org/packages/c2/22/17ee8d38c5cb0a948ba9bb6cd7be2351a021cf1ea6686aa4fac16c29c45a/hypothesis-6.170.14-cp315-abi3.abi3t-musllinux_1_2_riscv64.whl", hash = "sha256:b72805cf56012a3d96f4a1fbb869f178d448f242b4f64310956134a3c952113f", size = 1291604, upload-time = "2026-10-30T06:50:53.304Z" }, - { url = "https://files.pythonhosted.org/packages/0c/c8/c97cdaa1191519fadcc06bc118f271910d7d7972caeecb70b7003a62303c/hypothesis-6.170.14-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:a17500680ec2c3cf006c12d3832a6c8daba8a18386f93b3d1828de07b07910aa", size = 1331507, upload-time = "2026-10-30T06:51:02.784Z" }, - { url = "https://files.pythonhosted.org/packages/cf/c7/1007bdaf517b086df3c54d06de6c47f099704fd8bd6c2b5013e749833ee4/hypothesis-6.170.14-cp315-abi3.abi3t-win32.whl", hash = "sha256:b1d9baaef909100fd1a6ba5457ecffa4a184e820c7f0bd3d4589f14870f5cade", size = 684627, upload-time = "2026-10-30T06:50:49.194Z" }, - { url = "https://files.pythonhosted.org/packages/51/d1/68539ecbe240de4afc03c5fa120ecf0875690708f2a97914352ae3172d36/hypothesis-6.170.14-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:a725b854c5df088c5a579f1c323657258abe5d8e32e16cd07beb48960f31c070", size = 690617, upload-time = "2026-10-30T06:51:42.268Z" }, - { url = "https://files.pythonhosted.org/packages/66/d7/9671c708cdab1c49ff96344f6730ccd76a7e1c2bdbbb2bed93bc9d6a18b4/hypothesis-6.170.14-cp315-abi3.abi3t-win_arm64.whl", hash = "sha256:75f60ef38c010742339a9b2ec2a44cb0aed6c6c8f1455ad6a6de48f5216a72b2", size = 688595, upload-time = "2026-10-30T06:51:37.945Z" }, - { url = "https://files.pythonhosted.org/packages/de/a2/4944726564c20e77b333586825f577dca8c26e2961abc71c01a8f05b9291/hypothesis-6.170.14-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:cd353f6368bfd860bd6fa713dae8037bfefeae12e4dde4292661d0e351b5b266", size = 800715, upload-time = "2026-10-30T06:50:39.331Z" }, - { url = "https://files.pythonhosted.org/packages/f9/65/b68b5f4041869193108dadd5048fd4147cc37abe47b144c24a7574b0be3b/hypothesis-6.170.14-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:b225ad942600271fcf8d810856fa37e3fb21860ccc752a2b8efa2fb0eca5a7a2", size = 795583, upload-time = "2026-10-30T06:50:45.316Z" }, - { url = "https://files.pythonhosted.org/packages/6e/38/e53190ce08019b282e96ed43c0f1fce9b848c6d67fc88ded5ac272ced679/hypothesis-6.170.14-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9eda91235f462e9b98e25295badae1cce6406aa587207fe0a23015601e1acf59", size = 1124666, upload-time = "2026-10-30T06:50:30.653Z" }, - { url = "https://files.pythonhosted.org/packages/41/a3/121c98c06155805abc581b28e8c3de464eea444956d06dc7c293b81c7968/hypothesis-6.170.14-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f44ac697830ea44ac319311a86e892df38c6706f3ea9f98b148222dca63b8852", size = 1168061, upload-time = "2026-10-30T06:51:39.184Z" }, - { url = "https://files.pythonhosted.org/packages/d5/08/15811d68673ca8bcd83e17d5e79feaf7daeddcfd85235130ef8dd636ca02/hypothesis-6.170.14-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:7226b109f964525bf8830f4543925d5dcf30f488ccd2f55ff9fd50a33629d7b7", size = 693946, upload-time = "2026-10-30T06:51:01.356Z" }, - { url = "https://files.pythonhosted.org/packages/ba/ae/822ac5f03f0f13e96b4a7b380ede8fa4ae2a46730f4e5c6d7eca016147bb/hypothesis-6.170.14-pp312-pypy312_pp80-macosx_10_12_x86_64.whl", hash = "sha256:c7b5dee8b87f8a78c1786eb1f96a6c0c91fcc2e10b2e9d876dcbc8e3f65dffc3", size = 801000, upload-time = "2026-10-30T06:50:44.17Z" }, - { url = "https://files.pythonhosted.org/packages/fa/b2/e4a0901adb647ca375a794cbf1a23e5e49e59c77d191d1922e3d3c4ce6b6/hypothesis-6.170.14-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:e99d1bc7d8e8fc17cb67a38e003cbf4a17f41f7851c1f205efd35b6f3ba93da5", size = 792896, upload-time = "2026-10-30T06:51:25.028Z" }, - { url = "https://files.pythonhosted.org/packages/d1/9c/ac50eed9becb0de590d8af7bd1b67546e58b84dda4abb89ca563eed1babe/hypothesis-6.170.14-pp312-pypy312_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d66dab3b79eda78964665ab4f9d7a269137c14cd6ec7ea4fb27002a8786452b9", size = 1122853, upload-time = "2026-10-30T06:51:33.262Z" }, - { url = "https://files.pythonhosted.org/packages/c4/7f/bc41905c23c74c3db4620a5382977b168156f357e8a421c2b9f66f764979/hypothesis-6.170.14-pp312-pypy312_pp80-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:88d829c29907e7d86f8b1d33041bb73814062a3681ec51dcb231f64874f88b14", size = 1167065, upload-time = "2026-10-30T06:51:45.442Z" }, - { url = "https://files.pythonhosted.org/packages/0f/17/b28b4348a95694562357dc0c8ecb521dd607051dddd7af158c754b895710/hypothesis-6.170.14-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:90d4e85f22c3154a59df851bb2c59c89c129fba3155125d98ebad80bf69aad26", size = 692119, upload-time = "2026-10-30T06:51:19.8Z" }, + { url = "https://files.pythonhosted.org/packages/84/cf/3b56a81685915f6bf0d67b3a6c1139fd9bd4583066161823834e42b9eaa7/hypothesis-6.170.15-cp311-abi3-macosx_10_12_x86_64.whl", hash = "sha256:db8211e0a56fa29bf9e5d9ff9cd969a91ff4e5ffa8fb4983d3dd788253aeee2c", size = 800537, upload-time = "2026-11-06T09:53:36.823Z" }, + { url = "https://files.pythonhosted.org/packages/b6/09/477b3233cca8c447a6dc5fcc076a7294a4fdacb615d960695f6970d706dc/hypothesis-6.170.15-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:34e0859a53f20200f39db3f9cd92112eb6034c31dc670e88d56d8725f453562d", size = 795693, upload-time = "2026-11-06T09:54:14.601Z" }, + { url = "https://files.pythonhosted.org/packages/7c/7a/34e042f1545472abe29ecf9eebac6f748096580f6fb831817f097addbe29/hypothesis-6.170.15-cp311-abi3-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:5c5980821384206939c1c9d519b7adfb80b54d07e669ab0d36fe877f08cff07a", size = 1162432, upload-time = "2026-11-06T09:53:55.461Z" }, + { url = "https://files.pythonhosted.org/packages/3a/7f/95b7b04d2b7e45669db446ee10d97f5d04b143bba380559a7f3a7e0c5b1f/hypothesis-6.170.15-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f29339b5cd4c2a221885e8b7ddbd447b4dc7ee14f763a6f5aaff726d4d3fd5ed", size = 1124598, upload-time = "2026-11-06T09:54:26.015Z" }, + { url = "https://files.pythonhosted.org/packages/33/8e/896172d9706bfe2e09c9154fecb11c7b76e50014442783dd9d5b404c8c84/hypothesis-6.170.15-cp311-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:d836a61c3dd94c6fc4677f4d0d95d30b92eb0ceab6f2b5c58e35c32545583170", size = 1155097, upload-time = "2026-11-06T09:54:47.123Z" }, + { url = "https://files.pythonhosted.org/packages/29/33/b8791c6a9b4232c3cc8f592d3e36175bcb4bad6203f7e461db0a4f5fa11b/hypothesis-6.170.15-cp311-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:d18ffd069360589a66ed125db62f12b490b3b9f6d47e5fd2505f1089d63a0f17", size = 1148988, upload-time = "2026-11-06T09:54:33.101Z" }, + { url = "https://files.pythonhosted.org/packages/87/2c/3ee87dd6fdec16ce55a4aeb5f72ae24756855cdc4ee87637fb68c4daeadc/hypothesis-6.170.15-cp311-abi3-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:7636424c7b1477fdd279fce5a210b67687a3024ac7759fe2e46a767a76f8761c", size = 1201778, upload-time = "2026-11-06T09:53:49.736Z" }, + { url = "https://files.pythonhosted.org/packages/6b/6a/f2757fde7d1b3b5dda6df3441d346b59c60627f2c216d966739289149903/hypothesis-6.170.15-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:99a1a4711b5276e5bfc3aa0cca034d0e45f8696a46ac8dce008308f580c18234", size = 1168007, upload-time = "2026-11-06T09:54:34.331Z" }, + { url = "https://files.pythonhosted.org/packages/8d/79/b6ff2a2840e4bcdea5c4cf1bcdd3803954a632beec16cb9d77a9ee8ddbb8/hypothesis-6.170.15-cp311-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:f545a04342a53008fa696a0592f0a026278ee61fab04f3e9e395d0c7eba42fef", size = 1124154, upload-time = "2026-11-06T09:53:24.354Z" }, + { url = "https://files.pythonhosted.org/packages/52/d0/19bc4a98e9583936dbe6e754014ad1133d3a43c9068a880c4e91ce384fad/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1f11d685322a56ee73c2a7566ec9d1195740313c3b965bad3121c340ec0e657b", size = 1299503, upload-time = "2026-11-06T09:53:12.86Z" }, + { url = "https://files.pythonhosted.org/packages/ee/06/fad2d1546c08eb4133f9478716bf6bc5f881e0d06b5b4f1faf34fd515a5a/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:f6d5d34fa6b56f236ad9659043123efb85391a8a5640f067c9de82b0be0bff73", size = 1428191, upload-time = "2026-11-06T09:54:44.43Z" }, + { url = "https://files.pythonhosted.org/packages/ca/cd/71d43284cca9c5145ceae04ddac1adfc57e9da57cf8efd30c0876844c9bf/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_i686.whl", hash = "sha256:2ff9983a58647b03754fa3d1005e59a9c563e15256340fc062b4a34c7969d52a", size = 1382322, upload-time = "2026-11-06T09:54:06.405Z" }, + { url = "https://files.pythonhosted.org/packages/0f/56/5754189cd709d4eb34601f8ebb57f1d2381b2dd74f62352ba6b84bce4a12/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:6e461d7b392a630593134611ebb1fce6baba88dbbf4f07661a37ff58ff4e1b6a", size = 1278225, upload-time = "2026-11-06T09:52:59.772Z" }, + { url = "https://files.pythonhosted.org/packages/7e/a9/5224ea74356981f01222c42f0acc55821fb5aadf3f1f15adc797c7eefbd2/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:62c0675a837bbe0f3f7c7a89b701bee159759840c23b9bec9d565d3434fb0b3a", size = 1294018, upload-time = "2026-11-06T09:54:29.127Z" }, + { url = "https://files.pythonhosted.org/packages/9d/c5/297f16660b15eacb2872af9fb127e7fe83f48f6f9caf223cb5abd5a25bd8/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:124b0b9962ff6b25786692b7b6cb0065f8bb7870081ddd9baf4745b0ff4a5c7a", size = 1333737, upload-time = "2026-11-06T09:54:03.427Z" }, + { url = "https://files.pythonhosted.org/packages/19/18/7e35ba1bc1f0e3ec55d9d97864db42b5ffeea92766ae4bd7ced0f77cc930/hypothesis-6.170.15-cp311-abi3-win32.whl", hash = "sha256:d34e54f485777eb217c85c425ddbe7b278ef56540feedb5de4097a5abc9f5719", size = 687717, upload-time = "2026-11-06T09:54:40.259Z" }, + { url = "https://files.pythonhosted.org/packages/fa/d6/c16f5abdb56baa2d401de38c2f758090796c1716fed9aa690179772e6adf/hypothesis-6.170.15-cp311-abi3-win_amd64.whl", hash = "sha256:de9fe573a4955b0cf0354822fbfe9b79882e8de02f26287313fe1ad47ba3e69f", size = 693782, upload-time = "2026-11-06T09:53:17.157Z" }, + { url = "https://files.pythonhosted.org/packages/13/7a/ae3b7fdd44c30b662f27344ccb810d080d11b7f557c2cffa88d01e677295/hypothesis-6.170.15-cp311-abi3-win_arm64.whl", hash = "sha256:de5e11c568fd411a3cf07e4e34d4f8cf07d638de2f254c8bd87c1879679cdd9a", size = 692109, upload-time = "2026-11-06T09:53:52.599Z" }, + { url = "https://files.pythonhosted.org/packages/22/fa/4f61c0e5487d75d9ef20bb6d7b9e13b5aabf89d249896d9af0a648578be7/hypothesis-6.170.15-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:679635cd52626790214f879a8bdbb877923333fbd18905c591af41bd74d2f8db", size = 801251, upload-time = "2026-11-06T09:53:45.982Z" }, + { url = "https://files.pythonhosted.org/packages/51/c2/8eb51b3b243248fc7289b37aa78caeff847b98e7a35ba6f6e12a846d68ec/hypothesis-6.170.15-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f95b532f23bed43ef3c45fbd19baf4717687a4993fa6f42fc704fbde18bd744c", size = 796937, upload-time = "2026-11-06T09:54:31.637Z" }, + { url = "https://files.pythonhosted.org/packages/af/fe/80d94b0366d3408078c32758f7149592fdf963d431e52188728e5380d806/hypothesis-6.170.15-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9f5937e70c636ee46bd2242d9ef120d19744e63ce7d17a92fd4c9f57ef62b1c3", size = 1125542, upload-time = "2026-11-06T09:54:16.018Z" }, + { url = "https://files.pythonhosted.org/packages/fd/b4/c9dfacdfa074ebcee35ad8d9e6436480a45b543bd42ab92fa556e3bee113/hypothesis-6.170.15-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ecbd6294a636594580689debc3011a0ca3eb76577770f661224314202f107e14", size = 1168312, upload-time = "2026-11-06T09:53:22.993Z" }, + { url = "https://files.pythonhosted.org/packages/66/dd/29996ba7a8ef7eaea1493dffda4bfb04e85180a2f45d3d9ab7793ada3722/hypothesis-6.170.15-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:efaee8533a06b6a2382ff7c336ea5a747c1b22a4e97c19bfe825a02388f56d2d", size = 1300279, upload-time = "2026-11-06T09:54:30.502Z" }, + { url = "https://files.pythonhosted.org/packages/57/2d/b4be9bbb76ac5079af9cd5cf484e3e0ad91f60a7e98c69d56ac623d55573/hypothesis-6.170.15-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4af2d31c00306707166b4f39e5208d2585f9ef4accb10586534101eb32f243fb", size = 1334296, upload-time = "2026-11-06T09:53:08.948Z" }, + { url = "https://files.pythonhosted.org/packages/69/55/f0677edf64249c5d91ae9387678bfd43ae0f54905fd2a4dbede9cbaf1e0e/hypothesis-6.170.15-cp311-cp311-win_amd64.whl", hash = "sha256:b48cb85180255ec3eb3b3e5d49068c9ad447b25e34fccafdabae63d2c3d854ad", size = 693893, upload-time = "2026-11-06T09:54:49.687Z" }, + { url = "https://files.pythonhosted.org/packages/91/db/84d418c965fe889d21e7791f946f7c893bf492bcedb38f3f5b8eb405a035/hypothesis-6.170.15-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:29223a2d180e463f1205b7e5eb397db0c4827de06f2ae571b00c392d355c410e", size = 802327, upload-time = "2026-11-06T09:54:20.994Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8f/63d8644162728ba8b2c8a8a8b6a34476663c964cc0f6885c19f84ead40d6/hypothesis-6.170.15-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7953ad8f123b4289801b833666aaab757ba52e91ed687d954eb26f4af7328e5b", size = 794302, upload-time = "2026-11-06T09:54:24.828Z" }, + { url = "https://files.pythonhosted.org/packages/ec/2e/d479c69c08d5aabd7e6499f3dddc22b241db42922d746d05df9548213229/hypothesis-6.170.15-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b1f37920547eafa77814bc9b638e47299562123023bdf3c9cb002795bb90fc92", size = 1123978, upload-time = "2026-11-06T09:54:36.215Z" }, + { url = "https://files.pythonhosted.org/packages/ee/e2/824c524d04152e5c26111247d2d4dbf210d43df7c6612f7ff22c20de5abc/hypothesis-6.170.15-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e9e20ec17d2095e9314ea232b4e34b5510def0d9e7a7e764cc70cae88fe4b0c4", size = 1167677, upload-time = "2026-11-06T09:54:55.123Z" }, + { url = "https://files.pythonhosted.org/packages/ce/49/4aab201f1fd0109560d985076a4c852c1abda14984470369bf29ea89ade3/hypothesis-6.170.15-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:11c541cf103c784306f6037e5ab962cbe3d5891d36fd98df993f38d7ddbcd360", size = 1298862, upload-time = "2026-11-06T09:53:51.237Z" }, + { url = "https://files.pythonhosted.org/packages/db/a7/83fc4ef9484deefd955949a9a72a14d9435b6ace339feb27de25bf286e29/hypothesis-6.170.15-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:eecdcd38395facf6ea3af90320a574f5e63c310c194d2a0eb75f121223942386", size = 1333300, upload-time = "2026-11-06T09:53:39.58Z" }, + { url = "https://files.pythonhosted.org/packages/d5/18/5f1a5ce07a9e6b7a2cbfb6a8bceb9b5161de5477abb8d99d659a898b7554/hypothesis-6.170.15-cp312-cp312-win_amd64.whl", hash = "sha256:7dfb3d92df4faa67d3c975d1ecdefabc5a2481b789048f52cd5fb775c6c517b8", size = 691422, upload-time = "2026-11-06T09:54:05.043Z" }, + { url = "https://files.pythonhosted.org/packages/16/16/d75485989f250dd5017d1627902961c2f985686355f50d10170a2490d970/hypothesis-6.170.15-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:e3f478d4d9e13d528e352a4d938dea10b25793663ac752d774d7d35b008a1b45", size = 802290, upload-time = "2026-11-06T09:53:33.892Z" }, + { url = "https://files.pythonhosted.org/packages/24/45/54e42ac718e1164090c04b588024e4818a8e2a28b9002faa21e9fd59ab67/hypothesis-6.170.15-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9c92af3f0c8844d9eba793a4371035a45e88bb59579a1408ce5d3cceb9e2b1da", size = 794293, upload-time = "2026-11-06T09:54:09.14Z" }, + { url = "https://files.pythonhosted.org/packages/b8/ee/1a81a7d544e321165159a07e666f6c302ec109beccca3b37f8d0de54e0cd/hypothesis-6.170.15-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:dce4d989f6b9c0a589b944591f13de3dff34e186c14401e11b819fed81d70a5b", size = 1123881, upload-time = "2026-11-06T09:53:01.454Z" }, + { url = "https://files.pythonhosted.org/packages/c9/07/4d506b2e37601ec8b38a0c4b8f547dd344bd8eccd577dbd0543a744fce03/hypothesis-6.170.15-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f25261d1656f830a78863844be5fb55cd0208154dc9ddec85d44fe691488c557", size = 1167605, upload-time = "2026-11-06T09:53:32.309Z" }, + { url = "https://files.pythonhosted.org/packages/a5/77/a88824d02272f149870e36aaad0197dc5a186f53a1896ea3117f250b8414/hypothesis-6.170.15-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5ae92fa40b57c1cd331d63fe6f95aecfdb6aa32f15b4c418c108c41fcd4aef84", size = 1298841, upload-time = "2026-11-06T09:53:15.809Z" }, + { url = "https://files.pythonhosted.org/packages/68/b9/6e1b55b6b32926cebb7ef37076d8fda9d0f87045e90e4b75e93eeb9a56ac/hypothesis-6.170.15-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b829dc3cbd73fe08c02151afc438448180907da62c154cfa68abd178eafd4d48", size = 1333319, upload-time = "2026-11-06T09:52:57.279Z" }, + { url = "https://files.pythonhosted.org/packages/c8/77/7d2009c663eb26b329c622091f7593ee6c90eac663f389fdf7311d44b035/hypothesis-6.170.15-cp313-cp313-win_amd64.whl", hash = "sha256:1f7ede44b875dddd8f3e7562e6702c363e82c6fb680b0fe079536bae662987f8", size = 691393, upload-time = "2026-11-06T09:54:56.287Z" }, + { url = "https://files.pythonhosted.org/packages/96/85/977d43b789fe4ca530e76020bbd2db07a9af3c17a4bf27a276416b6540e5/hypothesis-6.170.15-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:ffac67d06f765fd000a132e71117ee92dbd59863cea18403220ca4e39b50397f", size = 802549, upload-time = "2026-11-06T09:54:17.455Z" }, + { url = "https://files.pythonhosted.org/packages/cb/1a/51e637155a8c897774463389f1341ec8d466a9860cf5e004689866c557b2/hypothesis-6.170.15-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:82b613ee882068e781d810eb73a8195b59edd6cc47e8acbe4971562044a99c83", size = 794333, upload-time = "2026-11-06T09:54:27.915Z" }, + { url = "https://files.pythonhosted.org/packages/24/c1/ea255465b482ba5fc5f678e4347d6c6bbe878c827ca652d634328be96534/hypothesis-6.170.15-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:eb6fe3d1cb91d4f14fd307f10ae969ef7e866c16e4010a750d1cade145dfd764", size = 1124402, upload-time = "2026-11-06T09:53:02.773Z" }, + { url = "https://files.pythonhosted.org/packages/7a/69/32a05f0ae41f699f30ff872be74fe46ee1d45ead7abfb114afe3a4b4a3ee/hypothesis-6.170.15-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f91f27a89e8d55c7f043cb1e10705096236d4f7bcb35f3ac4f821e0c9b9bcd05", size = 1167795, upload-time = "2026-11-06T09:54:00.357Z" }, + { url = "https://files.pythonhosted.org/packages/c2/fb/c16886cea3a7ae3045093480775eb058eed549f41aa0e21a8d96aa7d51b1/hypothesis-6.170.15-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e0e4ab687c0f2bd62b7963dc8c3c8d29211cdc6db7ce05d37ef2a20d21219c18", size = 1299361, upload-time = "2026-11-06T09:53:04.441Z" }, + { url = "https://files.pythonhosted.org/packages/b7/f3/ad57518f76503276c896388affeccca1ffb1cccc529d063dac588c4bb652/hypothesis-6.170.15-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:b01d130c103fdf78a4a748cae7d095edfe5d37534828413a509936fb3567db61", size = 1333515, upload-time = "2026-11-06T09:53:18.642Z" }, + { url = "https://files.pythonhosted.org/packages/2b/08/500fbe05990d886d4502fa334f6cf03607be473b2a2efffb660238135f05/hypothesis-6.170.15-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:1138c03edf4c4401afb28e50255644b4ab4e1ad52864456cd4e84458ba8c671a", size = 634104, upload-time = "2026-11-06T09:54:22.317Z" }, + { url = "https://files.pythonhosted.org/packages/41/53/11e3260a72024f41246061ad204627f8336bfbf0ec2b180648d01a05491f/hypothesis-6.170.15-cp314-cp314-win_amd64.whl", hash = "sha256:57ae2617424f5bb55af0146b47e0aff64a9d6677a4d5216cf2a66bd3bda0d457", size = 691115, upload-time = "2026-11-06T09:53:41.223Z" }, + { url = "https://files.pythonhosted.org/packages/ba/41/655fca0f45b7ea6df6b5bb70ab52b740cc6bc30b971366036eddd36a77c9/hypothesis-6.170.15-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:c0514f3f8ab5d56103b756317dedc8476945b0633e51112312247e3caecd0eb2", size = 800640, upload-time = "2026-11-06T09:53:05.61Z" }, + { url = "https://files.pythonhosted.org/packages/a5/89/6bf52da8b15846c7263eac9fcffb89cc1d1c82f96ca5b839a0d00bb3aa3a/hypothesis-6.170.15-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:cc5434cde3b22c900dfe01f891804b48f6e2aa93e891ca98a14c07dd04fa6d54", size = 792915, upload-time = "2026-11-06T09:53:11.508Z" }, + { url = "https://files.pythonhosted.org/packages/11/f9/a0c2a356c7a3a4b65ec2f80382c9ea5acc1a86247ac64ecb1b7dfc38ee95/hypothesis-6.170.15-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f22900eec7df2696073c05f60c666654eaa93f17aebe8964f751d75b131dcd90", size = 1122841, upload-time = "2026-11-06T09:53:21.626Z" }, + { url = "https://files.pythonhosted.org/packages/ef/f1/d4fa867fae5a733e4041720622417804bcfb79c00d265c5451243a5aba20/hypothesis-6.170.15-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7288412dfba6b5a6f875279a25409eda6b25d097c26ea710540f904287c55d06", size = 1166715, upload-time = "2026-11-06T09:54:42.908Z" }, + { url = "https://files.pythonhosted.org/packages/04/5d/cbf8acf14caa5a2e4d34dd088a507cc84da49a660b6f532104d8afdb2903/hypothesis-6.170.15-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7d546a5d6a5549a6b34304f7315d20aff7afd206996592329877da529b9d9153", size = 1297608, upload-time = "2026-11-06T09:53:29.22Z" }, + { url = "https://files.pythonhosted.org/packages/9c/a0/912a0ebf3ab19b39235233f9e1664147f6e842aa6915828d68c1d1e13f27/hypothesis-6.170.15-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:bd8b36d0403eff6473686c0e4d8b7704780ebf548b0b2cc86cb9cbbbe64f8c2f", size = 1332521, upload-time = "2026-11-06T09:53:47.664Z" }, + { url = "https://files.pythonhosted.org/packages/37/36/d9286c792272651db4059a3497a19cc7f4f60e0452c862274d506b0132fd/hypothesis-6.170.15-cp314-cp314t-win_amd64.whl", hash = "sha256:67eb006925a3a49ddc4a48d9af8314349291a7eee9b2baea6beb93bc48211ead", size = 691229, upload-time = "2026-11-06T09:54:45.888Z" }, + { url = "https://files.pythonhosted.org/packages/91/42/b152b66db2061b47ff928efc7162c2dcf4591d92dab19b3c574af3552220/hypothesis-6.170.15-cp315-abi3.abi3t-macosx_10_12_x86_64.whl", hash = "sha256:e007ff1dfb8bfa228b97ed6695325cfa1ba6487c7e1175c884e8795e71fb41a5", size = 800291, upload-time = "2026-11-06T09:54:07.899Z" }, + { url = "https://files.pythonhosted.org/packages/67/6f/49fe04f0b4cfd142d474e08a1855ea093c7367e6ff33e7c5d4a64592f743/hypothesis-6.170.15-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:742846b0e2e31640acf8bba7c2b8b6eb9cecd6817a906af6d4b5ced9db697660", size = 792763, upload-time = "2026-11-06T09:54:51.025Z" }, + { url = "https://files.pythonhosted.org/packages/88/e6/61ec7fb3b84dd8d8644d6a322d5dba4501e2f32d0b10b8b5467e7d6defd4/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:508488dd4e92e03ecd16ea086f33d766855ed1febd322a439ec231c920b1740a", size = 1158761, upload-time = "2026-11-06T09:54:02.105Z" }, + { url = "https://files.pythonhosted.org/packages/8d/ae/c9eb63eb1b2d935551494aa42ecf91bb214d89c52631854dfbb09ccb6d39/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ccc6a9ce18dced7f0d2cba36f334f44697c1c6e692949c1bbd0bc67a7065c86a", size = 1121659, upload-time = "2026-11-06T09:54:12.041Z" }, + { url = "https://files.pythonhosted.org/packages/0a/44/b99e644480a31153de52489dc4c062df5f82a10fbb2b699d0f17ecb08171/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:b8a0b5b3e21a1d2e235f42a813fbf04872196ad53151fdd4cfe02723db699f8d", size = 1152560, upload-time = "2026-11-06T09:54:41.478Z" }, + { url = "https://files.pythonhosted.org/packages/f8/0a/bfc1c697f34e395d635f49d2a29f1bfc41a0eccdcf9fba32fb33601325de/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:b59187094929ce6d5351a6f92e7f3831cd463fe69591def6ebd0023a3073af2e", size = 1146287, upload-time = "2026-11-06T09:53:42.894Z" }, + { url = "https://files.pythonhosted.org/packages/bb/69/90fac02af55ccbea1d1b3bbc72512c4f998e3fabc6b375c8c0afd0e6003f/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:0ecf4e2948c3de57ea12d66f6cf6c0e3ad88b5eae0d216cfa2922800ba5522a7", size = 1200042, upload-time = "2026-11-06T09:54:37.409Z" }, + { url = "https://files.pythonhosted.org/packages/f8/eb/6810206ee4864b39da6e81b2318516773d5a89b0e2132c00dfc9aa760179/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:55e3dcd5d8fbfd5a97018ff2712f375148b62ef537490c281a198977f3588578", size = 1165971, upload-time = "2026-11-06T09:53:25.72Z" }, + { url = "https://files.pythonhosted.org/packages/e1/c8/ebfb57d277e571c207d690efa56462f1f582721e5170bb86af42c3f97b07/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux_2_31_riscv64.whl", hash = "sha256:417fe54775f846fa4903bb2094ce3092a0ecc107db6676b21fd8069fcc328cb9", size = 1120269, upload-time = "2026-11-06T09:53:56.767Z" }, + { url = "https://files.pythonhosted.org/packages/8a/2b/69dff10b56fbc21dc0d240de503d741ec14cb6819f67530bca0b6ff7c5af/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:47438186039fcfba3a245bb407490d442ce2c9cce4370565f1bfcdcb887e91e2", size = 1296436, upload-time = "2026-11-06T09:53:54.24Z" }, + { url = "https://files.pythonhosted.org/packages/5f/43/42b037bb17dca205f5953b11792ecc2c73dbf7ec743d5dc490d010edb9b0/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_armv7l.whl", hash = "sha256:372b05075d4a259c5ebf3fcf43dc689ef5d4335bed9d0c9dd25d14997842c0c0", size = 1425535, upload-time = "2026-11-06T09:53:27.106Z" }, + { url = "https://files.pythonhosted.org/packages/a8/29/bb3050f958b0e3156909011afdcc07812b58a47eba50f53a39d931c1256b/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_i686.whl", hash = "sha256:2161fb65416bf8da3b1c3119aa92ea63cc177fd88249bf7dc4ca64b4872e0bd1", size = 1379162, upload-time = "2026-11-06T09:54:23.523Z" }, + { url = "https://files.pythonhosted.org/packages/a5/db/30a2291c92cd437b0c8184bcead204add93d174a1317894dc50ddd3a681d/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_ppc64le.whl", hash = "sha256:b3db4c8aecd13e043c419d90ccb683fdf19711b547ca9d23e685a35157d4657f", size = 1274757, upload-time = "2026-11-06T09:54:38.796Z" }, + { url = "https://files.pythonhosted.org/packages/a5/0a/5e1bf0060a1f9486f6cad2b512b5101526dc376565eb669c20964ccee730/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_riscv64.whl", hash = "sha256:3b81f08d6052ac74f479215029e253d88fb80e9867e8bc034252d345abfa94ce", size = 1292003, upload-time = "2026-11-06T09:53:14.207Z" }, + { url = "https://files.pythonhosted.org/packages/0b/b9/9d18977c7ec9fa0d0fb22f0e52b3a270fef7b8251579d46660fca285e289/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:a51297c26ab637a97ec3283a39de163efce0a926d0ccd4378faabf5994adb01f", size = 1331925, upload-time = "2026-11-06T09:54:53.632Z" }, + { url = "https://files.pythonhosted.org/packages/ff/af/a86d51e4550c92a794777a59a9332d135c975c6f6c25b7506c447c3be27e/hypothesis-6.170.15-cp315-abi3.abi3t-win32.whl", hash = "sha256:51246e702c458b42a4b5079c3e6904c9dfb5193de920ed91fdbfa09fa694c55b", size = 685060, upload-time = "2026-11-06T09:53:35.48Z" }, + { url = "https://files.pythonhosted.org/packages/dc/3d/ef64b33ef8c5eceb7448860b77bc1d28e3e3b3e92b7d662456fee227f4b0/hypothesis-6.170.15-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:a951de05b61b7c1235a732543dc6c3b105b6c894e736f21cb891449589aaeba7", size = 691031, upload-time = "2026-11-06T09:53:10.201Z" }, + { url = "https://files.pythonhosted.org/packages/e8/3d/f875573e232550be631b6932f93bd6b2234d880891394fe4d70d57e292b7/hypothesis-6.170.15-cp315-abi3.abi3t-win_arm64.whl", hash = "sha256:9dc31166ccb95928c6eb05817684b2dd1c2a3698a6daad0450e5f449e44bb633", size = 689008, upload-time = "2026-11-06T09:54:13.194Z" }, + { url = "https://files.pythonhosted.org/packages/4d/f4/34e1ca38f88cbf478f970b7743ea022e0d70d5b4e943eea7c06532aea6b0/hypothesis-6.170.15-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:bfe10cd8c8138ba84cdd0f72d72e0a85f0f9adea8bc730f4ab4676cd41a730af", size = 801079, upload-time = "2026-11-06T09:53:19.956Z" }, + { url = "https://files.pythonhosted.org/packages/6d/8b/3438b357b3f6e076ff3f68aee5a62c1319573c4858b9f9db6e12e2893fca/hypothesis-6.170.15-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:5c1331070d8688d31b9ce99a100593bc6afdada964689b5e1a5f2ecffefa2455", size = 795993, upload-time = "2026-11-06T09:54:52.505Z" }, + { url = "https://files.pythonhosted.org/packages/fb/a7/f25cc6ec59659ef59093ffa743a2494cc153bb8a8eeeb78e1c1e58720888/hypothesis-6.170.15-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b56ea17542eabcb9e2c1d574fcabc9df7e14a7376cfce324e2fa05e9c836fff8", size = 1125066, upload-time = "2026-11-06T09:54:19.213Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c3/4b58275fe5771859bd03fe5ceccee64968874fdb999c549abf7ae7f716b9/hypothesis-6.170.15-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1c3b98713318639a6c852f3fff60bddd466096528eb2cd5853ab077ef04f74c", size = 1168451, upload-time = "2026-11-06T09:53:38.214Z" }, + { url = "https://files.pythonhosted.org/packages/dd/b8/c935e11303f94a6e280e059aedc7c5a6458207f7039aa241d2504e178c53/hypothesis-6.170.15-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:7ea75bc4c55f0ebb80179ae7e8fe1c8ab09b553005d1aadcec14e97e1306a82a", size = 694365, upload-time = "2026-11-06T09:53:59.021Z" }, + { url = "https://files.pythonhosted.org/packages/3b/54/ab7c9a7581b0acaeb58850629f4772aab054f2fd6a77bd3264262dfb1156/hypothesis-6.170.15-pp312-pypy312_pp80-macosx_10_12_x86_64.whl", hash = "sha256:45c267cb5bcd7b73b1ca6cedb039de423b8695b34a31cc87c29a7787058e7e59", size = 801399, upload-time = "2026-11-06T09:54:10.562Z" }, + { url = "https://files.pythonhosted.org/packages/fe/a6/a7dfce075d7371c9951e2a69e78d93bff5099d1b7b0ca207497eed68428b/hypothesis-6.170.15-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:3eb9428e0ba92993b61cab0289b8450f469b1e4c56cbdbdeaad258f0fb4f107e", size = 793309, upload-time = "2026-11-06T09:53:07.629Z" }, + { url = "https://files.pythonhosted.org/packages/6f/b4/ce76691a588dca99c73116593b2514af2d0095e7e72d3bcdfb7dcecf2170/hypothesis-6.170.15-pp312-pypy312_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9c30c911be51aa4fa84706f1d79dcd9ad6b9728207e69667a3fed2d4ab711434", size = 1123240, upload-time = "2026-11-06T09:53:44.286Z" }, + { url = "https://files.pythonhosted.org/packages/52/a7/998ba78de4842158178f6d96eca52ec1c786548b3e08902d527469329c04/hypothesis-6.170.15-pp312-pypy312_pp80-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d2b68004bd5a238320569f7c03322b22815c2c145b1f7bbf52a319662570ee5c", size = 1167454, upload-time = "2026-11-06T09:54:48.426Z" }, + { url = "https://files.pythonhosted.org/packages/03/f5/410ff24a49dd645f651732f45e466cbb73f4bb73d1c54eaa5a07b832b0a2/hypothesis-6.170.15-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:d25e9a3f92e9f824bb110679506ece2b8fd7d093f1fa7d819ca46278a681a1f1", size = 692539, upload-time = "2026-11-06T09:53:30.812Z" }, ] [[package]] @@ -907,7 +907,7 @@ requires-dist = [ { name = "pytest-cov", marker = "extra == 'test'", specifier = ">=5" }, { name = "pytest-mock", marker = "extra == 'test'", specifier = ">=3.14" }, { name = "requests", extras = ["socks"], specifier = ">=2.34.2" }, - { name = "ruff", marker = "extra == 'dev'", specifier = "==0.17.3" }, + { name = "ruff", marker = "extra == 'dev'", specifier = "==0.17.4" }, { name = "urllib3", specifier = ">=2.8.0" }, ] provides-extras = ["test", "dev"] @@ -1298,15 +1298,15 @@ wheels = [ [[package]] name = "pytest-asyncio" -version = "1.4.1" +version = "1.4.1.post1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pytest" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f8/9a/887535e477847f5159377ab35303923644840b13c0ca03c0a467f84d4680/pytest_asyncio-1.4.1.tar.gz", hash = "sha256:e8266eb094e5ee9ffdb2068c9836f33e209ea77a970eb846933d416b5602669b", size = 145237, upload-time = "2026-10-25T21:05:37.135Z" } +sdist = { url = "https://files.pythonhosted.org/packages/73/7f/c60a4338420b33453d4f814ac0c930abd399f162b9bdd21af4b9e363037f/pytest_asyncio-1.4.1.post1.tar.gz", hash = "sha256:f582d9ea4a1c082195abe8bd29a1fe106aeb1cd435e3dad2d3bc2749935c36a2", size = 145360, upload-time = "2026-11-01T18:26:03.732Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/46/d7/cd9e2708afdbf059658adaf08bdb0792ca52489871051d6ce7d498b51277/pytest_asyncio-1.4.1-py3-none-any.whl", hash = "sha256:507afa78ec77c6661164ef1a2368bc7820383fd1a14b2a7f813de8b5a92949cc", size = 17061, upload-time = "2026-10-25T21:05:35.473Z" }, + { url = "https://files.pythonhosted.org/packages/e3/de/adbc7578959cfab07e5e7c05cf6d54224a51e7667ea2c07458b6bc571e75/pytest_asyncio-1.4.1.post1-py3-none-any.whl", hash = "sha256:0755e488cc0a2b9bd2eab7292cc6390d4cbb8390f1020745647bae5a708e0165", size = 17140, upload-time = "2026-11-01T18:26:02.168Z" }, ] [[package]] @@ -1424,27 +1424,27 @@ socks = [ [[package]] name = "ruff" -version = "0.17.3" +version = "0.17.4" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/59/73/81f140c4edd9cc323de5478e6bbd3bbcfae9a82692df1a258de8cec6a6d2/ruff-0.17.3.tar.gz", hash = "sha256:a57049c8addb3662073859bb55a7ad35aa54f8a7c9ed268911d1333c5aadaaa9", size = 5339444, upload-time = "2026-10-27T00:34:05.914Z" } +sdist = { url = "https://files.pythonhosted.org/packages/84/0e/3d154514b5bad104f7e1c13169c2d09aa9959fccdc06eb47610ccdfa83ed/ruff-0.17.4.tar.gz", hash = "sha256:f32d178b50e826e00f6c6c1be3f56333068acb9b67fe167143527fa9b81e890d", size = 5357750, upload-time = "2026-11-05T18:52:17.638Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9e/8c/083365310c4e79c842f25bf5a842facbd9b0c0ec336f96dffa5074fe723d/ruff-0.17.3-py3-none-linux_armv6l.whl", hash = "sha256:ab86b84cd9d05e56d329742c0cabdcbe2d1d56c98f4a04aab9b5b66196febfb4", size = 10216522, upload-time = "2026-10-27T00:33:29.822Z" }, - { url = "https://files.pythonhosted.org/packages/72/26/4b2edf31cfebe9605d8f6ed8f1d6f376d3a53d4c9a123e62661c64c440f0/ruff-0.17.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:e407b4a6852853a9a2cdce96963e94ad9775578bb44e7561a0f2829f3cc04b11", size = 10217786, upload-time = "2026-10-27T00:33:33.949Z" }, - { url = "https://files.pythonhosted.org/packages/a2/7e/537aba4b7f54397a374d2f6a6fc93e9c8015e18553f31a4a7b7dbced48b5/ruff-0.17.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:b75cc113b3aca388933d8296b667b1ac401a80317ea3074c9b0a66541199da29", size = 9440362, upload-time = "2026-10-27T00:33:35.784Z" }, - { url = "https://files.pythonhosted.org/packages/3d/66/283e39734f66c8a5ebaa93c22eb7b7515779a0b1d5a5c0ad20e05c0edb41/ruff-0.17.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ab5fa7ed5ce18554ea69d850ad162cbaa0c85fc47c08d83a569f806681c9a6ad", size = 10094281, upload-time = "2026-10-27T00:33:38.216Z" }, - { url = "https://files.pythonhosted.org/packages/21/4c/1ffc768497bd025a32c72152771e40c0b99bddc5cc6e4f50c7949a395346/ruff-0.17.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c673c170e27834d1262e3a9c1e97bdc9b9c3b180c63d89173ce69747232474c1", size = 10022543, upload-time = "2026-10-27T00:33:40.181Z" }, - { url = "https://files.pythonhosted.org/packages/73/c3/f90db547301080fcb82c92abf914c8bd57b89911d9b65a6c4cc6b52d0635/ruff-0.17.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6a754c0341bc9ca151b7b335988b3263921c08859f84ca219b70cee825571b6f", size = 10683921, upload-time = "2026-10-27T00:33:42.182Z" }, - { url = "https://files.pythonhosted.org/packages/e5/98/92d4a8a26c6c96cf1a5b34dd59036d8a71e52d650aab065c58867e964e63/ruff-0.17.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4590b9d86c0b1543ebb09094254e191cd43fe8edaf330baa035aab03da251532", size = 11373408, upload-time = "2026-10-27T00:33:44.19Z" }, - { url = "https://files.pythonhosted.org/packages/43/02/1f24d2e3064c9753926deeb901afa57777b37ee46799b09ddd7aee6e5145/ruff-0.17.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bbde18beccd98c29a227c63c99022e3443b99258e08326df6425dfe0443705ef", size = 10977469, upload-time = "2026-10-27T00:33:46.179Z" }, - { url = "https://files.pythonhosted.org/packages/f0/20/fecedea2209f574ab92033b344e01a7f0c2dc76c6d6d19a14c9f8141173f/ruff-0.17.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7fa4b0f931cdbcb8a52044f370a3eb429fb42eb88807b0e800fcaa98dd42b24e", size = 10577491, upload-time = "2026-10-27T00:33:48.233Z" }, - { url = "https://files.pythonhosted.org/packages/33/36/b93fdf0bc6f84f0cd487aadfb0354deb40013669ea35ac3d26855de1e959/ruff-0.17.3-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:39405f341deec934b4289634324ad695f72df2970f9121582872eaf5b722f0f5", size = 10608748, upload-time = "2026-10-27T00:33:50.284Z" }, - { url = "https://files.pythonhosted.org/packages/5d/b7/7d3f5f14145daead1efb0b9a8289ed1daa100f419d60774375951723ce00/ruff-0.17.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:68074094f55ca3d29ab19491f640282f7a84061c4c7977aa5094b968ca457e9a", size = 10075057, upload-time = "2026-10-27T00:33:52.074Z" }, - { url = "https://files.pythonhosted.org/packages/b0/ed/93ff7a5909ee56e2bd4b982deae9e0efb2724417874a90c9e41ad66c6dd7/ruff-0.17.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:27bb571ac78fef178fe5118d2827df95c2aae74a48fff2b15f6acd03af5ff5bb", size = 10022431, upload-time = "2026-10-27T00:33:54.061Z" }, - { url = "https://files.pythonhosted.org/packages/9b/07/a83b9eeec8c1c3c0e4eda15f06c3a91001bfd2687ea2f07b750719bf9712/ruff-0.17.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:029c37cbd3de48ca37aa12117bead2d065f15da17d66bf84e0d4274013705db2", size = 10394903, upload-time = "2026-10-27T00:33:56.158Z" }, - { url = "https://files.pythonhosted.org/packages/af/b2/05c39857c2526fcbebe46ad93a8dc97424656dfef14d3ef933abe1ffd331/ruff-0.17.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:692fdb46d0fd9c71e380947dc5fc72f2c3f881073bc1f739e4579376231affbe", size = 10799780, upload-time = "2026-10-27T00:33:58.204Z" }, - { url = "https://files.pythonhosted.org/packages/ec/d9/47171a16739eb7a353936b31c20cf54340531e68c9af7d72fd7a784e235d/ruff-0.17.3-py3-none-win32.whl", hash = "sha256:46539cb031b01fd29ae0a02142483c46640b233ee12bb1c1b690bffa1555d5ca", size = 9908481, upload-time = "2026-10-27T00:34:00.087Z" }, - { url = "https://files.pythonhosted.org/packages/d0/a0/f08c1631bfd81faa6a90eaf70c37c786c11bed2046302b56bb506c25e1a0/ruff-0.17.3-py3-none-win_amd64.whl", hash = "sha256:56b8ffb3f3b3cbccb8b76b71b38261b7ed982ef5d20f5b447b1b61a7f4949b24", size = 10341333, upload-time = "2026-10-27T00:34:02.099Z" }, - { url = "https://files.pythonhosted.org/packages/99/d5/4ad4ed31413c301430918e70d3d38ae6f097af0766cb9ab8c9d502b2a4d6/ruff-0.17.3-py3-none-win_arm64.whl", hash = "sha256:81fce74bcd6be0e9da7c67c7553fd0f1f12964a2052cd728ef917b937a5ca1d9", size = 9854332, upload-time = "2026-10-27T00:34:03.847Z" }, + { url = "https://files.pythonhosted.org/packages/e0/61/c83c78bbb6108f6c6270a106cf12b54175f4f42da088b9bb880f18e31289/ruff-0.17.4-py3-none-linux_armv6l.whl", hash = "sha256:2b08c4ff98dc234f4a3871a3105353b922fa875ea1073ca31001eb8c06bb4d89", size = 10252195, upload-time = "2026-11-05T18:51:36.594Z" }, + { url = "https://files.pythonhosted.org/packages/0a/12/dd158708378866e8b53e145a465dbc51a7cccb9fa197a74d67eaedde7234/ruff-0.17.4-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:13e781c3c5f663e7fba737eaaeb70dd943dd55171daf316afb25cd5268cfe0c7", size = 10266044, upload-time = "2026-11-05T18:51:39.502Z" }, + { url = "https://files.pythonhosted.org/packages/28/32/89a94a8eb11fd505a381ae6f04e190d038d9958695209dc1786ce5cfcda3/ruff-0.17.4-py3-none-macosx_11_0_arm64.whl", hash = "sha256:7ed2f416349944f908f9574215994602242b0836844eba48eec61473033afca0", size = 9432227, upload-time = "2026-11-05T18:51:41.968Z" }, + { url = "https://files.pythonhosted.org/packages/58/de/a392dc38b215798ae72e639d228b7f6c02d826a95d1c0ad7c4c0ee49ef5b/ruff-0.17.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8ea6e0017c785f7282092b11e46338e4ebed1b9e575ebf2e55a8a1eda968241a", size = 10136900, upload-time = "2026-11-05T18:51:44.562Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8f/a880f60f42005f6ffdf58f77af34c7ee327000b5607f48a2f6a69d8b242c/ruff-0.17.4-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7e061dcc0933c7031a616ac8d66ac540309b2aa21ab558101a8f53e9ac7a1185", size = 10051245, upload-time = "2026-11-05T18:51:46.7Z" }, + { url = "https://files.pythonhosted.org/packages/09/55/98844264108af7d5ec27ca3a9cd5a989094ca657a14599c4b69a537a0e9a/ruff-0.17.4-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f99e95a1515161138be3cbd1b06c06e739d8feb38ade35564556999fffc3686e", size = 10704341, upload-time = "2026-11-05T18:51:49.228Z" }, + { url = "https://files.pythonhosted.org/packages/28/a2/5edf97659c3ac7c73f978003bd314936f671037fdac6b978e9de3e4b2b65/ruff-0.17.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5f28cf0dd37cb172fa5a8d2e92e6ada3a9dbd0609f094ed24039929eef0b7524", size = 11394465, upload-time = "2026-11-05T18:51:51.534Z" }, + { url = "https://files.pythonhosted.org/packages/f2/8f/51371ae856b2bef4d15a044a574695fbc0f6ae63aafa42a2a22428070fb6/ruff-0.17.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b21c771b296888e8a35c6f48555f4b44e4483f61675d6ed51810a5203469ce6", size = 10988262, upload-time = "2026-11-05T18:51:53.91Z" }, + { url = "https://files.pythonhosted.org/packages/af/1b/62874f14c7873f27c7887d2b1ea41de990e14ba9518801ffe8eacb5d51a6/ruff-0.17.4-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2cd025509b2e15721b426fc70fd946d71f43b3db3b08e946dfec2d696d911690", size = 10572829, upload-time = "2026-11-05T18:51:56.129Z" }, + { url = "https://files.pythonhosted.org/packages/98/30/860b9dae67432b16b88558a9cb2d3194825fa62838f8b9cc49f5d9022095/ruff-0.17.4-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:49b77f7b3921669466882a4881168801bdb06ec2cd83fb936049016cf5fdece1", size = 10617545, upload-time = "2026-11-05T18:51:58.172Z" }, + { url = "https://files.pythonhosted.org/packages/0f/08/781a4b41a1c83fd6e30fea610d6502a6f94e49cf94693fd37bdcbc6bfe11/ruff-0.17.4-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:e3b84eb74f260d1c2dbd236fd9d4c011d4fdd0a52bdf8aea57a10e3a1b71fca5", size = 10111955, upload-time = "2026-11-05T18:52:00.59Z" }, + { url = "https://files.pythonhosted.org/packages/3c/e9/94b1c7b677120f30839254518924f73a8157e9bcfa200edcd5796fecdb99/ruff-0.17.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:20e43d7a08e712e33067ba887e6574546c79bd4831596ce8f16803ac7ff9ad90", size = 10058355, upload-time = "2026-11-05T18:52:03.61Z" }, + { url = "https://files.pythonhosted.org/packages/27/5f/a825910b9f309336dc33cb8c0774126662c1d2f765699b3e0a1bd538d01f/ruff-0.17.4-py3-none-musllinux_1_2_i686.whl", hash = "sha256:0d1f4848fd2ec0499be4046db9b7dfcc952666885f00233cc7033515282556a8", size = 10415932, upload-time = "2026-11-05T18:52:06.264Z" }, + { url = "https://files.pythonhosted.org/packages/8b/b8/0796468423413ea4df1a6e2442ae26cf49b8f7dda0eecf246e0d5d0dde54/ruff-0.17.4-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:6007e7f3a0e55b0fbdb947af69cf24c21b4928df6be8ef3e767c69b5ccccf496", size = 10826033, upload-time = "2026-11-05T18:52:08.675Z" }, + { url = "https://files.pythonhosted.org/packages/b9/ab/d8e407669ffe5014429baf780c2df47e001968a6e4c17f615e2e7b13a9ba/ruff-0.17.4-py3-none-win32.whl", hash = "sha256:3971a78cba76298b284c8321e6d40d93045ed348bec5c369d85099efc97fb7cf", size = 9931993, upload-time = "2026-11-05T18:52:11.169Z" }, + { url = "https://files.pythonhosted.org/packages/bd/15/42af8a72d8946e3c9efd2bbf6641e462b6832783b0d043d63ef5b280ba7f/ruff-0.17.4-py3-none-win_amd64.whl", hash = "sha256:67c5a894fc054cf41f75f7afa24815de5a74329d97634126c2a1015740ff4e8c", size = 10292922, upload-time = "2026-11-05T18:52:13.436Z" }, + { url = "https://files.pythonhosted.org/packages/68/9e/f1dbffcfb8ff25dadbc21f87a8b73c3848abe4abada9d4b08ccef8bec40c/ruff-0.17.4-py3-none-win_arm64.whl", hash = "sha256:181ae38a9a8fb94925bf7d0794327b48d7fd7f4b50cfd84c0e999cc09ef8d131", size = 9889396, upload-time = "2026-11-05T18:52:15.549Z" }, ] [[package]] From 99fc70b06b36f46aff0aca12915d55389c01f195 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:37:00 -0600 Subject: [PATCH 010/112] build(deps-dev): Bump @playwright/test from 1.64.1 to 1.65.0 in /dashboard/tests/browser (#4003) Bumps [@playwright/test](https://github.com/microsoft/playwright) from 1.64.1 to 1.65.0. - [Release notes](https://github.com/microsoft/playwright/releases) - [Commits](https://github.com/microsoft/playwright/compare/v1.64.1...v1.65.0) --- updated-dependencies: - dependency-name: "@playwright/test" dependency-version: 1.65.0 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- dashboard/tests/browser/package-lock.json | 24 +++++++++++------------ dashboard/tests/browser/package.json | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/dashboard/tests/browser/package-lock.json b/dashboard/tests/browser/package-lock.json index eb3f193293..64042a6bca 100644 --- a/dashboard/tests/browser/package-lock.json +++ b/dashboard/tests/browser/package-lock.json @@ -6,17 +6,17 @@ "": { "name": "pithead-browser-regressions", "devDependencies": { - "@playwright/test": "1.64.1" + "@playwright/test": "1.65.0" } }, "node_modules/@playwright/test": { - "version": "1.64.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", - "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.0.tgz", + "integrity": "sha512-iGURLGuKDLakSEl7Pgfv8h7f+XLT+V861Wfhz0zlEl5nyFuKUopdkFBPKqTllTUp06aOwPuH8iuUEb3yp3MpbQ==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright": "1.64.1" + "playwright": "1.65.0" }, "bin": { "playwright": "cli.js" @@ -26,13 +26,13 @@ } }, "node_modules/playwright": { - "version": "1.64.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", - "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.0.tgz", + "integrity": "sha512-F3AMWcR44qMBt4kq+6Kb6mX7bjGXshktKFOPULd7reED6ZJWevjbNRqysP7q+AATE9kdPEZBibex1BYsvpVoeA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.64.1" + "playwright-core": "1.65.0" }, "bin": { "playwright": "cli.js" @@ -42,9 +42,9 @@ } }, "node_modules/playwright-core": { - "version": "1.64.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", - "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.0.tgz", + "integrity": "sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==", "dev": true, "license": "Apache-2.0", "bin": { diff --git a/dashboard/tests/browser/package.json b/dashboard/tests/browser/package.json index 959dba9f5d..45e9ae4ad2 100644 --- a/dashboard/tests/browser/package.json +++ b/dashboard/tests/browser/package.json @@ -3,6 +3,6 @@ "private": true, "type": "module", "devDependencies": { - "@playwright/test": "1.64.1" + "@playwright/test": "1.65.0" } } From 3215be977a20e37cf461da0fa095dd0d4f6a52bd Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:07:12 -0600 Subject: [PATCH 011/112] dashboard: header line "Mining paused here" with the count of rigs on a backup pool (#4073) (#4087) Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- dashboard/README.md | 3 +- .../web/views/paused_badge.py | 26 +++++++ dashboard/mining_dashboard/web/views/views.py | 2 + .../tests/frontend/app/components.test.mjs | 10 +++ .../tests/web/views/test_paused_badge.py | 71 +++++++++++++++++++ docs/dashboard.md | 7 ++ 6 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 dashboard/mining_dashboard/web/views/paused_badge.py create mode 100644 dashboard/tests/web/views/test_paused_badge.py diff --git a/dashboard/README.md b/dashboard/README.md index 022feb0a72..e07d08b7ec 100644 --- a/dashboard/README.md +++ b/dashboard/README.md @@ -53,7 +53,8 @@ mining_dashboard/ ├── web/ # server.py (transport: / shell + /api/state + middleware), │ # views.py (build_state: the JSON state object), charts.py (the chart │ # window/range hub views.py re-exports), xvb_views.py (XvB, earnings -│ # and top-bar badges), infra_views.py (host, rig, energy, proxy, +│ # and top-bar badges), paused_badge.py (the "Mining paused here" line), +│ # infra_views.py (host, rig, energy, proxy, │ # Tari and sync sections), series_views.py (share health, blocks, │ # payouts, disk growth, XvB history, hashrate and cadence), │ # templates/index.html (static shell), diff --git a/dashboard/mining_dashboard/web/views/paused_badge.py b/dashboard/mining_dashboard/web/views/paused_badge.py new file mode 100644 index 0000000000..7737dbe560 --- /dev/null +++ b/dashboard/mining_dashboard/web/views/paused_badge.py @@ -0,0 +1,26 @@ +from mining_dashboard.config.config import monero_is_local + + +def _paused_reason(data, metrics): + if data.get("stratum_closed"): + return "stratum closed" + health = (data.get("monero_sync") or {}).get("health") or {} + if monero_is_local() and not metrics.monero.down and health.get("level") == "red": + return "node out of sync" + if metrics.global_syncing: + return "node syncing" + p2p = (data.get("pool") or {}).get("p2p") or {} + if p2p.get("uptime", 0) > 0 and not p2p.get("out_peers", 0) and not p2p.get("in_peers", 0): + return "P2Pool isolated" + return None + + +def paused_badges(data, metrics): + reason = _paused_reason(data, metrics) + if not reason: + return [] + moved = sum(1 for w in data.get("workers") or [] if w.get("mining_verdict") == "on_backup") + text = f"Mining paused here: {reason}" + if moved: + text += f", {moved} rig{'' if moved == 1 else 's'} on backup pool" + return [{"text": text, "variant": "bad"}] diff --git a/dashboard/mining_dashboard/web/views/views.py b/dashboard/mining_dashboard/web/views/views.py index f65eced10d..348a272a26 100644 --- a/dashboard/mining_dashboard/web/views/views.py +++ b/dashboard/mining_dashboard/web/views/views.py @@ -62,6 +62,7 @@ # facade: build_state assembles these sections, build_pool_network uses the address elider, and # the last two are re-exported unused so web/views/worker_detail.py's existing import keeps resolving. from mining_dashboard.web.views.monero_view import build_monero +from mining_dashboard.web.views.paused_badge import paused_badges # The time-series sections live in web/views/series_views.py (#1105). views.py stays the facade: # build_state assembles these sections and reads the palette and the window reject rate, and @@ -307,6 +308,7 @@ def build_state(data, state_mgr, range_arg, window=None, avg_window=DEFAULT_HASH badges = build_badges( data, metrics, mode_tok, db_healthy, wallet_change=recent_wallet_change(state_mgr) ) + badges[:0] = paused_badges(data, metrics) badges.append(_egress_badge(egress["summary"])) # glanceable Tor-only / leak header badge return { diff --git a/dashboard/tests/frontend/app/components.test.mjs b/dashboard/tests/frontend/app/components.test.mjs index 433ec68320..103d98e638 100644 --- a/dashboard/tests/frontend/app/components.test.mjs +++ b/dashboard/tests/frontend/app/components.test.mjs @@ -115,6 +115,16 @@ test('Header renders the brand, server badges, version + update badges', () => { assert.match(html, /New release v9\.9\.9 available/); // update badge (#224) }); +test('Header renders the paused-mining line as a single bad badge', () => { + const text = 'Mining paused here: node out of sync, 8 rigs on backup pool'; + assert.doesNotMatch(renderApp(), /Mining paused here/); + const s = clone(); + s.badges = [{ text, variant: 'bad' }, ...s.badges]; + const html = renderApp({ state: s }); + assert.equal(html.split('Mining paused here').length - 1, 1); + assert.match(html, /class="badge badge-bad"[^>]*>Mining paused here: node out of sync, 8 rigs on backup pool { // It used to render as a sibling of Header, position: fixed over the viewport (overlapping the // chart and the phone hint). It now mounts inside the header's own markup, right of the diff --git a/dashboard/tests/web/views/test_paused_badge.py b/dashboard/tests/web/views/test_paused_badge.py new file mode 100644 index 0000000000..1c82c56d62 --- /dev/null +++ b/dashboard/tests/web/views/test_paused_badge.py @@ -0,0 +1,71 @@ +import pytest + +import mining_dashboard.web.views.paused_badge as paused_badge +from mining_dashboard.web.views.paused_badge import paused_badges + + +@pytest.fixture(autouse=True) +def _local_node(monkeypatch): + monkeypatch.setattr(paused_badge, "monero_is_local", lambda: True) + + +def _rigs(*verdicts): + return {"workers": [{"mining_verdict": v} for v in verdicts]} + + +def test_absent_while_serving(_metrics): + data = {"pool": {"p2p": {"uptime": 50, "out_peers": 3, "in_peers": 1}}} + assert paused_badges(data, _metrics()) == [] + + +def test_node_out_of_sync_counts_rigs_on_backup(_metrics): + data = { + "monero_sync": {"health": {"level": "red"}}, + **_rigs("on_backup", "on_backup", "mining_here", "unknown"), + } + assert paused_badges(data, _metrics()) == [ + {"text": "Mining paused here: node out of sync, 2 rigs on backup pool", "variant": "bad"} + ] + + +def test_remote_node_health_is_not_a_trigger(_metrics, monkeypatch): + monkeypatch.setattr(paused_badge, "monero_is_local", lambda: False) + assert paused_badges({"monero_sync": {"health": {"level": "red"}}}, _metrics()) == [] + + +def test_rigs_clause_omitted_when_zero_and_singular_for_one(_metrics): + data = {"stratum_closed": True, **_rigs("mining_here")} + assert paused_badges(data, _metrics())[0]["text"] == "Mining paused here: stratum closed" + data = {"stratum_closed": True, **_rigs("on_backup")} + assert paused_badges(data, _metrics())[0]["text"].endswith(", 1 rig on backup pool") + + +def test_syncing_triggers(_metrics): + out = paused_badges({}, _metrics(global_syncing=True)) + assert out[0]["text"] == "Mining paused here: node syncing" + + +def test_p2pool_isolated_only_when_running_and_peerless(_metrics): + data = {"pool": {"p2p": {"uptime": 50, "out_peers": 0, "in_peers": 0}}} + assert paused_badges(data, _metrics())[0]["text"] == "Mining paused here: P2Pool isolated" + data = {"pool": {"p2p": {"uptime": 0, "out_peers": 0, "in_peers": 0}}} + assert paused_badges(data, _metrics()) == [] + + +def test_one_line_when_several_conditions_hold(_metrics): + data = {"stratum_closed": True, "pool": {"p2p": {"uptime": 5}}} + assert len(paused_badges(data, _metrics(global_syncing=True))) == 1 + + +def test_rides_build_state_first_in_badges(_data, _state_mgr): + from mining_dashboard.web.views import views + + data = _data() + data["stratum_closed"] = True + badges = views.build_state(data, _state_mgr(), "all")["badges"] + assert badges[0]["text"] == "Mining paused here: stratum closed" + assert sum(b["text"].startswith("Mining paused here") for b in badges) == 1 + assert not any( + b["text"].startswith("Mining paused here") + for b in views.build_state(_data(), _state_mgr(), "all")["badges"] + ) diff --git a/docs/dashboard.md b/docs/dashboard.md index 1b4a76766a..5a8de42960 100644 --- a/docs/dashboard.md +++ b/docs/dashboard.md @@ -132,6 +132,13 @@ reply. An `XMR Pruned` / `XMR Full` badge sits with the other badges beside the the bundled node's blockchain mode. It appears for a local node only — with `monero.mode: remote` the pruning state is unknown, so neither badge is shown. +A red `Mining paused here: ` badge leads the badges whenever this Pithead is not serving +work. The reason is the first that holds of: `stratum closed`, `node out of sync` (the local +Monero health verdict is red), `node syncing`, and `P2Pool isolated` (P2Pool is running with no +peers). When rigs have moved to a backup pool the line ends with `, N rigs on backup pool`, counted +from the workers whose mining verdict is `on_backup`; the clause is omitted at zero. The line +clears on the next poll once the condition ends. + When the dashboard host is a name (not already an IP), the machine's IP shows beside it as `hostname @ ip` (e.g. `pithead.local @ 192.168.1.42`), a way back in when the hostname doesn't resolve from a phone or another LAN machine. From 60799c7973a189dc0c3803e86440a31784943bf9 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:39:22 -0600 Subject: [PATCH 012/112] dashboard: LAN "Monero node offline" banner that needs no Tor (#4079) (#4092) * dashboard: LAN 'Monero node offline' banner that needs no Tor (#4079) Co-Authored-By: Claude Sonnet 5.5 * node alert: scope docs to tor.auto_heal, cover Tor reason end to end (#4079) Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- .../mining_dashboard/service/data_setup.py | 5 +- .../service/health/node_alert.py | 60 +++++++++++++ .../web/static/app/components.mjs | 2 + .../web/static/system/nodealert.mjs | 9 ++ dashboard/mining_dashboard/web/views/views.py | 2 + dashboard/tests/browser/node-alert.test.mjs | 34 ++++++++ dashboard/tests/frontend/fixtures/state.json | 1 + .../tests/frontend/system/nodealert.test.mjs | 24 +++++ .../tests/service/health/test_node_alert.py | 87 +++++++++++++++++++ .../tests/web/views/test_node_alert_view.py | 38 ++++++++ docs/dashboard.md | 10 +++ docs/dev/testing-strategy.md | 2 +- docs/monitoring.md | 12 ++- docs/telegram.md | 10 ++- 14 files changed, 286 insertions(+), 10 deletions(-) create mode 100644 dashboard/mining_dashboard/service/health/node_alert.py create mode 100644 dashboard/mining_dashboard/web/static/system/nodealert.mjs create mode 100644 dashboard/tests/browser/node-alert.test.mjs create mode 100644 dashboard/tests/frontend/system/nodealert.test.mjs create mode 100644 dashboard/tests/service/health/test_node_alert.py create mode 100644 dashboard/tests/web/views/test_node_alert_view.py diff --git a/dashboard/mining_dashboard/service/data_setup.py b/dashboard/mining_dashboard/service/data_setup.py index 1fa36f914f..5ecc8f6113 100644 --- a/dashboard/mining_dashboard/service/data_setup.py +++ b/dashboard/mining_dashboard/service/data_setup.py @@ -24,6 +24,7 @@ ) from mining_dashboard.service.health.degradation import DegradationMonitor from mining_dashboard.service.health.monero_health import MoneroChainHealth +from mining_dashboard.service.health.node_alert import tor_heal_status from mining_dashboard.service.health.node_health import NodeHealthMonitor from mining_dashboard.service.health.tari_health import TariChainHealth from mining_dashboard.service.health.tor_heal import TorEgressHealer @@ -262,10 +263,8 @@ def __init__(self, state_manager, proxy_client, xvb_client): self._restore_sync_gate() def _observe_monero(self, monero_sync): - """Attach the monerod peers-and-tip verdict (#2499) as ``monero_sync["health"]`` for the - card, /api/state, doctor and the alert edges. A remote node gets the "peers not visible" - verdict: its peer set is not ours to judge.""" monero_sync["health"] = self.monero_chain.observe(monero_sync, local=monero_is_local()) + self.latest_data["tor_heal"] = tor_heal_status(self.tor_healer) async def _observe_tari(self, tari_client, tari_sync): """One cycle of Tari health: the debounced node-down flag (#31), returned, and the chain diff --git a/dashboard/mining_dashboard/service/health/node_alert.py b/dashboard/mining_dashboard/service/health/node_alert.py new file mode 100644 index 0000000000..52576ba8af --- /dev/null +++ b/dashboard/mining_dashboard/service/health/node_alert.py @@ -0,0 +1,60 @@ +from mining_dashboard.service.health.tor_heal import BROKEN_AFTER_SEC, COOLDOWN_SEC, MAX_ATTEMPTS + +TITLE = "Monero node offline" +DOCTOR_ADVICE = "Run './pithead doctor' for current evidence." + + +def _minutes(seconds): + return max(int(seconds // 60), 0) + + +def tor_heal_status(healer): + if not healer.enabled: + return {"enabled": False} + now = healer._clock() + failing_since = healer._failing_since + last_attempt = healer._last_attempt + return { + "enabled": True, + "broken_sec": None if failing_since is None else int(now - failing_since), + "attempts": healer._attempts, + "last_action": healer._recovery_step, + "last_action_age_sec": None if last_attempt is None else int(now - last_attempt), + } + + +def _heal_lines(heal): + if not heal.get("enabled"): + return [] + attempts = heal.get("attempts") or 0 + if not attempts: + return ["Tor auto-heal: no action taken yet."] + age = heal.get("last_action_age_sec") + action = heal.get("last_action") or "recovery attempt" + lines = [ + f"Tor auto-heal last action: {action}" + + ("" if age is None else f", {_minutes(age)} min ago") + + f" (attempt {attempts} of {MAX_ATTEMPTS})." + ] + if attempts >= MAX_ATTEMPTS: + lines.append( + f"Tor auto-heal stopped after {MAX_ATTEMPTS} attempts; no more automatic action " + f"this outage. {DOCTOR_ADVICE}" + ) + elif age is not None and age < COOLDOWN_SEC: + lines.append(f"Next action after a {_minutes(COOLDOWN_SEC - age)} min cooldown.") + return lines + + +def build_node_alert(data): + health = (data.get("monero_sync") or {}).get("health") or {} + heal = data.get("tor_heal") or {} + reasons = [] + if health.get("level") == "red": + reasons.extend(health.get("reasons") or []) + broken = heal.get("broken_sec") + if broken is not None and broken >= BROKEN_AFTER_SEC: + reasons.append(f"Tor clearnet egress has failed for {_minutes(broken)} min") + if not reasons: + return None + return {"title": TITLE, "reasons": reasons, "heal": _heal_lines(heal)} diff --git a/dashboard/mining_dashboard/web/static/app/components.mjs b/dashboard/mining_dashboard/web/static/app/components.mjs index 31792a0ce0..793d4e6344 100644 --- a/dashboard/mining_dashboard/web/static/app/components.mjs +++ b/dashboard/mining_dashboard/web/static/app/components.mjs @@ -3,6 +3,7 @@ import { ComponentHealth } from "../network/health.mjs"; import { MineCartTrain } from "../network/minecart.mjs"; import { BackupPanel } from "../system/backupview.mjs"; import { DiagnosticsPanel } from "../system/diagview.mjs"; +import { NodeAlertBanner } from "../system/nodealert.mjs"; import { OsVerdictBanner } from "../system/osupdate.mjs"; import { SecurityPanel } from "../system/securityview.mjs"; import { SyncView } from "../system/syncview.mjs"; @@ -186,6 +187,7 @@ export function App({ return html`<${Fragment}> <${Header} state=${state} theme=${ui.theme} onTheme=${onTheme} />
+ <${NodeAlertBanner} alert=${state.node_alert} /> <${OsVerdictBanner} os=${state.os_update} /> ${!connected ? html`
Disconnected — showing data from ${state.last_update}. Retrying…${recoveryNeeded ? html`<${ConnectionRecovery} />` : null}
` : null} <${MinerConnection} /> diff --git a/dashboard/mining_dashboard/web/static/system/nodealert.mjs b/dashboard/mining_dashboard/web/static/system/nodealert.mjs new file mode 100644 index 0000000000..691ae34349 --- /dev/null +++ b/dashboard/mining_dashboard/web/static/system/nodealert.mjs @@ -0,0 +1,9 @@ +import { html } from "../app/preact.mjs"; + +export const NodeAlertBanner = ({ alert }) => + alert + ? html`` + : null; diff --git a/dashboard/mining_dashboard/web/views/views.py b/dashboard/mining_dashboard/web/views/views.py index 348a272a26..f057a56a7f 100644 --- a/dashboard/mining_dashboard/web/views/views.py +++ b/dashboard/mining_dashboard/web/views/views.py @@ -26,6 +26,7 @@ format_hashrate, format_time_abs, ) +from mining_dashboard.service.health.node_alert import build_node_alert from mining_dashboard.service.health.update_checker import parse_semver from mining_dashboard.service.metrics import build_metrics from mining_dashboard.service.network.egress import egress_posture_from_config @@ -388,6 +389,7 @@ def build_state(data, state_mgr, range_arg, window=None, avg_window=DEFAULT_HASH "xvb_history": build_xvb_history(state_mgr.get_xvb_history(), range_arg, window), "egress": egress, "topology": topology, + "node_alert": build_node_alert(data), "chart": build_chart( history, data.get("shares", []), diff --git a/dashboard/tests/browser/node-alert.test.mjs b/dashboard/tests/browser/node-alert.test.mjs new file mode 100644 index 0000000000..126296d982 --- /dev/null +++ b/dashboard/tests/browser/node-alert.test.mjs @@ -0,0 +1,34 @@ +import { expect, test } from "./fixtures.mjs"; + +const ALERT = { + title: "Monero node offline", + reasons: ["0 outgoing peers for 12 min", "Tor clearnet egress has failed for 20 min"], + heal: [ + "Tor auto-heal last action: Tor restart, 5 min ago (attempt 3 of 3).", + "Tor auto-heal stopped after 3 attempts; no more automatic action this outage.", + ], +}; + +test("the dashboard stays quiet while no node alert is active", async ({ page, ui }) => { + await ui.open(); + await expect(page.getByRole("group", { name: "Dashboard view" })).toBeVisible(); + await expect(page.getByRole("alert").filter({ hasText: "Monero node offline" })).toHaveCount(0); +}); + +for (const theme of ["Light", "Dark"]) { + test(`${theme} theme: the node alert names the outage and the auto-heal state`, async ({ + page, + ui, + }) => { + ui.state.node_alert = ALERT; + await ui.open(); + await page.getByRole("button", { name: theme, exact: true }).click(); + await expect(page.locator("html")).toHaveAttribute("data-theme", theme.toLowerCase()); + const banner = page.getByRole("alert").filter({ hasText: "Monero node offline" }); + await expect(banner).toBeVisible(); + await expect(banner).toContainText("0 outgoing peers for 12 min"); + await expect(banner).toContainText("Tor clearnet egress has failed for 20 min"); + await expect(banner).toContainText("Tor auto-heal last action: Tor restart, 5 min ago"); + await expect(banner).toContainText("Tor auto-heal stopped after 3 attempts"); + }); +} diff --git a/dashboard/tests/frontend/fixtures/state.json b/dashboard/tests/frontend/fixtures/state.json index 7deed6f81b..3281fce4ea 100644 --- a/dashboard/tests/frontend/fixtures/state.json +++ b/dashboard/tests/frontend/fixtures/state.json @@ -323,6 +323,7 @@ "reward": "0.0000 XMR", "ts": "Never" }, + "node_alert": null, "os_update": null, "page_title": "Pithead Dashboard", "payouts": { diff --git a/dashboard/tests/frontend/system/nodealert.test.mjs b/dashboard/tests/frontend/system/nodealert.test.mjs new file mode 100644 index 0000000000..31274df6b0 --- /dev/null +++ b/dashboard/tests/frontend/system/nodealert.test.mjs @@ -0,0 +1,24 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { clone, renderApp } from "../harness.mjs"; + +const ALERT = { + title: "Monero node offline", + reasons: ["0 outgoing peers for 12 min"], + heal: ["Tor auto-heal stopped after 3 attempts; no more automatic action this outage."], +}; + +test("no node alert renders no banner", () => { + assert.equal(renderApp({ state: clone() }).includes('id="node-alert"'), false); +}); + +test("a node alert names the outage, its reasons and the auto-heal state", () => { + const state = clone(); + state.node_alert = ALERT; + const html = renderApp({ state }); + assert.match(html, /id="node-alert"/); + assert.match(html, /Monero node offline/); + assert.match(html, /0 outgoing peers for 12 min/); + assert.match(html, /Tor auto-heal stopped after 3 attempts/); +}); diff --git a/dashboard/tests/service/health/test_node_alert.py b/dashboard/tests/service/health/test_node_alert.py new file mode 100644 index 0000000000..d8b642101b --- /dev/null +++ b/dashboard/tests/service/health/test_node_alert.py @@ -0,0 +1,87 @@ +from mining_dashboard.service.health.node_alert import ( + TITLE, + build_node_alert, + tor_heal_status, +) +from mining_dashboard.service.health.tor_heal import ( + BROKEN_AFTER_SEC, + COOLDOWN_SEC, + MAX_ATTEMPTS, + TorEgressHealer, +) + +RED = {"level": "red", "reasons": ["0 outgoing peers for 12 min"]} + + +class _Clock: + t = 1000.0 + + def __call__(self): + return self.t + + +def _healer(enabled=True): + clock = _Clock() + return TorEgressHealer(None, enabled=enabled, clock=clock, restart_monerod=False), clock + + +def _data(health=None, heal=None): + return {"monero_sync": {"health": health or {"level": "green"}}, "tor_heal": heal or {}} + + +def test_disabled_healer_reports_only_that(): + healer, _ = _healer(enabled=False) + assert tor_heal_status(healer) == {"enabled": False} + + +def test_green_monero_and_healthy_tor_raise_nothing(): + assert build_node_alert(_data()) is None + assert build_node_alert({}) is None + + +def test_red_monero_verdict_names_the_node_offline_with_its_reasons(): + alert = build_node_alert(_data(RED)) + assert alert["title"] == TITLE == "Monero node offline" + assert alert["reasons"] == RED["reasons"] + assert alert["heal"] == [] + + +def test_enabled_heal_with_no_action_says_so(): + healer, _ = _healer() + alert = build_node_alert(_data(RED, tor_heal_status(healer))) + assert alert["heal"] == ["Tor auto-heal: no action taken yet."] + + +def test_short_egress_failure_is_not_yet_an_alert(): + healer, clock = _healer() + healer.decide(False, clock.t) + clock.t += BROKEN_AFTER_SEC - 1 + healer.decide(False, clock.t) + assert build_node_alert(_data(heal=tor_heal_status(healer))) is None + + +def test_egress_failure_past_the_broken_window_alerts_without_a_monero_verdict(): + healer, clock = _healer() + healer.decide(False, clock.t) + clock.t += BROKEN_AFTER_SEC + assert healer.decide(False, clock.t) == "heal" + healer._recovery_step = "NEWNYM" + clock.t += 60 + alert = build_node_alert(_data(heal=tor_heal_status(healer))) + assert alert["reasons"] == ["Tor clearnet egress has failed for 16 min"] + assert alert["heal"] == [ + f"Tor auto-heal last action: NEWNYM, 1 min ago (attempt 1 of {MAX_ATTEMPTS}).", + f"Next action after a {COOLDOWN_SEC // 60 - 1} min cooldown.", + ] + + +def test_spent_attempt_cap_says_it_stopped(): + healer, clock = _healer() + healer.decide(False, clock.t) + for _ in range(MAX_ATTEMPTS): + clock.t += BROKEN_AFTER_SEC if healer._attempts == 0 else COOLDOWN_SEC + assert healer.decide(False, clock.t) == "heal" + alert = build_node_alert(_data(RED, tor_heal_status(healer))) + assert alert["heal"][0].startswith("Tor auto-heal last action: recovery attempt") + assert alert["heal"][1].startswith(f"Tor auto-heal stopped after {MAX_ATTEMPTS} attempts") + assert "./pithead doctor" in alert["heal"][1] diff --git a/dashboard/tests/web/views/test_node_alert_view.py b/dashboard/tests/web/views/test_node_alert_view.py new file mode 100644 index 0000000000..daa5a0744a --- /dev/null +++ b/dashboard/tests/web/views/test_node_alert_view.py @@ -0,0 +1,38 @@ +from types import SimpleNamespace + +from mining_dashboard.service.data_setup import DataSetupMixin +from mining_dashboard.service.health.monero_health import MoneroChainHealth +from mining_dashboard.web.views.views import build_state + + +def test_build_state_carries_the_node_alert_from_the_health_verdicts(_data, _state_mgr): + assert build_state(_data(), _state_mgr(), "all")["node_alert"] is None + data = _data() + data["monero_sync"] = {"health": {"level": "red", "reasons": ["0 outgoing peers"]}} + data["tor_heal"] = {"enabled": True, "attempts": 0} + alert = build_state(data, _state_mgr(), "all")["node_alert"] + assert alert["title"] == "Monero node offline" + assert alert["reasons"] == ["0 outgoing peers"] + assert alert["heal"] == ["Tor auto-heal: no action taken yet."] + + +def test_each_poll_publishes_the_tor_heal_state_beside_the_monero_verdict(): + healer = SimpleNamespace(enabled=False) + node = SimpleNamespace(monero_chain=MoneroChainHealth(), tor_healer=healer, latest_data={}) + DataSetupMixin._observe_monero(node, {"reachable": False}) + assert node.latest_data["tor_heal"] == {"enabled": False} + + +def test_build_state_reports_a_tor_outage_and_the_spent_attempt_cap(_data, _state_mgr): + data = _data() + data["tor_heal"] = { + "enabled": True, + "broken_sec": 3600, + "attempts": 3, + "last_action": "Tor restart", + "last_action_age_sec": 300, + } + alert = build_state(data, _state_mgr(), "all")["node_alert"] + assert alert["reasons"] == ["Tor clearnet egress has failed for 60 min"] + assert alert["heal"][0] == "Tor auto-heal last action: Tor restart, 5 min ago (attempt 3 of 3)." + assert alert["heal"][1].startswith("Tor auto-heal stopped after 3 attempts") diff --git a/docs/dashboard.md b/docs/dashboard.md index 5a8de42960..1eeaa1cf01 100644 --- a/docs/dashboard.md +++ b/docs/dashboard.md @@ -181,6 +181,16 @@ on; the wallet badge pairs with the `wallet_changed` alert; AVX2 is badge-only ( [Telegram Bot](telegram.md#choosing-which-alerts-you-get)). All active warning badges are echoed in the bot's `/status` reply. +### Monero node offline banner + +When monerod is red (no outgoing peers, or a height that has stopped moving) or, with `tor.auto_heal` +on, Tor clearnet egress has failed past the auto-heal's 15-minute broken window, a red banner above the dashboard reads +**Monero node offline** and lists the reasons. With auto-heal on it also adds the heal state: the +last action and its age, the cooldown before the next one, and, once the three attempts of an outage +are spent, a line saying the auto-heal has stopped and to run `./pithead doctor`. The banner is +computed from the dashboard's existing health verdicts and served over the LAN, so it needs no Tor +and no Telegram, the two paths that fail together in a Tor outage. It clears when the verdicts do. + ### Hero band A strip of headline KPIs sits below the top bar: diff --git a/docs/dev/testing-strategy.md b/docs/dev/testing-strategy.md index be18c8da4b..8ce9579a3f 100644 --- a/docs/dev/testing-strategy.md +++ b/docs/dev/testing-strategy.md @@ -232,7 +232,7 @@ The deploy-time axes — each changes a real runtime path. Full table and assert | Configured Tari RPC unreachable for 15 minutes, including after dashboard restart → rejects when required; optional Tari keeps mining Monero; alerts either way | `tari_down` | 1 ✅ · 3 ▶ | | Recovery hysteresis — readmit only after every required node stable `NODE_RECOVERY_AFTER_SEC` | reachable again | 1 ✅ | | Transient blip / never-reachable Monero → **no** false reject | debounce / `ever_up` | 1 ✅ | -| Monero node **isolated or not advancing** — the "at tip, with peers" contract for monerod (#2499): the real peer counts (the published RPC is restricted and answers 0, so an in-container helper reads the loopback-only admin RPC, #2921), `MoneroChainHealth` (0 outgoing peers `NODE_STALE_AFTER_SEC`, no new height 30 min), the card's Node Health / Peers / Height Moved, `node_down`-toggle alerts for each condition, `build/monero/healthcheck.sh` failing past `MONERO_HEALTH_PEERLESS_SEC`, doctor peers/tip age + FAIL, a `monero chain` status line, and the tier-4 strand leg (`run.sh --monero-stranded`) | red on both conditions with the numbers; remote node: no verdict | 1 ✅ (`test_monero_health.py`, `test_alert_service_monero_health.py`, `test_monero_client.py`, `monero-health-card.test.mjs`; healthcheck/doctor/status: `tests/stack/test-monero-chain.sh` covers restricted vs real zero vs no reading in the healthcheck, helper and doctor; `standalone/test_tor_recovery_info.sh` in tor-recover; `test_containers.py` the fresh/stale/malformed observation; `selftest-monero-peer-wait.sh` the peer predicates, the peer-wait capture and the RPC-boundary rows; `selftest-monero-p2p.sh` the bounded P2P advertisement decoder and non-secret failure diagnostics) · 4 ▶ (`run.sh --monero-stranded`, which checks the actual P2P advertisement, RPC boundary, current-run observation after deployment and restart, and the live tor-recover peer provider; bench-ci phase `monero-stranded`, about an hour, opt-in; KVM `provision` also runs the native Quadlet cold-start/restart RPC fixture) | +| Monero node **isolated or not advancing** — the "at tip, with peers" contract for monerod (#2499): the real peer counts (the published RPC is restricted and answers 0, so an in-container helper reads the loopback-only admin RPC, #2921), `MoneroChainHealth` (0 outgoing peers `NODE_STALE_AFTER_SEC`, no new height 30 min), the card's Node Health / Peers / Height Moved, `node_down`-toggle alerts for each condition, `build/monero/healthcheck.sh` failing past `MONERO_HEALTH_PEERLESS_SEC`, doctor peers/tip age + FAIL, a `monero chain` status line, and the tier-4 strand leg (`run.sh --monero-stranded`) | red on both conditions with the numbers; remote node: no verdict | 1 ✅ (`test_monero_health.py`, `test_alert_service_monero_health.py`, `test_monero_client.py`, `monero-health-card.test.mjs`; the LAN "Monero node offline" banner built from these verdicts and the Tor heal state: `test_node_alert.py`, `test_node_alert_view.py`, `nodealert.test.mjs`, and `tests/browser/node-alert.test.mjs` in both themes; healthcheck/doctor/status: `tests/stack/test-monero-chain.sh` covers restricted vs real zero vs no reading in the healthcheck, helper and doctor; `standalone/test_tor_recovery_info.sh` in tor-recover; `test_containers.py` the fresh/stale/malformed observation; `selftest-monero-peer-wait.sh` the peer predicates, the peer-wait capture and the RPC-boundary rows; `selftest-monero-p2p.sh` the bounded P2P advertisement decoder and non-secret failure diagnostics) · 4 ▶ (`run.sh --monero-stranded`, which checks the actual P2P advertisement, RPC boundary, current-run observation after deployment and restart, and the live tor-recover peer provider; bench-ci phase `monero-stranded`, about an hour, opt-in; KVM `provision` also runs the native Quadlet cold-start/restart RPC fixture) | | Monero node reachable but **out of sync** — the post-tor-restart 0-peer strand (#972): raw `synchronized` passthrough, debounced stale flag, alert via the `node_down` toggle, monerod restarted alongside an actual tor container restart (compose `depends_on: restart` + the final #424 auto-heal step), `restart monerod` leg, doctor WARN | `synchronized: false` ≥ `NODE_STALE_AFTER_SEC` after being in sync once | 1 ✅ (client/data_service/alert/tor_heal pytest, `tests/stack` doctor + restart + compose invariants) · 2 ✅ (flag over the wire) · 4 (real strand + re-peer needs the bench) | | Double outage; readmit only after both required nodes recover | both down → both up | 1 ✅ (added) · 3 ▶ | | #35 latch × #31 failover coexist after release | down post-release | 1 ✅ (added) · 3 ▶ | diff --git a/docs/monitoring.md b/docs/monitoring.md index 6d9bcd904a..8439525866 100644 --- a/docs/monitoring.md +++ b/docs/monitoring.md @@ -93,6 +93,11 @@ the whole host) and, once the period + grace elapses, Healthchecks.io alerts you endpoint only ever sees a Tor exit, not your host IP — it's never a clearnet beacon. This means your ping URL must be reachable over Tor (hosted `hc-ping.com` is; a self-hosted instance must be public or an onion service — a LAN-only address won't work). See the [Privacy note](#privacy-note). + Because the ping needs Tor, a Tor outage stops it and trips the check: the alert is evaluated on + Healthchecks.io's servers, so it reaches you even though the stack's own Telegram alerts, which + also travel over Tor, cannot leave the box. Healthchecks.io going quiet is the backstop for that + outage. For the detail the silence cannot give, open the dashboard over the LAN: it shows + **Monero node offline** with the auto-heal state, and needs no Tor. - **Fails quietly, rejects loudly.** A ping that can't get out — you're offline, or Tor is momentarily down — is logged at debug level only; Healthchecks.io alerts on the missed ping regardless, which is the point. A ping the endpoint *answers* with a non-2xx status is different: @@ -142,9 +147,10 @@ so the endpoint sees a **Tor exit**, not your host's IP, and the DNS lookup goes Two things to know: - **Tor is part of the ping path.** If the Tor container is down while the host is up, the ping - can't get out and the check will eventually alert — a *false* "host down". The 5-minute grace - absorbs brief Tor blips, and pings retry every cycle, so only a sustained Tor outage trips it. - That's usually what you want (Tor down *is* a problem worth knowing about). One such outage is + can't get out and the check will eventually alert, reading as "host down" while the host is up. + The 5-minute grace absorbs brief Tor blips, and pings retry every cycle, so only a sustained Tor + outage trips it. That's usually what you want (Tor down *is* a problem worth knowing about, and + it silences the [Telegram alerts](telegram.md#privacy-and-secrets) too). One such outage is Tor stuck on a **failing guard** — bootstrapped, mining fine, but clearnet exits dead (#424): `./pithead doctor` diagnoses it. `tor.auto_heal: true` tries bounded circuit refresh before one possible Tor restart; `./pithead restart tor` is the manual restart. See diff --git a/docs/telegram.md b/docs/telegram.md index 54850aa871..94be295d1a 100644 --- a/docs/telegram.md +++ b/docs/telegram.md @@ -252,8 +252,8 @@ reply, so the bot can't be used by anyone you haven't put in that chat. The bot Telegram (`getUpdates`) rather than exposing a webhook, so it needs **no inbound port** and rides the same outbound path as the alerts — nothing about your host is exposed to receive commands. -> **Tor-only host.** Like alerts, commands reach `api.telegram.org` over clearnet. With no clearnet -> egress the poll just fails silently and the bot answers nothing — see +> **Tor-dependent.** Like alerts, commands reach `api.telegram.org` through Tor. While Tor is down +> the poll just fails silently and the bot answers nothing — see > [Privacy and secrets](#privacy-and-secrets). --- @@ -387,7 +387,11 @@ it; that sends directly, and the LAN server seeing your host IP is expected on y same routing as the Healthchecks.io pinger and the XvB fetch. Telegram sees a **Tor exit, not your host IP**, so enabling the bot doesn't expose where your stack runs. If Tor is momentarily down (or Telegram is blocking that exit), sends and polls **fail silently** — no errors, no log spam, the - rest of the stack is unaffected — and resume on their own. + rest of the stack is unaffected — and resume on their own. So a Tor outage, the very failure that + can leave a Monero node offline, also silences every Telegram alert about it. Two surfaces do not + depend on Telegram: the Healthchecks.io dead-man's switch, which alerts when the pings stop (see + [Monitoring](monitoring.md#how-it-works)), and the dashboard's + **Monero node offline** banner, served over the LAN. --- From 5230d9d022c46ab145dfc1895b39fc830e7e9682 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:50:50 -0600 Subject: [PATCH 013/112] Tor render: raise MaxClientCircuitsPending, lower monero out-peers default (#4078) (#4088) * Tor render: MaxClientCircuitsPending 64 and monero out-peers default 24 (#4078) Co-Authored-By: Claude Sonnet 5.5 * Follow the out_peers default in the allowlist round trip and OS fallback (#4078) Co-Authored-By: Claude Sonnet 5.5 * Correct the out_peers headroom arithmetic, drop explanatory comments, add changelog (#4078) Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- CHANGELOG.md | 4 ++++ build/monero/bitmonero.conf.template | 7 ------- build/monero/entrypoint.sh | 18 ------------------ build/tor/torrc.template | 2 ++ config.reference.json | 2 +- docker-compose.yml | 2 +- docs/configuration.md | 2 +- docs/privacy.md | 2 +- lib/pithead/33-render-env.sh | 7 +------ tests/os/provision-browser-submit.sh | 2 +- .../control/test-control-editable-allowlist.sh | 2 +- tests/stack/test-monero-tari.sh | 6 ++---- tests/stack/test-tor-network.sh | 2 +- 13 files changed, 16 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d86007ad8..0c9910098d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,10 @@ per the process in [`docs/dev/releasing.md`](docs/dev/releasing.md). ### Fixed +- Tor's `MaxClientCircuitsPending` is raised to 64 and `monero.out_peers` now defaults to 24 (was 48), + so monerod, Tari and P2Pool onion dials no longer sit at Tor's pending-circuit ceiling right after + boot. A `config.json` without `monero.out_peers` re-renders at 24 on the next apply; an explicit value + is kept (#4078). - On the appliance, the dashboard's own schema migrations no longer run before the booted A/B slot commits. `pithead-boot` defers them while the slot is uncommitted, so an update that falls back leaves the previous release on the schema it understands, still recording payouts (#3998). diff --git a/build/monero/bitmonero.conf.template b/build/monero/bitmonero.conf.template index 47825e0f2f..75f9c779c9 100644 --- a/build/monero/bitmonero.conf.template +++ b/build/monero/bitmonero.conf.template @@ -35,13 +35,6 @@ public-node=1 # ZeroMQ publisher for block notifications (Required for P2Pool) zmq-pub=tcp://0.0.0.0:18083 -# Peer Management. P2Pool v4.18 recommends out-peers=32 / in-peers=64 for a clearnet node, where -# in-peers=64 is the one that matters: it caps INBOUND connections so they can't grow past ~1000 and -# hit Linux's open-files limit — we honor it exactly. out-peers defaults to 48 (monero.out_peers) -# because each peer is roughly one bandwidth-capped Tor circuit, so more peers = more aggregate -# download bandwidth during a Tor initial sync. It is also the biggest steady-state lever on Tor's -# CPU (#595): once synced, dropping to 32 cuts monerod's circuit count by a third. The optional -# clearnet initial sync (#183) overrides to the recommended 32 + adds P2Pool's priority nodes. out-peers=${MONERO_OUT_PEERS} in-peers=64 diff --git a/build/monero/entrypoint.sh b/build/monero/entrypoint.sh index 3d56ee0fb8..7260ad0091 100644 --- a/build/monero/entrypoint.sh +++ b/build/monero/entrypoint.sh @@ -9,24 +9,6 @@ CONFIG_PATH="${CONFIG_PATH:-/home/ubuntu/.bitmonero/bitmonero.conf}" # sync already completed — come up on Tor." Default matches the compose mount; overridable for tests. CLEARNET_MARKER="${CLEARNET_MARKER:-/clearnet-state/monero.synced}" -# Optional clearnet initial sync (#183). DEFAULT OFF. For the fast clearnet sync window only, this -# makes monerod match the connectivity P2Pool v4.18 recommends for a clearnet node: -# - strip the single `proxy=` line that forces ALL P2P over Tor → monerod dials its compiled-in -# clearnet seed nodes (and the priority nodes below) directly, at clearnet speed instead of -# crawling over bandwidth-capped Tor circuits. -# - out-peers → 32 (P2Pool v4.18's clearnet recommendation; the Tor render uses 48, a circuit- -# bandwidth workaround). in-peers stays 64 — the open-files cap, which is the rec we always honor. -# - add P2Pool's recommended priority nodes for guaranteed-good peers + block templates. These are -# CLEARNET hostnames, so they're added ONLY here: in Tor mode their resolution would leak a -# clearnet DNS lookup tied to this host's IP (#161). Connections still arrive over clearnet, -# which is exactly the exposure this opt-in window already accepts. -# `tx-proxy=tor,...` is LEFT IN PLACE so transaction broadcast stays on Tor (tx-origin privacy -# preserved) — and there's no tx broadcast during a sync anyway. The DNS blocklist / DNS -# checkpointing the rec also lists are MINING-time protections (bad-node bans, selfish-mining -# defense) that don't apply to a download-only sync; in Tor mining mode they'd leak DNS (#161), so -# we keep them off and rely on monerod's compiled-in checkpoints. The Tor render (the untouched -# template) restores every private default the moment the dashboard flips back. -# Kept as a function (portable sed, no in-place -e) so the shell test suite can exercise it directly. apply_clearnet_initial_sync() { local cfg="$1" tmp="$1.tmp" sed -e '/^proxy=/d' -e 's/^out-peers=.*/out-peers=32/' "$cfg" >"$tmp" && mv "$tmp" "$cfg" diff --git a/build/tor/torrc.template b/build/tor/torrc.template index 626faba36c..3133cc1409 100644 --- a/build/tor/torrc.template +++ b/build/tor/torrc.template @@ -37,6 +37,8 @@ CookieAuthFile /var/lib/tor/control_auth_cookie CookieAuthFileGroupReadable 1 DataDirectoryGroupReadable 1 +MaxClientCircuitsPending 64 + # --- Logging --- # Output logs to stdout for integration with Docker logging drivers Log notice stdout diff --git a/config.reference.json b/config.reference.json index eb039cebb7..93c7fbb6aa 100644 --- a/config.reference.json +++ b/config.reference.json @@ -37,7 +37,7 @@ "zmq_port": 18083 }, "prep_blocks_threads": "auto", - "out_peers": 48, + "out_peers": 24, "data_dir": "auto", "mem_limit": "auto" }, diff --git a/docker-compose.yml b/docker-compose.yml index 6f63e4dae8..2320e945c0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -102,7 +102,7 @@ services: - MONERO_CLEARNET_SYNC=${MONERO_CLEARNET_SYNC:-false} - MONERO_PREP_THREADS=${MONERO_PREP_THREADS} # Outbound peer target (#595): ~1 Tor circuit per peer; the steady-state Tor-CPU lever. - - MONERO_OUT_PEERS=${MONERO_OUT_PEERS:-48} + - MONERO_OUT_PEERS=${MONERO_OUT_PEERS:-24} # Subnet prefix (#180): the entrypoint envsubst's it into the Tor SOCKS IP in bitmonero.conf. - NETWORK_PREFIX=${NETWORK_PREFIX:-172.28.0} # The published binds, for the entrypoint's LAN-only gate (#2749), with ./data/lan-guard below. diff --git a/docs/configuration.md b/docs/configuration.md index 632a9b45c9..1753fdc244 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -276,7 +276,7 @@ the desired value is not presented as proof of what the still-running services u | `dashboard.hashrate_drop_minutes` | `10` | How many minutes the hashrate must stay below the threshold before the drop is reported — the debounce that keeps a brief blip from pinging you. | | **Advanced** | | _Tune storage, memory, networking, Tor, and update behavior._ | | `monero.prep_blocks_threads` | `auto` | Block-verification threads during sync. `auto` = host cores − 2, clamped to 4–8. | -| `monero.out_peers` | `48` | monerod's outbound peer target (8–1024). Over Tor each outbound peer is roughly one long-lived circuit, so this is the main steady-state lever on Tor's CPU (#595). Keep the default while syncing (more peers = more download bandwidth over Tor); once synced, `32` — the count P2Pool recommends for clearnet — cuts monerod's circuit maintenance by a third. | +| `monero.out_peers` | `24` | monerod's outbound peer target (8–1024). Over Tor each outbound peer is roughly one long-lived circuit, so this is the main steady-state lever on Tor's CPU (#595). The default is sized against the Tor container's `MaxClientCircuitsPending 64` (#4078): 24 monerod dials plus Tari and P2Pool onion dials (budgeted at about 20) leave about 20 pending circuits of headroom at boot, where the former 48 plus those dials needed about 68 against Tor's default of 32. The headroom is gone at 44; an existing `config.json` that sets `48` keeps it and no longer has any, so lower it to 24. The clearnet initial sync (#183) uses 32. | | `monero.data_dir` | `auto` | Where the Monero blockchain lives on the host. `auto` = `./data/monero`. Point this at an existing `.bitmonero` directory to reuse a synced node. See [Reusing an existing node](#reusing-an-existing-node). | | `monero.mem_limit` | `auto` | Upper limit on the monerod container's memory, so a leak/runaway OOM-restarts monerod alone instead of the host's OOM-killer picking a victim. `auto` is a generous ceiling (6 GB) that won't trip during normal operation or initial sync. monerod's OOM-triggering memory is small (~0.1 GiB at rest, ~1–3 GiB during sync) while its multi-GB blockchain DB is reclaimable, memory-mapped page cache that the kernel evicts under pressure rather than OOM-killing. Lower it only to free RAM. Raise it for a full (unpruned) node doing a heavy initial sync on a fast disk, or if a low-RAM host ever OOMs monerod during IBD (it restarts and resumes; the on-disk chain is transactional, no data loss). Accepts any Docker memory value, e.g. `"8g"`. (Tari has its own `tari.mem_limit`; the dashboard, P2Pool, Tor, and the proxies carry fixed ceilings in `docker-compose.yml`. P2Pool's is 4 GB, so it can hold its RandomX dataset when the HugePages reservation is short.) | | `tari.data_dir` | `auto` | Where the Tari node data lives on the host. `auto` = `./data/tari`. Unused with `tari.mode: remote` or `off` — no local node runs, and `setup`/`doctor` drop Tari's 200 GiB from this host's disk budget. Switching to `off` does not delete it, so switching back resumes from the chain already there. See [Hardware › Running a node elsewhere](hardware.md#running-a-node-elsewhere). | diff --git a/docs/privacy.md b/docs/privacy.md index 7d30200cd9..f9f38fcaa5 100644 --- a/docs/privacy.md +++ b/docs/privacy.md @@ -350,7 +350,7 @@ switch, or the exposure banner keeps warning about a sync that isn't happening. | | Tor-only (default) | Clearnet initial sync (opt-in) | |---|---|---| -| **Monero** P2P | over Tor (`proxy=172.28.0.25:9050`) | **direct to clearnet seed nodes** (proxy line dropped), `out-peers` 48 → **32** + P2Pool v4.18's recommended **priority nodes** (`p2pmd.xmrvsbeast.com`, `nodes.hashvault.pro`) for fast, reliable sync | +| **Monero** P2P | over Tor (`proxy=172.28.0.25:9050`) | **direct to clearnet seed nodes** (proxy line dropped), `out-peers` 24 → **32** + P2Pool v4.18's recommended **priority nodes** (`p2pmd.xmrvsbeast.com`, `nodes.hashvault.pro`) for fast, reliable sync | | **Monero** tx broadcast | over Tor (`tx-proxy=`) | **still over Tor** — unchanged | | **Tari** transport | Tor SOCKS (`type = "socks5"`) | **TCP** (`type = "tcp"`) | | **Tari** seeds | onion `peer_seeds`, `dns_seeds = []` | **`dns_seeds = ["seeds.tari.com"]`** (onion seeds are unreachable without Tor), onion `public_addresses` dropped | diff --git a/lib/pithead/33-render-env.sh b/lib/pithead/33-render-env.sh index 6394fa72e8..f272c9b576 100644 --- a/lib/pithead/33-render-env.sh +++ b/lib/pithead/33-render-env.sh @@ -81,13 +81,8 @@ render_env() { [ "$prep_threads" -gt 8 ] && prep_threads=8 fi - # Outbound peer target (#595): over Tor, each outbound peer is roughly one long-lived circuit, - # so out-peers is the biggest steady-state knob on Tor's CPU (circuit maintenance + rebuild). - # The default STAYS 48 — more peers means more aggregate bandwidth during a Tor initial sync, - # and a new operator's first run is exactly that. Once synced, 32 (P2Pool's clearnet - # recommendation) cuts monerod's circuit count by a third with no mining impact. local out_peers - out_peers=$(jq -r '.monero.out_peers // 48' "$CONFIG_FILE") + out_peers=$(jq -r '.monero.out_peers // 24' "$CONFIG_FILE") if ! [[ "$out_peers" =~ ^[0-9]+$ ]] || [ "$out_peers" -lt 8 ] || [ "$out_peers" -gt 1024 ]; then error "monero.out_peers must be an integer between 8 and 1024 (got \"$out_peers\")." fi diff --git a/tests/os/provision-browser-submit.sh b/tests/os/provision-browser-submit.sh index 95807f449a..a9b30d6335 100644 --- a/tests/os/provision-browser-submit.sh +++ b/tests/os/provision-browser-submit.sh @@ -194,7 +194,7 @@ phase_provision_control_regressions() { # # No re-read and no emptiness guard: reaching this line means the row above parsed $live as # JSON carrying 0.17, so it cannot be empty here. The `case` below is the real guard on the # value, and it reports rather than returning silently. - old=$(printf '%s' "$live" | jq -r '.monero.out_peers // 48') + old=$(printf '%s' "$live" | jq -r '.monero.out_peers // 24') case "$old" in *[!0-9]* | "" | ?????*) bad "post-provision approved setting returned an unsafe current value" return diff --git a/tests/stack/control/test-control-editable-allowlist.sh b/tests/stack/control/test-control-editable-allowlist.sh index ec4da65599..de289731d7 100644 --- a/tests/stack/control/test-control-editable-allowlist.sh +++ b/tests/stack/control/test-control-editable-allowlist.sh @@ -99,7 +99,7 @@ roundtrip_confirm "MONERO_CLEARNET_SYNC" '.monero.clearnet_initial_sync=true' '. assert_eq "firewall on: MONERO_CLEARNET_SYNC remains selected" "$(env_now MONERO_CLEARNET_SYNC)" "true" assert_eq "firewall on: TARI_CLEARNET_SYNC remains selected" "$(env_now TARI_CLEARNET_SYNC)" "true" roundtrip_confirm "TARI_DATA_DIR" '.tari.data_dir="'"$C"'/data/tari2"' '.tari.data_dir' "$C/data/tari2" -roundtrip_confirm "MONERO_OUT_PEERS" '.monero.out_peers=24' '.monero.out_peers' "24" +roundtrip_confirm "MONERO_OUT_PEERS" '.monero.out_peers=32' '.monero.out_peers' "32" roundtrip_confirm "MONERO_DATA_DIR" '.monero.data_dir="'"$C"'/data/monero2"' '.monero.data_dir' "$C/data/monero2" roundtrip_confirm "P2POOL_DATA_DIR" '.p2pool.data_dir="'"$C"'/data/p2pool2"' '.p2pool.data_dir' "$C/data/p2pool2" roundtrip_confirm "TOR_DATA_DIR" '.tor.data_dir="'"$C"'/data/tor2"' '.tor.data_dir' "$C/data/tor2" diff --git a/tests/stack/test-monero-tari.sh b/tests/stack/test-monero-tari.sh index 7ba31a05ed..4faeea81e0 100644 --- a/tests/stack/test-monero-tari.sh +++ b/tests/stack/test-monero-tari.sh @@ -495,10 +495,8 @@ assert_eq "grpc_lan_access true binds tari gRPC to all interfaces" "$(run_source assert_eq "prep_blocks_threads override reflected verbatim" "$(run_sourced "$V" env_get_file "$V/.env" MONERO_PREP_THREADS)" "6" echo "== black-box: monero.out_peers renders to .env, bounds enforced (#595) ==" -# Default 48 when unset (the Tor-IBD bandwidth default); an explicit value lands verbatim in -# MONERO_OUT_PEERS (each outbound peer ≈ one Tor circuit — the steady-state Tor CPU lever); -# out-of-range or non-integer values are refused before anything is written. -assert_eq "out_peers default renders 48" "$(run_sourced "$V" env_get_file "$V/.env" MONERO_OUT_PEERS)" "48" +assert_eq "out_peers default renders 24 (#4078)" "$(run_sourced "$V" env_get_file "$V/.env" MONERO_OUT_PEERS)" "24" +assert_eq "reference config out_peers is 24 (#4078)" "$(jq -r '.monero.out_peers' "$ROOT/config.reference.json")" "24" seed_env printf '{ "monero": {"mode":"local","wallet_address":"%s","node_username":"u","node_password":"p","out_peers":32}, "tari":{"wallet_address":"'"$VALID_TARI"'"}, "p2pool":{"pool":"main"}, "dashboard":{"secure":true,"host":"box.lan"} }\n' "$WALLET" >"$V/config.json" out="$(cd "$V" && PATH="$V/bin:$PATH" ./pithead apply -y 2>&1)" diff --git a/tests/stack/test-tor-network.sh b/tests/stack/test-tor-network.sh index b701c9f6e5..9e683f7503 100644 --- a/tests/stack/test-tor-network.sh +++ b/tests/stack/test-tor-network.sh @@ -446,7 +446,6 @@ assert_contains "monero clearnet: xmrvsbeast priority node (v4.18)" "$(cat "$MON assert_contains "monero clearnet: hashvault priority node (v4.18)" "$(cat "$MONT")" "add-priority-node=nodes.hashvault.pro:18080" # The committed template (the Tor-only default) keeps the proxy line + the Tor-tuned out-peers. assert_contains "monero default: Tor P2P proxy present (#183)" "$(cat "$ROOT/build/monero/bitmonero.conf.template")" 'proxy=${NETWORK_PREFIX}.25:9050' -# #595: the template's out-peers is now config-driven (monero.out_peers, default 48 in the render). assert_contains "monero default: out-peers config-driven for Tor (#183/#595)" "$(cat "$ROOT/build/monero/bitmonero.conf.template")" 'out-peers=${MONERO_OUT_PEERS}' # Compose wires both flags into container env: monerod reads MONERO_CLEARNET_SYNC in its entrypoint; # TARI_CLEARNET_SYNC is inert in the container but its presence makes a flag change recreate tari so @@ -649,6 +648,7 @@ assert_eq "tor entrypoint keeps /tmp/torrc as its container default (#1104)" \ assert_eq "tor entrypoint writes NO bare /tmp/torrc outside that default (#1104)" \ "$(grep -vE '^\s*#' "$TOR_ENTRY" | grep -cF '/tmp/torrc')" "1" tor_onion_on="$(tor_torrc true)" +assert_contains "torrc raises MaxClientCircuitsPending to 64 (#4078)" "$tor_onion_on" "MaxClientCircuitsPending 64" assert_contains "tor entrypoint: dashboard HiddenService appended when enabled (#343)" \ "$tor_onion_on" "HiddenServiceDir /var/lib/tor/dashboard/" assert_contains "tor entrypoint: onion vhost targets the bridge gateway .1 (#343)" \ From cddb359a681fb81621c238ae46192124d7651270 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:13:13 -0600 Subject: [PATCH 014/112] =?UTF-8?q?appliance:=20fix=20#4036,=20#4037=20and?= =?UTF-8?q?=20start=20#4038=20=E2=80=94=20download=20a=20redacted=20suppor?= =?UTF-8?q?t=20bundle=20from=20anywhere=20(#4053)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * wip: support-bundle control kind and recovery-bundle host verb Co-Authored-By: Claude Code * dashboard: support-bundle submit and download routes with a Backup-tab action Co-Authored-By: Claude Code * #4037: record every failed Healthchecks ping in a ring table and show them on the health page Co-Authored-By: Claude Code * tests/stack: support-bundle control verb domain — secrets absent, host clamp, cap refusal, journal-only recovery-bundle Co-Authored-By: Claude Code * review: drop added comments and docstrings; clear ruff/biome/shfmt Remove every comment and docstring this head added, keeping only lint pragmas and the stub shebang. Fix what the cheap gates caught on the head: S110 noqa on the recorder swallow, unused loop var in the recording test, biome formatting of the two new/changed .mjs cards, and shfmt on the new tests/stack domain file. Fix the domain's request builder: its printf had two format specifiers for three arguments, so the request JSON came out malformed and every assertion downstream was unproven. Co-Authored-By: Claude Code * docs: support-bundle download, recovery-console recipe, ping-failure record docs/dashboard.md gains the Backup-tab Support bundle card and the Monitoring ping line; docs/monitoring.md says what a failed ping records and that the ping URL is never stored; docs/operations.md documents recovery-bundle as the journal-only console route. Co-Authored-By: Claude Code * tests: pin get_ping_failures in the state-manager test doubles build_state embeds the ping-failure list directly in the payload, so an unpinned MagicMock made the payload unserializable in the three state drift-guard tests; the fixture is regenerated so its shape matches. Co-Authored-By: Claude Code * fix support-bundle clamp, result-archive pairing, and its stack domain - clamp an oversized hours value to the cap instead of falling back to the default, matching control_diag_logs, so the host cap means what the tests and operations.md say - evict a support-bundle archive together with its own result JSON under byte pressure; the count pass already paired them - stack domain: a real 95-char base58 fixture, the default-window assertion that was testing the string --, a well-formed clamp request, a cap case that clears the throttle stamp, a throttle case that keeps it, GNU stat, and path extraction that survives the log() prefix - cover the ping-failure recorder's error paths, a two-hop failure chain, and the support-bundle view's malformed-body and submit-failure legs - operations.md: link the dashboard card and the bug-report flow Co-Authored-By: Claude Code * tests: drop an unused import in the broken-store case Co-Authored-By: Claude Code * fix hours clamp on GNU bash: printf %d rejects base prefixes The clamp normalized with printf '%d' "10#...", which zsh accepts and GNU bash rejects — the runner's bash fell through to the default, so 9999 clamped to 72, exactly the red CI row. Normalize by string: strip leading zeros, then length-compare against the cap before any numeric test, so oversized and zero-filled values clamp to 168/72 in every shell that runs the CLI. Co-Authored-By: Claude Code * declare recovery-bundle in the verb ledgers Every dispatched verb needs a ledger answer: add it to the read-only verb lock's unclaimed set, to the CLI verb ledger lock's missing set, and to the strategy doc with the issue that owns the missing live run (#4054). Co-Authored-By: Claude Code * classify Tor SOCKS failures, test support-bundle retention, drop leftover comments Co-Authored-By: Claude Sonnet 5.5 * keep views.py and the healthchecks tests inside the file budget after the develop merge Co-Authored-By: Claude Sonnet 5.5 * drop the docstring from the SOCKS test module Co-Authored-By: Claude Sonnet 5.5 * tests: pin support-bundle units under one fixed verdict label Co-Authored-By: Claude Opus 5.5 * tests: cover support-bundle result-JSON pairing in retention; trim noqa note Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Code --- .../mining_dashboard/service/data_setup.py | 4 +- .../service/health/diagnostics_service.py | 7 + .../service/notify/healthchecks.py | 42 ++++- .../service/storage_schema.py | 36 ++++ dashboard/mining_dashboard/web/server.py | 5 +- .../web/static/app/components.mjs | 5 +- .../web/static/network/health.mjs | 34 +++- .../web/static/system/supportbundle.mjs | 99 +++++++++++ .../web/views/diagnostics_views.py | 38 +++++ .../web/views/download_views.py | 15 ++ dashboard/mining_dashboard/web/views/views.py | 3 +- .../tests/frontend/fixtures/_gen_state.py | 1 + dashboard/tests/frontend/fixtures/state.json | 1 + .../frontend/network/health-pings.test.mjs | 49 ++++++ .../frontend/system/supportbundle.test.mjs | 84 +++++++++ .../tests/service/notify/test_healthchecks.py | 140 +++++++++++++++ .../service/notify/test_healthchecks_socks.py | 64 +++++++ .../tests/service/test_ping_failures_store.py | 70 ++++++++ dashboard/tests/web/conftest.py | 1 + .../web/views/test_support_bundle_views.py | 161 ++++++++++++++++++ docs/dashboard.md | 24 ++- docs/dev/testing-strategy.md | 1 + docs/monitoring.md | 9 + docs/operations.md | 1 + lib/pithead/07-support-bundle.sh | 141 +++++++++++++++ lib/pithead/18-help-version.sh | 4 + lib/pithead/41-subcommand-chaining.sh | 2 +- lib/pithead/46b-control-support-bundle.sh | 34 ++++ lib/pithead/49-control-request-loop.sh | 40 +++-- lib/pithead/51-main-dispatch.sh | 1 + pithead-completion.bash | 2 +- tests/stack/control/control-results-prune.sh | 65 +++++++ .../control/test-control-support-bundle.sh | 143 ++++++++++++++++ tests/stack/run.sh | 2 + tests/stack/test-cli-verb-ledger-lock.sh | 2 +- tests/stack/test-readonly-verbs-lock.sh | 2 +- 36 files changed, 1294 insertions(+), 38 deletions(-) create mode 100644 dashboard/mining_dashboard/web/static/system/supportbundle.mjs create mode 100644 dashboard/tests/frontend/network/health-pings.test.mjs create mode 100644 dashboard/tests/frontend/system/supportbundle.test.mjs create mode 100644 dashboard/tests/service/notify/test_healthchecks_socks.py create mode 100644 dashboard/tests/service/test_ping_failures_store.py create mode 100644 dashboard/tests/web/views/test_support_bundle_views.py create mode 100644 lib/pithead/46b-control-support-bundle.sh create mode 100644 tests/stack/control/test-control-support-bundle.sh diff --git a/dashboard/mining_dashboard/service/data_setup.py b/dashboard/mining_dashboard/service/data_setup.py index 5ecc8f6113..29ad577de3 100644 --- a/dashboard/mining_dashboard/service/data_setup.py +++ b/dashboard/mining_dashboard/service/data_setup.py @@ -173,7 +173,9 @@ def __init__(self, state_manager, proxy_client, xvb_client): # Healthchecks.io dead-man's switch (Issue #79). Disabled by default — when off this is # a no-op. When on, each cycle pings a unique URL; the alert fires externally on the # *absence* of a ping, so it survives a host death the in-stack notifier can't report. - self.healthchecks = HealthchecksClient.from_config() + self.healthchecks = HealthchecksClient.from_config( + record_failure=self.state_manager.record_ping_failure + ) # Auto-transition a clearnet initial-sync node back to Tor once it's synced (#234). Reuses # the same docker control proxy as the #31 failover (start/stop only). on_transition surfaces diff --git a/dashboard/mining_dashboard/service/health/diagnostics_service.py b/dashboard/mining_dashboard/service/health/diagnostics_service.py index 5d386fded1..b09142c0fa 100644 --- a/dashboard/mining_dashboard/service/health/diagnostics_service.py +++ b/dashboard/mining_dashboard/service/health/diagnostics_service.py @@ -54,3 +54,10 @@ def submit_diag_logs(container: str, lines: int, actor: str = "") -> str: "lines": lines, } ) + + +def submit_support_bundle(hours=None, actor: str = "") -> str: + intent = {"id": str(uuid.uuid4()), "action": "support-bundle", "actor": actor} + if hours is not None: + intent["hours"] = hours + return request_spool.write(intent) diff --git a/dashboard/mining_dashboard/service/notify/healthchecks.py b/dashboard/mining_dashboard/service/notify/healthchecks.py index 658215976b..a84fc35cf0 100644 --- a/dashboard/mining_dashboard/service/notify/healthchecks.py +++ b/dashboard/mining_dashboard/service/notify/healthchecks.py @@ -57,6 +57,7 @@ def __init__( interval_seconds, tor_proxy=None, clock=time.monotonic, + record_failure=None, ): # A ping URL is the on/off switch: paste the full URL Healthchecks.io shows you (hosted or a # Tor-reachable self-hosted instance) to enable; leave it blank to keep the switch off. @@ -70,6 +71,7 @@ def __init__( # always injects it. self._proxies = {"http": tor_proxy, "https": tor_proxy} if tor_proxy else None self._clock = clock + self._record_failure = record_failure self._last_ping = None # monotonic time of the last *successful* send self._last_ping_ok = None # tri-state (None/True/False): logs only on state change @@ -80,12 +82,12 @@ def __init__( ) @classmethod - def from_config(cls): - """Build a client from the module-level config (env-backed) values.""" + def from_config(cls, record_failure=None): return cls( ping_url=HEALTHCHECKS_PING_URL, interval_seconds=_PING_INTERVAL_SEC, tor_proxy=TOR_SOCKS_PROXY, + record_failure=record_failure, ) def _due(self, now): @@ -119,21 +121,45 @@ def ping(self) -> bool: "Healthchecks ping recovered (was failing, now %s).", resp.status_code ) self._last_ping_ok = True - # Advance the throttle only on success so a transient outage keeps retrying. self._last_ping = now return True - # A revoked/typo'd URL still passes the scheme check but never counts as accepted; - # don't advance the throttle so the next cycle retries. Warn once on the transition - # so a dead URL doesn't spam every cycle. if self._last_ping_ok is not False: logger.warning("Healthchecks ping rejected: HTTP %s.", resp.status_code) self._last_ping_ok = False + self._record("http_status", f"HTTP {resp.status_code}") return False except requests.RequestException as e: - # Offline / Tor down / endpoint hiccup: the whole point is to survive these - # silently — Healthchecks.io will alert on the missed ping. DEBUG, never noise. logger.debug("Healthchecks ping failed (offline?): %s", e) + self._record(_failure_class(e, self._proxies is not None), type(e).__name__) return False except Exception as e: # pragma: no cover - defensive; never break the loop logger.debug("Healthchecks unexpected error: %s", e) + self._record("connect", type(e).__name__) return False + + def _record(self, reason, detail=""): + if not self._record_failure: + return + try: + self._record_failure(time.time(), reason, detail) + except Exception: # noqa: S110 + pass + + +def _failure_class(exc, via_proxy=False): + if isinstance(exc, requests.exceptions.ProxyError): + return "tor_socks" + cause = exc.__cause__ or exc.__context__ + hops = 0 + while cause is not None and hops < 10: + name = type(cause).__name__ + if name.startswith("Proxy"): + return "tor_socks" + if name in ("NameResolutionError", "gaierror"): + return "dns" + cause = cause.__cause__ or cause.__context__ + hops += 1 + if via_proxy and isinstance(exc, (requests.ConnectionError, requests.Timeout)): + if not isinstance(exc, requests.exceptions.SSLError): + return "tor_socks" + return "connect" diff --git a/dashboard/mining_dashboard/service/storage_schema.py b/dashboard/mining_dashboard/service/storage_schema.py index 0f3e0526b8..1df8198039 100644 --- a/dashboard/mining_dashboard/service/storage_schema.py +++ b/dashboard/mining_dashboard/service/storage_schema.py @@ -250,6 +250,9 @@ def _create_tables(self): "CREATE TABLE IF NOT EXISTS worker_config_revision (worker TEXT PRIMARY KEY, " "revision TEXT, last_change_id TEXT, ts REAL, drift_from TEXT, rigforge_version TEXT)" ) + self._conn.execute( + "CREATE TABLE IF NOT EXISTS ping_failures (ts REAL, reason TEXT, detail TEXT)" + ) def _create_indexes(self): """Creates indexes. Called after migrations so the indexed columns are guaranteed to @@ -349,3 +352,36 @@ def _migrate_db(self): self.logger.info("Migrating DB: Adding type column to worker_config") self._conn.execute("ALTER TABLE worker_config ADD COLUMN type TEXT DEFAULT 'apply'") self._migrate_worker_config_revision(cursor) + + PING_FAILURES_KEPT = 50 + + def record_ping_failure(self, ts: float, reason: str, detail: str = "") -> None: + try: + with self._db_lock: + if not self._conn: + return + with self._conn: + self._conn.execute( + "INSERT INTO ping_failures (ts, reason, detail) VALUES (?, ?, ?)", + (float(ts), str(reason), str(detail)[:200]), + ) + self._conn.execute( + "DELETE FROM ping_failures WHERE rowid NOT IN " + "(SELECT rowid FROM ping_failures ORDER BY ts DESC, rowid DESC LIMIT ?)", + (self.PING_FAILURES_KEPT,), + ) + except sqlite3.Error: + pass + + def get_ping_failures(self, limit: int = 10) -> list[dict]: + try: + with self._db_lock: + if not self._conn: + return [] + cur = self._conn.execute( + "SELECT ts, reason, detail FROM ping_failures ORDER BY ts DESC LIMIT ?", + (int(limit),), + ) + return [{"ts": r[0], "reason": r[1], "detail": r[2]} for r in cur.fetchall()] + except sqlite3.Error: + return [] diff --git a/dashboard/mining_dashboard/web/server.py b/dashboard/mining_dashboard/web/server.py index b2b2fa2708..fd5065d5ba 100644 --- a/dashboard/mining_dashboard/web/server.py +++ b/dashboard/mining_dashboard/web/server.py @@ -617,10 +617,7 @@ def create_app(state_manager, latest_data_ref): web.get("/api/control/backup-download", download_views.handle_backup_download), # Appliance OS update: one route, a closed action set, every judgment host-side. web.post("/api/control/os-update", handle_control_os_update), - # Service Diagnostics (#913/#943): read-only, polls /api/control/result above. - web.post("/api/control/diag-doctor", diagnostics_views.handle_diag_doctor), - web.post("/api/control/diag-logs", diagnostics_views.handle_diag_logs), - web.post("/api/control/onion-client-key", diagnostics_views.handle_onion_key), + *diagnostics_views.control_routes(), ] ) diff --git a/dashboard/mining_dashboard/web/static/app/components.mjs b/dashboard/mining_dashboard/web/static/app/components.mjs index 793d4e6344..922c19437e 100644 --- a/dashboard/mining_dashboard/web/static/app/components.mjs +++ b/dashboard/mining_dashboard/web/static/app/components.mjs @@ -6,6 +6,7 @@ import { DiagnosticsPanel } from "../system/diagview.mjs"; import { NodeAlertBanner } from "../system/nodealert.mjs"; import { OsVerdictBanner } from "../system/osupdate.mjs"; import { SecurityPanel } from "../system/securityview.mjs"; +import { SupportBundlePanel } from "../system/supportbundle.mjs"; import { SyncView } from "../system/syncview.mjs"; import { MinerConnection } from "../workers/minerconnection.mjs"; import { WorkersTable } from "../workers/workertable.mjs"; @@ -104,7 +105,7 @@ class DashboardView extends Component { } ${ backupView - ? html`
<${BackupPanel} enabled=${state.control_enabled} appliance=${!!state.os_update} active=${!suspended} />
` + ? html`
<${BackupPanel} enabled=${state.control_enabled} appliance=${!!state.os_update} active=${!suspended} /><${SupportBundlePanel} enabled=${state.control_enabled} />
` : null } ${ @@ -135,7 +136,7 @@ class DashboardView extends Component {
<${GlobalStats} state=${state} /> <${NetworkCard} state=${state} /> - <${ComponentHealth} topology=${state.topology} egress=${state.egress} /> + <${ComponentHealth} topology=${state.topology} egress=${state.egress} ping_failures=${state.ping_failures} />
` } `; diff --git a/dashboard/mining_dashboard/web/static/network/health.mjs b/dashboard/mining_dashboard/web/static/network/health.mjs index eff5648928..e1c933fe7d 100644 --- a/dashboard/mining_dashboard/web/static/network/health.mjs +++ b/dashboard/mining_dashboard/web/static/network/health.mjs @@ -1,24 +1,56 @@ import { egressRoute } from "../app/logic.mjs"; import { html } from "../app/preact.mjs"; +import { fmtEpoch } from "../system/securityview.mjs"; import { StackTopology } from "./topology.mjs"; +const PING_REASON_LABELS = { + tor_socks: "Tor proxy", + dns: "name resolution", + connect: "connection", + http_status: "HTTP status", +}; + // --- Operational view ---------------------------------------------------------------- // Component Health & egress posture (#170). The topology map (StackTopology) is the panel: every // component and the route of each link, derived from live config (service/egress.py), so it can't // drift from reality. The glanceable summary rides in the header badges + the line below; the older // per-component egress list lives on as an expandable drawer for the full text detail / a11y. -function ComponentHealth({ topology, egress }) { +function ComponentHealth({ topology, egress, ping_failures }) { if (!topology) return null; const { level, leaks } = topology.summary; const ok = level === "ok"; const summaryClass = ok ? "ok" : leaks ? "bad" : "warn"; + const pings = Array.isArray(ping_failures) ? ping_failures : []; + const pingsOk = pings.length === 0; return html`

Stack Topology & Egress

${ok ? "🛡️" : "⚠️"} ${topology.summary.label}
+
+ Monitoring ping${" "} + ${ + pingsOk + ? html`No failed pings recorded.` + : html`${pings.length} recent failure${pings.length === 1 ? "" : "s"}` + } +
+ ${ + pingsOk + ? null + : html`
    + ${pings.map((f) => { + const label = PING_REASON_LABELS[f.reason] || f.reason; + return html`
  • + ${fmtEpoch(f.ts)} + ${label}${" "} + ${f.detail || ""} +
  • `; + })} +
` + } <${StackTopology} topology=${topology} /> ${ egress diff --git a/dashboard/mining_dashboard/web/static/system/supportbundle.mjs b/dashboard/mining_dashboard/web/static/system/supportbundle.mjs new file mode 100644 index 0000000000..b8acacdeb7 --- /dev/null +++ b/dashboard/mining_dashboard/web/static/system/supportbundle.mjs @@ -0,0 +1,99 @@ +import { Component, html } from "../app/preact.mjs"; +import { pollResult } from "../config/configview.mjs"; + +const CONTROL_HEADERS = { "Content-Type": "application/json", "X-Pithead-Control": "1" }; +const BUNDLE_POLL_MAX = 450; +const BUNDLE_TIMEOUT = + "Stopped waiting for the support bundle. The host keeps collecting, but this dashboard did not return; reload, then collect again only after the earlier request has finished."; + +export const DEFAULT_HOURS = 72; + +export async function runSupportBundle(hours) { + const body = hours ? { hours } : {}; + const res = await fetch("/api/control/support-bundle", { + method: "POST", + headers: CONTROL_HEADERS, + body: JSON.stringify(body), + }); + if (!res.ok && res.status !== 202) throw new Error(`HTTP ${res.status}`); + const { id } = await res.json(); + const result = await pollResult(id, "running", BUNDLE_POLL_MAX, BUNDLE_TIMEOUT); + return { id, ...result }; +} + +export function bundleHref(id) { + return `/api/control/support-bundle-download?id=${encodeURIComponent(id)}`; +} + +export class SupportBundlePanel extends Component { + constructor(props) { + super(props); + this.state = { phase: "idle", hours: DEFAULT_HOURS, id: null, result: null }; + } + + async run() { + this.setState({ phase: "collecting" }); + try { + const out = await runSupportBundle(this.state.hours); + this.setState({ + id: out.id, + result: out, + phase: out.status === "applied" ? "ready" : "failed", + }); + } catch (e) { + this.setState({ phase: "failed", result: { error: String(e) } }); + } + } + + render() { + if (!this.props.enabled) { + return html`
+

Support bundle

+

The support bundle is off with the rest of the control channel — see + Configuration.

+
`; + } + const { phase, id, result } = this.state; + if (phase === "ready" && result) { + return html`
+

Support bundle ready

+

Archive: ${result.archive} + — journal of the last ${result.hours} hours, redacted on the host before it was + written.

+

The download stays available for about an hour; after + that, collect a fresh bundle.

+
+ Download bundle + +
+
`; + } + if (phase === "failed") { + return html`
+

Support bundle

+

${(result && result.error) || "The host did not complete the bundle."}

+ +
`; + } + return html`
+

Support bundle

+

Collect one redacted archive for a bug report: recent logs from every Pithead + service and container, dashboard health history, Tor bootstrap state, versions and the + RAUC slot, and the configuration's key shape. Values — passwords, wallet addresses, + tokens, onion addresses — are removed on the host before the archive is written. + Nothing leaves the box until you download it.

+ ${" "} + +
`; + } +} diff --git a/dashboard/mining_dashboard/web/views/diagnostics_views.py b/dashboard/mining_dashboard/web/views/diagnostics_views.py index 9312ffc017..c2937b2e57 100644 --- a/dashboard/mining_dashboard/web/views/diagnostics_views.py +++ b/dashboard/mining_dashboard/web/views/diagnostics_views.py @@ -108,3 +108,41 @@ async def handle_onion_key(request): logger.exception("Error submitting onion-client-key request") return web.json_response({"error": "Failed to submit the request."}, status=500) return web.json_response({"id": rid, "status": "pending"}, status=202) + + +async def handle_support_bundle(request): + _require_control_header(request) + hours = None + if request.can_read_body: + try: + body = await request.json() + except Exception: + raise web.HTTPBadRequest(text="Body must be JSON.") from None + if not isinstance(body, dict): + raise web.HTTPBadRequest(text="Body must be a JSON object.") + if "hours" in body: + hours = body.get("hours") + if isinstance(hours, bool) or not isinstance(hours, int) or hours < 1: + raise web.HTTPBadRequest(text="'hours' must be a positive integer.") + try: + rid = diagnostics_service.submit_support_bundle( + hours, request.headers.get("X-Auth-User", "") + ) + except Exception: + logger.exception("Error submitting support-bundle request") + return web.json_response({"error": "Failed to submit the request."}, status=500) + return web.json_response({"id": rid, "status": "pending"}, status=202) + + +def control_routes(): + from mining_dashboard.web.views import download_views + + return [ + web.post("/api/control/diag-doctor", handle_diag_doctor), + web.post("/api/control/diag-logs", handle_diag_logs), + web.post("/api/control/onion-client-key", handle_onion_key), + web.post("/api/control/support-bundle", handle_support_bundle), + web.get( + "/api/control/support-bundle-download", download_views.handle_support_bundle_download + ), + ] diff --git a/dashboard/mining_dashboard/web/views/download_views.py b/dashboard/mining_dashboard/web/views/download_views.py index 359fc34a12..4c130c9f68 100644 --- a/dashboard/mining_dashboard/web/views/download_views.py +++ b/dashboard/mining_dashboard/web/views/download_views.py @@ -38,3 +38,18 @@ async def handle_backup_download(request): return web.FileResponse( path, headers={"Content-Disposition": f'attachment; filename="{archive_name}"'} ) + + +async def handle_support_bundle_download(request): + try: + rid = str(uuid.UUID(request.query.get("id", ""))) + except ValueError: + raise web.HTTPBadRequest(text="'id' must be a UUID.") from None + res = control_service.result(rid) + archive_name = (res or {}).get("archive") + if not res or res.get("status") != "applied" or not archive_name: + raise web.HTTPNotFound(text="No completed support bundle for that id.") + path = os.path.join(config.CONTROL_RESULTS_DIR, f"{rid}.tar.gz") + return web.FileResponse( + path, headers={"Content-Disposition": f'attachment; filename="{archive_name}"'} + ) diff --git a/dashboard/mining_dashboard/web/views/views.py b/dashboard/mining_dashboard/web/views/views.py index f057a56a7f..b60b2bf8df 100644 --- a/dashboard/mining_dashboard/web/views/views.py +++ b/dashboard/mining_dashboard/web/views/views.py @@ -254,10 +254,8 @@ def build_state(data, state_mgr, range_arg, window=None, avg_window=DEFAULT_HASH ) metrics = build_metrics(data, state_mgr, history) db_healthy = state_mgr.is_db_healthy() - mode_tok, p2p_tok, xvb_tok = _mode_palette(metrics.mode) pool_net = build_pool_network(data, metrics) - # Built once, consumed twice: the Earnings card reads the full payload, the expected-vs-actual # summary (#808) rolls the same figures up — one build, so the two can't disagree. earnings = build_earnings( @@ -389,6 +387,7 @@ def build_state(data, state_mgr, range_arg, window=None, avg_window=DEFAULT_HASH "xvb_history": build_xvb_history(state_mgr.get_xvb_history(), range_arg, window), "egress": egress, "topology": topology, + "ping_failures": state_mgr.get_ping_failures(8), "node_alert": build_node_alert(data), "chart": build_chart( history, diff --git a/dashboard/tests/frontend/fixtures/_gen_state.py b/dashboard/tests/frontend/fixtures/_gen_state.py index bdbf4926e1..7c42cae7d9 100644 --- a/dashboard/tests/frontend/fixtures/_gen_state.py +++ b/dashboard/tests/frontend/fixtures/_gen_state.py @@ -127,6 +127,7 @@ def _state_mgr(): # Embedded directly in the payload (#249) — an unpinned MagicMock here is not JSON # serializable, unlike the list-shaped methods that iterate as empty. No standby held. sm.get_xvb_standby.return_value = None + sm.get_ping_failures.return_value = [] return sm diff --git a/dashboard/tests/frontend/fixtures/state.json b/dashboard/tests/frontend/fixtures/state.json index 3281fce4ea..5701cc76e0 100644 --- a/dashboard/tests/frontend/fixtures/state.json +++ b/dashboard/tests/frontend/fixtures/state.json @@ -330,6 +330,7 @@ "monero": [], "tari": [] }, + "ping_failures": [], "pool": { "blocks": 0, "diff": "0.00 M", diff --git a/dashboard/tests/frontend/network/health-pings.test.mjs b/dashboard/tests/frontend/network/health-pings.test.mjs new file mode 100644 index 0000000000..5f03622a50 --- /dev/null +++ b/dashboard/tests/frontend/network/health-pings.test.mjs @@ -0,0 +1,49 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { ComponentHealth } from "../../../mining_dashboard/web/static/network/health.mjs"; +import { render } from "../helpers/render.mjs"; + +const topology = { + summary: { level: "ok", label: "Tor-only egress", leaks: [] }, + nodes: [], + edges: [], +}; + +test("no ping failures: a calm empty state and no failure list", () => { + const out = render(ComponentHealth, { topology, egress: null, ping_failures: [] }); + assert.match(out, /Monitoring ping/); + assert.match(out, /No failed pings recorded/); + assert.doesNotMatch(out, /
    /); +}); + +test("undefined ping_failures (older state payload) renders the empty state, not a crash", () => { + const out = render(ComponentHealth, { topology }); + assert.match(out, /No failed pings recorded/); +}); + +test("failures render newest-first with the mapped reason label and detail", () => { + const out = render(ComponentHealth, { + topology, + egress: null, + ping_failures: [ + { ts: 1_762_900_000, reason: "http_status", detail: "HTTP 404" }, + { ts: 1_762_890_000, reason: "tor_socks", detail: "ProxyError" }, + ], + }); + assert.match(out, /ping-summary c-warn/); + assert.match(out, /2 recent failures/); + assert.match(out, /HTTP status/); + assert.match(out, /Tor proxy/); + assert.match(out, /HTTP 404/); +}); + +test("an unmapped reason still renders verbatim rather than vanishing", () => { + const out = render(ComponentHealth, { + topology, + egress: null, + ping_failures: [{ ts: 1, reason: "future_class", detail: "" }], + }); + assert.match(out, /future_class/); + assert.match(out, /1 recent failure<\/span>/); +}); diff --git a/dashboard/tests/frontend/system/supportbundle.test.mjs b/dashboard/tests/frontend/system/supportbundle.test.mjs new file mode 100644 index 0000000000..958f806a33 --- /dev/null +++ b/dashboard/tests/frontend/system/supportbundle.test.mjs @@ -0,0 +1,84 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { + bundleHref, + DEFAULT_HOURS, + runSupportBundle, + SupportBundlePanel, +} from "../../../mining_dashboard/web/static/system/supportbundle.mjs"; +import { render } from "../helpers/render.mjs"; + +const ID = "22222222-2222-4222-8222-222222222222"; +const okResult = (body) => ({ status: 200, ok: true, json: async () => body }); + +async function withFastPoll(fetchStub, fn) { + const realFetch = globalThis.fetch; + const realTimeout = globalThis.setTimeout; + globalThis.fetch = fetchStub; + globalThis.setTimeout = (cb) => { + cb(); + return 0; + }; + try { + return await fn(); + } finally { + globalThis.fetch = realFetch; + globalThis.setTimeout = realTimeout; + } +} + +test("runSupportBundle posts the requested window, skips 'running', returns id + archive", async () => { + let posted = null; + let polls = 0; + const fetchStub = async (url, opts) => { + if (url === "/api/control/support-bundle") { + posted = opts; + return { status: 202, ok: false, json: async () => ({ id: ID, status: "pending" }) }; + } + polls++; + if (polls === 1) return okResult({ status: "running" }); + return okResult({ status: "applied", archive: "support-bundle-x.tar.gz", hours: 24, ts: 1 }); + }; + const out = await withFastPoll(fetchStub, () => runSupportBundle(24)); + assert.equal(out.id, ID); + assert.equal(out.status, "applied"); + assert.equal(posted.headers["X-Pithead-Control"], "1"); + assert.equal(posted.body, JSON.stringify({ hours: 24 })); +}); + +test("no stated window sends no hours key — the host states its own default", async () => { + let body = null; + const fetchStub = async (url, opts) => { + if (url === "/api/control/support-bundle") { + body = opts.body; + return { status: 202, ok: false, json: async () => ({ id: ID, status: "pending" }) }; + } + return okResult({ status: "applied", archive: "a.tar.gz", hours: DEFAULT_HOURS }); + }; + const out = await withFastPoll(fetchStub, () => runSupportBundle(0)); + assert.equal(body, JSON.stringify({})); + assert.equal(out.hours, DEFAULT_HOURS); +}); + +test("a host rejection arrives as the outcome, not a throw", async () => { + const fetchStub = async (url) => + url === "/api/control/support-bundle" + ? { status: 202, ok: false, json: async () => ({ id: ID, status: "pending" }) } + : okResult({ status: "rejected", error: "a support bundle was collected less than a minute ago" }); + const out = await withFastPoll(fetchStub, () => runSupportBundle(72)); + assert.equal(out.status, "rejected"); +}); + +test("bundleHref carries the id url-encoded to the download route", () => { + assert.equal(bundleHref(ID), `/api/control/support-bundle-download?id=${ID}`); +}); + +test("idle card states the default window and the off card defers to Configuration", () => { + const on = render(SupportBundlePanel, { enabled: true }); + assert.match(on, /Collect support bundle/); + assert.match(on, /value="72"/); + const off = render(SupportBundlePanel, { enabled: false }); + assert.match(off, /control channel/); + assert.doesNotMatch(off, /Collect support bundle/); +}); diff --git a/dashboard/tests/service/notify/test_healthchecks.py b/dashboard/tests/service/notify/test_healthchecks.py index 6a39513778..d3505bf372 100644 --- a/dashboard/tests/service/notify/test_healthchecks.py +++ b/dashboard/tests/service/notify/test_healthchecks.py @@ -230,3 +230,143 @@ def test_reads_config_values(self): assert c.enabled is True # a URL is configured assert c.url == "https://hc-ping.com/zzz" assert c.interval == hc_mod._PING_INTERVAL_SEC # fixed throttle floor, not configurable + + +NameResolutionError = type("NameResolutionError", (Exception,), {}) +gaierror = type("gaierror", (Exception,), {}) +ProxyConnectionError = type("ProxyConnectionError", (Exception,), {}) + + +class TestFailureRecording: + URL = "https://hc-ping.com/secret-ping-token" + + def _client(self, recorder, **overrides): + return _client(ping_url=self.URL, record_failure=recorder, **overrides) + + def _recorder(self): + rows = [] + return rows, lambda ts, reason, detail: rows.append((ts, reason, detail)) + + def _wrapped(self, inner, outer): + exc = outer(f"while pinging {self.URL}") + exc.__cause__ = inner + return exc + + def test_a_success_records_nothing(self): + rows, rec = self._recorder() + with patch.object(hc_mod, "bounded_get", return_value=_resp(200)): + assert self._client(rec).ping() is True + assert rows == [] + + def test_unconfigured_and_throttled_paths_record_nothing(self): + rows, rec = self._recorder() + assert _client(ping_url="", record_failure=rec).ping() is False + assert rows == [] + clock = _Clock() + c = self._client(rec, clock=clock) + with patch.object(hc_mod, "bounded_get", return_value=_resp(200)): + assert c.ping() is True + rows.clear() + with patch.object(hc_mod, "bounded_get", return_value=_resp(200)): + assert c.ping() is False + assert rows == [] + + def test_rejection_is_recorded_as_http_status_with_the_status_in_detail(self): + rows, rec = self._recorder() + with patch.object(hc_mod, "bounded_get", return_value=_resp(404)): + assert self._client(rec).ping() is False + assert len(rows) == 1 + ts, reason, detail = rows[0] + assert reason == "http_status" + assert detail == "HTTP 404" + assert ts > 1_600_000_000 + + def test_proxy_error_maps_to_tor_socks(self): + rows, rec = self._recorder() + err = requests.exceptions.ProxyError(f"Cannot connect to proxy for {self.URL}") + with patch.object(hc_mod, "bounded_get", side_effect=err): + assert self._client(rec).ping() is False + assert rows[0][1:] == ("tor_socks", "ProxyError") + + def test_wrapped_proxy_connection_error_maps_to_tor_socks(self): + rows, rec = self._recorder() + err = self._wrapped( + ProxyConnectionError("proxy refused"), requests.exceptions.ConnectionError + ) + with patch.object(hc_mod, "bounded_get", side_effect=err): + assert self._client(rec).ping() is False + assert rows[0][1] == "tor_socks" + + def test_name_resolution_maps_to_dns(self): + rows, rec = self._recorder() + err = self._wrapped( + NameResolutionError("host not found"), requests.exceptions.ConnectionError + ) + with patch.object(hc_mod, "bounded_get", side_effect=err): + assert self._client(rec).ping() is False + assert rows[0][1] == "dns" + + def test_gaierror_maps_to_dns(self): + rows, rec = self._recorder() + err = self._wrapped(gaierror("nodename nor servname"), requests.exceptions.ConnectionError) + with patch.object(hc_mod, "bounded_get", side_effect=err): + assert self._client(rec).ping() is False + assert rows[0][1] == "dns" + + def test_a_class_two_hops_down_the_chain_still_maps(self): + rows, rec = self._recorder() + inner = NameResolutionError("host not found") + middle = OSError(f"SSLError while reaching {self.URL}") + middle.__cause__ = inner + err = self._wrapped(middle, requests.exceptions.ConnectionError) + with patch.object(hc_mod, "bounded_get", side_effect=err): + assert self._client(rec).ping() is False + assert rows[0][1] == "dns" + + def test_plain_connection_error_and_timeout_map_to_connect(self): + rows, rec = self._recorder() + with patch.object( + hc_mod, + "bounded_get", + side_effect=[ + requests.exceptions.ConnectionError(f"reset by peer on {self.URL}"), + requests.exceptions.Timeout(f"timed out against {self.URL}"), + ], + ): + assert self._client(rec).ping() is False + assert self._client(rec).ping() is False + assert [r[1] for r in rows] == ["connect", "connect"] + + def test_no_stored_field_ever_contains_the_ping_url(self): + rows, rec = self._recorder() + errs = [ + requests.exceptions.ProxyError(f"Cannot connect to proxy for {self.URL}"), + requests.exceptions.ConnectionError(f"reset by peer on {self.URL}"), + requests.exceptions.Timeout(f"timed out against {self.URL}"), + ] + c = self._client(rec) + for err in errs: + with patch.object(hc_mod, "bounded_get", side_effect=err): + assert c.ping() is False + with patch.object(hc_mod, "bounded_get", return_value=_resp(403)): + assert c.ping() is False + assert len(rows) == 4 + for _ts, reason, detail in rows: + assert self.URL not in str(detail) + assert "secret-ping-token" not in f"{reason}{detail}" + + def test_a_recorder_that_raises_never_breaks_the_ping(self): + def explode(ts, reason, detail): + raise RuntimeError("db on fire") + + c = self._client(explode) + with patch.object(hc_mod, "bounded_get", return_value=_resp(500)): + assert c.ping() is False + + def test_from_config_threads_the_recorder_through(self): + rows, rec = self._recorder() + with patch.object(hc_mod, "HEALTHCHECKS_PING_URL", self.URL): + c = HealthchecksClient.from_config(record_failure=rec) + with patch.object(hc_mod, "bounded_get", return_value=_resp(500)): + assert c.ping() is False + assert rows[0][1:] == ("http_status", "HTTP 500") diff --git a/dashboard/tests/service/notify/test_healthchecks_socks.py b/dashboard/tests/service/notify/test_healthchecks_socks.py new file mode 100644 index 0000000000..4ff3413a17 --- /dev/null +++ b/dashboard/tests/service/notify/test_healthchecks_socks.py @@ -0,0 +1,64 @@ +from unittest.mock import patch + +import requests + +import mining_dashboard.service.notify.healthchecks as hc_mod +from mining_dashboard.service.notify.healthchecks import HealthchecksClient + + +class TestTorSocksClassification: + URL = "https://hc-ping.com/secret-ping-token" + + def _client(self, recorder, **overrides): + return HealthchecksClient( + ping_url=self.URL, interval_seconds=60, record_failure=recorder, **overrides + ) + + def _recorder(self): + rows = [] + return rows, lambda ts, reason, detail: rows.append((ts, reason, detail)) + + def test_a_timeout_or_connect_failure_through_the_tor_proxy_is_tor_socks(self): + rows, rec = self._recorder() + c = self._client(rec, tor_proxy="socks5h://tor:9050") + errs = [ + requests.exceptions.ConnectTimeout(f"timed out against {self.URL}"), + requests.exceptions.ConnectionError(f"SOCKS5 error against {self.URL}"), + ] + for err in errs: + with patch.object(hc_mod, "bounded_get", side_effect=err): + assert c.ping() is False + assert [r[1] for r in rows] == ["tor_socks", "tor_socks"] + + def test_real_socks5_error_reply_and_hung_handshake_are_tor_socks(self): + import socket + import threading + + def serve(mode, ready, port_box): + srv = socket.socket() + srv.bind(("127.0.0.1", 0)) + srv.listen(1) + port_box.append(srv.getsockname()[1]) + ready.set() + conn, _ = srv.accept() + conn.recv(3) + if mode == "reply": + conn.sendall(b"\x05\x00") + conn.recv(512) + conn.sendall(b"\x05\x04\x00\x01\x00\x00\x00\x00\x00\x00") + else: + threading.Event().wait(2) + conn.close() + srv.close() + + for mode in ("reply", "hang"): + rows, rec = self._recorder() + ready, port_box = threading.Event(), [] + t = threading.Thread(target=serve, args=(mode, ready, port_box), daemon=True) + t.start() + ready.wait(5) + c = self._client(rec, tor_proxy=f"socks5h://127.0.0.1:{port_box[0]}") + with patch.object(hc_mod, "_PING_TIMEOUT_SEC", 0.5): + assert c.ping() is False + t.join(5) + assert rows[0][1] == "tor_socks", (mode, rows) diff --git a/dashboard/tests/service/test_ping_failures_store.py b/dashboard/tests/service/test_ping_failures_store.py new file mode 100644 index 0000000000..d67f2fe21d --- /dev/null +++ b/dashboard/tests/service/test_ping_failures_store.py @@ -0,0 +1,70 @@ +from mining_dashboard.service.storage_service import StateManager + + +def _sm(): + return StateManager(db_path=":memory:") + + +class TestPingFailuresStore: + def test_empty_store_reads_empty(self): + sm = _sm() + try: + assert sm.get_ping_failures() == [] + finally: + sm.close() + + def test_records_newest_first(self): + sm = _sm() + try: + sm.record_ping_failure(100.0, "connect", "ConnectionError") + sm.record_ping_failure(200.0, "http_status", "HTTP 404") + rows = sm.get_ping_failures() + assert [r["reason"] for r in rows] == ["http_status", "connect"] + assert rows[0]["ts"] == 200.0 + assert rows[1]["detail"] == "ConnectionError" + finally: + sm.close() + + def test_ring_keeps_only_the_newest_rows(self): + sm = _sm() + try: + for i in range(sm.PING_FAILURES_KEPT + 25): + sm.record_ping_failure(float(i), "connect", f"row {i}") + rows = sm.get_ping_failures(limit=1000) + assert len(rows) == sm.PING_FAILURES_KEPT + assert rows[0]["detail"] == f"row {sm.PING_FAILURES_KEPT + 24}" + finally: + sm.close() + + def test_limit_bounds_the_read(self): + sm = _sm() + try: + for i in range(5): + sm.record_ping_failure(float(i), "dns", "") + assert len(sm.get_ping_failures(limit=2)) == 2 + finally: + sm.close() + + def test_detail_is_truncated_so_nothing_long_hides_in_the_column(self): + sm = _sm() + try: + sm.record_ping_failure(1.0, "connect", "x" * 5000) + assert len(sm.get_ping_failures()[0]["detail"]) == 200 + finally: + sm.close() + + def test_recorder_survives_a_closed_connection(self): + sm = _sm() + sm.close() + sm.record_ping_failure(1.0, "connect", "after close") + assert sm.get_ping_failures() == [] + + def test_a_broken_store_costs_a_row_and_an_empty_read(self): + sm = _sm() + try: + sm._conn.execute("DROP TABLE ping_failures") + sm._conn.commit() + sm.record_ping_failure(1.0, "connect", "boom") + assert sm.get_ping_failures() == [] + finally: + sm.close() diff --git a/dashboard/tests/web/conftest.py b/dashboard/tests/web/conftest.py index f6169bbd48..e9ff72d6e0 100644 --- a/dashboard/tests/web/conftest.py +++ b/dashboard/tests/web/conftest.py @@ -136,6 +136,7 @@ def _state_mgr( sm.get_blocks.return_value = blocks or [] sm.get_disk_growth.return_value = disk_growth or [] sm.get_xvb_history.return_value = xvb_history or [] + sm.get_ping_failures.return_value = [] return sm return _state_mgr diff --git a/dashboard/tests/web/views/test_support_bundle_views.py b/dashboard/tests/web/views/test_support_bundle_views.py new file mode 100644 index 0000000000..66515a5412 --- /dev/null +++ b/dashboard/tests/web/views/test_support_bundle_views.py @@ -0,0 +1,161 @@ +import json +import uuid + +import pytest + +from mining_dashboard.service import control_service +from mining_dashboard.service.health import diagnostics_service +from mining_dashboard.service.storage_service import StateManager +from mining_dashboard.web.server import create_app + +CONTROL_HEADERS = {"X-Pithead-Control": "1"} + + +@pytest.fixture +def spool(tmp_path, monkeypatch): + (tmp_path / "requests").mkdir() + (tmp_path / "results").mkdir() + monkeypatch.setattr(control_service.config, "DASHBOARD_CONTROL_ENABLED", True) + monkeypatch.setattr(control_service.config, "CONTROL_REQUESTS_DIR", str(tmp_path / "requests")) + monkeypatch.setattr(control_service.config, "CONTROL_RESULTS_DIR", str(tmp_path / "results")) + return tmp_path + + +@pytest.fixture +async def bundle_client(aiohttp_client, spool): + sm = StateManager(db_path=":memory:") + cli = await aiohttp_client(create_app(sm, {})) + yield cli + sm.close() + + +def spooled(spool): + files = list((spool / "requests").glob("*.json")) + assert len(files) == 1, files + return json.loads(files[0].read_text()) + + +class TestSupportBundleDisabled: + async def test_routes_404_when_the_control_channel_is_off(self, aiohttp_client, monkeypatch): + monkeypatch.setattr(control_service.config, "DASHBOARD_CONTROL_ENABLED", False) + sm = StateManager(db_path=":memory:") + cli = await aiohttp_client(create_app(sm, {})) + try: + resp = await cli.post( + "/api/control/support-bundle", headers=CONTROL_HEADERS, json={"hours": 24} + ) + assert resp.status == 404 + resp = await cli.get( + "/api/control/support-bundle-download", params={"id": str(uuid.uuid4())} + ) + assert resp.status == 404 + finally: + sm.close() + + +class TestSupportBundleSubmit: + async def test_requires_the_control_header(self, bundle_client): + assert (await bundle_client.post("/api/control/support-bundle", json={})).status == 403 + + async def test_no_body_spools_no_hours_key_so_the_host_states_its_default( + self, bundle_client, spool + ): + resp = await bundle_client.post( + "/api/control/support-bundle", + headers={**CONTROL_HEADERS, "X-Auth-User": "admin"}, + ) + assert resp.status == 202 + body = await resp.json() + assert spooled(spool) == {"id": body["id"], "action": "support-bundle", "actor": "admin"} + + async def test_the_stated_window_is_spooled_verbatim_because_the_host_clamps( + self, bundle_client, spool + ): + resp = await bundle_client.post( + "/api/control/support-bundle", headers=CONTROL_HEADERS, json={"hours": 9999} + ) + assert resp.status == 202 + assert spooled(spool)["hours"] == 9999 + + @pytest.mark.parametrize("hours", [True, 0, -1, "24", None, [24]]) + async def test_a_malformed_window_is_a_400_and_spools_nothing( + self, bundle_client, spool, hours + ): + resp = await bundle_client.post( + "/api/control/support-bundle", headers=CONTROL_HEADERS, json={"hours": hours} + ) + assert resp.status == 400 + assert not list((spool / "requests").glob("*.json")) + + async def test_a_json_array_body_is_a_400_not_a_500(self, bundle_client): + resp = await bundle_client.post( + "/api/control/support-bundle", + data="[1]", + headers={**CONTROL_HEADERS, "Content-Type": "application/json"}, + ) + assert resp.status == 400 + + async def test_a_malformed_json_body_is_a_400_and_spools_nothing(self, bundle_client, spool): + resp = await bundle_client.post( + "/api/control/support-bundle", + data="{oops", + headers={**CONTROL_HEADERS, "Content-Type": "application/json"}, + ) + assert resp.status == 400 + assert not list((spool / "requests").glob("*.json")) + + async def test_a_failing_submit_is_a_500_and_spools_nothing( + self, bundle_client, monkeypatch, spool + ): + def boom(*args, **kwargs): + raise RuntimeError("the spool is on fire") + + monkeypatch.setattr(diagnostics_service, "submit_support_bundle", boom) + resp = await bundle_client.post( + "/api/control/support-bundle", headers=CONTROL_HEADERS, json={"hours": 24} + ) + assert resp.status == 500 + assert not list((spool / "requests").glob("*.json")) + + +class TestSupportBundleDownload: + async def _result(self, spool, rid, payload): + (spool / "results" / f"{rid}.json").write_text(json.dumps(payload)) + + async def test_a_non_uuid_is_a_400(self, bundle_client): + resp = await bundle_client.get( + "/api/control/support-bundle-download", params={"id": "nope"} + ) + assert resp.status == 400 + + async def test_an_unknown_id_is_a_404(self, bundle_client): + resp = await bundle_client.get( + "/api/control/support-bundle-download", params={"id": str(uuid.uuid4())} + ) + assert resp.status == 404 + + @pytest.mark.parametrize("payload", [{"status": "running"}, {"status": "failed"}, {}]) + async def test_a_result_that_is_not_applied_is_a_404(self, bundle_client, spool, payload): + rid = str(uuid.uuid4()) + await self._result(spool, rid, payload) + resp = await bundle_client.get("/api/control/support-bundle-download", params={"id": rid}) + assert resp.status == 404 + + async def test_applied_without_the_archive_on_disk_is_a_404(self, bundle_client, spool): + rid = str(uuid.uuid4()) + await self._result(spool, rid, {"status": "applied", "archive": "support-bundle-x.tar.gz"}) + resp = await bundle_client.get("/api/control/support-bundle-download", params={"id": rid}) + assert resp.status == 404 + + async def test_applied_streams_the_spool_archive_under_its_named_filename( + self, bundle_client, spool + ): + rid = str(uuid.uuid4()) + await self._result(spool, rid, {"status": "applied", "archive": "support-bundle-x.tar.gz"}) + (spool / "results" / f"{rid}.tar.gz").write_bytes(b"tarbytes") + resp = await bundle_client.get("/api/control/support-bundle-download", params={"id": rid}) + assert resp.status == 200 + assert await resp.read() == b"tarbytes" + assert ( + 'attachment; filename="support-bundle-x.tar.gz"' in resp.headers["Content-Disposition"] + ) diff --git a/docs/dashboard.md b/docs/dashboard.md index 1eeaa1cf01..dd0ccbd728 100644 --- a/docs/dashboard.md +++ b/docs/dashboard.md @@ -715,7 +715,10 @@ operational: a node you run is yours to restart and resync, and a node you point (`monero.mode: remote`, `tari.mode: remote`) is somebody else's to fix, so it is the first thing worth knowing when one stalls. It also makes the remote-node setting visible without opening `config.json`. A row reads `—` when the dashboard cannot tell — a payload from -before this shipped, rather than a node it has decided is local. +before this shipped, rather than a node it has decided is local. The card also keeps the dead-man's +switch honest: a **Monitoring ping** line under the diagram shows the recent failed Healthchecks.io +pings — timestamps and reason classes, nothing else — or says none failed. +[Monitoring](monitoring.md) says what is recorded and why the ping URL itself is never part of it. The what-if earnings calculator and the XvB tier calculator live only in Advanced view. Simple view shows a one-time banner pointing there; it goes away once you dismiss it or open Advanced view, and @@ -1576,9 +1579,26 @@ set up without a dashboard login, it points at **Set up again** in the boot menu labels it as the machine's own backup log, so commands in that log do not read as instructions for the browser. +A second card lives on the same tab: **Support bundle** +([#4036](https://github.com/p2pool-starter-stack/pithead/issues/4036)). One button asks the host to +collect one redacted diagnostics archive for a bug report: journal lines of every Pithead unit over +the window you ask for (the last 72 hours by default, 1 to 168), the dashboard's health history, +the Tor bootstrap state, versions, the active RAUC slot, and the config's key shape with every +value dropped. Every line passes the same redactor the diagnostics log tail uses on its way in; +the host refuses a bundle over its own size cap rather than truncating one onto the wire; and the +ask is audited like every other control request. The finished archive waits in the same results +spool with the same hour-window retention a backup gets: **Download bundle** appears only once the +host's result says applied, and nothing leaves the box until you press it. Attach it to a report +the way [#3746](https://github.com/p2pool-starter-stack/pithead/issues/3746) lays out. A box whose +stack never came up cannot serve the dashboard, so it builds the same archive from the console +instead: `pithead recovery-bundle` in [Operations](operations.md). + **Retention.** The host prunes control results and backup archives so they cannot fill `/data`. A fresh archive stays downloadable for at least one hour after the backup completes; past that -window, only the 3 most recent archives are kept. Ordinary control-request results (config +window, only the 3 most recent archives are kept, backups and support bundles alike. An expired +archive past those 3 is removed with its result; the 3 that remain stay downloadable until a newer +one displaces them or the byte cap evicts them, so a support bundle can outlive the hour the card +quotes. Ordinary control-request results (config previews, applies, upgrades) age out after a day or once more than 200 accumulate. Whatever these limits leave behind is capped at 512 MiB total, oldest first, unless the files that must remain (`os-update-state.json`, the result of a request still in flight, or a fresh backup pair) alone diff --git a/docs/dev/testing-strategy.md b/docs/dev/testing-strategy.md index 8ce9579a3f..8e97813e15 100644 --- a/docs/dev/testing-strategy.md +++ b/docs/dev/testing-strategy.md @@ -368,6 +368,7 @@ the situations above; `missing` means nothing does yet, with the issue that owns | `config-reset` | covered | KVM (appliance-only verb, `--phase reset` leg 0) | | `support-bundle` | covered | DIY `--lifecycle` runs `run-support-bundle.sh` (#3081): apply synthetic dashboard, stratum and disabled-Telegram credentials, collect a real bundle, require mode 600, doctor reports, masked config, redacted env, a live Compose census and nonempty log tails, and reject any fixture credential in any member. Restore the starting config and rendered env, wait for stack health, and compare config and env bytes and secret fingerprints. `selftest-support-bundle.sh` checks missing content, credential leaks, unsafe permissions, unarmed fixtures, partial-archive cleanup and restoration failures. | | `render-quadlet` | missing | #1217 — the podman/quadlet render has no live run anywhere | +| `recovery-bundle` | missing | #4054 — the appliance's journal-only bundle has no live tier-4 run yet; the tier4-kvm fault-phase leg owns it | | `test-alert` | by-design | deliberately deferred — real notification sinks; wire-level coverage is #2263 | | `logs` | by-design | a passthrough verb; tier 1 is the honest ceiling | | `version` | by-design | pure-output verb; tier 1 is the honest ceiling | diff --git a/docs/monitoring.md b/docs/monitoring.md index 8439525866..3dbdc65285 100644 --- a/docs/monitoring.md +++ b/docs/monitoring.md @@ -102,6 +102,15 @@ the whole host) and, once the period + grace elapses, Healthchecks.io alerts you momentarily down — is logged at debug level only; Healthchecks.io alerts on the missed ping regardless, which is the point. A ping the endpoint *answers* with a non-2xx status is different: a revoked or mistyped URL logs `Healthchecks ping rejected: HTTP ` once, on the transition. +- **A failed ping leaves a record.** Every failed attempt is appended to a ring of the last 50 rows + in the dashboard's own store: a timestamp, a reason class — Tor proxy, name resolution, + connection, or the HTTP status the endpoint answered — and nothing else. The ping URL is + **never** stored: it is the check's credential, so what gets recorded is the exception's class + and the status code, never a message. The **Stack Topology & Egress** card shows the recent + failures under **Monitoring ping** — "No failed pings recorded." while things are calm, a + timestamped list afterwards — so a broken Tor path and a dead stack stop looking identical from + the outside. Recording can never disturb the loop that keeps the box alive: a failing write costs + a row, nothing more. --- diff --git a/docs/operations.md b/docs/operations.md index 22512a20dc..bfd71bb17d 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -29,6 +29,7 @@ separately, [below](#appliance-only-commands). | `./pithead lan-guard-check` | Check the live LAN-only source rule. If it is missing, remove the node start marker and stop the nodes that publish LAN ports; if a stop cannot be verified, try restoring the rule on all three fixed node ports and keep reporting failure until the stop is verified. Fired every two minutes by `pithead-lan.timer`; `up`, `apply` and `upgrade` install the timer while a LAN port is configured or still published by a node. Run `./pithead up` after fixing the firewall to restore access. | | `./pithead render` | Regenerate every derived file (`.env`, the Caddyfile, service configs, host units) from `config.json` without touching containers. The appliance runs this every boot; run it by hand after replacing the program under an existing config. | | `./pithead support-bundle` | Collect a `chmod 600` diagnostics tarball for a bug report: host facts, `doctor` in prose and JSON, a masked config, a redacted `.env`, and the last 200 log lines per container with launch-line credentials, wallet addresses and the service onion scrubbed — as is any Monero address or onion written anywhere else in the log text. Read-only, and nothing leaves the box — review it, then share it. | +| `./pithead recovery-bundle` | The appliance's journal-only twin of `support-bundle` ([#4038](https://github.com/p2pool-starter-stack/pithead/issues/4038)): no dashboard, no container engine, no network — it reads the journal of every Pithead unit over the window you ask for (`--hours N`, default 72, clamped host-side to 168), passes every line through the same redactor, refuses an archive over its own size cap rather than truncating one, writes the result `chmod 600` under `/data/pithead/support-bundles/` and prints its path — the console recipe for a box that failed boot gating, where the machine stays up for diagnosis and the only thing on screen tells you to read the journal. Refuses where no journal exists: there, use `support-bundle`. Review the archive, then share it the way [#3746](https://github.com/p2pool-starter-stack/pithead/issues/3746) lays out; a box whose dashboard answers collects the same artifact from the browser instead — the **Support bundle** card in [Dashboard › Backup view](dashboard.md#backup-view). | | `./pithead config-reset` | **DESTRUCTIVE**. Clear the configuration and reopen the setup wizard, keeping every data directory — chains, wallets, Tor onion keys and dashboard history all stay, so reconfiguring costs no resync. Type-to-confirm unless `-y` / `--yes`. If Compose shutdown fails, print its error and warn that containers may still be running, then continue the wipe (exit 0 on completion). | | `./pithead uninstall` | **DESTRUCTIVE**. The clean exit: removes everything pithead put on this host, including the egress firewall rules with their `pithead-egress.service` boot unit and `pithead-egress.timer` check, the LAN-only source rule and its `pithead-lan.timer` check, and deletes NO data, on any flag. Prints the three-column inventory below, resolved for this box, and the exact command to delete the rest. Refuses in a `pithead-vX.Y.Z` directory that `current` does not point at, because every version directory drives the same live stack: run it in the live directory, and delete an old version directory by hand. Type-to-confirm unless `-y` / `--yes`. | | `./pithead version` | Print the installed stack version on one line (also `-V` / `--version`). Offline; no update check. `doctor` repeats it in its header. | diff --git a/lib/pithead/07-support-bundle.sh b/lib/pithead/07-support-bundle.sh index 828283a9f9..1750f136de 100644 --- a/lib/pithead/07-support-bundle.sh +++ b/lib/pithead/07-support-bundle.sh @@ -211,3 +211,144 @@ stack_support_bundle() { log "Support bundle written: $out" log "Secrets are redacted at collection, but REVIEW the contents before sharing: tar -tzf $(basename "$out")" } + +readonly PITHEAD_SUPPORT_DEFAULT_HOURS=72 +readonly PITHEAD_SUPPORT_MAX_HOURS=168 +readonly PITHEAD_SUPPORT_UNITS="pithead-boot.service pithead-boot-version.service pithead-address-watch.service pithead-miner-recovery.service dashboard.service caddy.service tor.service monerod.service tari.service p2pool.service xmrig-proxy.service docker-proxy.service docker-control.service xmrig.service rauc.service" + +bundle_support_clamp_hours() { + local h="$1" + case "$h" in + '' | *[!0-9]*) + printf '%s' "$PITHEAD_SUPPORT_DEFAULT_HOURS" + return 0 + ;; + *[!0]*) + h=${h#"${h%%[!0]*}"} + ;; + *) h=0 ;; + esac + [ "${#h}" -gt "${#PITHEAD_SUPPORT_MAX_HOURS}" ] && h="$PITHEAD_SUPPORT_MAX_HOURS" + [ "$h" -lt 1 ] && h="$PITHEAD_SUPPORT_DEFAULT_HOURS" + [ "$h" -gt "$PITHEAD_SUPPORT_MAX_HOURS" ] && h="$PITHEAD_SUPPORT_MAX_HOURS" + printf '%s' "$h" +} + +bundle_support_collect() { + local outdir="$1" hours="$2" ts out tmp unit db total rc=0 + local unit_cap="${PITHEAD_SUPPORT_MAX_BYTES_PER_UNIT:-2097152}" + local total_cap="${PITHEAD_SUPPORT_MAX_TOTAL_BYTES:-67108864}" + mkdir -p "$outdir" || return 1 + chmod 700 "$outdir" 2>/dev/null || true + ts=$(date -u +%Y%m%dT%H%M%SZ) + out="$outdir/support-bundle-$ts.tar.gz" + tmp=$(mktemp -d "$outdir/.support.XXXXXXXX") || return 1 + trap 'rm -rf "$tmp"; exit 130' INT TERM HUP + mkdir -p "$tmp/bundle/logs" + + { + echo "window_hours=$hours" + echo "window_start=$(date -u -d "$hours hours ago" +%FT%TZ 2>/dev/null || date -u +%FT%TZ)" + echo "collected=$(date -u +%FT%TZ)" + echo "pithead ${PITHEAD_VERSION:-unknown}" + uname -a + echo + [ -r /etc/os-release ] && cat /etc/os-release + echo + df -h / /data 2>/dev/null + echo + free -h 2>/dev/null + } >"$tmp/bundle/host.txt" 2>&1 + + if command -v journalctl >/dev/null 2>&1; then + for unit in $PITHEAD_SUPPORT_UNITS; do + journalctl -u "$unit" --since "$hours hours ago" --no-pager 2>/dev/null | + bundle_redact_log | tail -c "$unit_cap" >"$tmp/bundle/logs/$unit.log" || true + done + grep -Ei 'bootstrap|circuit' "$tmp/bundle/logs/tor.service.log" >"$tmp/bundle/tor.txt" 2>/dev/null || + printf 'no tor bootstrap or circuit lines in the window\n' >"$tmp/bundle/tor.txt" + else + printf 'journalctl not present — no journal entries collected\n' >"$tmp/bundle/journal.txt" + fi + + { + if command -v rauc >/dev/null 2>&1; then + rauc status 2>/dev/null | bundle_redact_log || echo "rauc status failed" + else + echo "rauc not present" + fi + } >"$tmp/bundle/rauc.txt" 2>&1 + + if [ -n "${CONFIG_FILE:-}" ] && [ -f "$CONFIG_FILE" ]; then + render_masked_config "$tmp/scratch" >/dev/null 2>&1 || true + if [ -f "$tmp/scratch/masked/config.json" ]; then + bundle_mask_config <"$tmp/scratch/masked/config.json" | + jq 'def j: if type=="object" then with_entries(.value |= j) elif type=="array" then map(j) else null end; j' \ + >"$tmp/bundle/config.shape.json" 2>/dev/null || true + fi + fi + + db="${DASHBOARD_DATA_DIR:-}/mining_data.db" + [ -f "$db" ] || db="/data/pithead/dashboard/mining_data.db" + [ -f "$db" ] || db="/data/mining_data.db" + if command -v python3 >/dev/null 2>&1 && [ -f "$db" ]; then + PITHEAD_SUPPORT_DB="$db" PITHEAD_SUPPORT_HOURS="$hours" python3 -I -c ' +import json, os, sqlite3, sys, time +db = os.environ["PITHEAD_SUPPORT_DB"] +since = time.time() - float(os.environ["PITHEAD_SUPPORT_HOURS"]) * 3600 +try: + conn = sqlite3.connect("file:%s?mode=ro" % db, uri=True) + conn.row_factory = sqlite3.Row + out = {} + for table, tcol, cols in ( + ("history", "timestamp", "timestamp, v, v_p2pool, v_xvb"), + ("events", "ts", "ts, type, detail"), + ): + try: + rows = conn.execute( + "SELECT %s FROM (SELECT %s FROM %s WHERE %s >= ? ORDER BY %s DESC LIMIT 5000) ORDER BY %s ASC" + % (cols, cols, table, tcol, tcol, tcol), + (since,), + ).fetchall() + out[table] = [dict(r) for r in rows] + except sqlite3.Error: + out[table] = None + print(json.dumps(out)) +except sqlite3.Error: + sys.exit(1) +' 2>/dev/null | bundle_redact_log >"$tmp/bundle/dashboard.history.json" || true + fi + + total=$(du -sk "$tmp/bundle" 2>/dev/null | awk '{print $1 * 1024}') + [ -n "$total" ] || total=0 + if [ "$total" -gt "$total_cap" ]; then + rm -rf "$tmp" + trap - INT TERM HUP + return 1 + fi + + (umask 077 && tar -czf "$tmp/bundle.tar.gz" -C "$tmp" bundle) || rc=$? + [ "$rc" -eq 0 ] && chmod 600 "$tmp/bundle.tar.gz" && mv -f "$tmp/bundle.tar.gz" "$out" || rc=1 + rm -rf "$tmp" + trap - INT TERM HUP + [ "$rc" -eq 0 ] || return 1 + printf '%s\n' "$out" +} + +recovery_bundle() { + local hours="$PITHEAD_SUPPORT_DEFAULT_HOURS" outdir arch + case "${1:-}" in + "") ;; + --hours) + [ "$#" -le 2 ] || error "Usage: pithead recovery-bundle [--hours N]" + hours=$(bundle_support_clamp_hours "${2:-}") + ;; + *) error "Usage: pithead recovery-bundle [--hours N]" ;; + esac + command -v journalctl >/dev/null 2>&1 || + error "recovery-bundle needs the appliance journal. On a host with a container engine use: $0 support-bundle" + outdir="${PITHEAD_RECOVERY_BUNDLE_DIR:-/data/pithead/support-bundles}" + arch=$(bundle_support_collect "$outdir" "$hours") || + error "Could not collect a support bundle — nothing was written." + log "Support bundle written: $arch" +} diff --git a/lib/pithead/18-help-version.sh b/lib/pithead/18-help-version.sh index 5dbf9de6f3..b303f11c75 100644 --- a/lib/pithead/18-help-version.sh +++ b/lib/pithead/18-help-version.sh @@ -58,6 +58,10 @@ Inspection: facts, doctor (prose + JSON), masked config, redacted .env, and the last 200 log lines per container (launch-line credentials scrubbed). Read-only; nothing leaves the box — review, then share. + recovery-bundle Appliance only: collect the same redacted bundle from the journal + alone — no dashboard, no container engine, no network — for a box + whose stack is down. Prints the archive path under /data. + [--hours N, default 72]. version, -V, --version Print the installed stack version (offline; no update check). Maintenance: diff --git a/lib/pithead/41-subcommand-chaining.sh b/lib/pithead/41-subcommand-chaining.sh index 090f4982ea..cd2daee0f5 100644 --- a/lib/pithead/41-subcommand-chaining.sh +++ b/lib/pithead/41-subcommand-chaining.sh @@ -3,7 +3,7 @@ # Every dispatchable subcommand, in help order. main's dispatch, the chain validator, and the # tab-completion script (pithead-completion.bash) key off this one list; tests/stack/run.sh fails # if any of the three drift apart. -readonly PITHEAD_COMMANDS="setup apply render up down restart tor-recover upgrade logs status test-alert doctor support-bundle reset-dashboard config-reset factory-reset backup restore uninstall firstboot-wizard load-images local-miner os-update control-run-pending egress-run-pending egress-status lan-guard-check onion-client-key rotate-dashboard-onion rotate-secrets render-quadlet version help" +readonly PITHEAD_COMMANDS="setup apply render up down restart tor-recover upgrade logs status test-alert doctor support-bundle recovery-bundle reset-dashboard config-reset factory-reset backup restore uninstall firstboot-wizard load-images local-miner os-update control-run-pending egress-run-pending egress-status lan-guard-check onion-client-key rotate-dashboard-onion rotate-secrets render-quadlet version help" # The subset allowed in a chain: commands that take no positional argument and terminate on their # own. Excluded: setup (interactive first-run), logs (follows until Ctrl+C), restore (needs an # archive path), reset-dashboard (destructive — run it deliberately, alone), test-alert (outbound diff --git a/lib/pithead/46b-control-support-bundle.sh b/lib/pithead/46b-control-support-bundle.sh new file mode 100644 index 0000000000..267c7affea --- /dev/null +++ b/lib/pithead/46b-control-support-bundle.sh @@ -0,0 +1,34 @@ +control_support_bundle() { + local file="$1" id="$2" actor="$3" cdir="$4" + local results="$cdir/results" auditf="$cdir/audit/control.log" + local stamp="$cdir/staged/.support-bundle-stamp" + local raw hours arch rc=0 fname dest + control_audit "$auditf" "$id" "$actor" "support-bundle" "started" + if [ -n "$(find "$stamp" -mmin -1 2>/dev/null)" ]; then + control_write_result "$results" "$id" "$(jq -n '{status:"rejected",error:"a support bundle was collected less than a minute ago — wait for the download window, then retry.",ts:(now|floor)}')" + control_audit "$auditf" "$id" "$actor" "support-bundle" "rejected" + return 0 + fi + raw=$(jq -r '.hours // ""' "$file") + hours=$(bundle_support_clamp_hours "$raw") + touch "$stamp" 2>/dev/null || true + control_write_result "$results" "$id" "$(jq -n '{status:"running",ts:(now|floor)}')" + arch=$(bundle_support_collect "$cdir/staged" "$hours") || rc=$? + if [ "$rc" -ne 0 ] || [ -z "$arch" ] || [ ! -f "$arch" ]; then + control_write_result "$results" "$id" "$(jq -n '{status:"failed",error:"the host could not collect a support bundle — nothing was written.",ts:(now|floor)}')" + control_audit "$auditf" "$id" "$actor" "support-bundle" "failed" + return 0 + fi + fname=$(basename "$arch") + dest="$results/$id.tar.gz" + if ! mv -f "$arch" "$dest"; then + rm -f "$arch" + control_write_result "$results" "$id" "$(jq -n '{status:"failed",error:"the host collected the bundle but could not move it onto the download leg.",ts:(now|floor)}')" + control_audit "$auditf" "$id" "$actor" "support-bundle" "failed" + return 0 + fi + chown "$APP_UID:$APP_GID" "$dest" 2>/dev/null || true + chmod 600 "$dest" 2>/dev/null || true + control_write_result "$results" "$id" "$(jq -n --arg f "$fname" --argjson h "$hours" '{status:"applied",archive:$f,hours:$h,ts:(now|floor)}')" + control_audit "$auditf" "$id" "$actor" "support-bundle" "applied" +} diff --git a/lib/pithead/49-control-request-loop.sh b/lib/pithead/49-control-request-loop.sh index a2882b21bd..7c7feb1527 100644 --- a/lib/pithead/49-control-request-loop.sh +++ b/lib/pithead/49-control-request-loop.sh @@ -77,7 +77,7 @@ control_process_request() { # # schema for EVERY action, exactly as `worker`/`changes` already do — the check is a shape # guard, and the value guard is per-verb: control_diag_logs takes the container name only if it # matches a member of its own fixed allowlist, and clamps the count host-side. - if [ "$(jq -r '(.action == "tor-history") as $history | [keys[] | select(. != "id" and . != "action" and . != "config" and . != "actor" and . != "version" and . != "worker" and . != "changes" and . != "confirm" and . != "approval" and . != "container" and . != "lines" and . != "chain" and . != "appliance" and (($history == false) or (. != "outage" and . != "observed_at")))] | length' "$file")" != "0" ]; then + if [ "$(jq -r '(.action == "tor-history") as $history | [keys[] | select(. != "id" and . != "action" and . != "config" and . != "actor" and . != "version" and . != "worker" and . != "changes" and . != "confirm" and . != "approval" and . != "container" and . != "lines" and . != "chain" and . != "appliance" and . != "hours" and (($history == false) or (. != "outage" and . != "observed_at")))] | length' "$file")" != "0" ]; then control_write_result "$cdir/results" "$id" "$(jq -n '{status:"rejected",error:"unexpected keys in request",ts:(now|floor)}')" control_audit "$cdir/audit/control.log" "$id" "" "invalid" "rejected" return 0 @@ -143,6 +143,7 @@ control_process_request() { # # bounded host-side and the log tail is redacted by bundle_redact_log before it is written. diag-doctor) control_diag_doctor "$id" "$actor" "$cdir" ;; diag-logs) control_diag_logs "$file" "$id" "$actor" "$cdir" ;; + support-bundle) control_support_bundle "$file" "$id" "$actor" "$cdir" ;; # Also read-only, and the one that hands back a SECRET rather than a report (#1882): the Tor # client-auth line without which a client-auth'd dashboard onion cannot be opened at all. It is # a one-time kit with the backup kit's TTL and redaction, and every reveal lands in audit/. @@ -195,12 +196,8 @@ control_prune_results() { # # backup kit's plaintext passphrase; remove it only after the download window, never while a # normal atomic rename can still be in flight. find "$dir" -maxdepth 1 -type f -name '.*.tmp' -mmin +"$window_min" -delete 2>/dev/null || true - # A listing that matches nothing makes ls exit 2. Inside the loop-list substitution that fires the - # inherited ERR trap ("pithead aborted unexpectedly (exit 2)", #3047) although the run carries on, - # so each listing swallows its own status. for archive in $(cd "$dir" 2>/dev/null && ls -1t -- *.tar.gz.enc 2>/dev/null || true); do [ -f "$dir/$archive" ] || continue - # Still inside its download window: untouchable, and does not count against the cap below. [ -n "$(find "$dir/$archive" -maxdepth 0 -mmin +"$window_min" 2>/dev/null)" ] || continue kept=$((kept + 1)) if [ "$kept" -gt "$max_archives" ]; then @@ -209,22 +206,31 @@ control_prune_results() { # fi done + local kept_b=0 + for archive in $(cd "$dir" 2>/dev/null && ls -1t -- *.tar.gz 2>/dev/null || true); do + [ -f "$dir/$archive" ] || continue + [ -n "$(find "$dir/$archive" -maxdepth 0 -mmin +"$window_min" 2>/dev/null)" ] || continue + kept_b=$((kept_b + 1)) + if [ "$kept_b" -gt "$max_archives" ]; then + id=$(basename "$archive" .tar.gz) + rm -f "$dir/$archive" "$dir/$id.json" + fi + done + local result n=0 - # Age and count share one pass (and one skip list) so a backup's own result JSON is never - # evicted here while its archive is still protected above — a separate age-only find/-delete - # had no way to see that pairing and could orphan an in-window archive's own status/passphrase. [ -n "$active_result" ] && [ -f "$dir/$active_result" ] && n=1 for result in $(cd "$dir" 2>/dev/null && ls -1t -- *.json 2>/dev/null || true); do case "$result" in os-update-state.json | tor-heal-outage.json | clearnet-*-tor.json | clearnet-*-baseline.json) continue ;; esac [ "$result" == "$active_result" ] && continue - [ -f "$dir/$(basename "$result" .json).tar.gz.enc" ] && continue # a backup's own result, handled above + [ -f "$dir/$(basename "$result" .json).tar.gz.enc" ] && continue + [ -f "$dir/$(basename "$result" .json).tar.gz" ] && continue n=$((n + 1)) if [ "$n" -gt "$max_count" ] || [ -n "$(find "$dir/$result" -maxdepth 0 -mmin +"$age_min" 2>/dev/null)" ]; then rm -f "$dir/$result" fi done - local total f + local total f pair total=$(du -sk "$dir" 2>/dev/null | awk '{print $1 * 1024}') [ -n "$total" ] || total=0 if [ "$total" -gt "$max_bytes" ]; then @@ -238,12 +244,18 @@ control_prune_results() { # id="${f%.tar.gz.enc}" rm -f "$dir/$f" "$dir/$id.json" ;; - # A backup's own result JSON: keep a fresh pair; evict an expired pair together. + *.tar.gz) + [ -n "$(find "$dir/$f" -maxdepth 0 -mmin +"$window_min" 2>/dev/null)" ] || continue + id="${f%.tar.gz}" + rm -f "$dir/$f" "$dir/$id.json" + ;; *.json) id="${f%.json}" - if [ -f "$dir/$id.tar.gz.enc" ]; then - [ -n "$(find "$dir/$id.tar.gz.enc" -maxdepth 0 -mmin +"$window_min" 2>/dev/null)" ] || continue - rm -f "$dir/$f" "$dir/$id.tar.gz.enc" + pair="$dir/$id.tar.gz.enc" + [ -f "$pair" ] || pair="$dir/$id.tar.gz" + if [ -f "$pair" ]; then + [ -n "$(find "$pair" -maxdepth 0 -mmin +"$window_min" 2>/dev/null)" ] || continue + rm -f "$dir/$f" "$pair" else rm -f "$dir/$f" fi diff --git a/lib/pithead/51-main-dispatch.sh b/lib/pithead/51-main-dispatch.sh index 9dd150a7ee..0639cbb02f 100644 --- a/lib/pithead/51-main-dispatch.sh +++ b/lib/pithead/51-main-dispatch.sh @@ -126,6 +126,7 @@ main() { esac ;; support-bundle) stack_support_bundle "$@" ;; + recovery-bundle) recovery_bundle "$@" ;; reset-dashboard) require_deployed reset_dashboard "$@" diff --git a/pithead-completion.bash b/pithead-completion.bash index b445ff9238..f861fa8cb3 100644 --- a/pithead-completion.bash +++ b/pithead-completion.bash @@ -13,7 +13,7 @@ # Keep in sync with PITHEAD_COMMANDS in the pithead script — tests/stack/run.sh fails if the # two lists drift. -_pithead_commands="setup apply render up down restart tor-recover upgrade logs status test-alert doctor support-bundle reset-dashboard config-reset factory-reset backup restore uninstall firstboot-wizard load-images local-miner os-update control-run-pending egress-run-pending egress-status lan-guard-check onion-client-key rotate-dashboard-onion rotate-secrets render-quadlet version help" +_pithead_commands="setup apply render up down restart tor-recover upgrade logs status test-alert doctor support-bundle recovery-bundle reset-dashboard config-reset factory-reset backup restore uninstall firstboot-wizard load-images local-miner os-update control-run-pending egress-run-pending egress-status lan-guard-check onion-client-key rotate-dashboard-onion rotate-secrets render-quadlet version help" # Service names = the top-level keys under `services:` in the docker-compose.yml next to the # pithead being completed. $1 = path to that compose file. diff --git a/tests/stack/control/control-results-prune.sh b/tests/stack/control/control-results-prune.sh index b168fb7d0b..a012101516 100644 --- a/tests/stack/control/control-results-prune.sh +++ b/tests/stack/control/control-results-prune.sh @@ -202,6 +202,71 @@ run_sourced "$SANDBOX" control_prune_results "$PRP" >/dev/null 2>&1 ok "byte eviction removes an expired backup result and archive together" || bad "byte eviction removes an expired backup result and archive together" "json: $([ -f "$PRP/results/$pair_id.json" ] && echo present || echo missing), archive: $([ -f "$PRP/results/$pair_id.tar.gz.enc" ] && echo present || echo missing)" +PRZ="$SANDBOX/ctrl4036bundles" +mkdir -p "$PRZ/results" +echo '{"step":"idle"}' >"$PRZ/results/os-update-state.json" +bundle() { # + echo '{"status":"applied","archive":"b.tar.gz"}' >"$PRZ/results/$1.json" + head -c 2000 "$PRZ/results/$1.tar.gz" + backdate "$PRZ/results/$1.json" "$2" + backdate "$PRZ/results/$1.tar.gz" "$2" +} +has() { [ -f "$PRZ/results/$1.json" ] && [ -f "$PRZ/results/$1.tar.gz" ]; } +gone() { [ ! -f "$PRZ/results/$1.json" ] && [ ! -f "$PRZ/results/$1.tar.gz" ]; } +bundle a0a0a0a0-0000-4000-8000-000000000801 1 +bundle a0a0a0a0-0000-4000-8000-000000000802 120 +bundle a0a0a0a0-0000-4000-8000-000000000803 130 +bundle a0a0a0a0-0000-4000-8000-000000000804 140 +export CONTROL_BACKUP_MAX_COUNT=2 CONTROL_RESULT_MAX_COUNT=100 CONTROL_RESULT_MAX_AGE_S=100000 CONTROL_BACKUP_DOWNLOAD_WINDOW_S=3600 +unset CONTROL_RESULTS_MAX_BYTES +run_sourced "$SANDBOX" control_prune_results "$PRZ" >/dev/null 2>&1 +has a0a0a0a0-0000-4000-8000-000000000801 && + ok "a support bundle inside its download window keeps its archive and result JSON" || + bad "a support bundle inside its download window keeps its archive and result JSON" "missing" +has a0a0a0a0-0000-4000-8000-000000000802 && has a0a0a0a0-0000-4000-8000-000000000803 && + ok "expired support bundles within CONTROL_BACKUP_MAX_COUNT keep their pairs" || + bad "expired support bundles within CONTROL_BACKUP_MAX_COUNT keep their pairs" "missing" +gone a0a0a0a0-0000-4000-8000-000000000804 && + ok "the support bundle past CONTROL_BACKUP_MAX_COUNT is evicted with its result JSON" || + bad "the support bundle past CONTROL_BACKUP_MAX_COUNT is evicted with its result JSON" "archive or json survived" +bz_before=$(du -sk "$PRZ/results" | awk '{print $1 * 1024}') +export CONTROL_RESULTS_MAX_BYTES=$((bz_before - 1)) +run_sourced "$SANDBOX" control_prune_results "$PRZ" >/dev/null 2>&1 +gone a0a0a0a0-0000-4000-8000-000000000803 && + ok "byte eviction removes the oldest expired support bundle and its result JSON together" || + bad "byte eviction removes the oldest expired support bundle and its result JSON together" "pair survived or was split" +has a0a0a0a0-0000-4000-8000-000000000801 && + ok "byte eviction spares the in-window support bundle" || + bad "byte eviction spares the in-window support bundle" "in-window bundle lost" +unset CONTROL_RESULTS_MAX_BYTES CONTROL_BACKUP_MAX_COUNT CONTROL_RESULT_MAX_COUNT CONTROL_RESULT_MAX_AGE_S +PRZ="$SANDBOX/ctrl4036pairing" +mkdir -p "$PRZ/results" +echo '{"step":"idle"}' >"$PRZ/results/os-update-state.json" +bundle a0a0a0a0-0000-4000-8000-000000000811 120 +export CONTROL_BACKUP_MAX_COUNT=3 CONTROL_RESULT_MAX_COUNT=100 CONTROL_RESULT_MAX_AGE_S=60 CONTROL_BACKUP_DOWNLOAD_WINDOW_S=3600 +unset CONTROL_RESULTS_MAX_BYTES +run_sourced "$SANDBOX" control_prune_results "$PRZ" >/dev/null 2>&1 +has a0a0a0a0-0000-4000-8000-000000000811 && + ok "a kept support bundle's result JSON outlives the plain-result age cap with its archive" || + bad "a kept support bundle's result JSON outlives the plain-result age cap with its archive" "json: $([ -f "$PRZ/results/a0a0a0a0-0000-4000-8000-000000000811.json" ] && echo present || echo missing)" +rm -f "$PRZ/results/a0a0a0a0-0000-4000-8000-000000000811".* +bundle a0a0a0a0-0000-4000-8000-000000000812 1 +backdate "$PRZ/results/a0a0a0a0-0000-4000-8000-000000000812.json" 240 +bz_before=$(du -sk "$PRZ/results" | awk '{print $1 * 1024}') +export CONTROL_RESULTS_MAX_BYTES=$((bz_before - 1)) CONTROL_RESULT_MAX_AGE_S=100000 +run_sourced "$SANDBOX" control_prune_results "$PRZ" >/dev/null 2>&1 +has a0a0a0a0-0000-4000-8000-000000000812 && + ok "byte eviction that reaches an in-window support bundle's JSON first keeps the pair" || + bad "byte eviction that reaches an in-window support bundle's JSON first keeps the pair" "json: $([ -f "$PRZ/results/a0a0a0a0-0000-4000-8000-000000000812.json" ] && echo present || echo missing)" +backdate "$PRZ/results/a0a0a0a0-0000-4000-8000-000000000812.tar.gz" 120 +run_sourced "$SANDBOX" control_prune_results "$PRZ" >/dev/null 2>&1 +gone a0a0a0a0-0000-4000-8000-000000000812 && + ok "byte eviction that reaches an expired support bundle's JSON first removes the pair" || + bad "byte eviction that reaches an expired support bundle's JSON first removes the pair" "archive: $([ -f "$PRZ/results/a0a0a0a0-0000-4000-8000-000000000812.tar.gz" ] && echo present || echo missing)" +unset CONTROL_RESULTS_MAX_BYTES CONTROL_BACKUP_MAX_COUNT CONTROL_RESULT_MAX_COUNT CONTROL_RESULT_MAX_AGE_S +unset -f bundle has gone +unset PRZ bz_before + # #3047: boot prunes a results/ dir with no archive or JSON in it. `ls` of an unmatched glob exits 2, # which inside the loop-list substitution fired the inherited ERR trap and logged "pithead aborted # unexpectedly (exit 2)" on a run that carried on. Run it under the production trap and options. diff --git a/tests/stack/control/test-control-support-bundle.sh b/tests/stack/control/test-control-support-bundle.sh new file mode 100644 index 0000000000..510b91f46c --- /dev/null +++ b/tests/stack/control/test-control-support-bundle.sh @@ -0,0 +1,143 @@ +# shellcheck shell=bash +: "${STACK_SUITE:?is unset: this file is a tests/stack/run.sh fragment, not a script — run tests/stack/run.sh}" +: "${SANDBOX:?}" + +SB="$SANDBOX/ctrl4036" +mkdir -p "$SB/results" "$SB/audit" "$SB/bin" "$SB/out" + +SB_ONION="abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion" +SB_ADDR="44nep4y8xiQPH96nSQgkChrvUXLrLb73HK5sSGa6hVt3thisdUwb9BtFKdw9iQ89GE7yWW8xvRqG6HZrAro79hPDvYSrqCG" +assert_eq "the Monero fixture is the 95-char shape the redactor keys on" "${#SB_ADDR}" "95" + +cat >"$SB/bin/journalctl" <>"\${SB_JOURNAL_LOG:-/dev/null}" +case "\$*" in +*monerod.service*) + printf 'monerod: --rpc-login rpcuser:rpcpassvalue servicing --wallet %s\n' "$SB_ADDR" + printf 'monerod: --http-access-token HTTPTOKENVALUE123 auth listener\n' + ;; +*tor.service*) + printf 'tor: Bootstrapped 100%% (done)\n' + printf 'tor: built circuit to exit\n' + printf 'tor: served %s\n' "$SB_ONION" + ;; +*) printf 'boot: starting service\n' ;; +esac +exit 0 +EOF +chmod +x "$SB/bin/journalctl" +export SB_JOURNAL_LOG="$SB/journal.log" + +sb_run() { + local keep="" + [ "${1:-}" = "--keep-stamp" ] && { + keep=1 + shift + } + mkdir -p "$SB/staged" + [ -n "$keep" ] || rm -f "$SB/staged/.support-bundle-stamp" + ( + export PATH="$SB/bin:$PATH" + run_sourced_e "$SANDBOX" control_process_request "$1" "$SB" + ) >/dev/null 2>&1 +} +sb_req() { + printf '{"id":"%s","action":"%s","actor":"admin"%s}\n' "$1" "$2" "${3:-}" >"$SB/req-$1.json" + printf '%s\n' "$SB/req-$1.json" +} + +echo "== control channel: support-bundle applies with an archive and audits the verb (#4036) ==" +sid1="c403c403-0000-4000-8000-000000000001" +sb_run "$(sb_req "$sid1" support-bundle)" +assert_eq "support-bundle applies" "$(jq -r .status "$SB/results/$sid1.json")" "applied" +assert_eq "the applied result names the archive, the way backup does" \ + "$(jq -r '.archive | test("^support-bundle-[0-9T]+Z\\.tar\\.gz$")' "$SB/results/$sid1.json")" "true" +assert_rc "the archive sits in the results spool under the request id" \ + "$( + ls "$SB/results/$sid1.tar.gz" >/dev/null 2>&1 + echo $? + )" "0" +assert_eq "the spool archive is mode 600" \ + "$(stat -c '%a' "$SB/results/$sid1.tar.gz")" "600" +assert_contains "support-bundle is audited applied" \ + "$(cat "$SB/audit/control.log")" '"action":"support-bundle","status":"applied"' + +echo "== control channel: the archive carries the unit journals and hides every seeded secret ==" +mkdir -p "$SB/extract1" +tar -xzf "$SB/results/$sid1.tar.gz" -C "$SB/extract1" +assert_contains "the default window is 72 hours when the intent states none" \ + "$(cat "$SB/journal.log")" "--since 72 hours ago" +assert_rc "every Pithead unit is asked for by exact membership" \ + "$(grep -c -- '--no-pager' "$SB/journal.log")" "15" +sb_missing="" +for unit in pithead-boot.service pithead-boot-version.service pithead-address-watch.service pithead-miner-recovery.service dashboard.service caddy.service tor.service monerod.service tari.service p2pool.service xmrig-proxy.service docker-proxy.service docker-control.service xmrig.service rauc.service; do + grep -qF -- "-u $unit " "$SB/journal.log" || sb_missing="$sb_missing $unit" +done +assert_eq "the journal is asked for every Pithead unit by name" "$sb_missing" "" +unset sb_missing unit +assert_contains "monerod journal lines land in the archive" \ + "$(cat "$SB/extract1/bundle/logs/monerod.service.log")" "monerod:" +assert_contains "tor bootstrap state is collected" \ + "$(cat "$SB/extract1/bundle/tor.txt")" "Bootstrapped 100%" +assert_not_contains "the seeded --rpc-login value is ABSENT from the whole archive" \ + "$(grep -rF 'rpcpassvalue' "$SB/extract1" || true)" "rpcpassvalue" +assert_not_contains "the seeded Monero payout address is ABSENT from the whole archive" \ + "$(grep -rF "$SB_ADDR" "$SB/extract1" || true)" "$SB_ADDR" +assert_not_contains "the seeded .onion is ABSENT from the whole archive" \ + "$(grep -rF "$SB_ONION" "$SB/extract1" || true)" "$SB_ONION" +assert_not_contains "the seeded --http-access-token value is ABSENT from the whole archive" \ + "$(grep -rF 'HTTPTOKENVALUE123' "$SB/extract1" || true)" "HTTPTOKENVALUE123" +assert_contains "the redactor fired rather than the lines vanishing: the marker is present" \ + "$(cat "$SB/extract1/bundle/logs/monerod.service.log")" "[redacted]" + +echo "== control channel: the hours window is a request, and the host clamps it (#4036) ==" +sid2="c403c403-0000-4000-8000-000000000002" +rm -f "$SB/journal.log" +sb_run "$(sb_req "$sid2" support-bundle ',"hours":9999')" +assert_eq "a widened window is clamped to the host cap, not trusted" \ + "$(jq -r .hours "$SB/results/$sid2.json")" "168" +assert_contains "the journal was cut at the clamped window" "$(cat "$SB/journal.log")" "--since 168 hours ago" +sid3="c403c403-0000-4000-8000-000000000003" +rm -f "$SB/journal.log" +sb_run "$( + printf '{"id":"%s","action":"support-bundle","actor":"admin","hours":"12x"}\n' "$sid3" | tee "$SB/req-$sid3.json" >/dev/null + printf '%s' "$SB/req-$sid3.json" +)" +assert_eq "a non-numeric window falls back to the stated default" \ + "$(jq -r .hours "$SB/results/$sid3.json")" "72" + +echo "== control channel: a bundle over the host cap is refused, not truncated onto the wire ==" +sid4="c403c403-0000-4000-8000-000000000004" +rm -f "$SB/staged/.support-bundle-stamp" +( + export PATH="$SB/bin:$PATH" PITHEAD_SUPPORT_MAX_TOTAL_BYTES=0 + run_sourced_e "$SANDBOX" control_process_request "$(sb_req "$sid4" support-bundle)" "$SB" +) >/dev/null 2>&1 +assert_eq "exceeding the total cap fails the request" "$(jq -r .status "$SB/results/$sid4.json")" "failed" +assert_rc "a refused bundle writes no archive" \ + "$([ -e "$SB/results/$sid4.tar.gz" ] && echo 0 || echo 1)" "1" + +echo "== control channel: a second bundle inside a minute is rejected outright ==" +sid5="c403c403-0000-4000-8000-000000000005" +sb_run "$(sb_req "$sid5" support-bundle)" +sb_run --keep-stamp "$(sb_req "$sid5" support-bundle)" +assert_eq "the throttle rejects the immediate second collect" \ + "$(jq -r .status "$SB/results/$sid5.json")" "rejected" + +echo "== host CLI: recovery-bundle shares the one collector and prints a 600 archive (#4038) ==" +rb=$( + export PATH="$SB/bin:$PATH" PITHEAD_RECOVERY_BUNDLE_DIR="$SB/out" + run_sourced_e "$SANDBOX" recovery_bundle --hours 24 2>/dev/null | + sed -n 's/.*Support bundle written: //p' | tail -1 +) +assert_rc "recovery-bundle writes an archive on a journal-only host" \ + "$([ -e "$rb" ] && echo 0 || echo 1)" "0" +assert_contains "the archive lands under the stated directory" "$rb" "$SB/out/support-bundle-" +assert_eq "the printed archive is mode 600" "$(stat -c '%a' "$rb")" "600" +mkdir -p "$SB/extract2" +tar -xzf "$rb" -C "$SB/extract2" +assert_contains "the journal-only archive carries journal lines" \ + "$(cat "$SB/extract2/bundle/logs/tor.service.log")" "Bootstrapped 100%" +assert_not_contains "the same one redactor covers the host CLI path" \ + "$(grep -rF 'rpcpassvalue' "$SB/extract2" || true)" "rpcpassvalue" diff --git a/tests/stack/run.sh b/tests/stack/run.sh index 9f01ce7ebe..f5a4e4ac80 100755 --- a/tests/stack/run.sh +++ b/tests/stack/run.sh @@ -281,6 +281,8 @@ if in_block 5; then # shellcheck source=tests/stack/control/test-control-diagnostics.sh disable=SC2015 _d0=$((PASS + FAIL)) && source "$HERE/control/test-control-diagnostics.sh" && domain_ran test-control-diagnostics.sh "$_d0" "$?" || domain_ran test-control-diagnostics.sh "$_d0" "$?" + # shellcheck source=tests/stack/control/test-control-support-bundle.sh disable=SC2015 + _d0=$((PASS + FAIL)) && source "$HERE/control/test-control-support-bundle.sh" && domain_ran test-control-support-bundle.sh "$_d0" "$?" || domain_ran test-control-support-bundle.sh "$_d0" "$?" # shellcheck source=tests/stack/test-grub-hugepages.sh disable=SC2015 _d0=$((PASS + FAIL)) && source "$HERE/test-grub-hugepages.sh" && domain_ran test-grub-hugepages.sh "$_d0" "$?" || domain_ran test-grub-hugepages.sh "$_d0" "$?" # shellcheck source=tests/stack/test-wizard-setup.sh disable=SC2015 diff --git a/tests/stack/test-cli-verb-ledger-lock.sh b/tests/stack/test-cli-verb-ledger-lock.sh index b8f9c8e8d4..2bcf2f4b09 100644 --- a/tests/stack/test-cli-verb-ledger-lock.sh +++ b/tests/stack/test-cli-verb-ledger-lock.sh @@ -20,7 +20,7 @@ echo "== domain: the CLI verb ledger accounts for every dispatched verb (#2348) ==" CVL_COVERED="setup apply render up down restart tor-recover upgrade status doctor backup restore load-images firstboot-wizard local-miner os-update factory-reset control-run-pending egress-run-pending egress-status lan-guard-check onion-client-key uninstall rotate-secrets rotate-dashboard-onion reset-dashboard config-reset" -CVL_MISSING="support-bundle render-quadlet" +CVL_MISSING="support-bundle render-quadlet recovery-bundle" CVL_BYDESIGN="test-alert logs version help" cvl_cmds="$( diff --git a/tests/stack/test-readonly-verbs-lock.sh b/tests/stack/test-readonly-verbs-lock.sh index 93a4864584..0bae70e190 100644 --- a/tests/stack/test-readonly-verbs-lock.sh +++ b/tests/stack/test-readonly-verbs-lock.sh @@ -157,7 +157,7 @@ kill "$ROVHOLDER" 2>/dev/null # ROV_UNCLAIMED is a floor, not a finding: it is what this domain makes NO claim about, not a set # shown to mutate. Some of it is very likely read-only too; nothing here says so either way. ROV_PROVEN="logs status doctor" -ROV_UNCLAIMED="setup apply render up down restart tor-recover upgrade test-alert support-bundle reset-dashboard config-reset factory-reset backup restore uninstall firstboot-wizard load-images local-miner os-update control-run-pending egress-run-pending egress-status lan-guard-check onion-client-key rotate-dashboard-onion rotate-secrets render-quadlet version help" +ROV_UNCLAIMED="setup apply render up down restart tor-recover upgrade test-alert support-bundle recovery-bundle reset-dashboard config-reset factory-reset backup restore uninstall firstboot-wizard load-images local-miner os-update control-run-pending egress-run-pending egress-status lan-guard-check onion-client-key rotate-dashboard-onion rotate-secrets render-quadlet version help" rov_cmds="$( cd "$SANDBOX" || exit From e444d0ea6613f385e41fa7e057f0fa87b9a07421 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:27:21 -0600 Subject: [PATCH 015/112] Data plane: per-rig mining verdict and this-Pithead-only Workers Alive / Total Hashrate (#4071) (#4097) * dashboard: per-rig mining verdict and this-Pithead-only Workers Alive / Total Hashrate (#4071) Co-Authored-By: Claude Sonnet 5.5 * dashboard: count rigs on this host's names as here and feed the paused badge from the verdict (#4071) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- dashboard/README.md | 16 ++ .../mining_dashboard/service/data_helpers.py | 40 +--- dashboard/mining_dashboard/service/metrics.py | 5 +- .../service/mining_verdict.py | 70 +++++++ .../mining_dashboard/web/views/infra_views.py | 8 +- .../web/views/paused_badge.py | 4 +- dashboard/tests/frontend/fixtures/state.json | 14 ++ dashboard/tests/service/test_data_helpers.py | 4 +- .../tests/service/test_mining_verdict.py | 189 ++++++++++++++++++ .../tests/web/views/test_paused_badge.py | 2 +- 10 files changed, 313 insertions(+), 39 deletions(-) create mode 100644 dashboard/mining_dashboard/service/mining_verdict.py create mode 100644 dashboard/tests/service/test_mining_verdict.py diff --git a/dashboard/README.md b/dashboard/README.md index e07d08b7ec..013315b774 100644 --- a/dashboard/README.md +++ b/dashboard/README.md @@ -16,6 +16,22 @@ The server is a data API; the browser renders the UI. There is no server-side te strings and semantic tokens (`variant: "ok"`, `level: "high"`) and emits no HTML. The same `Metrics` is meant to back future consumers (Telegram #45, calculator #12) without re-deriving from the raw dict. +- Each `workers[]` row carries `mining`, the rig's own connection verdict (#4071): + `{"state", "pool"}` with `state` one of `mining_here`, `on_backup`, `not_connected` or + `unknown`. It is read from the `connection` block (`pool` as `host:port`, `uptime`) of the rig's + summary feed, the shape rigforge's `tests/contract/v1/feed.json` pins. A live pool whose host + is one of this host's names (`HOST_IP`, the detected host IPv4, a specific `STRATUM_BIND`, the + host name and `.local`, so `pithead.local`, or loopback) is `mining_here` on + `STRATUM_PORT` and `on_backup` on any other port. A pool at another IP address is `on_backup` + once this host knows a non-loopback address of its own. A pool named by a host name the + dashboard cannot match, or a pool string without a port, is `unknown`: it is never verified as + foreign. `pool` carries the reported string. A rig with no live connection (`uptime` 0) is + `not_connected`, and a rig that answers without a `connection` block is `unknown`. "Workers + Alive" (`proxy_workers`), the total hashrate, the per-window totals and the "Mining paused + here" header's backup-rig count use these verdicts: the counters take only stratum-side values + of online rows that are not `on_backup` or `not_connected`. The rig's own hashrate is the + separate `telemetry_h10`, `telemetry_h60` and `telemetry_h15` fields (H/s, `null` when not + probed); it is never summed into a total, and `h60`/`h15` stay the proxy's figures. - The client (`static/dashboard.js` + `components.mjs`) is a small Preact app, rendered with `htm` tagged templates (no JSX, no build step). It polls `/api/state` every 30s and renders declaratively, so the chart instance, table sort, selected range, and the simple/advanced view diff --git a/dashboard/mining_dashboard/service/data_helpers.py b/dashboard/mining_dashboard/service/data_helpers.py index d2ec334c38..11c57cfca7 100644 --- a/dashboard/mining_dashboard/service/data_helpers.py +++ b/dashboard/mining_dashboard/service/data_helpers.py @@ -17,6 +17,7 @@ from mining_dashboard.client.xmrig_client import parse_rigforge from mining_dashboard.config import config from mining_dashboard.helper.utils import effective_hashrate, get_tier_info +from mining_dashboard.service import mining_verdict as mv from mining_dashboard.service.control_service import SECRET_SENTINEL, mask_secrets # xmrig-proxy 6.x /workers rows are positional arrays; name the fields we read so the @@ -191,35 +192,20 @@ def _merge_proxy_summary(last_good, summary_data): def _merge_direct_stats(workers, results, active_pool_port): - """Augment proxy-derived workers with direct-API stats (uptime + hashrate). - - ``results`` is the per-worker output of the direct worker API, positionally aligned - with ``workers``. xmrig-proxy ``/1/summary`` reports kH/s while an xmrig miner reports - H/s; the ``kind`` field distinguishes them so we scale to H/s. If the direct API is - unreachable (falsy ``extra_stats``) the worker keeps its proxy-derived hashrate/uptime - and stays online — the proxy already confirmed it's connected and submitting shares — - rather than dropping out of the hashrate total and reading zero (Fixes #28). Each - worker is tagged with ``active_pool`` for the UI badge, and with ``api_ok`` (True/False) plus - ``adopted`` when the worker API was probed, so the UI can tell a rig whose configured feed - failed from one never adopted (#1857) — both distinct from a worker that's simply offline. - """ + local_hosts = mv.local_stratum_hosts() final_workers = [] for w, extra_stats in zip(workers, results, strict=False): - # api_ok: True (probe succeeded), False (probe failed — surfaced, not swallowed), or unset - # (not probed, e.g. an internal IP per the SSRF guard). `adopted` (#1857) rides with it. api_ok = extra_stats.get("api_ok") if extra_stats else None if api_ok is not None: w["api_ok"], w["adopted"] = api_ok, bool(extra_stats.get("adopted")) - # RigForge enriched feed (#235): a superset /1/summary carries an extra `rigforge` block. - # Present only for RigForge rigs whose descriptor port points at the enriched feed; a - # plain-xmrig rig parses to None and gets no chips. A miner-down enriched body has no XMRig - # keys, so this rides in even when api_ok can't confirm live hashrate. rf = parse_rigforge(extra_stats) if extra_stats else None if rf is not None: w["rigforge"] = rf - if api_ok: # only a successful probe carries uptime + per-miner hashrate + w["mining"] = mv.mining_verdict(extra_stats, local_hosts, config.STRATUM_PORT) + + if api_ok: w["uptime"] = extra_stats.get("uptime", w["uptime"]) is_proxy = extra_stats.get("kind") == "proxy" @@ -227,9 +213,9 @@ def _merge_direct_stats(workers, results, active_pool_port): hr_total = extra_stats.get("hashrate", {}).get("total", []) if isinstance(hr_total, list) and len(hr_total) >= 3: - w["h10"] = (hr_total[0] or 0) * hr_scale - w["h60"] = (hr_total[1] or 0) * hr_scale - w["h15"] = (hr_total[2] or 0) * hr_scale + w["telemetry_h10"] = (hr_total[0] or 0) * hr_scale + w["telemetry_h60"] = (hr_total[1] or 0) * hr_scale + w["telemetry_h15"] = (hr_total[2] or 0) * hr_scale w["active_pool"] = active_pool_port final_workers.append(w) @@ -237,16 +223,10 @@ def _merge_direct_stats(workers, results, active_pool_port): def _aggregate_hashrate(workers): - """Total live hashrate across online workers, as ``(total_h15, total_h10)``. - - The headline figure prefers the 15m average, falling back to 60s then 10s when a - longer window hasn't accumulated yet (Priority: 15m > 60s > 10s). Offline workers - contribute nothing. - """ total_hr = 0 total_h10 = 0 for w in workers: - if w.get("status") == "online": + if w.get("status") == "online" and not mv.mines_elsewhere(w): total_hr += effective_hashrate(w) total_h10 += w.get("h10", 0) return total_hr, total_h10 @@ -266,7 +246,7 @@ def _aggregate_window_hashrates(workers): """ totals = {win: 0 for win in _WINDOW_WORKER_KEYS} for w in workers: - if w.get("status") == "online": + if w.get("status") == "online" and not mv.mines_elsewhere(w): for win, src in _WINDOW_WORKER_KEYS.items(): totals[win] += w.get(src, 0) or 0 return totals diff --git a/dashboard/mining_dashboard/service/metrics.py b/dashboard/mining_dashboard/service/metrics.py index a54258afda..fbdef6863e 100644 --- a/dashboard/mining_dashboard/service/metrics.py +++ b/dashboard/mining_dashboard/service/metrics.py @@ -33,6 +33,7 @@ shares_in_pplns_window, xvb_stats_are_stale, ) +from mining_dashboard.service.mining_verdict import mines_elsewhere @dataclass(frozen=True) @@ -209,7 +210,9 @@ def build_metrics(latest_data, state_mgr, history=None): luck_pct = 0.0 workers = data.get("workers", []) - workers_online = sum(1 for w in workers if w.get("status") == "online") + workers_online = sum( + 1 for w in workers if w.get("status") == "online" and not mines_elsewhere(w) + ) return Metrics( total_h15=total_h15, diff --git a/dashboard/mining_dashboard/service/mining_verdict.py b/dashboard/mining_dashboard/service/mining_verdict.py new file mode 100644 index 0000000000..7941ad6487 --- /dev/null +++ b/dashboard/mining_dashboard/service/mining_verdict.py @@ -0,0 +1,70 @@ +import ipaddress +import socket + +from mining_dashboard.config import config +from mining_dashboard.helper.utils import detect_host_ipv4, is_ip_address + +HERE = "mining_here" +BACKUP = "on_backup" +NOT_CONNECTED = "not_connected" +UNKNOWN = "unknown" +ELSEWHERE = (BACKUP, NOT_CONNECTED) + +_UNCONFIGURED_HOST = "Unknown Host" +_LOOPBACK = ("127.0.0.1", "::1", "localhost") + + +def _strip_host(host): + return str(host).strip().strip("[]").lower() + + +def local_stratum_hosts(): + name = socket.gethostname() + hosts = {config.HOST_IP, detect_host_ipv4(), name, f"{name}.local", *_LOOPBACK} + if config.STRATUM_BIND != "0.0.0.0": + hosts.add(config.STRATUM_BIND) + return {_strip_host(h) for h in hosts if h and h != _UNCONFIGURED_HOST} + + +def _split_pool(pool): + host, sep, port = pool.rpartition(":") + if not sep or not (port.isascii() and port.isdigit()): + return None + return _strip_host(host), int(port) + + +def _knows_own_address(local_hosts): + return any(is_ip_address(h) and not ipaddress.ip_address(h).is_loopback for h in local_hosts) + + +def _is_number(value): + return isinstance(value, int | float) and not isinstance(value, bool) + + +def mining_verdict(payload, local_hosts, stratum_port): + unknown = {"state": UNKNOWN, "pool": None} + if not isinstance(payload, dict) or not payload.get("api_ok"): + return unknown + conn = payload.get("connection") + if not isinstance(conn, dict): + return unknown + uptime, pool = conn.get("uptime"), conn.get("pool") + if not _is_number(uptime): + return unknown + if uptime <= 0: + return {"state": NOT_CONNECTED, "pool": None} + if not isinstance(pool, str) or not pool.strip(): + return unknown + pool = pool.strip() + parsed = _split_pool(pool) + if parsed is None: + return {"state": UNKNOWN, "pool": pool} + host, port = parsed + if host in local_hosts: + return {"state": HERE if port == stratum_port else BACKUP, "pool": pool} + foreign = is_ip_address(host) and _knows_own_address(local_hosts) + return {"state": BACKUP if foreign else UNKNOWN, "pool": pool} + + +def mines_elsewhere(worker): + return (worker.get("mining") or {}).get("state") in ELSEWHERE diff --git a/dashboard/mining_dashboard/web/views/infra_views.py b/dashboard/mining_dashboard/web/views/infra_views.py index 1f392a510d..f6817a2178 100644 --- a/dashboard/mining_dashboard/web/views/infra_views.py +++ b/dashboard/mining_dashboard/web/views/infra_views.py @@ -180,12 +180,12 @@ def build_workers(workers, rigforge_release=None): "rejected_str": rejected_str, "invalid": invalid, "reject_flag": _reject_flag(accepted, rejected), - # Probe verdict + adoption (#1857): the client flags only api_ok False, and - # adopted decides whether that reads "api ⚠" (config to fix) or "not adopted". + "mining": worker.get("mining") or {"state": "unknown", "pool": None}, + "telemetry_h10": worker.get("telemetry_h10"), + "telemetry_h60": worker.get("telemetry_h60"), + "telemetry_h15": worker.get("telemetry_h15"), "api_ok": worker.get("api_ok"), "adopted": worker.get("adopted"), - # RigForge enriched feed (#235): version badge + health/power/tune/watchdog - # chips, or None for a plain-xmrig worker (renders nothing extra). "rigforge": _rigforge_display( worker.get("rigforge"), worker.get("status") == "online" ), diff --git a/dashboard/mining_dashboard/web/views/paused_badge.py b/dashboard/mining_dashboard/web/views/paused_badge.py index 7737dbe560..3acf09fac1 100644 --- a/dashboard/mining_dashboard/web/views/paused_badge.py +++ b/dashboard/mining_dashboard/web/views/paused_badge.py @@ -1,4 +1,5 @@ from mining_dashboard.config.config import monero_is_local +from mining_dashboard.service.mining_verdict import BACKUP def _paused_reason(data, metrics): @@ -19,7 +20,8 @@ def paused_badges(data, metrics): reason = _paused_reason(data, metrics) if not reason: return [] - moved = sum(1 for w in data.get("workers") or [] if w.get("mining_verdict") == "on_backup") + workers = data.get("workers") or [] + moved = sum(1 for w in workers if (w.get("mining") or {}).get("state") == BACKUP) text = f"Mining paused here: {reason}" if moved: text += f", {moved} rig{'' if moved == 1 else 's'} on backup pool" diff --git a/dashboard/tests/frontend/fixtures/state.json b/dashboard/tests/frontend/fixtures/state.json index 5701cc76e0..1f051a8a5a 100644 --- a/dashboard/tests/frontend/fixtures/state.json +++ b/dashboard/tests/frontend/fixtures/state.json @@ -714,6 +714,10 @@ "invalid": 0, "ip": "192.168.1.10", "ip_sort": 3232235786, + "mining": { + "pool": null, + "state": "unknown" + }, "name": "rig-alpha", "pool": "p2pool", "reject_flag": null, @@ -742,6 +746,9 @@ }, "rigforge_update": null, "status": "online", + "telemetry_h10": null, + "telemetry_h15": null, + "telemetry_h60": null, "uptime": 0, "uptime_str": "0m 0s" }, @@ -757,6 +764,10 @@ "invalid": 0, "ip": "192.168.1.11", "ip_sort": 3232235787, + "mining": { + "pool": null, + "state": "unknown" + }, "name": "rig-bravo", "pool": "p2pool", "reject_flag": null, @@ -785,6 +796,9 @@ }, "rigforge_update": null, "status": "offline", + "telemetry_h10": null, + "telemetry_h15": null, + "telemetry_h60": null, "uptime": 0, "uptime_str": "0m 0s" } diff --git a/dashboard/tests/service/test_data_helpers.py b/dashboard/tests/service/test_data_helpers.py index 7d3f96ca4b..ebf2392989 100644 --- a/dashboard/tests/service/test_data_helpers.py +++ b/dashboard/tests/service/test_data_helpers.py @@ -348,7 +348,7 @@ def test_proxy_kind_scales_khs_to_hs(self): # A successful probe carries api_ok=True (injected by get_stats); enrichment applies. extra = {"api_ok": True, "kind": "proxy", "uptime": 120, "hashrate": {"total": [1, 2, 3]}} [w] = _merge_direct_stats([self._worker()], [extra], "3333") - assert (w["h10"], w["h60"], w["h15"]) == (1000, 2000, 3000) + assert (w["telemetry_h10"], w["telemetry_h60"], w["telemetry_h15"]) == (1000, 2000, 3000) assert w["uptime"] == 120 assert w["active_pool"] == "3333" assert w["api_ok"] is True @@ -356,7 +356,7 @@ def test_proxy_kind_scales_khs_to_hs(self): def test_xmrig_kind_not_scaled(self): extra = {"api_ok": True, "uptime": 99, "hashrate": {"total": [10, 20, 30]}} [w] = _merge_direct_stats([self._worker()], [extra], "3344") - assert (w["h10"], w["h60"], w["h15"]) == (10, 20, 30) + assert (w["telemetry_h10"], w["telemetry_h60"], w["telemetry_h15"]) == (10, 20, 30) assert w["active_pool"] == "3344" assert w["api_ok"] is True diff --git a/dashboard/tests/service/test_mining_verdict.py b/dashboard/tests/service/test_mining_verdict.py new file mode 100644 index 0000000000..e1d73761db --- /dev/null +++ b/dashboard/tests/service/test_mining_verdict.py @@ -0,0 +1,189 @@ +import pytest + +from mining_dashboard.service import mining_verdict as mv +from mining_dashboard.service.data_helpers import ( + _aggregate_hashrate, + _aggregate_window_hashrates, + _merge_direct_stats, +) +from mining_dashboard.service.metrics import build_metrics +from mining_dashboard.web.views import paused_badge +from mining_dashboard.web.views.infra_views import build_workers + +HOSTS = {"192.168.1.5", "pithead.lan"} +PORT = 3333 + + +def _probe(pool="192.168.1.5:3333", uptime=600, **extra): + return {"api_ok": True, "connection": {"pool": pool, "uptime": uptime}, **extra} + + +def _verdict(payload): + return mv.mining_verdict(payload, HOSTS, PORT) + + +class TestMiningVerdict: + def test_here_on_host_and_port_match(self): + assert _verdict(_probe()) == {"state": "mining_here", "pool": "192.168.1.5:3333"} + + def test_here_ignores_case_and_ipv6_brackets(self): + assert _verdict(_probe("PitHead.LAN:3333"))["state"] == "mining_here" + v6 = mv.mining_verdict(_probe("[fd00::5]:3333"), {"fd00::5"}, PORT) + assert v6["state"] == "mining_here" + + def test_backup_carries_reported_pool(self): + assert _verdict(_probe("10.9.9.9:3333")) == {"state": "on_backup", "pool": "10.9.9.9:3333"} + + def test_same_host_other_port_is_not_here(self): + assert _verdict(_probe("192.168.1.5:3344"))["state"] == "on_backup" + + def test_unparseable_pool_is_unknown_not_here(self): + assert _verdict(_probe("192.168.1.5"))["state"] == "unknown" + assert _verdict(_probe("192.168.1.5:\u00b2"))["state"] == "unknown" + + def test_unmatched_name_is_unknown_not_backup(self): + assert _verdict(_probe("poolbox.lan:3333")) == { + "state": "unknown", + "pool": "poolbox.lan:3333", + } + + def test_foreign_ip_is_unknown_without_own_address(self): + loopback_only = {"127.0.0.1", "pithead.local"} + assert mv.mining_verdict(_probe("10.9.9.9:3333"), loopback_only, PORT)["state"] == "unknown" + + def test_documented_appliance_name_and_loopback_are_here(self, monkeypatch): + monkeypatch.setattr(mv.config, "HOST_IP", "127.0.0.1") + monkeypatch.setattr(mv.config, "STRATUM_BIND", "0.0.0.0") + monkeypatch.setattr(mv, "detect_host_ipv4", lambda: "192.168.1.42") + monkeypatch.setattr(mv.socket, "gethostname", lambda: "pithead") + hosts = mv.local_stratum_hosts() + for pool in ("pithead.local:3333", "127.0.0.1:3333", "localhost:3333"): + assert mv.mining_verdict(_probe(pool), hosts, PORT)["state"] == "mining_here" + + def test_disconnected_rig_is_not_connected(self): + assert _verdict(_probe("", 0)) == {"state": "not_connected", "pool": None} + + def test_no_connection_block_is_unknown(self): + assert _verdict({"api_ok": True, "hashrate": {}})["state"] == "unknown" + + def test_malformed_connection_is_unknown(self): + for conn in (None, "x", {}, {"pool": "192.168.1.5:3333"}, {"pool": 5, "uptime": 9}): + assert _verdict({"api_ok": True, "connection": conn})["state"] == "unknown" + assert _verdict(_probe(uptime=True))["state"] == "unknown" + assert _verdict(_probe(""))["state"] == "unknown" + + def test_failed_or_missing_probe_is_unknown(self): + assert _verdict({"api_ok": False})["state"] == "unknown" + assert _verdict({})["state"] == "unknown" + assert _verdict(None)["state"] == "unknown" + + def test_unknown_local_identity_never_claims_backup(self): + assert mv.mining_verdict(_probe("10.9.9.9:3333"), set(), PORT)["state"] == "unknown" + assert mv.mining_verdict(_probe("pithead.local:3333"), set(), PORT)["state"] == "unknown" + + def test_local_hosts_skip_unconfigured_and_wildcard(self, monkeypatch): + monkeypatch.setattr(mv.config, "HOST_IP", "Unknown Host") + monkeypatch.setattr(mv.config, "STRATUM_BIND", "0.0.0.0") + monkeypatch.setattr(mv, "detect_host_ipv4", lambda: None) + monkeypatch.setattr(mv.socket, "gethostname", lambda: "rigbox") + base = {"127.0.0.1", "::1", "localhost", "rigbox", "rigbox.local"} + assert mv.local_stratum_hosts() == base + monkeypatch.setattr(mv.config, "HOST_IP", "Pithead.Lan") + monkeypatch.setattr(mv.config, "STRATUM_BIND", "10.0.0.2") + monkeypatch.setattr(mv, "detect_host_ipv4", lambda: "192.168.1.5") + assert mv.local_stratum_hosts() == base | {"pithead.lan", "10.0.0.2", "192.168.1.5"} + + +@pytest.fixture +def local_pithead(monkeypatch): + monkeypatch.setattr(mv.config, "HOST_IP", "192.168.1.5") + monkeypatch.setattr(mv.config, "STRATUM_BIND", "0.0.0.0") + monkeypatch.setattr(mv.config, "STRATUM_PORT", 3333) + monkeypatch.setattr(mv, "detect_host_ipv4", lambda: None) + monkeypatch.setattr(mv.socket, "gethostname", lambda: "pithead") + + +def _row(name, h15=1000): + return { + "name": name, + "ip": "10.0.0.1", + "status": "online", + "h10": h15, + "h60": h15, + "h15": h15, + "h1h": h15, + "h12h": h15, + "h24h": h15, + "uptime": 0, + } + + +def _fleet(local_pithead): + probes = [ + _probe(hashrate={"total": [7, 7, 7]}), + _probe("10.9.9.9:3333", hashrate={"total": [5000, 5000, 5000]}), + _probe("pithead.local:3333", hashrate={"total": [3, 3, 3]}), + _probe("", 0, hashrate={"total": [0, 0, 0]}), + {"api_ok": True, "hashrate": {"total": [9, 9, 9]}}, + {}, + ] + rows = [_row(f"r{i}") for i in range(len(probes))] + return _merge_direct_stats(rows, probes, "3333") + + +class TestMergeAndCounters: + def test_each_row_carries_one_verdict(self, local_pithead): + states = [w["mining"]["state"] for w in _fleet(local_pithead)] + assert states == [ + "mining_here", + "on_backup", + "mining_here", + "not_connected", + "unknown", + "unknown", + ] + + def test_telemetry_is_separate_and_never_summed(self, local_pithead): + fleet = _fleet(local_pithead) + assert fleet[1]["telemetry_h15"] == 5000 + assert fleet[1]["h15"] == 1000 + total, _ = _aggregate_hashrate(fleet) + assert total == 1000 * 4 + + def test_total_excludes_elsewhere_rows(self, local_pithead): + total, total_h10 = _aggregate_hashrate(_fleet(local_pithead)) + assert (total, total_h10) == (4000, 4000) + windows = _aggregate_window_hashrates(_fleet(local_pithead)) + assert windows["24h"] == 4000 + + def test_workers_alive_excludes_elsewhere_rows(self, local_pithead): + fleet = _fleet(local_pithead) + m = build_metrics({"workers": fleet}, _mgr()) + assert (m.workers_online, m.workers_total) == (4, 6) + + def test_proxy_offline_row_with_live_telemetry_keeps_proxy_rate(self, local_pithead): + row = _row("gone", h15=0) + row["status"] = "offline" + [w] = _merge_direct_stats([row], [_probe(hashrate={"total": [800, 800, 800]})], "3333") + assert (w["h15"], w["telemetry_h15"]) == (0, 800) + assert _aggregate_hashrate([w]) == (0, 0) + + def test_state_rows_expose_verdict_and_telemetry(self, local_pithead): + rows = build_workers(_fleet(local_pithead)) + by = {r["name"]: r for r in rows} + assert by["r1"]["mining"] == {"state": "on_backup", "pool": "10.9.9.9:3333"} + assert by["r1"]["telemetry_h15"] == 5000 + assert by["r5"]["mining"] == {"state": "unknown", "pool": None} + assert by["r5"]["telemetry_h15"] is None + + def test_paused_badge_counts_merged_backup_rows(self, local_pithead, monkeypatch): + monkeypatch.setattr(paused_badge, "monero_is_local", lambda: True) + data = {"stratum_closed": True, "workers": _fleet(local_pithead)} + [badge] = paused_badge.paused_badges(data, None) + assert badge["text"] == "Mining paused here: stratum closed, 1 rig on backup pool" + + +def _mgr(): + from tests.service.test_metrics import _mgr as mgr + + return mgr() diff --git a/dashboard/tests/web/views/test_paused_badge.py b/dashboard/tests/web/views/test_paused_badge.py index 1c82c56d62..14c94536e5 100644 --- a/dashboard/tests/web/views/test_paused_badge.py +++ b/dashboard/tests/web/views/test_paused_badge.py @@ -10,7 +10,7 @@ def _local_node(monkeypatch): def _rigs(*verdicts): - return {"workers": [{"mining_verdict": v} for v in verdicts]} + return {"workers": [{"mining": {"state": v, "pool": None}} for v in verdicts]} def test_absent_while_serving(_metrics): From b6273ba0846a3cfb8eb8b627a6dfe3ee46e48c71 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:28:12 -0600 Subject: [PATCH 016/112] =?UTF-8?q?dashboard:=20fix=20#4057,=20#4058,=20#4?= =?UTF-8?q?060=20=E2=80=94=20reload=20a=20stale=20tab,=20explain=20failed?= =?UTF-8?q?=20actions=20on=20one,=20keep=20the=20config=20draft=20(#4096)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * dashboard: fix #4057, #4058, #4060 — reload a stale tab, say so when an action fails on one, keep the config draft Co-Authored-By: Claude Sonnet 5.5 * dashboard: close secret leaks in the stored config draft, fail open on blocked storage, retry a guard-blocked stale report Co-Authored-By: Claude Sonnet 5.5 * dashboard: store only the last valid redacted config draft, retry a guard-blocked reconnect reload Co-Authored-By: Claude Sonnet 5.5 * ci: clear the gitleaks history finding from the draft-redaction test Co-Authored-By: Claude Sonnet 5.5 * dashboard: keep the reload out of the poll's error path and treat a missing guard stamp as never reloaded Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- .config/gitleaksignore | 3 + CHANGELOG.md | 8 + .../web/static/app/components.mjs | 2 + .../web/static/app/freshness.mjs | 117 ++++++++ .../web/static/config/configdraft.mjs | 108 ++++++++ .../web/static/config/configview.mjs | 29 +- .../web/static/config/controlclient.mjs | 37 ++- .../mining_dashboard/web/static/dashboard.js | 25 +- .../web/static/system/osupdate.mjs | 21 +- .../browser/config-draft-reload.test.mjs | 88 ++++++ dashboard/tests/browser/config-draft.test.mjs | 2 +- .../tests/browser/osupdate-close.test.mjs | 24 +- .../frontend/app/connectionrecovery.test.mjs | 5 + .../frontend/app/dashboard-freshness.test.mjs | 98 +++++++ .../tests/frontend/app/dashboard.test.mjs | 46 +--- .../tests/frontend/app/freshness.test.mjs | 174 ++++++++++++ .../frontend/config/configdraft.test.mjs | 251 ++++++++++++++++++ .../tests/frontend/config/configview.test.mjs | 2 +- .../config/controlclient-stale.test.mjs | 177 ++++++++++++ .../tests/frontend/helpers/dashboardenv.mjs | 50 ++++ .../tests/frontend/helpers/stalepage.mjs | 43 +++ .../frontend/system/osupdate-stale.test.mjs | 161 +++++++++++ docs/dashboard.md | 35 ++- docs/dev/testing-strategy.md | 1 + 24 files changed, 1421 insertions(+), 86 deletions(-) create mode 100644 dashboard/mining_dashboard/web/static/app/freshness.mjs create mode 100644 dashboard/mining_dashboard/web/static/config/configdraft.mjs create mode 100644 dashboard/tests/browser/config-draft-reload.test.mjs create mode 100644 dashboard/tests/frontend/app/dashboard-freshness.test.mjs create mode 100644 dashboard/tests/frontend/app/freshness.test.mjs create mode 100644 dashboard/tests/frontend/config/configdraft.test.mjs create mode 100644 dashboard/tests/frontend/config/controlclient-stale.test.mjs create mode 100644 dashboard/tests/frontend/helpers/dashboardenv.mjs create mode 100644 dashboard/tests/frontend/helpers/stalepage.mjs create mode 100644 dashboard/tests/frontend/system/osupdate-stale.test.mjs diff --git a/.config/gitleaksignore b/.config/gitleaksignore index e82460f220..8c4f9b40ed 100644 --- a/.config/gitleaksignore +++ b/.config/gitleaksignore @@ -41,3 +41,6 @@ be95cee9f654b55eff157c89350913921fdb23ab:tests/os/selftest-miner-connection.sh:g # Current fixtures use SOAK_REPLY; these historical fingerprints exempt no later copies. 767ae18596b06a63ef98beccf31ac0a212786365:tests/os/soak-selftest.sh:generic-api-key:86 767ae18596b06a63ef98beccf31ac0a212786365:tests/os/soak-selftest.sh:generic-api-key:88 +# Synthetic secret strings in the first #4060 draft-redaction test commit; the current test file has no such literal at these lines. +ff9e346a13f2d1e645aa6bc5b0ff5cd85d8f6e69:dashboard/tests/frontend/config/configdraft.test.mjs:generic-api-key:72 +ff9e346a13f2d1e645aa6bc5b0ff5cd85d8f6e69:dashboard/tests/frontend/config/configdraft.test.mjs:generic-api-key:81 diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c9910098d..d779ed9413 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,14 @@ per the process in [`docs/dev/releasing.md`](docs/dev/releasing.md). ### Fixed +- A dashboard tab left open across a restart, rollback or update now reloads itself: it notices a + changed version or the first successful refresh after the disconnected banner, shows "Pithead was + updated or restarted. Reloading…" and reloads once the dashboard answers, at most once every 2 + minutes (#4057). OS-update and Configuration requests from a stale tab show "Pithead restarted or + the page is out of date. Reloading…" instead of `HTTP 401`, `HTTP 403` or the browser's own network + error, show the server's text for other failures, and a plain-text error no longer surfaces as a + JSON `SyntaxError` (#4058). An unsaved Configuration draft survives the reload in the tab's + `sessionStorage`, without any secret you typed (#4060). - Tor's `MaxClientCircuitsPending` is raised to 64 and `monero.out_peers` now defaults to 24 (was 48), so monerod, Tari and P2Pool onion dials no longer sit at Tor's pending-circuit ceiling right after boot. A `config.json` without `monero.out_peers` re-renders at 24 on the next apply; an explicit value diff --git a/dashboard/mining_dashboard/web/static/app/components.mjs b/dashboard/mining_dashboard/web/static/app/components.mjs index 922c19437e..164df44f3f 100644 --- a/dashboard/mining_dashboard/web/static/app/components.mjs +++ b/dashboard/mining_dashboard/web/static/app/components.mjs @@ -149,6 +149,7 @@ export function App({ state, connected, recoveryNeeded = false, + reloading = null, ui, onRange, onSort, @@ -190,6 +191,7 @@ export function App({
    <${NodeAlertBanner} alert=${state.node_alert} /> <${OsVerdictBanner} os=${state.os_update} /> + ${reloading ? html`
    ${reloading}
    ` : null} ${!connected ? html`
    Disconnected — showing data from ${state.last_update}. Retrying…${recoveryNeeded ? html`<${ConnectionRecovery} />` : null}
    ` : null} <${MinerConnection} /> ${ diff --git a/dashboard/mining_dashboard/web/static/app/freshness.mjs b/dashboard/mining_dashboard/web/static/app/freshness.mjs new file mode 100644 index 0000000000..0aa989af5d --- /dev/null +++ b/dashboard/mining_dashboard/web/static/app/freshness.mjs @@ -0,0 +1,117 @@ +export const UPDATED_MESSAGE = "Pithead was updated or restarted. Reloading…"; +export const STALE_MESSAGE = "Pithead restarted or the page is out of date. Reloading…"; +export const RELOAD_GUARD_MS = 120000; +export const GUARD_KEY = "pitheadAutoReloadAt"; +const RECONNECT_MS = 2000; +const RECONNECT_MAX = 300; + +export function createFreshness({ + reload = () => window.location.reload(), + store = { + getItem: (k) => sessionStorage.getItem(k), + setItem: (k, v) => sessionStorage.setItem(k, v), + }, + fetchFn = (url, opts) => fetch(url, opts), + now = () => Date.now(), + sleep = (ms) => new Promise((r) => setTimeout(r, ms)), + onChange = () => {}, +} = {}) { + let firstVersion = null; + let message = null; + let holds = 0; + let wanted = false; + let reloaded = false; + let waiting = false; + + function show(text) { + if (message === text) return; + message = text; + onChange(); + } + + function recentlyReloaded() { + try { + const stamp = Number(store.getItem(GUARD_KEY)); + const elapsed = now() - stamp; + return stamp > 0 && elapsed >= 0 && elapsed < RELOAD_GUARD_MS; + } catch { + return false; + } + } + + function stamp() { + try { + store.setItem(GUARD_KEY, String(now())); + } catch { + return; + } + } + + function attempt() { + if (reloaded || holds > 0 || recentlyReloaded()) return; + stamp(); + reloaded = true; + reload(); + } + + function request(text) { + show(text); + wanted = true; + attempt(); + } + + function goodPoll(version, recovered) { + if (firstVersion === null && version) firstVersion = version; + if (recovered || (version && version !== firstVersion)) request(UPDATED_MESSAGE); + else if (wanted) attempt(); + } + + async function reportPageStale() { + show(STALE_MESSAGE); + if (waiting) return; + waiting = true; + try { + for (let i = 0; i < RECONNECT_MAX && !reloaded; i++) { + const answered = await fetchFn("/api/state?range=1h", { + signal: AbortSignal.timeout(10000), + }).then( + (res) => res.ok, + () => false, + ); + if (answered) { + wanted = true; + attempt(); + if (reloaded || holds > 0) return; + } + await sleep(RECONNECT_MS); + } + } finally { + waiting = false; + } + } + + return { + goodPoll, + reportPageStale, + hold: () => { + holds++; + }, + release: () => { + holds = Math.max(0, holds - 1); + if (holds === 0 && wanted) attempt(); + }, + message: () => message, + }; +} + +let current = createFreshness(); +export const installFreshness = (deps) => (current = createFreshness(deps)); +export const reportPageStale = () => current.reportPageStale(); +export const holdAutoReload = () => current.hold(); +export const releaseAutoReload = () => current.release(); +export function holdWhile(owner, busy) { + if (!!owner.holding === busy) return; + owner.holding = busy; + if (busy) current.hold(); + else current.release(); +} diff --git a/dashboard/mining_dashboard/web/static/config/configdraft.mjs b/dashboard/mining_dashboard/web/static/config/configdraft.mjs new file mode 100644 index 0000000000..3f4d6a286a --- /dev/null +++ b/dashboard/mining_dashboard/web/static/config/configdraft.mjs @@ -0,0 +1,108 @@ +import { html } from "../app/preact.mjs"; +import { validNumber } from "./configfield.mjs"; +import { + editableCandidate, + isSecretSentinel, + jsonSyntaxError, + parseConfigJson, +} from "./configlogic.mjs"; + +export const DRAFT_KEY = "pitheadConfigDraft"; +const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +export const SECRET_PATHS = [ + ["dashboard", "auth", "password"], + ["telegram", "bot_token"], + ["workers", "api_token"], + ["monero", "node_username"], + ["monero", "node_password"], + ["monero", "view_key"], + ["tari", "view_key"], + ["p2pool", "stratum_password"], + ["healthchecks", "ping_url"], + ["notifications", "ntfy", "url"], + ["notifications", "ntfy", "token"], + ["xvb", "standby", "source"], +]; +const WORKER_TOKENS = ["token", "api_token"]; +const MAX_DRAFT_CHARS = 500000; + +const keep = (fetched) => (plainSentinel(fetched) ? fetched : ""); +const plainSentinel = (v) => + isSecretSentinel(v) && Object.values(v).every((x) => x === true || typeof x === "number"); +const typed = (v) => Boolean(v) && !plainSentinel(v); + +function scrubDocument(doc, cfg) { + const reset = (parent, key, fetchedParent) => { + if (!parent || typeof parent !== "object" || !typed(parent[key])) return; + parent[key] = keep(fetchedParent?.[key]); + }; + const at = (root, path) => + path.reduce((node, key) => (isObject(node) ? node[key] : undefined), root); + for (const path of SECRET_PATHS) + reset(at(doc, path.slice(0, -1)), path[path.length - 1], at(cfg, path.slice(0, -1))); + const hooks = at(doc, ["notifications", "webhooks"]); + const fetchedHooks = at(cfg, ["notifications", "webhooks"]); + for (let i = 0; Array.isArray(hooks) && i < hooks.length; i++) reset(hooks, i, fetchedHooks); + const workers = at(doc, ["workers", "list"]); + const fetchedWorkers = at(cfg, ["workers", "list"]); + for (let i = 0; Array.isArray(workers) && i < workers.length; i++) + for (const key of WORKER_TOKENS) reset(workers[i], key, fetchedWorkers?.[i]); +} + +export function redactDraft(text, cfg) { + const doc = JSON.parse(text); + scrubDocument(doc, cfg); + return JSON.stringify(doc, null, 2); +} + +export function syncDraft({ candidate, cfg, pristine, editText, drafts, jsonError }, store) { + if (!candidate) return; + try { + store ??= sessionStorage; + if ( + (editText === pristine && Object.values(drafts).every(validNumber)) || + editText.length > MAX_DRAFT_CHARS + ) { + store.removeItem(DRAFT_KEY); + return; + } + const text = jsonError ? JSON.stringify(candidate, null, 2) : editText; + store.setItem(DRAFT_KEY, JSON.stringify({ editText: redactDraft(text, cfg), drafts })); + } catch { + return; + } +} + +export function restoreDraft(fetchedText, store) { + let stash; + try { + store ??= sessionStorage; + stash = JSON.parse(store.getItem(DRAFT_KEY)); + } catch { + return null; + } + if (!isObject(stash) || typeof stash.editText !== "string") return null; + const drafts = Object.fromEntries( + Object.entries(isObject(stash.drafts) ? stash.drafts : {}).filter( + ([, raw]) => typeof raw === "string", + ), + ); + const error = jsonSyntaxError(stash.editText); + const staged = error ? { error } : parseConfigJson(stash.editText); + if (staged.error) + return { editText: stash.editText, drafts, jsonError: staged.error, draftRestored: true }; + const candidate = editableCandidate(staged.config); + const editText = + JSON.stringify(candidate) === JSON.stringify(staged.config) + ? stash.editText + : JSON.stringify(candidate, null, 2); + if (editText === fetchedText) + return Object.keys(drafts).length ? { drafts, draftRestored: true } : null; + return { candidate, editText, drafts, jsonError: null, draftRestored: true }; +} + +export const draftNote = (state) => + state.draftRestored + ? html`

    Your unsaved edits were restored after the page reloaded.

    ` + : null; diff --git a/dashboard/mining_dashboard/web/static/config/configview.mjs b/dashboard/mining_dashboard/web/static/config/configview.mjs index 030ea5c97a..adecff805b 100644 --- a/dashboard/mining_dashboard/web/static/config/configview.mjs +++ b/dashboard/mining_dashboard/web/static/config/configview.mjs @@ -10,6 +10,7 @@ import { Modal } from "../app/modal.mjs"; import { Component, createRef, html } from "../app/preact.mjs"; import { applyFailure, previewFailure, upgradeFailure } from "./applyfailure.mjs"; +import { draftNote, restoreDraft, syncDraft } from "./configdraft.mjs"; import { Field, validNumber } from "./configfield.mjs"; import { buildSections, @@ -25,7 +26,7 @@ import { import { PreviewModal } from "./configpreview.mjs"; import { coerceForType, focusSection, pathGet, pathSet } from "./configsync.mjs"; import { ConfigVersion } from "./configversion.mjs"; -import { controlCommitResult, requirePreviewResponse } from "./controlclient.mjs"; +import { controlCommitResult, controlFetch, requirePreviewResponse } from "./controlclient.mjs"; export { editableCandidate, PreviewModal }; @@ -52,12 +53,8 @@ export async function pollResult(id, skip, max = POLL_MAX, timeoutMessage) { continue; } if (res.status === 202) continue; - // Both flows recreate the dashboard container itself; while it restarts, the reverse proxy - // (caddy) stays up and answers 502/503/504 — the upstream is briefly gone, not failed. Ride - // these out like a dropped connection (#59/#622); the durable control result is the real - // outcome and `max` is the backstop. A real backend 500 (upstream up, erroring) still throws. if (res.status === 502 || res.status === 503 || res.status === 504) continue; - if (!res.ok) throw new Error(`HTTP ${res.status}`); + await requirePreviewResponse(res); const out = await res.json(); if (out.status === skip) continue; return out; @@ -99,15 +96,16 @@ export class ConfigView extends Component { this.modalRef = createRef(); } componentDidMount() { - this.load(); + this.load(true); } componentDidUpdate(_previousProps, { editText, pristine }) { + syncDraft(this.state); const dirty = this.state.editText !== this.state.pristine; if (dirty !== (editText !== pristine)) this.props.onDirtyChange?.(dirty); } - async load() { + async load(restore) { try { - const res = await fetch("/api/config"); + const res = await controlFetch("/api/config"); if (res.status === 404) return this.setState({ phase: "disabled" }); await requirePreviewResponse(res); const cfg = await res.json(); @@ -129,6 +127,8 @@ export class ConfigView extends Component { editText: text, jsonError: null, error: null, + draftRestored: false, + ...(restore && restoreDraft(text)), }); } catch (e) { this.setState({ phase: "error", error: String(e) }); @@ -228,7 +228,7 @@ export class ConfigView extends Component { this.setState({ phase: "previewing", error: null }); try { const proposed = staged.config; - const res = await fetch("/api/control/preview", { + const res = await controlFetch("/api/control/preview", { method: "POST", headers: CONTROL_HEADERS, body: JSON.stringify({ config: proposed }), @@ -261,12 +261,12 @@ export class ConfigView extends Component { body.payout_suffixes = this.state.payoutSuffixes; } const opts = { method: "POST", headers: CONTROL_HEADERS, body: JSON.stringify(body) }; - let res = null; // #2366: a restart (#622) can drop this request or answer 502/503/504 — poll the id below + let res = null; try { res = await fetch("/api/control/commit", opts); } catch {} const restarting = !res || [502, 503, 504].includes(res.status); - if (!restarting && !res.ok && res.status !== 202) throw new Error(`HTTP ${res.status}`); + if (!restarting) await requirePreviewResponse(res); const out = restarting ? await this.poll(id, "previewed") : await controlCommitResult(res, id, this.poll.bind(this)); @@ -406,6 +406,7 @@ export class ConfigView extends Component { ); return html`
    <${ConfigVersion} cfg=${this.state.cfg} /> + ${draftNote(this.state)} ${error ? previewFailure(error, this.props.appliance) : null} ${ lastApply?.status === "failed" @@ -450,12 +451,12 @@ export class ConfigView extends Component { // flow is the logic; UpgradeControl only maps its outcome onto UI state. The server answers 202 // straight away, so the real outcome arrives via pollResult, skipping "running" and the restart. export async function runUpgrade(version) { - const res = await fetch("/api/control/upgrade", { + const res = await controlFetch("/api/control/upgrade", { method: "POST", headers: CONTROL_HEADERS, body: JSON.stringify({ version }), }); - if (!res.ok && res.status !== 202) throw new Error(`HTTP ${res.status}`); + await requirePreviewResponse(res); const out = await res.json(); return pollResult(out.id, "running", UPGRADE_POLL_MAX); } diff --git a/dashboard/mining_dashboard/web/static/config/controlclient.mjs b/dashboard/mining_dashboard/web/static/config/controlclient.mjs index e24b9944b8..a21bdd8b3d 100644 --- a/dashboard/mining_dashboard/web/static/config/controlclient.mjs +++ b/dashboard/mining_dashboard/web/static/config/controlclient.mjs @@ -1,13 +1,44 @@ +import { reportPageStale, STALE_MESSAGE } from "../app/freshness.mjs"; + +export class ControlError extends Error { + toString() { + return this.message; + } +} + +export function staleError() { + reportPageStale(); + return new ControlError(STALE_MESSAGE); +} + +export async function controlFetch(url, opts) { + try { + return await fetch(url, opts); + } catch { + throw staleError(); + } +} + export async function controlCommitResult(response, id, poll) { - let result = await response.text(); - result = result ? JSON.parse(result) : await poll(id, "previewed"); + const text = await response.text(); + let result; + if (text) { + try { + result = JSON.parse(text); + } catch { + throw new ControlError(text); + } + } else { + result = await poll(id, "previewed"); + } if (!result || typeof result.status !== "string") throw new Error("Unreadable control response"); if (result.status === "pending" || result.status === "previewed") return poll(id, "previewed"); return result; } export async function requirePreviewResponse(response) { + if (response.status === 401 || response.status === 403) throw staleError(); if (!response.ok && response.status !== 202) { - throw new Error((await response.text()) || `HTTP ${response.status}`); + throw new ControlError((await response.text()) || `HTTP ${response.status}`); } } diff --git a/dashboard/mining_dashboard/web/static/dashboard.js b/dashboard/mining_dashboard/web/static/dashboard.js index ff2a6b364c..a97ad6e5d5 100644 --- a/dashboard/mining_dashboard/web/static/dashboard.js +++ b/dashboard/mining_dashboard/web/static/dashboard.js @@ -11,6 +11,7 @@ // (#903, tests/frontend/dashboard.test.mjs). import { App } from "./app/components.mjs"; +import { installFreshness } from "./app/freshness.mjs"; import { normalizeAvgWindow, normalizeSeries, @@ -58,6 +59,13 @@ export function initDashboard({ schedule = (fn, ms) => setInterval(fn, ms), renderApp = null, now = () => Date.now(), + reload, + store, + onWindowEvent = (fn) => { + if (typeof window === "undefined") return; + window.addEventListener("focus", fn); + window.addEventListener("visibilitychange", fn); + }, } = {}) { const root = doc.getElementById("app"); const pageUrl = new URL(href); @@ -87,8 +95,6 @@ export function initDashboard({ inspectWorker: null, }; - // Reflect the current theme onto ; the CSS palette (and the chart, which reads - // the resolved CSS variables) follow from there. function applyTheme(theme) { doc.documentElement.setAttribute("data-theme", theme); } @@ -97,14 +103,13 @@ export function initDashboard({ let connected = true; // false after a failed fetch (we keep showing the last snapshot) let disconnectedSince = null; let inflight = false; // guard against overlapping fetches if one is slow + const freshness = installFreshness({ reload, store, fetchFn, now, onChange: () => rerender() }); - // Tests inject renderApp to observe exactly what the App would receive; the browser default - // renders the real with the same props. const paint = renderApp ?? ((p) => render( - html`<${App} state=${p.state} connected=${p.connected} recoveryNeeded=${p.recoveryNeeded} ui=${p.ui} + html`<${App} state=${p.state} connected=${p.connected} recoveryNeeded=${p.recoveryNeeded} reloading=${p.reloading} ui=${p.ui} onRange=${p.onRange} onSort=${p.onSort} onView=${p.onView} onTheme=${p.onTheme} onZoom=${p.onZoom} onResetZoom=${p.onResetZoom} onToggleSeries=${p.onToggleSeries} onAvgWindow=${p.onAvgWindow} onDismissHint=${p.onDismissHint} @@ -117,6 +122,7 @@ export function initDashboard({ state, connected, recoveryNeeded: disconnectedSince !== null && now() - disconnectedSince >= 60000, + reloading: freshness.message(), ui, onRange: setRange, onSort, @@ -145,9 +151,8 @@ export function initDashboard({ async function tick() { if (inflight) return; inflight = true; + let fresh = null; try { - // A custom zoom window overrides the preset range; the server adapts resolution to it. The - // averaging window (#168) applies to both — the server selects which window's columns to plot. const base = ui.window ? "from=" + ui.window.from + "&to=" + ui.window.to : "range=" + encodeURIComponent(ui.range); @@ -157,10 +162,12 @@ export function initDashboard({ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), }); if (!res.ok) throw new Error("HTTP " + res.status); + const recovered = !connected; state = await res.json(); connected = true; disconnectedSince = null; if (state.page_title) doc.title = state.page_title; + fresh = { version: state.version?.text, recovered }; } catch (e) { connected = false; if (disconnectedSince === null) disconnectedSince = now(); @@ -169,6 +176,7 @@ export function initDashboard({ inflight = false; rerender(); } + if (fresh) freshness.goodPoll(fresh.version, fresh.recovered); } function setRange(r) { @@ -245,6 +253,9 @@ export function initDashboard({ rerender(); // paint the loading shell immediately const firstLoad = tick(); // first data load schedule(tick, REFRESH_MS); // then live updates + onWindowEvent(() => { + if (doc.visibilityState !== "hidden") tick(); + }); return { tick, firstLoad }; } diff --git a/dashboard/mining_dashboard/web/static/system/osupdate.mjs b/dashboard/mining_dashboard/web/static/system/osupdate.mjs index afc05d205f..3fba4215c0 100644 --- a/dashboard/mining_dashboard/web/static/system/osupdate.mjs +++ b/dashboard/mining_dashboard/web/static/system/osupdate.mjs @@ -12,8 +12,10 @@ // dashboard answers again; the post-reboot verdict (updated / rolled back) arrives via the // host-persisted state in state.os_update and renders as a banner. +import { holdWhile } from "../app/freshness.mjs"; import { Modal } from "../app/modal.mjs"; import { Component, createRef, html } from "../app/preact.mjs"; +import { controlFetch, requirePreviewResponse } from "../config/controlclient.mjs"; import { hostAnswered, osBadgeLabel, @@ -32,26 +34,22 @@ const OS_POLL_MAX = 450; // Resume attempts chained per Download/Retry click: 48 x ~10 min covers a very slow Tor night // while a genuinely dead route still terminates. const OS_RESUME_MAX = 48; +const BUSY_PHASES = ["checking", "downloading", "verifying", "installing", "rebooting"]; export const fmtMiB = (bytes) => Number.isFinite(bytes) && bytes > 0 ? Math.round(bytes / 1048576) + " MiB" : ""; -// POST one OS-update step; resolves to the intent id (the server always answers 202). export async function osAction(action, version) { const body = version ? { action, version } : { action }; - const res = await fetch("/api/control/os-update", { + const res = await controlFetch("/api/control/os-update", { method: "POST", headers: CONTROL_HEADERS, body: JSON.stringify(body), }); - if (!res.ok && res.status !== 202) throw new Error(`HTTP ${res.status}`); + await requirePreviewResponse(res); return (await res.json()).id; } -// Poll one intent to its terminal result, surfacing in-flight progress ("downloading", -// "installing") through onProgress instead of skipping it — the difference from configview's -// pollResult, which has no progress to show. Rides out dropped connections and proxy 50x the -// same way (the host result file is the durable outcome). export async function pollOsResult(id, onProgress, max = OS_POLL_MAX) { for (let i = 0; i < max; i++) { await new Promise((r) => setTimeout(r, POLL_MS)); @@ -63,7 +61,7 @@ export async function pollOsResult(id, onProgress, max = OS_POLL_MAX) { } if (res.status === 202 || res.status === 502 || res.status === 503 || res.status === 504) continue; - if (!res.ok) throw new Error(`HTTP ${res.status}`); + await requirePreviewResponse(res); const out = await res.json(); if (out.status === "downloading" || out.status === "installing") { if (onProgress) onProgress(out); @@ -146,13 +144,16 @@ export class OsUpdateControl extends Component { this.cancelled = false; this.modalRef = createRef(); } + componentWillUnmount() { + holdWhile(this, false); + } componentDidUpdate() { + holdWhile(this, BUSY_PHASES.includes(this.state.phase)); if (this.state.phase === "rebooting" && hostAnswered(this.props.os, this.rebootVerdictTs)) this.setState({ phase: "closed", confirmText: "" }); } cancel() { - const busy = ["checking", "downloading", "verifying", "installing", "rebooting"]; - if (busy.includes(this.state.phase)) return; + if (BUSY_PHASES.includes(this.state.phase)) return; this.modalRef.current?.close(); } stepPhase() { diff --git a/dashboard/tests/browser/config-draft-reload.test.mjs b/dashboard/tests/browser/config-draft-reload.test.mjs new file mode 100644 index 0000000000..5760dfd22e --- /dev/null +++ b/dashboard/tests/browser/config-draft-reload.test.mjs @@ -0,0 +1,88 @@ +import assert from "node:assert/strict"; +import { expect, test } from "./fixtures.mjs"; + +const config = { + dashboard: { energy: { cost_per_kwh: 0.17 } }, + _editable_keys: ["dashboard.energy.cost_per_kwh"], +}; +const NOTE = "Your unsaved edits were restored after the page reloaded."; + +test("an unsaved configuration draft survives a page reload; applied save and discard clear it", async ({ + page, + ui, +}) => { + await page.route("**/api/config", (route) => route.fulfill({ json: config })); + await page.route("**/api/control/preview", (route) => + route.fulfill({ + json: { id: "draft-preview", status: "previewed", changes: [{ msg: "Energy cost changed" }] }, + }), + ); + await page.route("**/api/control/commit", (route) => + route.fulfill({ json: { status: "applied" } }), + ); + ui.state.control_enabled = false; + await ui.mount(`import { App } from '/static/app/components.mjs'; +const state = ${JSON.stringify(ui.state)}; +const ui = {view:'config',range:'all',series:{},avg:'10m',theme:'auto',hintDismissed:true}; +const draw = () => render(html\`<\${App} state=\${state} connected=\${true} ui=\${ui} + onView=\${mode => {ui.view = mode; draw();}} />\`, document.getElementById('fixture')); +draw(); +`); + const nav = page.getByRole("navigation", { name: "View" }); + const marker = () => + nav.getByRole("button", { name: "Configuration — Unsaved changes", exact: true }); + const editor = page.locator(".config-view textarea"); + const stash = () => page.evaluate(() => sessionStorage.getItem("pitheadConfigDraft")); + const cost = async () => JSON.parse(await editor.inputValue()).dashboard.energy.cost_per_kwh; + const openPane = () => + page + .locator(".config-view summary") + .filter({ hasText: "the configuration this page sends" }) + .click(); + + await editor.waitFor({ state: "attached" }); + await openPane(); + await page + .locator(".config-view summary") + .filter({ hasText: /^Energy$/ }) + .click(); + const original = await editor.inputValue(); + await page.locator('.config-view input[type="number"]').fill("0.18"); + await marker().waitFor(); + + await page.reload(); + await marker().waitFor(); + await openPane(); + assert.equal(await cost(), 0.18); + await page.getByText(NOTE).waitFor(); + + await editor.fill('{"dashboard":'); + await page.reload(); + await marker().waitFor(); + await openPane(); + assert.equal(await cost(), 0.18); + await expect(page.locator(".config-view .status-bad")).toHaveCount(0); + + await page.getByRole("button", { name: "Discard edits", exact: true }).click(); + await marker().waitFor({ state: "detached" }); + assert.equal(await stash(), null); + await page.reload(); + await editor.waitFor({ state: "attached" }); + await marker().waitFor({ state: "detached" }); + assert.equal(await editor.inputValue(), original); + + await openPane(); + await editor.fill(JSON.stringify({ dashboard: { energy: { cost_per_kwh: 0.19 } } }, null, 2)); + await marker().waitFor(); + assert.notEqual(await stash(), null); + await page.getByRole("button", { name: "Save & preview changes" }).click(); + await page.getByRole("button", { name: "Confirm & apply", exact: true }).click(); + await page.getByText("Changes applied — only the affected containers were recreated.").waitFor(); + await marker().waitFor({ state: "detached" }); + assert.equal(await stash(), null); + await page.reload(); + await editor.waitFor({ state: "attached" }); + await marker().waitFor({ state: "detached" }); + assert.equal(await editor.inputValue(), original); + await expect(page.getByText(NOTE)).toHaveCount(0); +}); diff --git a/dashboard/tests/browser/config-draft.test.mjs b/dashboard/tests/browser/config-draft.test.mjs index 31296f99dd..0fe402121c 100644 --- a/dashboard/tests/browser/config-draft.test.mjs +++ b/dashboard/tests/browser/config-draft.test.mjs @@ -203,7 +203,7 @@ draw(); const valid = await editor.inputValue(); await page.getByRole("button", { name: "Save & preview changes" }).click(); await page.getByRole("button", { name: "Confirm & apply", exact: true }).click(); - await page.getByText("HTTP 500").waitFor(); + await page.getByText("boom", { exact: true }).waitFor(); assert.equal(await page.getByRole("button", { name: "Reload", exact: true }).count(), 0); await page.getByRole("button", { name: "Back to the form", exact: true }).click(); await marker().waitFor(); diff --git a/dashboard/tests/browser/osupdate-close.test.mjs b/dashboard/tests/browser/osupdate-close.test.mjs index 341b4e9e44..c1421d8383 100644 --- a/dashboard/tests/browser/osupdate-close.test.mjs +++ b/dashboard/tests/browser/osupdate-close.test.mjs @@ -77,13 +77,35 @@ test("staged reboot requires exact confirmation and Later erases it", async ({ p expect(actions).toEqual([]); }); +const STALE = "Pithead restarted or the page is out of date. Reloading…"; + +test("a refused action on a stale tab reloads the page once the dashboard answers", async ({ + page, + ui, +}) => { + let states = 0; + await page.route("**/api/control/os-update", (route) => route.fulfill({ status: 401 })); + await page.route("**/api/state?**", (route) => + ++states === 1 ? route.fulfill({ status: 503 }) : route.fulfill({ json: ui.state }), + ); + await mount(ui); + await page.getByRole("button", { name: "OS updates", exact: true }).click(); + const dialog = page.getByRole("dialog", { name: "System update" }); + await dialog.getByRole("button", { name: "Check now" }).click(); + await expect(dialog.getByText(STALE)).toBeVisible(); + await page.waitForEvent("load", { timeout: 15000 }); + expect(states).toBeGreaterThanOrEqual(2); + expect(await page.evaluate(() => sessionStorage.getItem("pitheadAutoReloadAt"))).not.toBeNull(); +}); + test("a host refusal never offers installation or reboot", async ({ page, ui }) => { await page.route("**/api/control/os-update", (route) => route.fulfill({ status: 403 })); + await page.route("**/api/state?**", (route) => route.fulfill({ status: 503 })); await mount(ui); await page.getByRole("button", { name: "OS updates", exact: true }).click(); const dialog = page.getByRole("dialog", { name: "System update" }); await dialog.getByRole("button", { name: "Check now" }).click(); - await expect(dialog.getByText("HTTP 403")).toBeVisible(); + await expect(dialog.getByText(STALE)).toBeVisible(); await expect(dialog.getByRole("button", { name: /Install|Reboot|Retry/ })).toHaveCount(0); await dialog.getByRole("button", { name: "Close", exact: true }).click(); await expect(dialog).toHaveCount(0); diff --git a/dashboard/tests/frontend/app/connectionrecovery.test.mjs b/dashboard/tests/frontend/app/connectionrecovery.test.mjs index f7ef0381bb..ae26b0d425 100644 --- a/dashboard/tests/frontend/app/connectionrecovery.test.mjs +++ b/dashboard/tests/frontend/app/connectionrecovery.test.mjs @@ -9,7 +9,11 @@ test("sustained failures show recovery advice at 60 seconds, clear on success, a let time = 0; let fail = false; let painted; + let reloads = 0; const d = initDashboard({ + reload: () => reloads++, + store: { getItem: () => null, setItem() {} }, + onWindowEvent() {}, doc: { getElementById: () => null, documentElement: { setAttribute() {} } }, storage: { getItem: () => null }, href: "https://pithead.test/", @@ -38,6 +42,7 @@ test("sustained failures show recovery advice at 60 seconds, clear on success, a await d.tick(); assert.equal(painted.connected, true); assert.equal(painted.recoveryNeeded, false); + assert.equal(reloads, 1); fail = true; time = 120000; await d.tick(); diff --git a/dashboard/tests/frontend/app/dashboard-freshness.test.mjs b/dashboard/tests/frontend/app/dashboard-freshness.test.mjs new file mode 100644 index 0000000000..30dd440cdc --- /dev/null +++ b/dashboard/tests/frontend/app/dashboard-freshness.test.mjs @@ -0,0 +1,98 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { initDashboard } from '../../../mining_dashboard/web/static/dashboard.js'; +import { + GUARD_KEY, RELOAD_GUARD_MS, UPDATED_MESSAGE, +} from '../../../mining_dashboard/web/static/app/freshness.mjs'; +import { aborted, httpError, makeEnv, ok } from '../helpers/dashboardenv.mjs'; + +const at = (version, extra = {}) => ok({ version: { text: version }, ...extra }); + +test('a changed version shows the notice and reloads once, on the poll that noticed', async () => { + const t = makeEnv({ responses: [at('v1'), at('v1'), at('v2'), at('v2')] }); + const d = initDashboard(t.env); + await d.firstLoad; + await d.tick(); + assert.equal(t.reloads.length, 0); + assert.equal(t.last().reloading, null); + await d.tick(); + assert.equal(t.reloads.length, 1); + assert.equal(t.last().reloading, UPDATED_MESSAGE); + await d.tick(); + assert.equal(t.reloads.length, 1); + assert.ok(Number(t.session[GUARD_KEY]) > 0); +}); + +test('the same version across many polls never reloads', async () => { + const t = makeEnv({ responses: Array.from({ length: 6 }, () => at('v1')) }); + const d = initDashboard(t.env); + await d.firstLoad; + for (let i = 0; i < 5; i++) await d.tick(); + assert.equal(t.reloads.length, 0); + assert.equal(t.last().reloading, null); +}); + +test('failing polls keep the banner and never reload; the first good poll reloads exactly once', async () => { + const t = makeEnv({ responses: [at('v1'), aborted(), httpError(502), aborted(), at('v1'), at('v1')] }); + const d = initDashboard(t.env); + await d.firstLoad; + for (let i = 0; i < 3; i++) { + await d.tick(); + assert.equal(t.last().connected, false); + assert.equal(t.reloads.length, 0); + assert.equal(t.last().reloading, null); + } + await d.tick(); + assert.equal(t.reloads.length, 1); + assert.equal(t.last().reloading, UPDATED_MESSAGE); + await d.tick(); + assert.equal(t.reloads.length, 1); +}); + +test('a trigger inside the two-minute window shows the notice without reloading, and polling still paints', async () => { + const recent = String(Date.now() - RELOAD_GUARD_MS / 2); + const t = makeEnv({ + session: { [GUARD_KEY]: recent }, + responses: [at('v1', { n: 1 }), at('v2', { n: 2 }), at('v2', { n: 3 })], + }); + const d = initDashboard(t.env); + await d.firstLoad; + await d.tick(); + assert.equal(t.reloads.length, 0); + assert.equal(t.last().reloading, UPDATED_MESSAGE); + assert.equal(t.last().state.n, 2); + await d.tick(); + assert.equal(t.reloads.length, 0); + assert.equal(t.last().state.n, 3); + assert.equal(t.session[GUARD_KEY], recent); +}); + +test('a trigger after the window has passed reloads and records the time', async () => { + const old = String(Date.now() - RELOAD_GUARD_MS - 1000); + const t = makeEnv({ session: { [GUARD_KEY]: old }, responses: [at('v1'), at('v2')] }); + const d = initDashboard(t.env); + await d.firstLoad; + await d.tick(); + assert.equal(t.reloads.length, 1); + assert.notEqual(t.session[GUARD_KEY], old); +}); + +test('focus and visibility each run one extra poll through the in-flight guard; hiding does not', async () => { + const t = makeEnv({ responses: [at('v1'), at('v1'), at('v1')] }); + const d = initDashboard(t.env); + await d.firstLoad; + assert.equal(t.windowHandlers.length, 1); + const fire = t.windowHandlers[0]; + t.doc.visibilityState = 'hidden'; + fire(); + assert.equal(t.fetches.length, 1); + t.doc.visibilityState = 'visible'; + const first = fire(); + fire(); + await new Promise((r) => setImmediate(r)); + assert.equal(t.fetches.length, 2); + await first; + await d.tick(); + assert.equal(t.fetches.length, 3); +}); diff --git a/dashboard/tests/frontend/app/dashboard.test.mjs b/dashboard/tests/frontend/app/dashboard.test.mjs index 03b77d455b..8f914b8dcd 100644 --- a/dashboard/tests/frontend/app/dashboard.test.mjs +++ b/dashboard/tests/frontend/app/dashboard.test.mjs @@ -16,52 +16,9 @@ import assert from 'node:assert/strict'; import { FETCH_TIMEOUT_MS, initDashboard, loadSeries, REFRESH_MS, windowFromUrl, } from '../../../mining_dashboard/web/static/dashboard.js'; +import { aborted, httpError, makeEnv, ok } from '../helpers/dashboardenv.mjs'; import { SERIES_KEYS } from '../../../mining_dashboard/web/static/app/logic.mjs'; -// --- fakes ------------------------------------------------------------------------------------ - -// Build an injectable environment. `responses` is a queue of response factories, one per expected -// fetch — a test that polls more than it queued fails loudly instead of hanging. -function makeEnv({ href = 'http://pithead.test/', stored = {}, responses = [] } = {}) { - const fetches = []; // { url, opts } per fetch, in order - const paints = []; // the full props object of every render, in order - const urls = []; // history.replaceState rewrites, in order - const doc = { - title: '', - documentElement: { - attrs: {}, - setAttribute(name, value) { this.attrs[name] = value; }, - }, - getElementById: () => null, - }; - let interval = null; - const env = { - doc, - href, - storage: { - getItem: (k) => (k in stored ? stored[k] : null), - setItem: (k, v) => { stored[k] = String(v); }, - }, - fetchFn: (url, opts) => { - fetches.push({ url, opts }); - assert.ok(responses.length > 0, `unexpected fetch: ${url}`); - return responses.shift()(url, opts); - }, - replaceUrl: (u) => urls.push(u), - schedule: (fn, ms) => { interval = { fn, ms }; }, - renderApp: (props) => paints.push(props), - }; - return { - env, fetches, paints, urls, doc, stored, - interval: () => interval, - last: () => paints[paints.length - 1], - }; -} - -const ok = (body) => () => Promise.resolve({ ok: true, json: async () => body }); -const httpError = (status) => () => Promise.resolve({ ok: false, status }); -const aborted = () => () => Promise.reject(new DOMException('signal timed out', 'TimeoutError')); - // A poll that hangs like a dropped Tor circuit: never settles on its own; the test fires the // abort the same way AbortSignal.timeout eventually would. function hangingPoll() { @@ -205,6 +162,7 @@ test('poll failure: disconnected banner state, last snapshot kept, recovery on n await d.tick(); // the next 30s tick reaches the server again assert.equal(t.last().connected, true); assert.equal(t.last().state.page_title, 'back'); + assert.equal(t.reloads.length, 1); }); test('poll failure: a non-2xx response counts as disconnected', async () => { diff --git a/dashboard/tests/frontend/app/freshness.test.mjs b/dashboard/tests/frontend/app/freshness.test.mjs new file mode 100644 index 0000000000..34e335c6b0 --- /dev/null +++ b/dashboard/tests/frontend/app/freshness.test.mjs @@ -0,0 +1,174 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { + createFreshness, GUARD_KEY, holdWhile, installFreshness, releaseAutoReload, holdAutoReload, + reportPageStale, RELOAD_GUARD_MS, STALE_MESSAGE, UPDATED_MESSAGE, +} from '../../../mining_dashboard/web/static/app/freshness.mjs'; + +function make({ responses = [], session = {}, clock = 1e12 } = {}) { + const reloads = []; + const polls = []; + const changes = []; + const deps = { + reload: () => reloads.push(1), + store: { + getItem: (k) => (k in session ? session[k] : null), + setItem: (k, v) => { session[k] = String(v); }, + }, + fetchFn: async (url) => { + polls.push(url); + const next = responses.shift(); + if (next instanceof Error) throw next; + return { ok: next !== false }; + }, + now: () => clock, + sleep: async () => {}, + onChange: () => changes.push(1), + }; + return { f: createFreshness(deps), deps, reloads, polls, changes, session }; +} + +test('reportPageStale shows its message, polls /api/state, and reloads only after an ok answer', async () => { + const t = make({ responses: [new TypeError('down'), false, true] }); + await t.f.reportPageStale(); + assert.equal(t.f.message(), STALE_MESSAGE); + assert.deepEqual(t.polls, ['/api/state?range=1h', '/api/state?range=1h', '/api/state?range=1h']); + assert.equal(t.reloads.length, 1); +}); + +test('reportPageStale never reloads while the server stays unreachable', async () => { + const t = make({ responses: Array.from({ length: 400 }, () => new TypeError('down')) }); + await t.f.reportPageStale(); + assert.equal(t.reloads.length, 0); + assert.equal(t.f.message(), STALE_MESSAGE); +}); + +test('concurrent reportPageStale calls share one reconnect loop', async () => { + const t = make({ responses: [true] }); + await Promise.all([t.f.reportPageStale(), t.f.reportPageStale()]); + assert.equal(t.polls.length, 1); + assert.equal(t.reloads.length, 1); +}); + +test('a held reload waits for release, then fires once', async () => { + const t = make(); + t.f.hold(); + t.f.goodPoll('v1', false); + t.f.goodPoll('v2', false); + assert.equal(t.f.message(), UPDATED_MESSAGE); + assert.equal(t.reloads.length, 0); + t.f.release(); + assert.equal(t.reloads.length, 1); + t.f.release(); + assert.equal(t.reloads.length, 1); +}); + +test('release without a pending reload does nothing; two holds need two releases', () => { + const t = make(); + t.f.hold(); + t.f.release(); + assert.equal(t.reloads.length, 0); + t.f.hold(); + t.f.hold(); + t.f.goodPoll('v1', false); + t.f.goodPoll('v2', false); + t.f.release(); + assert.equal(t.reloads.length, 0); + t.f.release(); + assert.equal(t.reloads.length, 1); +}); + +test('the guard blocks a second reload inside the window and allows it after', async () => { + const t = make({ responses: [true, true] }); + await t.f.reportPageStale(); + assert.equal(t.reloads.length, 1); + assert.equal(t.session[GUARD_KEY], '1000000000000'); + const again = createFreshness({ ...t.deps, now: () => 1e12 + RELOAD_GUARD_MS - 1 }); + again.goodPoll('v1', true); + assert.equal(t.reloads.length, 1); + assert.equal(again.message(), UPDATED_MESSAGE); + const later = createFreshness({ ...t.deps, now: () => 1e12 + RELOAD_GUARD_MS }); + later.goodPoll('v1', true); + assert.equal(t.reloads.length, 2); +}); + +test('unreadable or unwritable storage still reloads, once per page', () => { + const t = make(); + const broken = { + getItem: () => { throw new Error('denied'); }, + setItem: () => { throw new Error('denied'); }, + }; + const f = createFreshness({ ...t.deps, store: broken }); + f.goodPoll('v1', false); + f.goodPoll('v2', false); + f.goodPoll('v2', false); + assert.equal(f.message(), UPDATED_MESSAGE); + assert.equal(t.reloads.length, 1); +}); + +test('a guard-blocked reportPageStale keeps polling and reloads when the window has passed', async () => { + let clock = 1e12; + const t = make({ responses: Array.from({ length: 200 }, () => true), session: { [GUARD_KEY]: String(clock - 1000) } }); + const f = createFreshness({ + ...t.deps, + now: () => clock, + sleep: async () => { clock += 10000; }, + }); + await f.reportPageStale(); + assert.equal(t.reloads.length, 1); + assert.ok(t.polls.length > 5); + assert.ok(clock - 1e12 >= RELOAD_GUARD_MS - 1000); +}); + +test('the first version is remembered and a missing version never triggers', () => { + const t = make(); + t.f.goodPoll(undefined, false); + t.f.goodPoll('v1', false); + t.f.goodPoll(undefined, false); + t.f.goodPoll('v1', false); + assert.equal(t.reloads.length, 0); + assert.equal(t.f.message(), null); + assert.equal(t.changes.length, 0); +}); + +test('the module-level functions drive the installed instance; holdWhile is edge-triggered', async () => { + const t = make({ responses: [true] }); + installFreshness(t.deps); + const owner = {}; + holdWhile(owner, true); + holdWhile(owner, true); + await reportPageStale(); + assert.equal(t.reloads.length, 0); + holdWhile(owner, false); + holdWhile(owner, false); + assert.equal(t.reloads.length, 1); + holdAutoReload(); + releaseAutoReload(); +}); + +test('a guard-blocked reconnect reload is retried on a later good poll once the window passed', () => { + let clock = 1e12; + const t = make({ session: { [GUARD_KEY]: String(clock - 1000) } }); + const f = createFreshness({ ...t.deps, now: () => clock }); + f.goodPoll('v1', true); + f.goodPoll('v1', false); + assert.equal(t.reloads.length, 0); + clock += RELOAD_GUARD_MS; + f.goodPoll('v1', false); + assert.equal(t.reloads.length, 1); + f.goodPoll('v1', false); + assert.equal(t.reloads.length, 1); +}); + +test('a guard timestamp in the future (clock moved back) does not block reloads', () => { + const t = make({ session: { [GUARD_KEY]: String(1e12 + 5 * RELOAD_GUARD_MS) } }); + t.f.goodPoll('v1', true); + assert.equal(t.reloads.length, 1); +}); + +test('a tab that never auto-reloaded is not blocked, whatever the clock reads', () => { + const t = make({ clock: 1000 }); + t.f.goodPoll('v1', true); + assert.equal(t.reloads.length, 1); +}); diff --git a/dashboard/tests/frontend/config/configdraft.test.mjs b/dashboard/tests/frontend/config/configdraft.test.mjs new file mode 100644 index 0000000000..40cffb2ff7 --- /dev/null +++ b/dashboard/tests/frontend/config/configdraft.test.mjs @@ -0,0 +1,251 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; + +import { + DRAFT_KEY, + draftNote, + redactDraft, + restoreDraft, + SECRET_PATHS, + syncDraft, +} from "../../../mining_dashboard/web/static/config/configdraft.mjs"; +import { ConfigView } from "../../../mining_dashboard/web/static/config/configview.mjs"; +import { renderToString } from "../helpers/render.mjs"; +import { reply, withFetch } from "../helpers/stalepage.mjs"; + +const memory = (seed = {}) => { + const data = { ...seed }; + return { + data, + getItem: (k) => (k in data ? data[k] : null), + setItem: (k, v) => { + data[k] = String(v); + }, + removeItem: (k) => { + delete data[k]; + }, + }; +}; + +const CFG = { + dashboard: { auth: { password: { __secret__: true } }, energy: { cost_per_kwh: 0.1 } }, + _editable_keys: ["dashboard.energy.cost_per_kwh", "dashboard.auth.password"], +}; +const state = (over) => ({ + candidate: {}, + cfg: CFG, + pristine: '{"a":1}', + editText: '{"a":1}', + drafts: {}, + ...over, +}); + +test("syncDraft stores only a draft that differs from pristine and removes it when they match", () => { + const store = memory(); + syncDraft(state(), store); + assert.equal(DRAFT_KEY in store.data, false); + syncDraft(state({ editText: '{"a":2}', drafts: { "x.y": "1." } }), store); + const stored = JSON.parse(store.data[DRAFT_KEY]); + assert.deepEqual(JSON.parse(stored.editText), { a: 2 }); + assert.deepEqual(stored.drafts, { "x.y": "1." }); + syncDraft(state(), store); + assert.equal(DRAFT_KEY in store.data, false); +}); + +test("syncDraft leaves the stash alone before a config has loaded", () => { + const store = memory({ [DRAFT_KEY]: "kept" }); + syncDraft({ candidate: null, cfg: null, pristine: "", editText: "", drafts: {} }, store); + assert.equal(store.data[DRAFT_KEY], "kept"); +}); + +test("syncDraft survives unavailable storage", () => { + const broken = { + setItem: () => { + throw new Error("quota"); + }, + removeItem: () => { + throw new Error("quota"); + }, + }; + syncDraft(state({ editText: "x" }), broken); + syncDraft(state(), broken); +}); + +test("a typed secret never reaches storage; the sentinel is stored in its place", () => { + const plain = ["typed", "later"].join("-"); + const typed = JSON.stringify({ dashboard: { auth: { password: plain }, energy: {} } }); + const store = memory(); + syncDraft(state({ editText: typed }), store); + const raw = store.data[DRAFT_KEY]; + assert.equal(raw.includes(plain), false); + assert.deepEqual(JSON.parse(JSON.parse(raw).editText).dashboard.auth.password, { __secret__: true }); +}); + +const LEAKS = [ + ["a typed worker token", '{"workers":{"list":[{"token":"LEAK"}]}}'], + ["a typed worker api_token", '{"workers":{"list":[{"api_token":"LEAK"}]}}'], + ["a typed webhook", '{"notifications":{"webhooks":["https://hook.example/LEAK"]}}'], + ["a typed value for an unset secret", '{"monero":{"node_password":"LEAK"}}'], + ["a typed ntfy token", '{"notifications":{"ntfy":{"token":"LEAK"}}}'], + ["a typed view key", '{"tari":{"view_key":"LEAK"}}'], + ["a duplicate key", '{"telegram":{"bot_token":"LEAK"},"telegram":{}}'], + ["a sentinel with extra properties", '{"telegram":{"bot_token":{"__secret__":true,"v":"LEAK"}}}'], + ["a webhook sentinel with a text slot", '{"notifications":{"webhooks":[{"__secret__":true,"slot":"LEAK"}]}}'], + ["a typed object where a secret goes", '{"telegram":{"bot_token":{"x":"LEAK"}}}'], +]; +for (const [name, text] of LEAKS) { + test(`redactDraft never keeps ${name}`, () => { + assert.doesNotMatch(redactDraft(text, CFG), /LEAK/); + }); +} + +test("redactDraft resets a typed secret to what the server sent: its marker, or empty when unset", () => { + const cfg = { dashboard: { auth: { password: { __secret__: true } } } }; + const out = JSON.parse( + redactDraft('{"dashboard":{"auth":{"password":"new"}},"monero":{"node_password":"typed"}}', cfg), + ); + assert.deepEqual(out.dashboard.auth.password, { __secret__: true }); + assert.equal(out.monero.node_password, ""); +}); + +test("redactDraft leaves same-named non-secret keys alone", () => { + const text = '{"xvb":{"url":"na.example:4247"},"monero":{"source":"x"},"label":"password"}'; + assert.deepEqual(JSON.parse(redactDraft(text, CFG)), JSON.parse(text)); +}); + +test("an invalid-JSON draft stores the last valid candidate, never the broken text", () => { + const store = memory(); + const broken = '{"monero": {"node_password": "LEAK'; + syncDraft( + state({ candidate: { a: 2 }, editText: broken, jsonError: "Unexpected end of JSON input" }), + store, + ); + const raw = store.data[DRAFT_KEY]; + assert.doesNotMatch(raw, /LEAK/); + assert.deepEqual(JSON.parse(JSON.parse(raw).editText), { a: 2 }); +}); + +test("an invalid numeric field draft alone is kept and restored without a marker", () => { + const store = memory(); + syncDraft(state({ drafts: { "dashboard.energy.cost_per_kwh": "-" } }), store); + assert.ok(DRAFT_KEY in store.data); + const out = restoreDraft(JSON.stringify({ a: 1 }, null, 2), store); + assert.deepEqual(out, { drafts: { "dashboard.energy.cost_per_kwh": "-" }, draftRestored: true }); +}); + +test("a valid numeric field draft alone is not a draft", () => { + const store = memory({ [DRAFT_KEY]: "old" }); + syncDraft(state({ drafts: { "dashboard.energy.cost_per_kwh": "0.3" } }), store); + assert.equal(DRAFT_KEY in store.data, false); +}); + +test("a draft too large to store is dropped", () => { + const store = memory({ [DRAFT_KEY]: "old" }); + syncDraft(state({ editText: "x".repeat(600000) }), store); + assert.equal(DRAFT_KEY in store.data, false); +}); + +test("the client's secret paths match the server's SECRET_PATHS", () => { + const source = readFileSync( + new URL("../../../mining_dashboard/service/control_service.py", import.meta.url), + "utf8", + ); + const block = source.match(/^SECRET_PATHS = \[([\s\S]*?)^\]/m)[1]; + const server = [...block.matchAll(/^\s*\(([^)]*)\),/gm)].map(([, tuple]) => + [...tuple.matchAll(/"([^"]+)"/g)].map(([, key]) => key), + ); + assert.ok(server.length > 5); + assert.deepEqual(SECRET_PATHS, server); +}); + +test("redactDraft keeps the document when no secret was typed", () => { + const text = '{ "dashboard": {"auth": {"password": {"__secret__": true}}} }'; + assert.deepEqual(JSON.parse(redactDraft(text, CFG)), JSON.parse(text)); +}); + +test("restoreDraft returns the draft with its text, drafts and a restored flag", () => { + const stash = { editText: '{"a":2}', drafts: { "x.y": "1." } }; + const store = memory({ [DRAFT_KEY]: JSON.stringify(stash) }); + const out = restoreDraft('{"a":1}', store); + assert.equal(out.draftRestored, true); + assert.equal(out.jsonError, null); + assert.deepEqual(out.drafts, { "x.y": "1." }); + assert.deepEqual(out.candidate, { a: 2 }); + assert.equal(out.editText, '{"a":2}'); +}); + +test("restoreDraft keeps an invalid-JSON draft with its error", () => { + const store = memory({ [DRAFT_KEY]: JSON.stringify({ editText: '{"a": ', drafts: {} }) }); + const out = restoreDraft('{"a":1}', store); + assert.equal(out.editText, '{"a": '); + assert.ok(out.jsonError); + assert.equal(out.draftRestored, true); + assert.equal("candidate" in out, false); +}); + +test("restoreDraft drops garbage and a draft identical to the fetched config", () => { + for (const raw of [null, "not json", "[]", '"s"', '{"editText":5}', '{"editText":"{\\"a\\":1}"}']) { + const store = memory(raw === null ? {} : { [DRAFT_KEY]: raw }); + assert.equal(restoreDraft('{"a":1}', store), null, String(raw)); + } +}); + +test("restoreDraft keeps only string field drafts", () => { + const store = memory({ + [DRAFT_KEY]: JSON.stringify({ editText: '{"a":2}', drafts: { ok: "1.", bad: 5, worse: null } }), + }); + assert.deepEqual(restoreDraft('{"a":1}', store).drafts, { ok: "1." }); +}); + +test("draftNote renders one status line only for a restored draft", () => { + assert.equal(draftNote({ draftRestored: false }), null); + assert.match(renderToString(draftNote({ draftRestored: true })), /unsaved edits were restored/); +}); + +const FETCHED = { dashboard: { energy: { cost_per_kwh: 0.1 } }, _editable_keys: ["dashboard.energy.cost_per_kwh"] }; + +async function mounted(seed) { + const real = globalThis.sessionStorage; + const store = memory(seed); + globalThis.sessionStorage = store; + const view = new ConfigView({}); + view.setState = (patch) => Object.assign(view.state, patch); + await withFetch(async () => reply(200, "", FETCHED), () => view.load(true)); + return { view, store, restore: () => (globalThis.sessionStorage = real) }; +} + +test("ConfigView restores a stashed draft on load and flags it", async () => { + const draft = JSON.stringify({ dashboard: { energy: { cost_per_kwh: 0.25 } } }, null, 2); + const { view, restore } = await mounted({ [DRAFT_KEY]: JSON.stringify({ editText: draft, drafts: {} }) }); + restore(); + assert.equal(view.state.editText, draft); + assert.notEqual(view.state.editText, view.state.pristine); + assert.equal(view.state.candidate.dashboard.energy.cost_per_kwh, 0.25); + assert.equal(view.state.draftRestored, true); +}); + +test("ConfigView ignores the stash when load is not a restore (Discard edits)", async () => { + const draft = JSON.stringify({ dashboard: { energy: { cost_per_kwh: 0.25 } } }, null, 2); + const { view, store, restore } = await mounted({ [DRAFT_KEY]: JSON.stringify({ editText: draft, drafts: {} }) }); + await withFetch(async () => reply(200, "", FETCHED), () => view.load()); + view.componentDidUpdate({}, { editText: "", pristine: "" }); + restore(); + assert.equal(view.state.editText, view.state.pristine); + assert.equal(view.state.draftRestored, false); + assert.equal(DRAFT_KEY in store.data, false); +}); + +test("ConfigView persists an edit and clears the stash once the save is applied", async () => { + const { view, store, restore } = await mounted({}); + const field = view.state.sections + .flatMap((s) => s.fields) + .find(({ key }) => key === "dashboard.energy.cost_per_kwh"); + view.onFieldEdit(field, "0.3"); + view.componentDidUpdate({}, { editText: view.state.pristine, pristine: view.state.pristine }); + assert.match(JSON.parse(store.data[DRAFT_KEY]).editText, /0\.3/); + view.state.pristine = view.state.editText; + view.componentDidUpdate({}, { editText: view.state.editText, pristine: "" }); + restore(); + assert.equal(DRAFT_KEY in store.data, false); +}); diff --git a/dashboard/tests/frontend/config/configview.test.mjs b/dashboard/tests/frontend/config/configview.test.mjs index f5387aff69..9f1f07aac2 100644 --- a/dashboard/tests/frontend/config/configview.test.mjs +++ b/dashboard/tests/frontend/config/configview.test.mjs @@ -181,7 +181,7 @@ test("commit surfaces a real HTTP error from the commit request instead of polli ); assert.equal(calls, 1); assert.equal(view.state.phase, "error"); - assert.match(view.state.error, /HTTP 400/); + assert.equal(view.state.error, "bad request"); }); test("a rejected appliance preview labels the host validation log", async () => { diff --git a/dashboard/tests/frontend/config/controlclient-stale.test.mjs b/dashboard/tests/frontend/config/controlclient-stale.test.mjs new file mode 100644 index 0000000000..d592cacc7f --- /dev/null +++ b/dashboard/tests/frontend/config/controlclient-stale.test.mjs @@ -0,0 +1,177 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { + ConfigView, + pollResult, + runUpgrade, + UpgradeControl, +} from "../../../mining_dashboard/web/static/config/configview.mjs"; +import { controlCommitResult } from "../../../mining_dashboard/web/static/config/controlclient.mjs"; +import { installStaleProbe, reply, STALE, withFetch } from "../helpers/stalepage.mjs"; + +const ID = "33333333-3333-4333-8333-333333333333"; +const reject = () => Promise.reject(new TypeError("Failed to fetch")); + +function viewWith(preview = { id: ID, destructive: false }) { + const view = new ConfigView({}); + view.setState = (patch) => Object.assign(view.state, patch); + view.state.preview = preview; + view.state.candidate = {}; + return view; +} + +const shown = async (fn) => { + try { + await fn(); + } catch (e) { + return String(e); + } + assert.fail("expected a rejection"); +}; + +test("controlCommitResult shows a non-JSON body as text instead of a SyntaxError", async () => { + const text = await shown(() => + controlCommitResult({ text: async () => "gateway exploded" }, ID, async () => ({})), + ); + assert.equal(text, "gateway exploded"); +}); + +test("controlCommitResult still parses JSON and polls an empty body", async () => { + const applied = await controlCommitResult( + { text: async () => '{"status":"applied"}' }, + ID, + async () => assert.fail("no poll"), + ); + assert.equal(applied.status, "applied"); + const polled = await controlCommitResult({ text: async () => "" }, ID, async () => ({ + status: "applied", + })); + assert.equal(polled.status, "applied"); +}); + +for (const [name, stub] of [ + ["401 with a body", async () => reply(401, "login required")], + ["403", async () => reply(403)], +]) { + test(`commit: ${name} takes the stale-page path`, async () => { + const probe = installStaleProbe(); + const view = viewWith(); + await withFetch(stub, () => view.commit()); + await probe.settle(); + assert.equal(view.state.phase, "error"); + assert.equal(view.state.error, STALE); + assert.equal(probe.reloads.length, 1); + }); +} + +test("commit: a plain-text 500 shows its body and an empty one shows HTTP 500", async () => { + const probe = installStaleProbe(); + const view = viewWith(); + await withFetch(async () => reply(500, "disk full"), () => view.commit()); + assert.equal(view.state.error, "disk full"); + await withFetch(async () => reply(500), () => view.commit()); + assert.equal(view.state.error, "HTTP 500"); + await probe.settle(); + assert.equal(probe.reloads.length, 0); +}); + +test("commit: a 502 or a dropped connection mid-commit rides out via the poll, not the stale path", async () => { + for (const first of [async () => reply(502), reject]) { + const probe = installStaleProbe(); + const view = viewWith(); + let polled = null; + view.poll = async (id, skip) => { + polled = [id, skip]; + return { status: "applied" }; + }; + await withFetch(first, () => view.commit()); + await probe.settle(); + assert.deepEqual(polled, [ID, "previewed"]); + assert.equal(view.state.phase, "done"); + assert.equal(probe.reloads.length, 0); + } +}); + +test("commit: a non-JSON 200 body shows as text", async () => { + installStaleProbe(); + const view = viewWith(); + await withFetch(async () => reply(200, "proxy error"), () => view.commit()); + assert.equal(view.state.phase, "error"); + assert.equal(view.state.error, "proxy error"); +}); + +test("preview: a network rejection or 401/403 shows the stale message and reloads", async () => { + for (const stub of [reject, async () => reply(401), async () => reply(403)]) { + const probe = installStaleProbe(); + const view = viewWith(); + view.state.candidate = {}; + view.state.pristine = "{}"; + view.state.editText = "{}"; + await withFetch(stub, () => view.save()); + await probe.settle(); + assert.equal(view.state.error, STALE); + assert.equal(probe.reloads.length, 1); + } +}); + +test("preview: a plain-text 500 shows its body", async () => { + installStaleProbe(); + const view = viewWith(); + view.state.pristine = "{}"; + await withFetch(async () => reply(500, "preview crashed"), () => view.save()); + assert.equal(view.state.error, "preview crashed"); +}); + +test("load: 403 shows the stale message and reloads", async () => { + const probe = installStaleProbe(); + const view = new ConfigView({}); + view.setState = (patch) => Object.assign(view.state, patch); + await withFetch(async () => reply(403), () => view.load()); + await probe.settle(); + assert.equal(view.state.phase, "error"); + assert.equal(view.state.error, STALE); + assert.equal(probe.reloads.length, 1); +}); + +for (const [name, stub, expected] of [ + ["401", async () => reply(401, "login"), STALE], + ["403", async () => reply(403), STALE], + ["a network rejection", reject, STALE], + ["a plain-text 500", async () => reply(500, "upgrade refused"), "upgrade refused"], + ["an empty 500", async () => reply(500), "HTTP 500"], +]) { + test(`runUpgrade: ${name} shows ${expected === STALE ? "the stale message" : `"${expected}"`}`, async () => { + const probe = installStaleProbe(); + const text = await withFetch(stub, () => shown(() => runUpgrade("v9.9.9"))); + await probe.settle(); + assert.equal(text, expected); + assert.equal(probe.reloads.length, expected === STALE ? 1 : 0); + }); +} + +test("UpgradeControl shows the stale message alone in its failure result", async () => { + installStaleProbe(); + const control = new UpgradeControl({ update: { available: true, latest: "v9.9.9" }, enabled: true }); + control.setState = (patch) => Object.assign(control.state, patch); + await withFetch(async () => reply(403), () => control.run()); + assert.equal(control.state.phase, "failed"); + assert.equal(control.state.result.error, STALE); +}); + +test("pollResult: 401 and 403 take the stale path; a 500 shows its body; 502/503/504 and drops ride out", async () => { + const probe = installStaleProbe(); + for (const status of [401, 403]) { + const text = await withFetch(async () => reply(status), () => shown(() => pollResult(ID))); + assert.equal(text, STALE); + } + await probe.settle(); + assert.equal(probe.reloads.length, 1); + assert.equal( + await withFetch(async () => reply(500, "result store broke"), () => shown(() => pollResult(ID))), + "result store broke", + ); + const steps = [() => reply(502), () => reply(503), () => reply(504), reject, () => reply(200, "", { status: "applied" })]; + const out = await withFetch(async () => steps.shift()(), () => pollResult(ID, "running")); + assert.equal(out.status, "applied"); +}); diff --git a/dashboard/tests/frontend/helpers/dashboardenv.mjs b/dashboard/tests/frontend/helpers/dashboardenv.mjs new file mode 100644 index 0000000000..e019e78992 --- /dev/null +++ b/dashboard/tests/frontend/helpers/dashboardenv.mjs @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; + + +export function makeEnv({ href = 'http://pithead.test/', stored = {}, responses = [], session = {} } = {}) { + const fetches = []; + const paints = []; + const urls = []; + const doc = { + title: '', + documentElement: { + attrs: {}, + setAttribute(name, value) { this.attrs[name] = value; }, + }, + getElementById: () => null, + }; + const reloads = []; + const windowHandlers = []; + let interval = null; + const env = { + doc, + href, + storage: { + getItem: (k) => (k in stored ? stored[k] : null), + setItem: (k, v) => { stored[k] = String(v); }, + }, + fetchFn: (url, opts) => { + fetches.push({ url, opts }); + assert.ok(responses.length > 0, `unexpected fetch: ${url}`); + return responses.shift()(url, opts); + }, + replaceUrl: (u) => urls.push(u), + schedule: (fn, ms) => { interval = { fn, ms }; }, + renderApp: (props) => paints.push(props), + reload: () => reloads.push(1), + store: { + getItem: (k) => (k in session ? session[k] : null), + setItem: (k, v) => { session[k] = String(v); }, + }, + onWindowEvent: (fn) => windowHandlers.push(fn), + }; + return { + env, fetches, paints, urls, doc, stored, session, reloads, windowHandlers, + interval: () => interval, + last: () => paints[paints.length - 1], + }; +} + +export const ok = (body) => () => Promise.resolve({ ok: true, json: async () => body }); +export const httpError = (status) => () => Promise.resolve({ ok: false, status }); +export const aborted = () => () => Promise.reject(new DOMException('signal timed out', 'TimeoutError')); diff --git a/dashboard/tests/frontend/helpers/stalepage.mjs b/dashboard/tests/frontend/helpers/stalepage.mjs new file mode 100644 index 0000000000..82cf6ad878 --- /dev/null +++ b/dashboard/tests/frontend/helpers/stalepage.mjs @@ -0,0 +1,43 @@ +import { installFreshness } from "../../../mining_dashboard/web/static/app/freshness.mjs"; + +export const STALE = "Pithead restarted or the page is out of date. Reloading…"; + +export function installStaleProbe() { + const reloads = []; + const session = {}; + installFreshness({ + reload: () => reloads.push(1), + store: { + getItem: (k) => session[k] ?? null, + setItem: (k, v) => { + session[k] = String(v); + }, + }, + fetchFn: async () => ({ ok: true }), + sleep: async () => {}, + }); + return { reloads, settle: () => new Promise((r) => setImmediate(r)) }; +} + +export async function withFetch(stub, fn) { + const realFetch = globalThis.fetch; + const realTimeout = globalThis.setTimeout; + globalThis.fetch = stub; + globalThis.setTimeout = (cb) => { + cb(); + return 0; + }; + try { + return await fn(); + } finally { + globalThis.fetch = realFetch; + globalThis.setTimeout = realTimeout; + } +} + +export const reply = (status, text = "", json = {}) => ({ + status, + ok: status >= 200 && status < 300, + text: async () => text, + json: async () => json, +}); diff --git a/dashboard/tests/frontend/system/osupdate-stale.test.mjs b/dashboard/tests/frontend/system/osupdate-stale.test.mjs new file mode 100644 index 0000000000..1d14f05263 --- /dev/null +++ b/dashboard/tests/frontend/system/osupdate-stale.test.mjs @@ -0,0 +1,161 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { installFreshness } from "../../../mining_dashboard/web/static/app/freshness.mjs"; +import { + osAction, + OsUpdateControl, + pollOsResult, +} from "../../../mining_dashboard/web/static/system/osupdate.mjs"; +import { installStaleProbe, reply, STALE, withFetch } from "../helpers/stalepage.mjs"; + +const ID = "22222222-2222-4222-8222-222222222222"; + +const shown = async (fn) => { + try { + await fn(); + } catch (e) { + return String((e && e.message) || e); + } + assert.fail("expected a rejection"); +}; + +for (const [name, stub] of [ + ["401 with a body", async () => reply(401, "login required")], + ["403", async () => reply(403)], + ["a network rejection", async () => Promise.reject(new TypeError("Failed to fetch"))], + ["a Safari network rejection", async () => Promise.reject(new TypeError("Load failed"))], +]) { + test(`osAction: ${name} shows the stale-page message and reloads once /api/state answers`, async () => { + const probe = installStaleProbe(); + const text = await withFetch(stub, () => shown(() => osAction("install"))); + await probe.settle(); + assert.equal(text, STALE); + assert.equal(probe.reloads.length, 1); + }); +} + +test("osAction: 401 never reloads before /api/state answers ok", async () => { + const reloads = []; + const answers = [false, false, true]; + installFreshness({ + reload: () => reloads.push(1), + store: { getItem: () => null, setItem: () => {} }, + fetchFn: async () => ({ ok: answers.shift() }), + sleep: async () => {}, + }); + await withFetch( + async () => reply(401), + () => shown(() => osAction("check")), + ); + await new Promise((r) => setImmediate(r)); + assert.equal(answers.length, 0); + assert.equal(reloads.length, 1); +}); + +test("osAction: a plain-text 500 shows the body, an empty one shows HTTP 500", async () => { + const probe = installStaleProbe(); + const body = await withFetch( + async () => reply(500, "control spool is full"), + () => shown(() => osAction("download", "v1.2.3")), + ); + const bare = await withFetch( + async () => reply(500), + () => shown(() => osAction("download", "v1.2.3")), + ); + await probe.settle(); + assert.equal(body, "control spool is full"); + assert.equal(bare, "HTTP 500"); + assert.equal(probe.reloads.length, 0); +}); + +test("osAction: a 202 still resolves to the intent id", async () => { + const id = await withFetch( + async () => reply(202, "", { id: ID }), + () => osAction("check"), + ); + assert.equal(id, ID); +}); + +test("pollOsResult: 401 and 403 take the stale-page path, a plain-text 500 shows its body", async () => { + const probe = installStaleProbe(); + for (const status of [401, 403]) { + const text = await withFetch( + async () => reply(status), + () => shown(() => pollOsResult(ID)), + ); + assert.equal(text, STALE); + } + await probe.settle(); + assert.equal(probe.reloads.length, 1); + const body = await withFetch( + async () => reply(500, "runner crashed"), + () => shown(() => pollOsResult(ID)), + ); + assert.equal(body, "runner crashed"); +}); + +test("pollOsResult: 502, 503, 504 and dropped connections are still ridden out", async () => { + const probe = installStaleProbe(); + const steps = [ + () => reply(502), + () => reply(503), + () => reply(504), + () => Promise.reject(new TypeError("Failed to fetch")), + () => reply(200, "", { status: "checked" }), + ]; + const out = await withFetch( + async () => steps.shift()(), + () => pollOsResult(ID), + ); + await probe.settle(); + assert.equal(out.status, "checked"); + assert.equal(probe.reloads.length, 0); +}); + +test("a stale-page failure surfaces in the error pane as the message alone", async () => { + installStaleProbe(); + const view = new OsUpdateControl({ os: {}, enabled: true }); + view.setState = (patch) => Object.assign(view.state, patch); + await withFetch( + async () => reply(403), + () => view.check(), + ); + assert.equal(view.state.phase, "error"); + assert.equal(view.state.error, STALE); +}); + +test("an automatic reload is held through every in-progress phase and released on leaving them", () => { + const reloads = []; + const f = installFreshness({ + reload: () => reloads.push(1), + store: { getItem: () => null, setItem: () => {} }, + }); + const view = new OsUpdateControl({ os: { step: "idle" }, enabled: true }); + f.goodPoll("v1", false); + for (const phase of ["checking", "downloading", "verifying", "installing"]) { + view.state.phase = phase; + view.componentDidUpdate(); + f.goodPoll("v2", false); + assert.equal(reloads.length, 0, phase); + } + view.state.phase = "error"; + view.componentDidUpdate(); + assert.equal(reloads.length, 1); +}); + +test("unmounting mid-flow releases the hold", () => { + const reloads = []; + const f = installFreshness({ + reload: () => reloads.push(1), + store: { getItem: () => null, setItem: () => {} }, + }); + const view = new OsUpdateControl({ os: { step: "idle" }, enabled: true }); + view.state.phase = "downloading"; + view.componentDidUpdate(); + f.goodPoll("v1", false); + f.goodPoll("v2", false); + assert.equal(reloads.length, 0); + view.componentWillUnmount(); + assert.equal(reloads.length, 1); +}); diff --git a/docs/dashboard.md b/docs/dashboard.md index dd0ccbd728..21de9259ce 100644 --- a/docs/dashboard.md +++ b/docs/dashboard.md @@ -123,6 +123,15 @@ certificate's SHA-256 fingerprint with the current one on the appliance console; mismatch and accept only a match. Polling reconnects after trust is restored. The page cannot distinguish certificate, network and authentication failures. +A tab remembers the version from its first successful refresh. When a later refresh reports a +different version, or the first successful refresh after the disconnected banner, the page shows +"Pithead was updated or restarted. Reloading…" and reloads itself, so an open tab does not keep +running old code after a restart, rollback or update. The page reloads only after the dashboard +has answered, never into a browser error page, and at most once every 2 minutes per tab: a +trigger inside that window shows the message but leaves the reload to a later refresh. The page +also checks once when the window regains focus or becomes visible. An update-dialog step in +progress holds the reload until it finishes or fails; the Configuration draft is kept across it. + ### Top bar A status strip across the top shows the hostname, host telemetry (CPU, load, RAM, HugePages, disk), @@ -1242,9 +1251,17 @@ including invalid JSON. **Unsaved changes** beside the Configuration button mark edits. Return to Configuration to finish them; the marker clears after a successful apply or **Discard edits**. When the stack enters its synchronization screen the editor is hidden, not unmounted, so the draft and the marker are still there when the dashboard returns. The page only -shows the loading screen before its first state response, when no editor exists yet. Drafts are -not stored across a browser reload or close. The page cannot observe an HTTP authentication change, -so a re-authenticated tab keeps its draft until it is reloaded +shows the loading screen before its first state response, when no editor exists yet. An unsaved +draft is also kept in the tab's `sessionStorage`, so it survives a reload, automatic or manual: the +reloaded editor shows the draft, the **Unsaved changes** marker and a line saying the draft was +restored. Text that is not valid JSON is never stored: after a reload the editor shows the last +valid state of the draft, without the broken edit. **Discard edits**, **Discard draft and +reload from host** and a successful apply clear it; closing the tab drops it. The stored copy never +holds a secret you typed: every secret field the server masks (the API tokens and passwords, the +Monero and Tari view keys, the ping, ntfy and standby URLs, the webhook list and each worker token) +goes back to the value the page received, its `__secret__` marker or empty, so retype a new +secret after a reload. The page cannot observe an HTTP authentication +change, so a re-authenticated tab keeps its draft until it is reloaded ([#3323](https://github.com/p2pool-starter-stack/pithead/issues/3323) tracks a reset). The flow mirrors the CLI's `apply`: @@ -1296,7 +1313,12 @@ The flow mirrors the CLI's `apply`: draft with the host's configuration. After a successful apply, **Back to the form** reloads it. The error card shown when the commit request itself fails (an HTTP error, an unreadable response, or a poll timeout; a timeout does not mean the apply failed) offers the same two actions. Only a - failed first load, which has no draft, offers a plain **Reload**. + failed first load, which has no draft, offers a plain **Reload**. A non-2xx answer shows the + response text, or `HTTP` and the status when it is empty. A request that cannot reach the + dashboard, or that is answered 401 or 403 (what a tab from before a restart gets), shows + "Pithead restarted or the page is out of date. Reloading…" and the page reloads once the + dashboard answers. A restart during the apply is not that case: the commit keeps polling for + its result. Every reference setting belongs to a policy class. The ordinary allowlist covers routine operations; all remaining values confirm unless they are in the physical-presence set. Typed @@ -1691,7 +1713,10 @@ drives the appliance's A/B update from the browser, one explicit step at a time, control channel as everything else on this page: the dashboard container only asks, and the host re-derives and re-verifies every step itself. **Close** dismisses the dialog in one click, including after an update-check error, and returns focus to **OS updates**. **Retry** remains available -when there is a target to download. +when there is a target to download. A step that cannot reach the dashboard, or that is answered +401 or 403, shows "Pithead restarted or the page is out of date. Reloading…" and the page reloads +once the dashboard answers; any other refusal shows the response text, or `HTTP` and the status +when it is empty. 1. **Check.** The host asks the release API (over Tor) for the latest release and its OS bundle. The dashboard's passive new-release badge covers the same ground hourly, from inside the diff --git a/docs/dev/testing-strategy.md b/docs/dev/testing-strategy.md index 8e97813e15..6fa75f84fe 100644 --- a/docs/dev/testing-strategy.md +++ b/docs/dev/testing-strategy.md @@ -295,6 +295,7 @@ and require tier-4 appliance proof when changed. | Confirmed running earnings (#787): yesterday as a **calendar** day vs the trailing 24h/7d/30d spans, the DST-length day boundary, partial marking when a window outruns the recorded payout history, and one roll-up feeding both the dashboard card and `/earnings` | stored payouts | 1 ✅ (`test_earnings.py`, `test_telegram_commands.py`, `components.test.mjs`) | | Expected-vs-actual earnings summary (#808/#817): one shared 30d window, the combined Monero+XvB row (estimate folded on the expected side because win payouts are inseparable on the actual side), per-stream gates and honest degradation, Tari block counts, XvB win windowing, and the card's render branches in both views | metrics + stored payouts | 1 ✅ (`test_views.py` `TestEarningsVsActual`, `test_metrics.py`, `components.test.mjs`) | | Client entry point (#903): the 30s poll with its pre-tick abort so a hung Tor circuit can't latch the in-flight guard (#382), disconnected-banner state and recovery with the last snapshot kept, preference seeding from URL/localStorage through the normalizers, zoom/range/avg query building, and the handler wiring the App receives | injected fetch/storage/timer fakes | 1 ✅ (`dashboard.test.mjs`) | +| Stale-tab freshness (#4057, #4058, #4060): reload on a changed `state.version.text` or the first good poll after a disconnect, the once-per-2-minutes `sessionStorage` guard, the focus/visibility poll, the hold seam, the stale-page path for network failures and 401/403 on update and config requests with the server's text kept for other errors, and the Configuration draft kept across a reload without a typed secret | injected reload/store/fetch/timer fakes; Playwright reload | 1 ✅ (`freshness.test.mjs`, `dashboard-freshness.test.mjs`, `osupdate-stale.test.mjs`, `controlclient-stale.test.mjs`, `configdraft.test.mjs`) · browser ✅ (`config-draft-reload.test.mjs`, `osupdate-close.test.mjs`) | | P2Pool initial sidechain bootstrap stats are marked syncing, the served overview explains the state, and synced stats clear it | stopped P2Pool writer + injected pool stats | 1 ✅ (collector, API, frontend render, fault-leg failure/cleanup selftest) · 4 ▶ (`--fault-injection`, `fault_p2pool_sidechain_sync`) | | Dashboard reads correct live state on a real stack | real daemons | 4 ▶ | From 08d92fcd95f0edcfeb580fe7e68985e00e6dba99 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:46:45 -0600 Subject: [PATCH 017/112] =?UTF-8?q?dashboard:=20fix=20#4072=20=E2=80=94=20?= =?UTF-8?q?label=20where=20each=20rig=20mines,=20explain=20DOWN,=20list=20?= =?UTF-8?q?unnamed=20proxy=20clients=20(#4108)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * dashboard: fix #4072 — label where each rig mines, explain DOWN beside telemetry, list unnamed proxy clients Co-Authored-By: Claude Sonnet 5.5 * dashboard: explain a DOWN row that only has a decaying proxy rate; sort a null proxy name Co-Authored-By: Claude Sonnet 5.5 * dashboard: an unnamed proxy row opens no Worker Inspect through its badges either Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- dashboard/README.md | 7 +++ .../mining_dashboard/web/static/app/logic.mjs | 22 ++----- .../web/static/app/miningnote.mjs | 15 +++++ .../web/static/workers/workertable.mjs | 23 +++++--- .../mining_dashboard/web/views/infra_views.py | 18 +++--- dashboard/tests/browser/workers.test.mjs | 57 ++++++++++++++++++ .../frontend/app/components-workers.test.mjs | 58 +++++++++++++++++++ .../tests/frontend/app/logic-status.test.mjs | 21 +++++++ dashboard/tests/frontend/app/logic.test.mjs | 2 +- dashboard/tests/frontend/fixtures/state.json | 4 ++ .../tests/web/views/test_workers_rows.py | 37 ++++++++++++ 11 files changed, 230 insertions(+), 34 deletions(-) create mode 100644 dashboard/mining_dashboard/web/static/app/miningnote.mjs create mode 100644 dashboard/tests/web/views/test_workers_rows.py diff --git a/dashboard/README.md b/dashboard/README.md index 013315b774..d12c6e3dfb 100644 --- a/dashboard/README.md +++ b/dashboard/README.md @@ -32,6 +32,13 @@ The server is a data API; the browser renders the UI. There is no server-side te of online rows that are not `on_backup` or `not_connected`. The rig's own hashrate is the separate `telemetry_h10`, `telemetry_h60` and `telemetry_h15` fields (H/s, `null` when not probed); it is never summed into a total, and `h60`/`h15` stay the proxy's figures. + The Workers table (#4072) renders the verdict in each row as "on backup pool: ", "not + connected to this Pithead" or "mining location unknown", never lists a rig mining elsewhere as + alive, and explains a `DOWN` row that still has telemetry as "telemetry only — not this + Pithead" (or "no live connection here" when only the proxy's decaying rate remains). `telemetry_str` is the formatted `telemetry_h60`, shown in its own "Rig telemetry 1m" + column. A proxy client with no rig name (`-` or empty) is a row named `unnamed proxy worker + (
    )` with `unnamed: true`, shown with its address and proxy hashrate and without a + Worker Inspect link. - The client (`static/dashboard.js` + `components.mjs`) is a small Preact app, rendered with `htm` tagged templates (no JSX, no build step). It polls `/api/state` every 30s and renders declaratively, so the chart instance, table sort, selected range, and the simple/advanced view diff --git a/dashboard/mining_dashboard/web/static/app/logic.mjs b/dashboard/mining_dashboard/web/static/app/logic.mjs index 1dce2a8a23..0f8631227e 100644 --- a/dashboard/mining_dashboard/web/static/app/logic.mjs +++ b/dashboard/mining_dashboard/web/static/app/logic.mjs @@ -3,12 +3,8 @@ // without a browser or a JS toolchain. Presentation (components, the canvas) stays elsewhere and // is covered by the browser smoke test. -// Worker table columns, each carrying the state key it sorts on. Hashrate/uptime/IP and the -// accepted/rejected share counts sort numerically (raw values the server includes alongside the -// formatted strings); name sorts as text. The order matches the rendered s. -// The hashrate windows are named for what the proxy data is — 1m and 10m (#387) — matching the -// chart's averaging toggle and Telegram's "(10m avg)". The legacy h10 field isn't shown: via the -// proxy it's just a second copy of the 1m rate. +import { aliveHere } from "./miningnote.mjs"; + export const WORKER_COLUMNS = [ { label: "Worker", key: "name" }, { label: "IP", key: "ip_sort" }, @@ -17,17 +13,15 @@ export const WORKER_COLUMNS = [ { label: "10m", key: "h15" }, { label: "Accepted", key: "accepted" }, { label: "Rejected", key: "rejected" }, + { label: "Rig telemetry 1m", key: "telemetry_h60" }, ]; -// Return a new array of workers sorted by the given column index. ``idx == null`` keeps the -// server's order (online first, then name). Numeric columns compare numerically (so 1000 sorts -// after 9, not before it); everything else compares as a locale string. Never mutates input. export function sortWorkers(workers, idx, asc) { if (idx === null || idx === undefined) return workers; const key = WORKER_COLUMNS[idx].key; const sorted = [...workers].sort((a, b) => { - const va = a[key], - vb = b[key]; + const va = a[key] ?? -1, + vb = b[key] ?? -1; if (typeof va === "number" && typeof vb === "number") return va - vb; return String(va).localeCompare(String(vb)); }); @@ -525,10 +519,6 @@ export function bandBorderWidth(series, ctx, fullWidth) { return y0 === 0 && y1 === 0 ? 0 : fullWidth; } -// What to show in a worker's "Uptime" cell. For an online worker it's the real uptime; for an -// offline one it's "DOWN" — never the raw duration, which for a disconnected worker kept climbing -// and read like uptime when it was really downtime (#169). The raw numeric `uptime` is left on the -// row for client-side column sorting; only the displayed string changes. export function uptimeCell(worker) { - return worker.status === "online" ? worker.uptime_str : "DOWN"; + return aliveHere(worker) ? worker.uptime_str : "DOWN"; } diff --git a/dashboard/mining_dashboard/web/static/app/miningnote.mjs b/dashboard/mining_dashboard/web/static/app/miningnote.mjs new file mode 100644 index 0000000000..018522d088 --- /dev/null +++ b/dashboard/mining_dashboard/web/static/app/miningnote.mjs @@ -0,0 +1,15 @@ +export function aliveHere(worker) { + return ( + worker.status === "online" && !["on_backup", "not_connected"].includes(worker.mining?.state) + ); +} + +export function miningNote(worker) { + const { state, pool } = worker.mining || {}; + if (state === "on_backup") return "on backup pool: " + pool; + if (state === "not_connected") return "not connected to this Pithead"; + if (state === "unknown") return "mining location unknown"; + if (aliveHere(worker)) return null; + if (worker.telemetry_h60 > 0) return "telemetry only — not this Pithead"; + return worker.h60 > 0 || worker.h15 > 0 ? "no live connection here" : null; +} diff --git a/dashboard/mining_dashboard/web/static/workers/workertable.mjs b/dashboard/mining_dashboard/web/static/workers/workertable.mjs index 87e630e8a1..5d1b673de5 100644 --- a/dashboard/mining_dashboard/web/static/workers/workertable.mjs +++ b/dashboard/mining_dashboard/web/static/workers/workertable.mjs @@ -1,4 +1,5 @@ import { sortWorkers, uptimeCell, WORKER_COLUMNS } from "../app/logic.mjs"; +import { aliveHere, miningNote } from "../app/miningnote.mjs"; import { html } from "../app/preact.mjs"; // --- Workers table (WORKER_COLUMNS + sortWorkers live in logic.mjs, unit-tested) ----- @@ -118,15 +119,20 @@ function WorkersTable({ workers, summary, ui, onSort, hostIp, stratumPort, local )} - ${rows.map( - (w) => html` - + ${rows.map((w) => { + const inspect = w.unnamed ? null : onInspect; + return html` + ${ - onInspect - ? html`` : w.name - } <${PoolBadge} pool=${w.pool} /><${ApiBadge} w=${w} onInspect=${onInspect} /><${RigForgeChips} rf=${w.rigforge} /><${RigUpdateBadge} up=${w.rigforge_update} name=${w.name} onInspect=${onInspect} /> + } <${PoolBadge} pool=${w.pool} /><${ApiBadge} w=${w} onInspect=${inspect} /><${RigForgeChips} rf=${w.rigforge} /><${RigUpdateBadge} up=${w.rigforge_update} name=${w.name} onInspect=${inspect} />${ + miningNote(w) + ? html` ${miningNote(w)}` + : null + } ${w.ip} ${uptimeCell(w)} ${w.h60_str} @@ -137,8 +143,9 @@ function WorkersTable({ workers, summary, ui, onSort, hostIp, stratumPort, local ? html` ${w.reject_flag.text}` : null } - `, - )} + ${w.telemetry_str} + `; + })}
    diff --git a/dashboard/mining_dashboard/web/views/infra_views.py b/dashboard/mining_dashboard/web/views/infra_views.py index f6817a2178..059b4ee2d8 100644 --- a/dashboard/mining_dashboard/web/views/infra_views.py +++ b/dashboard/mining_dashboard/web/views/infra_views.py @@ -137,7 +137,7 @@ def build_workers(workers, rigforge_release=None): """Worker rows as data: raw numeric fields (for client-side sorting) alongside their formatted display strings, plus a pool token for the badge. Online first, then by name.""" rows = [] - sorted_workers = sorted(workers, key=lambda x: (x["status"] != "online", x["name"])) + sorted_workers = sorted(workers, key=lambda x: (x["status"] != "online", x["name"] or "")) for worker in sorted_workers: try: @@ -152,24 +152,22 @@ def build_workers(workers, rigforge_release=None): uptime = worker.get("uptime", 0) h60 = worker.get("h60", 0) h15 = worker.get("h15", 0) - # Per-worker share health (Issue #82). Raw counts for client-side sorting; a display - # string that appends invalid only when it's non-zero (keeps the common case clean); - # and an optional warning flag the client renders when the reject rate is high. accepted = worker.get("accepted", 0) rejected = worker.get("rejected", 0) invalid = worker.get("invalid", 0) rejected_str = f"{rejected:,} (+{invalid:,} inv)" if invalid else f"{rejected:,}" + unnamed = str(worker["name"] or "").strip() in ("", "-") + telemetry_h60 = worker.get("telemetry_h60") rows.append( { - "name": worker["name"], + "name": f"unnamed proxy worker ({worker['ip']})" if unnamed else worker["name"], + "unnamed": unnamed, "ip": worker["ip"], "ip_sort": _ip_to_sort_int(worker.get("ip", "0.0.0.0")), "pool": pool, "status": "online" if worker["status"] == "online" else "offline", "uptime": uptime, "uptime_str": format_duration(uptime), - # No h10 here: the table shows the 1m (h60) and 10m (h15) windows — via the - # proxy the legacy h10 field is just a second copy of the 1m rate (#387). "h60": h60, "h60_str": format_hashrate(h60), "h15": h15, @@ -182,14 +180,16 @@ def build_workers(workers, rigforge_release=None): "reject_flag": _reject_flag(accepted, rejected), "mining": worker.get("mining") or {"state": "unknown", "pool": None}, "telemetry_h10": worker.get("telemetry_h10"), - "telemetry_h60": worker.get("telemetry_h60"), + "telemetry_h60": telemetry_h60, + "telemetry_str": "—" + if telemetry_h60 is None + else format_hashrate(telemetry_h60), "telemetry_h15": worker.get("telemetry_h15"), "api_ok": worker.get("api_ok"), "adopted": worker.get("adopted"), "rigforge": _rigforge_display( worker.get("rigforge"), worker.get("status") == "online" ), - # {available, latest, url} | None — this rig runs an older RigForge (#596). "rigforge_update": rigforge_update_for(worker, rigforge_release), } ) diff --git a/dashboard/tests/browser/workers.test.mjs b/dashboard/tests/browser/workers.test.mjs index d7b07a9e24..39bc072a4c 100644 --- a/dashboard/tests/browser/workers.test.mjs +++ b/dashboard/tests/browser/workers.test.mjs @@ -95,3 +95,60 @@ render(html\`<\${Harness} />\`, document.getElementById('fixture')); await expect(dialog).toBeVisible(); expect(reads).toBe(2); }); + +test("the Workers table labels each mining verdict and lists an unnamed proxy client", async ({ + page, + ui, +}) => { + const base = ui.state.workers[0]; + const row = (name, ip, extra) => ({ ...base, name, ip, ...extra }); + ui.state.workers = [ + row("rig-here", "10.0.0.1", { + status: "online", + mining: { state: "mining_here", pool: "h:3333" }, + }), + row("rig-away", "10.0.0.2", { + status: "online", + mining: { state: "on_backup", pool: "backup.example:3333" }, + telemetry_h60: 31000, + telemetry_str: "31.00 kH/s", + }), + row("rig-dark", "10.0.0.3", { + status: "offline", + mining: { state: "not_connected", pool: null }, + }), + row("rig-unk", "10.0.0.4", { status: "online", mining: { state: "unknown", pool: null } }), + row("rig-tele", "10.0.0.5", { + status: "offline", + mining: { state: "mining_here", pool: null }, + telemetry_h60: 3100, + telemetry_str: "3.10 kH/s", + }), + row("unnamed proxy worker (10.0.0.9)", "10.0.0.9", { + status: "online", + unnamed: true, + mining: { state: "unknown", pool: null }, + }), + ]; + await ui.open(); + await page + .getByRole("group", { name: "Dashboard view" }) + .getByRole("button", { name: "Advanced", exact: true }) + .click(); + + const table = page.locator("#workers-table"); + const rowOf = (text) => table.locator("tbody tr", { hasText: text }); + await expect(rowOf("rig-away")).toContainText("on backup pool: backup.example:3333"); + await expect(rowOf("rig-away")).toContainText("DOWN"); + await expect(rowOf("rig-away")).toContainText("31.00 kH/s"); + await expect(rowOf("rig-dark")).toContainText("not connected to this Pithead"); + await expect(rowOf("rig-unk")).toContainText("mining location unknown"); + await expect(rowOf("rig-tele")).toContainText("telemetry only — not this Pithead"); + await expect(rowOf("rig-here")).not.toContainText("on backup pool"); + await expect(rowOf("rig-here")).toHaveClass("status-ok"); + await expect(rowOf("rig-away")).toHaveClass("status-bad"); + await expect(rowOf("rig-dark")).toHaveClass("status-bad"); + const unnamed = rowOf("unnamed proxy worker (10.0.0.9)"); + await expect(unnamed).toContainText("10.0.0.9"); + await expect(unnamed.locator(".worker-name-link")).toHaveCount(0); +}); diff --git a/dashboard/tests/frontend/app/components-workers.test.mjs b/dashboard/tests/frontend/app/components-workers.test.mjs index be06a7ecd8..915ea78695 100644 --- a/dashboard/tests/frontend/app/components-workers.test.mjs +++ b/dashboard/tests/frontend/app/components-workers.test.mjs @@ -174,3 +174,61 @@ test('WorkersTable badges a rig running an older RigForge — and only that rig none.workers.forEach((w) => (w.rigforge_update = null)); assert.doesNotMatch(renderApp({ state: none }), /RigForge release is available/); }); + +const rowOf = (html, name) => html.match(new RegExp(`(?:(?!)[\\s\\S])*${name}[\\s\\S]*?`))[0]; + +test('WorkersTable labels where each rig mines and never shows an elsewhere rig alive (#4072)', () => { + const s = clone(); + const [a, b] = s.workers; + Object.assign(a, { name: 'rig-away', mining: { state: 'on_backup', pool: 'backup.example:3333' } }); + Object.assign(b, { name: 'rig-dark', mining: { state: 'not_connected', pool: null } }); + s.workers.push({ ...a, name: 'rig-unk', mining: { state: 'unknown', pool: null } }); + s.workers.push({ ...a, name: 'rig-here', mining: { state: 'mining_here', pool: 'h:3333' } }); + const html = renderApp({ state: s }); + const away = rowOf(html, 'rig-away'); + assert.match(away, /on backup pool: backup\.example:3333/); + assert.match(away, /DOWN/); + assert.match(away, /^ { + const s = clone(); + Object.assign(s.workers[0], { + name: 'rig-tele', + status: 'offline', + mining: { state: 'mining_here', pool: null }, + telemetry_h60: 31000, + telemetry_str: '31.00 kH/s', + }); + const row = rowOf(renderApp({ state: s }), 'rig-tele'); + assert.match(row, /DOWN/); + assert.match(row, /telemetry only — not this Pithead/); + assert.match(row, /]*>31\.00 kH\/s<\/td>/); + assert.match(renderApp({ state: s }), />Rig telemetry 1m { + const s = clone(); + s.control_enabled = true; + Object.assign(s.workers[0], { + name: 'unnamed proxy worker (10.0.0.9)', + unnamed: true, + ip: '10.0.0.9', + api_ok: false, + adopted: false, + rigforge_update: { available: true, latest: 'v1.11.2', url: 'https://h/v1.11.2' }, + }); + Object.assign(s.workers[1], { api_ok: false, adopted: false }); + const html = renderApp({ state: s }); + const row = rowOf(html, 'unnamed proxy worker'); + assert.match(row, /10\.0\.0\.9/); + assert.match(row, /not adopted/); + assert.doesNotMatch(row, /`; +} function Header({ state, theme, onTheme }) { const s = state.system, @@ -24,6 +36,7 @@ function Header({ state, theme, onTheme }) { <${VersionBadge} version=${state.version} /> <${UpdateBadge} update=${state.update} /> <${ThemeSwitcher} theme=${theme} onTheme=${onTheme} /> + <${SignOut} state=${state} /> <${UpgradeControl} update=${state.update} enabled=${state.control_enabled && !appliance} appliance=${appliance} /> ${ diff --git a/dashboard/mining_dashboard/web/static/config/configwarnings.mjs b/dashboard/mining_dashboard/web/static/config/configwarnings.mjs index 3f07d325ae..49982e2ad2 100644 --- a/dashboard/mining_dashboard/web/static/config/configwarnings.mjs +++ b/dashboard/mining_dashboard/web/static/config/configwarnings.mjs @@ -14,7 +14,7 @@ export const FIELD_WARNINGS = { "tari.wallet_address": "Tari payout address is changing — future merge-mining rewards go to the new address.", "dashboard.auth.password": - "Dashboard login password changing — every other signed-in session is logged out, a mistyped password locks this session out too, and on the appliance it is also the console root login. Keep another way to reach this machine handy before you confirm.", + "Dashboard login password changing — every signed-in session is logged out, this one included, a mistyped password locks you out, and on the appliance it is also the console root login. Keep another way to reach this machine handy before you confirm.", "telegram.enabled": "Telegram bot — turning it off stops every Telegram alert, the wallet-change and clearnet-exposure tamper alarms included.", "telegram.bot_token": diff --git a/dashboard/mining_dashboard/web/static/dashboard.css b/dashboard/mining_dashboard/web/static/dashboard.css index 6133b2b421..4b34787932 100644 --- a/dashboard/mining_dashboard/web/static/dashboard.css +++ b/dashboard/mining_dashboard/web/static/dashboard.css @@ -10,3 +10,4 @@ @import "./styles/topology.css"; @import "./styles/config.css"; @import "./styles/workers.css"; +@import "./styles/login.css"; diff --git a/dashboard/mining_dashboard/web/static/login.js b/dashboard/mining_dashboard/web/static/login.js new file mode 100644 index 0000000000..e56ef01322 --- /dev/null +++ b/dashboard/mining_dashboard/web/static/login.js @@ -0,0 +1,36 @@ +const form = document.getElementById("login-form"); +const errorBox = document.getElementById("login-error"); + +function fail(message) { + errorBox.textContent = message; + errorBox.hidden = false; +} + +form.addEventListener("submit", async (event) => { + event.preventDefault(); + errorBox.hidden = true; + const button = form.querySelector("button"); + button.disabled = true; + try { + const response = await fetch("/api/auth/login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + username: form.username.value, + password: form.password.value, + remember: form.remember.checked, + }), + }); + if (response.ok) { + location.assign("/"); + return; + } + if (response.status === 401) fail("Wrong username or password."); + else if (response.status === 429) fail("Too many attempts. Wait a minute and try again."); + else fail("Sign-in is unavailable right now. Try again shortly."); + } catch { + fail("Could not reach the dashboard. Check your connection and try again."); + } finally { + button.disabled = false; + } +}); diff --git a/dashboard/mining_dashboard/web/static/styles/login.css b/dashboard/mining_dashboard/web/static/styles/login.css new file mode 100644 index 0000000000..05b9376bd8 --- /dev/null +++ b/dashboard/mining_dashboard/web/static/styles/login.css @@ -0,0 +1,51 @@ +.login-container { + max-width: 380px; + margin-top: 12vh; +} +.login-card { + background: var(--card); + border: 1px solid var(--border); + border-radius: 8px; + padding: 24px; +} +.login-form { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 16px; +} +.login-form label { + color: var(--text-muted); + font-size: 0.85rem; +} +.login-form input[type="text"], +.login-form input[type="password"] { + background: var(--bg); + border: 1px solid var(--border); + border-radius: 6px; + color: var(--text); + padding: 8px 10px; + font-size: 1rem; +} +.login-form input:focus { + outline: none; + border-color: var(--accent); +} +.login-remember { + display: flex; + align-items: center; + gap: 8px; +} +.login-form .btn-toggle { + border: 1px solid var(--border); + border-radius: 6px; + color: var(--text); + padding: 8px 16px; +} +.login-form .btn-toggle:disabled { + opacity: 0.55; + cursor: not-allowed; +} +.signout-btn { + margin-left: 8px; +} diff --git a/dashboard/mining_dashboard/web/templates/login.html b/dashboard/mining_dashboard/web/templates/login.html new file mode 100644 index 0000000000..c5738efcf7 --- /dev/null +++ b/dashboard/mining_dashboard/web/templates/login.html @@ -0,0 +1,34 @@ + + + + + + Sign in - Pithead + + + + + + + + + diff --git a/dashboard/tests/service/test_auth_sessions.py b/dashboard/tests/service/test_auth_sessions.py new file mode 100644 index 0000000000..9e116676a6 --- /dev/null +++ b/dashboard/tests/service/test_auth_sessions.py @@ -0,0 +1,70 @@ +import pytest + +from mining_dashboard.service import auth_sessions +from mining_dashboard.service.storage_service import StateManager + + +class TestSessionLifetimes: + @pytest.fixture + def store(self): + sm = StateManager(db_path=":memory:") + auth_sessions.create_schema(sm) + yield sm + sm.close() + + @pytest.fixture + def clock(self, monkeypatch): + now = [1_000_000.0] + monkeypatch.setattr(auth_sessions.time, "time", lambda: now[0]) + return now + + def test_unremembered_session_expires_after_idle_timeout(self, store, clock): + token = auth_sessions.issue(store, "admin", "e", False) + clock[0] += auth_sessions.IDLE_SECONDS - 5 + assert auth_sessions.validate(store, token, "e")[0] == "admin" + clock[0] += auth_sessions.IDLE_SECONDS - 5 + assert auth_sessions.validate(store, token, "e")[0] == "admin" + clock[0] += auth_sessions.IDLE_SECONDS + 5 + assert auth_sessions.validate(store, token, "e") is None + + def test_remembered_session_outlives_the_idle_timeout(self, store, clock): + token = auth_sessions.issue(store, "admin", "e", True) + clock[0] += auth_sessions.IDLE_SECONDS * 3 + assert auth_sessions.validate(store, token, "e") is not None + + def test_remembered_session_lasts_thirty_days_unused(self, store, clock): + token = auth_sessions.issue(store, "admin", "e", True) + clock[0] += 30 * 86400 - 5 + assert auth_sessions.validate(store, token, "e") is not None + clock[0] += 30 * 86400 + 5 + assert auth_sessions.validate(store, token, "e") is None + + def test_use_slides_the_remembered_window_and_asks_for_a_cookie_refresh(self, store, clock): + token = auth_sessions.issue(store, "admin", "e", True) + clock[0] += 20 * 86400 + _, _, refresh = auth_sessions.validate(store, token, "e") + assert refresh is True + clock[0] += 20 * 86400 + assert auth_sessions.validate(store, token, "e") is not None + + def test_no_cookie_refresh_within_a_day(self, store, clock): + token = auth_sessions.issue(store, "admin", "e", True) + clock[0] += 3600 + assert auth_sessions.validate(store, token, "e")[2] is False + + def test_unremembered_sessions_never_ask_for_a_persistent_cookie(self, store, clock): + token = auth_sessions.issue(store, "admin", "e", False) + clock[0] += 2 * 86400 // 8 + assert auth_sessions.validate(store, token, "e")[2] is False + + def test_session_table_is_capped(self, store, clock): + for _ in range(auth_sessions.MAX_SESSIONS + 5): + clock[0] += 1 + auth_sessions.issue(store, "admin", "e", False) + count = store._conn.execute("SELECT COUNT(*) FROM dashboard_sessions").fetchone()[0] + assert count == auth_sessions.MAX_SESSIONS + + def test_tokens_are_stored_hashed(self, store): + token = auth_sessions.issue(store, "admin", "e", False) + ids = [r["id"] for r in store._conn.execute("SELECT id FROM dashboard_sessions")] + assert token not in ids diff --git a/dashboard/tests/web/test_auth.py b/dashboard/tests/web/test_auth.py new file mode 100644 index 0000000000..957e4c019b --- /dev/null +++ b/dashboard/tests/web/test_auth.py @@ -0,0 +1,265 @@ +import asyncio +import base64 + +import pytest +from aiohttp import web + +from mining_dashboard.service.storage_service import StateManager +from mining_dashboard.web import auth +from mining_dashboard.web.server import create_app + +EPOCH = {auth.EPOCH_HEADER: "epoch-one"} +GOOD = ("admin", "correct horse") + + +def verifier_app(calls): + async def verify(request): + calls.append(request.headers.get("Authorization", "")) + expected = "Basic " + base64.b64encode(":".join(GOOD).encode()).decode() + if request.headers.get("Authorization") == expected: + return web.Response(status=204) + return web.Response(status=401, headers={"WWW-Authenticate": 'Basic realm="restricted"'}) + + app = web.Application() + app.router.add_get("/", verify) + return app + + +@pytest.fixture +async def verifier_calls(): + return [] + + +@pytest.fixture +async def stack(aiohttp_client, verifier_calls): + verifier = await aiohttp_client(verifier_app(verifier_calls)) + sm = StateManager(db_path=":memory:") + app = create_app(sm, {"shares": [], "workers": []}) + app["auth"]["verify_url"] = str(verifier.make_url("/")) + client = await aiohttp_client(app) + yield client + sm.close() + + +def login(client, user=GOOD[0], password=GOOD[1], remember=False, headers=EPOCH, **extra): + body = {"username": user, "password": password, "remember": remember, **extra} + return client.post("/api/auth/login", json=body, headers=headers) + + +def cookie_of(resp): + return resp.headers["Set-Cookie"] + + +class TestLogin: + async def test_success_sets_session_cookie_without_max_age(self, stack): + resp = await login(stack) + assert resp.status == 200 + cookie = cookie_of(resp) + assert cookie.startswith(f"{auth.COOKIE}=") + assert "HttpOnly" in cookie + assert "SameSite=Strict" in cookie + assert "Max-Age" not in cookie + assert "Secure" not in cookie + + async def test_remember_sets_thirty_day_cookie(self, stack): + resp = await login(stack, remember=True) + assert f"Max-Age={30 * 86400}" in cookie_of(resp) + + async def test_remember_must_be_literal_true(self, stack): + resp = await login(stack, remember="yes") + assert "Max-Age" not in cookie_of(resp) + + async def test_cookie_secure_when_proxy_reports_https(self, stack): + resp = await login(stack, headers={**EPOCH, "X-Forwarded-Proto": "https"}) + assert "Secure" in cookie_of(resp) + + async def test_wrong_password_is_401_with_no_cookie(self, stack): + resp = await login(stack, password="nope") + assert resp.status == 401 + assert "Set-Cookie" not in resp.headers + assert (await resp.json())["error"] == "Invalid username or password." + + async def test_wrong_user_is_401(self, stack): + assert (await login(stack, user="root")).status == 401 + + async def test_username_with_colon_never_reaches_the_verifier(self, stack, verifier_calls): + assert (await login(stack, user="admin:x", password="y")).status == 401 + assert verifier_calls == [] + + async def test_missing_epoch_header_is_404(self, stack): + assert (await login(stack, headers={})).status == 404 + + async def test_malformed_bodies_are_400(self, stack): + for payload in ("not json", "[]", '{"username": 1, "password": "x"}'): + resp = await stack.post( + "/api/auth/login", + data=payload, + headers={**EPOCH, "Content-Type": "application/json"}, + ) + assert resp.status == 400 + + async def test_verifier_down_is_503(self, stack): + stack.app["auth"]["verify_url"] = "http://127.0.0.1:9/" + assert (await login(stack)).status == 503 + + async def test_repeated_failures_are_rate_limited(self, stack, verifier_calls): + for _ in range(auth.FAILURE_LIMIT): + assert (await login(stack, password="nope")).status == 401 + resp = await login(stack, password="nope") + assert resp.status == 429 + assert int(resp.headers["Retry-After"]) >= 1 + before = len(verifier_calls) + assert (await login(stack)).status == 429 + assert len(verifier_calls) == before + + async def test_rate_limit_is_per_client(self, stack): + for _ in range(auth.FAILURE_LIMIT): + await login(stack, password="nope", headers={**EPOCH, "X-Forwarded-For": "10.0.0.1"}) + other = await login(stack, headers={**EPOCH, "X-Forwarded-For": "10.0.0.2"}) + assert other.status == 200 + + async def test_concurrent_verifications_beyond_the_cap_are_refused(self, stack): + release = asyncio.Event() + started = [] + real = auth._verify + + async def held(request, username, password): + started.append(username) + await release.wait() + return await real(request, username, password) + + auth._verify = held + try: + pending = [ + asyncio.ensure_future( + login(stack, headers={**EPOCH, "X-Forwarded-For": f"10.0.1.{n}"}) + ) + for n in range(auth.MAX_CONCURRENT_VERIFY) + ] + for _ in range(100): + if len(started) == auth.MAX_CONCURRENT_VERIFY: + break + await asyncio.sleep(0.01) + assert len(started) == auth.MAX_CONCURRENT_VERIFY + extra = await login(stack, headers={**EPOCH, "X-Forwarded-For": "10.0.1.99"}) + assert extra.status == 429 + release.set() + assert [r.status for r in await asyncio.gather(*pending)] == [200] * len(pending) + finally: + auth._verify = real + release.set() + assert stack.app["auth"]["busy"] == 0 + + async def test_login_page_is_served(self, stack): + resp = await stack.get("/login") + assert resp.status == 200 + assert 'id="login-form"' in await resp.text() + assert 'id="login-remember"' in await resp.text() + + +class TestCheck: + async def signed_in(self, stack, **kw): + await login(stack, **kw) + + async def test_valid_session_returns_user(self, stack): + await self.signed_in(stack) + resp = await stack.get("/api/auth/check", headers=EPOCH) + assert resp.status == 204 + assert resp.headers["X-Auth-User"] == "admin" + + async def test_no_cookie_api_request_is_401(self, stack): + resp = await stack.get( + "/api/auth/check", headers={**EPOCH, "X-Forwarded-Uri": "/api/state"} + ) + assert resp.status == 401 + + async def test_no_cookie_browser_navigation_redirects_to_login(self, stack): + resp = await stack.get( + "/api/auth/check", + headers={**EPOCH, "Accept": "text/html", "X-Forwarded-Uri": "/"}, + allow_redirects=False, + ) + assert resp.status == 303 + assert resp.headers["Location"] == "/login" + + async def test_missing_epoch_is_401(self, stack): + await self.signed_in(stack) + assert (await stack.get("/api/auth/check")).status == 401 + + async def test_password_change_ends_every_session(self, stack): + await self.signed_in(stack) + await self.signed_in(stack, remember=True) + changed = {auth.EPOCH_HEADER: "epoch-two"} + assert (await stack.get("/api/auth/check", headers=changed)).status == 401 + assert (await stack.get("/api/auth/check", headers=EPOCH)).status == 401 + + async def test_new_login_after_change_drops_stale_sessions(self, stack): + await self.signed_in(stack) + await login(stack, headers={auth.EPOCH_HEADER: "epoch-two"}) + rows = ( + stack.app["state_manager"] + ._conn.execute("SELECT DISTINCT epoch FROM dashboard_sessions") + .fetchall() + ) + assert [r["epoch"] for r in rows] == ["epoch-two"] + + async def test_logout_ends_the_session_at_once(self, stack): + await self.signed_in(stack) + resp = await stack.post("/api/auth/logout") + assert resp.status == 200 + assert "Max-Age=0" in cookie_of(resp) + stack.session.cookie_jar.clear() + assert (await stack.get("/api/auth/check", headers=EPOCH)).status == 401 + + async def test_logout_revokes_server_side_even_if_cookie_is_replayed(self, stack): + resp = await login(stack) + token = cookie_of(resp).split(";")[0].split("=", 1)[1] + await stack.post("/api/auth/logout") + replay = await stack.get("/api/auth/check", headers=EPOCH, cookies={auth.COOKIE: token}) + assert replay.status == 401 + + +class TestStateAndRefresh: + async def test_state_reports_the_signed_in_user(self, stack): + await login(stack) + body = await (await stack.get("/api/state", headers={"X-Auth-User": "admin"})).json() + assert body["auth_user"] == "admin" + assert body["auth_session"] is True + + async def test_state_without_a_session_has_no_signout(self, stack): + body = await (await stack.get("/api/state", headers={"X-Auth-User": "admin"})).json() + assert body["auth_session"] is False + + async def test_refresh_header_reissues_the_remember_cookie(self, stack): + token = cookie_of(await login(stack, remember=True)).split(";")[0].split("=", 1)[1] + resp = await stack.get( + "/api/state", + headers={auth.REFRESH_HEADER: "1"}, + cookies={auth.COOKIE: token}, + ) + assert f"Max-Age={30 * 86400}" in cookie_of(resp) + assert token in cookie_of(resp) + + async def test_no_refresh_header_leaves_cookies_alone(self, stack): + resp = await stack.get("/api/state", cookies={auth.COOKIE: "abc"}) + assert "Set-Cookie" not in resp.headers + + +class TestAttempts: + def test_limit_opens_after_the_window(self): + attempts = auth.Attempts() + for _ in range(auth.FAILURE_LIMIT): + attempts.failed("a", now=100.0) + assert attempts.retry_after("a", now=100.0) > 0 + assert attempts.retry_after("a", now=100.0 + auth.FAILURE_WINDOW) == 0 + + def test_tracked_clients_are_bounded_and_evict_the_oldest(self): + attempts = auth.Attempts() + for n in range(auth.MAX_TRACKED_CLIENTS): + attempts.failed(f"c{n}", now=1.0) + for _ in range(auth.FAILURE_LIMIT - 1): + attempts.failed("c0", now=1.0) + attempts.failed("new", now=1.0) + assert len(attempts._failures) == auth.MAX_TRACKED_CLIENTS + assert "c0" not in attempts._failures + assert "new" in attempts._failures diff --git a/docs/configuration.md b/docs/configuration.md index 1753fdc244..1f396f5b76 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -248,7 +248,7 @@ the desired value is not presented as proof of what the still-running services u | `dashboard.expose_public_ip` | `false` | Appliance only. The appliance serves the dashboard on the addresses it holds, and on a network that passes IPv6 through, one of those is a globally-routable address — which would put the control panel on the open internet, gated only by your router. By default those addresses are left out of the site list _and_ out of Caddy's listener, so the dashboard answers on LAN, ULA and loopback addresses only. Reach it from outside over the onion service instead. Set `true` only if you deliberately want it published on a routable address and have your own protection in front of it. | | `dashboard.port` | `auto` | Host port Caddy binds the dashboard on. `auto` = the scheme default (443 with `dashboard.secure: true`, 80 without). Set a number (e.g. `8443`) to move it — for a host already running another reverse proxy on 80/443, so that proxy can front the stack. In HTTPS mode a custom port also drops Caddy's automatic HTTP→HTTPS redirect (which would otherwise hold port 80), so the fronting proxy owns any redirect. See [Co-hosting on a shared server](#co-hosting-on-a-shared-server). | | `dashboard.auth.username` | `admin` | Login name for the dashboard when a password is set (see below). Letters, digits, and `. _ @ -`, 1–64 chars. Ignored while `dashboard.auth.password` is empty. | -| `dashboard.auth.password` | `""` _(off)_ | Optional password to open the dashboard. Turns on a Caddy [HTTP basic-auth](https://caddyserver.com/docs/caddyfile/directives/basic_auth) prompt in front of every page. `""` (default) = no login, anyone who can reach the dashboard sees it. Both setup wizards generate a password by default; the empty reference value remains unchanged for upgraded and restored configs. Any 8–128-character string (no double-quotes) turns the prompt on. The plaintext lives only in your owner-only `config.json`; pithead bcrypt-hashes it with the pinned Caddy image and stores only the hash in `.env`, so the password itself is never persisted in rendered state. The hashing container disables runtime logging to keep its credential hash out of the system journal. Basic-auth credentials travel in cleartext over HTTP, so keep `dashboard.secure: true` (the default); pithead warns if you set a password with `secure: false`. See [Exposing the dashboard safely](#exposing-the-dashboard-safely). | +| `dashboard.auth.password` | `""` _(off)_ | Optional password to open the dashboard. Turns on a sign-in page in front of every dashboard page, with a "Remember me" box and a "Sign out" button. Scripts and API clients can still send the same username and password as HTTP [basic auth](https://caddyserver.com/docs/caddyfile/directives/basic_auth). `""` (default) = no login, anyone who can reach the dashboard sees it. Both setup wizards generate a password by default; the empty reference value remains unchanged for upgraded and restored configs. Any 8–128-character string (no double-quotes) turns the prompt on. The plaintext lives only in your owner-only `config.json`; pithead bcrypt-hashes it with the pinned Caddy image and stores only the hash in `.env`, so the password itself is never persisted in rendered state. The hashing container disables runtime logging to keep its credential hash out of the system journal. The password travels in cleartext over HTTP, so keep `dashboard.secure: true` (the default); pithead warns if you set a password with `secure: false`. See [Exposing the dashboard safely](#exposing-the-dashboard-safely). | | `dashboard.onion.enabled` | `false` _(off)_ | Privacy-relevant, default off. `true` publishes the dashboard as a Tor v3 onion service so you can reach it remotely over Tor — no port-forward, no VPN, no public IP. It fronts the authenticated Caddy login on the internal bridge, never the LAN. pithead **fails closed**: if no `dashboard.auth.password` is set it generates a strong one (saved to `config.json`, login `admin`); a password you set yourself must be at least 16 characters. See [Remote access over Tor](#remote-access-over-tor-onion-service). | | `dashboard.onion.client_auth` | `true` _(on)_ | Only applies when `dashboard.onion.enabled` is `true`. Keeps Tor v3 **client authorization** on: the onion does not respond at all without your client key, so the address can't be scanned or brute-forced — the password becomes a second factor behind it. pithead generates the keypair; get the client line from the dashboard header's **Show client key** button, or with `./pithead onion-client-key` on a machine you can log in to. Set to `false` for a deliberately password-only onion — but not alongside `dashboard.control.enabled: true`: `apply` refuses that pairing, since a root-capable config-mutation channel must not sit behind only a brute-forceable password on an anonymously-reachable address. Because an appliance turns the config editor on for itself, an appliance onion is always client-authorized. | | `dashboard.control.enabled` | `false` _(off)_ | Security-relevant, default off. `true` turns on the dashboard's **Configuration view**: edit `config.json` from the browser, preview the changes, and apply them. The dashboard container never runs `pithead` itself — it writes a typed change request into a spool directory and a root systemd unit on the host (`pithead-control`) validates and applies it (see [Dashboard › Configuration view](dashboard.md#configuration-view)). Fails closed twice: enabling it without a `dashboard.auth.password` is a validation error, because this channel can change the payout wallet; and enabling it on a published onion (`dashboard.onion.enabled`) with `dashboard.onion.client_auth: false` is refused too, since a password alone is brute-forceable over Tor. | @@ -497,8 +497,32 @@ or the whole CA directory. Normal leaf renewals retain the root in `caddy_data`; deletes that volume and requires a new export and trust decision. The appliance uses its own certificate; this procedure is for DIY installs. +**Signing in.** With a password set, the dashboard opens a sign-in page: a username, the password +and a "Remember me" box. The session cookie is `HttpOnly` and `SameSite=Strict`, and `Secure` when +the page is served over HTTPS. + +- **Remember me off:** the session ends when the browser closes, or after 8 hours without use. +- **Remember me on:** the session lasts 30 days and renews while you use the dashboard. +- **Sign out** ends the session at once. Changing `dashboard.auth.password` or + `dashboard.auth.username` and running `apply` ends every session, this one included. +- **Wrong passwords:** five failures from one address in a minute lock sign-in from that address + for the rest of the minute. Each attempt appears in the access log shown in the Security panel. + Basic-auth requests are not rate-limited. On the onion address every visitor reaches the + dashboard from the Tor container, so they share one failure count. +- **Scripts and API clients** keep sending the username and password as HTTP basic auth, for + example `curl -u admin:PASSWORD`. A basic-auth request for a page that asks for HTML + (`Accept: text/html`, outside `/api/`) is sent to the sign-in page instead, which is what a + browser does. Local callers on `127.0.0.1:8000` are unaffected. +- **After an upgrade from 2.0.3** the password is unchanged. A browser that still holds the old + basic-auth login is sent to the sign-in page on its next page load. Once it has a session + cookie, the cookie decides and the old basic-auth login is ignored, so "Sign out" works. +- The sign-in page checks the password through a Caddy listener that binds `127.0.0.1:8001` only, + so the dashboard never holds the password hash. Following a link to the dashboard from another + site shows the sign-in page once, because `SameSite=Strict` withholds the cookie from that first + request. + To remove the login again, clear the password (`"password": ""`) and `apply`. pithead drops the -`basic_auth` block and the dashboard is open on the LAN as before. +login and the dashboard is open on the LAN as before. ### Co-hosting on a shared server @@ -525,8 +549,9 @@ A couple of things to know: and redirects to HTTPS. On a custom port that redirect is switched off (it would otherwise keep holding port 80, defeating the point). Your fronting proxy owns the http→https bounce. - **This does not remove Caddy or its login.** `dashboard.port` only moves the port. The dashboard - itself still binds `127.0.0.1:8000` with no authentication of its own — the `dashboard.auth` login - lives in Caddy — so keep Caddy in the path and set a password before your proxy exposes it. + itself still binds `127.0.0.1:8000` with no authentication of its own — Caddy checks the + `dashboard.auth` login before a request reaches it — so keep Caddy in the path and set a password + before your proxy exposes it. ### Remote access over Tor (onion service) diff --git a/docs/dev/testing-strategy.md b/docs/dev/testing-strategy.md index 5a5ce3d1df..a1a83fd8fe 100644 --- a/docs/dev/testing-strategy.md +++ b/docs/dev/testing-strategy.md @@ -292,6 +292,7 @@ and require tier-4 appliance proof when changed. | system levels (cpu/mem/disk/hugepages), worker pool/online, chart outage breaks | metrics | 1 ✅ | | dashboard DB writes failing → `db_healthy:false` (#131) | data dir read-only | 1 ✅ (flag logic) · 4 ▶ (`--fault-injection`, #202) | | `/metrics` Prometheus exposition (#379), through Caddy + basic_auth | scrape | 1 ✅ (format) · 4 ▶ (`--check`) | +| Dashboard sign-in page (#4089): session cookie versus remember lifetime, sign out, session end on password change, per-address rate limit, basic auth still accepted, no-password mode, Caddy session gate and loopback verifier render | scripted HTTP through real Caddy and the dashboard image | 1 ✅ (`dashboard/tests/web/test_auth.py`, `dashboard/tests/service/test_auth_sessions.py`, `tests/stack/dashboard/test-dashboard-login.sh`) · 3 ✅ (`tests/integration/mini-stack/test-boot-health-proxy.sh` login and rotated legs) | | `share_stats` series populated on a mining box (#116) | polls land | 1 ✅ (shape) · 4 ▶ (`--check`) | | Confirmed running earnings (#787): yesterday as a **calendar** day vs the trailing 24h/7d/30d spans, the DST-length day boundary, partial marking when a window outruns the recorded payout history, and one roll-up feeding both the dashboard card and `/earnings` | stored payouts | 1 ✅ (`test_earnings.py`, `test_telegram_commands.py`, `components.test.mjs`) | | Expected-vs-actual earnings summary (#808/#817): one shared 30d window, the combined Monero+XvB row (estimate folded on the expected side because win payouts are inseparable on the actual side), per-stream gates and honest degradation, Tari block counts, XvB win windowing, and the card's render branches in both views | metrics + stored payouts | 1 ✅ (`test_views.py` `TestEarningsVsActual`, `test_metrics.py`, `components.test.mjs`) | diff --git a/lib/pithead/35-caddyfile-and-auth-helpers.sh b/lib/pithead/35-caddyfile-and-auth-helpers.sh index 12ff43f81b..e6060403d0 100644 --- a/lib/pithead/35-caddyfile-and-auth-helpers.sh +++ b/lib/pithead/35-caddyfile-and-auth-helpers.sh @@ -49,29 +49,51 @@ caddy_hash_password_b64() { printf '%s' "$hash" | openssl base64 -A } -generate_caddyfile() { # [output=Caddyfile] [mint-appliance-cert=true] +generate_caddyfile() { local target="${1:-Caddyfile}" mint_appliance_cert="${2:-true}" - # Every vhost forwards the authenticated basic_auth username as X-Auth-User (#33) — the audit - # `actor` for control-channel requests. header_up SETS the header, so a client-supplied - # X-Auth-User can never spoof it; with auth off the placeholder renders empty. - # - # Optional basic_auth block (#8), rendered only when a dashboard password is configured. The - # hash is decoded from its base64 .env form back to the raw bcrypt string Caddy expects; it - # protects every route, so the dashboard prompts for login before anything is served. - local auth="" + local auth="" gate verify_site="" proxy_user_hdr="" epoch if [ -n "${DASHBOARD_AUTH_HASH_B64:-}" ]; then local hash hash=$(printf '%s' "$DASHBOARD_AUTH_HASH_B64" | openssl base64 -d -A) - auth=$(printf ' basic_auth {\n %s %s\n }' "$DASHBOARD_AUTH_USER" "$hash") + auth=$(printf ' basic_auth {\n %s %s\n }' "$DASHBOARD_AUTH_USER" "$hash") + epoch=$(printf 'pithead-session-epoch-v1:%s:%s' "$DASHBOARD_AUTH_USER" "$DASHBOARD_AUTH_HASH_B64" | sha256_hex) + gate=$(printf '%s\n' \ + ' request_header -X-Auth-User' \ + ' request_header -X-Pithead-Session-Refresh' \ + ' @pithead_public path /login /api/auth/login /api/auth/logout /static/login.js /static/dashboard.css /static/styles/* /static/theme-init.js /static/pithead-mark.svg' \ + ' reverse_proxy @pithead_public 127.0.0.1:8000 {' \ + " header_up X-Pithead-Auth-Epoch \"$epoch\"" \ + ' header_up X-Forwarded-For {http.request.remote.host}' \ + ' header_up -X-Pithead-Boot-Probe' \ + ' }' \ + ' @pithead_basic {' \ + ' header_regexp Authorization (?i)^basic\s' \ + ' not header_regexp Cookie (^|;\s*)pithead_session=' \ + ' }' \ + ' @pithead_page {' \ + ' method GET' \ + ' header Accept *text/html*' \ + ' not path /api/*' \ + ' }' \ + ' route @pithead_basic {' \ + ' vars pithead_basic 1' \ + ' redir @pithead_page /login 303' \ + "$auth" \ + ' request_header X-Auth-User {http.auth.user.id}' \ + ' }' \ + ' @pithead_session not vars pithead_basic 1' \ + ' forward_auth @pithead_session 127.0.0.1:8000 {' \ + ' uri /api/auth/check' \ + " header_up X-Pithead-Auth-Epoch \"$epoch\"" \ + ' copy_headers X-Auth-User X-Pithead-Session-Refresh' \ + ' }') + verify_site=$(printf 'http://127.0.0.1:8001 {\n bind 127.0.0.1\n route {\n basic_auth {\n %s %s\n }\n respond 204\n }\n}\n' "$DASHBOARD_AUTH_USER" "$hash") + else + gate=$(printf '%s\n' \ + ' @pithead_auth_paths path /login /api/auth/*' \ + ' respond @pithead_auth_paths 404') + proxy_user_hdr=' header_up X-Auth-User {http.auth.user.id}' fi - # Access log (#349): every vhost writes a JSON line per request (timestamp, status, method, - # URI, authenticated user) to one shared file under the host-mounted CADDY_LOG_DIR; the - # dashboard tails it read-only, and repeated 401s there are the operator's "someone is - # guessing the password" signal. Caddy redacts credential headers (Authorization, Cookie) - # unless the log_credentials global option is set — it never is here — so no password material - # lands in the log. Growth is bounded by Caddy's native rolling: 4 MiB per file, the current - # file plus 2 rolled ones. mode 0644 lets the non-root dashboard read what root-run Caddy - # writes (Caddy's default is 0600). local logblk=' log { output file /var/log/caddy/access.log { roll_size 4MiB @@ -314,20 +336,16 @@ $logblk route { $boot_marker rewrite @boot_health / -$auth +$gate reverse_proxy 127.0.0.1:8000 { - header_up X-Auth-User {http.auth.user.id} +$proxy_user_hdr header_up -X-Pithead-Boot-Probe } } } EOF + [ -z "$verify_site" ] || printf '\n%s' "$verify_site" >>"$target" - # Onion vhost (#343): a second site reachable ONLY from the tor container, via the bridge gateway - # (NETWORK_PREFIX.1 — the /24's first host, where host-networked Caddy binds and bridge containers - # route out). It is never on the LAN. Plain HTTP: Tor provides the transport encryption inside the - # tunnel, so no `tls internal` here. It MUST carry the same auth block — refuse to publish an - # unauthenticated control panel (config validation already fails closed; this is belt-and-suspenders). if [ "${DASHBOARD_ONION_ENABLED:-false}" == "true" ]; then if [ -z "$auth" ]; then error "Refusing to render the dashboard onion vhost without a login: dashboard.onion.enabled is on but no auth hash is set." @@ -337,11 +355,12 @@ EOF http://${NETWORK_PREFIX}.1 { $(_onion_bind_line) -$auth $logblk - reverse_proxy 127.0.0.1:8000 { - header_up X-Auth-User {http.auth.user.id} - header_up -X-Pithead-Boot-Probe + route { +$gate + reverse_proxy 127.0.0.1:8000 { + header_up -X-Pithead-Boot-Probe + } } } EOF @@ -360,11 +379,12 @@ EOF https://${DASHBOARD_ONION} { tls internal $(_onion_bind_line) -$auth $logblk - reverse_proxy 127.0.0.1:8000 { - header_up X-Auth-User {http.auth.user.id} - header_up -X-Pithead-Boot-Probe + route { +$gate + reverse_proxy 127.0.0.1:8000 { + header_up -X-Pithead-Boot-Probe + } } } EOF diff --git a/tests/integration/mini-stack/boot-health-proxy.py b/tests/integration/mini-stack/boot-health-proxy.py index 9a2e0198a6..910d0046d3 100644 --- a/tests/integration/mini-stack/boot-health-proxy.py +++ b/tests/integration/mini-stack/boot-health-proxy.py @@ -38,8 +38,46 @@ def request(path, auth=None, method="GET", headers=None): return response.status, response.read() +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +raw_opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect) + + +def call(path, method="GET", headers=None, body=None, auth=None): + hdrs = {"Host": "panel.example:8080", **(headers or {})} + if auth: + hdrs["Authorization"] = auth + data = None + if body is not None: + data = json.dumps(body).encode() + hdrs["Content-Type"] = "application/json" + req = urllib.request.Request( + f"http://{host}:{PORT}{path}", data=data, headers=hdrs, method=method + ) + try: + response = raw_opener.open(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + return response.status, response.headers, response.read() + + +def sign_in(password, remember=False): + return call( + "/api/auth/login", + "POST", + body={"username": "admin", "password": password, "remember": remember}, + ) + + +def session_cookie(headers): + return headers["Set-Cookie"].split(";", 1)[0] + + def summary(failures, warning): - # Access logging is asynchronous; wait for the exact count, never accept an empty log. for _ in range(50): status, body = request("/api/access", GOOD_AUTH) require(status == 200, (status, body[:200])) @@ -112,8 +150,70 @@ def summary(failures, warning): headers = {} if value is None else {"X-Pithead-Boot-Probe": value} require(request(PROBE, headers=headers)[0] == 401) summary(23, True) +elif mode == "login": + status, _, body = call("/login") + require(status == 200 and b'id="login-form"' in body, status) + for asset in ("/static/login.js", "/static/dashboard.css"): + require(call(asset)[0] == 200, asset) + require(call("/static/dashboard.js")[0] == 401) + status, headers, _ = call("/", headers={"Accept": "text/html"}) + require(status == 303 and headers["Location"].startswith("/login"), (status, headers)) + require(call("/api/state")[0] == 401) + require(call("/api/auth/check")[0] == 401) + status, headers, _ = sign_in("wrong-password") + require(status == 401 and "Set-Cookie" not in headers, status) + + status, headers, _ = sign_in("fixture-password") + require(status == 200, status) + set_cookie = headers["Set-Cookie"] + require("HttpOnly" in set_cookie and "SameSite=Strict" in set_cookie, set_cookie) + require("Max-Age" not in set_cookie, set_cookie) + cookie = session_cookie(headers) + status, _, body = call("/api/state", headers={"Cookie": cookie, "X-Auth-User": "evil"}) + state = json.loads(body) + require(status == 200 and state["auth_user"] == "admin", (status, state.get("auth_user"))) + require(state["auth_session"] is True) + status, headers, _ = call("/", auth=GOOD_AUTH, headers={"Accept": "text/html"}) + require(status == 303 and headers["Location"] == "/login", (status, headers)) + require(call("/api/state", auth=GOOD_AUTH, headers={"Accept": "text/html"})[0] == 200) + status, _, body = call("/api/state", auth=BAD_AUTH, headers={"Cookie": cookie}) + require(status == 200 and json.loads(body)["auth_user"] == "admin", status) + status, _, body = call("/api/state", auth=GOOD_AUTH, headers={"X-Auth-User": "evil"}) + require(status == 200 and json.loads(body)["auth_user"] == "admin") + require(call("/api/state", headers={"X-Auth-User": "admin"})[0] == 401) + + status, headers, _ = sign_in("fixture-password", remember=True) + require(status == 200 and "Max-Age=2592000" in headers["Set-Cookie"], headers["Set-Cookie"]) + remembered = session_cookie(headers) + require(call("/api/state", headers={"Cookie": remembered})[0] == 200) + + require(call("/api/auth/logout", "POST", headers={"Cookie": cookie})[0] == 200) + require(call("/api/state", headers={"Cookie": cookie})[0] == 401) + require(call("/api/state", headers={"Cookie": remembered})[0] == 200) + print("COOKIE=" + remembered) +elif mode == "rotated": + old = os.environ["OLD_COOKIE"] + require(call("/api/state", headers={"Cookie": old})[0] == 401) + require(call("/api/state", auth=GOOD_AUTH)[0] == 401) + status, headers, _ = sign_in("rotated-password") + require(status == 200, status) + fresh = session_cookie(headers) + require(call("/api/state", headers={"Cookie": fresh})[0] == 200) + statuses = [sign_in("wrong-password")[0] for _ in range(7)] + require(statuses[0] == 401 and statuses[-1] == 429 and 429 in statuses, statuses) + status, headers, _ = sign_in("rotated-password") + require(status == 429 and int(headers["Retry-After"]) >= 1, status) + for _ in range(50): + entries = json.loads(call("/api/access", headers={"Cookie": fresh})[2])["entries"] + seen = {e["status"] for e in entries if e["uri"] == "/api/auth/login"} + if {200, 401, 429} <= seen: + break + time.sleep(0.1) + else: + raise AssertionError(seen) elif mode == "unlocked": status, body = request(PROBE, headers={"X-Pithead-Boot-Probe": CAPABILITY}) require(status == 200 and b"/dev/null +docker run --rm -i --network "container:$name-caddy" -e OLD_COOKIE="$old_cookie" -e DASHBOARD_AUTH_HASH_B64 --entrypoint python \ + pithead-dashboard:itest - rotated 127.0.0.1 <"$ROOT/tests/integration/mini-stack/boot-health-proxy.py" DASHBOARD_AUTH_HASH_B64="" generate_caddyfile "$scratch/Caddyfile" docker exec "$name-caddy" caddy reload --config /etc/caddy/Caddyfile >/dev/null diff --git a/tests/stack/dashboard/test-dashboard-login.sh b/tests/stack/dashboard/test-dashboard-login.sh new file mode 100644 index 0000000000..a38fff9208 --- /dev/null +++ b/tests/stack/dashboard/test-dashboard-login.sh @@ -0,0 +1,51 @@ +# shellcheck shell=bash +: "${STACK_SUITE:?is unset: this file is a tests/stack/run.sh fragment, not a script — run tests/stack/run.sh}" +auth_hb64="$(printf '%s' '$2y$14$UNITTESTbcrypthashvalue000000000000000000000000000000' | openssl base64 -A)" +# shellcheck disable=SC1090 # STACK path is dynamic by design +caddy_on="$( + cd "$SANDBOX" && source "$STACK" 2>/dev/null + set +e + DASHBOARD_SECURE=true HOST_IP=box.lan DASHBOARD_AUTH_USER=admin DASHBOARD_AUTH_HASH_B64="$auth_hb64" \ + generate_caddyfile >/dev/null 2>&1 + cat Caddyfile +)" +# shellcheck disable=SC1090 # STACK path is dynamic by design +caddy_off="$( + cd "$SANDBOX" && source "$STACK" 2>/dev/null + set +e + DASHBOARD_SECURE=true HOST_IP=box.lan DASHBOARD_AUTH_USER=admin DASHBOARD_AUTH_HASH_B64="" \ + generate_caddyfile >/dev/null 2>&1 + cat Caddyfile +)" +echo "== unit: generate_caddyfile session gate ==" +assert_contains "login: session check goes through forward_auth" "$caddy_on" "forward_auth @pithead_session 127.0.0.1:8000" +assert_contains "login: forward_auth targets the dashboard check endpoint" "$caddy_on" "uri /api/auth/check" +assert_contains "login: forward_auth copies the actor from the session" "$caddy_on" "copy_headers X-Auth-User X-Pithead-Session-Refresh" +assert_contains "login: basic auth still gates scripts and API clients" "$caddy_on" "route @pithead_basic {" +assert_contains "login: the basic-auth actor reaches the dashboard" "$caddy_on" " request_header X-Auth-User {http.auth.user.id}" +assert_contains "login: client-supplied actor header is stripped first" "$caddy_on" "request_header -X-Auth-User" +assert_contains "login: the sign-in endpoints skip the gate" "$caddy_on" "@pithead_public path /login /api/auth/login /api/auth/logout" +assert_contains "login: basic auth is matched case-insensitively (RFC 7617)" "$caddy_on" "header_regexp Authorization (?i)^basic\\s" +assert_contains "login: a session cookie wins over cached basic credentials" "$caddy_on" "not header_regexp Cookie (^|;\\s*)pithead_session=" +assert_contains "login: a browser page load with basic credentials goes to the sign-in page" "$caddy_on" "redir @pithead_page /login 303" +assert_contains "login: everything not on the basic path takes the session gate" "$caddy_on" "@pithead_session not vars pithead_basic 1" +assert_contains "login: the sign-in route sets the client address itself" "$caddy_on" "header_up X-Forwarded-For {http.request.remote.host}" +assert_contains "login: a loopback-only verifier site exists" "$caddy_on" "http://127.0.0.1:8001 {" +assert_not_contains "login: the actor is no longer overwritten by the proxy" "$caddy_on" "header_up X-Auth-User" +epoch_on="$(printf '%s\n' "$caddy_on" | sed -n 's/.*header_up X-Pithead-Auth-Epoch "\([0-9a-f]*\)".*/\1/p' | sort -u)" +assert_eq "login: one 64-hex epoch is sent on every gated route" "$(printf '%s' "$epoch_on" | grep -cE '^[0-9a-f]{64}$')" "1" +auth_hb64_other="$(printf '%s' '$2y$14$UNITTESTbcrypthashvalue000000000000000000000000000001' | openssl base64 -A)" +# shellcheck disable=SC1090 # STACK path is dynamic by design +caddy_other="$( + cd "$SANDBOX" && source "$STACK" 2>/dev/null + set +e + DASHBOARD_SECURE=true HOST_IP=box.lan DASHBOARD_AUTH_USER=admin DASHBOARD_AUTH_HASH_B64="$auth_hb64_other" \ + generate_caddyfile >/dev/null 2>&1 + cat Caddyfile +)" +assert_not_contains "login: a new password changes the epoch" "$caddy_other" "$epoch_on" +assert_not_contains "no login: no session gate" "$caddy_off" "forward_auth" +assert_not_contains "no login: no verifier site" "$caddy_off" "127.0.0.1:8001" +assert_not_contains "no login: no epoch" "$caddy_off" "X-Pithead-Auth-Epoch" +assert_contains "no login: the sign-in paths are 404, as before" "$caddy_off" "respond @pithead_auth_paths 404" +assert_contains "no login: the actor placeholder still renders empty" "$caddy_off" "header_up X-Auth-User {http.auth.user.id}" diff --git a/tests/stack/dashboard/test-dashboard-onion.sh b/tests/stack/dashboard/test-dashboard-onion.sh index 7cdea0453f..dba86239ab 100644 --- a/tests/stack/dashboard/test-dashboard-onion.sh +++ b/tests/stack/dashboard/test-dashboard-onion.sh @@ -37,7 +37,8 @@ caddy_onion="$( )" assert_contains "onion vhost bound to the bridge gateway" "$caddy_onion" "http://172.28.0.1 {" assert_contains "onion vhost carries basic_auth" "$caddy_onion" "basic_auth" -# The onion site (everything after the gateway address) must not get a TLS directive. +assert_contains "onion vhost carries the session gate" "${caddy_onion#*172.28.0.1}" "forward_auth @pithead_session 127.0.0.1:8000" +assert_contains "onion vhost serves the sign-in endpoints" "${caddy_onion#*172.28.0.1}" "@pithead_public path /login" onion_site="${caddy_onion#*172.28.0.1}" case "$onion_site" in *"tls internal"*) bad "onion vhost is plain HTTP" "'tls internal' present on the onion site" ;; diff --git a/tests/stack/dashboard/test-dashboard.sh b/tests/stack/dashboard/test-dashboard.sh index a2c8806d83..57b90851d8 100644 --- a/tests/stack/dashboard/test-dashboard.sh +++ b/tests/stack/dashboard/test-dashboard.sh @@ -233,14 +233,8 @@ caddy_onion="$( cat Caddyfile )" assert_eq "insecure+onion: both vhosts bind, never one wildcard and one specific" \ - "$(printf '%s' "$caddy_onion" | grep -c '^ bind ')" "2" + "$(printf '%s' "$caddy_onion" | grep -c '^ bind ')" "3" -# The invariant, checked by counting rather than by naming the blocks: EVERY site block in the -# rendered file carries a bind, or none does. A hardcoded count only proves the blocks that -# happened to render, and that is exactly how the HTTPS onion vhost shipped unbound — it renders -# only once DASHBOARD_ONION holds a provisioned address, so every test that left it empty saw a -# correct file. `_site_count` counts site openers (a line starting at column 0 and ending in `{`); -# the global options block opens with a bare `{`, which the leading-character class excludes. _site_count() { printf '%s' "$1" | grep -cE '^[^[:space:]{].*\{[[:space:]]*$'; } _bind_count() { printf '%s' "$1" | grep -c '^ bind '; } # shellcheck disable=SC1090 # STACK path is dynamic by design @@ -259,12 +253,8 @@ caddy_onion_https="$( generate_caddyfile >/dev/null 2>&1 cat Caddyfile )" -# Six blocks since #1123 took :80 over and #1132 took :443's own empty-200 default: the two LAN -# vhosts (the known-host :80 redirect and the HTTPS one), the :80 catch-all, the :443 catch-all, -# and the two onion vhosts. The number is worth pinning rather than deriving — it is what caught -# the redirect blocks arriving without anyone re-counting. -assert_eq "secure+onion+provisioned: the HTTPS onion vhost renders (6 site blocks)" \ - "$(_site_count "$caddy_onion_https")" "6" +assert_eq "secure+onion+provisioned: the HTTPS onion vhost renders (7 site blocks)" \ + "$(_site_count "$caddy_onion_https")" "7" assert_eq "secure+onion+provisioned: every site block binds — no unbound wildcard on :443" \ "$(_bind_count "$caddy_onion_https")" "$(_site_count "$caddy_onion_https")" @@ -292,17 +282,9 @@ caddy_onion_https_diy="$( generate_caddyfile >/dev/null 2>&1 cat Caddyfile )" -assert_eq "DIY secure+onion+provisioned: no site block binds" \ - "$(_bind_count "$caddy_onion_https_diy")" "0" +assert_eq "DIY secure+onion+provisioned: only the loopback verifier binds" \ + "$(_bind_count "$caddy_onion_https_diy")" "1" -# No two site blocks may name the same scheme://address. Caddy rejects the WHOLE file with -# "ambiguous site definition" and, under Restart=always, crash-loops — dashboard and onion down -# together. This is reachable because `hostname -I` reports the container-bridge gateway (it is a -# real host address), so it landed in the auto-expanded LAN list AND in the onion block, which -# serves on exactly that address. With dashboard.secure:false the two schemes match and the file -# is unadaptable. Counting binds cannot see this, which is why it is a separate structural check: -# these two assertions together are the cheap tier-1 stand-in for the real `caddy adapt` gate -# tracked in #1037. _dupe_sites() { printf '%s' "$1" | grep -E '^[^[:space:]{].*\{[[:space:]]*$' | sed 's/[[:space:]]*{[[:space:]]*$//' | tr ',' '\n' | tr -d ' ' | grep -v '^$' | @@ -344,8 +326,8 @@ caddy_onion_off="$( generate_caddyfile >/dev/null 2>&1 cat Caddyfile )" -assert_eq "DIY insecure+onion: neither vhost binds — no wildcard/specific clash" \ - "$(printf '%s' "$caddy_onion_off" | grep -c '^ bind ')" "0" +assert_eq "DIY insecure+onion: neither vhost binds — only the loopback verifier does" \ + "$(printf '%s' "$caddy_onion_off" | grep -c '^ bind ')" "1" unset -f _caddy_appliance unset -f _site_count _bind_count unset -f _dupe_sites diff --git a/tests/stack/run.sh b/tests/stack/run.sh index f5a4e4ac80..55e820c8c6 100755 --- a/tests/stack/run.sh +++ b/tests/stack/run.sh @@ -85,6 +85,8 @@ if in_block 1; then _d0=$((PASS + FAIL)) && source "$HERE/dashboard/test-dashboard-exposure-live.sh" && domain_ran test-dashboard-exposure-live.sh "$_d0" "$?" || domain_ran test-dashboard-exposure-live.sh "$_d0" "$?" # shellcheck source=tests/stack/dashboard/test-dashboard-onion.sh disable=SC2015 _d0=$((PASS + FAIL)) && source "$HERE/dashboard/test-dashboard-onion.sh" && domain_ran test-dashboard-onion.sh "$_d0" "$?" || domain_ran test-dashboard-onion.sh "$_d0" "$?" + # shellcheck source=tests/stack/dashboard/test-dashboard-login.sh disable=SC2015 + _d0=$((PASS + FAIL)) && source "$HERE/dashboard/test-dashboard-login.sh" && domain_ran test-dashboard-login.sh "$_d0" "$?" || domain_ran test-dashboard-login.sh "$_d0" "$?" # shellcheck source=tests/stack/dashboard/test-sync-progress-hold.sh disable=SC2015 _d0=$((PASS + FAIL)) && source "$HERE/dashboard/test-sync-progress-hold.sh" && domain_ran test-sync-progress-hold.sh "$_d0" "$?" || domain_ran test-sync-progress-hold.sh "$_d0" "$?" # shellcheck source=tests/stack/dashboard/test-onion-apply-password.sh disable=SC2015 diff --git a/tests/stack/standalone/test_caddyfile.sh b/tests/stack/standalone/test_caddyfile.sh index b61462f426..c6cbd28dbc 100755 --- a/tests/stack/standalone/test_caddyfile.sh +++ b/tests/stack/standalone/test_caddyfile.sh @@ -97,6 +97,7 @@ run_suite() ( suite_failures=0 run_suite "$ROOT/tests/stack/dashboard/test-dashboard.sh" || ((suite_failures += 1)) run_suite "$ROOT/tests/stack/dashboard/test-dashboard-onion.sh" || ((suite_failures += 1)) +run_suite "$ROOT/tests/stack/dashboard/test-dashboard-login.sh" || ((suite_failures += 1)) run_suite "$ROOT/tests/stack/appliance/test-appliance-caddyfile-optional-env.sh" || ((suite_failures += 1)) run_suite "$ROOT/tests/stack/appliance/test-appliance-identity.sh" || ((suite_failures += 1)) From dfe585530a485d2c03345f956604005461e5da12 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:41:14 -0600 Subject: [PATCH 025/112] fix(os,build): bound image-fetch retries so one github.com 5xx stops killing builds (#3992) * fix(os,build): bound image-fetch retries so one github.com 5xx stops killing builds The appliance rootfs fetched the rigforge archive with a single-attempt curl, so one transient 5xx failed the whole image build and with it the tier4-kvm job. Route the layer through os/rootfs/fetch-archive.sh, the fetch-go-source bounded three-attempt contract (180s deadline, delays 5s/10s, final failure names the URL and the final status), and pin the p2pool and xmrig-proxy release fetches to explicit wget --tries/--timeout/--waitretry instead of the implicit 20 retries. tests/os/selftest-archive-fetch.sh drives both Dockerfiles' fetch commands over a local HTTP server: healthy, transient 504 recovered, persistent 504 bounded to three attempts, attempt deadline enforced. Fixes p2pool-starter-stack/pithead#3953. Co-Authored-By: Claude Code * fix(os): keep the fetch-archive helper out of the shipped rootfs; pin its stage The helper is build-only, like fetch-go-source in the throwaway gobuild stage, so remove it at the end of the rigforge layer. The selftest now asserts COPY/RUN membership in the image's final stage instead of plain character order. Co-Authored-By: Claude Code * test(os): scope the helper-removal assertion to the fetching RUN Co-Authored-By: Claude Sonnet 5.5 * ci: re-run checks against the develop base Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Code --- build/p2pool/Dockerfile | 2 +- build/xmrig-proxy/Dockerfile | 2 +- docs/dev/repo-map.md | 2 +- os/rootfs/Dockerfile | 8 +- os/rootfs/fetch-archive.sh | 21 +++ tests/os/selftest-archive-fetch.sh | 3 + tests/os/test_archive_fetch.py | 214 +++++++++++++++++++++++++++++ 7 files changed, 246 insertions(+), 6 deletions(-) create mode 100644 os/rootfs/fetch-archive.sh create mode 100644 tests/os/selftest-archive-fetch.sh create mode 100644 tests/os/test_archive_fetch.py diff --git a/build/p2pool/Dockerfile b/build/p2pool/Dockerfile index ea8ade34ee..92be35a270 100644 --- a/build/p2pool/Dockerfile +++ b/build/p2pool/Dockerfile @@ -9,7 +9,7 @@ RUN for attempt in 1 2 3; do apt-get update && break || { [ "$attempt" = 3 ] && wget ca-certificates libgomp1 socat \ && rm -rf /var/lib/apt/lists/* -RUN wget -O p2pool.tar.gz https://github.com/SChernykh/p2pool/releases/download/${P2POOL_VERSION}/p2pool-${P2POOL_VERSION}-linux-x64.tar.gz \ +RUN wget --tries=3 --timeout=180 --waitretry=10 -O p2pool.tar.gz https://github.com/SChernykh/p2pool/releases/download/${P2POOL_VERSION}/p2pool-${P2POOL_VERSION}-linux-x64.tar.gz \ && echo "${P2POOL_HASH} p2pool.tar.gz" | sha256sum -c - \ && tar xzf p2pool.tar.gz \ && mv p2pool-${P2POOL_VERSION}-linux-x64/p2pool /usr/local/bin/p2pool \ diff --git a/build/xmrig-proxy/Dockerfile b/build/xmrig-proxy/Dockerfile index d81d72d13d..66430ad687 100644 --- a/build/xmrig-proxy/Dockerfile +++ b/build/xmrig-proxy/Dockerfile @@ -12,7 +12,7 @@ RUN for attempt in 1 2 3; do apt-get update && break || { [ "$attempt" = 3 ] && && rm -rf /var/lib/apt/lists/* # Download, verify integrity, and install the XMRig Proxy binary -RUN wget -O xmrig-proxy.tar.gz https://github.com/xmrig/xmrig-proxy/releases/download/v${XMRIG_PROXY_VERSION}/xmrig-proxy-${XMRIG_PROXY_VERSION}-linux-static-x64.tar.gz \ +RUN wget --tries=3 --timeout=180 --waitretry=10 -O xmrig-proxy.tar.gz https://github.com/xmrig/xmrig-proxy/releases/download/v${XMRIG_PROXY_VERSION}/xmrig-proxy-${XMRIG_PROXY_VERSION}-linux-static-x64.tar.gz \ && echo "${XMRIG_PROXY_HASH} xmrig-proxy.tar.gz" | sha256sum -c - \ && tar xzf xmrig-proxy.tar.gz \ && mv xmrig-proxy-${XMRIG_PROXY_VERSION}/xmrig-proxy /usr/local/bin/xmrig-proxy \ diff --git a/docs/dev/repo-map.md b/docs/dev/repo-map.md index bff9866ba7..323634bbe0 100644 --- a/docs/dev/repo-map.md +++ b/docs/dev/repo-map.md @@ -37,7 +37,7 @@ pithead/ | Browser UI | `dashboard/mining_dashboard/web/static/dashboard.js` | Feature modules and styles below; `make test-frontend`. | | Compose | `docker-compose.yml`, `config.reference.json` | Runtime service graph and configuration contract; `make test-compose`. | | Containers | `build//` | Dockerfiles, entrypoints, healthchecks, and Monero's bounded archive downloader; CI builds the images, and `make test-tools` checks download recovery. | -| Appliance | `os/README.md`, `os/build-image.sh` | Rootfs, RAUC slots, installer, and host services; `tests/os/run.sh`. The rig share leg (`tests/os/rig-share-leg.sh`) adds the M11 hashrate floor and calls the adopt leg (`tests/os/rig-adopt-leg.sh`, `selftest-rig-adopt.sh`), which pushes a reversible config change through the coordinator control routes; `tests/os/require-complete-verdict.sh` (`selftest-require-complete.sh`) fails a `--require-complete` run on any missing-input skip. | +| Appliance | `os/README.md`, `os/build-image.sh` | Rootfs, RAUC slots, installer, and host services; `tests/os/run.sh`. The rig share leg (`tests/os/rig-share-leg.sh`) adds the M11 hashrate floor and calls the adopt leg (`tests/os/rig-adopt-leg.sh`, `selftest-rig-adopt.sh`), which pushes a reversible config change through the coordinator control routes; `tests/os/require-complete-verdict.sh` (`selftest-require-complete.sh`) fails a `--require-complete` run on any missing-input skip. `os/rootfs/fetch-archive.sh` bounds the baked RigForge archive fetch; `tests/os/selftest-archive-fetch.sh` runs its local transport regression. | | Release | `scripts/release/release.sh`, [release guide](releasing.md) | Stage, verify, promote, and publish; `make release ARGS="--dry-run"` previews the plan. | | Manual QA | [Start here](manual-qa/README.md), `docs/dev/manual-qa/` | DIY, appliance and release guides retain the checklist step IDs; the start page holds the run sheet, result rules and glossary. | diff --git a/os/rootfs/Dockerfile b/os/rootfs/Dockerfile index 645b4b3370..629afdb6c2 100644 --- a/os/rootfs/Dockerfile +++ b/os/rootfs/Dockerfile @@ -127,15 +127,17 @@ RUN chmod +x /usr/local/bin/docker-compose /usr/local/bin/cosign \ # cpupower CLI as linux-cpupower (linux-tools-common is Ubuntu's name and does not exist here). # msr-tools gives doctor its rdmsr probe; gettext-base is envsubst, which renders the unit on # every boot and is the ONLY tool a prebuilt tree strictly needs. Unsupported RigForge tests and their extra tool dependencies are not baked. +COPY os/rootfs/fetch-archive.sh /usr/local/bin/fetch-archive ARG RIGFORGE_REF=8f06cb8df791f3cb16d47bbee85fde92103cbe0b -RUN curl -fsSL -o /tmp/rigforge.tar.gz \ - "https://github.com/p2pool-starter-stack/rigforge/archive/${RIGFORGE_REF}.tar.gz" \ +RUN sh /usr/local/bin/fetch-archive \ + "https://github.com/p2pool-starter-stack/rigforge/archive/${RIGFORGE_REF}.tar.gz" /tmp/rigforge.tar.gz \ && mkdir -p /opt/rigforge \ && tar -xzf /tmp/rigforge.tar.gz -C /opt/rigforge --strip-components=1 \ && rm -rf /tmp/rigforge.tar.gz /opt/rigforge/tests \ && chmod +x /opt/rigforge/rigforge.sh \ && printf 'ref=%s version=%s\n' "$RIGFORGE_REF" "$(tr -d ' \t\r\n' /opt/rigforge/RIGFORGE_REF + >/opt/rigforge/RIGFORGE_REF \ + && rm /usr/local/bin/fetch-archive # Prebuild XMRig at RigForge's own pin, read from the baked tree so the two cannot drift. The # appliance may be Tor-only, and RigForge's build step clones github over clearnet — so the # clone happens HERE, on the build host, and pithead-sync seeds the result into the workspace diff --git a/os/rootfs/fetch-archive.sh b/os/rootfs/fetch-archive.sh new file mode 100644 index 0000000000..7b46f92799 --- /dev/null +++ b/os/rootfs/fetch-archive.sh @@ -0,0 +1,21 @@ +#!/bin/sh +set -eu + +url=$1 +destination=$2 + +for attempt in 1 2 3; do + printf 'Archive fetch %s: attempt %s/3 (180s deadline)\n' "$url" "$attempt" >&2 + if code=$(timeout --kill-after=5s 180s curl -fsSL -o "${destination}.part" -w '%{http_code}' "$url"); then + mv "${destination}.part" "$destination" + exit 0 + else + fetch_rc=$? + printf 'Archive fetch attempt %s/3 failed (exit %s, status %s)\n' "$attempt" "$fetch_rc" "${code:-000}" >&2 + fi + rm -f "${destination}.part" + if [ "$attempt" -lt 3 ]; then sleep "$((attempt * 5))"; fi +done + +printf 'Archive fetch exhausted after 3 attempts: %s (final status %s)\n' "$url" "${code:-000}" >&2 +exit 1 diff --git a/tests/os/selftest-archive-fetch.sh b/tests/os/selftest-archive-fetch.sh new file mode 100644 index 0000000000..3bf6eb1b50 --- /dev/null +++ b/tests/os/selftest-archive-fetch.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -euo pipefail +python3 "$(dirname "$0")/test_archive_fetch.py" diff --git a/tests/os/test_archive_fetch.py b/tests/os/test_archive_fetch.py new file mode 100644 index 0000000000..a69227c51d --- /dev/null +++ b/tests/os/test_archive_fetch.py @@ -0,0 +1,214 @@ +import functools +import http.server +import os +import re +import shutil +import subprocess +import tempfile +import threading +import time +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DOCKERFILE = Path(os.environ.get("ROOTFS_DOCKERFILE", ROOT / "os/rootfs/Dockerfile")) +RELEASE_DOCKERFILES = ( + (ROOT / "build/p2pool/Dockerfile", "p2pool.tar.gz"), + (ROOT / "build/xmrig-proxy/Dockerfile", "xmrig-proxy.tar.gz"), +) +PAYLOAD = b"archive bytes\n" + + +class FetchTestBase(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.served = self.root / "served" + self.served.mkdir() + (self.served / "payload.bin").write_bytes(PAYLOAD) + self.mode = "healthy" + self.interruptions = 0 + self.release = threading.Event() + self.requests = [] + owner = self + + class Handler(http.server.SimpleHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + owner.requests.append(self.path) + if owner.mode == "slow": + owner.release.wait(60) + self.close_connection = True + return + transient = owner.mode == "transient" and not owner.interruptions + if owner.mode == "failed" or transient: + owner.interruptions += 1 + self.send_response(504) + self.end_headers() + self.wfile.write(b"Gateway Time-out\n") + return + super().do_GET() + + handler = functools.partial(Handler, directory=str(self.served)) + self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + thread = threading.Thread(target=self.server.serve_forever) + thread.start() + self.addCleanup(thread.join) + self.addCleanup(self.server.server_close) + self.addCleanup(self.server.shutdown) + self.addCleanup(self.release.set) + self.url = f"http://127.0.0.1:{self.server.server_port}/payload.bin" + self.bin = self.root / "bin" + self.bin.mkdir() + self.sleep_log = self.root / "sleeps" + self.write_tool("sleep", f'printf "%s\\n" "$1" >> "{self.sleep_log}"\n') + self.env = { + key: value + for key, value in os.environ.items() + if key.lower() not in ("http_proxy", "https_proxy", "all_proxy") + } + self.env["PATH"] = str(self.bin) + os.pathsep + self.env["PATH"] + + def write_tool(self, name, body): + tool = self.bin / name + tool.write_text("#!/bin/sh\nset -eu\n" + body) + tool.chmod(0o755) + + def shorten_deadline(self): + real_timeout = shutil.which("timeout") + self.assertIsNotNone(real_timeout) + self.write_tool( + "timeout", + f'[ "$1" = --kill-after=5s ]\n[ "$2" = 180s ]\nshift 2\n' + f'exec "{real_timeout}" --kill-after=5s 1s "$@"\n', + ) + + def reset(self, mode): + self.mode = mode + self.interruptions = 0 + self.requests.clear() + + def assert_clean_failure(self, destination, result): + self.assertNotEqual(result.returncode, 0, result.stderr) + self.assertFalse(destination.exists()) + self.assertEqual(list(self.root.glob("destination*")), []) + + +class ArchiveLayerFetchTest(FetchTestBase): + def fetch(self): + dockerfile = DOCKERFILE.read_text().replace("\\\n", "") + command = next( + line[4:] + for line in dockerfile.splitlines() + if line.startswith("RUN sh /usr/local/bin/fetch-archive") + ) + command = command.split(" && mkdir -p /opt/rigforge", 1)[0] + command = command.replace( + '"https://github.com/p2pool-starter-stack/rigforge/archive/${RIGFORGE_REF}.tar.gz"', + f'"{self.url}"', + ) + command = command.replace( + "/usr/local/bin/fetch-archive", str(ROOT / "os/rootfs/fetch-archive.sh") + ) + destination = self.root / "destination.bin" + command = command.replace("/tmp/rigforge.tar.gz", str(destination)) # noqa: S108 + result = subprocess.run( # noqa: S603 + ["/bin/sh", "-eu", "-c", command], + env=self.env, + capture_output=True, + text=True, + timeout=25, + ) + return destination, result + + def test_healthy_fetch_succeeds_first_attempt(self): + self.reset("healthy") + destination, result = self.fetch() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(destination.read_bytes(), PAYLOAD) + self.assertEqual(len(self.requests), 1) + self.assertIn("attempt 1/3 (180s deadline)", result.stderr) + self.assertNotIn("attempt 2/3", result.stderr) + self.assertFalse(self.sleep_log.exists()) + + def test_transient_5xx_recovers_cleanly(self): + self.reset("transient") + destination, result = self.fetch() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(self.requests), 2) + self.assertEqual(destination.read_bytes(), PAYLOAD) + self.assertIn("attempt 2/3", result.stderr) + self.assertIn("failed (exit 22, status 504)", result.stderr) + self.assertEqual(self.sleep_log.read_text(), "5\n") + + def test_persistent_5xx_fails_after_bounded_attempts(self): + self.reset("failed") + destination, result = self.fetch() + self.assert_clean_failure(destination, result) + self.assertEqual(len(self.requests), 3) + self.assertEqual(result.stderr.count("(180s deadline)"), 3) + self.assertIn(f"exhausted after 3 attempts: {self.url} (final status 504)", result.stderr) + self.assertEqual(self.sleep_log.read_text(), "5\n10\n") + + def test_attempt_deadline_is_enforced(self): + self.shorten_deadline() + self.reset("slow") + started = time.monotonic() + destination, result = self.fetch() + self.assert_clean_failure(destination, result) + self.assertLess(time.monotonic() - started, 20) + self.assertEqual(result.stderr.count("failed (exit 124, status 000)"), 3) + self.assertEqual(self.sleep_log.read_text(), "5\n10\n") + + def test_dockerfile_copies_helper_in_the_stage_that_fetches(self): + dockerfile = DOCKERFILE.read_text() + stage = dockerfile[dockerfile.rindex("FROM debian") :] + run = stage[stage.index("RUN sh /usr/local/bin/fetch-archive") :] + run = run[: run.index("\n# ")] + self.assertIn(" && rm /usr/local/bin/fetch-archive", run) + copied = stage.index("COPY os/rootfs/fetch-archive.sh /usr/local/bin/fetch-archive") + self.assertLess(copied, stage.index("RUN sh /usr/local/bin/fetch-archive")) + + +@unittest.skipUnless(shutil.which("wget"), "needs GNU wget on PATH") +class ReleaseWgetFetchTest(FetchTestBase): + def wget(self, dockerfile, artifact): + text = Path(dockerfile).read_text().replace("\\\n", "") + line = next( + line[4:] + for line in text.splitlines() + if line.startswith("RUN wget") and artifact in line + ) + command = re.sub(r"https://\S+", self.url, line.split(" && echo", 1)[0]) + workdir = self.root / "workdir" + workdir.mkdir(exist_ok=True) + result = subprocess.run( # noqa: S603 + ["/bin/sh", "-eu", "-c", command], + env=self.env, + cwd=workdir, + capture_output=True, + text=True, + timeout=30, + ) + return workdir / artifact, result + + def test_release_fetch_bounds_the_attempts(self): + for dockerfile, artifact in RELEASE_DOCKERFILES: + for mode, attempts in (("healthy", 1), ("transient", 2), ("failed", 3)): + with self.subTest(artifact=artifact, mode=mode): + self.reset(mode) + artifact_path, result = self.wget(dockerfile, artifact) + self.assertEqual(len(self.requests), attempts, result.stderr) + if attempts < 3: + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(artifact_path.read_bytes(), PAYLOAD) + else: + self.assertNotEqual(result.returncode, 0) + artifact_path.unlink(missing_ok=True) + + +if __name__ == "__main__": + unittest.main() From 676b98c0f53206d62436c69456ddb4f834ae3926 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:28:08 -0600 Subject: [PATCH 026/112] P2Pool with zero peers for a bounded window is restarted, with backoff, and says so at the cap (#4077) (#4098) * P2Pool with zero peers for 15 minutes is restarted with backoff, a daily cap and an audit row (#4077) Co-Authored-By: Claude Sonnet 5.5 * tests(os): source the p2pool-heal phase in the module selftest (#4077) Co-Authored-By: Claude Sonnet 5.5 * tests: keep run-faults.sh within its budget; guest p2pool-heal reports diagnostics (#4077) Co-Authored-By: Claude Sonnet 5.5 * tests(os): p2pool-heal proves the control-path restart when the guest P2Pool reports no stats (#4077) Co-Authored-By: Claude Sonnet 5.5 * tests(os): name what the p2pool-heal row proves (#4077) Co-Authored-By: Claude Sonnet 5.5 * tests(os): p2pool-heal starts a gate-stopped guest P2Pool before the control-path proof (#4077) Co-Authored-By: Claude Sonnet 5.5 * tests(os): leave the run.sh usage comment as it was (#4077) Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- .../mining_dashboard/service/data_service.py | 4 +- .../mining_dashboard/service/data_setup.py | 6 + .../service/health/p2pool_heal.py | 161 ++++++++++++ .../tests/service/health/test_p2pool_heal.py | 244 ++++++++++++++++++ docs/dev/repo-map.md | 4 + docs/dev/testing-strategy.md | 1 + docs/operations.md | 18 ++ tests/integration/lib/run-faults.sh | 2 +- tests/integration/lib/run-pool-peer-loss.sh | 99 +++++++ tests/integration/run.sh | 2 + .../selftest/selftest-pool-peer-loss.sh | 74 ++++++ .../selftest/selftest-run-modules.sh | 6 +- tests/os/README.md | 7 + tests/os/phases/pool-heal.sh | 19 ++ tests/os/pool-heal-guest.sh | 107 ++++++++ tests/os/run.sh | 3 + tests/os/selftest-pool-heal.sh | 38 +++ tests/os/selftest-run-modules.sh | 10 +- 18 files changed, 794 insertions(+), 11 deletions(-) create mode 100644 dashboard/mining_dashboard/service/health/p2pool_heal.py create mode 100644 dashboard/tests/service/health/test_p2pool_heal.py create mode 100644 tests/integration/lib/run-pool-peer-loss.sh create mode 100755 tests/integration/selftest/selftest-pool-peer-loss.sh create mode 100644 tests/os/phases/pool-heal.sh create mode 100755 tests/os/pool-heal-guest.sh create mode 100755 tests/os/selftest-pool-heal.sh diff --git a/dashboard/mining_dashboard/service/data_service.py b/dashboard/mining_dashboard/service/data_service.py index b8062d9a43..8d5a30ce7d 100644 --- a/dashboard/mining_dashboard/service/data_service.py +++ b/dashboard/mining_dashboard/service/data_service.py @@ -584,10 +584,8 @@ async def run(self): if self.healthchecks.enabled: await asyncio.to_thread(self.healthchecks.ping) - # 6c. Tor guard self-heal (#424): when opted in, probe Tor clearnet egress - # (self-throttled) and restart tor if it's stuck on a failing guard — - # bounded, cooled-down, loud. Off (the default) this is a plain no-op. await self.tor_healer.check() + await self.p2pool_healer.check(p2pool_stats) # 7. External XvB stats sync over Tor (#163), throttled to every 10th iteration, # and ONLY when XvB is enabled — disabling XvB must stop the egress entirely. diff --git a/dashboard/mining_dashboard/service/data_setup.py b/dashboard/mining_dashboard/service/data_setup.py index 85282d4816..2dcc505bfc 100644 --- a/dashboard/mining_dashboard/service/data_setup.py +++ b/dashboard/mining_dashboard/service/data_setup.py @@ -1,5 +1,6 @@ import logging import os +from functools import partial from mining_dashboard.client.docker.docker_control import DockerControl from mining_dashboard.client.monero.monero_wallet_client import MoneroWalletClient @@ -27,6 +28,7 @@ from mining_dashboard.service.health.monero_health import MoneroChainHealth from mining_dashboard.service.health.node_alert import tor_heal_status from mining_dashboard.service.health.node_health import NodeHealthMonitor +from mining_dashboard.service.health.p2pool_heal import P2PoolPeerHealer from mining_dashboard.service.health.tari_health import TariChainHealth from mining_dashboard.service.health.tor_heal import TorEgressHealer from mining_dashboard.service.health.update_checker import GitHubReleaseClient, UpdateChecker @@ -219,6 +221,10 @@ def __init__(self, state_manager, proxy_client, xvb_client): # tip, no peers, behind the explorer). Detection and alert only; the alert rides the same # always-on sender as the tor-heal note. self.tari_chain = TariChainHealth(notify=self.alert_service.tor_heal_alert) + self.p2pool_healer = P2PoolPeerHealer( + self.docker_control, + audit=partial(self._record_audit_event, "p2pool-heal", "p2pool-heal"), + ) # Hashrate-degradation detector (Issue #99): flags a sustained total-hashrate drop and its # recovery. Runs every cycle (cheap, self-contained EMA baseline) so it can mark the chart # even with Telegram off; a loss also drives a hashrate_loss alert. diff --git a/dashboard/mining_dashboard/service/health/p2pool_heal.py b/dashboard/mining_dashboard/service/health/p2pool_heal.py new file mode 100644 index 0000000000..fbb32c492b --- /dev/null +++ b/dashboard/mining_dashboard/service/health/p2pool_heal.py @@ -0,0 +1,161 @@ +import asyncio +import logging +import time +from collections import deque + +from mining_dashboard.collector.containers import get_container_health + +logger = logging.getLogger("P2PoolHeal") + +ZERO_PEERS_AFTER_SEC = 15 * 60 +REJOIN_WAIT_SEC = 20 * 60 +MAX_REJOIN_WAIT_SEC = 80 * 60 +MAX_RESTARTS_PER_DAY = 3 +DAY_SEC = 24 * 60 * 60 +P2POOL_STOP_GRACE_SEC = 30 +P2POOL_STOP_REQUEST_TIMEOUT_SEC = 90 +P2POOL_START_ATTEMPTS = 3 +P2POOL_START_RETRY_DELAY_SEC = 5 +P2POOL_LATE_START_CYCLES = 3 +STATS_STALE_SEC = 120 + + +class P2PoolPeerHealer: + CONTAINER = "p2pool" + + def __init__(self, docker_control, audit=None, clock=time.monotonic): + self._docker = docker_control + self._audit = audit + self._clock = clock + self._zero_since = None + self._restarts = deque() + self._outage_restarts = 0 + self._next_allowed = None + self._awaiting_tip = False + self._tip_mark = None + self._warned_cap = False + self._uptime = None + self._uptime_changed = None + self._late_starts = 0 + + async def check(self, p2pool_stats) -> None: + try: + await self._check(p2pool_stats) + except Exception as exc: + logger.warning("P2Pool heal cycle failed (%s)", type(exc).__name__) + + async def _check(self, p2pool_stats) -> None: + now = self._clock() + if self._late_starts: + await self._retry_start() + p2p = p2pool_stats.get("p2p", {}) + uptime = p2p.get("uptime") + if not uptime: + self._zero_since = None + return + if uptime != self._uptime: + self._uptime = uptime + self._uptime_changed = now + elif now - self._uptime_changed >= STATS_STALE_SEC: + self._zero_since = None + return + peers = (p2p.get("out_peers") or 0) + (p2p.get("in_peers") or 0) + if peers > 0: + self._zero_since = None + self._observe_tip(p2pool_stats.get("pool", {}).get("sidechain_height")) + return + self._tip_mark = None + if self._zero_since is None: + self._zero_since = now + if now - self._zero_since < ZERO_PEERS_AFTER_SEC: + return + if self._next_allowed is not None and now < self._next_allowed: + return + while self._restarts and now - self._restarts[0] >= DAY_SEC: + self._restarts.popleft() + if len(self._restarts) < MAX_RESTARTS_PER_DAY: + self._warned_cap = False + if len(self._restarts) >= MAX_RESTARTS_PER_DAY: + if not self._warned_cap: + self._warned_cap = True + logger.warning( + "P2Pool still has no peers after %d automatic restarts in 24 hours. " + "No more automatic action; run './pithead doctor' and restart it with " + "'./pithead restart p2pool'.", + MAX_RESTARTS_PER_DAY, + ) + return + health = (await get_container_health()).get(self.CONTAINER) + if not health or not health.get("running") or health.get("restarting"): + self._zero_since = None + return + await self._restart(now, (now - self._zero_since) / 60) + + async def _retry_start(self) -> None: + health = (await get_container_health()).get(self.CONTAINER) + if not health or health.get("running") or health.get("restarting"): + self._late_starts = 0 + return + self._late_starts -= 1 + if await self._docker.start(self.CONTAINER, request_timeout=60): + self._late_starts = 0 + logger.warning( + "P2Pool started on a later cycle after the restart's start was unconfirmed." + ) + + def _observe_tip(self, height) -> None: + if not self._awaiting_tip or not isinstance(height, int) or height <= 0: + return + if self._tip_mark is None: + self._tip_mark = height + elif height > self._tip_mark: + logger.info( + "P2Pool rejoined the sidechain after %d automatic restart(s): tip %d -> %d.", + self._outage_restarts, + self._tip_mark, + height, + ) + self._awaiting_tip = False + self._tip_mark = None + self._outage_restarts = 0 + self._next_allowed = None + self._warned_cap = False + + async def _restart(self, now, outage_minutes) -> None: + self._outage_restarts += 1 + self._restarts.append(now) + wait = min(REJOIN_WAIT_SEC * 2 ** (self._outage_restarts - 1), MAX_REJOIN_WAIT_SEC) + self._next_allowed = now + wait + self._awaiting_tip = True + self._tip_mark = None + self._zero_since = None + logger.warning( + "P2Pool has had no peers for %.0f minutes. Restarting it (%d/%d in 24 hours); " + "next restart no sooner than %d minutes if the sidechain tip does not resume.", + outage_minutes, + len(self._restarts), + MAX_RESTARTS_PER_DAY, + wait // 60, + ) + stopped = await self._docker.stop( + self.CONTAINER, + stop_timeout=P2POOL_STOP_GRACE_SEC, + request_timeout=P2POOL_STOP_REQUEST_TIMEOUT_SEC, + ) + started = False + for attempt in range(P2POOL_START_ATTEMPTS): + if attempt: + await asyncio.sleep(P2POOL_START_RETRY_DELAY_SEC) + if await self._docker.start(self.CONTAINER, request_timeout=60): + started = True + break + logger.warning( + "P2Pool restart control results: stop=%s, start=%s.", + "confirmed" if stopped else "unconfirmed", + "confirmed" if started else "unconfirmed", + ) + self._late_starts = 0 if started else P2POOL_LATE_START_CYCLES + if self._audit is not None: + await self._audit( + "restart", "applied" if stopped and started else "unconfirmed", "p2pool" + ) diff --git a/dashboard/tests/service/health/test_p2pool_heal.py b/dashboard/tests/service/health/test_p2pool_heal.py new file mode 100644 index 0000000000..3be060ce10 --- /dev/null +++ b/dashboard/tests/service/health/test_p2pool_heal.py @@ -0,0 +1,244 @@ +import itertools +import logging +from unittest.mock import AsyncMock, patch + +import pytest + +from mining_dashboard.service.health.p2pool_heal import ( + DAY_SEC, + MAX_REJOIN_WAIT_SEC, + MAX_RESTARTS_PER_DAY, + P2POOL_LATE_START_CYCLES, + REJOIN_WAIT_SEC, + STATS_STALE_SEC, + ZERO_PEERS_AFTER_SEC, + P2PoolPeerHealer, +) +from tests.service.health.test_tor_heal import _Clock, _FakeDocker + +HEALTH = "mining_dashboard.service.health.p2pool_heal.get_container_health" + + +_UPTIME = itertools.count(1) + + +def _stats(peers=0, height=100, uptime=None): + uptime = next(_UPTIME) if uptime is None else uptime + return { + "p2p": {"out_peers": peers, "in_peers": 0, "uptime": uptime}, + "pool": {"sidechain_height": height}, + } + + +@pytest.fixture(autouse=True) +def _p2pool_running(): + with ( + patch(HEALTH, AsyncMock(return_value={"p2pool": {"running": True}})) as health, + patch("mining_dashboard.service.health.p2pool_heal.asyncio.sleep", AsyncMock()), + ): + yield health + + +def _healer(docker=None, audit=None): + clock = _Clock() + return P2PoolPeerHealer(docker or _FakeDocker(), audit=audit, clock=clock), clock + + +async def _peerless_for(healer, clock, seconds, step=60): + end = clock.t + seconds + while clock.t < end: + await healer.check(_stats()) + clock.t += step + await healer.check(_stats()) + + +class TestPeerlessWindow: + async def test_peerless_window_restarts_p2pool_and_audits(self, caplog): + docker = _FakeDocker() + audit = AsyncMock() + healer, clock = _healer(docker, audit) + with caplog.at_level(logging.WARNING, logger="P2PoolHeal"): + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + assert docker.calls == [("stop", "p2pool"), ("start", "p2pool")] + audit.assert_awaited_once_with("restart", "applied", "p2pool") + assert "has had no peers for" in caplog.text + + async def test_a_peerless_blip_never_restarts(self): + docker = _FakeDocker() + healer, clock = _healer(docker) + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC - 120) + await healer.check(_stats(peers=3)) + clock.t += 600 + await healer.check(_stats()) + assert docker.calls == [] + + async def test_an_unread_stats_file_is_not_a_zero_peer_reading(self): + docker = _FakeDocker() + healer, clock = _healer(docker) + for _ in range(ZERO_PEERS_AFTER_SEC // 60 + 5): + await healer.check(_stats(uptime=0)) + clock.t += 60 + assert docker.calls == [] + + async def test_an_absent_or_stopped_p2pool_is_never_touched(self, _p2pool_running): + docker = _FakeDocker() + healer, clock = _healer(docker) + for health in ({}, {"p2pool": {"running": False}}, {"p2pool": {"restarting": True}}): + _p2pool_running.return_value = health + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + assert docker.calls == [] + + async def test_a_failed_start_is_retried_and_the_attempt_is_kept(self): + class _Down(_FakeDocker): + async def start(self, container, **kwargs): + await super().start(container, **kwargs) + return False + + docker = _Down() + audit = AsyncMock() + healer, clock = _healer(docker, audit) + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + assert [c for c in docker.calls if c[0] == "start"] == [("start", "p2pool")] * 3 + audit.assert_awaited_once_with("restart", "unconfirmed", "p2pool") + + +class TestBackoffAndCap: + async def test_still_peerless_waits_for_the_rejoin_window_then_restarts_again(self): + docker = _FakeDocker() + healer, clock = _healer(docker) + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + assert len(docker.calls) == 2 + await _peerless_for(healer, clock, REJOIN_WAIT_SEC - 2 * 60) + assert len(docker.calls) == 2 + await _peerless_for(healer, clock, 3 * 60) + assert len(docker.calls) == 4 + + async def test_backoff_doubles_and_is_bounded(self): + healer, clock = _healer() + waits = [] + for _ in range(MAX_RESTARTS_PER_DAY): + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + waits.append(healer._next_allowed - healer._restarts[-1]) + clock.t = healer._next_allowed + assert waits == [REJOIN_WAIT_SEC, 2 * REJOIN_WAIT_SEC, MAX_REJOIN_WAIT_SEC] + + async def test_cap_stops_restarting_and_says_so_once(self, caplog): + docker = _FakeDocker() + healer, clock = _healer(docker) + with caplog.at_level(logging.WARNING, logger="P2PoolHeal"): + for _ in range(MAX_RESTARTS_PER_DAY + 2): + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC + MAX_REJOIN_WAIT_SEC) + assert [c for c in docker.calls if c[0] == "stop"] == [("stop", "p2pool")] * ( + MAX_RESTARTS_PER_DAY + ) + assert caplog.text.count("No more automatic action") == 1 + + async def test_the_daily_cap_refills_after_a_day(self): + docker = _FakeDocker() + healer, clock = _healer(docker) + for _ in range(MAX_RESTARTS_PER_DAY): + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC + MAX_REJOIN_WAIT_SEC) + stops = len([c for c in docker.calls if c[0] == "stop"]) + clock.t += DAY_SEC + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + assert len([c for c in docker.calls if c[0] == "stop"]) == stops + 1 + + +class TestRecovery: + async def test_peers_alone_do_not_end_the_outage_until_the_tip_moves(self, caplog): + healer, clock = _healer() + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + with caplog.at_level(logging.INFO, logger="P2PoolHeal"): + await healer.check(_stats(peers=4, height=1)) + await healer.check(_stats(peers=4, height=1)) + assert healer._awaiting_tip + assert "rejoined" not in caplog.text + await healer.check(_stats(peers=4, height=7)) + assert not healer._awaiting_tip + assert "rejoined the sidechain" in caplog.text + assert healer._outage_restarts == 0 + + async def test_recovery_resets_backoff_so_the_next_outage_starts_fresh(self): + docker = _FakeDocker() + healer, clock = _healer(docker) + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + await healer.check(_stats(peers=4, height=1)) + await healer.check(_stats(peers=4, height=2)) + clock.t += 5 * 60 + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + assert [c for c in docker.calls if c[0] == "stop"] == [("stop", "p2pool")] * 2 + + async def test_a_peerless_dip_after_restart_restarts_the_tip_baseline(self): + healer, clock = _healer() + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + await healer.check(_stats(peers=4, height=50)) + await healer.check(_stats(peers=0, height=50)) + await healer.check(_stats(peers=4, height=10)) + assert healer._awaiting_tip + + +class TestGuards: + async def test_a_stats_file_that_stopped_updating_is_not_a_zero_peer_reading(self): + docker = _FakeDocker() + healer, clock = _healer(docker) + for _ in range((ZERO_PEERS_AFTER_SEC + 2 * STATS_STALE_SEC) // 60): + await healer.check(_stats(uptime=500)) + clock.t += 60 + assert docker.calls == [] + + async def test_a_zero_height_is_not_a_tip_baseline(self): + healer, clock = _healer() + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + await healer.check(_stats(peers=4, height=0)) + await healer.check(_stats(peers=4, height=9)) + assert healer._awaiting_tip + await healer.check(_stats(peers=4, height=12)) + assert not healer._awaiting_tip + + async def test_the_cap_warning_is_given_again_after_the_daily_cap_refills(self, caplog): + healer, clock = _healer() + with caplog.at_level(logging.WARNING, logger="P2PoolHeal"): + for _ in range(MAX_RESTARTS_PER_DAY + 1): + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC + MAX_REJOIN_WAIT_SEC) + clock.t += DAY_SEC + for _ in range(MAX_RESTARTS_PER_DAY + 1): + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC + MAX_REJOIN_WAIT_SEC) + assert caplog.text.count("No more automatic action") == 2 + + async def test_a_restart_whose_start_was_unconfirmed_is_started_on_a_later_cycle( + self, _p2pool_running + ): + class _SlowStart(_FakeDocker): + def __init__(self): + super().__init__() + self.refuse = True + + async def start(self, container, **kwargs): + await super().start(container, **kwargs) + return not self.refuse + + docker = _SlowStart() + healer, clock = _healer(docker) + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + calls = len(docker.calls) + docker.refuse = False + _p2pool_running.return_value = {"p2pool": {"running": False}} + await healer.check(_stats()) + assert docker.calls[calls:] == [("start", "p2pool")] + await healer.check(_stats()) + assert len(docker.calls) == calls + 1 + + async def test_late_start_attempts_are_bounded(self, _p2pool_running): + class _Refuse(_FakeDocker): + async def start(self, container, **kwargs): + await super().start(container, **kwargs) + return False + + docker = _Refuse() + healer, clock = _healer(docker) + await _peerless_for(healer, clock, ZERO_PEERS_AFTER_SEC) + calls = len(docker.calls) + _p2pool_running.return_value = {"p2pool": {"running": False}} + for _ in range(P2POOL_LATE_START_CYCLES + 3): + await healer.check(_stats()) + assert len(docker.calls) == calls + P2POOL_LATE_START_CYCLES diff --git a/docs/dev/repo-map.md b/docs/dev/repo-map.md index 323634bbe0..a05f1d1f99 100644 --- a/docs/dev/repo-map.md +++ b/docs/dev/repo-map.md @@ -164,6 +164,7 @@ Explicit saturated Tor circuit-history recovery is in `02e-tor-recovery.sh`; its read-only authenticated bootstrap probe is `build/tor/recovery-diagnose.sh`; the dashboard's clearnet healer stays in `service/health/tor_heal.py`, with host history observations and recovery results in `service/health/tor_heal_history.py`. +The P2Pool zero-peer watchdog is `service/health/p2pool_heal.py`. The automatic `tor-recover` control wrapper is `48b-control-tor-recover.sh`; it calls the same host-gated recovery as the CLI. @@ -380,6 +381,9 @@ through `caddy-failure-evidence.sh` for a bounded, allowlisted guest snapshot; `tests/os/selftest-caddy-failure-evidence.sh` exercises collection and the failure branch. The opt-in KVM `tor-heal` phase streams `tor-heal-guest.sh` into an isolated guest to prove saturated-history recovery and the disabled control with production timers. +The opt-in KVM `p2pool-heal` phase streams `pool-heal-guest.sh` into a guest to prove the dashboard's +zero-peer P2Pool restart through the appliance control path; `run-pool-peer-loss.sh` is the `fault-injection` leg that +cuts a live P2Pool's peers. The restrictive-checkout image probe is `tests/stack/standalone/test_image_permissions.sh`, run by image CI and the lifecycle phase through `run-source-image.sh`. The offline image assertion is `tests/stack/standalone/test_tor_saturated_image.sh`, diff --git a/docs/dev/testing-strategy.md b/docs/dev/testing-strategy.md index a1a83fd8fe..02515aedf8 100644 --- a/docs/dev/testing-strategy.md +++ b/docs/dev/testing-strategy.md @@ -385,6 +385,7 @@ the situations above; `missing` means nothing does yet, with the issue that owns | p2pool actually reached the Tari node over gRPC (#1397): the merge-mining client's `uses chain_id` line, which p2pool cannot log without a successful call to the node. Its two sibling lines land ~175 ms earlier and are local, so a check keyed on them would pass with Tari unreachable — that case is a distinct `local-only` verdict and fails. The startup signal may be delayed by Monero RPC retries. Poll for up to 120 seconds at 2-second intervals, strip ANSI escapes before matching, and reject success across a container epoch change. Log-read failure is binding and distinct from readiness expiry | live p2pool log since the current container epoch, with bounded target-filtered output and no first-lines cap | 1 ✅ (verdicts, capture bounds and the ANSI control, `selftest-mergemine-probe.sh`; delayed readiness, persistent failure and epoch controls in `selftest-mergemine-readiness.sh`) · 4 ✅ (the leg — run against the live stack read-only, not yet inside a full gate run) | | A live Tari node stranded from its peers stops reading healthy, and recovers (#2464). An iptables rule in the tari container's own network namespace, tagged `pithead-e2e-fault-tari-stranded`, drops its traffic to tor. It is not a host `DOCKER-USER` rule, because same-bridge traffic does not reach that chain without br_netfilter (job 1315). The leg fails straight away if the rule is not in place, and reports the rule's drop counter whenever a verdict wait fails. The leg waits (up to 25 minutes) for the node's first zero-peer reading and records that disconnect latency on its own row, since it varies from about 3 to over 15 minutes (jobs 1324, 1611); it then asserts the verdict goes amber within 10 minutes of that reading plus a poll, then red with a non-zero doctor exit and a red `pithead status` line within 30 minutes plus a poll. The panel reads red with its reasons, and the red alert reaches a loopback webhook fed by the sender Telegram uses; delivery by Telegram itself is a counted `missing` skip. After six more minutes of red, neither tari nor p2pool has restarted: detection only, with remediation in #2827. It then removes the rule and asserts the node rejoins on its own, the verdict returns to green without a restart, and the recovery note is sent. The rule is also removed by an EXIT trap, and the leg asserts none is left | a local Tari node, passwordless `sudo nsenter` and `iptables` on the box | 1 ✅ (verdict and alerts: `test_tari_health.py`; doctor/status: `tests/stack/test-tari-chain.sh`) · 4 ▶ (`run.sh --tari-stranded`; bench-ci phase `tari-stranded`, about an hour, opt-in) | | Tor clearnet probe failure (#2458) is corroborated on isolated circuits and a second target before bounded NEWNYM; local Monero re-dials only after a real Tor restart. The `fault-injection` row blocks the dashboard-to-Tor SOCKS dial in the dashboard's network namespace for 25 minutes, preserving Tor's relay and onion connections, then checks read-only access to the live Tor state and onion identities, the rule's dropped-packet counter, logged targets, NEWNYM, a proxy worker online at every minute and at least one accepted share in each five-minute window, container start times and recovery after unblock. With `--no-mining-asserts`, the entire Tor clearnet probe fault leg is a named `by-design` skip before any live probe, config change or firewall rule; it cannot prove mining continuity without a miner. Without that flag, a missing mining witness still fails. A mining failure during the fault does not shorten it, so the Tor assertions still run. The proxy counter includes shares while the worker is on a donation pool; P2Pool's session hash counter does not. Same-bridge traffic bypasses the host OUTPUT hook. The row never disables the stack's Tor-egress firewall. The separate `tor-recover` check/apply contract requires saturated circuit history plus either a peerless, stalled local Monero or, when RPC is unavailable, sustained authenticated bootstrap 95%, no established circuit and repeated recent invalid timing warnings. Its pure CLI tests cover positive check/apply paths, refusal, identity/chain preservation and protocol errors; `test_tor_bootstrap_recovery.sh` covers the unavailable-RPC path and `test_tor_heal_outage_recovery.sh` the sustained-heal-outage class (#3052: refused without two rounds from one outage, after recovery, with stale evidence, working egress or an unsaturated history) and the read-only `tor-history` verb the dashboard heal uses to alert on a saturated history. The lifecycle healthy-Tor refusal probe retries only mutation-lock exit 75 every two seconds within a monotonic 60-second command budget (with a two-second kill grace) before judging the original exit-1 and unsaturated-history assertions. `tor-recovery-admission.log` retains each attempt’s elapsed time and exit status plus lock-record and kernel-owner fields on contention, capped at 16 kernel owners and a five-second sampler deadline; it excludes paths, command arguments and raw CLI output. Persistent contention fails the guard assertions. `selftest-tor-probe-fault.sh` covers clearing and persistent overlap, other exit codes and diagnostic projection. The live row does not poison Tor state or exercise positive apply. | active rig and local Monero; host `nsenter` and `iptables` privilege for the live fault | 1 ✅ (`test_tor_heal.py`, `test_tor_heal_refresh.py`, `test_tor_recovery.sh`, `test_tor_heal_outage_recovery.sh`, `selftest-run-modules.sh`, `selftest-tor-probe-fault.sh`, `selftest-fault-rules.sh`) · 4 ▶ (`fault-injection` phase on the tested head) | +| P2Pool with **zero peers** for 15 minutes is restarted by the dashboard with 20/40/80-minute backoff, a cap of three per 24 hours, a log line and an audit row, and recovery is judged on sidechain tip progress (#4077); a stopped, restarting or absent `p2pool` and an unread stats file are never touched | zero out and in connections for 15 minutes with a running local `p2pool` | 1 ✅ (`test_p2pool_heal.py`, `selftest-pool-peer-loss.sh`, `selftest-pool-heal.sh`) · 4 (`fault-injection` row cuts every P2Pool peer path and requires an unattended restart and tip resume; opt-in KVM `p2pool-heal` phase restarts the guest P2Pool through the appliance container control path) | | P2Pool's Tari merge-mining payload against Tari's own validator across the mainnet 350,000 fork (#2586, V6 of #1129). A throwaway, peerless P2Pool built from `build/p2pool` with the archive under test mines against the box's monerod and a recording Tari node serving mainnet templates at 349,999, 350,000 and 350,001. The fixture in `tests/integration/mergemine/`, compiled inside Tari's workspace at the pinned tag, runs Tari's `monero_randomx_difficulty` under MainNet constants on each submission and on two controls built from the same Monero block: the legacy Keccak-state payload and a one-bit-mutated prefix. Tari picks the format by height, so the prefix payload must be rejected at 349,999 and the legacy one accepted there; from 350,000 the prefix payload is accepted and both controls are rejected, each with Tari's reason printed. The one test-only deviation: achieved work is compared with the test difficulty, not mainnet's target (both printed). Nothing reaches Tari mainnet | local Monero on the box, both wallets in `config.json` | 1 ✅ (row mapping, skip and cleanup, `selftest-mergemine-submit.sh`) · 4 ▶ (`run.sh --mergemine-submit`; bench-ci phase `mergemine-submit`) | | A live Tari node accepts P2Pool 4.18.1's blocks (#2589, V5 of #1129). The shipping `minotari_node` build runs only MainNet and StageNet. Mainnet is off limits, and StageNet never activates the coinbase-prefix payload. The node is therefore Tari's published `-esme` image of the release `docker-compose.yml` pins: the same source revision, built for the testnet target, running LocalNet with the payload active from height 0. The leg prints both images' revisions and build targets, and fails unless the revision and version match the shipping image. The node runs alone on an `--internal` docker network at LocalNet's fixed difficulty of 1. A throwaway P2Pool built from `build/p2pool` with the archive under test joins that network and `mining_net`, reads the box's monerod and mines until it reports blocks at five heights. `tests/integration/mergemine/localnet_probe.py` then reads every reported block back from the node. Tari's SubmitBlock also answers OK for an orphan, so a block counts only when it is on the node's main chain at the reported height, mined with RandomXM, and every submitted height needs one (at least three). Each accepted block's parent must be the previous accepted block, and P2Pool must take the next height's template after it. Nothing reaches Tari mainnet | local Monero on the box, both wallets in `config.json` | 1 ✅ (probe decoding and verdicts, the image pin, skips and cleanup, `selftest-mergemine-localnet.sh`) · 4 ▶ (`run.sh --mergemine-localnet`; bench-ci phase `mergemine-localnet`) | | Caddy TLS scheme; Tor onion provisioning; HugePages/AVX2; real disk pressure; prune DB size | real host | 4 ▶ | diff --git a/docs/operations.md b/docs/operations.md index ebd021e392..b36e7566a9 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1029,6 +1029,24 @@ restarts or recreates tor (`up`, `apply`, `upgrade`, `restart tor`), and the fin Local node only. With `monero.mode: remote` there is no `monerod` here to restart and doctor's Monero sync check skips, so a stranded node is the remote host's problem to detect and fix. +**P2Pool has no peers.** P2Pool can log `no connections to other p2pool nodes` for hours while +monerod and Tor look healthy; it then mines a private sidechain and its shares never reach the +pool (#4077). The dashboard restarts P2Pool by itself, with no opt-in and no setting to tune. The +bounds are fixed: + +- **Trigger:** the dashboard reads zero outgoing and zero incoming P2Pool connections continuously + for 15 minutes. A stats file it cannot read or that stopped updating, a stopped or restarting `p2pool` container (the + sync gate holds it stopped while the node syncs) and a box with no local `p2pool` container are + never a trigger. +- **Recovery is the sidechain tip, not the container.** After a restart the outage stays open until + peers are back and the sidechain height then advances. A real rejoin took about 16 minutes (#4045), so the + next restart waits 20 minutes, then 40, then 80 if P2Pool is still peerless. +- **Cap:** at most 3 automatic restarts in any 24 hours. After the third, the dashboard logs + `No more automatic action` once and stops until a restart ages out or the tip resumes; restart + by hand with `./pithead restart p2pool`. +- **Trail:** every restart logs a `P2PoolHeal` warning in the dashboard log and writes a + `p2pool-heal` row (action `restart`, status `applied` or `unconfirmed`) to the audit log. + **Monero node isolated or not advancing.** A local monerod can keep `synchronized: true` and a green RPC healthcheck while it has no outgoing peers, or while its tip stops moving because every peer sits on the same stale block (#2499). The diff --git a/tests/integration/lib/run-faults.sh b/tests/integration/lib/run-faults.sh index 6b6e35f7dc..959bab7e22 100644 --- a/tests/integration/lib/run-faults.sh +++ b/tests/integration/lib/run-faults.sh @@ -366,9 +366,9 @@ run_fault_injection() { fault_disk_enospc fault_p2pool_cold_cache_dns fault_p2pool_sidechain_sync + fault_p2pool_peer_loss fault_tor_probe_egress [ "$IT_FAIL" -gt "$fails_before" ] && capture_artifacts "fault-injection" "$OUT_DIR" - # Belt-and-braces: whatever happened above, leave monerod + tor up, the dashboard data dir # writable (real fs, not the ENOSPC tmpfs), the firewall reinstated, the timedatectl shadow # gone, and the stack healthy — all unconditional so a mid-phase abort can't leave the box diff --git a/tests/integration/lib/run-pool-peer-loss.sh b/tests/integration/lib/run-pool-peer-loss.sh new file mode 100644 index 0000000000..12bf974ec3 --- /dev/null +++ b/tests/integration/lib/run-pool-peer-loss.sh @@ -0,0 +1,99 @@ +# shellcheck shell=bash +: "${INTEGRATION_RUN_SUITE:?source via the suite runner}" + +P2POOL_PEER_LOSS_TAG="pithead-e2e-fault-p2pool-peers" +P2POOL_PEER_LOSS_DISCONNECT_MAX=1500 +P2POOL_PEER_LOSS_RESTART_MAX=2400 +P2POOL_PEER_LOSS_REJOIN_MAX=1800 + +p2pool_ns_ipt() { + rx "p=\$(docker inspect -f '{{.State.Pid}}' p2pool 2>/dev/null); [ \"\${p:-0}\" -gt 0 ] && sudo -n nsenter -t \"\$p\" -n iptables $*" 2>/dev/null +} +p2pool_peer_loss_rules() { + printf '%s\n' \ + "OUTPUT -d $1 -m comment --comment $P2POOL_PEER_LOSS_TAG -j DROP" \ + "OUTPUT -p tcp --dport 37888:37890 -m comment --comment $P2POOL_PEER_LOSS_TAG -j DROP" \ + "OUTPUT -p tcp --sport 37888:37890 -m comment --comment $P2POOL_PEER_LOSS_TAG -j DROP" \ + "INPUT -p tcp --dport 37888:37890 -m comment --comment $P2POOL_PEER_LOSS_TAG -j DROP" +} +p2pool_peer_loss_count() { + local chain total=0 n + for chain in INPUT OUTPUT; do + n=$(p2pool_ns_ipt "-S $chain" | grep -c -- "$P2POOL_PEER_LOSS_TAG") + total=$((total + n)) + done + printf '%s\n' "$total" +} +p2pool_peer_total() { + local pdir + pdir=$(env_on_box P2POOL_DATA_DIR) + rx "sudo -n cat $(quote_arg "$pdir/stats/local/p2p") 2>/dev/null | jq -r '(.connections // 0) + (.incoming_connections // 0)'" 2>/dev/null +} +p2pool_started_at() { rx "docker inspect p2pool --format '{{.State.StartedAt}}'" 2>/dev/null; } +_pred_p2pool_peerless() { [ "$(p2pool_peer_total)" = 0 ]; } +_pred_p2pool_restarted() { [ "$(p2pool_started_at)" != "$1" ]; } +_pred_p2pool_has_peers() { [ "$(p2pool_peer_total)" -gt 0 ] 2>/dev/null; } +_pred_p2pool_rejoin_logged() { + rx "docker logs --since $1 dashboard 2>&1 | grep -q 'P2Pool rejoined the sidechain'" >/dev/null 2>&1 +} + +fault_p2pool_peer_loss() { + local tor pdir started epoch t0 t_zero logs rule restarts + pdir=$(env_on_box P2POOL_DATA_DIR) + if [ -z "$pdir" ]; then + it_fail "p2pool peer-loss leg has a data dir (#4077)" "no P2POOL_DATA_DIR in .env" + return + fi + fault_rules_clear_all + tor=$(rx "docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' tor" 2>/dev/null | head -n1) + if [ -z "$tor" ]; then + it_fail "p2pool peer-loss leg finds the tor address (#4077)" "empty, fault not injected" + return + fi + if ! wait_for 900 10 "p2pool holding peers before the fault" _pred_p2pool_has_peers; then + it_skip_leg "p2pool peer-loss: cut a P2Pool that holds peers (#4077)" "p2pool had no peer for 15 minutes before any fault" "missing" + return + fi + started=$(p2pool_started_at) + epoch=$(rx 'date +%s') + fault_rules_trap_arm + it_step "fault: cut every P2Pool peer path inside p2pool's network namespace ($P2POOL_PEER_LOSS_TAG)…" + while IFS= read -r rule; do + p2pool_ns_ipt "-I $rule" >/dev/null + done < <(p2pool_peer_loss_rules "$tor") + t0=$(now_s) + if [ "$(p2pool_peer_loss_count)" -ge 4 ] 2>/dev/null; then + it_pass "p2pool peer-loss: the four DROP rules are in p2pool's namespace (#4077)" + else + it_fail "p2pool peer-loss: the four DROP rules are in p2pool's namespace (#4077)" "not found, fault not injected" + fault_rules_clear_all + fault_rules_trap_disarm + return + fi + if wait_for "$P2POOL_PEER_LOSS_DISCONNECT_MAX" 15 "p2pool reporting zero peers" _pred_p2pool_peerless; then + t_zero=$(now_s) + it_pass "p2pool peer-loss: P2Pool reported zero peers $((t_zero - t0)) s after the cut (#4077)" + else + it_fail "p2pool peer-loss: P2Pool reports zero peers within ${P2POOL_PEER_LOSS_DISCONNECT_MAX} s of the cut (#4077)" "still holding peers" + fault_rules_clear_all + fault_rules_trap_disarm + return + fi + if wait_for "$P2POOL_PEER_LOSS_RESTART_MAX" 30 "dashboard restarts the peerless p2pool" _pred_p2pool_restarted "$started"; then + it_pass "p2pool peer-loss: the dashboard restarted the peerless P2Pool unattended $(($(now_s) - t_zero)) s after the first zero reading (#4077)" + else + it_fail "p2pool peer-loss: the dashboard restarts a P2Pool peerless for 15 minutes (#4077)" "container start time unchanged after ${P2POOL_PEER_LOSS_RESTART_MAX} s" + fi + logs=$(rx "docker logs --since $epoch dashboard 2>&1") + assert_contains "p2pool peer-loss: the restart is named in the dashboard log (#4077)" "$logs" "P2Pool has had no peers for" + if wait_for "$P2POOL_PEER_LOSS_REJOIN_MAX" 30 "p2pool peers and sidechain tip resume" _pred_p2pool_rejoin_logged "$epoch"; then + it_pass "p2pool peer-loss: peers returned and the sidechain tip resumed unattended (#4077)" + else + it_fail "p2pool peer-loss: peers return and the sidechain tip resumes unattended (#4077)" "no tip progress within ${P2POOL_PEER_LOSS_REJOIN_MAX} s of the restart" + fi + restarts=$(rx "docker logs --since $epoch dashboard 2>&1 | grep -c 'P2Pool has had no peers for'") + assert_eq "p2pool peer-loss: exactly one restart for the one outage (#4077)" "$restarts" "1" + fault_rules_clear_all + fault_rules_trap_disarm + assert_eq "p2pool peer-loss: no $P2POOL_PEER_LOSS_TAG rule left behind (#4077)" "$(p2pool_peer_loss_count)" "0" +} diff --git a/tests/integration/run.sh b/tests/integration/run.sh index 44519f783c..a33bd06e3a 100755 --- a/tests/integration/run.sh +++ b/tests/integration/run.sh @@ -141,6 +141,8 @@ source "$HERE/lib/run-faults.sh" || exit $? source "$HERE/lib/run-pool-sync-fault.sh" || exit $? # shellcheck source=tests/integration/lib/run-tor-probe-fault.sh source "$HERE/lib/run-tor-probe-fault.sh" || exit $? +# shellcheck source=tests/integration/lib/run-pool-peer-loss.sh +source "$HERE/lib/run-pool-peer-loss.sh" || exit $? # shellcheck source=tests/integration/lib/run-egress-status.sh source "$HERE/lib/run-egress-status.sh" || exit $? # shellcheck source=tests/integration/lib/run-hardening.sh diff --git a/tests/integration/selftest/selftest-pool-peer-loss.sh b/tests/integration/selftest/selftest-pool-peer-loss.sh new file mode 100755 index 0000000000..d0565b2d84 --- /dev/null +++ b/tests/integration/selftest/selftest-pool-peer-loss.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +INTEGRATION_RUN_SUITE=1 +# shellcheck source=tests/integration/lib.sh +source "$HERE/../lib.sh" +# shellcheck source=tests/integration/lib/fault-rules.sh +source "$HERE/../lib/fault-rules.sh" +# shellcheck source=tests/integration/lib/run-pool-peer-loss.sh +source "$HERE/../lib/run-pool-peer-loss.sh" + +FAIL=0 +check() { + "$@" || { + FAIL=$((FAIL + 1)) + printf 'FAIL: %s\n' "$*" >&2 + } +} + +echo "== the leg tags every rule with the sweep prefix ==" +check test "${P2POOL_PEER_LOSS_TAG#"$FAULT_RULE_PREFIX"}" = p2pool-peers +rules=$(p2pool_peer_loss_rules 172.28.0.25) +check test "$(printf '%s\n' "$rules" | wc -l | tr -d ' ')" -eq 4 +check test "$(printf '%s\n' "$rules" | grep -c -- "--comment $P2POOL_PEER_LOSS_TAG -j DROP")" -eq 4 +check grep -Fq 'OUTPUT -d 172.28.0.25 ' <<<"$rules" +check grep -Fq 'INPUT -p tcp --dport 37888:37890' <<<"$rules" + +echo "== a P2Pool that never held peers is a missing-precondition skip, not a pass or a fault ==" +( + injected=0 + env_on_box() { echo /data/p2pool; } + fault_rules_clear_all() { :; } + rx() { echo 172.28.0.25; } + wait_for() { return 1; } + p2pool_ns_ipt() { injected=1; } + fault_p2pool_peer_loss + check test "$injected" -eq 0 + check test "$IT_FAIL" -eq 0 + check test "$IT_PASS" -eq 0 + check test "$IT_SKIPPED_MISSING" -eq 1 + test "$FAIL" -eq 0 +) + +echo "== a missing data dir is a failure before any work ==" +( + env_on_box() { echo ""; } + rx() { + echo "unexpected rx" >&2 + return 1 + } + fault_p2pool_peer_loss + check test "$IT_FAIL" -eq 1 + test "$FAIL" -eq 0 +) + +echo "== a leg that cannot install its rules fails and sweeps ==" +( + cleared=0 + env_on_box() { echo /data/p2pool; } + fault_rules_clear_all() { cleared=$((cleared + 1)); } + fault_rules_trap_arm() { :; } + fault_rules_trap_disarm() { :; } + rx() { echo 172.28.0.25; } + wait_for() { return 0; } + p2pool_ns_ipt() { :; } + p2pool_peer_loss_count() { echo 0; } + p2pool_started_at() { echo t0; } + fault_p2pool_peer_loss + check test "$IT_FAIL" -eq 1 + check test "$cleared" -eq 2 + test "$FAIL" -eq 0 +) + +[ "$FAIL" -eq 0 ] && echo "selftest-pool-peer-loss: PASS" diff --git a/tests/integration/selftest/selftest-run-modules.sh b/tests/integration/selftest/selftest-run-modules.sh index 0d8565dba1..19f3f6d9a5 100755 --- a/tests/integration/selftest/selftest-run-modules.sh +++ b/tests/integration/selftest/selftest-run-modules.sh @@ -3,7 +3,7 @@ set -uo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT="$HERE/.." -modules=(run-usage.sh run-cli.sh run-matrix.sh run-egress-claim.sh run-onion-targets.sh run-state.sh run-tari-wallet.sh run-lan-guard.sh run-scenario.sh run-source-image.sh run-wizard-defaults.sh run-connection-announcements.sh run-reset-restore.sh run-support-bundle.sh run-lifecycle.sh run-reset-dashboard.sh run-rotate-secrets.sh run-faults.sh run-pool-sync-fault.sh run-tor-probe-fault.sh run-egress-status.sh run-hardening.sh run-rotate-onion.sh run-safety.sh run-rigforge.sh run-rig-control.sh run-rig-reverse.sh run-alert-egress.sh run-mergemine-submit.sh run-tari-stranded.sh run-monero-stranded.sh run-mergemine-localnet.sh) +modules=(run-usage.sh run-cli.sh run-matrix.sh run-egress-claim.sh run-onion-targets.sh run-state.sh run-tari-wallet.sh run-lan-guard.sh run-scenario.sh run-source-image.sh run-wizard-defaults.sh run-connection-announcements.sh run-reset-restore.sh run-support-bundle.sh run-lifecycle.sh run-reset-dashboard.sh run-rotate-secrets.sh run-faults.sh run-pool-sync-fault.sh run-tor-probe-fault.sh run-pool-peer-loss.sh run-egress-status.sh run-hardening.sh run-rotate-onion.sh run-safety.sh run-rigforge.sh run-rig-control.sh run-rig-reverse.sh run-alert-egress.sh run-mergemine-submit.sh run-tari-stranded.sh run-monero-stranded.sh run-mergemine-localnet.sh) echo "== run.sh modules load completely in their preserved order ==" expected_modules="$(printf 'lib/%s ' "${modules[@]}" | sed 's/ $//')" @@ -13,7 +13,7 @@ actual_modules="$(sed -n 's|^source "$HERE/\(lib/run-[a-z-]*\.sh\)".*|\1|p' "$RO exit 1 } -expected_functions='usage parse_args print_list push_config env_on_box running_services _pred_mining_probe_running assert_mining_probe_ready service_state secret_fingerprint preflight record_manifest run_scenario clearnet_flag_effective restore_firewall_after_clearnet assert_host_claims_spent_sync assert_onion_targets _onion_reachable_external assert_running_state assert_egress_dial_pair public_remotes_in_proc_tcp _pred_tari_payouts_found _pred_payout_wallet_ready _pred_monero_wallet_caught_up assert_payout_wallet_ready assert_tari_payout_scan _lan_probe _lan_flush_rules _lan_strip _lan_capture _lan_probe_open _lan_assert_open assert_lan_guard_live assert_lan_guard_timer_flush _lan_timer_pause _lan_exit_code assert_lan_guard_crash_restart assert_lan_guard_boot_restore assert_lan_guard_boot_failure assert_scenario assert_egress_posture assert_xvb_over_tor assert_metrics_via_caddy assert_doctor_ok assert_share_stats_live assert_telemetry_tables_present assert_current_state box_fstype box_avail_gb box_mode _pred_readiness_monero _pred_readiness_status status_verdict_lines assert_release_readiness lifecycle_gate_snippet retain_lifecycle_gate_samples lifecycle_gate_sample source_image_reconcile_snippet run_source_image_reconcile run_image_permissions wizard_restore_baseline run_cli_wizard_defaults connection_announcements_snippet run_connection_announcements run_restore_dashboard_probe run_reset_restore reset_restore_wait_reboot reset_restore_shutdown_clean reset_restore_wait_empty run_support_bundle _run_lifecycle kept_data_snapshot_snippet kept_chain_files_snippet run_uninstall_round_trip telemetry_rows_diff _pred_status_down _monerod_is _pred_monerod_missing _pred_monerod_unhealthy _pred_monerod_healthy _pred_proxy_stopped _pred_failover_armed _pred_p2pool_running _pred_tor_stopped _pred_tor_healthy _reset_dashboard_services_healthy run_reset_dashboard _rotate_proxy_live_args _rotate_monero_rpc_probe _rotate_proxy_token_accepted _rotate_stratum_auth _rotate_proxy_upstream_active _rotate_rig_accepted _rotate_proxy_accepted_after _rotate_p2pool_monero_live _rotate_new_baks _rotate_cleanup_baks _rotate_abort_restore run_rotate_secrets _rig_active_pool _pred_rig_pool_differs _pred_rig_pool_returned _rig_pool_leg fault_node_down fault_unhealthy fault_missing fault_db_readonly fault_firewall_rollback _gf_flows _gf_down fault_firewall_grandfathered_flow fault_tor_down fault_clock_drift fault_disk_enospc _pred_p2pool_peers _pred_dnswatch_listening fault_p2pool_cold_cache_dns _restore_p2pool_peer_lists run_fault_injection run_fault_injection_maybe p2pool_sidechain_sync_snippet fault_p2pool_sidechain_sync tor_probe_ns_ipt _tor_probe_mining_sample fault_tor_probe_egress _tor_probe_recovered tor_recovery_lock_snapshot_snippet tor_recovery_probe_now_s tor_recovery_healthy_probe _await_egress_state fault_firewall_status_alert fault_firewall_boot_restore _set_env_token _spool_write _uuid4 _wait_control_status _remove_control_units run_hardening run_auth_fail_closed rotate_onion_data_dir rotate_onion_key_fingerprint rotate_onion_client_key_fingerprint rotate_onion_env_fingerprint rotate_onion_mining_fingerprint wait_onion_retired rotate_onion_restore run_rotate_onion safety_backup safety_secret_drift_categories safety_restore_exact safety_rollback_if_failed safety_abort_restore arm_safety_abort_restore reset_dashboard_remove_blocker reset_dashboard_cleanup safety_cleanup restore_baseline summary run_rigforge_integration assert_subnet_live run_subnet_scenario _worker_apply _max_temp_round_trip _restore_rig_control_baseline run_rigforge_control _pred_rig_present run_rigforge_reverse _rig_control_apply _rig_control_await _pred_feed_maxt _rig_direct_summary _reverse_feed_failure_detail run_rigforge_rollback it_alert_refused _alert_egress_overlay _alert_egress_verdict run_alert_egress_smoke _mm_rows _mm_cleanup run_mergemine_submit tari_ns_ipt tari_strand_count tari_strand_drops tari_strand_remove_all tari_hook_start tari_hook_stop tari_restore_config tari_strand_abort tari_health_field _pred_tari_level _pred_tari_at_least_amber _pred_tari_zero_peers _pred_tari_alerted _pred_tari_recovery_alerted tari_started_at tari_strand_state run_tari_stranded monero_ns_ipt monero_strand_count monero_strand_remove_all monero_hook_start monero_hook_stop monero_restore_config monero_strand_abort monero_health_field _pred_monero_level monero_peer_counts monero_out_peers monero_tor_recovery_out monero_observation _pred_monero_zero_out _pred_monero_has_peers _pred_monerod_docker_health _pred_monero_alerted _pred_monero_recovery_alerted monero_peer_sample _pred_monero_has_peers_sampled monero_peer_wait_diagnostics _monero_http_code assert_monero_p2p_advertisement assert_monero_rpc_boundary monero_started_at monero_strand_state run_monero_stranded _mml_fact _mml_target_row _mml_inspect _mml_ip _mml_cleanup run_mergemine_localnet' +expected_functions='usage parse_args print_list push_config env_on_box running_services _pred_mining_probe_running assert_mining_probe_ready service_state secret_fingerprint preflight record_manifest run_scenario clearnet_flag_effective restore_firewall_after_clearnet assert_host_claims_spent_sync assert_onion_targets _onion_reachable_external assert_running_state assert_egress_dial_pair public_remotes_in_proc_tcp _pred_tari_payouts_found _pred_payout_wallet_ready _pred_monero_wallet_caught_up assert_payout_wallet_ready assert_tari_payout_scan _lan_probe _lan_flush_rules _lan_strip _lan_capture _lan_probe_open _lan_assert_open assert_lan_guard_live assert_lan_guard_timer_flush _lan_timer_pause _lan_exit_code assert_lan_guard_crash_restart assert_lan_guard_boot_restore assert_lan_guard_boot_failure assert_scenario assert_egress_posture assert_xvb_over_tor assert_metrics_via_caddy assert_doctor_ok assert_share_stats_live assert_telemetry_tables_present assert_current_state box_fstype box_avail_gb box_mode _pred_readiness_monero _pred_readiness_status status_verdict_lines assert_release_readiness lifecycle_gate_snippet retain_lifecycle_gate_samples lifecycle_gate_sample source_image_reconcile_snippet run_source_image_reconcile run_image_permissions wizard_restore_baseline run_cli_wizard_defaults connection_announcements_snippet run_connection_announcements run_restore_dashboard_probe run_reset_restore reset_restore_wait_reboot reset_restore_shutdown_clean reset_restore_wait_empty run_support_bundle _run_lifecycle kept_data_snapshot_snippet kept_chain_files_snippet run_uninstall_round_trip telemetry_rows_diff _pred_status_down _monerod_is _pred_monerod_missing _pred_monerod_unhealthy _pred_monerod_healthy _pred_proxy_stopped _pred_failover_armed _pred_p2pool_running _pred_tor_stopped _pred_tor_healthy _reset_dashboard_services_healthy run_reset_dashboard _rotate_proxy_live_args _rotate_monero_rpc_probe _rotate_proxy_token_accepted _rotate_stratum_auth _rotate_proxy_upstream_active _rotate_rig_accepted _rotate_proxy_accepted_after _rotate_p2pool_monero_live _rotate_new_baks _rotate_cleanup_baks _rotate_abort_restore run_rotate_secrets _rig_active_pool _pred_rig_pool_differs _pred_rig_pool_returned _rig_pool_leg fault_node_down fault_unhealthy fault_missing fault_db_readonly fault_firewall_rollback _gf_flows _gf_down fault_firewall_grandfathered_flow fault_tor_down fault_clock_drift fault_disk_enospc _pred_p2pool_peers _pred_dnswatch_listening fault_p2pool_cold_cache_dns _restore_p2pool_peer_lists run_fault_injection run_fault_injection_maybe p2pool_sidechain_sync_snippet fault_p2pool_sidechain_sync tor_probe_ns_ipt _tor_probe_mining_sample fault_tor_probe_egress _tor_probe_recovered tor_recovery_lock_snapshot_snippet tor_recovery_probe_now_s tor_recovery_healthy_probe p2pool_ns_ipt p2pool_peer_loss_rules p2pool_peer_loss_count p2pool_peer_total p2pool_started_at _pred_p2pool_peerless _pred_p2pool_restarted _pred_p2pool_has_peers _pred_p2pool_rejoin_logged fault_p2pool_peer_loss _await_egress_state fault_firewall_status_alert fault_firewall_boot_restore _set_env_token _spool_write _uuid4 _wait_control_status _remove_control_units run_hardening run_auth_fail_closed rotate_onion_data_dir rotate_onion_key_fingerprint rotate_onion_client_key_fingerprint rotate_onion_env_fingerprint rotate_onion_mining_fingerprint wait_onion_retired rotate_onion_restore run_rotate_onion safety_backup safety_secret_drift_categories safety_restore_exact safety_rollback_if_failed safety_abort_restore arm_safety_abort_restore reset_dashboard_remove_blocker reset_dashboard_cleanup safety_cleanup restore_baseline summary run_rigforge_integration assert_subnet_live run_subnet_scenario _worker_apply _max_temp_round_trip _restore_rig_control_baseline run_rigforge_control _pred_rig_present run_rigforge_reverse _rig_control_apply _rig_control_await _pred_feed_maxt _rig_direct_summary _reverse_feed_failure_detail run_rigforge_rollback it_alert_refused _alert_egress_overlay _alert_egress_verdict run_alert_egress_smoke _mm_rows _mm_cleanup run_mergemine_submit tari_ns_ipt tari_strand_count tari_strand_drops tari_strand_remove_all tari_hook_start tari_hook_stop tari_restore_config tari_strand_abort tari_health_field _pred_tari_level _pred_tari_at_least_amber _pred_tari_zero_peers _pred_tari_alerted _pred_tari_recovery_alerted tari_started_at tari_strand_state run_tari_stranded monero_ns_ipt monero_strand_count monero_strand_remove_all monero_hook_start monero_hook_stop monero_restore_config monero_strand_abort monero_health_field _pred_monero_level monero_peer_counts monero_out_peers monero_tor_recovery_out monero_observation _pred_monero_zero_out _pred_monero_has_peers _pred_monerod_docker_health _pred_monero_alerted _pred_monero_recovery_alerted monero_peer_sample _pred_monero_has_peers_sampled monero_peer_wait_diagnostics _monero_http_code assert_monero_p2p_advertisement assert_monero_rpc_boundary monero_started_at monero_strand_state run_monero_stranded _mml_fact _mml_target_row _mml_inspect _mml_ip _mml_cleanup run_mergemine_localnet' actual_functions="$(for module in "${modules[@]}"; do sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)() {.*/\1/p' "$ROOT/lib/$module"; done | tr '\n' ' ' | sed 's/ $//')" [ "$actual_functions" = "$expected_functions" ] || { echo "integration function order or completeness mismatch" >&2 @@ -65,6 +65,8 @@ source "$ROOT/lib/run-faults.sh" || exit $? source "$ROOT/lib/run-pool-sync-fault.sh" || exit $? # shellcheck source=tests/integration/lib/run-tor-probe-fault.sh source "$ROOT/lib/run-tor-probe-fault.sh" || exit $? +# shellcheck source=tests/integration/lib/run-pool-peer-loss.sh +source "$ROOT/lib/run-pool-peer-loss.sh" || exit $? # shellcheck source=tests/integration/lib/run-egress-status.sh source "$ROOT/lib/run-egress-status.sh" || exit $? # shellcheck source=tests/integration/lib/run-hardening.sh diff --git a/tests/os/README.md b/tests/os/README.md index b19d235e8b..b74b5f2f94 100644 --- a/tests/os/README.md +++ b/tests/os/README.md @@ -33,6 +33,13 @@ no unexpected-abort message or debug advice. `selftest-tor-recovery-refusal.sh` this guest script against the generated CLI and a pre-fix dispatch negative control, without a container or guest. The live result requires a KVM job on the PR head. +The opt-in `p2pool-heal` phase (#4077) provisions a guest. When the guest P2Pool reports readable peerless stats, it +observes the dashboard restart it (within 50 minutes), keep at least 20 minutes between restarts, stay within three +and leave P2Pool running. A stock guest P2Pool reports no stats, so the phase instead runs the dashboard's healer +inside the dashboard container against zero-peer stats and the real container control path, and requires the +P2Pool container to restart and be running. Peer-loss detection itself is proved by the `fault-injection` e2e leg. +`selftest-pool-heal.sh` exercises the phase wrapper without a guest. + The opt-in `tor-heal` phase provisions a local-node guest and faults only that guest's Tor. It retains the production timers: 90 minutes with auto-heal disabled, then up to 95 minutes with it enabled. It requires the first-round diagnosis within 25 minutes, a host recovery diff --git a/tests/os/phases/pool-heal.sh b/tests/os/phases/pool-heal.sh new file mode 100644 index 0000000000..be6ddee969 --- /dev/null +++ b/tests/os/phases/pool-heal.sh @@ -0,0 +1,19 @@ +# shellcheck shell=bash +: "${OS_RUN_SUITE:?source via the suite runner}" +phase_p2pool_heal() { + # shellcheck disable=SC2034 + local img token="" jar="" scode="" marker="" tries=0 code="" pv_user="" pv_pass="" PROVISION_DASHBOARD_HOST=fixture-box rc=0 + _phase_provision_initial || { + bad "p2pool-heal: guest provisioning failed before observation" + return 1 + } + SSH_TIMEOUT=6000 _ssh 'timeout 5800 bash -s' <"$SCRIPT_DIR/pool-heal-guest.sh" || rc=$? + case "$rc" in + 0) ok "guest P2Pool is restarted by the dashboard healer (#4077)" ;; + 77) it_skip_leg "p2pool-heal: observe a peerless guest P2Pool (#4077)" "the guest skipped" missing ;; + *) + printf 'Guest stderr: %s\n' "$(tail -c 2048 "$SSH_ERR" 2>/dev/null | tr -d '\r')" + bad "guest P2Pool peer-loss restart, backoff or cap failed (#4077)" + ;; + esac +} diff --git a/tests/os/pool-heal-guest.sh b/tests/os/pool-heal-guest.sh new file mode 100755 index 0000000000..964d2d16de --- /dev/null +++ b/tests/os/pool-heal-guest.sh @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +stage=initialization +diagnose() { + local stats + stats=$(find /data -path '*/stats/local/p2p' -type f 2>/dev/null | head -n 1) + printf 'diagnose: p2pool %s\n' "$(docker inspect p2pool --format '{{.State.Status}} started={{.State.StartedAt}} health={{.State.Health.Status}}' 2>&1 | head -c 300)" >&2 + printf 'diagnose: stats file %s\n' "${stats:-absent}" >&2 + [ -z "$stats" ] || jq -c 'del(.peers)' "$stats" 2>&1 | head -c 600 >&2 + printf '\ndiagnose: dashboard P2Pool log lines: %s\n' "$(docker logs --since "$epoch" dashboard 2>&1 | grep -c 'P2Pool')" >&2 + docker logs --tail 5 p2pool 2>&1 | head -c 800 >&2 || true +} +trap 'printf "P2Pool heal guest failed at %s (line %s, exit %s)\n" "$stage" "$LINENO" "$?" >&2; diagnose' ERR +cd /data/pithead +epoch=$(date +%s) +started_at() { docker inspect p2pool --format '{{.State.StartedAt}}'; } +running() { [ "$(docker inspect p2pool --format '{{.State.Running}}' 2>/dev/null || true)" = true ]; } +peers() { + local stats + stats=$(find /data -path '*/stats/local/p2p' -type f 2>/dev/null | head -n 1) + [ -n "$stats" ] || { + echo 0 + return + } + jq -r '(.connections // 0) + (.incoming_connections // 0)' "$stats" +} +heal_lines() { + docker logs -t --since "$epoch" dashboard 2>&1 | grep 'P2Pool has had no peers for' || true +} +control_path_restart() { + docker exec -i dashboard python3 - <<'PY' +import asyncio + +from mining_dashboard.client.docker.docker_control import DockerControl +from mining_dashboard.service.health import p2pool_heal as heal + + +class Clock: + now = 0.0 + + def __call__(self): + return self.now + + +async def main(): + clock = Clock() + healer = heal.P2PoolPeerHealer(DockerControl(), clock=clock) + uptime = iter(range(1, 100)) + + def stats(): + return {"p2p": {"out_peers": 0, "in_peers": 0, "uptime": next(uptime)}, "pool": {}} + + await healer.check(stats()) + clock.now = heal.ZERO_PEERS_AFTER_SEC + 1 + await healer.check(stats()) + + +asyncio.run(main()) +PY +} +stage=peerless-precondition +stats=$(find /data -path '*/stats/local/p2p' -type f 2>/dev/null | head -n 1) +if [ -z "$stats" ] || [ "$(jq -r '.uptime // 0' "$stats")" -le 0 ] || [ "$(peers)" -gt 0 ]; then + stage=control-path + before=$(started_at) + for ((attempt = 0; attempt < 3; attempt++)); do + running || docker start p2pool >/dev/null + control_path_restart + [ "$(started_at)" != "$before" ] && break + done + [ "$(started_at)" != "$before" ] + echo 'PASS: the dashboard healer restarts the guest P2Pool through the appliance container control path (#4077)' + exit 0 +fi +stage=wait-p2pool-running +for ((attempt = 0; attempt < 60; attempt++)); do + running && break + sleep 10 +done +running +first_start=$(started_at) +stage=observe-restart +deadline=$((epoch + 50 * 60)) +while [ "$(date +%s)" -lt "$deadline" ]; do + [ "$(started_at)" != "$first_start" ] && break + sleep 30 +done +[ "$(started_at)" != "$first_start" ] +[ "$(heal_lines | wc -l)" -ge 1 ] +echo 'PASS: the dashboard restarted a P2Pool that stayed peerless for 15 minutes (#4077)' +stage=running-after-restart +running +echo 'PASS: P2Pool is running after the dashboard restart (#4077)' +stage=backoff +deadline=$(($(date +%s) + 30 * 60)) +while [ "$(date +%s)" -lt "$deadline" ] && [ "$(heal_lines | wc -l)" -lt 2 ]; do + sleep 30 +done +lines=$(heal_lines) +count=$(printf '%s\n' "$lines" | grep -c . || true) +[ "$count" -le 3 ] +[ "$count" -ge 2 ] +first=$(date -d "$(printf '%s\n' "$lines" | sed -n 1p | cut -d' ' -f1)" +%s) +second=$(date -d "$(printf '%s\n' "$lines" | sed -n 2p | cut -d' ' -f1)" +%s) +[ $((second - first)) -ge 1200 ] +running +echo 'PASS: a peerless P2Pool is restarted with backoff, stays within the daily cap and ends running (#4077)' diff --git a/tests/os/run.sh b/tests/os/run.sh index 48ad186846..2cf69e4e4d 100755 --- a/tests/os/run.sh +++ b/tests/os/run.sh @@ -241,6 +241,8 @@ source "$SCRIPT_DIR/phases/crossupdate.sh" || exit $? source "$SCRIPT_DIR/phases/stack.sh" || exit $? # shellcheck source=tests/os/phases/tor-heal.sh source "$SCRIPT_DIR/phases/tor-heal.sh" || exit $? +# shellcheck source=tests/os/phases/pool-heal.sh +source "$SCRIPT_DIR/phases/pool-heal.sh" || exit $? require_host require_clean_bench if [ "$PHASE" = "boot" ] || [ "$PHASE" = "all" ]; then @@ -278,6 +280,7 @@ image-upgrade) _run_phase image-upgrade phase_image_upgrade ;; crossupdate) _run_phase crossupdate phase_crossupdate ;; stack) _run_phase stack phase_stack ;; tor-heal) _run_phase tor-heal phase_tor_heal ;; +p2pool-heal) _run_phase p2pool-heal phase_p2pool_heal ;; all) # ALL of them. This arm once ran five of eight while the release checklist told a maintainer # that step 1 covered everything — the mid-write and mid-commit power cuts, the corrupt-bundle diff --git a/tests/os/selftest-pool-heal.sh b/tests/os/selftest-pool-heal.sh new file mode 100755 index 0000000000..e8aa5fed43 --- /dev/null +++ b/tests/os/selftest-pool-heal.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +set -euo pipefail +export TMPDIR="${TMPDIR:-${RUNNER_TEMP:-/tmp}}" +ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +work=$(mktemp -d "${TMPDIR:?}/pool-heal-selftest.XXXXXX") +trap 'rm -rf "$work"' EXIT +# shellcheck disable=SC2034 +OS_RUN_SUITE=1 SCRIPT_DIR="$ROOT/tests/os" +# shellcheck source=tests/os/phases/pool-heal.sh +source "$ROOT/tests/os/phases/pool-heal.sh" +ok() { printf '%s\n' "$*" >>"$work/pass"; } +bad() { printf '%s\n' "$*" >>"$work/fail"; } +it_skip_leg() { printf '%s|%s|%s\n' "$1" "$2" "$3" >>"$work/skip"; } +_phase_provision_initial() { return "${provision_rc:-0}"; } +_ssh() { + [ "$SSH_TIMEOUT" = 6000 ] && [ "$1" = 'timeout 5800 bash -s' ] + cat >"$work/guest-script" + return "${guest_rc:-0}" +} +phase_p2pool_heal +cmp "$ROOT/tests/os/pool-heal-guest.sh" "$work/guest-script" +grep -q '#4077' "$work/pass" +rm "$work/guest-script" +provision_rc=1 +if phase_p2pool_heal; then exit 1; fi +[ ! -e "$work/guest-script" ] +provision_rc=0 guest_rc=77 +phase_p2pool_heal +grep -q '|missing$' "$work/skip" +[ "$(wc -l <"$work/pass" | tr -d ' ')" = 1 ] +guest_rc=17 +SSH_ERR="$work/ssh-err" +echo 'P2Pool heal guest failed at first-restart (line 1, exit 17)' >"$SSH_ERR" +phase_p2pool_heal >"$work/phase-output" +grep -q 'Guest stderr: P2Pool heal guest failed at first-restart' "$work/phase-output" +[ "$(wc -l <"$work/fail" | tr -d ' ')" = 2 ] +bash -n "$ROOT/tests/os/pool-heal-guest.sh" +echo 'selftest-pool-heal: PASS' diff --git a/tests/os/selftest-run-modules.sh b/tests/os/selftest-run-modules.sh index cbbf48cf78..0e803e586d 100755 --- a/tests/os/selftest-run-modules.sh +++ b/tests/os/selftest-run-modules.sh @@ -1,15 +1,15 @@ #!/usr/bin/env bash set -uo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -modules=(lib/core.sh wizard-redirect-leg.sh phases/boot.sh phases/update-spare-slot.sh phases/update.sh phases/update-dashboard.sh phases/update-healthgate-leg.sh phases/install.sh phases/provision.sh phases/setup-defaults.sh phases/media.sh phases/rig.sh phases/rigmedia.sh phases/fault.sh phases/reset.sh phases/image-upgrade.sh phases/crossupdate.sh phases/stack.sh phases/tor-heal.sh) -function_files=(lib/core.sh wizard-redirect-leg.sh phases/boot.sh phases/update-spare-slot.sh phases/update.sh phases/update-dashboard.sh phases/update-healthgate-leg.sh phases/install-initial.sh phases/install-rig.sh phases/install-reinstall.sh phases/install-fresh-start.sh phases/install-restore-preboot.sh phases/install-restore.sh phases/install.sh phases/provision-initial.sh phases/provision-reboot.sh phases/provision-power-cut.sh phases/provision-migration.sh phases/provision.sh phases/setup-defaults.sh phases/media.sh phases/rig.sh phases/rigmedia.sh phases/fault.sh phases/reset-config.sh phases/reset-slot.sh phases/reset.sh phases/image-upgrade.sh phases/crossupdate.sh phases/stack.sh phases/tor-heal.sh) +modules=(lib/core.sh wizard-redirect-leg.sh phases/boot.sh phases/update-spare-slot.sh phases/update.sh phases/update-dashboard.sh phases/update-healthgate-leg.sh phases/install.sh phases/provision.sh phases/setup-defaults.sh phases/media.sh phases/rig.sh phases/rigmedia.sh phases/fault.sh phases/reset.sh phases/image-upgrade.sh phases/crossupdate.sh phases/stack.sh phases/tor-heal.sh phases/pool-heal.sh) +function_files=(lib/core.sh wizard-redirect-leg.sh phases/boot.sh phases/update-spare-slot.sh phases/update.sh phases/update-dashboard.sh phases/update-healthgate-leg.sh phases/install-initial.sh phases/install-rig.sh phases/install-reinstall.sh phases/install-fresh-start.sh phases/install-restore-preboot.sh phases/install-restore.sh phases/install.sh phases/provision-initial.sh phases/provision-reboot.sh phases/provision-power-cut.sh phases/provision-migration.sh phases/provision.sh phases/setup-defaults.sh phases/media.sh phases/rig.sh phases/rigmedia.sh phases/fault.sh phases/reset-config.sh phases/reset-slot.sh phases/reset.sh phases/image-upgrade.sh phases/crossupdate.sh phases/stack.sh phases/tor-heal.sh phases/pool-heal.sh) expected_modules="${modules[*]}" actual_modules="$(sed -n 's|^source "$SCRIPT_DIR/\([a-z/-]*\.sh\)".*|\1|p' "$HERE/run.sh" | tr '\n' ' ' | sed 's/ $//')" [ "$actual_modules" = "$expected_modules" ] || { echo "os module order mismatch: $actual_modules" >&2 exit 1 } -expected_functions='ok bad info it_warn it_err have _ssh _control_requests_drained _wait_ssh _boot_id _wait_new_boot _reboot_wait _ssh_unreachable_reason _marker _dash_marker_served _wait_dhcp_ip _wait_setup_page _build_image _build_bundle _stage_bundle _install_cmd _commit_cmd _boot_spare_cmd _install_and_boot_cmd _rollback_cmd require_host require_probe_key_matches_image require_clean_bench cleanup serial_has wait_serial redirect_location_matches wizard_redirect_probe phase_wizard_redirect phase_dashboard_redirect phase_boot _secure_boot_guest_leg _vm_boot_disk _update_spare_slot_uncommitted phase_update _wizard_provision_capture _os_step _serve_update_dir _leg4_srv_stop phase_update_dashboard _update_healthgate_leg_body phase_update_healthgate_leg _restore_target_preboot_verdict _restore_installer_preboot_verdict phase_install _provision_reboot_gate_committed phase_provision phase_setup_defaults _make_media_stick _attach_media_stick _detach_media_stick _media_stick_has_config phase_media _rig_mining_up phase_rig _rigmedia_remove_target _rigmedia_stage_image _rigmedia_hash _rigmedia_containers _rigmedia_journal _rigmedia_before_hash_or_cleanup _rigmedia_after_hash_or_cleanup _rigmedia_containers_or_cleanup _rigmedia_journal_or_cleanup _rigmedia_quiesce _rigmedia_quiesce_or_cleanup _rigmedia_fail_cleanup phase_rigmedia phase_fault _reset_config_shutdown_passed _reset_config_wait_empty _phase_reset_config _reset_slot_snapshot _reset_slot_wait _reset_slot_good_stack _reset_slot_observe _reset_slot_rearm _phase_reset_slot phase_reset _image_upgrade_input_failure _image_upgrade_input_run _image_upgrade_inputs_valid _image_upgrade_node_v4 _image_upgrade_prepare_inputs _image_upgrade_sign_wrong_key _image_upgrade_stage_guest _image_upgrade_clear_guest_inputs _image_upgrade_read_guest_failure _image_upgrade_read_miner_readiness phase_image_upgrade phase_crossupdate stack_browser_config _stack_run_integration _provision_remote_node_coordinator _stack_container_restart_leg phase_stack phase_tor_heal' +expected_functions='ok bad info it_warn it_err have _ssh _control_requests_drained _wait_ssh _boot_id _wait_new_boot _reboot_wait _ssh_unreachable_reason _marker _dash_marker_served _wait_dhcp_ip _wait_setup_page _build_image _build_bundle _stage_bundle _install_cmd _commit_cmd _boot_spare_cmd _install_and_boot_cmd _rollback_cmd require_host require_probe_key_matches_image require_clean_bench cleanup serial_has wait_serial redirect_location_matches wizard_redirect_probe phase_wizard_redirect phase_dashboard_redirect phase_boot _secure_boot_guest_leg _vm_boot_disk _update_spare_slot_uncommitted phase_update _wizard_provision_capture _os_step _serve_update_dir _leg4_srv_stop phase_update_dashboard _update_healthgate_leg_body phase_update_healthgate_leg _restore_target_preboot_verdict _restore_installer_preboot_verdict phase_install _provision_reboot_gate_committed phase_provision phase_setup_defaults _make_media_stick _attach_media_stick _detach_media_stick _media_stick_has_config phase_media _rig_mining_up phase_rig _rigmedia_remove_target _rigmedia_stage_image _rigmedia_hash _rigmedia_containers _rigmedia_journal _rigmedia_before_hash_or_cleanup _rigmedia_after_hash_or_cleanup _rigmedia_containers_or_cleanup _rigmedia_journal_or_cleanup _rigmedia_quiesce _rigmedia_quiesce_or_cleanup _rigmedia_fail_cleanup phase_rigmedia phase_fault _reset_config_shutdown_passed _reset_config_wait_empty _phase_reset_config _reset_slot_snapshot _reset_slot_wait _reset_slot_good_stack _reset_slot_observe _reset_slot_rearm _phase_reset_slot phase_reset _image_upgrade_input_failure _image_upgrade_input_run _image_upgrade_inputs_valid _image_upgrade_node_v4 _image_upgrade_prepare_inputs _image_upgrade_sign_wrong_key _image_upgrade_stage_guest _image_upgrade_clear_guest_inputs _image_upgrade_read_guest_failure _image_upgrade_read_miner_readiness phase_image_upgrade phase_crossupdate stack_browser_config _stack_run_integration _provision_remote_node_coordinator _stack_container_restart_leg phase_stack phase_tor_heal phase_p2pool_heal' actual_functions="$(for module in "${function_files[@]}"; do sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)() {.*/\1/p' "$HERE/$module"; done | grep -vE '^_phase_(install|provision)_|^_monerod_(height|evidence)$' | tr '\n' ' ' | sed 's/ $//')" [ "$actual_functions" = "$expected_functions" ] || { echo "os function order or completeness mismatch" >&2 @@ -63,8 +63,8 @@ image_upgrade_certificate_continuity_leg() { :; } source "$HERE/phases/crossupdate.sh" || exit $? # shellcheck source=tests/os/phases/stack.sh source "$HERE/phases/stack.sh" || exit $? -# shellcheck source=tests/os/phases/tor-heal.sh -source "$HERE/phases/tor-heal.sh" || exit $? +# shellcheck source=/dev/null +source "$HERE/phases/tor-heal.sh" && source "$HERE/phases/pool-heal.sh" || exit $? # #2254: stack.sh is sourced into the runner's scope, so SCRIPT_DIR is the runner's own # directory (tests/os), never stack.sh's (tests/os/phases). _stack_run_integration must resolve # the DIY gate as "$SCRIPT_DIR/../integration/run.sh"; a stray extra ".." would send it above the From bba3f6a465b3df43d19f7e07d6d66c02a767fb5c Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:28:15 -0600 Subject: [PATCH 027/112] fix(os): address watch restarts Caddy only for an address change, under the mutation lock (#4028) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(os): restart Caddy from the address watch only for an address change, under the lock The watch recorded what Caddy served only for itself, so an apply, up or control commit that re-rendered the certificate and Caddyfile and restarted Caddy left the record stale: the next tick restarted the current Caddy again, outside the mutation lock, and blamed the addresses. The watch now treats a files-only change as owned by the operation that made it — record and name it, do not restart — and does render, compare and restart inside one non-blocking mutation lock, deferring both to the next tick when the lock is busy. Co-Authored-By: Claude Code * fix(os): retry the address-watch restart until it lands, keeping the address set unrecorded A failed Caddy restart left the address set recorded, so the next quiet tick adopted the files instead of retrying the restart. Record the set only once the render and (when files moved) the restart have both succeeded. Co-Authored-By: Claude Code * fix(os): restart Caddy from the address watch only for files its own render moved The served-record gate still restarted a current Caddy when an apply landed in the same tick gap as an address change, dropped a restart the watch itself owed when the address set flapped back before the retry, and persisted a baseline it read outside the mutation lock on a fresh box. Gate on the render's own effect, keep a pending marker for owed restarts, and touch no state before the lock. Co-Authored-By: Claude Code * test(integration): stub the forced address-watch tick in the recovery selftest The reset-restore selftest's remote-command stub records any command it does not know and the drive turns that into rc 127, so the tick the stability leg now fires made every leg that reaches it report a web failure. Teach the stub the command it already models on the real box. Co-Authored-By: Claude Code * test(stack): drop the comments the review flagged on the address-watch suite Project rule: no comments in code. Explanations live in docs/dev/testing-strategy.md. Co-Authored-By: Claude Code * os, test: log a refused lock-file open and share the record-and-log block The watch went quiet forever when the lock file could not be opened; one line names the fault. The two record-and-log blocks become one function. And the explanatory comment the review flagged, which this file carried before the edit landed in its hunk, goes. Co-Authored-By: Claude Code --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Code --- CHANGELOG.md | 9 + docs/dev/testing-strategy.md | 3 +- os/overlay/pithead-address-watch | 105 +++++++--- tests/integration/lib/reset-restore-web.sh | 1 + ...elftest-caddy-stable-address-watch-tick.sh | 67 +++++++ .../selftest/selftest-reset-restore.sh | 1 + .../appliance/test-appliance-address-watch.sh | 187 ++++++++++++------ 7 files changed, 283 insertions(+), 90 deletions(-) create mode 100644 tests/integration/selftest/selftest-caddy-stable-address-watch-tick.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index f8e2cb2c18..77ea07d82f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,15 @@ per the process in [`docs/dev/releasing.md`](docs/dev/releasing.md). - On the appliance, the dashboard's own schema migrations no longer run before the booted A/B slot commits. `pithead-boot` defers them while the slot is uncommitted, so an update that falls back leaves the previous release on the schema it understands, still recording payouts (#3998). +- On the appliance, the address watch no longer restarts a dashboard Caddy that already serves the + current files. When an apply, `up` or a control commit re-renders the dashboard certificate or the + Caddyfile, it restarts Caddy itself, and the next five-minute watch tick now records those files + and names them in its log instead of restarting a current Caddy and blaming an address change that + did not happen. The watch restarts Caddy only when its own render moved the files it serves — or + for the restart a failed attempt of its own left owed — and only while it holds the stack mutation + lock, so its restart no longer overlaps an apply, an `up` or a control operation; a busy lock + defers the render and the restart to the next tick, and when an apply lands in the same tick gap + as an address change the apply's restart stands (#3987). ## [2.0.3] - 2026-11-10 diff --git a/docs/dev/testing-strategy.md b/docs/dev/testing-strategy.md index 02515aedf8..3f40e9cc1e 100644 --- a/docs/dev/testing-strategy.md +++ b/docs/dev/testing-strategy.md @@ -570,7 +570,8 @@ the failure means. | Dashboard OS-update end-to-end: provision, check against a bench-local release server (root-owned test seam), download RESUMES from an interrupted transfer — proven by an independent witness (#1051: the server's own request log, not just the `resumed_from` field the test staged itself and which would hold even if curl silently restarted from zero), a floor above the running version refused with the #1393 premise (the plain below-floor door needs a downgrade bundle the leg does not build and is tier 1's, #1694) and a bad-signature refusal, both with honest errors, install + explicit reboot intent + boot-gated commit lands the new slot, persisted verdict reaches `/api/state`. The initial authenticated `/api/state` read waits up to 120 s for HTTP 200 and valid JSON, polling at 5 s intervals with requests capped at 8 s and the remaining deadline; timeout names the last HTTP code and at most 200 body bytes. A ready JSON body without `os_update` still fails immediately. | `tests/os/selftest-update-dashboard-readiness.sh` (transport/JSON retries, timeout diagnostics and unchanged state assertion) + battery `--phase update` leg 4 (+ the `provision` os_update presence check) | 1 (readiness fixtures) · 4 (current-head update phase required) | | Post-reboot `rolled_back` verdict (#1051): a dashboard-driven install leaves an in-flight flag naming the target version; booting a DIFFERENT version writes the verdict into the state file and consumes the flag; landing on the target version leaves it alone (the commit gate's success half owns that); no in-flight flag is a no-op. Pulled out of `pithead-boot`'s executed-only body into `os_update_rollback_verdict`, sourceable the same way as `gate_ready`/`gate_url`, because it is pure file logic (an in-flight flag, `VERSION`, one `jq` call) that needs no real A/B updater to prove — before this it ran only on a real boot and no tier could drive it with a fixture | `tests/stack/appliance/test-appliance-boot.sh` (sourced `pithead-boot`, fixture `in-flight.json`/`VERSION`) | 1 ✅ | | The boot gate re-mints a certificate that an address outran (#1265): `render` mints BEFORE `up` from the address list as it stands, `doctor` re-checks coverage in the gate loop AFTER `up` once the list has settled, so a SLAAC/ULA address arriving in between failed doctor on all 90 rounds and a good update rolled back. The loop now re-mints — only when THIS round's doctor failed on coverage and nothing else (`gate_blocked_only_by_cert`), only from a doctor run this round (`gate_doctor_ran`), at most three times a boot — through `render`'s own idempotent mint, and restarts Caddy only when the certificate file changed (`gate_remint_cert`); `fail_boot` copies the failing checks into the in-flight flag and the fallback boot's `rolled_back` verdict carries them as `blocking` and names the first on the console, so "rolled back" no longer implies a bad release. The loop's wiring is asserted by order in the script (the loop sits below the sourcing boundary) | `tests/stack/appliance/test-appliance-boot-remint.sh` (sourced `pithead-boot`, fixture doctor JSON, stubbed `pithead render` + restart command) | 1 ✅ · 4 (added — unverified until the next battery run; the race needs a late-arriving address, which `--phase update` does not stage) | -| An address that arrives after the boot gate committed reaches the certificate and Caddy (#2463): `pithead-address-watch.timer` runs every five minutes, compares `hostname -I` with what the last render saw, and re-renders under the mutation lock (the mint is idempotent by SAN set) when it differs, restarting Caddy whenever the certificate or Caddyfile differs from what Caddy last served, even after a render that failed part-way. It stays out of the way while `pithead-boot` is activating and retries when the lock is held or a render fails. Tier 1 drives the script with stubbed `hostname`/`systemctl` and a fake `pithead render`; the image check asserts the timer and script are baked | `tests/stack/appliance/test-appliance-address-watch.sh` (also the IPv6 spelling fix: `ipv6_canonical`, the mint comparison and doctor) · `tests/os/verify-image.sh` · `tests/os/appliance-address-watch-leg.sh` (adds a ULA after provisioning, starts the service, requires the timer enabled and active, the certificate to carry the address and doctor's row green) | 1 ✅ · 4 (`--phase provision`) | +| An address that arrives after the boot gate committed reaches the certificate and Caddy (#2463): `pithead-address-watch.timer` runs every five minutes, compares `hostname -I` with the address set the last render recorded, and when it differs renders under the mutation lock (the mint is idempotent by SAN set) and restarts Caddy inside that same lock when its own render moved the files — even after a render that failed part-way, and for the restart its own failed attempt owed even when the address set flapped back meanwhile; a busy lock defers the render AND the restart to the next tick, writing nothing before the lock is held. Files an apply, up or control commit re-rendered and restarted itself are recorded and named, never restarted over — including when they land in the same tick gap as an address change, where the watch's render is a no-op and the apply's restart stands (#3987 — the stale served record used to restart a current Caddy up to five minutes after every apply, outside the lock, blaming the addresses). It stays out of the way while `pithead-boot` is activating. Tier 1 drives the script with stubbed `hostname`/`systemctl` and a fake `pithead render`, including a files-only change and a restart that must find the lock held; the image check asserts the timer and script are baked | `tests/stack/appliance/test-appliance-address-watch.sh` (also the IPv6 spelling fix: `ipv6_canonical`, the mint comparison and doctor) · `tests/os/verify-image.sh` · `tests/os/appliance-address-watch-leg.sh` (adds a ULA after provisioning, starts the service, requires the timer enabled and active, the certificate to carry the address and doctor's row green) | 1 ✅ · 4 (`--phase provision`, `--phase stack`) | +| The 60-second quiet-Caddy legs catch the address watch firing (#3987): `rr_caddy_stable` starts `pithead-address-watch.service` once inside its 60-second window after taking the baseline snapshot, so a watch that restarts a Caddy already serving the current files fails the leg deterministically instead of racing the five-minute timer; a box without the unit installed still passes | fake `rx` docker-inspect state and a file-backed fake clock; the restart during the tick flips the snapshot and fails the leg | 1 ✅ (`selftest-caddy-stable-address-watch-tick.sh`) · 4 (`--phase stack`, the `auth recovery`/`reset recovery`/`startup restore` rows) | | `apply` reaches the mint on an unchanged config (#1265): the no-change branch on an appliance re-renders the Caddyfile under the hold (`apply_refresh_appliance_tls`; the idempotent SAN-set mint lives inside `generate_caddyfile`) and restarts Caddy only when the certificate or the Caddyfile moved; a DIY host takes the old path untouched; the call sits between the control-runner convergence and the "nothing to apply" line, asserted by order in the slice | `tests/stack/appliance/test-appliance-cert-advisory.sh` (sourced `pithead`, stubbed `generate_caddyfile` + `docker`) | 1 ✅ | | The gate commits a coverage-only hold the re-mint could not clear (#1265): `gate_remint_cert` records what it did (`reminted`, `unchanged`, `failed`, `exhausted`); `gate_cert_advisory` admits only `unchanged` and `exhausted`, carries doctor's coverage message into the `updated` verdict as `advisory` and onto the console beside the `apply` remedy; a failed render is the slot's own health and the window keeps judging it; the loop's single commit path and the verdict's field are asserted by order and text | `tests/stack/appliance/test-appliance-cert-advisory.sh` (sourced `pithead-boot`, fixture doctor JSON, stubbed `pithead render`) | 1 ✅ · 4 (added — unverified: the battery stages no late-arriving address) | | The /data floor after a data_migration update that FAILED its gate (#1393): the raise records the floor it replaced (or `none`) in `.os-data-floor.prev` BEFORE raising, and even when the raise is a no-op; the fallback boot (`restore_data_floor_after_fallback`, sourced from `pithead-boot`) puts the floor back from that record and ONLY from a record — with none, the floor stays (never lowered without one) and only the stale marker goes; the commit-side removal consumes the record; and `os_update_version_guard` refuses a floor above the running version with the true premise (failed migrating update, or a slot installed outside pithead), the open route, and no reset named. The two boot call sites sit below the sourcing boundary and are asserted by the script's text | `tests/stack/appliance/test-appliance-data-floor.sh` (sandbox files, sourced `pithead-boot`, the real `pithead` guard) | 1 ✅ · 4 ✅ (the provision phase's floor-fallback leg, `tests/os/data-floor-fallback-leg.sh`, builds its copied-tree synthetic bundle, waits for an observed reboot followed by a nonempty marker other than literal `vfail` and a commit in the current boot’s journal (the previous slot may carry `v1` or `vmig`), restores the recorded floor after its gate fails, and keeps the floor fail-safe with no record; `tests/os/selftest-floor-fallback.sh` rejects the old boot, the failing slot even if it commits, missing markers and uncommitted fallback boots) | diff --git a/os/overlay/pithead-address-watch b/os/overlay/pithead-address-watch index 840e407e06..c64a29a977 100755 --- a/os/overlay/pithead-address-watch +++ b/os/overlay/pithead-address-watch @@ -1,17 +1,4 @@ #!/bin/bash -# Keep the dashboard certificate and Caddy's listeners in step with the machine's addresses (#2463). -# -# `pithead render` mints the certificate and writes Caddy's site and bind lists from the addresses -# the box holds AT THAT MOMENT. pithead-boot re-checks them for the first ~15 minutes of a boot -# (#1265) and then commits; an IPv6 address that arrives later (a SLAAC or ULA prefix from the -# router) was never covered, so doctor FAILed on it for as long as the box stayed up. This runs from -# a timer, notices that `hostname -I` no longer matches what the last render saw, and renders again: -# the mint is idempotent by SAN set, so an unchanged certificate stays put and only a real change of -# names replaces it. Caddy is restarted only when the certificate or the Caddyfile changed. -# -# Not while pithead-boot is still working (its gate loop owns the render then), and not on a box -# that has no rendered stack yet. Never fails the unit: the next tick tries again, and a failed -# render leaves the recorded address set unchanged so it is retried. set -u cd "${PITHEAD_DIR:-/data/pithead}" 2>/dev/null || exit 0 STATE="${PITHEAD_ADDRESS_WATCH_STATE:-/run/pithead-address-watch}" @@ -20,38 +7,98 @@ BOOT_UNIT="${PITHEAD_BOOT_UNIT:-pithead-boot.service}" LOCK="${PITHEAD_LOCK_FILE:-.pithead.lock}" [ -x ./pithead ] && [ -s .env ] && [ -s config.json ] || exit 0 -# pithead-boot's gate loop owns the render while it runs. Any other state (active, failed after a -# fallback boot) is a settled box whose certificate may be stale. [ "$(systemctl is-active "$BOOT_UNIT" 2>/dev/null)" != activating ] || exit 0 addrs=$(hostname -I 2>/dev/null | tr ' ' '\n' | sed '/^$/d' | sort | tr '\n' ' ') [ -n "$addrs" ] || exit 0 -# The certificate and Caddyfile Caddy was last known to be serving: recorded when this script -# restarts it, and the files as found on the first tick (pithead-boot started Caddy from them). sig() { sha256sum "$TLS_DIR/wizard.crt" Caddyfile 2>/dev/null | cut -d' ' -f1 | tr '\n' ' '; } -served=$(cat "$STATE.served" 2>/dev/null) -if [ -z "$served" ]; then - served=$(sig) - printf '%s' "$served" >"$STATE.served" + +adopt_rendered_files() { + printf '%s' "$now" >"$STATE.served" + rm -f "$STATE.pending" + echo "pithead-address-watch: the dashboard certificate or the Caddyfile changed while the addresses held — the operation that re-rendered them owns the Caddy restart; recorded, not restarted here" +} + +if [ -f "$STATE" ] && [ "$addrs" = "$(cat "$STATE")" ]; then + now=$(sig) + if [ ! -f "$STATE.served" ]; then + printf '%s' "$now" >"$STATE.served" + exit 0 + fi + if [ "$now" = "$(cat "$STATE.served")" ]; then + rm -f "$STATE.pending" + exit 0 + fi + if [ ! -f "$STATE.pending" ] || [ "$now" != "$(cat "$STATE.pending")" ]; then + adopt_rendered_files + exit 0 + fi + exec 9>>"$LOCK" || { + echo "pithead-address-watch: cannot open the mutation lock file; retrying on the next tick" + exit 0 + } + if ! flock -n 9; then + echo "pithead-address-watch: another pithead operation holds the lock; retrying on the next tick" + exit 0 + fi + now=$(sig) + if [ "$now" != "$(cat "$STATE.pending")" ]; then + adopt_rendered_files + exit 0 + fi + echo "pithead-address-watch: the Caddy restart the watch owed for these files is due — restarting Caddy" + if ${PITHEAD_CADDY_RESTART_CMD:-docker compose restart caddy} >/dev/null 2>&1; then + printf '%s' "$now" >"$STATE.served" + rm -f "$STATE.pending" + else + echo "pithead-address-watch: Caddy did not restart; retrying on the next tick" + fi + exit 0 fi -[ -f "$STATE" ] && [ "$addrs" = "$(cat "$STATE")" ] && [ "$(sig)" = "$served" ] && exit 0 -# render is not under pithead's own mutation lock; take it here so this never interleaves with an -# apply, up or restart the control plane is running. Busy means try again next tick. -if flock -n "$LOCK" ./pithead render >/dev/null 2>&1; then - printf '%s' "$addrs" >"$STATE" +exec 9>>"$LOCK" || { + echo "pithead-address-watch: cannot open the mutation lock file; retrying on the next tick" + exit 0 +} +if ! flock -n 9; then + echo "pithead-address-watch: another pithead operation holds the lock; retrying on the next tick" + exit 0 +fi + +pre=$(sig) +render_ok=0 +if PITHEAD_LOCK_HELD=$$ ./pithead render >/dev/null 2>&1; then + render_ok=1 else - echo "pithead-address-watch: render failed or another pithead operation holds the lock; retrying on the next tick" + echo "pithead-address-watch: render failed; retrying on the next tick" fi -# A render that failed after minting still left files Caddy is not serving, so compare regardless. now=$(sig) -if [ "$now" != "$served" ]; then +served=$(cat "$STATE.served" 2>/dev/null) +[ -n "$served" ] || { + served="$pre" + printf '%s' "$served" >"$STATE.served" +} +pending=$(cat "$STATE.pending" 2>/dev/null) +restarted=0 +if [ "$now" != "$pre" ] || { [ -n "$pending" ] && [ "$now" = "$pending" ]; }; then echo "pithead-address-watch: the machine's addresses changed — re-rendered the dashboard certificate and Caddyfile, restarting Caddy" if ${PITHEAD_CADDY_RESTART_CMD:-docker compose restart caddy} >/dev/null 2>&1; then printf '%s' "$now" >"$STATE.served" + rm -f "$STATE.pending" + restarted=1 else + printf '%s' "$now" >"$STATE.pending" echo "pithead-address-watch: Caddy did not restart; retrying on the next tick" fi +else + rm -f "$STATE.pending" + if [ "$now" != "$served" ]; then + printf '%s' "$now" >"$STATE.served" + echo "pithead-address-watch: the machine's addresses changed and the rendered dashboard files were already current — no Caddy restart" + fi +fi +if [ "$render_ok" = 1 ] && { [ "$now" = "$pre" ] || [ "$restarted" = 1 ]; }; then + printf '%s' "$addrs" >"$STATE" fi exit 0 diff --git a/tests/integration/lib/reset-restore-web.sh b/tests/integration/lib/reset-restore-web.sh index d6d9a11c59..60b38ca737 100644 --- a/tests/integration/lib/reset-restore-web.sh +++ b/tests/integration/lib/reset-restore-web.sh @@ -26,6 +26,7 @@ rr_caddy_stable() { local before current deadline wait_for 60 5 "Caddy healthy" rr_caddy_snapshot >/dev/null || return 1 before=$(rr_caddy_snapshot) || return 1 + rx 'systemctl start pithead-address-watch.service >/dev/null 2>&1 || true' >/dev/null 2>&1 || true deadline=$(($(now_s) + 60)) while :; do sleep 5 diff --git a/tests/integration/selftest/selftest-caddy-stable-address-watch-tick.sh b/tests/integration/selftest/selftest-caddy-stable-address-watch-tick.sh new file mode 100644 index 0000000000..032c716462 --- /dev/null +++ b/tests/integration/selftest/selftest-caddy-stable-address-watch-tick.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +set -uo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=tests/integration/lib.sh +source "$HERE/../lib.sh" +export INTEGRATION_RUN_SUITE=1 +TD="$(mktemp -d)" +trap 'rm -rf "$TD"' EXIT +export IT_MODE=local IT_REMOTE_DIR="$TD" +# shellcheck source=tests/integration/lib/reset-restore-web.sh +source "$HERE/../lib/reset-restore-web.sh" + +CALLS="$TD/calls" +echo 0 >"$TD/rc" +TICK_CHURNS=0 +TICK_RC=0 +rx() { + local snippet="$1" + printf '%s\n' "$snippet" >>"$CALLS" + case "$snippet" in + *'systemctl start pithead-address-watch.service'*) + if [ "$TICK_CHURNS" = 1 ]; then + echo $(($(cat "$TD/rc") + 1)) >"$TD/rc" + fi + return "$TICK_RC" + ;; + *'docker inspect'*) printf 'cid %s 1700000000 true healthy' "$(cat "$TD/rc")" ;; + esac +} +sleep() { :; } +echo 1000 >"$TD/clock" +now_s() { + local t + t=$(cat "$TD/clock") + t=$((t + 6)) + echo "$t" >"$TD/clock" + printf '%s' "$t" +} + +run_stable() { + : >"$CALLS" + rr_caddy_stable >"$TD/out" 2>&1 +} + +echo "== rr_caddy_stable fires one address-watch tick inside its window (#3987) ==" +TICK_CHURNS=0 TICK_RC=0 +run_stable +assert_rc "a stable Caddy across a fired address-watch tick passes the leg" "$?" "0" +assert_eq "the tick is fired while the window watches" "$( + awk '/docker inspect/ && !seen++ {first=NR} + /systemctl start pithead-address-watch.service/ {tick=NR} + END {print (tick > first && tick < NR) ? "inside" : "outside"}' "$CALLS" +)" "inside" + +TICK_CHURNS=1 TICK_RC=0 +run_stable +assert_rc "a tick that restarts a current Caddy fails the leg (the #3987 double restart)" "$?" "1" + +TICK_CHURNS=0 TICK_RC=5 +run_stable +assert_rc "a box without the unit installed still passes the leg" "$?" "0" + +if [ "$IT_FAIL" -gt 0 ]; then + echo "selftest-caddy-stable-address-watch-tick: FAIL ($IT_FAIL)" >&2 + exit 1 +fi +echo "selftest-caddy-stable-address-watch-tick: PASS" diff --git a/tests/integration/selftest/selftest-reset-restore.sh b/tests/integration/selftest/selftest-reset-restore.sh index 1b7706cbee..530da9ae1e 100644 --- a/tests/integration/selftest/selftest-reset-restore.sh +++ b/tests/integration/selftest/selftest-reset-restore.sh @@ -123,6 +123,7 @@ drive_reset_restore() ( printf '%s\n%s' "$body" "$code" ;; 'ss -ltnp; docker logs --tail 40 caddy') : ;; + 'systemctl start pithead-address-watch.service'*) : ;; ls*) [ "$fault" != archive ] && printf 'backups/fixture.tar.gz.enc' ;; 'set -e; stage=census;'*) diff --git a/tests/stack/appliance/test-appliance-address-watch.sh b/tests/stack/appliance/test-appliance-address-watch.sh index 3476111fec..7385e471c4 100644 --- a/tests/stack/appliance/test-appliance-address-watch.sh +++ b/tests/stack/appliance/test-appliance-address-watch.sh @@ -1,10 +1,5 @@ # shellcheck shell=bash : "${STACK_SUITE:?is unset: this file is a tests/stack/run.sh fragment, not a script — run tests/stack/run.sh}" -# The address watch (#2463): an address that arrives after pithead-boot committed used to leave the -# dashboard certificate and Caddy's bind list stale until the next apply or reboot. The script -# re-renders when `hostname -I` differs from what the last render saw, and restarts Caddy only when -# the certificate or Caddyfile actually changed. Driven with stubbed hostname/systemctl and a fake -# ./pithead whose render "mints" from the current address list. Sourced by tests/stack/run.sh. echo "== unit: pithead-address-watch — re-render when an address arrives after boot (#2463) ==" AW="$SANDBOX/address-watch" @@ -22,91 +17,163 @@ cat >"$AW/bin/systemctl" <<'STUB' #!/bin/bash cat "$AW_BOOT_STATE" STUB -cat >"$AW/dir/pithead" <<'STUB' +cat >"$AW/bin/_restart-ok" <<'STUB' +#!/bin/bash +echo restart >>"$AW_RESTARTS" +if (exec 7>>"$AW/lock" && flock -n 7) 2>/dev/null; then echo free >>"$AW/lock-seen"; else echo held >>"$AW/lock-seen"; fi +STUB +cat >"$AW/bin/_restart-fail" <<'STUB' +#!/bin/bash +echo restart >>"$AW_RESTARTS" +exit 1 +STUB +cat >"$AW/bin/_render-mints" <<'STUB' #!/bin/bash -[ "$1" = render ] || exit 2 echo render >>"$AW_LOG" -[ ! -f "$AW_RENDER_FAIL" ] || exit 1 cp "$AW_ADDRS" data/tls/wizard.crt cp "$AW_ADDRS" Caddyfile STUB -cat >"$AW/bin/restart-caddy" <<'STUB' +cat >"$AW/bin/_render-quiet" <<'STUB' #!/bin/bash -echo restart >>"$AW_RESTARTS" +echo render >>"$AW_LOG" +STUB +cat >"$AW/bin/_render-fail-mints" <<'STUB' +#!/bin/bash +echo render >>"$AW_LOG" +echo minted >data/tls/wizard.crt +exit 1 STUB -chmod +x "$AW/bin/restart-caddy" "$AW/bin/hostname" "$AW/bin/systemctl" "$AW/dir/pithead" +chmod +x "$AW/bin/_restart-ok" "$AW/bin/_restart-fail" "$AW/bin/_render-mints" "$AW/bin/_render-quiet" \ + "$AW/bin/_render-fail-mints" "$AW/bin/hostname" "$AW/bin/systemctl" export AW -aw_run() { # [boot-state] -> script output; render calls in $AW/log, restarts in $AW/restarts +_run() { + local rs + if [ -f "$AW/run-restart" ]; then rs="$(cat "$AW/run-restart")"; else rs="$AW/bin/_restart-ok"; fi + printf '%s\n' "$rs" >"$AW/restart-used" printf '%s\n' "$1" >"$AW/addrs" printf '%s\n' "${2:-active}" >"$AW/boot-state" AW_ADDRS="$AW/addrs" AW_BOOT_STATE="$AW/boot-state" AW_LOG="$AW/log" AW_RENDER_FAIL="$AW/render-fail" \ PATH="$AW/bin:$PATH" PITHEAD_DIR="$AW/dir" PITHEAD_LOCK_FILE="$AW/lock" PITHEAD_ADDRESS_WATCH_STATE="$AW/state" \ - PITHEAD_TLS_DIR=data/tls AW_RESTARTS="$AW/restarts" PITHEAD_CADDY_RESTART_CMD="$AW/bin/restart-caddy" \ + PITHEAD_TLS_DIR=data/tls AW_RESTARTS="$AW/restarts" PITHEAD_CADDY_RESTART_CMD="$rs" \ bash "$HERE/../../os/overlay/pithead-address-watch" 2>&1 } -aw_count() { +_render() { + cp "$AW/bin/_render-$1" "$AW/dir/pithead" +} +_restart() { + printf '%s' "$AW/bin/_restart-$1" >"$AW/run-restart" +} +_count() { local n n=$(grep -c "$1" "$2" 2>/dev/null) echo "${n:-0}" } -aw_run "192.168.1.5" >/dev/null -assert_eq "the first tick records the address set and renders once" "$(aw_count render "$AW/log")" "1" -aw_run "192.168.1.5" >/dev/null -assert_eq "an unchanged address set does not render again" "$(aw_count render "$AW/log")" "1" -out=$(aw_run "192.168.1.5 fd1c::7") -assert_eq "a ULA arriving later renders again" "$(aw_count render "$AW/log")" "2" -assert_eq "…and restarts Caddy because the certificate changed" "$(aw_count restart "$AW/restarts")" "2" +_render mints +_run "192.168.1.5" >/dev/null +assert_eq "the first tick records the address set and renders once" "$(_count render "$AW/log")" "1" +assert_eq "…and restarts Caddy onto the files its render moved" "$(_count restart "$AW/restarts")" "1" +_run "192.168.1.5" >/dev/null +assert_eq "an unchanged address set does not render again" "$(_count render "$AW/log")" "1" +out=$(_run "192.168.1.5 fd1c::7") +assert_eq "a ULA arriving later renders again" "$(_count render "$AW/log")" "2" +assert_eq "…and restarts Caddy because the certificate changed" "$(_count restart "$AW/restarts")" "2" assert_contains "…and says why on the journal" "$out" "addresses changed" -aw_run "fd1c::7 192.168.1.5" >/dev/null -assert_eq "the same set in a different order is not a change" "$(aw_count render "$AW/log")" "2" -# render that changes nothing -cat >"$AW/dir/pithead" <<'STUB' -#!/bin/bash -echo render >>"$AW_LOG" -STUB -aw_run "192.168.1.5 fd1c::7 fd1c::8" >/dev/null -assert_eq "a render that changes nothing does not restart Caddy" "$(aw_count restart "$AW/restarts")" "2" -# render that rewrites the files and then fails: Caddy must still be restarted onto them, and the -# retry must not forget it (the address set is unrecorded, the served signature is not) -cat >"$AW/dir/pithead" <<'STUB' -#!/bin/bash -echo render >>"$AW_LOG" -echo minted >data/tls/wizard.crt -exit 1 -STUB +_run "fd1c::7 192.168.1.5" >/dev/null +assert_eq "the same set in a different order is not a change" "$(_count render "$AW/log")" "2" +_render quiet +_run "192.168.1.5 fd1c::7 fd1c::8" >/dev/null +assert_eq "a render that changes nothing does not restart Caddy" "$(_count restart "$AW/restarts")" "2" +_render fail-mints +_restart fail out=$( - aw_run "192.168.1.5 fd1c::9" + _run "192.168.1.5 fd1c::9" echo "rc=$?" ) assert_contains "a failed render leaves the unit successful" "$out" "rc=0" assert_contains "…and names the retry" "$out" "retrying on the next tick" -assert_eq "…yet Caddy is restarted onto the files it left" "$(aw_count restart "$AW/restarts")" "3" -before=$(aw_count render "$AW/log") -aw_run "192.168.1.5 fd1c::9" >/dev/null -assert_eq "…and the next tick renders again, the set never having been recorded" "$(aw_count render "$AW/log")" "$((before + 1))" -assert_eq "…without restarting Caddy a second time for the same files" "$(aw_count restart "$AW/restarts")" "3" -# a pithead operation holding the mutation lock: no render, retry -cat >"$AW/dir/pithead" <<'STUB' -#!/bin/bash -echo render >>"$AW_LOG" -STUB -before=$(aw_count render "$AW/log") +before=$(_count render "$AW/log") +_x=$(_count restart "$AW/restarts") +assert_eq "…the files the failed render left still got one restart attempt" "$_x" "3" +_run "192.168.1.5 fd1c::9" >/dev/null +assert_eq "…the next tick renders again, the set never having been recorded" "$(_count render "$AW/log")" "$((before + 1))" +assert_eq "…and attempts the restart again from its own marker" "$(_count restart "$AW/restarts")" "$((_x + 1))" +_restart ok +_run "192.168.1.5 fd1c::9" >/dev/null +assert_eq "…the retry lands the moment Caddy can restart" "$(_count restart "$AW/restarts")" "$((_x + 2))" +assert_eq "…and the pending marker clears with it" "$(cat "$AW/state.pending" 2>/dev/null)" "" +_render mints +before=$(_count render "$AW/log") out=$(flock -n "$AW/lock" true && ( exec 8>>"$AW/lock" flock 8 - aw_run "192.168.1.5 fd1c::b" + _run "192.168.1.5 fd1c::b" )) -assert_eq "a held mutation lock defers the render" "$(aw_count render "$AW/log")" "$before" +assert_eq "a held mutation lock defers the render" "$(_count render "$AW/log")" "$before" assert_contains "…and says it will retry" "$out" "retrying on the next tick" -aw_run "192.168.1.5 fd1c::b" >/dev/null -assert_eq "the render runs once the lock is free" "$(aw_count render "$AW/log")" "$((before + 1))" -before=$(aw_count render "$AW/log") -aw_run "192.168.1.5 fd1c::a" activating >/dev/null -assert_eq "nothing renders while pithead-boot is still running" "$(aw_count render "$AW/log")" "$before" -aw_run "192.168.1.5 fd1c::a" failed >/dev/null -assert_eq "a failed pithead-boot (fallback boot) does not disable the watch" "$(aw_count render "$AW/log")" "$((before + 1))" -unset AW aw_run aw_count out before +before=$(_count render "$AW/log") +_x=$(_count restart "$AW/restarts") +_run "192.168.1.5 fd1c::b" >/dev/null +assert_eq "the render runs once the lock is free" "$(_count render "$AW/log")" "$((before + 1))" +assert_eq "…and its restart runs while the mutation lock is held" "$(tail -n 1 "$AW/lock-seen")" "held" +assert_eq "…with no lock that was free underneath it" "$(tail -n 1 "$AW/restart-used")" "$AW/bin/_restart-ok" +before=$(_count render "$AW/log") +_run "192.168.1.5 fd1c::a" activating >/dev/null +assert_eq "nothing renders while pithead-boot is still running" "$(_count render "$AW/log")" "$before" +_run "192.168.1.5 fd1c::a" failed >/dev/null +assert_eq "a failed pithead-boot (fallback boot) does not disable the watch" "$(_count render "$AW/log")" "$((before + 1))" +printf 'apply-crt\n' >"$AW/dir/data/tls/wizard.crt" +printf 'apply-caddy\n' >"$AW/dir/Caddyfile" +before=$(_count render "$AW/log") +_x=$(_count restart "$AW/restarts") +out=$(_run "192.168.1.5 fd1c::a") +assert_eq "a files-only change does not make the watch render" "$(_count render "$AW/log")" "$before" +assert_eq "the tick after an apply-owned re-render does not restart a Caddy that already serves the files" \ + "$(_count restart "$AW/restarts")" "$_x" +assert_contains "…and the log names the served files, not the addresses" "$out" "certificate or the Caddyfile changed" +assert_not_contains "…without blaming the addresses" "$out" "addresses changed" +assert_eq "the recorded signature makes the following tick quiet" "$(_run "192.168.1.5 fd1c::a")" "" +_restart fail +_run "192.168.1.5 fd1c::e" >/dev/null +before=$(_count render "$AW/log") +_x=$(_count restart "$AW/restarts") +_restart ok +out=$(_run "192.168.1.5 fd1c::a") +assert_eq "the owed restart is retried without rendering again" "$(_count render "$AW/log")" "$before" +assert_eq "…under the mutation lock" "$(tail -n 1 "$AW/lock-seen")" "held" +assert_eq "…as exactly one restart, the owed one" "$(_count restart "$AW/restarts")" "$((_x + 1))" +assert_contains "…named for the owed restart" "$out" "owed" +assert_eq "the following tick is quiet" "$(_run "192.168.1.5 fd1c::a")" "" +assert_eq "…with no pending marker left behind" "$(cat "$AW/state.pending" 2>/dev/null)" "" +_render quiet +printf 'apply-crt2\n' >"$AW/dir/data/tls/wizard.crt" +printf 'apply-caddy2\n' >"$AW/dir/Caddyfile" +before=$(_count render "$AW/log") +_x=$(_count restart "$AW/restarts") +out=$(_run "192.168.1.5 fd1c::h") +assert_eq "an address change whose files are already current renders once" "$(_count render "$AW/log")" "$((before + 1))" +assert_eq "…and does not restart the Caddy apply already restarted" "$(_count restart "$AW/restarts")" "$_x" +assert_contains "…while the log says the files were already current" "$out" "already current" +assert_not_contains "…without claiming a restart" "$out" "restarting Caddy" +assert_eq "the following tick is quiet" "$(_run "192.168.1.5 fd1c::h")" "" +rm -f "$AW/state" "$AW/state.served" "$AW/state.pending" +before=$(_count render "$AW/log") +_x=$(_count restart "$AW/restarts") +out=$( + exec 8>>"$AW/lock" + flock 8 + _run "192.168.1.5 fd1c::i" +) +assert_contains "a busy first tick says it will retry" "$out" "retrying on the next tick" +assert_eq "…renders nothing" "$(_count render "$AW/log")" "$before" +assert_eq "…and leaves no served baseline behind" "$(cat "$AW/state.served" 2>/dev/null)" "" +assert_eq "…and restarts nothing" "$(_count restart "$AW/restarts")" "$_x" +out=$(_run "192.168.1.5 fd1c::i") +assert_eq "the free tick on unchanged files is quiet" "$out" "" +assert_eq "…and restarts nothing, Caddy already serving what the render produced" \ + "$(_count restart "$AW/restarts")" "$_x" +assert_contains "…while recording the address set" "$(cat "$AW/state")" "192.168.1.5" +unset AW _run _render _restart _count out before _x echo "== unit: address_watch_verdict — the KVM provision leg's discrimination (#2463) ==" # shellcheck source=tests/os/appliance-address-watch-leg.sh From 34fbca9f6db90be79a951402303b7cdc43c04571 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:58:56 -0600 Subject: [PATCH 028/112] rig share leg: keep the #3375 fastpath receipt when the proxy is recreated mid-reading (#4111) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(os): keep the proxy-recreation receipt when the proxy is recreated mid-reading A pithead-miner-recovery run whose worker-list reading straddled the proxy recreation adopted the new container identity — a failed reading printed the same "reset" as a connected one, and a connected reading of the old container sat beside an inspect of the new — so the recorded identity moved without ever being compared and the recreation fastpath could never fire (#4081). The run now brackets its reading with the container identity and moves the recorded identity only when a connected reading saw no change across it, so the next reading still sees the recreation and restarts xmrig at once. The rig share leg's receipt line now records which path restarted xmrig (fastpath_restart/timer_restart). Closes #4081 Co-Authored-By: Claude Code * tests: carry the recovery journal and restart-path verdict on every rig leg failure Co-Authored-By: Claude Code * tests: follow the split recovery and xmrig journal windows in the diagnostics contract Co-Authored-By: Claude Code --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Code --- docs/dev/appliance-wizard.md | 7 +- docs/dev/file-budget.tsv | 1 + os/overlay/pithead-miner-recovery | 9 +- tests/os/appliance-miner-recovery-leg.sh | 37 ++++++-- .../os/selftest-miner-recovery-diagnostics.sh | 6 +- tests/os/selftest-miner-recovery-leg.sh | 56 +++++++++++ tests/os/selftest-miner-recovery.sh | 95 ++++++++++++++++++- 7 files changed, 195 insertions(+), 16 deletions(-) create mode 100644 tests/os/selftest-miner-recovery-leg.sh diff --git a/docs/dev/appliance-wizard.md b/docs/dev/appliance-wizard.md index caa09ed5ae..1b524c6b81 100644 --- a/docs/dev/appliance-wizard.md +++ b/docs/dev/appliance-wizard.md @@ -539,9 +539,12 @@ Five steps, each answering a hardware-validated failure: or block the slot commit — the stack serving is the product's health, the miner is a passenger (`|| true`). The appliance checks an active, enabled local miner every 30 seconds. A successful proxy worker-list reading that finds the proxy container restarted since the - previous reading while the local miner still has no connection queues an immediate XMRig + recorded identity while the local miner still has no connection queues an immediate XMRig restart — a proxy replaced underneath a live miner is the stall XMRig never recovers from - itself, so it does not wait out the window. Otherwise five minutes of successful proxy + itself, so it does not wait out the window. The guard brackets each reading with the container + identity and moves the recorded identity only on a successful reading that saw no change + across it, so a proxy recreated during a failed or connected reading still reads as a + recreation on the next reading. Otherwise five minutes of successful proxy worker-list readings with no connection for the local miner’s rendered identity queue an XMRig restart, logged by `pithead-miner-recovery.service`. Other connected rigs do not reset that window. Missing readings, a connected local miner, a stopped diff --git a/docs/dev/file-budget.tsv b/docs/dev/file-budget.tsv index c81ee78d79..6f403fedfe 100644 --- a/docs/dev/file-budget.tsv +++ b/docs/dev/file-budget.tsv @@ -85,3 +85,4 @@ tests/stack/test-config.sh 705 tests/stack/test-monero-tari.sh 557 tests/stack/test-rig-worker.sh 616 tests/stack/test-tor-network.sh 776 +tests/os/selftest-miner-recovery.sh 412 diff --git a/os/overlay/pithead-miner-recovery b/os/overlay/pithead-miner-recovery index 6dc772b23f..d2d60ef9fa 100755 --- a/os/overlay/pithead-miner-recovery +++ b/os/overlay/pithead-miner-recovery @@ -19,6 +19,7 @@ systemctl is-active --quiet xmrig.service || reset_window worker_config=${PITHEAD_MINER_RECOVERY_CONFIG:-/data/rigforge/data/worker/xmrig/build/config.json} worker=$(jq -er '.pools[0].user | select(type == "string" and length > 0)' "$worker_config" 2>/dev/null) || reset_window rig_id=$(jq -er '.pools[0]["rig-id"] // "" | select(type == "string")' "$worker_config" 2>/dev/null) || reset_window +proxy_before=$(timeout 5 podman inspect -f '{{.State.StartedAt}}' xmrig-proxy 2>/dev/null) || proxy_before= reading=$( timeout 15 podman exec -i dashboard python - "$worker" "$rig_id" <<'PY' import os @@ -49,13 +50,15 @@ try: count += row[2] print("idle" if count == 0 else "reset") except Exception: - print("reset") + print("error") PY ) 2>/dev/null || reset_window -proxy_now=$(timeout 10 podman inspect -f '{{.State.StartedAt}}' xmrig-proxy 2>/dev/null) || proxy_now= +proxy_now=$(timeout 5 podman inspect -f '{{.State.StartedAt}}' xmrig-proxy 2>/dev/null) || proxy_now= seen_proxy=$(cat "$STATE.proxy" 2>/dev/null || true) [ "$reading" = idle ] || { - mark_proxy + if [ "$reading" = reset ] && [ "$proxy_before" = "$proxy_now" ]; then + mark_proxy + fi reset_window } if [ -n "$seen_proxy" ] && [ -n "$proxy_now" ] && [ "$seen_proxy" != "$proxy_now" ]; then diff --git a/tests/os/appliance-miner-recovery-leg.sh b/tests/os/appliance-miner-recovery-leg.sh index eeec1e927d..0cc17a63f0 100644 --- a/tests/os/appliance-miner-recovery-leg.sh +++ b/tests/os/appliance-miner-recovery-leg.sh @@ -57,15 +57,25 @@ miner_cleanup() { return "$failed" } miner_diagnostics() { - local recorded=no + local recorded=no journal [ ! -e "$T3375/strand" ] || recorded=yes printf 'pithead-t3375: failure phase=%s strand_recorded=%s\n' "${MINER_PHASE:-unknown}" "$recorded" printf 'pithead-t3375: local connections/accepted: ' miner_counts || printf '%s\n' unreadable timeout 10 systemctl show pithead-t3375-watcher.service -p LoadState -p ActiveState -p Result -p ExecMainStatus || true timeout 10 journalctl --no-pager -n 40 --since '-20 minutes' -u pithead-t3375-watcher.service || true - timeout 10 journalctl --no-pager -n 40 --since '-20 minutes' \ - -u pithead-miner-recovery.service -u xmrig.service || true + if [ -e "$T3375/backup-at" ]; then + if journal=$(timeout 10 journalctl --no-pager --since "@$(cat "$T3375/backup-at")" \ + -u pithead-miner-recovery.service); then + printf '%s\n' "$journal" + miner_journal_receipt "$journal" || true + else + printf '%s\n' 'pithead-t3375: recovery_journal=unreadable' + fi + else + timeout 10 journalctl --no-pager -n 40 --since '-20 minutes' -u pithead-miner-recovery.service || true + fi + timeout 10 journalctl --no-pager -n 40 --since '-20 minutes' -u xmrig.service || true } miner_guest_exit() { local rc=$? @@ -91,12 +101,23 @@ miner_watch_restore() { fi return "$failed" } +miner_journal_receipt() { + local journal=$1 timer=absent + if grep -Fq 'disconnected for 300 seconds' <<<"$journal"; then timer=observed; fi + if grep -Fq 'proxy was recreated' <<<"$journal"; then + printf '%s\n' "pithead-t3375: fastpath_restart=observed timer_restart=$timer" + return 0 + fi + printf '%s\n' "pithead-t3375: fastpath_restart=missing timer_restart=$timer" + return 1 +} miner_fastpath_receipt() { - [ -e /usr/local/sbin/pithead-miner-recovery ] || return 0 - grep -Fq 'proxy was recreated' /usr/local/sbin/pithead-miner-recovery || return 0 - timeout 10 journalctl --no-pager --since "@$(cat "$T3375/backup-at")" \ - -u pithead-miner-recovery.service | grep -Fq 'proxy was recreated' || return 1 - printf '%s\n' 'pithead-t3375: fastpath_restart=observed' + local bin=${PITHEAD_MINER_RECOVERY_BIN:-/usr/local/sbin/pithead-miner-recovery} journal + [ -e "$bin" ] || return 0 + grep -Fq 'proxy was recreated' "$bin" || return 0 + journal=$(timeout 10 journalctl --no-pager --since "@$(cat "$T3375/backup-at")" \ + -u pithead-miner-recovery.service) || return 1 + miner_journal_receipt "$journal" } miner_watch() { local end=$((SECONDS + 1200)) diff --git a/tests/os/selftest-miner-recovery-diagnostics.sh b/tests/os/selftest-miner-recovery-diagnostics.sh index 91bbf18b89..1e1e893cd5 100644 --- a/tests/os/selftest-miner-recovery-diagnostics.sh +++ b/tests/os/selftest-miner-recovery-diagnostics.sh @@ -18,7 +18,8 @@ journalctl() { [ -e "$T3375/armed" ] || return 99 case "$*" in '--no-pager -n 40 --since -20 minutes -u pithead-t3375-watcher.service') printf '%s\n' 'fixture watcher failure' ;; - '--no-pager -n 40 --since -20 minutes -u pithead-miner-recovery.service -u xmrig.service') printf '%s\n' 'fixture miner journal' ;; + '--no-pager -n 40 --since -20 minutes -u pithead-miner-recovery.service') printf '%s\n' 'fixture recovery journal' ;; + '--no-pager -n 40 --since -20 minutes -u xmrig.service') printf '%s\n' 'fixture xmrig journal' ;; *) return 99 ;; esac return "${JOURNAL_RC:-0}" @@ -34,7 +35,8 @@ for journal_rc in 0 1; do grep -Fx 'pithead-t3375: local connections/accepted: [0,0]' "$work/log" >/dev/null grep -Fx 'Result=exit-code' "$work/log" >/dev/null grep -Fx 'fixture watcher failure' "$work/log" >/dev/null - grep -Fx 'fixture miner journal' "$work/log" >/dev/null + grep -Fx 'fixture recovery journal' "$work/log" >/dev/null + grep -Fx 'fixture xmrig journal' "$work/log" >/dev/null done systemctl() { case "$*" in diff --git a/tests/os/selftest-miner-recovery-leg.sh b/tests/os/selftest-miner-recovery-leg.sh new file mode 100644 index 0000000000..fd245bfdfb --- /dev/null +++ b/tests/os/selftest-miner-recovery-leg.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +set -euo pipefail +export TMPDIR="${TMPDIR:-/tmp}" +ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +work=$(mktemp -d "${TMPDIR:?}/miner-recovery-leg.XXXXXX") +trap 'rm -rf "$work"' EXIT +# shellcheck source=tests/os/appliance-miner-recovery-leg.sh +source "$ROOT/tests/os/appliance-miner-recovery-leg.sh" +T3375="$work/strand" +mkdir "$T3375" +miner_counts() { return 1; } +timeout() { + if [ "$1" = 10 ]; then + shift + "$@" + else + command timeout "$@" + fi +} +systemctl() { return 0; } +journalctl() { + case "$*" in + *'--since @'*) + [ -r "$work/recovery-journal" ] || return 1 + cat "$work/recovery-journal" + ;; + *'-u pithead-t3375-watcher.service') printf '%s\n' 'watcher noise' ;; + *'-u pithead-miner-recovery.service') printf '%s\n' 'recovery fallback' ;; + *'-u xmrig.service') printf '%s\n' 'xmrig noise' ;; + esac +} +MINER_PHASE=verdict +echo 0 >"$T3375/backup-at" +printf '%s\n' 'pithead-miner-recovery: active local miner disconnected for 300 seconds; restarting xmrig' >"$work/recovery-journal" +out=$(miner_diagnostics) +grep -Fq 'local connections/accepted: unreadable' <<<"$out" +grep -Fq 'pithead-t3375: fastpath_restart=missing timer_restart=observed' <<<"$out" +grep -Fq 'disconnected for 300 seconds' <<<"$out" +printf '%s\n' 'pithead-miner-recovery: local miner proxy was recreated while the miner was disconnected; restarting xmrig' >"$work/recovery-journal" +out=$(miner_diagnostics) +grep -Fq 'pithead-t3375: fastpath_restart=observed timer_restart=absent' <<<"$out" +printf '%s\n' \ + 'pithead-miner-recovery: local miner proxy was recreated while the miner was disconnected; restarting xmrig' \ + 'pithead-miner-recovery: active local miner disconnected for 300 seconds; restarting xmrig' >"$work/recovery-journal" +out=$(miner_diagnostics) +grep -Fq 'pithead-t3375: fastpath_restart=observed timer_restart=observed' <<<"$out" +rm "$work/recovery-journal" +out=$(miner_diagnostics) +grep -Fq 'pithead-t3375: recovery_journal=unreadable' <<<"$out" +grep -Fq 'xmrig noise' <<<"$out" +! grep -Fq 'fastpath_restart=' <<<"$out" +rm "$T3375/backup-at" +out=$(miner_diagnostics) +grep -Fq 'recovery fallback' <<<"$out" +! grep -Fq 'fastpath_restart=' <<<"$out" +printf '%s\n' 'PASS: every failure diagnosis carries the recovery journal and the restart-path verdict' diff --git a/tests/os/selftest-miner-recovery.sh b/tests/os/selftest-miner-recovery.sh index bdff2a3af4..fa799d0a7c 100644 --- a/tests/os/selftest-miner-recovery.sh +++ b/tests/os/selftest-miner-recovery.sh @@ -21,6 +21,9 @@ cat >"$work/bin/podman" <<'SH' #!/bin/bash if [ "$1" = inspect ]; then [ "${INSPECT_FAIL:-0}" = 0 ] || exit 1 + if [ -n "${PROXY_STARTED_AT_FILE:-}" ] && [ -f "$PROXY_STARTED_AT_FILE" ]; then + PROXY_STARTED_AT=$(cat "$PROXY_STARTED_AT_FILE") + fi [ -n "${PROXY_STARTED_AT:-}" ] || exit 1 printf '%s\n' "$PROXY_STARTED_AT" exit 0 @@ -38,6 +41,7 @@ SH cat >"$work/python/mining_dashboard/helper/http.py" <<'PY' import json import os +import time class Response: def raise_for_status(self): if os.environ.get("HTTP_FAIL") == "1": @@ -46,6 +50,12 @@ class Response: return json.loads(os.environ["PROXY_WORKERS"]) def bounded_get(url, headers, timeout): assert url == "http://xmrig-proxy:3344/1/workers" + hold = os.environ.get("PROXY_HOLD") + if hold: + with open(hold, "w") as marker: + marker.write("reading") + while os.path.exists(hold): + time.sleep(0.05) assert headers == {"Authorization": "Bearer fixture-token"} assert timeout == 5 return Response() @@ -113,6 +123,57 @@ export PROXY_WORKERS='{"mode":"rig_id","workers":[]}' tick 1320 no_restart [ "$(cat "$work/state")" = 1320 ] +export PROXY_STARTED_AT_FILE="$work/proxy-id" +printf '4000\n' >"$work/proxy-id" +export PROXY_WORKERS='{"mode":"rig_id","workers":[["fixture-local","fixture",1]]}' +tick 3000 +no_restart +[ "$(cat "$work/state.proxy")" = 4000 ] +export PROXY_HOLD="$work/recreate" +bash "$ROOT/os/overlay/pithead-miner-recovery" >"$work/output" & +bg=$! +bg_end=$((SECONDS + 20)) +until [ -e "$PROXY_HOLD" ]; do + [ "$SECONDS" -lt "$bg_end" ] || { + kill "$bg" + exit 1 + } + sleep 0.05 +done +printf '5000\n' >"$work/proxy-id" +rm -f "$PROXY_HOLD" +wait "$bg" +no_restart +[ "$(cat "$work/state.proxy")" = 4000 ] +export PROXY_WORKERS='{"mode":"rig_id","workers":[["fixture-rig","fixture",1]]}' +unset PROXY_HOLD +tick 3030 +[ "$(cat "$work/calls")" = restart ] +grep -Fq 'proxy was recreated while the miner was disconnected; restarting xmrig' "$work/output" +[ "$(cat "$work/state.proxy")" = 5000 ] +[ ! -e "$work/state" ] +export PROXY_STARTED_AT=6000 +unset PROXY_STARTED_AT_FILE +rm -f "$work/state" "$work/state.proxy" "$work/calls" +export PROXY_WORKERS='{"mode":"rig_id","workers":[["fixture-local","fixture",1]]}' +tick 3100 +no_restart +[ "$(cat "$work/state.proxy")" = 6000 ] +export HTTP_FAIL=1 +export PROXY_STARTED_AT=7000 +tick 3130 +no_restart +[ "$(cat "$work/state.proxy")" = 6000 ] +unset HTTP_FAIL +export PROXY_WORKERS='{"mode":"rig_id","workers":[]}' +rm -f "$work/state" +tick 3160 +[ "$(cat "$work/calls")" = restart ] +grep -Fq 'proxy was recreated while the miner was disconnected; restarting xmrig' "$work/output" +[ "$(cat "$work/state.proxy")" = 7000 ] +rm -f "$work/state" "$work/state.proxy" "$work/calls" +unset PROXY_STARTED_AT +export PROXY_WORKERS='{"mode":"rig_id","workers":[]}' export INSPECT_FAIL=1 rm -f "$work/state" "$work/state.proxy" tick 1400 @@ -220,7 +281,7 @@ done grep -Fq '/usr/local/sbin/pithead-miner-recovery' "$ROOT/os/rootfs/Dockerfile" grep -Fq 'ExecStart=/usr/local/sbin/pithead-miner-recovery' "$ROOT/os/overlay/pithead-miner-recovery.service" grep -Fq 'OnUnitInactiveSec=30s' "$ROOT/os/overlay/pithead-miner-recovery.timer" -printf '%s\n' 'PASS: miner recovery debounce, proxy-recreation fast restart, refusals, decoder, failure and image wiring' +printf '%s\n' 'PASS: miner recovery debounce, proxy-recreation fast restart, identity bracket, refusals, decoder, failure and image wiring' # shellcheck source=tests/os/appliance-miner-recovery-leg.sh source "$ROOT/tests/os/appliance-miner-recovery-leg.sh" @@ -317,3 +378,35 @@ if miner_watch_restore; then fi [ -e "$T3375/paused" ] printf '%s\n' 'PASS: failed watchdog restoration retains its control files' +export PITHEAD_MINER_RECOVERY_BIN="$work/recovery-bin" +printf '%s\n' 'printf proxy was recreated marker' >"$work/recovery-bin" +mkdir -p "$T3375" +printf '0\n' >"$T3375/backup-at" +journalctl() { printf '%s\n' 'pithead-t3375: nothing relevant'; } +rc=0 +out=$(miner_fastpath_receipt) || rc=$? +[ "$rc" = 1 ] +[ "$out" = 'pithead-t3375: fastpath_restart=missing timer_restart=absent' ] +journalctl() { + printf '%s\n' 'pithead-miner-recovery: active local miner disconnected for 300 seconds; restarting xmrig' +} +rc=0 +out=$(miner_fastpath_receipt) || rc=$? +[ "$rc" = 1 ] +[ "$out" = 'pithead-t3375: fastpath_restart=missing timer_restart=observed' ] +journalctl() { + printf '%s\n' \ + 'pithead-miner-recovery: local miner proxy was recreated while the miner was disconnected; restarting xmrig' \ + 'pithead-miner-recovery: active local miner disconnected for 300 seconds; restarting xmrig' +} +out=$(miner_fastpath_receipt) +[ "$out" = 'pithead-t3375: fastpath_restart=observed timer_restart=observed' ] +journalctl() { + printf '%s\n' 'pithead-miner-recovery: local miner proxy was recreated while the miner was disconnected; restarting xmrig' +} +out=$(miner_fastpath_receipt) +[ "$out" = 'pithead-t3375: fastpath_restart=observed timer_restart=absent' ] +printf '%s\n' 'no fastpath marker here' >"$work/recovery-bin" +miner_fastpath_receipt +unset PITHEAD_MINER_RECOVERY_BIN +printf '%s\n' 'PASS: receipt distinguishes fastpath and timer restarts' From edc5a609940f741df96de0e3c4bb4d6d846f1c72 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:59:04 -0600 Subject: [PATCH 029/112] Per-service Restart in Service diagnostics through the control channel (#4062) (#4110) * dashboard: per-service Restart in Service diagnostics through a new svc-restart control verb (#4062) Co-Authored-By: Claude Sonnet 5.5 * tests: drop header comment from the restart frontend test (#4062) Co-Authored-By: Claude Sonnet 5.5 * integration: mini-stack round trip for the svc-restart verb (#4062) Co-Authored-By: Claude Sonnet 5.5 * integration: format the mini-stack call (#4062) Co-Authored-By: Claude Sonnet 5.5 * tests: svc-restart rows use static labels (#4062) Co-Authored-By: Claude Sonnet 5.5 * integration: show the response and runner tail when the svc-restart round trip fails (#4062) Co-Authored-By: Claude Sonnet 5.5 * integration: probe the route when the svc-restart round trip fails (#4062) Co-Authored-By: Claude Sonnet 5.5 * integration: restore the spool permissions before the svc-restart round trip (#4062) Co-Authored-By: Claude Sonnet 5.5 * tests: assert the refusal text without a regex escape (#4062) Co-Authored-By: Claude Sonnet 5.5 * tests: restore the closing of the svc-restart browser journey after the merge (#4062) Co-Authored-By: Claude Sonnet 5.5 * tests: the restart failure row uses a refused submission after the merge (#4062) Co-Authored-By: Claude Sonnet 5.5 * svc-restart: keep hyphens in the audited service, drop added comments, add a live tier-4 phase (#4062) Co-Authored-By: Claude Sonnet 5.5 * selftest: the lifecycle gate drive sets RUN_SVC_RESTART (#4062) Co-Authored-By: Claude Sonnet 5.5 * selftest: register the svc-restart module in the run.sh module order (#4062) Co-Authored-By: Claude Sonnet 5.5 * svc-restart: remove explanatory comments from the hunks this PR edits (#4062) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- .../service/health/diagnostics_service.py | 6 + .../web/static/system/diagview.mjs | 69 +++++++++- .../web/views/diagnostics_views.py | 22 ++++ dashboard/tests/browser/diagnostics.test.mjs | 62 +++++++++ .../frontend/system/diagview-restart.test.mjs | 119 +++++++++++++++++ .../tests/web/views/test_diagnostics_views.py | 66 +++++++++- docs/dashboard.md | 26 +++- docs/dev/integration-testing.md | 7 +- docs/operations.md | 6 + lib/pithead/42-control-approval-helpers.sh | 2 +- lib/pithead/46c-control-svc-restart.sh | 57 ++++++++ lib/pithead/49-control-request-loop.sh | 6 +- tests/integration/e2e.sh | 10 +- tests/integration/lib/harness-args.sh | 4 +- tests/integration/lib/run-cli.sh | 4 + tests/integration/lib/run-svc-restart.sh | 70 ++++++++++ tests/integration/lib/run-usage.sh | 3 + .../mini-stack/control-roundtrip.sh | 33 +++++ .../integration/mini-stack/run-mini-stack.sh | 11 +- tests/integration/run.sh | 8 +- .../selftest/selftest-e2e-phases.sh | 10 +- .../selftest/selftest-e2e-sweep.sh | 4 +- .../selftest-lifecycle-restore-health.sh | 6 +- .../selftest/selftest-run-modules.sh | 6 +- .../control/test-control-lifecycle-verbs.sh | 123 ++++++++++++++++++ 25 files changed, 691 insertions(+), 49 deletions(-) create mode 100644 dashboard/tests/frontend/system/diagview-restart.test.mjs create mode 100644 lib/pithead/46c-control-svc-restart.sh create mode 100644 tests/integration/lib/run-svc-restart.sh diff --git a/dashboard/mining_dashboard/service/health/diagnostics_service.py b/dashboard/mining_dashboard/service/health/diagnostics_service.py index b09142c0fa..4e0ee60d77 100644 --- a/dashboard/mining_dashboard/service/health/diagnostics_service.py +++ b/dashboard/mining_dashboard/service/health/diagnostics_service.py @@ -56,6 +56,12 @@ def submit_diag_logs(container: str, lines: int, actor: str = "") -> str: ) +def submit_svc_restart(container: str, actor: str = "") -> str: + return request_spool.write( + {"id": str(uuid.uuid4()), "action": "svc-restart", "actor": actor, "container": container} + ) + + def submit_support_bundle(hours=None, actor: str = "") -> str: intent = {"id": str(uuid.uuid4()), "action": "support-bundle", "actor": actor} if hours is not None: diff --git a/dashboard/mining_dashboard/web/static/system/diagview.mjs b/dashboard/mining_dashboard/web/static/system/diagview.mjs index 71bd5dba35..10e82f04cd 100644 --- a/dashboard/mining_dashboard/web/static/system/diagview.mjs +++ b/dashboard/mining_dashboard/web/static/system/diagview.mjs @@ -36,9 +36,18 @@ export const DIAG_SERVICES = [ ...DIAG_CONTAINERS.slice(3), ]; -// Doctor has no section/name field. These narrow tokens group its existing messages for display; -// one cross-service check may appear under more than one service, while unmatched checks remain -// visible under Machine checks. No check is dropped or rewritten. +export const RESTART_IMPACT = { + tor: "Every Tor circuit drops and rebuilds, and monerod is restarted with it so it re-dials its peers; wallet-rpc is interrupted while monerod restarts.", + monerod: + "wallet-rpc is interrupted until monerod answers again, and the node's sync pauses briefly.", + "wallet-rpc": "Monero wallet sync and payouts pause briefly.", + tari: "tari-wallet is interrupted until the node answers again, and the node's sync pauses briefly.", + "tari-wallet": "Tari wallet sync and payouts pause briefly.", + p2pool: "xmrig-proxy is interrupted and miners reconnect once p2pool answers again.", + "xmrig-proxy": "Miners reconnect once the proxy answers again.", +}; +export const DIAG_RESTARTABLE = Object.keys(RESTART_IMPACT); + const SERVICE_HINTS = { tor: [/\btor\b/i, /\bonion\b/i, /\bsocks\b/i, /egress firewall/i], monerod: [/\bmonerod\b/i, /\bmonero node\b/i, /monero.*synchron/i], @@ -159,7 +168,7 @@ const STATUS_CLS = { fail: "status-bad", warn: "status-warn", ok: "status-ok" }; export class DiagnosticsPanel extends Component { constructor(props) { super(props); - this.state = { healthPhase: "idle", healthResult: null, logs: {} }; + this.state = { healthPhase: "idle", healthResult: null, logs: {}, restarts: {} }; } async runHealth() { @@ -207,6 +216,57 @@ export class DiagnosticsPanel extends Component { } } + setRestart(service, restart) { + this.setState((state) => ({ restarts: { ...state.restarts, [service]: restart } })); + } + + async runRestart(service) { + this.setRestart(service, { phase: "waiting", result: null }); + try { + const result = await runDiag("svc-restart", { container: service }, `the ${service} restart`); + this.setRestart(service, { + phase: result.status === "applied" ? "done" : "failed", + result, + }); + } catch (error) { + this.setRestart(service, { + phase: "failed", + result: { error: String(error.message || error) }, + }); + } + } + + renderRestart(service) { + if (!DIAG_RESTARTABLE.includes(service)) return null; + const restart = this.state.restarts[service] || { phase: "idle", result: null }; + const { phase, result } = restart; + return html`
    + + ${ + phase === "confirm" + ? html`

    Restart ${service}? ${RESTART_IMPACT[service]} + +

    ` + : null + } + ${phase === "waiting" ? html`

    Waiting for the host to restart ${service}…

    ` : null} + ${phase === "done" ? html`

    ${service} was restarted.

    ` : null} + ${ + phase === "failed" + ? html`

    ${(result && (result.error || result.note)) || `The host could not restart ${service}.`}

    ` + : null + } +
    `; + } + renderChecks(rows) { if (!rows.length) return html`

    No service-specific check returned.

    `; @@ -265,6 +325,7 @@ export class DiagnosticsPanel extends Component { : html`

    Run the health check to see this service's checks.

    ` } ${this.renderLog(service.name)} + ${this.renderRestart(service.name)} `; } diff --git a/dashboard/mining_dashboard/web/views/diagnostics_views.py b/dashboard/mining_dashboard/web/views/diagnostics_views.py index c2937b2e57..e60a555802 100644 --- a/dashboard/mining_dashboard/web/views/diagnostics_views.py +++ b/dashboard/mining_dashboard/web/views/diagnostics_views.py @@ -86,6 +86,27 @@ async def handle_diag_logs(request): return web.json_response({"id": rid, "status": "pending"}, status=202) +async def handle_svc_restart(request): + _require_control_header(request) + try: + body = await request.json() + except Exception: + raise web.HTTPBadRequest(text="Body must be JSON.") from None + if not isinstance(body, dict): + raise web.HTTPBadRequest(text="Body must be a JSON object.") + container = body.get("container") + if not diagnostics_service.valid_container(container): + raise web.HTTPBadRequest(text="'container' must be a compose service name.") + try: + rid = diagnostics_service.submit_svc_restart( + container, request.headers.get("X-Auth-User", "") + ) + except Exception: + logger.exception("Error submitting svc-restart request") + return web.json_response({"error": "Failed to submit the restart request."}, status=500) + return web.json_response({"id": rid, "status": "pending"}, status=202) + + async def handle_onion_key(request): """Ask the host for the dashboard onion's Tor client-auth credential, shown once (#1882). @@ -140,6 +161,7 @@ def control_routes(): return [ web.post("/api/control/diag-doctor", handle_diag_doctor), web.post("/api/control/diag-logs", handle_diag_logs), + web.post("/api/control/svc-restart", handle_svc_restart), web.post("/api/control/onion-client-key", handle_onion_key), web.post("/api/control/support-bundle", handle_support_bundle), web.get( diff --git a/dashboard/tests/browser/diagnostics.test.mjs b/dashboard/tests/browser/diagnostics.test.mjs index 67885d69e5..e81cc4d1b8 100644 --- a/dashboard/tests/browser/diagnostics.test.mjs +++ b/dashboard/tests/browser/diagnostics.test.mjs @@ -90,6 +90,68 @@ test("a failed service-log read displays its reason and can be retried", async ( } }); +test("a service restart is confirmed first, then shows the host's result and a refusal", async ({ + page, + ui, +}) => { + await page.clock.install(); + const posts = []; + await page.route("**/api/control/svc-restart", async (route) => { + posts.push(route.request()); + await route.fulfill({ status: 202, json: { id: `restart-${posts.length}` } }); + }); + await page.route("**/api/control/result?**", (route) => { + const id = new URL(route.request().url()).searchParams.get("id"); + return route.fulfill({ + json: + id === "restart-1" + ? { status: "applied", container: "tor" } + : { + status: "rejected", + error: "tor was restarted less than 120s ago; wait before restarting it again.", + }, + }); + }); + await mount(ui); + + const tor = page.locator("section").filter({ + has: page.getByRole("heading", { name: "tor", exact: true }), + }); + await expect( + page + .locator("section") + .filter({ + has: page.getByRole("heading", { name: "caddy", exact: true }), + }) + .getByRole("button", { name: /Restart/ }), + ).toHaveCount(0); + + await tor.getByRole("button", { name: "Restart tor" }).click(); + await expect(tor.getByText(/monerod is restarted with it/)).toBeVisible(); + expect(posts).toHaveLength(0); + await tor.getByRole("button", { name: "Cancel" }).click(); + await expect(tor.getByText(/monerod is restarted with it/)).toHaveCount(0); + + await tor.getByRole("button", { name: "Restart tor" }).click(); + await tor.getByRole("button", { name: "Confirm restart of tor" }).click(); + await expect(tor.getByRole("button", { name: "Restart tor" })).toBeDisabled(); + await expect(tor.getByText(/Waiting for the host to restart tor/)).toBeVisible(); + await page.clock.fastForward(2000); + await expect(tor.getByText("tor was restarted.")).toBeVisible(); + await expect(tor.getByRole("button", { name: "Restart tor" })).toBeEnabled(); + + await tor.getByRole("button", { name: "Restart tor" }).click(); + await tor.getByRole("button", { name: "Confirm restart of tor" }).click(); + await page.clock.fastForward(2000); + await expect(tor.getByText(/wait before restarting it again/)).toBeVisible(); + + expect(posts).toHaveLength(2); + for (const request of posts) { + expect(request.headers()["x-pithead-control"]).toBe("1"); + expect(request.postDataJSON()).toEqual({ container: "tor" }); + } +}); + for (const theme of ["Light", "Dark"]) { test(`${theme} theme: the diagnostics controls render as bordered buttons with a focus ring`, async ({ page, diff --git a/dashboard/tests/frontend/system/diagview-restart.test.mjs b/dashboard/tests/frontend/system/diagview-restart.test.mjs new file mode 100644 index 0000000000..e42ea4b09e --- /dev/null +++ b/dashboard/tests/frontend/system/diagview-restart.test.mjs @@ -0,0 +1,119 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; + +import { + DIAG_RESTARTABLE, + DiagnosticsPanel, +} from "../../../mining_dashboard/web/static/system/diagview.mjs"; +import { renderToString } from "../helpers/render.mjs"; + +const ID = "22222222-2222-4222-8222-222222222222"; +const okResult = (body) => ({ status: 200, ok: true, json: async () => body }); + +async function withFastPoll(fetchStub, fn) { + const realFetch = globalThis.fetch; + const realTimeout = globalThis.setTimeout; + globalThis.fetch = fetchStub; + globalThis.setTimeout = (cb) => { + cb(); + return 0; + }; + try { + return await fn(); + } finally { + globalThis.fetch = realFetch; + globalThis.setTimeout = realTimeout; + } +} + +function inst(props = { enabled: true }, state = {}) { + const panel = new DiagnosticsPanel(props); + panel.props = props; + panel.state = { ...panel.state, ...state }; + panel.setState = (next) => { + const patch = typeof next === "function" ? next(panel.state, panel.props) : next; + panel.state = { ...panel.state, ...patch }; + }; + return panel; +} + +const restartPost = (opts) => JSON.parse(opts.body); + +test("every restartable service shows a Restart button and the four platform services show none", () => { + const out = renderToString(inst().render()); + assert.equal((out.match(/]*>Restart [a-z0-9-]+/g) || []).length, DIAG_RESTARTABLE.length); + for (const service of ["wallet-rpc", "tari-wallet", "tor", "monerod"]) { + assert.match(out, new RegExp(`]*>Restart ${service}\\b`)); + } + for (const service of ["dashboard", "caddy", "docker-proxy", "docker-control"]) { + assert.doesNotMatch(out, new RegExp(`]*>Restart ${service}\\b`)); + } +}); + +test("the restart confirmation names the service and its dependents before anything is sent", () => { + const panel = inst({ enabled: true }, { restarts: { tor: { phase: "confirm", result: null } } }); + const out = renderToString(panel.renderRestart("tor")); + assert.match(out, /Restart tor\?/); + assert.match(out, /monerod is restarted with it/); + assert.match(out, /Confirm restart of tor/); + assert.match(out, /Cancel/); + const monerod = renderToString( + inst({ enabled: true }, { restarts: { monerod: { phase: "confirm", result: null } } }).renderRestart("monerod"), + ); + assert.match(monerod, /wallet-rpc is interrupted/); +}); + +test("a confirmed restart posts the closed request once, disables the button, and shows success", async () => { + const posts = []; + const fetchStub = async (url, opts) => { + if (url === "/api/control/svc-restart") { + posts.push({ headers: opts.headers, body: restartPost(opts) }); + return { status: 202, ok: false, json: async () => ({ id: ID }) }; + } + return okResult({ status: "applied", container: "tor" }); + }; + const panel = inst(); + const run = withFastPoll(fetchStub, () => panel.runRestart("tor")); + assert.equal(panel.state.restarts.tor.phase, "waiting"); + const waiting = renderToString(panel.renderRestart("tor")); + assert.match(waiting, /disabled/); + assert.match(waiting, /Waiting for the host to restart tor/); + await run; + assert.equal(panel.state.restarts.tor.phase, "done"); + assert.match(renderToString(panel.renderRestart("tor")), /tor was restarted/); + assert.equal(posts.length, 1); + assert.deepEqual(posts[0].body, { container: "tor" }); + assert.equal(posts[0].headers["X-Pithead-Control"], "1"); +}); + +test("a host refusal or failure is shown verbatim as the restart result", async () => { + for (const status of ["rejected", "failed"]) { + const error = `host said no ${status}`; + const fetchStub = async (url) => + url === "/api/control/svc-restart" + ? { status: 202, ok: false, json: async () => ({ id: ID }) } + : okResult({ status, error }); + const panel = inst(); + await withFastPoll(fetchStub, () => panel.runRestart("monerod")); + assert.equal(panel.state.restarts.monerod.phase, "failed"); + assert.ok(renderToString(panel.renderRestart("monerod")).includes(error)); + } +}); + +test("a refused submission on restart is a failed state, not an unhandled rejection", async () => { + const panel = inst(); + await withFastPoll( + async () => ({ status: 500, ok: false, text: async () => "" }), + () => panel.runRestart("p2pool"), + ); + assert.equal(panel.state.restarts.p2pool.phase, "failed"); + assert.match(renderToString(panel.renderRestart("p2pool")), /Could not submit the p2pool restart: HTTP 500/); +}); + +test("the browser restart list has not drifted from the host's restart allowlist", () => { + const pithead = readFileSync(new URL("../../../../pithead", import.meta.url), "utf8"); + const match = /readonly PITHEAD_SVC_RESTART_SERVICES="([^"]*)"/.exec(pithead); + assert.ok(match, "could not find PITHEAD_SVC_RESTART_SERVICES in pithead"); + assert.deepEqual([...DIAG_RESTARTABLE].sort(), match[1].split(/\s+/).filter(Boolean).sort()); +}); diff --git a/dashboard/tests/web/views/test_diagnostics_views.py b/dashboard/tests/web/views/test_diagnostics_views.py index e8c3b2f914..71c3feccf1 100644 --- a/dashboard/tests/web/views/test_diagnostics_views.py +++ b/dashboard/tests/web/views/test_diagnostics_views.py @@ -54,7 +54,11 @@ async def test_both_routes_404_when_the_control_channel_is_off( sm = StateManager(db_path=":memory:") cli = await aiohttp_client(create_app(sm, {})) try: - for path in ("/api/control/diag-doctor", "/api/control/diag-logs"): + for path in ( + "/api/control/diag-doctor", + "/api/control/diag-logs", + "/api/control/svc-restart", + ): resp = await cli.post(path, headers=CONTROL_HEADERS, json={"container": "tor"}) assert resp.status == 404, path finally: @@ -203,3 +207,63 @@ async def test_a_spool_failure_is_a_500_that_names_no_path(self, diag_client, mo ) assert resp.status == 500 assert "nonexistent" not in json.dumps(await resp.json()) + + +class TestSvcRestart: + async def test_requires_the_control_header(self, diag_client, spool): + resp = await diag_client.post("/api/control/svc-restart", json={"container": "tor"}) + assert resp.status == 403 + assert list((spool / "requests").glob("*.json")) == [] + + @pytest.mark.parametrize("body", [b"nope", b"[]", b'"tor"']) + async def test_a_body_that_is_not_a_json_object_is_a_400(self, diag_client, spool, body): + resp = await diag_client.post( + "/api/control/svc-restart", + headers={**CONTROL_HEADERS, "Content-Type": "application/json"}, + data=body, + ) + assert resp.status == 400 + assert list((spool / "requests").glob("*.json")) == [] + + @pytest.mark.parametrize("container", [None, 7, "", "Tor", "tor; reboot", "../x", "a" * 80]) + async def test_a_malformed_service_is_a_400_and_spools_nothing( + self, diag_client, spool, container + ): + resp = await diag_client.post( + "/api/control/svc-restart", headers=CONTROL_HEADERS, json={"container": container} + ) + assert resp.status == 400 + assert list((spool / "requests").glob("*.json")) == [] + + async def test_202_and_spools_a_closed_request(self, diag_client, spool): + resp = await diag_client.post( + "/api/control/svc-restart", + headers={**CONTROL_HEADERS, "X-Auth-User": "admin"}, + json={"container": "monerod", "lines": 5}, + ) + assert resp.status == 202 + body = await resp.json() + assert body["status"] == "pending" + assert spooled(spool) == { + "id": body["id"], + "action": "svc-restart", + "actor": "admin", + "container": "monerod", + } + + async def test_a_wellformed_but_unlisted_service_still_spools_for_the_host_to_refuse( + self, diag_client, spool + ): + resp = await diag_client.post( + "/api/control/svc-restart", headers=CONTROL_HEADERS, json={"container": "caddy"} + ) + assert resp.status == 202 + assert spooled(spool)["container"] == "caddy" + + async def test_a_spool_failure_is_a_500_that_names_no_path(self, diag_client, monkeypatch): + monkeypatch.setattr(request_spool.config, "CONTROL_REQUESTS_DIR", "/nonexistent/requests") + resp = await diag_client.post( + "/api/control/svc-restart", headers=CONTROL_HEADERS, json={"container": "tor"} + ) + assert resp.status == 500 + assert "nonexistent" not in json.dumps(await resp.json()) diff --git a/docs/dashboard.md b/docs/dashboard.md index e19ff94d6d..8adaba2ca5 100644 --- a/docs/dashboard.md +++ b/docs/dashboard.md @@ -1554,9 +1554,10 @@ that is gone from the dashboard, and the host's own `control.log` — which the ### Service diagnostics -Two read-only questions you can ask the host, in the same card stack as the config editor and -under the same `dashboard.control.enabled` flag. Neither changes anything: they run a check and -report, which is why neither asks you to confirm. +Two read-only questions you can ask the host and one recovery action, in the same card stack as +the config editor and under the same `dashboard.control.enabled` flag. The two questions change +nothing: they run a check and report, which is why neither asks you to confirm. The restart does +change the machine and always asks first (see [Restart a service](#restart-a-service)). **Run health check** runs the host's own `pithead doctor` and shows what it found — the same checks the CLI prints, failures first, with the host's summary counts above them. This is the one @@ -1585,6 +1586,25 @@ regenerates a missing hidden service for the Monero node, the Tari node, or the those verdicts ask you to save a change rather than to find a console. P2Pool's is the exception: apply refuses to finish while that one is missing, so no dashboard surface can regenerate it. +#### Restart a service + +Each service card with a restart control has a **Restart** button next to its log: `tor`, +`monerod`, `wallet-rpc`, `tari`, `tari-wallet`, `p2pool` and `xmrig-proxy`. `dashboard`, `caddy`, +`docker-proxy` and `docker-control` have none, and the host refuses them if asked: restarting the +page you are reading or the proxy in front of it would cut off the answer. The button opens a +confirmation naming what else is interrupted (restarting `tor` also restarts `monerod`; restarting +`monerod` interrupts `wallet-rpc`; a wallet pauses its sync and payouts briefly), and sends nothing +until you confirm. The button stays disabled while the host works, then shows the result or the +host's reason for refusing. + +The host decides, not the dashboard. It restarts only a service on its fixed list, with +`docker compose restart ` under the same lock as `apply`, `upgrade` and `backup`. It +refuses, with a reason and without queueing, while another of those operations holds the lock, +while the LAN-only source rule for a published port is not in place, and when the same service was +restarted in the last 120 seconds. Every request is recorded in the control audit log with the +actor, the action `svc-restart`, the service and the outcome (`started`, `rejected`, `applied` or +`failed`). + One thing reads differently here than at a terminal: the report is redacted on its way to the browser, so where `pithead doctor` prints your dashboard's onion address in full, this panel shows it as `[redacted].onion`. That is the only address the redaction changes here. The report names the diff --git a/docs/dev/integration-testing.md b/docs/dev/integration-testing.md index c793fec898..5e5a18b639 100644 --- a/docs/dev/integration-testing.md +++ b/docs/dev/integration-testing.md @@ -247,6 +247,7 @@ Useful flags (full list in `run.sh --help`): | `--candidate-image-key ` | Name the separate externally anchored image-signing public key. This permits an ephemeral test key for the candidate bundle while retaining the project image trust root. | | `--xvb-routing-smoke` | From a known live `xvb.enabled=true`, `xvb.tor=true` baseline with hooked kernel DROP rules, prove the candidate wallet-bearing client in a temporary Tor-only Docker network, then use a strict apply that refuses to start containers unless those rules are installed. Observe the real proxy/dashboard move from P2Pool to XvB and naturally return, then restore exact enabled config, route, worker identities, hashes, and secrets. The isolated fetch proves the candidate client/network leg, not process attribution for the host-network dashboard. Requires `--safety-backup`; no recent PPLNS share is a failure. Every poll is bounded; worst case is about 45 minutes. | | `--auth-fail-closed` | Also empty `PROXY_AUTH_TOKEN` in `.env` and assert `pithead up` refuses to start (the live counterpart to the tier-1 compose-config check, [#153](https://github.com/p2pool-starter-stack/pithead/issues/153)/[#203](https://github.com/p2pool-starter-stack/pithead/issues/203)), then restore the exact token and recover. Token edits keep the temporary and replacement `.env` owner-only (0600), preserve its owner and group, and remove the temporary file on failure. Restore mismatches report no token values. `selftest-auth-fail-closed.sh` covers permissions under a 022 umask and a failed-restore negative control without a live stack. Destructive-then-restored; ssh or local mode. | +| `--svc-restart` | Enable `dashboard.control`, restart `xmrig-proxy` through the control spool and assert the host runner applies it, the stack is healthy afterwards, the container's start time moved and the audit entry names the service; a repeat inside the cooldown and a service outside the allowlist are refused ([#4062](https://github.com/p2pool-starter-stack/pithead/issues/4062)). Local mode only; restores the baseline and removes the control units. | | `--rotate-onion` | Also run `rotate-dashboard-onion` on a reserved non-production fixture ([#2345](https://github.com/p2pool-starter-stack/pithead/issues/2345)). After the safety backup, `e2e.sh` creates a one-run Tor data directory and uses `pithead render` followed by the normal `rotate-dashboard-onion` path to mint and persist fresh dashboard, client-auth, and mining identities there after capturing the baseline chain snapshot and before deploying consumer containers; a provisioning failure refuses deployment. The bootstrap render explicitly adopts the reserved host's control and firewall units, as the following upgrade does; baseline restoration converges their original owner afterward. It binds the harness to that exact directory with a root-owned marker outside the mount, then removes the fixture and its credential snapshot after baseline convergence detaches its container mounts; no live identity is copied, and `--keep` is refused. The phase rotates the fixture again, then proves the new address answers over the real Tor network, the retired address becomes unreachable with its original key after a bounded transition, every fixture mining key stays unchanged, the Caddyfile names only the new vhost ([#546](https://github.com/p2pool-starter-stack/pithead/issues/546)'s regression), and `HOST_IP` survives the render ([#356](https://github.com/p2pool-starter-stack/pithead/issues/356)'s regression). Destructive-then-restored: keeps the client credential in a fingerprinted, owner-only file outside container mounts, swaps the saved Tor hidden-service key files back into place, verifies their fingerprints and hostname, renders the old address into the derived files, and proves it externally reachable again; the run-level EXIT restore does the same after a failed or interrupted phase. The wrapper retains the fixture and fails cleanup if either recovery copy remains after phase restoration. A missing, invalid, or unreachable fixture fails instead of skipping. | | `--rigforge-control` | Also drive the RigForge WRITE paths against a real rig with `dashboard.control` on and the rig pinned in `workers.list[]` (#506; the deprecated `dashboard.workers[]` fallback was removed in 2.0.0 (#1832), so a baseline still carrying that key is migrated to `workers.list[]` before the legs run): the enriched read survives a populated masked-token descriptor ([#514](https://github.com/p2pool-starter-stack/pithead/issues/514)), the rig is editable and a reversible Worker Inspect edit lands on it on four of the six writable keys — `max_temp_c` ([#508](https://github.com/p2pool-starter-stack/pithead/issues/508)/[#513](https://github.com/p2pool-starter-stack/pithead/issues/513)), `DONATION` and `watchdog_interval_min` ([#1236](https://github.com/p2pool-starter-stack/pithead/issues/1236)), and `pools` (needs `IT_RIG_POOLS_PROBE`, and leaves the rig on it); `autotune` and `watchdog` are refused on purpose — a rig-side edit reflects back in the feed + masked prefill ([#516](https://github.com/p2pool-starter-stack/pithead/issues/516)), and an auto-rollback is recorded end-to-end ([#517](https://github.com/p2pool-starter-stack/pithead/issues/517)). Destructive-then-restored; local mode only; each leg self-skips without its prerequisites (see below). A failed phase stops every later requested phase, and the summary lists each of them under "did NOT run". | | `--rig-host ` / `--rig-control-port

    ` | The borrowed rig's LAN host and writable control API port (default `8082`), used to inject a `workers.list[]` descriptor when the box's baseline lacks one ([#185](https://github.com/p2pool-starter-stack/pithead/issues/185)/#506). Pair with `IT_RIG_TOKEN` (env; never a flag). | @@ -576,13 +577,13 @@ via an `EXIT` trap): `--mode`: `targeted` (default, lean) validates the dashboard and the sync logic against the already-synced node: `check` + `--lifecycle` (one controlled restart exercises the sync gate / -node-down failover) + `--auth-fail-closed`, plus `--rigforge` and `--rigforge-control` when a rig is +node-down failover) + `--auth-fail-closed` + `--svc-restart`, plus `--rigforge` and `--rigforge-control` when a rig is borrowed. No full config sweep, and never a re-sync. Container restarts reload the existing chain; monerod re-confirms the tip in seconds, but a recreated tari also has to rebuild its Tor circuits first, which can take upward of 20 minutes ([#2455](https://github.com/p2pool-starter-stack/pithead/issues/2455)) — `deploy_branch` waits on that before running the harness, since the harness reads the Tari panel once. `check` is pure reads only. `matrix` is the opt-in full destructive -config sweep (lifecycle + fault-injection + auth-fail-closed + hardening + `--subnet`, plus the same +config sweep (lifecycle + fault-injection + auth-fail-closed + svc-restart + hardening + `--subnet`, plus the same two rig phases, all under `--safety-backup` auto-rollback) for a pre-release tier-4 gate. The rig phases are gated on a borrowed miner rather than on the mode: the release runbook mandates `targeted`, so keeping the write paths matrix-only left them out of the gate that decides whether a @@ -598,7 +599,7 @@ you did not ask for cannot fail and skip one you did. The mode's scenario, the rig identity, the pregate and the restore still run. `--scenario ` alone only changes the scenario; it keeps the mode's and borrowed rig's phases. Only an allowlisted `run.sh` phase flag is accepted — `--lifecycle`, `--fault-injection`, `--fault-injection-ssh`, `--auth-fail-closed`, -`--hardening`, `--rotate-onion`, `--subnet`, `--safety-backup`, `--rigforge`, `--rigforge-control`, +`--svc-restart`, `--hardening`, `--rotate-onion`, `--subnet`, `--safety-backup`, `--rigforge`, `--rigforge-control`, `--xvb-routing-smoke`, `--rotate-secrets`, `--sweep`, or `--scenario ` as two `--harness-arg` (the flag, then the name) — and anything else is refused before any bench work, never built into a shell string from the raw value. Not supported with `--mode check`, which runs nothing but `--check` by design. `--rotate-secrets` diff --git a/docs/operations.md b/docs/operations.md index b36e7566a9..1efd4080c2 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -48,6 +48,12 @@ show that the control runner is stuck. The `wallet-rpc` and `tari-wallet` checks but their logs stay in the owner-only support bundle because their ordinary output can carry wallet material the browser log redactor cannot safely recognize. +Each service card with a **Restart** button (`tor`, `monerod`, `wallet-rpc`, `tari`, `tari-wallet`, +`p2pool`, `xmrig-proxy`) restarts only that service after a confirmation that names what else is +interrupted. The host refuses while another pithead operation holds the lock, while the LAN-only +source rule is not in place, and within 120 seconds of the last restart of the same service; see +[Restart a service](dashboard.md#restart-a-service). + ### Appliance-only commands These exist on every install but only do something on [the appliance image](appliance.md), where the diff --git a/lib/pithead/42-control-approval-helpers.sh b/lib/pithead/42-control-approval-helpers.sh index 7ee3e71c82..cbb92f5e65 100644 --- a/lib/pithead/42-control-approval-helpers.sh +++ b/lib/pithead/42-control-approval-helpers.sh @@ -342,6 +342,6 @@ control_audit() { # [keys] [approver "$(printf '%s' "$3" | tr -cd 'A-Za-z0-9._@-')" \ "$(printf '%s' "$4" | tr -cd 'a-z-')" \ "$(printf '%s' "$5" | tr -cd 'a-z-')" \ - "$(printf '%s' "${6:-}" | tr -cd 'A-Za-z0-9._ ')" \ + "$(printf '%s' "${6:-}" | tr -cd 'A-Za-z0-9._ -')" \ "$(printf '%s' "${7:-}" | tr -cd 'A-Za-z0-9._@-')" >>"$1" } diff --git a/lib/pithead/46c-control-svc-restart.sh b/lib/pithead/46c-control-svc-restart.sh new file mode 100644 index 0000000000..628bfc0aac --- /dev/null +++ b/lib/pithead/46c-control-svc-restart.sh @@ -0,0 +1,57 @@ +readonly PITHEAD_SVC_RESTART_SERVICES="tor monerod wallet-rpc tari tari-wallet p2pool xmrig-proxy" +readonly PITHEAD_SVC_RESTART_COOLDOWN_S=120 +readonly PITHEAD_SVC_RESTART_EX_GUARD=11 +readonly PITHEAD_SVC_RESTART_EX_COOLDOWN=12 + +control_svc_restart_locked() ( + local cdir="$1" service="$2" logf="$3" stamp last now + stamp="$cdir/svc-restart-$service" + PITHEAD_LOCK_TIMEOUT=0 mutation_lock_acquire svc-restart + lan_guard_ready || exit "$PITHEAD_SVC_RESTART_EX_GUARD" + now=$(date +%s) + last=0 + [ -f "$stamp" ] && [ ! -L "$stamp" ] && read -r last <"$stamp" || true + [[ "$last" =~ ^[0-9]+$ ]] || last=0 + [ $((now - last)) -ge "$PITHEAD_SVC_RESTART_COOLDOWN_S" ] || exit "$PITHEAD_SVC_RESTART_EX_COOLDOWN" + docker compose restart "$service" >"$logf" 2>&1 || exit 1 + printf '%s\n' "$now" >"$stamp" +) + +control_svc_restart() { + local file="$1" id="$2" actor="$3" cdir="$4" + local results="$cdir/results" auditf="$cdir/audit/control.log" + local service found=0 c rc=0 logf="$cdir/staged/.$id.log" error + service=$(jq -r 'if (.container | type) == "string" then .container else "" end' "$file") + for c in $PITHEAD_SVC_RESTART_SERVICES; do + [ "$service" = "$c" ] && found=1 && break + done + if [ "$found" -ne 1 ] || [ "$(jq -r 'keys | sort == ["action","actor","container","id"]' "$file")" != true ]; then + control_write_result "$results" "$id" "$(jq -n '{status:"rejected",action:"svc-restart",error:"not a service this dashboard may restart.",ts:(now|floor)}')" + control_audit "$auditf" "$id" "$actor" "svc-restart" "rejected" + return 0 + fi + control_audit "$auditf" "$id" "$actor" "svc-restart" "started" "$service" + mkdir -p "$cdir/staged" + control_svc_restart_locked "$cdir" "$service" "$logf" || rc=$? + case "$rc" in + 0) + control_write_result "$results" "$id" "$(jq -n --arg s "$service" '{status:"applied",action:"svc-restart",container:$s,ts:(now|floor)}')" + control_audit "$auditf" "$id" "$actor" "svc-restart" "applied" "$service" + rm -f "$logf" + return 0 + ;; + "$PITHEAD_EX_LOCK_TIMEOUT") error="Another pithead operation is in progress; try again when it has finished." ;; + "$PITHEAD_SVC_RESTART_EX_GUARD") error="The LAN-only source rule for the published ports is not in place, so a restart is refused. Run './pithead up' on the host." ;; + "$PITHEAD_SVC_RESTART_EX_COOLDOWN") error="$service was restarted less than ${PITHEAD_SVC_RESTART_COOLDOWN_S}s ago; wait before restarting it again." ;; + *) + error="The restart of $service failed on the host: $(tail -c 1500 "$logf" 2>/dev/null | bundle_redact_log)" + control_write_result "$results" "$id" "$(jq -n --arg s "$service" --arg e "$error" '{status:"failed",action:"svc-restart",container:$s,error:$e,ts:(now|floor)}')" + control_audit "$auditf" "$id" "$actor" "svc-restart" "failed" "$service" + rm -f "$logf" + return 0 + ;; + esac + control_write_result "$results" "$id" "$(jq -n --arg s "$service" --arg e "$error" '{status:"rejected",action:"svc-restart",container:$s,error:$e,ts:(now|floor)}')" + control_audit "$auditf" "$id" "$actor" "svc-restart" "rejected" "$service" + rm -f "$logf" +} diff --git a/lib/pithead/49-control-request-loop.sh b/lib/pithead/49-control-request-loop.sh index 7c7feb1527..86d4f151fd 100644 --- a/lib/pithead/49-control-request-loop.sh +++ b/lib/pithead/49-control-request-loop.sh @@ -139,14 +139,10 @@ control_process_request() { # os-verify) control_os_verify "$file" "$id" "$actor" "$cdir" ;; os-install) control_os_install "$file" "$id" "$actor" "$cdir" ;; os-reboot) control_os_reboot "$file" "$id" "$actor" "$cdir" ;; - # Read-only diagnostics for a shell-less appliance operator: report, never mutate. Both are - # bounded host-side and the log tail is redacted by bundle_redact_log before it is written. diag-doctor) control_diag_doctor "$id" "$actor" "$cdir" ;; diag-logs) control_diag_logs "$file" "$id" "$actor" "$cdir" ;; + svc-restart) control_svc_restart "$file" "$id" "$actor" "$cdir" ;; support-bundle) control_support_bundle "$file" "$id" "$actor" "$cdir" ;; - # Also read-only, and the one that hands back a SECRET rather than a report (#1882): the Tor - # client-auth line without which a client-auth'd dashboard onion cannot be opened at all. It is - # a one-time kit with the backup kit's TTL and redaction, and every reveal lands in audit/. onion-client-key) control_onion_client_key "$id" "$actor" "$cdir" ;; *) control_write_result "$cdir/results" "$id" "$(jq -n '{status:"rejected",error:"unknown action",ts:(now|floor)}')" diff --git a/tests/integration/e2e.sh b/tests/integration/e2e.sh index 582cf134f3..68197138aa 100755 --- a/tests/integration/e2e.sh +++ b/tests/integration/e2e.sh @@ -600,20 +600,16 @@ run_harness() { [ "$MODE" = "check" ] && target_dir="$RESTORE_DIR" case "$MODE" in check) phases="--check" ;; - targeted) phases="${TARGETED_SCENARIO_ARGS---scenario local-pruned-main-secure-tari}${HARNESS_PHASE_ARGS:- --auth-fail-closed --lifecycle}" ;; # readiness/check run inline first (below); NOT here — run.sh returns after --readiness - matrix) phases="${SCENARIO:+--scenario $(quote_arg "$SCENARIO")}${HARNESS_PHASE_ARGS:- --safety-backup --lifecycle --reset-dashboard --fault-injection --auth-fail-closed --hardening --subnet}" ;; + targeted) phases="${TARGETED_SCENARIO_ARGS---scenario local-pruned-main-secure-tari}${HARNESS_PHASE_ARGS:- --auth-fail-closed --lifecycle --svc-restart}" ;; + matrix) phases="${SCENARIO:+--scenario $(quote_arg "$SCENARIO")}${HARNESS_PHASE_ARGS:- --safety-backup --lifecycle --reset-dashboard --fault-injection --auth-fail-closed --svc-restart --hardening --subnet}" ;; esac [ "${#REMOTE_NODE_ARGS[@]}" -eq 0 ] || printf -v remote_args ' %q' "${REMOTE_NODE_ARGS[@]}" - # RigForge read (#185/#235/#260) + the WRITE paths (#513/#514/#516/#517/#1002b/#1236): both need a - # REAL rig, both self-skip loudly without one. The write half was matrix-only until #1364. rig_supply if [ "$BORROW_MINER" = "1" ] && [ "$MODE" != "check" ]; then rig_supply [ -n "$RIG_NAME" ] || die "Borrowed rig NAME unavailable from $RIGFORGE_CONFIG." - [ -n "${HARNESS_PHASE_ARGS:-}" ] || phases="$phases --rigforge --rigforge-control" # hand-picked phases replace these too (bench-ci#878) + [ -n "${HARNESS_PHASE_ARGS:-}" ] || phases="$phases --rigforge --rigforge-control" phases="$phases --rig-name $(quote_arg "$RIG_NAME")${RIG_HOST:+ --rig-host $(quote_arg "$RIG_HOST") --rig-control-port $(quote_arg "$RIG_CONTROL_PORT")}${RIGFORGE_BOOTSTRAP_VERSION:+ --rigforge-bootstrap-version $(quote_arg "$RIGFORGE_BOOTSTRAP_VERSION")}" fi - # #905: no borrowed miner means no worker will ever appear — tell the harness to SKIP its two - # mining assertions (workers online, stratum hashes) instead of failing a healthy stack. local no_mining="" [ "$BORROW_MINER" = "1" ] || no_mining="--no-mining-asserts" phases="$phases${HARNESS_SCENARIO_ARGS:-}$remote_args $no_mining" diff --git a/tests/integration/lib/harness-args.sh b/tests/integration/lib/harness-args.sh index a71ba7c0f0..a6a8520498 100644 --- a/tests/integration/lib/harness-args.sh +++ b/tests/integration/lib/harness-args.sh @@ -16,7 +16,7 @@ validate_harness_args() { # reads HARNESS_ARGS[]; sets HARNESS_PHASE_ARGS, HARNE while [ "$i" -lt "${#HARNESS_ARGS[@]}" ]; do arg="${HARNESS_ARGS[$i]}" case "$arg" in - --lifecycle | --reset-dashboard | --fault-injection | --fault-injection-ssh | --auth-fail-closed | --hardening | --rotate-onion | --subnet | --safety-backup | --rigforge | --rigforge-control | --xvb-routing-smoke | --rotate-secrets | --alert-egress | --mergemine-submit | --mergemine-localnet | --tari-stranded | --monero-stranded | --sweep) + --lifecycle | --reset-dashboard | --fault-injection | --fault-injection-ssh | --auth-fail-closed | --svc-restart | --hardening | --rotate-onion | --subnet | --safety-backup | --rigforge | --rigforge-control | --xvb-routing-smoke | --rotate-secrets | --alert-egress | --mergemine-submit | --mergemine-localnet | --tari-stranded | --monero-stranded | --sweep) HARNESS_PHASE_ARGS="$HARNESS_PHASE_ARGS $arg" if [ "$arg" = --rotate-onion ]; then [ "${KEEP:-0}" != 1 ] || die "--rotate-onion cannot be combined with --keep; its isolated identity must be removed." @@ -31,7 +31,7 @@ validate_harness_args() { # reads HARNESS_ARGS[]; sets HARNESS_PHASE_ARGS, HARNE i=$((i + 2)) ;; *) - die "--harness-arg does not accept '$arg' — allowed: --lifecycle, --reset-dashboard, --fault-injection, --fault-injection-ssh, --auth-fail-closed, --hardening, --rotate-onion, --subnet, --safety-backup, --rigforge, --rigforge-control, --xvb-routing-smoke, --rotate-secrets, --alert-egress, --mergemine-submit, --mergemine-localnet, --tari-stranded, --monero-stranded, --sweep, --scenario ." + die "--harness-arg does not accept '$arg' — allowed: --lifecycle, --reset-dashboard, --fault-injection, --fault-injection-ssh, --auth-fail-closed, --svc-restart, --hardening, --rotate-onion, --subnet, --safety-backup, --rigforge, --rigforge-control, --xvb-routing-smoke, --rotate-secrets, --alert-egress, --mergemine-submit, --mergemine-localnet, --tari-stranded, --monero-stranded, --sweep, --scenario ." ;; esac done diff --git a/tests/integration/lib/run-cli.sh b/tests/integration/lib/run-cli.sh index df44c5b051..c4e306caf9 100644 --- a/tests/integration/lib/run-cli.sh +++ b/tests/integration/lib/run-cli.sh @@ -180,6 +180,10 @@ parse_args() { RUN_AUTH_FAIL_CLOSED=1 shift ;; + --svc-restart) + RUN_SVC_RESTART=1 + shift + ;; --hardening) RUN_HARDENING=1 shift diff --git a/tests/integration/lib/run-svc-restart.sh b/tests/integration/lib/run-svc-restart.sh new file mode 100644 index 0000000000..4d90bb8694 --- /dev/null +++ b/tests/integration/lib/run-svc-restart.sh @@ -0,0 +1,70 @@ +# shellcheck shell=bash +: "${INTEGRATION_RUN_SUITE:?source via the suite runner}" + +_svc_restart_request() { + local cdir="$1" service="$2" id + id="$(_uuid4)" + _spool_write "$cdir/requests/$id.json" \ + "$(jq -nc --arg id "$id" --arg s "$service" '{id:$id,action:"svc-restart",actor:"itest",container:$s}')" + SVC_RESTART_ID="$id" + SVC_RESTART_STATUS="$(_wait_control_status "$cdir" "$id" "" 120 || echo timeout)" +} + +run_svc_restart() { + # shellcheck disable=SC2034 + IT_CURRENT_SCENARIO="svc-restart" + echo "" + it_log "── per-service restart phase (#4062) ────────────" + + if ! has_compose_profile "$(env_on_box COMPOSE_PROFILES)" local_node; then + it_skip_phase "svc-restart" "remote mode: no local containers/systemd to exercise" "by-design" + return 0 + fi + + local ctrl_config cdir + ctrl_config="$(printf '%s' "$BASELINE_CONFIG" | jq '.dashboard.secure=true | .dashboard.auth={username:"admin",password:"a tier4 control passphrase"} | .dashboard.control={enabled:true}')" + push_config "$ctrl_config" + it_step "apply with dashboard.control enabled (installs the systemd path unit)…" + pithead apply -y >"$OUT_DIR/svc-restart.apply.log" 2>&1 || true + wait_status_ok 180 || true + cdir="$(env_on_box CONTROL_DIR)" + + if [ -z "$cdir" ] || ! rx "systemctl is-enabled pithead-control.path >/dev/null 2>&1"; then + it_fail "control runner is installed for the svc-restart phase (#4062)" "CONTROL_DIR unset or pithead-control.path not enabled; see $OUT_DIR/svc-restart.apply.log" + else + local started_before started_after + started_before="$(rx 'docker inspect xmrig-proxy --format "{{.State.StartedAt}}"' 2>/dev/null)" + it_step "svc-restart xmrig-proxy through the control spool…" + _svc_restart_request "$cdir" xmrig-proxy + assert_eq "svc-restart of xmrig-proxy applied by the host runner (#4062)" "$SVC_RESTART_STATUS" "applied" + wait_status_ok 240 || true + pithead status >/dev/null 2>&1 + assert_rc "stack healthy after a svc-restart of xmrig-proxy (#4062)" "$?" "0" + started_after="$(rx 'docker inspect xmrig-proxy --format "{{.State.StartedAt}}"' 2>/dev/null)" + if [ -n "$started_before" ] && [ -n "$started_after" ] && [ "$started_before" != "$started_after" ]; then + it_pass "xmrig-proxy was really restarted: its container start time moved (#4062)" + else + it_fail "xmrig-proxy was really restarted: its container start time moved (#4062)" "StartedAt before=[$started_before] after=[$started_after]" + fi + assert_contains "svc-restart is audited with the service (#4062)" \ + "$(rx "cat $(quote_arg "$cdir/audit/control.log") 2>/dev/null")" '"action":"svc-restart","status":"applied","keys":"xmrig-proxy"' + + _svc_restart_request "$cdir" xmrig-proxy + assert_eq "a repeat svc-restart inside the cooldown is rejected (#4062)" "$SVC_RESTART_STATUS" "rejected" + assert_contains "the cooldown refusal says why (#4062)" \ + "$(rx "jq -r '.error // empty' $(quote_arg "$cdir/results/$SVC_RESTART_ID.json") 2>/dev/null")" "wait before restarting it again" + + _svc_restart_request "$cdir" caddy + assert_eq "svc-restart of a service outside the allowlist is rejected (#4062)" "$SVC_RESTART_STATUS" "rejected" + fi + + it_step "restoring baseline (disables control, removes the path unit)…" + push_config "$BASELINE_CONFIG" + pithead apply -y >/dev/null 2>&1 + wait_status_ok 240 || true + if _remove_control_units; then + it_pass "control systemd units removed after the svc-restart phase (#4062)" + else + it_warn "pithead-control units survived teardown — remove them by hand on the box (sudo unavailable?)" + fi +} diff --git a/tests/integration/lib/run-usage.sh b/tests/integration/lib/run-usage.sh index 6aeef24d11..03c0284229 100644 --- a/tests/integration/lib/run-usage.sh +++ b/tests/integration/lib/run-usage.sh @@ -91,6 +91,9 @@ MATRIX: in .env and assert `pithead up` REFUSES to start (the live counterpart to the tier-1 compose-config check), then restore the exact token and recover. DESTRUCTIVE-then-restored; works in both ssh and local mode. + --svc-restart local-only: enable control, restart xmrig-proxy through the control spool, + assert applied + healthy + a moved container start time + the audit entry, + the cooldown refusal and the allowlist refusal (#4062). DESTRUCTIVE-then-restored. --hardening local-only: rootfs write refusal, control path-unit apply/refusal, Tor recovery. DESTRUCTIVE-then-restored; enables then disables control (#377/#33/#424). --rotate-onion rotate an isolated onion fixture; prove reachability, retirement and restore (#2345). diff --git a/tests/integration/mini-stack/control-roundtrip.sh b/tests/integration/mini-stack/control-roundtrip.sh index a413c3645d..04e3fc5713 100644 --- a/tests/integration/mini-stack/control-roundtrip.sh +++ b/tests/integration/mini-stack/control-roundtrip.sh @@ -161,3 +161,36 @@ assert_payout_control_roundtrip() { c_bad "the dashboard reads the host-applied payout address back" "readback did not match" fi } + +assert_svc_restart_control_roundtrip() { + local response + chmod 755 "$C/data/control" "$C/data/control/results" + chmod 733 "$C/data/control/requests" + : >"$CTRL_LOG" + if ! dashboard_control_request svc-restart '{"container":"tor"}'; then + c_bad "a service restart reaches the host runner" "dashboard or host runner failed; response=$(head -c 300 "$CONTROL_RESPONSE"); runner=$(tail -n 8 "$SANDBOX/control-runner.log" 2>/dev/null | tr '\n' '|')" + return + fi + response=$(cat "$CONTROL_RESPONSE") + if printf '%s' "$response" | jq -e '.status == "applied" and .container == "tor"' >/dev/null && + grep -qxF '[docker] compose restart tor' "$CTRL_LOG"; then + c_ok "the dashboard's svc-restart request restarts exactly the named service on the host" + else + c_bad "the dashboard's svc-restart request restarts exactly the named service on the host" \ + "status=$(printf '%s' "$response" | jq -r '.status // "missing"')" + fi + + : >"$CTRL_LOG" + if ! dashboard_control_request svc-restart '{"container":"caddy"}'; then + c_bad "a refused service restart still returns the host's verdict" "dashboard or host runner failed" + return + fi + response=$(cat "$CONTROL_RESPONSE") + if printf '%s' "$response" | jq -e '.status == "rejected"' >/dev/null && + ! grep -q 'compose restart' "$CTRL_LOG"; then + c_ok "the host refuses a service outside the restart allowlist without touching docker" + else + c_bad "the host refuses a service outside the restart allowlist without touching docker" \ + "status=$(printf '%s' "$response" | jq -r '.status // "missing"')" + fi +} diff --git a/tests/integration/mini-stack/run-mini-stack.sh b/tests/integration/mini-stack/run-mini-stack.sh index 28740e8f68..da55d616b2 100755 --- a/tests/integration/mini-stack/run-mini-stack.sh +++ b/tests/integration/mini-stack/run-mini-stack.sh @@ -174,14 +174,9 @@ compose up -d >/dev/null 2>&1 log "waiting for the dashboard API" wait_dashboard_api && c_ok "dashboard API is up" || c_bad "dashboard API is up" "no /api/state after ~60s" -assert_payout_control_roundtrip # 0a. payout address approval crosses the dashboard/host boundary (#1959) - -# 0. The /api/state payload must carry the #170 Stack Topology & Egress contract, derived live -# from config by the REAL dashboard. The pure derivation is unit-tested (tests/service/ -# test_egress.py); this proves it survives the trip through build_state -> /api/state on a -# running server: both sections present, their summary shared verbatim with the map (so the -# header badge can't disagree with it), the topology's node set is the canonical one, and every -# edge lands on a placeable node (an off-map endpoint would vanish silently from the diagram). +assert_payout_control_roundtrip +assert_svc_restart_control_roundtrip + log "scenario 0: /api/state exposes a well-formed #170 topology + egress contract" contract="$( compose exec -T dashboard python3 - <<'PY' 2>&1 diff --git a/tests/integration/run.sh b/tests/integration/run.sh index a33bd06e3a..cff35cbcb6 100755 --- a/tests/integration/run.sh +++ b/tests/integration/run.sh @@ -58,6 +58,7 @@ RUN_FAULTS=0 FAULT_SSH=0 FAULT_SSH_DEST="" RUN_AUTH_FAIL_CLOSED=0 +RUN_SVC_RESTART=0 RUN_HARDENING=0 RUN_ROTATE_ONION=0 RUN_RIGFORGE=0 @@ -147,6 +148,8 @@ source "$HERE/lib/run-pool-peer-loss.sh" || exit $? source "$HERE/lib/run-egress-status.sh" || exit $? # shellcheck source=tests/integration/lib/run-hardening.sh source "$HERE/lib/run-hardening.sh" || exit $? +# shellcheck source=tests/integration/lib/run-svc-restart.sh +source "$HERE/lib/run-svc-restart.sh" || exit $? # shellcheck source=tests/integration/lib/run-rotate-onion.sh source "$HERE/lib/run-rotate-onion.sh" || exit $? # shellcheck source=tests/integration/lib/run-safety.sh @@ -275,10 +278,8 @@ main() { fi local lifecycle_ok=1 _gated LIFECYCLE_STACK_INTACT=0 - # A failed rigforge-control leaves the borrowed rig off its baseline, so no later phase runs; - # name every requested one in the summary instead of dropping it silently (#2755). if [ "$rig_control_ok" != 1 ]; then - for _gated in LIFECYCLE:lifecycle RESET_DASHBOARD:reset-dashboard ROTATE_SECRETS:rotate-secrets FAULTS:fault-injection AUTH_FAIL_CLOSED:auth-fail-closed HARDENING:hardening \ + for _gated in LIFECYCLE:lifecycle RESET_DASHBOARD:reset-dashboard ROTATE_SECRETS:rotate-secrets FAULTS:fault-injection AUTH_FAIL_CLOSED:auth-fail-closed SVC_RESTART:svc-restart HARDENING:hardening \ XVB_ROUTING:xvb-routing ALERT_EGRESS:alert-egress MERGEMINE_SUBMIT:mergemine-submit \ MERGEMINE_LOCALNET:mergemine-localnet SUBNET:subnet; do local _flag="RUN_${_gated%%:*}" @@ -301,6 +302,7 @@ main() { [ "$rig_control_ok" = 1 ] && [ "$RUN_RESET_DASHBOARD" = "1" ] && run_reset_dashboard [ "$rig_control_ok" = 1 ] && [ "$RUN_ROTATE_SECRETS" = "1" ] && run_rotate_secrets [ "$rig_control_ok" = 1 ] && [ "$RUN_AUTH_FAIL_CLOSED" = "1" ] && run_auth_fail_closed + [ "$rig_control_ok" = 1 ] && [ "$RUN_SVC_RESTART" = "1" ] && run_svc_restart [ "$rig_control_ok" = 1 ] && [ "$RUN_HARDENING" = "1" ] && run_hardening [ "$rig_control_ok" = 1 ] && [ "$RUN_ROTATE_ONION" = "1" ] && run_rotate_onion [ "$rig_control_ok" = 1 ] && [ "$RUN_XVB_ROUTING" = "1" ] && run_xvb_routing_smoke diff --git a/tests/integration/selftest/selftest-e2e-phases.sh b/tests/integration/selftest/selftest-e2e-phases.sh index 5e1a7aea91..5f42ae08d4 100755 --- a/tests/integration/selftest/selftest-e2e-phases.sh +++ b/tests/integration/selftest/selftest-e2e-phases.sh @@ -130,7 +130,7 @@ assert_eq "targeted requests the rigforge-control WRITE phase (#1364)" \ "$(has_phase "$TARGETED" --rigforge-control)" "yes" assert_eq "targeted launches EXACTLY its documented phases, and nothing else" \ "$(phase_set "$TARGETED")" \ - "--auth-fail-closed --lifecycle --rig-control-port --rig-host --rig-name --rigforge --rigforge-control --scenario 8082 local-pruned-main-secure-tari rig1 rig1 " + "--auth-fail-closed --lifecycle --rig-control-port --rig-host --rig-name --rigforge --rigforge-control --scenario --svc-restart 8082 local-pruned-main-secure-tari rig1 rig1 " echo "== --mode matrix keeps everything it had ==" MATRIX="$(compose_phases matrix 1)" @@ -138,11 +138,11 @@ assert_eq "matrix still requests the rigforge-control WRITE phase" \ "$(has_phase "$MATRIX" --rigforge-control)" "yes" assert_eq "matrix launches EXACTLY its documented phases, and nothing else" \ "$(phase_set "$MATRIX")" \ - "--auth-fail-closed --fault-injection --hardening --lifecycle --reset-dashboard --rig-control-port --rig-host --rig-name --rigforge --rigforge-control --safety-backup --subnet 8082 rig1 rig1 " + "--auth-fail-closed --fault-injection --hardening --lifecycle --reset-dashboard --rig-control-port --rig-host --rig-name --rigforge --rigforge-control --safety-backup --subnet --svc-restart 8082 rig1 rig1 " FOCUSED_MATRIX="$(compose_phases matrix 1 s3cr3t-tok3n local-pruned-main-secure-tari v1.17.2)" assert_eq "matrix accepts one scenario and explicit bootstrap target without dropping its phases" \ "$(phase_set "$FOCUSED_MATRIX")" \ - "--auth-fail-closed --fault-injection --hardening --lifecycle --reset-dashboard --rig-control-port --rig-host --rig-name --rigforge --rigforge-bootstrap-version --rigforge-control --safety-backup --scenario --subnet 8082 local-pruned-main-secure-tari rig1 rig1 v1.17.2 " + "--auth-fail-closed --fault-injection --hardening --lifecycle --reset-dashboard --rig-control-port --rig-host --rig-name --rigforge --rigforge-bootstrap-version --rigforge-control --safety-backup --scenario --subnet --svc-restart 8082 local-pruned-main-secure-tari rig1 rig1 v1.17.2 " echo "== --mode check stays non-destructive (pure reads) ==" CHECK="$(compose_phases check 1)" @@ -170,9 +170,9 @@ NOMINER="$(compose_phases targeted 0)" assert_eq "no borrowed miner => no write phase (there is no rig to write to)" \ "$(has_phase "$NOMINER" --rigforge-control)" "no" assert_eq "no borrowed miner => EXACTLY the rig-free phases, plus --no-mining-asserts (#905)" \ - "$(phase_set "$NOMINER")" "--auth-fail-closed --lifecycle --no-mining-asserts --scenario local-pruned-main-secure-tari " + "$(phase_set "$NOMINER")" "--auth-fail-closed --lifecycle --no-mining-asserts --scenario --svc-restart local-pruned-main-secure-tari " -contains() { # -> "yes" | "no" +contains() { case "$1" in *"$2"*) echo yes ;; *) echo no ;; esac } diff --git a/tests/integration/selftest/selftest-e2e-sweep.sh b/tests/integration/selftest/selftest-e2e-sweep.sh index 0e31c3d659..507441f88d 100644 --- a/tests/integration/selftest/selftest-e2e-sweep.sh +++ b/tests/integration/selftest/selftest-e2e-sweep.sh @@ -87,11 +87,11 @@ assert_eq "--mode matrix with the token is the same sweep" \ echo "== nothing else changes ==" assert_eq "targeted without the token still pins its scenario and runs its preset" \ - "$(phases_of targeted 0 '')" "--scenario local-pruned-main-secure-tari --auth-fail-closed --lifecycle --no-mining-asserts" + "$(phases_of targeted 0 '')" "--scenario local-pruned-main-secure-tari --auth-fail-closed --lifecycle --svc-restart --no-mining-asserts" assert_eq "a hand-picked targeted phase still keeps the preset's scenario" \ "$(phases_of targeted 0 '' --hardening)" "--scenario local-pruned-main-secure-tari --hardening --no-mining-asserts" assert_eq "--mode matrix still means the sweep plus the destructive phases" \ - "$(phases_of matrix 0 '')" " --safety-backup --lifecycle --reset-dashboard --fault-injection --auth-fail-closed --hardening --subnet --no-mining-asserts" + "$(phases_of matrix 0 '')" " --safety-backup --lifecycle --reset-dashboard --fault-injection --auth-fail-closed --svc-restart --hardening --subnet --no-mining-asserts" echo "== a single scenario contradicts the sweep and is refused before any bench work ==" assert_contains "--harness-arg --scenario with the token" \ diff --git a/tests/integration/selftest/selftest-lifecycle-restore-health.sh b/tests/integration/selftest/selftest-lifecycle-restore-health.sh index 9edeefcb11..33912769f2 100644 --- a/tests/integration/selftest/selftest-lifecycle-restore-health.sh +++ b/tests/integration/selftest/selftest-lifecycle-restore-health.sh @@ -268,10 +268,10 @@ fi MAIN_SRC="$(sed -n '/^ local lifecycle_ok=1 _gated$/,/^ fi # fault-injection gate$/p' "$HERE/../run.sh")" assert_contains "the extracted gate includes lifecycle and fault injection" "$MAIN_SRC" "run_fault_injection" -drive_gate() { # [rig-control-ok] -> fault-ran +drive_gate() { ( # shellcheck disable=SC2034 # read by the extracted run.sh gate via eval - RUN_LIFECYCLE=1 RUN_RESET_DASHBOARD=0 RUN_ROTATE_SECRETS=1 RUN_FAULTS=1 RUN_AUTH_FAIL_CLOSED=0 RUN_HARDENING=0 RUN_XVB_ROUTING=0 RUN_ALERT_EGRESS=0 \ + RUN_LIFECYCLE=1 RUN_RESET_DASHBOARD=0 RUN_ROTATE_SECRETS=1 RUN_FAULTS=1 RUN_AUTH_FAIL_CLOSED=0 RUN_SVC_RESTART=0 RUN_HARDENING=0 RUN_XVB_ROUTING=0 RUN_ALERT_EGRESS=0 \ RUN_MERGEMINE_SUBMIT=0 RUN_MERGEMINE_LOCALNET=0 RUN_SUBNET=0 rig_control_ok="${2:-1}" fault_ran=no lifecycle_rc="$1" run_lifecycle() { LIFECYCLE_STACK_INTACT="${intact:-0}" @@ -294,7 +294,7 @@ assert_eq "a failed rigforge-control names the requested phases it gates off (#2 drive_abort() { ( # shellcheck disable=SC2034 - RUN_LIFECYCLE=1 RUN_RESET_DASHBOARD=0 RUN_ROTATE_SECRETS=0 RUN_FAULTS=0 RUN_AUTH_FAIL_CLOSED=0 RUN_HARDENING=0 RUN_XVB_ROUTING=0 RUN_ALERT_EGRESS=0 \ + RUN_LIFECYCLE=1 RUN_RESET_DASHBOARD=0 RUN_ROTATE_SECRETS=0 RUN_FAULTS=0 RUN_AUTH_FAIL_CLOSED=0 RUN_SVC_RESTART=0 RUN_HARDENING=0 RUN_XVB_ROUTING=0 RUN_ALERT_EGRESS=0 \ RUN_MERGEMINE_SUBMIT=0 RUN_MERGEMINE_LOCALNET=0 RUN_SUBNET=0 rig_control_ok=1 IT_FAIL=0 rows="" lc_rc="$1" lc_step="$2" lc_own="$3" # shellcheck disable=SC2034 run_lifecycle() { diff --git a/tests/integration/selftest/selftest-run-modules.sh b/tests/integration/selftest/selftest-run-modules.sh index 19f3f6d9a5..715fbc86a6 100755 --- a/tests/integration/selftest/selftest-run-modules.sh +++ b/tests/integration/selftest/selftest-run-modules.sh @@ -3,7 +3,7 @@ set -uo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT="$HERE/.." -modules=(run-usage.sh run-cli.sh run-matrix.sh run-egress-claim.sh run-onion-targets.sh run-state.sh run-tari-wallet.sh run-lan-guard.sh run-scenario.sh run-source-image.sh run-wizard-defaults.sh run-connection-announcements.sh run-reset-restore.sh run-support-bundle.sh run-lifecycle.sh run-reset-dashboard.sh run-rotate-secrets.sh run-faults.sh run-pool-sync-fault.sh run-tor-probe-fault.sh run-pool-peer-loss.sh run-egress-status.sh run-hardening.sh run-rotate-onion.sh run-safety.sh run-rigforge.sh run-rig-control.sh run-rig-reverse.sh run-alert-egress.sh run-mergemine-submit.sh run-tari-stranded.sh run-monero-stranded.sh run-mergemine-localnet.sh) +modules=(run-usage.sh run-cli.sh run-matrix.sh run-egress-claim.sh run-onion-targets.sh run-state.sh run-tari-wallet.sh run-lan-guard.sh run-scenario.sh run-source-image.sh run-wizard-defaults.sh run-connection-announcements.sh run-reset-restore.sh run-support-bundle.sh run-lifecycle.sh run-reset-dashboard.sh run-rotate-secrets.sh run-faults.sh run-pool-sync-fault.sh run-tor-probe-fault.sh run-pool-peer-loss.sh run-egress-status.sh run-hardening.sh run-svc-restart.sh run-rotate-onion.sh run-safety.sh run-rigforge.sh run-rig-control.sh run-rig-reverse.sh run-alert-egress.sh run-mergemine-submit.sh run-tari-stranded.sh run-monero-stranded.sh run-mergemine-localnet.sh) echo "== run.sh modules load completely in their preserved order ==" expected_modules="$(printf 'lib/%s ' "${modules[@]}" | sed 's/ $//')" @@ -13,7 +13,7 @@ actual_modules="$(sed -n 's|^source "$HERE/\(lib/run-[a-z-]*\.sh\)".*|\1|p' "$RO exit 1 } -expected_functions='usage parse_args print_list push_config env_on_box running_services _pred_mining_probe_running assert_mining_probe_ready service_state secret_fingerprint preflight record_manifest run_scenario clearnet_flag_effective restore_firewall_after_clearnet assert_host_claims_spent_sync assert_onion_targets _onion_reachable_external assert_running_state assert_egress_dial_pair public_remotes_in_proc_tcp _pred_tari_payouts_found _pred_payout_wallet_ready _pred_monero_wallet_caught_up assert_payout_wallet_ready assert_tari_payout_scan _lan_probe _lan_flush_rules _lan_strip _lan_capture _lan_probe_open _lan_assert_open assert_lan_guard_live assert_lan_guard_timer_flush _lan_timer_pause _lan_exit_code assert_lan_guard_crash_restart assert_lan_guard_boot_restore assert_lan_guard_boot_failure assert_scenario assert_egress_posture assert_xvb_over_tor assert_metrics_via_caddy assert_doctor_ok assert_share_stats_live assert_telemetry_tables_present assert_current_state box_fstype box_avail_gb box_mode _pred_readiness_monero _pred_readiness_status status_verdict_lines assert_release_readiness lifecycle_gate_snippet retain_lifecycle_gate_samples lifecycle_gate_sample source_image_reconcile_snippet run_source_image_reconcile run_image_permissions wizard_restore_baseline run_cli_wizard_defaults connection_announcements_snippet run_connection_announcements run_restore_dashboard_probe run_reset_restore reset_restore_wait_reboot reset_restore_shutdown_clean reset_restore_wait_empty run_support_bundle _run_lifecycle kept_data_snapshot_snippet kept_chain_files_snippet run_uninstall_round_trip telemetry_rows_diff _pred_status_down _monerod_is _pred_monerod_missing _pred_monerod_unhealthy _pred_monerod_healthy _pred_proxy_stopped _pred_failover_armed _pred_p2pool_running _pred_tor_stopped _pred_tor_healthy _reset_dashboard_services_healthy run_reset_dashboard _rotate_proxy_live_args _rotate_monero_rpc_probe _rotate_proxy_token_accepted _rotate_stratum_auth _rotate_proxy_upstream_active _rotate_rig_accepted _rotate_proxy_accepted_after _rotate_p2pool_monero_live _rotate_new_baks _rotate_cleanup_baks _rotate_abort_restore run_rotate_secrets _rig_active_pool _pred_rig_pool_differs _pred_rig_pool_returned _rig_pool_leg fault_node_down fault_unhealthy fault_missing fault_db_readonly fault_firewall_rollback _gf_flows _gf_down fault_firewall_grandfathered_flow fault_tor_down fault_clock_drift fault_disk_enospc _pred_p2pool_peers _pred_dnswatch_listening fault_p2pool_cold_cache_dns _restore_p2pool_peer_lists run_fault_injection run_fault_injection_maybe p2pool_sidechain_sync_snippet fault_p2pool_sidechain_sync tor_probe_ns_ipt _tor_probe_mining_sample fault_tor_probe_egress _tor_probe_recovered tor_recovery_lock_snapshot_snippet tor_recovery_probe_now_s tor_recovery_healthy_probe p2pool_ns_ipt p2pool_peer_loss_rules p2pool_peer_loss_count p2pool_peer_total p2pool_started_at _pred_p2pool_peerless _pred_p2pool_restarted _pred_p2pool_has_peers _pred_p2pool_rejoin_logged fault_p2pool_peer_loss _await_egress_state fault_firewall_status_alert fault_firewall_boot_restore _set_env_token _spool_write _uuid4 _wait_control_status _remove_control_units run_hardening run_auth_fail_closed rotate_onion_data_dir rotate_onion_key_fingerprint rotate_onion_client_key_fingerprint rotate_onion_env_fingerprint rotate_onion_mining_fingerprint wait_onion_retired rotate_onion_restore run_rotate_onion safety_backup safety_secret_drift_categories safety_restore_exact safety_rollback_if_failed safety_abort_restore arm_safety_abort_restore reset_dashboard_remove_blocker reset_dashboard_cleanup safety_cleanup restore_baseline summary run_rigforge_integration assert_subnet_live run_subnet_scenario _worker_apply _max_temp_round_trip _restore_rig_control_baseline run_rigforge_control _pred_rig_present run_rigforge_reverse _rig_control_apply _rig_control_await _pred_feed_maxt _rig_direct_summary _reverse_feed_failure_detail run_rigforge_rollback it_alert_refused _alert_egress_overlay _alert_egress_verdict run_alert_egress_smoke _mm_rows _mm_cleanup run_mergemine_submit tari_ns_ipt tari_strand_count tari_strand_drops tari_strand_remove_all tari_hook_start tari_hook_stop tari_restore_config tari_strand_abort tari_health_field _pred_tari_level _pred_tari_at_least_amber _pred_tari_zero_peers _pred_tari_alerted _pred_tari_recovery_alerted tari_started_at tari_strand_state run_tari_stranded monero_ns_ipt monero_strand_count monero_strand_remove_all monero_hook_start monero_hook_stop monero_restore_config monero_strand_abort monero_health_field _pred_monero_level monero_peer_counts monero_out_peers monero_tor_recovery_out monero_observation _pred_monero_zero_out _pred_monero_has_peers _pred_monerod_docker_health _pred_monero_alerted _pred_monero_recovery_alerted monero_peer_sample _pred_monero_has_peers_sampled monero_peer_wait_diagnostics _monero_http_code assert_monero_p2p_advertisement assert_monero_rpc_boundary monero_started_at monero_strand_state run_monero_stranded _mml_fact _mml_target_row _mml_inspect _mml_ip _mml_cleanup run_mergemine_localnet' +expected_functions='usage parse_args print_list push_config env_on_box running_services _pred_mining_probe_running assert_mining_probe_ready service_state secret_fingerprint preflight record_manifest run_scenario clearnet_flag_effective restore_firewall_after_clearnet assert_host_claims_spent_sync assert_onion_targets _onion_reachable_external assert_running_state assert_egress_dial_pair public_remotes_in_proc_tcp _pred_tari_payouts_found _pred_payout_wallet_ready _pred_monero_wallet_caught_up assert_payout_wallet_ready assert_tari_payout_scan _lan_probe _lan_flush_rules _lan_strip _lan_capture _lan_probe_open _lan_assert_open assert_lan_guard_live assert_lan_guard_timer_flush _lan_timer_pause _lan_exit_code assert_lan_guard_crash_restart assert_lan_guard_boot_restore assert_lan_guard_boot_failure assert_scenario assert_egress_posture assert_xvb_over_tor assert_metrics_via_caddy assert_doctor_ok assert_share_stats_live assert_telemetry_tables_present assert_current_state box_fstype box_avail_gb box_mode _pred_readiness_monero _pred_readiness_status status_verdict_lines assert_release_readiness lifecycle_gate_snippet retain_lifecycle_gate_samples lifecycle_gate_sample source_image_reconcile_snippet run_source_image_reconcile run_image_permissions wizard_restore_baseline run_cli_wizard_defaults connection_announcements_snippet run_connection_announcements run_restore_dashboard_probe run_reset_restore reset_restore_wait_reboot reset_restore_shutdown_clean reset_restore_wait_empty run_support_bundle _run_lifecycle kept_data_snapshot_snippet kept_chain_files_snippet run_uninstall_round_trip telemetry_rows_diff _pred_status_down _monerod_is _pred_monerod_missing _pred_monerod_unhealthy _pred_monerod_healthy _pred_proxy_stopped _pred_failover_armed _pred_p2pool_running _pred_tor_stopped _pred_tor_healthy _reset_dashboard_services_healthy run_reset_dashboard _rotate_proxy_live_args _rotate_monero_rpc_probe _rotate_proxy_token_accepted _rotate_stratum_auth _rotate_proxy_upstream_active _rotate_rig_accepted _rotate_proxy_accepted_after _rotate_p2pool_monero_live _rotate_new_baks _rotate_cleanup_baks _rotate_abort_restore run_rotate_secrets _rig_active_pool _pred_rig_pool_differs _pred_rig_pool_returned _rig_pool_leg fault_node_down fault_unhealthy fault_missing fault_db_readonly fault_firewall_rollback _gf_flows _gf_down fault_firewall_grandfathered_flow fault_tor_down fault_clock_drift fault_disk_enospc _pred_p2pool_peers _pred_dnswatch_listening fault_p2pool_cold_cache_dns _restore_p2pool_peer_lists run_fault_injection run_fault_injection_maybe p2pool_sidechain_sync_snippet fault_p2pool_sidechain_sync tor_probe_ns_ipt _tor_probe_mining_sample fault_tor_probe_egress _tor_probe_recovered tor_recovery_lock_snapshot_snippet tor_recovery_probe_now_s tor_recovery_healthy_probe p2pool_ns_ipt p2pool_peer_loss_rules p2pool_peer_loss_count p2pool_peer_total p2pool_started_at _pred_p2pool_peerless _pred_p2pool_restarted _pred_p2pool_has_peers _pred_p2pool_rejoin_logged fault_p2pool_peer_loss _await_egress_state fault_firewall_status_alert fault_firewall_boot_restore _set_env_token _spool_write _uuid4 _wait_control_status _remove_control_units run_hardening run_auth_fail_closed _svc_restart_request run_svc_restart rotate_onion_data_dir rotate_onion_key_fingerprint rotate_onion_client_key_fingerprint rotate_onion_env_fingerprint rotate_onion_mining_fingerprint wait_onion_retired rotate_onion_restore run_rotate_onion safety_backup safety_secret_drift_categories safety_restore_exact safety_rollback_if_failed safety_abort_restore arm_safety_abort_restore reset_dashboard_remove_blocker reset_dashboard_cleanup safety_cleanup restore_baseline summary run_rigforge_integration assert_subnet_live run_subnet_scenario _worker_apply _max_temp_round_trip _restore_rig_control_baseline run_rigforge_control _pred_rig_present run_rigforge_reverse _rig_control_apply _rig_control_await _pred_feed_maxt _rig_direct_summary _reverse_feed_failure_detail run_rigforge_rollback it_alert_refused _alert_egress_overlay _alert_egress_verdict run_alert_egress_smoke _mm_rows _mm_cleanup run_mergemine_submit tari_ns_ipt tari_strand_count tari_strand_drops tari_strand_remove_all tari_hook_start tari_hook_stop tari_restore_config tari_strand_abort tari_health_field _pred_tari_level _pred_tari_at_least_amber _pred_tari_zero_peers _pred_tari_alerted _pred_tari_recovery_alerted tari_started_at tari_strand_state run_tari_stranded monero_ns_ipt monero_strand_count monero_strand_remove_all monero_hook_start monero_hook_stop monero_restore_config monero_strand_abort monero_health_field _pred_monero_level monero_peer_counts monero_out_peers monero_tor_recovery_out monero_observation _pred_monero_zero_out _pred_monero_has_peers _pred_monerod_docker_health _pred_monero_alerted _pred_monero_recovery_alerted monero_peer_sample _pred_monero_has_peers_sampled monero_peer_wait_diagnostics _monero_http_code assert_monero_p2p_advertisement assert_monero_rpc_boundary monero_started_at monero_strand_state run_monero_stranded _mml_fact _mml_target_row _mml_inspect _mml_ip _mml_cleanup run_mergemine_localnet' actual_functions="$(for module in "${modules[@]}"; do sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)() {.*/\1/p' "$ROOT/lib/$module"; done | tr '\n' ' ' | sed 's/ $//')" [ "$actual_functions" = "$expected_functions" ] || { echo "integration function order or completeness mismatch" >&2 @@ -71,6 +71,8 @@ source "$ROOT/lib/run-pool-peer-loss.sh" || exit $? source "$ROOT/lib/run-egress-status.sh" || exit $? # shellcheck source=tests/integration/lib/run-hardening.sh source "$ROOT/lib/run-hardening.sh" || exit $? +# shellcheck source=tests/integration/lib/run-svc-restart.sh +source "$ROOT/lib/run-svc-restart.sh" || exit $? # shellcheck source=tests/integration/lib/run-rotate-onion.sh source "$ROOT/lib/run-rotate-onion.sh" || exit $? # shellcheck source=tests/integration/lib/run-safety.sh diff --git a/tests/stack/control/test-control-lifecycle-verbs.sh b/tests/stack/control/test-control-lifecycle-verbs.sh index 511bd29296..16afbfac8f 100644 --- a/tests/stack/control/test-control-lifecycle-verbs.sh +++ b/tests/stack/control/test-control-lifecycle-verbs.sh @@ -79,3 +79,126 @@ run_sourced_e "$SANDBOX" control_process_request "$CC/req_x.json" "$CC" >/dev/nu assert_eq "unknown verb rejected (bounded action set)" "$(jq -r .error "$CC/results/$uid_x.json")" "unknown action" assert_eq "unknown verb never runs a host command" "$(cat "$SELF_LOG")" "" unset PITHEAD_SELF SELF_LOG + +echo "== control channel: svc-restart — one allowlisted service, under the lock, with a cooldown (#4062) ==" +SR="$SANDBOX/ctrl4062" +mkdir -p "$SR/results" "$SR/audit" "$SR/bin" +cat >"$SR/bin/docker" <<'EOF2' +#!/usr/bin/env bash +echo "$*" >>"$SR_DOCKER_LOG" +[ "${SR_DOCKER_RC:-0}" -eq 0 ] || { echo "no such service" >&2; exit "$SR_DOCKER_RC"; } +exit 0 +EOF2 +chmod +x "$SR/bin/docker" +export SR SR_DOCKER_LOG="$SR/docker.log" +sr_req() { + printf '{"id":"%s","action":"svc-restart","actor":"admin"%s%s}\n' "$1" "${2:+,\"container\":$2}" "${3:-}" >"$SR/req-$1.json" + printf '%s\n' "$SR/req-$1.json" +} +sr_run() { + ( + export PATH="$SR/bin:$PATH" PITHEAD_LOCK_FILE="$SR/.lock" + if [ "${2:-1}" = 0 ]; then + bash -Eeuo pipefail -c 'cd "$1"; source "$2"; lan_guard_ready() { return 1; }; control_process_request "$3" "$4"' _ "$SANDBOX" "$STACK" "$1" "$SR" + else + run_sourced_e "$SANDBOX" control_process_request "$1" "$SR" + fi + ) >/dev/null 2>&1 +} +sr_status() { jq -r '.status' "$SR/results/$1.json"; } +sr_id() { printf 'c4062c40-0000-4000-8000-%012d' "$1"; } + +: >"$SR_DOCKER_LOG" +sr_run "$(sr_req "$(sr_id 1)" '"tor"')" +assert_eq "an allowlisted service restarts" "$(sr_status "$(sr_id 1)")" "applied" +assert_eq "the restart runs exactly one compose restart of that service" "$(cat "$SR_DOCKER_LOG")" "compose restart tor" +assert_contains "started and applied are audited with the actor and the service" \ + "$(cat "$SR/audit/control.log")" '"actor":"admin","action":"svc-restart","status":"applied","keys":"tor"' +assert_contains "the audit also records the start" "$(cat "$SR/audit/control.log")" '"action":"svc-restart","status":"started","keys":"tor"' + +: >"$SR_DOCKER_LOG" +sr_run "$(sr_req "$(sr_id 2)" '"tor"')" +assert_eq "a repeat inside the cooldown is rejected" "$(sr_status "$(sr_id 2)")" "rejected" +assert_contains "the cooldown refusal says why" "$(jq -r .error "$SR/results/$(sr_id 2).json")" "wait before restarting it again" +assert_eq "a cooled-down request never reaches docker" "$(cat "$SR_DOCKER_LOG")" "" + +: >"$SR_DOCKER_LOG" +sr_run "$(sr_req "$(sr_id 3)" '"monerod"')" +assert_eq "the cooldown is per service" "$(sr_status "$(sr_id 3)")" "applied" +printf '%s\n' "$(($(date +%s) - 1000))" >"$SR/svc-restart-tor" +sr_run "$(sr_req "$(sr_id 4)" '"tor"')" +assert_eq "an expired cooldown allows the restart again" "$(sr_status "$(sr_id 4)")" "applied" + +sr_allowed="" +for svc in wallet-rpc tari tari-wallet p2pool xmrig-proxy; do + : >"$SR_DOCKER_LOG" + sr_run "$(sr_req "$(sr_id 10)" "\"$svc\"")" + sr_allowed+="$(cat "$SR_DOCKER_LOG")"$'\n' + rm -f "$SR/results/$(sr_id 10).json" +done +assert_eq "every other allowlisted service restarts with exactly one compose restart" "$sr_allowed" \ + $'compose restart wallet-rpc\ncompose restart tari\ncompose restart tari-wallet\ncompose restart p2pool\ncompose restart xmrig-proxy\n' + +sr_audit="$(cat "$SR/audit/control.log")" +assert_contains "the audit records wallet-rpc with its hyphen" "$sr_audit" '"action":"svc-restart","status":"applied","keys":"wallet-rpc"' +assert_contains "the audit records tari-wallet with its hyphen" "$sr_audit" '"action":"svc-restart","status":"applied","keys":"tari-wallet"' +assert_contains "the audit records xmrig-proxy with its hyphen" "$sr_audit" '"action":"svc-restart","status":"applied","keys":"xmrig-proxy"' + +sr_refused="" +: >"$SR_DOCKER_LOG" +for bad_svc in dashboard caddy docker-proxy docker-control "tor monerod" "tor;id" '' '../tor' 'TOR' 'torx'; do + sr_run "$(sr_req "$(sr_id 20)" "\"$bad_svc\"")" + sr_refused+="$(sr_status "$(sr_id 20)") " + rm -f "$SR/results/$(sr_id 20).json" +done +assert_eq "every non-allowlisted name is rejected by exact membership" "$sr_refused" \ + "rejected rejected rejected rejected rejected rejected rejected rejected rejected rejected " +assert_eq "no rejected name ever reaches docker" "$(cat "$SR_DOCKER_LOG")" "" +sr_run "$(sr_req "$(sr_id 21)" '')" +assert_eq "a request with no service is rejected" "$(sr_status "$(sr_id 21)")" "rejected" +sr_run "$(sr_req "$(sr_id 22)" '7')" +assert_eq "a non-string service is rejected" "$(sr_status "$(sr_id 22)")" "rejected" +sr_run "$(sr_req "$(sr_id 23)" '["tor"]')" +assert_eq "an array service is rejected" "$(sr_status "$(sr_id 23)")" "rejected" +sr_run "$(sr_req "$(sr_id 24)" '"p2pool"' ',"lines":5')" +assert_eq "extra keys on the verb are rejected and nothing restarts" "$(sr_status "$(sr_id 24)")" "rejected" +assert_contains "a rejection is audited" "$(cat "$SR/audit/control.log")" '"action":"svc-restart","status":"rejected"' + +: >"$SR_DOCKER_LOG" +rm -f "$SR/svc-restart-p2pool" +sr_run "$(sr_req "$(sr_id 30)" '"p2pool"')" 0 +assert_eq "a restart is refused while the LAN guard is not ready" "$(sr_status "$(sr_id 30)")" "rejected" +assert_contains "the guard refusal names the cause" "$(jq -r .error "$SR/results/$(sr_id 30).json")" "LAN-only source rule" +assert_eq "a guard refusal never reaches docker" "$(cat "$SR_DOCKER_LOG")" "" + +: >"$SR_DOCKER_LOG" +SR_DOCKER_RC=1 sr_run "$(sr_req "$(sr_id 31)" '"p2pool"')" +assert_eq "a failing compose restart is a failed result" "$(sr_status "$(sr_id 31)")" "failed" +assert_contains "the failure carries the host's reason" "$(jq -r .error "$SR/results/$(sr_id 31).json")" "no such service" +assert_contains "the failure is audited" "$(cat "$SR/audit/control.log")" '"action":"svc-restart","status":"failed","keys":"p2pool"' +sr_run "$(sr_req "$(sr_id 32)" '"p2pool"')" +assert_eq "a failed restart does not start the cooldown" "$(sr_status "$(sr_id 32)")" "applied" + +if command -v flock >/dev/null 2>&1; then + : >"$SR_DOCKER_LOG" + rm -f "$SR/svc-restart-xmrig-proxy" + : >"$SR/.lock" + ( + exec 9>>"$SR/.lock" + flock -w 20 9 || exit 1 + exec sleep 30 + ) >/dev/null 2>&1 & + sr_holder=$! + sr_i=0 + while flock -n "$SR/.lock" true 2>/dev/null && [ "$sr_i" -lt 200 ]; do + sleep 0.05 + sr_i=$((sr_i + 1)) + done + sr_run "$(sr_req "$(sr_id 40)" '"xmrig-proxy"')" + assert_eq "a restart while the mutation lock is held is rejected as busy, not queued" "$(sr_status "$(sr_id 40)")" "rejected" + assert_contains "the busy refusal says another operation is running" "$(jq -r .error "$SR/results/$(sr_id 40).json")" "in progress" + assert_eq "a busy refusal never reaches docker" "$(cat "$SR_DOCKER_LOG")" "" + kill "$sr_holder" 2>/dev/null || true + wait "$sr_holder" 2>/dev/null || true +fi +unset SR SR_DOCKER_LOG From fcbb18819bd3ab956887572716cc55bd97f75298 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:59:28 -0600 Subject: [PATCH 030/112] test(os): clean the floor-fallback leg's bundle, log and rootfs tag off the host (#3299) (#4069) Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Code --- tests/os/README.md | 5 +- tests/os/data-floor-fallback-leg.sh | 28 +++++-- tests/os/selftest-floor-cleanup.sh | 119 ++++++++++++++++++++++++++++ tests/stack/test-harness-tooling.sh | 3 + 4 files changed, 149 insertions(+), 6 deletions(-) create mode 100644 tests/os/selftest-floor-cleanup.sh diff --git a/tests/os/README.md b/tests/os/README.md index b74b5f2f94..4e392f5e64 100644 --- a/tests/os/README.md +++ b/tests/os/README.md @@ -273,7 +273,10 @@ the configured test registry fail before the image build. Release builds do not bundle stamped with a version no release carries. Its copied build tree opts into the harness-only synthetic compose path, names its compose file explicitly, uses the resolved signing material, and records the file hash in `COMPOSE_SOURCE`, so the build does not need a - git origin or a local dev-key directory. The + git origin or a local dev-key directory. Its stamped bundle, its build log and the stamped + `pithead-os-rootfs-` image tag its build creates live inside the leg's own temp + directory, and the leg removes them all when it ends — success or failure — because nothing + the leg writes on the host may outlive the job (#3299). The resulting slot cannot bring the stack up and falls back uncommitted: the previous slot's boot must put the `/data` floor back from the record the raise left, and the same fall-back with the record deleted must leave the floor alone and make `os-update` refuse with the diff --git a/tests/os/data-floor-fallback-leg.sh b/tests/os/data-floor-fallback-leg.sh index 37bb9f8beb..a4af72fe4e 100644 --- a/tests/os/data-floor-fallback-leg.sh +++ b/tests/os/data-floor-fallback-leg.sh @@ -34,6 +34,7 @@ . "$SCRIPT_DIR/../../os/rauc/populate-slot.sh" FLOOR_FALLBACK_VERSION=99.0.0 +FLOOR_LEG_TMP="" # $1 marker, $2 stamped version, $3 minimum_os_version -> prints the bundle path (outside # os/rauc/build, so _build_bundle's `find | head -1` in a later phase can never pick it up). @@ -45,7 +46,7 @@ _build_bundle_stamped() { keyring="$(cd "$(dirname "$RAUC_KEYRING")" && pwd -P)/$(basename "$RAUC_KEYRING")" || return 1 mkdir -p "$HOST_SCRATCH" || return 1 wt=$(mktemp -d "$HOST_SCRATCH/floor-fallback.XXXXXX") || return 1 - out="$HOST_SCRATCH/os-floor-fallback-$marker.raucb" + out="${FLOOR_LEG_TMP:-$HOST_SCRATCH}/os-floor-fallback-$marker.raucb" { git archive HEAD | tar -x -C "$wt" && printf '%s\n' "$version" >"$wt/VERSION" && @@ -59,9 +60,10 @@ _build_bundle_stamped() { os/rauc/mkbundle.sh --dev ) && cp "$wt/os/rauc/build/update.raucb" "$out" - } >>/tmp/os-fault-bundle.log 2>&1 + } >>"${FLOOR_LEG_TMP:-$HOST_SCRATCH}/build.log" 2>&1 local rc=$? rm -rf "$wt" + docker rmi "pithead-os-rootfs-$marker" >/dev/null 2>&1 || true [ "$rc" = 0 ] || return 1 printf '%s' "$out" } @@ -120,7 +122,7 @@ _floor_target_slot() { esac } -phase_provision_floor_fallback_leg() { # $1 = the migration leg's data_migration bundle at VERSION +_floor_fallback_leg_body() { local good_bundle="$1" vfail="$FLOOR_FALLBACK_VERSION" floor0 bundle out rc state target_slot stamp want_stamp info "floor-fallback leg — a data_migration update that fails its gate must give the /data floor back (#1393)" floor0=$(_ssh "cat /data/pithead/.os-data-floor 2>/dev/null" | tr -d ' \r\n') @@ -130,8 +132,8 @@ phase_provision_floor_fallback_leg() { # $1 = the migration leg's data_migration fi ok "floor before the failing update: $floor0" bundle=$(_build_bundle_stamped vfail "$vfail" "$vfail") || { - bundle_build_evidence - bad "the $vfail migration bundle build failed — read the build output above (/tmp/os-fault-bundle.log)" + bundle_build_evidence "$FLOOR_LEG_TMP/build.log" + bad "the $vfail migration bundle build failed — read the build output above" return } ok "built a data_migration bundle stamped $vfail (floor $vfail): $(basename "$bundle")" @@ -268,3 +270,19 @@ phase_provision_floor_fallback_leg() { # $1 = the migration leg's data_migration ok "the refusal names no reset and no restore" fi } + +phase_provision_floor_fallback_leg() { + local rc=0 scratch="${HOST_SCRATCH:-${TMPDIR:-/tmp}}" + mkdir -p "$scratch" || { + bad "could not create the floor-fallback leg's scratch directory" + return 1 + } + FLOOR_LEG_TMP=$(mktemp -d "$scratch/pithead-floor-fallback-leg.XXXXXX") || { + bad "could not create a temporary directory for the floor-fallback leg" + return 1 + } + _floor_fallback_leg_body "$@" || rc=$? + rm -rf "$FLOOR_LEG_TMP" + FLOOR_LEG_TMP="" + return "$rc" +} diff --git a/tests/os/selftest-floor-cleanup.sh b/tests/os/selftest-floor-cleanup.sh new file mode 100644 index 0000000000..24a6f64dfb --- /dev/null +++ b/tests/os/selftest-floor-cleanup.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +set -uo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +T=$(mktemp -d) +trap 'rm -rf "$T"' EXIT +# shellcheck source=tests/os/data-floor-fallback-leg.sh +SCRIPT_DIR="$HERE" source "$HERE/data-floor-fallback-leg.sh" + +fail() { + echo "FAIL: $1" + exit 1 +} + +TAGS="$T/tags" +: >"$TAGS" +: >"$TAGS.seen" +mkdir -p "$T/bin" "$T/tree/os/rauc" "$T/leg" +cat >"$T/bin/docker" <>"$TAGS" + printf '%s\n' "\$1" >>"$TAGS.seen" + fi + shift + done + ;; +rmi) + shift + while [ \$# -gt 0 ]; do + grep -vxF -- "\$1" "$TAGS" >"$TAGS.next" || true + mv "$TAGS.next" "$TAGS" + shift + done + ;; +esac +EOF +cat >"$T/tree/os/build-image.sh" <"$T/tree/os/rauc/mkbundle.sh" <os/rauc/build/update.raucb +echo "fake mkbundle done" +EOF +cat >"$T/bin/git" <"$T/fake.crt" + : >"$T/fake.key" + : >"$T/fake.keyring" + : >"$T/key.pub" + KEY="$T/key" + RAUC_CERT="$T/fake.crt" RAUC_KEY="$T/fake.key" RAUC_KEYRING="$T/fake.keyring" +} + +FLOOR_LEG_TMP="$T/leg" + +out=$(PATH="$T/bin:$PATH" _build_bundle_stamped vfail 99.0.0 99.0.0) +rc=$? +[ "$rc" -eq 0 ] || fail "stamped build returned $rc: $(cat "$FLOOR_LEG_TMP/build.log" 2>/dev/null)" +case "$out" in +"$T/leg"/*) ;; +*) fail "bundle printed at $out, want it under the leg directory" ;; +esac +[ -s "$out" ] || fail "bundle missing at $out" +grep -q 'fake build-image' "$FLOOR_LEG_TMP/build.log" || fail "build log not written under the leg directory" +grep -qxF 'pithead-os-rootfs-vfail' "$TAGS.seen" || fail "rootfs tag never built" +[ ! -s "$TAGS" ] || fail "rootfs image tag left on the host: $(cat "$TAGS")" + +out=$(PATH="$T/bin:$PATH" BUILD_FAIL=1 _build_bundle_stamped vfail2 99.0.0 99.0.0) +rc=$? +[ "$rc" -ne 0 ] || fail "failing build returned success" +grep -qxF 'pithead-os-rootfs-vfail2' "$TAGS.seen" || fail "failing build never tagged the rootfs" +[ ! -s "$TAGS" ] || fail "rootfs tag left after a failed build: $(cat "$TAGS")" +[ ! -e "$FLOOR_LEG_TMP/os-floor-fallback-vfail2.raucb" ] || fail "failed build left a bundle in the leg dir" +grep -q 'fake build-image failed' "$FLOOR_LEG_TMP/build.log" || fail "failed build left no log in the leg dir" + +ok() { :; } +info() { :; } +bad() { :; } +CAPTURED="" +BODY_FAIL="" +_floor_fallback_leg_body() { + { [ -n "$FLOOR_LEG_TMP" ] && [ -d "$FLOOR_LEG_TMP" ]; } || fail "leg body entered without its directory" + printf x >"$FLOOR_LEG_TMP/artifact" + CAPTURED="$FLOOR_LEG_TMP" + [ -z "$BODY_FAIL" ] +} +phase_provision_floor_fallback_leg "$T/bundle" +rc=$? +[ "$rc" -eq 0 ] || fail "successful leg body reported rc $rc" +[ -n "$CAPTURED" ] || fail "leg body never ran" +[ ! -e "$CAPTURED" ] || fail "the leg left $CAPTURED behind" +CAPTURED="" +BODY_FAIL=1 +phase_provision_floor_fallback_leg "$T/bundle" +rc=$? +[ "$rc" -ne 0 ] || fail "failed leg body returned success" +[ ! -e "$CAPTURED" ] || fail "the failed leg left $CAPTURED behind" + +printf 'selftest-floor-cleanup: ok\n' diff --git a/tests/stack/test-harness-tooling.sh b/tests/stack/test-harness-tooling.sh index aad48be0d9..48ceab31d4 100644 --- a/tests/stack/test-harness-tooling.sh +++ b/tests/stack/test-harness-tooling.sh @@ -194,6 +194,9 @@ assert_rc "#2871 serial match survives a large log under pipefail" "$?" "0" echo "== unit: #3049 floor-fallback staging self-test ==" bash "$ROOT/tests/os/selftest-floor-staging.sh" >/dev/null 2>&1 assert_rc "#3049 failed bundle staging never invokes os-update; success still does" "$?" "0" +echo "== unit: #3299 floor-fallback host-cleanup self-test ==" +bash "$ROOT/tests/os/selftest-floor-cleanup.sh" >/dev/null 2>&1 +assert_rc "#3299 floor-fallback leg leaves no bundle, build log or rootfs tag on the host" "$?" "0" echo "== unit: #1676 version-aging helper self-test ==" # tests/os/run.sh's leg 4 must make the guest claim a version OLDER than the bundle it is about to # install, and every minor release-prep tip is x.y.0 — the shape the helper used to refuse, which From eb929ceb93371ba968cb1fcfda8fe49755f0ca64 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:59:35 -0600 Subject: [PATCH 031/112] Report a failed migration-hold clear at the chain commit gate (#4022) * Report a failed migration-hold clear at the chain commit gate The commit gate swallowed release_held_chain_services' silent return 1 when clear_migration_hold failed, so the held chain services never came up and no FAULT line appeared. Print the FAULT naming the recovery and attempt the release anyway; the commit already stands and the next boot clears a leftover marker. Pin both with a selftest case that fails the clear after commit. Co-Authored-By: Claude Code * Move the release-path source pin to the alerting shape The #3894 pin held the exact `clear_migration_hold "$@" || return 1` line; the release now alerts on that branch, so the pin follows the line while still refusing a bare rm and demanding the durable clear. Co-Authored-By: Claude Code --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Code --- os/overlay/pithead-boot | 2 +- tests/os/selftest-migration-boot.sh | 16 +++++++++++++++- .../stack/appliance/test-appliance-data-floor.sh | 2 +- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/os/overlay/pithead-boot b/os/overlay/pithead-boot index fcbc1e7449..83316daa8e 100755 --- a/os/overlay/pithead-boot +++ b/os/overlay/pithead-boot @@ -243,7 +243,7 @@ clear_migration_hold() { mutation_migration_cleanup clear "$@"; } RELEASE_UP_TRIES=${PITHEAD_RELEASE_UP_TRIES:-5} RELEASE_UP_PAUSE=${PITHEAD_RELEASE_UP_PAUSE:-10} release_held_chain_services() { # cwd /data/pithead -> 0 once `up` succeeds, 1 after the last try - clear_migration_hold "$@" || return 1 + clear_migration_hold "$@" || echo "pithead-boot: FAULT — migration protection could not be cleared after commitment; the chain services are released anyway. Reboot, or run './pithead up' from /data/pithead and read 'journalctl -u pithead-boot' if they did not start." >&2 echo "pithead-boot: slot committed — chain services released, the data migration runs now" local try for try in $(seq "$RELEASE_UP_TRIES"); do diff --git a/tests/os/selftest-migration-boot.sh b/tests/os/selftest-migration-boot.sh index d1b05811e7..27d985dc58 100755 --- a/tests/os/selftest-migration-boot.sh +++ b/tests/os/selftest-migration-boot.sh @@ -79,6 +79,9 @@ last=$(grep '^rauc ' "${CALLS:?}" | tail -1) case "$*" in -f*/.os-data-floor.*) [ "${SYNC_FAIL_FLOOR:-0}" != 1 ] || exit 1 ;; esac +if [ "$#" -eq 0 ] && [ "${SYNC_FAIL_CLEAR:-0}" = 1 ] && [ ! -e "${PITHEAD_MIGRATION_MARKER_FILE:-}" ]; then + exit 1 +fi EOF cat >"$T/bin/stat" <<'EOF' #!/usr/bin/env bash @@ -118,7 +121,7 @@ fixture_env() { export PITHEAD_MIGRATION_MARKER_FILE="$1/.os-migration-pending" export PITHEAD_LOCK_FILE="$1/lock" export RAUC_BOOT_SLOT="$2" RAUC_MARK_GOOD_RC=0 RAUC_MARK_BAD_RC=0 - export SYNC_FAIL_COMMIT=0 SYNC_FAIL_FLOOR=0 + export SYNC_FAIL_COMMIT=0 SYNC_FAIL_FLOOR=0 SYNC_FAIL_CLEAR=0 } ownership_case() ( @@ -163,6 +166,7 @@ gate_case() ( export RAUC_MARK_BAD_RC="${CASE_MARK_BAD_RC:-0}" export SYNC_FAIL_COMMIT="${CASE_SYNC_FAIL_COMMIT:-0}" export SYNC_FAIL_FLOOR="${CASE_SYNC_FAIL_FLOOR:-0}" + export SYNC_FAIL_CLEAR="${CASE_SYNC_FAIL_CLEAR:-0}" # shellcheck source=/dev/null source "$dir/pithead" # shellcheck disable=SC2034 # read by the extracted production loop @@ -253,6 +257,16 @@ assert_absent "$RELEASE/.os-data-floor.prev" assert_absent "$RELEASE/.os-migration-pending" assert_call "$RELEASE" 'pithead up' +CLEAR_FAIL=$(new_fixture candidate-clear-fail 2.0.0 B '2.0.0|B') +set +e +CASE_SYNC_FAIL_CLEAR=1 gate_case "$CLEAR_FAIL" B 1 >"$CLEAR_FAIL/out" 2>&1 +rc=$? +set -e +[ "$rc" -eq 0 ] || fail "a committed boot failed because the migration hold could not be cleared" +grep -Fq 'FAULT — migration protection could not be cleared after commitment' "$CLEAR_FAIL/out" || + fail 'a failed migration-hold clear at the commit gate was not reported' +assert_call "$CLEAR_FAIL" 'pithead up' + if [ "$(uname -s)" = Linux ]; then RACE=$(new_fixture cleanup-race 1.5.0 A '2.0.0|B') OLD_FINGERPRINT=$( diff --git a/tests/stack/appliance/test-appliance-data-floor.sh b/tests/stack/appliance/test-appliance-data-floor.sh index 002d03832f..f32d5a2042 100644 --- a/tests/stack/appliance/test-appliance-data-floor.sh +++ b/tests/stack/appliance/test-appliance-data-floor.sh @@ -123,7 +123,7 @@ assert_contains "fallback cleanup is reached after the successful commit" "$comm [ "$hold_chain" != 0 ] || restore_data_floor_after_fallback "$migration_fingerprint"' assert_contains "the shared commit cleanup removes and syncs both records" "$(cat "$BOOT")" \ ' clear) rm -f "$(os_migration_marker_file)" "$(os_data_floor_file).prev" && sync || exit 1 ;;' -assert_contains "held coordinator release uses durable record cleanup" "$(cat "$BOOT")" ' clear_migration_hold "$@" || return 1' +assert_contains "held coordinator release uses durable record cleanup" "$(cat "$BOOT")" ' clear_migration_hold "$@" || echo "pithead-boot: FAULT' assert_contains "the rig uses the same cleanup after commitment" "$(cat "$BOOT")" \ 'if [ "$hold_chain" = 1 ]; then clear_migration_hold "$migration_fingerprint"; else restore_data_floor_after_fallback "$migration_fingerprint"; fi' From 0d987a68a1e2eaf998d9f41992e23cd2534c9ca7 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:05:51 -0600 Subject: [PATCH 032/112] Re-dial monerod after any Tor start; restart a peerless monerod within bounds (#4076) (#4093) * Re-dial monerod after any Tor start and restart a peerless monerod within bounds (#4076) Co-Authored-By: Claude Sonnet 5.5 * Give a restarted monerod its own settle window, retry a failed start, keep the peerless clock across Tor flaps (#4076) Co-Authored-By: Claude Sonnet 5.5 * Count the peerless grace only while Tor is healthy (#4076) Co-Authored-By: Claude Sonnet 5.5 * Register the new e2e predicate and fix a markdown heading lint (#4076) Co-Authored-By: Claude Sonnet 5.5 * Keep an issue reference off a line start in operations.md (#4076) Co-Authored-By: Claude Sonnet 5.5 * Drop the header comment block from the monero-stranded leg (#4076) Co-Authored-By: Claude Sonnet 5.5 * Make the e2e external Tor start leg fail unless the dashboard re-dials monerod (#4076) Co-Authored-By: Claude Sonnet 5.5 * Do not let peers read while Tor boots cancel the pending re-dial (#4076) Co-Authored-By: Claude Sonnet 5.5 * Wait for the peerless reason, not any red, before the e2e red-state rows (#4076) Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- .../mining_dashboard/service/data_service.py | 1 + .../mining_dashboard/service/data_setup.py | 9 + .../service/health/monero_health.py | 6 +- .../service/health/monerod_redial.py | 136 +++++++++++ .../service/health/test_monerod_redial.py | 225 ++++++++++++++++++ docs/architecture.md | 2 +- docs/configuration.md | 2 +- docs/dev/repo-map.md | 2 +- docs/dev/testing-strategy.md | 2 +- docs/operations.md | 16 +- tests/integration/lib/run-monero-stranded.sh | 57 +++-- .../selftest/selftest-monero-peer-wait.sh | 4 + .../selftest/selftest-run-modules.sh | 2 +- 13 files changed, 436 insertions(+), 28 deletions(-) create mode 100644 dashboard/mining_dashboard/service/health/monerod_redial.py create mode 100644 dashboard/tests/service/health/test_monerod_redial.py diff --git a/dashboard/mining_dashboard/service/data_service.py b/dashboard/mining_dashboard/service/data_service.py index 8d5a30ce7d..3197be3e68 100644 --- a/dashboard/mining_dashboard/service/data_service.py +++ b/dashboard/mining_dashboard/service/data_service.py @@ -586,6 +586,7 @@ async def run(self): await self.tor_healer.check() await self.p2pool_healer.check(p2pool_stats) + await self.monerod_redial.check(monero_sync.get("health")) # 7. External XvB stats sync over Tor (#163), throttled to every 10th iteration, # and ONLY when XvB is enabled — disabling XvB must stop the egress entirely. diff --git a/dashboard/mining_dashboard/service/data_setup.py b/dashboard/mining_dashboard/service/data_setup.py index 2dcc505bfc..095bb6464e 100644 --- a/dashboard/mining_dashboard/service/data_setup.py +++ b/dashboard/mining_dashboard/service/data_setup.py @@ -26,6 +26,7 @@ from mining_dashboard.service.health.degradation import DegradationMonitor from mining_dashboard.service.health.mining_guard import MiningGuard from mining_dashboard.service.health.monero_health import MoneroChainHealth +from mining_dashboard.service.health.monerod_redial import MonerodRedial from mining_dashboard.service.health.node_alert import tor_heal_status from mining_dashboard.service.health.node_health import NodeHealthMonitor from mining_dashboard.service.health.p2pool_heal import P2PoolPeerHealer @@ -217,6 +218,9 @@ def __init__(self, state_manager, proxy_client, xvb_client): self.tor_healer = TorEgressHealer( self.docker_control, notify=self.alert_service.tor_heal_alert ) + self.monerod_redial = MonerodRedial( + self.docker_control, audit=self._audit_monerod_restart, enabled=monero_is_local() + ) # Tari chain health (#2464): a live, reachable node that stopped following the chain (stale # tip, no peers, behind the explorer). Detection and alert only; the alert rides the same # always-on sender as the tor-heal note. @@ -272,6 +276,11 @@ def __init__(self, state_manager, proxy_client, xvb_client): self.miner_released = bool(self.latest_data.get("miner_released", False)) self._restore_sync_gate() + async def _audit_monerod_restart(self, reason, status): + await self._record_audit_event( + "health", "monerod-redial", "restart", status, f"monerod {reason}" + ) + def _observe_monero(self, monero_sync): monero_sync["health"] = self.monero_chain.observe(monero_sync, local=monero_is_local()) self.latest_data["tor_heal"] = tor_heal_status(self.tor_healer) diff --git a/dashboard/mining_dashboard/service/health/monero_health.py b/dashboard/mining_dashboard/service/health/monero_health.py index d081eebead..088c88abd0 100644 --- a/dashboard/mining_dashboard/service/health/monero_health.py +++ b/dashboard/mining_dashboard/service/health/monero_health.py @@ -11,9 +11,9 @@ - **stalled** best height unchanged for :data:`STALLED_SEC`. Monero targets 2-minute blocks, so 30 minutes without one is a stuck node, not a slow interval. -Either is ``red`` with the numbers in the reason. This monitor detects and alerts; it restarts -nothing. A remote node (``monero.mode: remote``) has no peer or sync verdict we can trust, so its -verdict says peers are not visible rather than guessing. +Either is ``red`` with the numbers in the reason. This monitor only detects and alerts; +``monerod_redial`` acts on the peerless verdict. A remote node (``monero.mode: remote``) has no +peer or sync verdict we can trust, so its verdict says peers are not visible rather than guessing. """ import time diff --git a/dashboard/mining_dashboard/service/health/monerod_redial.py b/dashboard/mining_dashboard/service/health/monerod_redial.py new file mode 100644 index 0000000000..b975683604 --- /dev/null +++ b/dashboard/mining_dashboard/service/health/monerod_redial.py @@ -0,0 +1,136 @@ +import asyncio +import logging +import time + +from mining_dashboard.collector.containers import get_container_health + +logger = logging.getLogger("MonerodRedial") + +CHECK_INTERVAL_SEC = 60 +REDIAL_SETTLE_SEC = 300 +WATCHDOG_GRACE_SEC = 300 +COOLDOWN_SEC = 30 * 60 +DAILY_CAP = 3 +DAY_SEC = 24 * 60 * 60 +MONEROD_STOP_GRACE_SEC = 60 +MONEROD_STOP_REQUEST_TIMEOUT_SEC = 90 +MONEROD_START_REQUEST_TIMEOUT_SEC = 60 +MONEROD_START_ATTEMPTS = 3 +MONEROD_START_RETRY_DELAY_SEC = 5 + + +class MonerodRedial: + def __init__(self, docker_control, audit=None, enabled=True, clock=time.monotonic): + self.enabled = enabled + self._docker = docker_control + self._audit = audit + self._clock = clock + self._last_check = None + self._tor_started = None + self._monerod_started = None + self._pending_tor_start = None + self._settle_since = None + self._peerless_since = None + self._restarts = [] + self._warned_cap = False + + async def check(self, verdict) -> None: + if not self.enabled: + return + now = self._clock() + if self._last_check is not None and now - self._last_check < CHECK_INTERVAL_SEC: + return + self._last_check = now + try: + await self._cycle(now, verdict or {}) + except Exception as exc: + logger.warning("monerod re-dial cycle failed (%s)", type(exc).__name__) + + async def _cycle(self, now, verdict) -> None: + states = await get_container_health() + tor = states.get("tor", {}) + monerod = states.get("monerod", {}) + tor_started = tor.get("started_at") + if tor_started is not None: + if self._tor_started is not None and tor_started > self._tor_started: + self._pending_tor_start = tor_started + self._tor_started = tor_started + if not monerod.get("running"): + self._reset_clocks() + self._pending_tor_start = None + return + peers = verdict.get("peers_out") if verdict.get("peers_visible") else None + monerod_started = monerod.get("started_at") + if monerod_started != self._monerod_started: + self._monerod_started = monerod_started + self._settle_since = None + tor_ready = bool(tor.get("running")) and tor.get("health") == "healthy" + if not tor_ready: + self._reset_clocks() + return + if verdict.get("peerless"): + self._peerless_since = self._peerless_since if self._peerless_since is not None else now + else: + self._peerless_since = None + if peers: + self._pending_tor_start = None + if self._pending_tor_start is not None and peers == 0: + self._settle_since = self._settle_since if self._settle_since is not None else now + else: + self._settle_since = None + if self._settle_since is not None and now - self._settle_since >= REDIAL_SETTLE_SEC: + await self._restart(now, "tor-start") + elif self._peerless_since is not None and now - self._peerless_since >= WATCHDOG_GRACE_SEC: + await self._restart(now, "peerless") + + def _reset_clocks(self): + self._settle_since = None + self._peerless_since = None + + async def _restart(self, now, reason) -> None: + self._restarts = [t for t in self._restarts if now - t < DAY_SEC] + if len(self._restarts) >= DAILY_CAP: + if not self._warned_cap: + self._warned_cap = True + logger.warning( + "monerod is still peerless after %d automatic restarts in 24 hours; no more " + "automatic action. Check Tor with './pithead tor-recover check' and restart " + "monerod by hand: './pithead restart monerod'.", + DAILY_CAP, + ) + return + if self._restarts and now - self._restarts[-1] < COOLDOWN_SEC: + return + self._restarts.append(now) + self._warned_cap = False + self._pending_tor_start = None + self._reset_clocks() + logger.warning( + "Restarting monerod to re-dial its peers through Tor (%s, %d/%d in 24 hours).", + "Tor restarted and monerod has no peers" + if reason == "tor-start" + else "no outgoing peers beyond the health bound", + len(self._restarts), + DAILY_CAP, + ) + stopped = await self._docker.stop( + "monerod", + stop_timeout=MONEROD_STOP_GRACE_SEC, + request_timeout=MONEROD_STOP_REQUEST_TIMEOUT_SEC, + ) + started = False + for attempt in range(MONEROD_START_ATTEMPTS): + if attempt: + await asyncio.sleep(MONEROD_START_RETRY_DELAY_SEC) + started = await self._docker.start( + "monerod", request_timeout=MONEROD_START_REQUEST_TIMEOUT_SEC + ) + if started: + break + if not (stopped and started): + logger.warning( + "monerod restart could not be fully issued; if the node stays peerless, run " + "'./pithead restart monerod'." + ) + if self._audit is not None: + await self._audit(reason, "applied" if stopped and started else "failed") diff --git a/dashboard/tests/service/health/test_monerod_redial.py b/dashboard/tests/service/health/test_monerod_redial.py new file mode 100644 index 0000000000..e3e5d2fc3f --- /dev/null +++ b/dashboard/tests/service/health/test_monerod_redial.py @@ -0,0 +1,225 @@ +import pytest + +from mining_dashboard.service.health import monerod_redial as mr +from mining_dashboard.service.health.monerod_redial import MonerodRedial + +TARGET = "mining_dashboard.service.health.monerod_redial" + + +class _Docker: + def __init__(self, ok=True): + self.calls = [] + self.ok = ok + + async def stop(self, container, **kwargs): + self.calls.append(("stop", container)) + return self.ok + + async def start(self, container, **kwargs): + self.calls.append(("start", container)) + return self.ok + + +async def _no_sleep(_): + return None + + +class _Rig: + def __init__(self, monkeypatch, enabled=True, ok=True): + self.t = 1000.0 + self.docker = _Docker(ok) + self.audits = [] + self.tor = {"running": True, "health": "healthy", "started_at": 100.0} + self.monerod = {"running": True, "started_at": 50.0} + self.redial = MonerodRedial( + self.docker, audit=self._audit, enabled=enabled, clock=lambda: self.t + ) + + async def health(): + return {"tor": self.tor, "monerod": self.monerod} + + monkeypatch.setattr(f"{TARGET}.get_container_health", health) + + async def _audit(self, reason, status): + self.audits.append((reason, status)) + + async def step(self, peers_out=0, peerless=False, seconds=mr.CHECK_INTERVAL_SEC): + self.t += seconds + await self.redial.check( + {"peers_visible": peers_out is not None, "peers_out": peers_out, "peerless": peerless} + ) + + async def run(self, seconds, **verdict): + end = self.t + seconds + while self.t < end: + await self.step(**verdict) + + @property + def restarts(self): + return self.docker.calls.count(("stop", "monerod")) + + +@pytest.mark.asyncio +async def test_external_tor_start_redials_peerless_monerod_once(monkeypatch): + rig = _Rig(monkeypatch) + await rig.step(peers_out=8) + rig.tor["started_at"] = 900.0 + await rig.run(mr.REDIAL_SETTLE_SEC + mr.CHECK_INTERVAL_SEC, peers_out=0) + assert rig.docker.calls == [("stop", "monerod"), ("start", "monerod")] + assert rig.audits == [("tor-start", "applied")] + await rig.run(mr.COOLDOWN_SEC * 2, peers_out=0) + assert rig.restarts == 1 + + +@pytest.mark.asyncio +async def test_stale_peers_while_tor_boots_do_not_cancel_the_redial(monkeypatch): + rig = _Rig(monkeypatch) + await rig.step(peers_out=8) + rig.tor.update(started_at=900.0, health="starting") + await rig.step(peers_out=6) + rig.tor["health"] = "healthy" + await rig.run(mr.REDIAL_SETTLE_SEC + mr.CHECK_INTERVAL_SEC * 2, peers_out=0) + assert rig.restarts == 1 + assert rig.audits == [("tor-start", "applied")] + + +@pytest.mark.asyncio +async def test_no_redial_before_tor_reports_a_circuit(monkeypatch): + rig = _Rig(monkeypatch) + await rig.step(peers_out=8) + rig.tor.update(started_at=900.0, health="starting") + await rig.run(mr.REDIAL_SETTLE_SEC * 3, peers_out=0) + assert rig.restarts == 0 + rig.tor["health"] = "healthy" + await rig.run(mr.REDIAL_SETTLE_SEC + mr.CHECK_INTERVAL_SEC, peers_out=0) + assert rig.restarts == 1 + + +@pytest.mark.asyncio +async def test_monerod_that_recovers_by_itself_is_left_alone(monkeypatch): + rig = _Rig(monkeypatch) + await rig.step(peers_out=8) + rig.tor["started_at"] = 900.0 + await rig.step(peers_out=0) + await rig.run(mr.REDIAL_SETTLE_SEC, peers_out=5) + await rig.run(mr.REDIAL_SETTLE_SEC * 3, peers_out=0) + assert rig.restarts == 0 + + +@pytest.mark.asyncio +async def test_monerod_restarted_after_tor_gets_its_own_settle_window(monkeypatch): + rig = _Rig(monkeypatch) + await rig.step(peers_out=8) + rig.tor["started_at"] = 900.0 + await rig.run(mr.REDIAL_SETTLE_SEC - mr.CHECK_INTERVAL_SEC * 2, peers_out=0) + rig.monerod["started_at"] = 950.0 + await rig.run(mr.REDIAL_SETTLE_SEC - mr.CHECK_INTERVAL_SEC, peers_out=0) + assert rig.restarts == 0 + await rig.run(mr.CHECK_INTERVAL_SEC * 3, peers_out=0) + assert rig.restarts == 1 + + +@pytest.mark.asyncio +async def test_monerod_restarted_after_tor_that_gets_peers_is_left_alone(monkeypatch): + rig = _Rig(monkeypatch) + await rig.step(peers_out=8) + rig.tor["started_at"] = 900.0 + rig.monerod["started_at"] = 950.0 + await rig.step(peers_out=0) + await rig.run(mr.REDIAL_SETTLE_SEC * 3, peers_out=4) + assert rig.restarts == 0 + + +@pytest.mark.asyncio +async def test_start_that_fails_is_retried(monkeypatch): + rig = _Rig(monkeypatch) + starts = iter([False, False, True]) + + async def start(container, **kwargs): + rig.docker.calls.append(("start", container)) + return next(starts) + + rig.docker.start = start + monkeypatch.setattr(f"{TARGET}.asyncio.sleep", _no_sleep) + await rig.run(mr.WATCHDOG_GRACE_SEC + mr.CHECK_INTERVAL_SEC * 2, peers_out=0, peerless=True) + assert rig.docker.calls.count(("start", "monerod")) == 3 + assert rig.audits == [("peerless", "applied")] + + +@pytest.mark.asyncio +async def test_stopped_monerod_is_never_started(monkeypatch): + rig = _Rig(monkeypatch) + await rig.step(peers_out=8) + rig.tor["started_at"] = 900.0 + rig.monerod["running"] = False + await rig.run(mr.REDIAL_SETTLE_SEC * 3, peers_out=0, peerless=True) + assert rig.docker.calls == [] + + +@pytest.mark.asyncio +async def test_disabled_for_a_remote_node(monkeypatch): + rig = _Rig(monkeypatch, enabled=False) + await rig.run(mr.WATCHDOG_GRACE_SEC * 3, peers_out=0, peerless=True) + assert rig.docker.calls == [] + + +@pytest.mark.asyncio +async def test_peerless_verdict_restarts_after_the_grace(monkeypatch): + rig = _Rig(monkeypatch) + await rig.run(mr.WATCHDOG_GRACE_SEC - mr.CHECK_INTERVAL_SEC, peers_out=0, peerless=True) + assert rig.restarts == 0 + await rig.run(mr.CHECK_INTERVAL_SEC * 2, peers_out=0, peerless=True) + assert rig.restarts == 1 + assert rig.audits == [("peerless", "applied")] + + +@pytest.mark.asyncio +async def test_peerless_watchdog_waits_for_a_healthy_tor(monkeypatch): + rig = _Rig(monkeypatch) + rig.tor["health"] = "unhealthy" + await rig.run(mr.WATCHDOG_GRACE_SEC * 3, peers_out=0, peerless=True) + assert rig.restarts == 0 + rig.tor["health"] = "healthy" + await rig.step(peers_out=0, peerless=True) + assert rig.restarts == 0 + await rig.run(mr.WATCHDOG_GRACE_SEC + mr.CHECK_INTERVAL_SEC, peers_out=0, peerless=True) + assert rig.restarts == 1 + + +@pytest.mark.asyncio +async def test_tor_health_flap_restarts_the_peerless_grace(monkeypatch): + rig = _Rig(monkeypatch) + await rig.run(mr.WATCHDOG_GRACE_SEC - mr.CHECK_INTERVAL_SEC, peers_out=0, peerless=True) + rig.tor["health"] = "starting" + await rig.step(peers_out=0, peerless=True) + rig.tor["health"] = "healthy" + await rig.step(peers_out=0, peerless=True) + assert rig.restarts == 0 + await rig.run(mr.WATCHDOG_GRACE_SEC + mr.CHECK_INTERVAL_SEC, peers_out=0, peerless=True) + assert rig.restarts == 1 + + +@pytest.mark.asyncio +async def test_cap_lifts_after_a_day(monkeypatch): + rig = _Rig(monkeypatch) + await rig.run(mr.COOLDOWN_SEC * (mr.DAILY_CAP + 2), peers_out=0, peerless=True) + assert rig.restarts == mr.DAILY_CAP + await rig.run(mr.DAY_SEC, peers_out=0, peerless=True) + assert rig.restarts > mr.DAILY_CAP + + +@pytest.mark.asyncio +async def test_cap_warning_is_logged_once(monkeypatch, caplog): + rig = _Rig(monkeypatch) + await rig.run(mr.COOLDOWN_SEC * (mr.DAILY_CAP + 4), peers_out=0, peerless=True) + assert rig.restarts == mr.DAILY_CAP + assert sum("no more automatic action" in r.getMessage() for r in caplog.records) == 1 + + +@pytest.mark.asyncio +async def test_unconfirmed_restart_is_audited_failed(monkeypatch): + rig = _Rig(monkeypatch, ok=False) + monkeypatch.setattr(f"{TARGET}.asyncio.sleep", _no_sleep) + await rig.run(mr.WATCHDOG_GRACE_SEC + mr.CHECK_INTERVAL_SEC * 2, peers_out=0, peerless=True) + assert rig.audits == [("peerless", "failed")] + assert rig.docker.calls.count(("start", "monerod")) == mr.MONEROD_START_ATTEMPTS diff --git a/docs/architecture.md b/docs/architecture.md index 35dd2f59cc..a44531ab0e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,7 +20,7 @@ directly instead. | 5 | **Tor** | Provides SOCKS5 proxies and hidden services (onion addresses) for the other containers. | | 6 | **Dashboard** | The web monitoring UI and the algorithmic switching engine. | | 7 | **Docker Proxy** | A **read-only** proxy onto the Docker socket so the dashboard can read container stats/logs — no write access. | -| 8 | **Docker Control** | A second, minimal socket proxy scoped to **only** `start`/`stop` (nothing else — not create/kill/exec/reads), so the dashboard can reject workers when a node is down (Issue #31), hold p2pool + xmrig-proxy until the chains finish syncing (Issue #35), switch a clearnet-syncing node back to Tor once it's synced (Issue #234), and, opt-in via `dashboard.fail_closed`, hold p2pool + xmrig-proxy again on an unrecoverable dashboard health failure (Issue #490), restart `tor` only after the opt-in egress healer (`tor.auto_heal`) exhausts circuit refreshes, and restart local `monerod` after that real Tor restart. NEWNYM requests go through the audited host control spool, which keeps Tor’s control cookie inside the Tor container. Kept separate so its write grant can't widen the read-only proxy. | +| 8 | **Docker Control** | A second, minimal socket proxy scoped to **only** `start`/`stop` (nothing else — not create/kill/exec/reads), so the dashboard can reject workers when a node is down (Issue #31), hold p2pool + xmrig-proxy until the chains finish syncing (Issue #35), switch a clearnet-syncing node back to Tor once it's synced (Issue #234), and, opt-in via `dashboard.fail_closed`, hold p2pool + xmrig-proxy again on an unrecoverable dashboard health failure (Issue #490), restart `tor` only after the opt-in egress healer (`tor.auto_heal`) exhausts circuit refreshes, restart local `monerod` after that real Tor restart, and restart a local `monerod` that stays peerless after any Tor start or beyond the peerless bound (three per 24 hours). NEWNYM requests go through the audited host control spool, which keeps Tor’s control cookie inside the Tor container. Kept separate so its write grant can't widen the read-only proxy. | | 9 | **Caddy** | A reverse proxy that serves the dashboard over HTTPS (automatic local TLS) on the LAN. | | 10 | **Monero Wallet-RPC** (`wallet-rpc`) | Opt-in: runs only when `monero.view_key` is set (compose profile `payout_confirm`). A view-only `monero-wallet-rpc` against the local node, so the dashboard can confirm P2Pool payouts on-chain. See [Dashboard › Payout confirmation](dashboard.md#payout-confirmation). | | 11 | **Tari Console Wallet** (`tari-wallet`) | Opt-in: runs only when `tari.view_key` is set (compose profile `tari_payout_confirm`). A view-only `minotari_console_wallet` against the local Tari node, confirming merge-mine payouts on-chain. See [Dashboard › Payout confirmation](dashboard.md#payout-confirmation). | diff --git a/docs/configuration.md b/docs/configuration.md index 1f396f5b76..dda2d4914d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -283,7 +283,7 @@ the desired value is not presented as proof of what the still-running services u | `tari.mem_limit` | `auto` | Upper limit on the Tari container's memory, so a runaway Tari restarts cleanly on its own instead of dragging down the whole host. `auto` picks a safe size for your machine. Leave it unless you want to give Tari less RAM (to free it for other apps) or more (if it ever restarts too often). Accepts any Docker memory value, e.g. `"8g"`. Local mode only: with `tari.mode: remote` or `off` there is no container to cap and the key is ignored. | | `p2pool.data_dir` | `auto` | Where P2Pool data lives on the host. `auto` = `./data/p2pool`. | | `tor.data_dir` | `auto` | Where Tor's state (including onion keys) lives. `auto` = `./data/tor`. | -| `tor.auto_heal` | `false` _(off)_ | Privacy-relevant, DIY default off; appliances enable it when absent. Enabling it delegates a limited circuit-refresh capability to the dashboard: isolated Tor SOCKS probes to two independent targets must fail for 15 minutes before it requests recovery. The host cannot verify those HTTPS results itself, so it independently limits NEWNYM to twice per 24 hours, 30 minutes apart. Persistent failure permits one disruptive final action: a Tor container restart and local Monero re-dial, or, when history is saturated, host-gated `tor-recover apply`. State recovery backs up the state and resets guards only with the exact saturated signature, corroborating evidence, onion-key verification, the mutation lock and a persistent six-hour cooldown. The monitor's three-attempt outage budget resets after two successful probes, or when the Tor container starts without the heal having restarted it (an operator, `./pithead` or Docker restart opens a fresh outage window); otherwise it warns. Its circuit refreshes and state recovery go through the host control runner, and a refresh must be confirmed before the final restart, so the heal also needs `dashboard.control.enabled: true`, which the appliance sets only when a dashboard login exists; without it the heal only probes and logs warnings, and sends a recovery note when egress returns. See [Operations › Troubleshooting](operations.md#troubleshooting). | +| `tor.auto_heal` | `false` _(off)_ | Privacy-relevant, DIY default off; appliances enable it when absent. Enabling it delegates a limited circuit-refresh capability to the dashboard: isolated Tor SOCKS probes to two independent targets must fail for 15 minutes before it requests recovery. The host cannot verify those HTTPS results itself, so it independently limits NEWNYM to twice per 24 hours, 30 minutes apart. Persistent failure permits one disruptive final action: a Tor container restart and local Monero re-dial (independent of this key, the dashboard also re-dials a peerless local monerod after any Tor start, bounded to three restarts per 24 hours; see [Operations › Troubleshooting](operations.md#troubleshooting)), or, when history is saturated, host-gated `tor-recover apply`. State recovery backs up the state and resets guards only with the exact saturated signature, corroborating evidence, onion-key verification, the mutation lock and a persistent six-hour cooldown. The monitor's three-attempt outage budget resets after two successful probes, or when the Tor container starts without the heal having restarted it (an operator, `./pithead` or Docker restart opens a fresh outage window); otherwise it warns. Its circuit refreshes and state recovery go through the host control runner, and a refresh must be confirmed before the final restart, so the heal also needs `dashboard.control.enabled: true`, which the appliance sets only when a dashboard login exists; without it the heal only probes and logs warnings, and sends a recovery note when egress returns. See [Operations › Troubleshooting](operations.md#troubleshooting). | | `dashboard.data_dir` | `auto` | Where the dashboard's database lives. `auto` = `./data/dashboard`, unless the four other `*.data_dir` all point under one parent directory — then the dashboard joins them at `/dashboard`. `upgrade`/`apply` moves the live database automatically only from the old in-install default. A confirmed change to an explicit path copies and verifies the database, including the payout-wallet alarm baseline, and leaves the old copy in place; a non-empty target refuses the change rather than guessing (see [Data directories](#data-directories)). | | `dashboard.check_for_updates` | `true` _(on)_ | The dashboard periodically asks GitHub whether a newer Pithead release exists and, if so, shows a header badge linking to it (e.g. "New release v1.4.0 available"). Notify-only: it never updates anything; you upgrade with `./pithead upgrade` on your own terms. On by default because the check is routed over Tor (the same bridge SOCKS as the XvB fetch, `socks5h` so the DNS lookup goes through Tor too), so GitHub sees a Tor exit, not your IP. It's cached (hourly) and fails silently offline. The same flag also covers the per-worker [RigForge new-release badge](workers.md#rigforge-new-release-badge) — one more hourly, Tor-routed fetch of the latest RigForge release, compared against every rig's reported version. Set to `false` to opt out of both. See [Privacy › Runtime egress](privacy.md#runtime-egress). | | `network.subnet` | `172.28.0.0/24` | The private Docker bridge the stack's containers run on. Change it only if install fails with `Pool overlaps with other one on this address space`, i.e. your host already uses `172.28.0.0/24` for another Docker network or interface. Must be a free `X.Y.Z.0/24` block (e.g. `"172.30.0.0/24"`); the services keep their fixed host octets (`.25`–`.31`) within it, so the structured addressing the dashboard and the worker SSRF guard rely on is preserved. | diff --git a/docs/dev/repo-map.md b/docs/dev/repo-map.md index a05f1d1f99..3d277ec6ff 100644 --- a/docs/dev/repo-map.md +++ b/docs/dev/repo-map.md @@ -164,7 +164,7 @@ Explicit saturated Tor circuit-history recovery is in `02e-tor-recovery.sh`; its read-only authenticated bootstrap probe is `build/tor/recovery-diagnose.sh`; the dashboard's clearnet healer stays in `service/health/tor_heal.py`, with host history observations and recovery results in `service/health/tor_heal_history.py`. -The P2Pool zero-peer watchdog is `service/health/p2pool_heal.py`. +The P2Pool zero-peer watchdog is `service/health/p2pool_heal.py`. The peerless-monerod watchdog and the re-dial after any Tor start are `service/health/monerod_redial.py`. The automatic `tor-recover` control wrapper is `48b-control-tor-recover.sh`; it calls the same host-gated recovery as the CLI. diff --git a/docs/dev/testing-strategy.md b/docs/dev/testing-strategy.md index 3f40e9cc1e..0abd9c8233 100644 --- a/docs/dev/testing-strategy.md +++ b/docs/dev/testing-strategy.md @@ -233,7 +233,7 @@ The deploy-time axes — each changes a real runtime path. Full table and assert | Configured Tari RPC unreachable for 15 minutes, including after dashboard restart → rejects when required; optional Tari keeps mining Monero; alerts either way | `tari_down` | 1 ✅ · 3 ▶ | | Recovery hysteresis — readmit only after every required node stable `NODE_RECOVERY_AFTER_SEC` | reachable again | 1 ✅ | | Transient blip / never-reachable Monero → **no** false reject | debounce / `ever_up` | 1 ✅ | -| Monero node **isolated or not advancing** — the "at tip, with peers" contract for monerod (#2499): the real peer counts (the published RPC is restricted and answers 0, so an in-container helper reads the loopback-only admin RPC, #2921), `MoneroChainHealth` (0 outgoing peers `NODE_STALE_AFTER_SEC`, no new height 30 min), the card's Node Health / Peers / Height Moved, `node_down`-toggle alerts for each condition, `build/monero/healthcheck.sh` failing past `MONERO_HEALTH_PEERLESS_SEC`, doctor peers/tip age + FAIL, a `monero chain` status line, and the tier-4 strand leg (`run.sh --monero-stranded`) | red on both conditions with the numbers; remote node: no verdict | 1 ✅ (`test_monero_health.py`, `test_alert_service_monero_health.py`, `test_monero_client.py`, `monero-health-card.test.mjs`; the LAN "Monero node offline" banner built from these verdicts and the Tor heal state: `test_node_alert.py`, `test_node_alert_view.py`, `nodealert.test.mjs`, and `tests/browser/node-alert.test.mjs` in both themes; healthcheck/doctor/status: `tests/stack/test-monero-chain.sh` covers restricted vs real zero vs no reading in the healthcheck, helper and doctor; `standalone/test_tor_recovery_info.sh` in tor-recover; `test_containers.py` the fresh/stale/malformed observation; `selftest-monero-peer-wait.sh` the peer predicates, the peer-wait capture and the RPC-boundary rows; `selftest-monero-p2p.sh` the bounded P2P advertisement decoder and non-secret failure diagnostics) · 4 ▶ (`run.sh --monero-stranded`, which checks the actual P2P advertisement, RPC boundary, current-run observation after deployment and restart, and the live tor-recover peer provider; bench-ci phase `monero-stranded`, about an hour, opt-in; KVM `provision` also runs the native Quadlet cold-start/restart RPC fixture) | +| Monero node **isolated or not advancing** — the "at tip, with peers" contract for monerod (#2499): the real peer counts (the published RPC is restricted and answers 0, so an in-container helper reads the loopback-only admin RPC, #2921), `MoneroChainHealth` (0 outgoing peers `NODE_STALE_AFTER_SEC`, no new height 30 min), the card's Node Health / Peers / Height Moved, `node_down`-toggle alerts for each condition, `build/monero/healthcheck.sh` failing past `MONERO_HEALTH_PEERLESS_SEC`, doctor peers/tip age + FAIL, a `monero chain` status line, and the tier-4 strand leg (`run.sh --monero-stranded`) | red on both conditions with the numbers; remote node: no verdict | 1 ✅ (`test_monero_health.py`, `test_monerod_redial.py` (re-dial after an external Tor start, the peerless watchdog, cooldown and cap), `test_alert_service_monero_health.py`, `test_monero_client.py`, `monero-health-card.test.mjs`; the LAN "Monero node offline" banner built from these verdicts and the Tor heal state: `test_node_alert.py`, `test_node_alert_view.py`, `nodealert.test.mjs`, and `tests/browser/node-alert.test.mjs` in both themes; healthcheck/doctor/status: `tests/stack/test-monero-chain.sh` covers restricted vs real zero vs no reading in the healthcheck, helper and doctor; `standalone/test_tor_recovery_info.sh` in tor-recover; `test_containers.py` the fresh/stale/malformed observation; `selftest-monero-peer-wait.sh` the peer predicates, the peer-wait capture and the RPC-boundary rows; `selftest-monero-p2p.sh` the bounded P2P advertisement decoder and non-secret failure diagnostics) · 4 ▶ (`run.sh --monero-stranded`, which checks that the dashboard watchdog restarts the stranded monerod unattended, that the dashboard restarts a monerod kept peerless after an external restart of the tor container, the actual P2P advertisement, RPC boundary, current-run observation after deployment and restart, and the live tor-recover peer provider; bench-ci phase `monero-stranded`, about an hour, opt-in; KVM `provision` also runs the native Quadlet cold-start/restart RPC fixture) | | Monero node reachable but **out of sync** — the post-tor-restart 0-peer strand (#972): raw `synchronized` passthrough, debounced stale flag, alert via the `node_down` toggle, monerod restarted alongside an actual tor container restart (compose `depends_on: restart` + the final #424 auto-heal step), `restart monerod` leg, doctor WARN | `synchronized: false` ≥ `NODE_STALE_AFTER_SEC` after being in sync once | 1 ✅ (client/data_service/alert/tor_heal pytest, `tests/stack` doctor + restart + compose invariants) · 2 ✅ (flag over the wire) · 4 (real strand + re-peer needs the bench) | | Double outage; readmit only after both required nodes recover | both down → both up | 1 ✅ (added) · 3 ▶ | | #35 latch × #31 failover coexist after release | down post-release | 1 ✅ (added) · 3 ▶ | diff --git a/docs/operations.md b/docs/operations.md index 1efd4080c2..f200b118d7 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1032,6 +1032,12 @@ check) WARNs on the live state. Fix: Stack operations don't need the manual step: compose restarts monerod automatically whenever it restarts or recreates tor (`up`, `apply`, `upgrade`, `restart tor`), and the final `tor.auto_heal` container restart does the same. NEWNYM does not restart monerod. (#972) +The dashboard also covers a Tor start it did not see happen, with or without `tor.auto_heal` +(#4076). It notes every start of the tor container (an operator, `./pithead`, Docker or an +update). Once Tor reports healthy (bootstrapped), a monerod that has held 0 outgoing peers for five +minutes is restarted, once per Tor start. A monerod that was itself restarted in the meantime (by +compose or the Tor heal) gets its own five minutes first. + Local node only. With `monero.mode: remote` there is no `monerod` here to restart and doctor's Monero sync check skips, so a stranded node is the remote host's problem to detect and fix. @@ -1083,12 +1089,20 @@ alerts and recovers even while peer counts are unavailable; only the peerless ed counts. Remote and unreachable nodes have no chain verdict. The container's `docker inspect` health becomes `unhealthy` after 600 seconds without outgoing peers (`MONERO_HEALTH_PEERLESS_SEC`) or 30 minutes without height progress; it still prints its peer -counts, so the card keeps reading them. The stack only reports: it restarts nothing. Fix: +counts, so the card keeps reading them. A local monerod whose verdict stays peerless for five more +minutes, while Tor reports healthy, is restarted by the dashboard (#4076). +Restarts are spaced at least 30 minutes apart, capped at three per rolling 24 hours, logged +(`Restarting monerod to re-dial its peers through Tor`) and recorded in the audit log. At the cap +the dashboard logs once that it has stopped, and the manual fix stays: ```bash ./pithead restart monerod ``` +Only a running local monerod is cycled: a stopped one (held by the LAN-access guard on a DIY host, see #2749) +is never started, and a remote node is never touched. The cap and spacing are held in the dashboard's +memory, so a dashboard restart clears them. + The clocks start when the dashboard first sees the node and again whenever it stops answering, so a dashboard restart or a monerod restart never reads as a stall; a node that does not answer shows no verdict here, because the node-down alert already covers it. With `monero.mode: remote` the peers of the remote node are not visible to this stack, so the diff --git a/tests/integration/lib/run-monero-stranded.sh b/tests/integration/lib/run-monero-stranded.sh index dbe83a6291..4ce9afd711 100644 --- a/tests/integration/lib/run-monero-stranded.sh +++ b/tests/integration/lib/run-monero-stranded.sh @@ -1,20 +1,11 @@ # shellcheck shell=bash : "${INTEGRATION_RUN_SUITE:?source via the suite runner}" -# --- Monero stranded leg (--monero-stranded, #2499) -------------------------- -# A live monerod with no peers must stop reading healthy on every layer. Like the Tari leg (#2464), an -# iptables rule in monerod's own network namespace drops its traffic to the tor container, so the RPC -# keeps answering and the process stays up while its outgoing peers die. Asserts, on the real clocks -# (monero_health.py, build/monero/healthcheck.sh, peers read from the in-container helper, #2921): the first 0-outgoing-peer reading (latency -# recorded); then within the 10-minute bound plus a poll, the verdict red with the numbers, the -# container's docker health unhealthy, doctor non-zero, status naming it, the card's payload red, and -# the alert at a loopback webhook; no automatic restart; then, the rule removed, the operator's fix -# (`pithead restart monerod`: the dead SOCKS sockets do not recover on their own, job 1789 waited -# 40 minutes) and every layer returns to green, with the recovery note. Opt-in, about 40 minutes: never part of a preset. -# The rule carries a fixed comment, dies with monerod's namespace, and is removed by an EXIT trap too. MONERO_STRAND_TAG="pithead-e2e-fault-monero-stranded" MONERO_POLL_SLACK=180 # a dashboard poll, the healthcheck's 30 s x 3 retries, and the harness's sampling MONERO_DISCONNECT_MAX=1500 +MONERO_WATCHDOG_MAX=2400 +MONERO_TOR_REDIAL_MAX=1500 MONERO_HOOK_PORT=18198 MONERO_HOOK_LOG=/tmp/pithead-e2e-monero-alerts.log @@ -54,6 +45,7 @@ monero_strand_abort() { monero_health_field() { jq_get "$(api_state)" ".monero.health.$1"; } _pred_monero_level() { [ "$(monero_health_field level)" = "$1" ]; } +_pred_monero_red_peerless() { [ "$(monero_health_field level)" = red ] && monero_health_field reasons | grep -q "outgoing peers for"; } # monerod's real peer counts (#2921), from the fixed in-container helper that reads the admin RPC on the # container's loopback: the published RPC is restricted and answers 0 for every count. Empty when the # helper gives no reading, which no predicate below reads as zero or as peers. @@ -163,6 +155,7 @@ assert_monero_rpc_boundary() { "$(rx 'u=$(grep -E "^MONERO_NODE_USERNAME=" .env | cut -d= -f2-); p=$(grep -E "^MONERO_NODE_PASSWORD=" .env | cut -d= -f2-); curl -fsS --max-time 8 --digest -u "$u:$p" http://127.0.0.1:18081/get_info | jq -c "{restricted, o: .outgoing_connections_count}"' 2>/dev/null)" '"restricted":true' } +_pred_monerod_restarted_since() { [ "$(monero_started_at)" != "$1" ]; } monero_started_at() { rx "docker inspect -f '{{.State.StartedAt}}' monerod" 2>/dev/null; } monero_strand_state() { echo "verdict '$(monero_health_field level)', peers $(monero_health_field peers_out) out / $(monero_health_field peers_in) in, docker health '$(rx "docker inspect -f '{{.State.Health.Status}}' monerod" 2>/dev/null)'"; } @@ -225,6 +218,25 @@ run_monero_stranded() { trap monero_strand_abort EXIT started="$(monero_started_at)" + it_step "external Tor start: restart the tor container outside the stack's own operations, and keep monerod stranded (#4076)…" + rx "docker restart tor" >/dev/null 2>&1 + tor="$(rx "docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' tor" 2>/dev/null | head -n1)" + monero_ns_ipt "-I OUTPUT -d $tor -m comment --comment $MONERO_STRAND_TAG -j DROP" >/dev/null + if wait_for "$MONERO_TOR_REDIAL_MAX" 15 "monerod re-dialled by the dashboard after an external Tor start" _pred_monerod_restarted_since "$started"; then + it_pass "monero-stranded: the dashboard restarted the stranded monerod after an external Tor start, unattended" + else + it_fail "monero-stranded: the dashboard restarts the stranded monerod within ${MONERO_TOR_REDIAL_MAX} s of an external Tor start" "$(monero_strand_state)" + fi + assert_eq "monero-stranded: the Tor-start re-dial is logged once for the owner" \ + "$(rx "docker logs dashboard 2>&1 | grep -c 'Tor restarted and monerod has no peers'" 2>/dev/null)" "1" + monero_strand_remove_all + if wait_for 900 15 "monerod holding outgoing peers after the Tor-start re-dial" _pred_monero_has_peers_sampled; then + it_pass "monero-stranded: monerod holds outgoing peers after the Tor-start re-dial" + else + it_fail "monero-stranded: monerod holds outgoing peers after the Tor-start re-dial" "$(monero_strand_state)" + fi + started="$(monero_started_at)" + it_step "fault: drop monerod -> tor inside monerod's network namespace ($MONERO_STRAND_TAG)…" monero_ns_ipt "-I OUTPUT -d $tor -m comment --comment $MONERO_STRAND_TAG -j DROP" >/dev/null t0=$(now_s) @@ -245,7 +257,7 @@ run_monero_stranded() { fi assert_eq "monero-stranded: tor-recover reads the real fault zero" "$(monero_tor_recovery_out)" "0" # The bound (NODE_STALE_AFTER_SEC, 10 min) runs from the first zero reading; one poll of slack. - if wait_for $((600 + MONERO_POLL_SLACK)) 10 "Monero verdict red" _pred_monero_level red; then + if wait_for $((600 + MONERO_POLL_SLACK)) 10 "Monero verdict red for the peerless reading" _pred_monero_red_peerless; then it_pass "monero-stranded: red $(($(now_s) - ${t_zero:-$t0})) s after the first 0-peer reading: $(monero_health_field reasons)" else it_fail "monero-stranded: red within 10 min of the first 0-peer reading + one poll" "$(monero_strand_state)" @@ -267,21 +279,28 @@ run_monero_stranded() { else it_fail "monero-stranded: the peerless alert left the dashboard" "nothing at the loopback sink" fi - assert_eq "monero-stranded: detection only, monerod was not restarted" "$(monero_started_at)" "$started" + assert_eq "monero-stranded: red alone does not restart monerod" "$(monero_started_at)" "$started" - it_step "recover: remove the rule, then the advised fix (restart monerod); every layer must return to green…" + it_step "recover: nobody restarts monerod; the dashboard watchdog must re-dial it unattended (#4076)…" + t0=$(now_s) + if wait_for "$MONERO_WATCHDOG_MAX" 10 "monerod restarted by the watchdog" _pred_monerod_restarted_since "$started"; then + it_pass "monero-stranded: the watchdog restarted the peerless monerod $(($(now_s) - t0)) s after red, unattended" + else + it_fail "monero-stranded: the watchdog restarts a peerless monerod within ${MONERO_WATCHDOG_MAX} s" "$(monero_strand_state)" + fi + assert_eq "monero-stranded: the restart is logged once for the owner" \ + "$(rx "docker logs dashboard 2>&1 | grep -c 'no outgoing peers beyond the health bound'" 2>/dev/null)" "1" monero_strand_remove_all - pithead restart monerod >/dev/null 2>&1 t0=$(now_s) if wait_for 900 15 "monerod has outgoing peers again after the fix" _pred_monero_has_peers_sampled; then - it_pass "monero-stranded: real outgoing peers returned after the fault was removed and monerod restarted" + it_pass "monero-stranded: real outgoing peers returned after the watchdog restarted monerod" else it_fail "monero-stranded: real outgoing peers returned after recovery" "$(monero_strand_state)" fi if wait_for 1500 15 "Monero verdict green after the fix" _pred_monero_level green; then - it_pass "monero-stranded: green $(($(now_s) - t0)) s after the fault was removed and monerod restarted" + it_pass "monero-stranded: green $(($(now_s) - t0)) s after the watchdog restarted monerod" else - it_fail "monero-stranded: green after the fault was removed and monerod restarted" "$(monero_strand_state)" + it_fail "monero-stranded: green after the watchdog restarted monerod" "$(monero_strand_state)" fi assert_eq "monero-stranded: header clears the Monero chain warning after recovery" \ "$(api_state | jq -r 'any(.badges[]; .text == "Monero chain unhealthy")')" "false" @@ -291,7 +310,7 @@ run_monero_stranded() { it_fail "monero-stranded: docker inspect health is healthy again" "$(monero_strand_state)" fi assert_eq "monero-stranded: the fresh recovery observation belongs to a newer container run" \ - "$(monero_observation | jq -r --argjson before "${observation_before:-null}" '.peers_out > 0 and .monero_run_started > $before.monero_run_started' 2>/dev/null)" "true" + "$(monero_observation | jq -r --argjson before "${observation_before:-null}" '.monero_run_started > $before.monero_run_started' 2>/dev/null)" "true" if [ "$(monero_tor_recovery_out)" -gt 0 ] 2>/dev/null; then it_pass "monero-stranded: tor-recover verifies real peers after recovery" else diff --git a/tests/integration/selftest/selftest-monero-peer-wait.sh b/tests/integration/selftest/selftest-monero-peer-wait.sh index 0eae51c8f0..070be454db 100755 --- a/tests/integration/selftest/selftest-monero-peer-wait.sh +++ b/tests/integration/selftest/selftest-monero-peer-wait.sh @@ -105,6 +105,10 @@ PEERS="" _pred_monero_zero_out && it_fail "no reading is not zero" "zero_out true with no helper output" || it_pass "no reading is not zero" _pred_monero_has_peers && it_fail "no reading is not peers" "has_peers true with no helper output" || it_pass "no reading is not peers" +echo "== the restart predicate compares monerod's start time ==" +_pred_monerod_restarted_since T && it_fail "an unchanged start time is no restart" "restarted true at T" || it_pass "an unchanged start time is no restart" +_pred_monerod_restarted_since OLD && it_pass "a changed start time is a restart" || it_fail "a changed start time is a restart" "restarted false" + echo "== the RPC boundary rows ==" boundary() { assert_monero_rpc_boundary 2>&1; } PEERS='{"outgoing":3,"incoming":0,"white":1,"grey":1}' diff --git a/tests/integration/selftest/selftest-run-modules.sh b/tests/integration/selftest/selftest-run-modules.sh index 715fbc86a6..2012f32777 100755 --- a/tests/integration/selftest/selftest-run-modules.sh +++ b/tests/integration/selftest/selftest-run-modules.sh @@ -13,7 +13,7 @@ actual_modules="$(sed -n 's|^source "$HERE/\(lib/run-[a-z-]*\.sh\)".*|\1|p' "$RO exit 1 } -expected_functions='usage parse_args print_list push_config env_on_box running_services _pred_mining_probe_running assert_mining_probe_ready service_state secret_fingerprint preflight record_manifest run_scenario clearnet_flag_effective restore_firewall_after_clearnet assert_host_claims_spent_sync assert_onion_targets _onion_reachable_external assert_running_state assert_egress_dial_pair public_remotes_in_proc_tcp _pred_tari_payouts_found _pred_payout_wallet_ready _pred_monero_wallet_caught_up assert_payout_wallet_ready assert_tari_payout_scan _lan_probe _lan_flush_rules _lan_strip _lan_capture _lan_probe_open _lan_assert_open assert_lan_guard_live assert_lan_guard_timer_flush _lan_timer_pause _lan_exit_code assert_lan_guard_crash_restart assert_lan_guard_boot_restore assert_lan_guard_boot_failure assert_scenario assert_egress_posture assert_xvb_over_tor assert_metrics_via_caddy assert_doctor_ok assert_share_stats_live assert_telemetry_tables_present assert_current_state box_fstype box_avail_gb box_mode _pred_readiness_monero _pred_readiness_status status_verdict_lines assert_release_readiness lifecycle_gate_snippet retain_lifecycle_gate_samples lifecycle_gate_sample source_image_reconcile_snippet run_source_image_reconcile run_image_permissions wizard_restore_baseline run_cli_wizard_defaults connection_announcements_snippet run_connection_announcements run_restore_dashboard_probe run_reset_restore reset_restore_wait_reboot reset_restore_shutdown_clean reset_restore_wait_empty run_support_bundle _run_lifecycle kept_data_snapshot_snippet kept_chain_files_snippet run_uninstall_round_trip telemetry_rows_diff _pred_status_down _monerod_is _pred_monerod_missing _pred_monerod_unhealthy _pred_monerod_healthy _pred_proxy_stopped _pred_failover_armed _pred_p2pool_running _pred_tor_stopped _pred_tor_healthy _reset_dashboard_services_healthy run_reset_dashboard _rotate_proxy_live_args _rotate_monero_rpc_probe _rotate_proxy_token_accepted _rotate_stratum_auth _rotate_proxy_upstream_active _rotate_rig_accepted _rotate_proxy_accepted_after _rotate_p2pool_monero_live _rotate_new_baks _rotate_cleanup_baks _rotate_abort_restore run_rotate_secrets _rig_active_pool _pred_rig_pool_differs _pred_rig_pool_returned _rig_pool_leg fault_node_down fault_unhealthy fault_missing fault_db_readonly fault_firewall_rollback _gf_flows _gf_down fault_firewall_grandfathered_flow fault_tor_down fault_clock_drift fault_disk_enospc _pred_p2pool_peers _pred_dnswatch_listening fault_p2pool_cold_cache_dns _restore_p2pool_peer_lists run_fault_injection run_fault_injection_maybe p2pool_sidechain_sync_snippet fault_p2pool_sidechain_sync tor_probe_ns_ipt _tor_probe_mining_sample fault_tor_probe_egress _tor_probe_recovered tor_recovery_lock_snapshot_snippet tor_recovery_probe_now_s tor_recovery_healthy_probe p2pool_ns_ipt p2pool_peer_loss_rules p2pool_peer_loss_count p2pool_peer_total p2pool_started_at _pred_p2pool_peerless _pred_p2pool_restarted _pred_p2pool_has_peers _pred_p2pool_rejoin_logged fault_p2pool_peer_loss _await_egress_state fault_firewall_status_alert fault_firewall_boot_restore _set_env_token _spool_write _uuid4 _wait_control_status _remove_control_units run_hardening run_auth_fail_closed _svc_restart_request run_svc_restart rotate_onion_data_dir rotate_onion_key_fingerprint rotate_onion_client_key_fingerprint rotate_onion_env_fingerprint rotate_onion_mining_fingerprint wait_onion_retired rotate_onion_restore run_rotate_onion safety_backup safety_secret_drift_categories safety_restore_exact safety_rollback_if_failed safety_abort_restore arm_safety_abort_restore reset_dashboard_remove_blocker reset_dashboard_cleanup safety_cleanup restore_baseline summary run_rigforge_integration assert_subnet_live run_subnet_scenario _worker_apply _max_temp_round_trip _restore_rig_control_baseline run_rigforge_control _pred_rig_present run_rigforge_reverse _rig_control_apply _rig_control_await _pred_feed_maxt _rig_direct_summary _reverse_feed_failure_detail run_rigforge_rollback it_alert_refused _alert_egress_overlay _alert_egress_verdict run_alert_egress_smoke _mm_rows _mm_cleanup run_mergemine_submit tari_ns_ipt tari_strand_count tari_strand_drops tari_strand_remove_all tari_hook_start tari_hook_stop tari_restore_config tari_strand_abort tari_health_field _pred_tari_level _pred_tari_at_least_amber _pred_tari_zero_peers _pred_tari_alerted _pred_tari_recovery_alerted tari_started_at tari_strand_state run_tari_stranded monero_ns_ipt monero_strand_count monero_strand_remove_all monero_hook_start monero_hook_stop monero_restore_config monero_strand_abort monero_health_field _pred_monero_level monero_peer_counts monero_out_peers monero_tor_recovery_out monero_observation _pred_monero_zero_out _pred_monero_has_peers _pred_monerod_docker_health _pred_monero_alerted _pred_monero_recovery_alerted monero_peer_sample _pred_monero_has_peers_sampled monero_peer_wait_diagnostics _monero_http_code assert_monero_p2p_advertisement assert_monero_rpc_boundary monero_started_at monero_strand_state run_monero_stranded _mml_fact _mml_target_row _mml_inspect _mml_ip _mml_cleanup run_mergemine_localnet' +expected_functions='usage parse_args print_list push_config env_on_box running_services _pred_mining_probe_running assert_mining_probe_ready service_state secret_fingerprint preflight record_manifest run_scenario clearnet_flag_effective restore_firewall_after_clearnet assert_host_claims_spent_sync assert_onion_targets _onion_reachable_external assert_running_state assert_egress_dial_pair public_remotes_in_proc_tcp _pred_tari_payouts_found _pred_payout_wallet_ready _pred_monero_wallet_caught_up assert_payout_wallet_ready assert_tari_payout_scan _lan_probe _lan_flush_rules _lan_strip _lan_capture _lan_probe_open _lan_assert_open assert_lan_guard_live assert_lan_guard_timer_flush _lan_timer_pause _lan_exit_code assert_lan_guard_crash_restart assert_lan_guard_boot_restore assert_lan_guard_boot_failure assert_scenario assert_egress_posture assert_xvb_over_tor assert_metrics_via_caddy assert_doctor_ok assert_share_stats_live assert_telemetry_tables_present assert_current_state box_fstype box_avail_gb box_mode _pred_readiness_monero _pred_readiness_status status_verdict_lines assert_release_readiness lifecycle_gate_snippet retain_lifecycle_gate_samples lifecycle_gate_sample source_image_reconcile_snippet run_source_image_reconcile run_image_permissions wizard_restore_baseline run_cli_wizard_defaults connection_announcements_snippet run_connection_announcements run_restore_dashboard_probe run_reset_restore reset_restore_wait_reboot reset_restore_shutdown_clean reset_restore_wait_empty run_support_bundle _run_lifecycle kept_data_snapshot_snippet kept_chain_files_snippet run_uninstall_round_trip telemetry_rows_diff _pred_status_down _monerod_is _pred_monerod_missing _pred_monerod_unhealthy _pred_monerod_healthy _pred_proxy_stopped _pred_failover_armed _pred_p2pool_running _pred_tor_stopped _pred_tor_healthy _reset_dashboard_services_healthy run_reset_dashboard _rotate_proxy_live_args _rotate_monero_rpc_probe _rotate_proxy_token_accepted _rotate_stratum_auth _rotate_proxy_upstream_active _rotate_rig_accepted _rotate_proxy_accepted_after _rotate_p2pool_monero_live _rotate_new_baks _rotate_cleanup_baks _rotate_abort_restore run_rotate_secrets _rig_active_pool _pred_rig_pool_differs _pred_rig_pool_returned _rig_pool_leg fault_node_down fault_unhealthy fault_missing fault_db_readonly fault_firewall_rollback _gf_flows _gf_down fault_firewall_grandfathered_flow fault_tor_down fault_clock_drift fault_disk_enospc _pred_p2pool_peers _pred_dnswatch_listening fault_p2pool_cold_cache_dns _restore_p2pool_peer_lists run_fault_injection run_fault_injection_maybe p2pool_sidechain_sync_snippet fault_p2pool_sidechain_sync tor_probe_ns_ipt _tor_probe_mining_sample fault_tor_probe_egress _tor_probe_recovered tor_recovery_lock_snapshot_snippet tor_recovery_probe_now_s tor_recovery_healthy_probe p2pool_ns_ipt p2pool_peer_loss_rules p2pool_peer_loss_count p2pool_peer_total p2pool_started_at _pred_p2pool_peerless _pred_p2pool_restarted _pred_p2pool_has_peers _pred_p2pool_rejoin_logged fault_p2pool_peer_loss _await_egress_state fault_firewall_status_alert fault_firewall_boot_restore _set_env_token _spool_write _uuid4 _wait_control_status _remove_control_units run_hardening run_auth_fail_closed _svc_restart_request run_svc_restart rotate_onion_data_dir rotate_onion_key_fingerprint rotate_onion_client_key_fingerprint rotate_onion_env_fingerprint rotate_onion_mining_fingerprint wait_onion_retired rotate_onion_restore run_rotate_onion safety_backup safety_secret_drift_categories safety_restore_exact safety_rollback_if_failed safety_abort_restore arm_safety_abort_restore reset_dashboard_remove_blocker reset_dashboard_cleanup safety_cleanup restore_baseline summary run_rigforge_integration assert_subnet_live run_subnet_scenario _worker_apply _max_temp_round_trip _restore_rig_control_baseline run_rigforge_control _pred_rig_present run_rigforge_reverse _rig_control_apply _rig_control_await _pred_feed_maxt _rig_direct_summary _reverse_feed_failure_detail run_rigforge_rollback it_alert_refused _alert_egress_overlay _alert_egress_verdict run_alert_egress_smoke _mm_rows _mm_cleanup run_mergemine_submit tari_ns_ipt tari_strand_count tari_strand_drops tari_strand_remove_all tari_hook_start tari_hook_stop tari_restore_config tari_strand_abort tari_health_field _pred_tari_level _pred_tari_at_least_amber _pred_tari_zero_peers _pred_tari_alerted _pred_tari_recovery_alerted tari_started_at tari_strand_state run_tari_stranded monero_ns_ipt monero_strand_count monero_strand_remove_all monero_hook_start monero_hook_stop monero_restore_config monero_strand_abort monero_health_field _pred_monero_level _pred_monero_red_peerless monero_peer_counts monero_out_peers monero_tor_recovery_out monero_observation _pred_monero_zero_out _pred_monero_has_peers _pred_monerod_docker_health _pred_monero_alerted _pred_monero_recovery_alerted monero_peer_sample _pred_monero_has_peers_sampled monero_peer_wait_diagnostics _monero_http_code assert_monero_p2p_advertisement assert_monero_rpc_boundary _pred_monerod_restarted_since monero_started_at monero_strand_state run_monero_stranded _mml_fact _mml_target_row _mml_inspect _mml_ip _mml_cleanup run_mergemine_localnet' actual_functions="$(for module in "${modules[@]}"; do sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)() {.*/\1/p' "$ROOT/lib/$module"; done | tr '\n' ' ' | sed 's/ $//')" [ "$actual_functions" = "$expected_functions" ] || { echo "integration function order or completeness mismatch" >&2 From 89fa73c2be08c0b614e3acca64d948d5acc41fff Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:22:05 -0600 Subject: [PATCH 033/112] fix(os): a wedged Tor no longer spends the committed slot's fallback (#4049) (#4080) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(os): a wedged Tor no longer spends the committed slot's fallback (#4049) The boot gate judged the network as part of the slot: Tor stuck in a saturated circuit-build history on the shared /data held the three-signal window shut, and fail_boot spent the machine's one automatic reboot falling back to an older copy that carries the same fault. When the dashboard answers and every boot check still failing is this machine's network — chain-following verdicts, the saturated-tor history FAIL, chain-node down/not-ready rows, tor-family status rows only while wedged — the booted slot now commits instead of spending the fallback: mark-good, clear the failure counter, name the fault in the boot log and in the OS update verdict (updated, with the fault recorded as advisory), and leave mining down until the network recovers. A genuinely broken slot — silent dashboard, crash-looping container with the network up, bad render — still rolls back unchanged. Proof: a stack unit over the classifier and the commit harness (71 asserts), and tier-4 legs for a plain reboot and an OS update across the live wedge. Co-Authored-By: Claude Code * fix(os): classify only at the window end; leg 6 compares the right boot (#4049) Verifier pass: an up failure classified mid-boot, while tor is legitimately starting on every healthy boot, could have committed a dead image through the network advisory — the up-failure hook is gone, only the 16-minute window end classifies, and a wedged network never fails pithead up in the first place. Leg 6 compared the post-reboot boot id against the pre-reboot one, so it could never pass; it now samples the boot id after the reboot returned and asserts nothing else rebooted behind it. Leg 7 refuses to run without a live wedge. Co-Authored-By: Claude Code * test(os): let shfmt have its two lines — chain the wedged phase from leg 5 (#4049) shfmt canonicalizes a semicolon-joined call, so the file-budget join in phases/update.sh could not stand; the phase now runs from the end of phase_update_healthgate_leg and update.sh goes back untouched. Co-Authored-By: Claude Code * test(os): declare the v3wedge dashboard marker (#4049) Co-Authored-By: Claude Code * test: re-anchor the moved verdict, source the new phase module (#4049) The head's shell blocks went red on the test wiring, not the fix: - tests/os/selftest-run-modules.sh pinned the new wedged-Tor phase functions but never sourced their module, so the type loop died; sourced with its shellcheck pragma like the phases beside it. The file sat exactly at its file-budget ceiling, so the no-op-then arm of the image-upgrade capture row became an if ! flip — same verdict, two lines shorter, ceiling intact. - test-appliance-cert-advisory.sh anchored the verdict jq inside pithead-boot, where branch 4049 moved it into pithead-boot-stack-health; the static block now anchors the call site in pithead-boot and the jq containment in stack-health (function before verdict before gate_network_advisory_commit), mutation-checked in both directions locally. Co-Authored-By: Claude Code * test(os): the wedge plant says which step failed and what tor logged (#4049) Co-Authored-By: Claude Sonnet 5.5 * test(os): give the wedge plant the full start period plus retries, report on stdout (#4049) Co-Authored-By: Claude Sonnet 5.5 * test(os): wedge Tor with a persistent compose override, not a state the image repairs (#4049) Co-Authored-By: Claude Sonnet 5.5 * fix(os): a failed up with Tor wedged reaches the gate window, not fail_boot (#4049) Co-Authored-By: Claude Sonnet 5.5 * test: shfmt the boot_up_failed unit (#4049) Co-Authored-By: Claude Sonnet 5.5 * test(os): report the dashboard's own view when the marker is not served through the wedge (#4049) Co-Authored-By: Claude Sonnet 5.5 * test(os): the wedge legs fetch the dashboard marker with the dashboard login (#4049) Co-Authored-By: Claude Sonnet 5.5 * test: keep tests/stack/run.sh at its 400-line target (#4049) Co-Authored-By: Claude Sonnet 5.5 * test(os): restore the wedge module source in the runner selftest after the merge (#4049) Co-Authored-By: Claude Sonnet 5.5 * fix(os): a restarting chain node is the slot, not the wedge (#4049) Co-Authored-By: Claude Sonnet 5.5 * fix(os): the advisory commit starts the on-box miner like a normal commit (#4049) Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Code --- CHANGELOG.md | 7 + docs/appliance.md | 11 +- docs/dev/file-budget.tsv | 1 - os/overlay/pithead-boot | 16 +- os/overlay/pithead-boot-stack-health | 87 +++++ tests/os/dashboard-markers.json | 3 +- tests/os/phases/update-healthgate-leg.sh | 1 + tests/os/phases/update-wedged-tor-legs.sh | 235 +++++++++++ tests/os/run.sh | 2 + tests/os/selftest-run-modules.sh | 12 +- .../test-appliance-boot-network-advisory.sh | 368 ++++++++++++++++++ .../appliance/test-appliance-cert-advisory.sh | 15 +- tests/stack/run.sh | 4 +- 13 files changed, 733 insertions(+), 29 deletions(-) create mode 100644 tests/os/phases/update-wedged-tor-legs.sh create mode 100644 tests/stack/appliance/test-appliance-boot-network-advisory.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index 77ea07d82f..96cccaf7b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,13 @@ per the process in [`docs/dev/releasing.md`](docs/dev/releasing.md). ### Fixed +- On the appliance, a wedged Tor — one whose boot never finishes because the circuit-build history + on the data partition is saturated — no longer costs the committed slot its fallback. The boot + health gate commits when the dashboard answers and every failing check is that network fault, + names the fault in the boot log and in the update's recorded outcome, and leaves the return to the + previous version unspent for a copy that is genuinely broken. That includes the case where + `compose up` itself refuses because Tor is unhealthy: the boot now goes on to the gate window + instead of rebooting at once (#4049). - A dashboard tab left open across a restart, rollback or update now reloads itself: it notices a changed version or the first successful refresh after the disconnected banner, shows "Pithead was updated or restarted. Reloading…" and reloads once the dashboard answers, at most once every 2 diff --git a/docs/appliance.md b/docs/appliance.md index c6c06ca2e0..086ccd4c89 100644 --- a/docs/appliance.md +++ b/docs/appliance.md @@ -499,7 +499,16 @@ and returning to the previous version. If the certificate still does not match a the machine keeps the new version and notes the gap in its boot log and with the update's recorded outcome: the mismatch is about this machine's addresses, not the update, and running `cd /data/pithead && ./pithead apply` at the console mints the certificate — that command now does so -even when the configuration is unchanged. The machine refuses images that are unsigned, built for +even when the configuration is unchanged. A second thing the machine will not trade its return to the +previous version for: when the checks that fail are all this machine's network — Tor not reaching the +network, and only the checks that hang off that connection failing with it — the new copy is not what +broke, and the old copy meets the same fault, because the broken state lives on the data partition the +two copies share. The machine then keeps the new version, keeps serving the dashboard, and names the +network fault in the boot log and in the update's recorded outcome, exactly as it names a held-back +check. Mining stays down until the network recovers; nothing else does. A genuinely broken copy still +goes back: a bad render, a container crash-looping (a chain node that keeps restarting counts even while Tor is stuck), or a +dashboard that never answers all spend the return to the previous version as before. +The machine refuses images that are unsigned, built for different hardware, or older than what it runs. The dashboard has no downgrade override. At the console, `cd /data/pithead && ./pithead os-update BUNDLE --allow-downgrade` installs an older signed image, but never one below the `/data` migration floor. It also refuses an update diff --git a/docs/dev/file-budget.tsv b/docs/dev/file-budget.tsv index 6f403fedfe..0d5972634c 100644 --- a/docs/dev/file-budget.tsv +++ b/docs/dev/file-budget.tsv @@ -43,7 +43,6 @@ lib/pithead/14-local-miner.sh 414 lib/pithead/28-parse-and-validate-config.sh 464 lib/pithead/33-render-env.sh 481 lib/pithead/36-quadlet-units.sh 406 -os/overlay/pithead-boot 403 scripts/watch/trivyignore-watch.sh 599 tests/integration/e2e.sh 684 tests/integration/fakes/test_contract.py 437 diff --git a/os/overlay/pithead-boot b/os/overlay/pithead-boot index 83316daa8e..8a128bb44a 100755 --- a/os/overlay/pithead-boot +++ b/os/overlay/pithead-boot @@ -91,6 +91,7 @@ fail_boot_contended() { # # repeated at both call sites below, so the hold-chain and the ordinary boot cannot drift apart. boot_up_failed() { # [ "$1" = "$PITHEAD_EX_LOCK_TIMEOUT" ] && fail_boot_contended "the stack could not be brought up" + [ "$(gate_tor_transport_verdict)" = wedged ] && return 0 fail_boot "the stack could not be brought up" } @@ -364,19 +365,7 @@ for gate_attempt in $(seq 90); do commit_config_stamp [ "$hold_chain" != 0 ] || restore_data_floor_after_fallback "$migration_fingerprint" || echo "pithead-boot: FAULT — the previous migration candidate remains protected" >&2 echo "pithead-boot: stack is serving (HTTP $code) and doctor reports ${gate_advisory:-healthy}${gate_advisory:+ as its only failing check} — booted slot committed${gate_advisory:+ with that recorded as advisory; run './pithead apply' on the machine to re-mint}" - # OS-update verdict, success half: this slot just committed while an in-flight flag names - # exactly this version — the dashboard-driven update landed and can no longer fall back. - if [ -f "$OS_INFLIGHT" ] && command -v jq >/dev/null 2>&1; then - to=$(jq -r '.to // ""' "$OS_INFLIGHT" 2>/dev/null) - if [ -n "$to" ] && [ "$to" = "$(tr -d '[:space:]' /dev/null)" ]; then - mkdir -p "$OS_STATE_DIR" 2>/dev/null || true - jq -n --arg f "$(jq -r '.from // ""' "$OS_INFLIGHT" 2>/dev/null)" --arg t "$to" --arg a "$gate_advisory" \ - '{step:"idle",verdict:{outcome:"updated",from:$f,to:$t,ts:(now|floor),advisory:(if $a == "" then [] else [$a] end)}}' \ - >"$OS_STATE_DIR/os-update-state.json" 2>/dev/null || true - echo "pithead-boot: OS update to $to committed — verdict published to the dashboard" - fi - rm -f "$OS_INFLIGHT" - fi + boot_publish_os_update_verdict "$gate_advisory" # Post-commit, the held chain services start and the forward migration runs NOW. Never # grounds to fail a boot the commit already accepted: the function alerts and returns. [ "$hold_chain" = 1 ] && { release_held_chain_services "$migration_fingerprint" || true; } @@ -399,4 +388,5 @@ for gate_attempt in $(seq 90); do fi sleep 10 done +if [ "$(gate_tor_transport_verdict)" = wedged ] && gate_network_advisory_commit; then exit 0; fi fail_boot "the stack never became healthy (serving + doctor + status)" diff --git a/os/overlay/pithead-boot-stack-health b/os/overlay/pithead-boot-stack-health index fb5cf0300c..a8dc1fa013 100644 --- a/os/overlay/pithead-boot-stack-health +++ b/os/overlay/pithead-boot-stack-health @@ -105,3 +105,90 @@ schema_hold_release() { ${PITHEAD_DASHBOARD_RESTART_CMD:-docker compose restart dashboard} >/dev/null 2>&1 || echo "pithead-boot: FAULT — the committed slot could not restart the dashboard to run its deferred database migrations; run 'docker compose restart dashboard' from /data/pithead" >&2 } +gate_tor_transport_verdict() { + local cid info state health BOOT_TOR_VERDICT=down + cid=$(docker compose ps -aq tor 2>/dev/null | head -n 1) + [ -n "$cid" ] || { printf 'down\n'; return 0; } + info=$(docker inspect --format '{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$cid" 2>/dev/null) + [ -n "$info" ] || { printf 'down\n'; return 0; } + state=${info%% *} + health=${info##* } + if [ "$state" = running ]; then + case "$health" in + healthy) BOOT_TOR_VERDICT=up ;; + starting | unhealthy) BOOT_TOR_VERDICT=wedged ;; + esac + fi + printf '%s\n' "$BOOT_TOR_VERDICT" +} +gate_blocked_only_by_network() { + GATE_NETWORK_ADVISORY="" + command -v jq >/dev/null 2>&1 || return 1 + [ -s "${BOOT_DOCTOR_JSON:-}" ] || return 1 + jq -e --arg tor "$1" --arg sat "Tor's circuit-build-time history is saturated" ' + ($tor != "down") as $torup | + ($tor == "wedged") as $w | + [.checks[]? | select(.status == "fail") | .message] | + all(.[]; + test("^(Monero|Tari) node is NOT following the chain") + or ($torup and test("^" + $sat)) + or ($w and test("^(monerod|tari|wallet-rpc|tari-wallet) is (down|not ready)") and (test("estarting") | not)))' \ + "$BOOT_DOCTOR_JSON" >/dev/null 2>&1 || return 1 + local line blocked="" bad=0 + while IFS= read -r line; do + [ -n "$line" ] || continue + case "$line" in + *[Rr]estarting*) bad=1 ;; + 'container monero: chain '* | 'container tari: chain '*) ;; + 'container tor: '* | 'container monerod: '* | 'container tari: '* | 'container wallet-rpc: '* | 'container tari-wallet: '*) + [ "$1" = wedged ] || bad=1 ;; + *) bad=1 ;; + esac + blocked="${blocked:+$blocked; }$line" + done <<<"$2" + [ "$bad" = 0 ] || return 1 + local fails + fails=$(jq -r '[.checks[]? | select(.status == "fail") | .message] | join("; ")' "$BOOT_DOCTOR_JSON" 2>/dev/null) + GATE_NETWORK_ADVISORY=$(printf '%s' "${fails:+$fails}${blocked:+${fails:+; }$blocked}" | jq -Rr '.[0:480]') + [ -n "$GATE_NETWORK_ADVISORY" ] +} +boot_publish_os_update_verdict() { + [ -f "${OS_INFLIGHT:-}" ] && command -v jq >/dev/null 2>&1 || return 0 + local state_dir + state_dir="${OS_STATE_DIR:-data/control/results}" + local to + to=$(jq -r '.to // ""' "$OS_INFLIGHT" 2>/dev/null) + if [ -n "$to" ] && [ "$to" = "$(tr -d '[:space:]' /dev/null)" ]; then + mkdir -p "$state_dir" 2>/dev/null || true + jq -n --arg f "$(jq -r '.from // ""' "$OS_INFLIGHT" 2>/dev/null)" --arg t "$to" --arg a "${1:-}" \ + '{step:"idle",verdict:{outcome:"updated",from:$f,to:$t,ts:(now|floor),advisory:(if $a == "" then [] else [$a] end)}}' \ + >"$state_dir/os-update-state.json" 2>/dev/null || true + echo "pithead-boot: OS update to $to committed — verdict published to the dashboard" + fi + rm -f "$OS_INFLIGHT" +} +gate_network_advisory_commit() { + local gs gh gp target rs rargs=() code size blocked verdict + IFS='|' read -r gs gh gp <<<"$(gate_url)" + target=$(gate_target_url "$gs" "$gh" "$gp") + rs=$(gate_resolve_spec "$gh" "$gp") + [ -n "$rs" ] && rargs=(--resolve "$rs") + read -r code size <<<"$(gate_probe_header | curl --header @- -kso /dev/null -w '%{http_code} %{size_download}' --max-time 5 \ + --noproxy '*' --connect-to '::127.0.0.1:' "${rargs[@]}" "$target" 2>/dev/null)" + gate_answer_is_dashboard "${code:-000}" "${size:-0}" || return 1 + PITHEAD_BOOT_GATE=1 ./pithead doctor --json >"$BOOT_DOCTOR_JSON" 2>/dev/null || true + boot_status || true + blocked=$(boot_status_blocking) + verdict=$(gate_tor_transport_verdict) + gate_blocked_only_by_network "$verdict" "$blocked" || return 1 + rauc status mark-good && sync || return 1 + boot_gate_passed + commit_config_stamp + echo "pithead-boot: the dashboard answers and every boot check that still fails is this machine's network, not the slot (${GATE_NETWORK_ADVISORY}) — the fault lives on the shared data, so the previous version carries it too and a rollback could not clear it: the booted slot commits with the fault recorded as advisory, and mining stays down until the network recovers" + boot_publish_os_update_verdict "$GATE_NETWORK_ADVISORY" + [ "${hold_chain:-0}" != 0 ] || restore_data_floor_after_fallback "${migration_fingerprint:-}" || + echo "pithead-boot: FAULT — the previous migration candidate remains protected" >&2 + [ "${hold_chain:-}" = 1 ] && { release_held_chain_services "${migration_fingerprint:-}" || true; } + timeout 1800 ./pithead local-miner || true + return 0 +} diff --git a/tests/os/dashboard-markers.json b/tests/os/dashboard-markers.json index 68f950eb0f..0ac42b2566 100644 --- a/tests/os/dashboard-markers.json +++ b/tests/os/dashboard-markers.json @@ -7,5 +7,6 @@ "candidate", "certificate-continuity", "vmigfault", - "vfail" + "vfail", + "v3wedge" ] diff --git a/tests/os/phases/update-healthgate-leg.sh b/tests/os/phases/update-healthgate-leg.sh index b84e069c17..cb8e6a099a 100644 --- a/tests/os/phases/update-healthgate-leg.sh +++ b/tests/os/phases/update-healthgate-leg.sh @@ -151,4 +151,5 @@ phase_update_healthgate_leg() { info "leg 5 failure evidence (boot journal, verdict, grubenv, doctor) kept at $SERIAL.leg5-evidence" bash scripts/sanitize-test-log.sh --lines 200 "$SERIAL.leg5-evidence" fi + phase_update_wedged_tor_legs } diff --git a/tests/os/phases/update-wedged-tor-legs.sh b/tests/os/phases/update-wedged-tor-legs.sh new file mode 100644 index 0000000000..ca6caf61e5 --- /dev/null +++ b/tests/os/phases/update-wedged-tor-legs.sh @@ -0,0 +1,235 @@ +# shellcheck shell=bash +: "${OS_RUN_SUITE:?source via the suite runner}" +_wedged_tor_plant() { + info "planting the #3052 saturated circuit-build history on the shared /data (the #4049 wedge)" + _ssh bash -s <<'GUEST' +set -e +trap 'rc=$?; echo "wedge plant: line $LINENO exit $rc: $BASH_COMMAND"' ERR +cd /data/pithead +data=$(sed -n 's/^TOR_DATA_DIR=//p' .env) +[ -s "$data/state" ] +work=$(mktemp -d) +cp "$data/state" "$work/original-state" +docker compose stop tor >/dev/null 2>&1 +awk '!/^CircuitBuild/ && !/^TotalBuildTimes /' "$work/original-state" >"$data/state" +printf 'CircuitBuildAbandonedCount 1000\nTotalBuildTimes 1000\n' >>"$data/state" +grep -qx 'CircuitBuildAbandonedCount 1000' "$data/state" +grep -qx 'TotalBuildTimes 1000' "$data/state" +! grep -q '^CircuitBuildTimeBin ' "$data/state" +printf 'services:\n tor:\n entrypoint: ["sleep", "infinity"]\n' >docker-compose.override.yml +docker compose up -d --no-deps --force-recreate tor >/dev/null 2>&1 +for _ in $(seq 150); do + s=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$(docker compose ps -aq tor | head -n 1)" 2>/dev/null) + [ "$s" = unhealthy ] && exit 0 + sleep 10 +done +echo "wedge plant: tor health after 25 min: ${s:-unreadable}" +docker logs --tail 15 "$(docker compose ps -aq tor | head -n 1)" 2>&1 | sed 's/^/wedge plant: tor: /' || true +exit 1 +GUEST +} +_wedged_tor_still_wedged() { + local out + out=$(_ssh "cd /data/pithead && docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{end}} {{json .State.Health}}' \"\$(docker compose ps -aq tor | head -n 1)\" 2>/dev/null" 2>/dev/null) + case "$out" in + unhealthy*) ;; + *) + printf '%s' "$out" + return 1 + ;; + esac +} +_wedged_marker_served() { + local want="$1" deadline=$(($(date +%s) + $2)) got="" + while [ "$(date +%s)" -lt "$deadline" ]; do + got=$(curl -fsSk -m 5 -u "$DASH_USER:$DASH_PASS" "https://${ip:-}/static/os-test-marker.txt" 2>/dev/null) + [ "$got" = "$want" ] && return 0 + sleep 5 + done + return 1 +} +_wedged_tor_advisory_wait() { + local deadline=$(($(date +%s) + $1)) + while [ "$(date +%s)" -lt "$deadline" ]; do + _ssh "journalctl -u pithead-boot -b 0 2>/dev/null | grep -F 'commits with the fault recorded as advisory' >/dev/null" && return 0 + sleep 15 + done + return 1 +} +_update_wedged_tor_reboot_leg() { + info "leg 6 — a Tor wedge on the shared data must not cost the committed slot its fallback (#4049): plain reboot" + if ! _wedged_tor_plant; then + bad "leg 6: the saturated tor state never made the tor container unhealthy — the wedge was never live, so the rest of this leg would prove nothing" + return + fi + ok "leg 6: tor runs wedged (unhealthy, saturated state on /data)" + local before marker + before=$(_boot_id) || { + bad "leg 6: could not read the boot id before the plain reboot" + return + } + _ssh 'reboot' >/dev/null 2>&1 || true + _wait_new_boot "$before" 420 || { + bad "leg 6: guest never returned after the plain reboot" + return + } + local booted + booted=$(_boot_id) || booted="" + marker=$(SSH_TIMEOUT=20 _ssh cat /etc/pithead-test-marker 2>/dev/null) + [ "$marker" = "v2" ] && ok "leg 6: the wedged box booted back onto its committed slot (v2)" || + bad "leg 6: expected v2 to boot after the reboot, got '${marker:-none}'" + if _wedged_tor_advisory_wait 2160; then + ok "leg 6: the boot gate committed through the network advisory instead of spending the fallback" + else + bad "leg 6: 36 minutes after the reboot pithead-boot never logged the advisory commit — fail_boot ran (or the gate is still holding), and the box just spent its fallback on the network" + return + fi + if _ssh "journalctl -u pithead-boot -b 0 2>/dev/null | grep -F 'saturated and clearnet egress is down' >/dev/null"; then + ok "leg 6: the commit named the network fault it was committing through" + else + bad "leg 6: the advisory commit did not name the saturated tor history it was committing through" + fi + if ! _ssh "journalctl -u pithead-boot -b 0 2>/dev/null | grep -F 'never became healthy' >/dev/null"; then + ok "leg 6: no fail_boot this boot — the window ended in a commit, not in a reboot decision" + else + bad "leg 6: fail_boot still ran on a wedged-network boot" + fi + _wedged_tor_still_wedged >/dev/null && + ok "leg 6: the wedge is still live after the commit (the fault was survived, not cleared)" || + bad "leg 6: tor recovered by itself during the leg — the leg was not run against a live wedge" + if _wedged_marker_served v2 300; then + ok "leg 6: the dashboard serves through the wedge" + else + bad "leg 6: the dashboard never served v2 through the wedge" + curl -sk -m 5 -o /dev/null -w "host http %{http_code} %{errormsg}\n" "https://${ip:-}/static/os-test-marker.txt" 2>&1 | sed 's/^/dashboard diag: /' + _ssh "cd /data/pithead && curl -sk -m 5 -o /dev/null -w 'marker http %{http_code}\n' https://localhost/static/os-test-marker.txt; docker ps -a --format '{{.Names}} {{.Status}}'; docker logs --tail 25 dashboard 2>&1; docker logs --tail 10 caddy 2>&1" 2>&1 | sed 's/^/dashboard diag: /' + fi + if _ssh "test ! -e /data/pithead/.boot-gate-failures"; then + ok "leg 6: the boot-failure counter stayed clear, so a later real fault still gets its one reboot" + else + bad "leg 6: .boot-gate-failures exists after the advisory commit" + fi + local after + after=$(_boot_id) || after="" + [ -n "$after" ] && [ -n "$booted" ] && [ "$after" = "$booted" ] && + ok "leg 6: the machine rebooted exactly for the plain reboot — fail_boot never fired behind the commit" || + bad "leg 6: the boot id changed after the wedge boot — something rebooted this box behind the gate" + marker=$(SSH_TIMEOUT=20 _ssh cat /etc/pithead-test-marker 2>/dev/null) + [ "$marker" = "v2" ] && ok "leg 6: still v2 at the end of the window — no GRUB fallback" || + bad "leg 6: the guest left v2 during the window (marker '${marker:-none}')" +} +_update_wedged_tor_update_leg() { + info "leg 7 — an OS update while Tor stays wedged must commit, with the fault recorded as advisory (#4049)" + if ! _wedged_tor_still_wedged >/dev/null; then + bad "leg 7: no live wedge to update through — the rest of this leg would prove nothing about a wedge commit" + return + fi + local fbundle fbrc tag srv srv_pid host_addr port=8932 aged out before marker + info "leg 7: building the v3wedge bundle (the wedge is still planted; nothing about this bundle is special)" + fbundle=$(_build_bundle v3wedge) + fbrc=$? + if [ "$fbrc" -ne 0 ] || [ -z "$fbundle" ]; then + bundle_build_evidence + bad "leg 7: the v3wedge bundle build failed — read /tmp/os-fault-bundle.log" + return + fi + ok "leg 7: built the bundle: $(basename "$fbundle")" + tag="v$(tr -d ' \t\r\n' "$srv/releases-latest.json" + host_addr=$(ip -4 -o addr show virbr0 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -1) + [ -n "$host_addr" ] || host_addr="192.168.122.1" + if ! srv_pid=$(_serve_update_dir "$srv" "$port"); then + rm -rf "$srv" + bad "leg 7: the bench release server never answered on :$port — the harness, not the product" + return + fi + if ! aged=$(aged_version "${tag#v}") || ! _ssh "printf 'http://$host_addr:$port' > /data/pithead/os-update-test-base && printf '%s\n' '$aged' > /data/pithead/VERSION"; then + kill "$srv_pid" 2>/dev/null + rm -rf "$srv" + bad "leg 7: could not age the guest or plant the update-server seam" + return + fi + _ssh 'rm -f /data/pithead/data/os-update/.check-stamp /data/pithead/data/os-update/.check-stamp-short' + out=$(_os_step '{"action":"check"}' 120) + if [ "$(printf '%s' "$out" | jq -r '.status')" = "checked" ]; then + out=$(_os_step "{\"action\":\"download\",\"version\":\"$tag\"}" 900) + [ "$(printf '%s' "$out" | jq -r '.status')" = "downloaded" ] && out=$(_os_step '{"action":"verify"}' 180) + [ "$(printf '%s' "$out" | jq -r '.status')" = "verified" ] && out=$(_os_step '{"action":"install"}' 900) + fi + kill "$srv_pid" 2>/dev/null + rm -rf "$srv" + if [ "$(printf '%s' "$out" | jq -r '.status')" = "installed" ]; then + ok "leg 7: bundle installed into the spare slot over the wedge through the dashboard action" + else + bad "leg 7: the dashboard could not check, download, verify and install the bundle (got: $(printf '%s' "$out" | cut -c1-200))" + return + fi + before=$(_boot_id) || { + bad "leg 7: could not read the boot id before the update reboot" + return + } + _os_step '{"action":"reboot"}' 30 >/dev/null 2>&1 || true + _wait_new_boot "$before" 420 || { + bad "leg 7: guest never returned after booting the updated slot" + return + } + marker=$(SSH_TIMEOUT=20 _ssh cat /etc/pithead-test-marker 2>/dev/null) + [ "$marker" = "v3wedge" ] && ok "leg 7: the updated slot booted (v3wedge)" || { + bad "leg 7: expected v3wedge booted after install, got '${marker:-none}'" + return + } + if _wedged_tor_advisory_wait 2160; then + ok "leg 7: the update committed through the network advisory — the wedge never reached fail_boot" + else + bad "leg 7: 36 minutes into the updated boot there is no advisory commit; marker now: $(SSH_TIMEOUT=20 _ssh cat /etc/pithead-test-marker 2>/dev/null)" + return + fi + local verdict + verdict=$(_ssh "cat /data/pithead/data/control/results/os-update-state.json" 2>/dev/null) + if printf '%s' "$verdict" | jq -e '.verdict.outcome == "updated" and ((.verdict.advisory | length) >= 1)' >/dev/null 2>&1; then + ok "leg 7: the dashboard's update verdict is updated, with the fault recorded as advisory" + else + bad "leg 7: the update verdict is not an updated-with-advisory: $(printf '%s' "$verdict" | cut -c1-200)" + fi + if printf '%s' "$verdict" | jq -e '[.verdict.advisory[] | select(contains("saturated and clearnet egress is down"))] | length >= 1' >/dev/null 2>&1; then + ok "leg 7: the advisory names the wedged tor fault it committed through" + else + bad "leg 7: the advisory does not name the tor fault" + fi + if _ssh "test ! -e /data/pithead/data/os-update/in-flight.json"; then + ok "leg 7: the in-flight flag was consumed by the commit (the next boot reads updated, not rolled_back)" + else + bad "leg 7: the in-flight flag survived the commit" + fi + _wedged_tor_still_wedged >/dev/null && + ok "leg 7: tor is still wedged on the committed update — the update was committed through the fault, not after it cleared" || + bad "leg 7: tor recovered during the leg — this run did not stay wedged" + if _wedged_marker_served v3wedge 300; then + ok "leg 7: the dashboard of the committed update serves through the wedge" + else + bad "leg 7: the dashboard never served v3wedge through the wedge" + curl -sk -m 5 -o /dev/null -w "host http %{http_code} %{errormsg}\n" "https://${ip:-}/static/os-test-marker.txt" 2>&1 | sed 's/^/dashboard diag: /' + _ssh "cd /data/pithead && curl -sk -m 5 -o /dev/null -w 'marker http %{http_code}\n' https://localhost/static/os-test-marker.txt; docker ps -a --format '{{.Names}} {{.Status}}'; docker logs --tail 25 dashboard 2>&1; docker logs --tail 10 caddy 2>&1" 2>&1 | sed 's/^/dashboard diag: /' + fi + marker=$(SSH_TIMEOUT=20 _ssh cat /etc/pithead-test-marker 2>/dev/null) + [ "$marker" = "v3wedge" ] && ok "leg 7: still v3wedge at the end of the window — the update kept its slot" || + bad "leg 7: the guest left v3wedge during the window (marker '${marker:-none}')" +} +phase_update_wedged_tor_legs() { + local fail_before=$FAIL + if [ "${LEG4_PITHEAD_BOOT_PROVED:-0}" != "1" ]; then + it_skip_leg "wedged-Tor boot gate commit (#4049)" \ + "leg 4 did not reach a committed, provisioned guest on this run, so there is no live pithead-boot to reboot or update through a wedge" missing + return + fi + _update_wedged_tor_reboot_leg + _update_wedged_tor_update_leg + if [ "$FAIL" -gt "$fail_before" ]; then + rollback_evidence "$SERIAL.leg67-evidence" + info "legs 6-7 failure evidence (boot journal, verdict, grubenv, doctor) kept at $SERIAL.leg67-evidence" + bash scripts/sanitize-test-log.sh --lines 200 "$SERIAL.leg67-evidence" + fi +} diff --git a/tests/os/run.sh b/tests/os/run.sh index 2cf69e4e4d..925756e879 100755 --- a/tests/os/run.sh +++ b/tests/os/run.sh @@ -217,6 +217,8 @@ source "$SCRIPT_DIR/phases/update.sh" || exit $? source "$SCRIPT_DIR/phases/update-dashboard.sh" || exit $? # shellcheck source=tests/os/phases/update-healthgate-leg.sh source "$SCRIPT_DIR/phases/update-healthgate-leg.sh" || exit $? +# shellcheck source=tests/os/phases/update-wedged-tor-legs.sh +source "$SCRIPT_DIR/phases/update-wedged-tor-legs.sh" || exit $? # shellcheck source=tests/os/phases/install.sh source "$SCRIPT_DIR/phases/install.sh" || exit $? # shellcheck source=tests/os/phases/provision.sh diff --git a/tests/os/selftest-run-modules.sh b/tests/os/selftest-run-modules.sh index 0e803e586d..dccf13ebfe 100755 --- a/tests/os/selftest-run-modules.sh +++ b/tests/os/selftest-run-modules.sh @@ -1,15 +1,15 @@ #!/usr/bin/env bash set -uo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -modules=(lib/core.sh wizard-redirect-leg.sh phases/boot.sh phases/update-spare-slot.sh phases/update.sh phases/update-dashboard.sh phases/update-healthgate-leg.sh phases/install.sh phases/provision.sh phases/setup-defaults.sh phases/media.sh phases/rig.sh phases/rigmedia.sh phases/fault.sh phases/reset.sh phases/image-upgrade.sh phases/crossupdate.sh phases/stack.sh phases/tor-heal.sh phases/pool-heal.sh) -function_files=(lib/core.sh wizard-redirect-leg.sh phases/boot.sh phases/update-spare-slot.sh phases/update.sh phases/update-dashboard.sh phases/update-healthgate-leg.sh phases/install-initial.sh phases/install-rig.sh phases/install-reinstall.sh phases/install-fresh-start.sh phases/install-restore-preboot.sh phases/install-restore.sh phases/install.sh phases/provision-initial.sh phases/provision-reboot.sh phases/provision-power-cut.sh phases/provision-migration.sh phases/provision.sh phases/setup-defaults.sh phases/media.sh phases/rig.sh phases/rigmedia.sh phases/fault.sh phases/reset-config.sh phases/reset-slot.sh phases/reset.sh phases/image-upgrade.sh phases/crossupdate.sh phases/stack.sh phases/tor-heal.sh phases/pool-heal.sh) +modules=(lib/core.sh wizard-redirect-leg.sh phases/boot.sh phases/update-spare-slot.sh phases/update.sh phases/update-dashboard.sh phases/update-healthgate-leg.sh phases/update-wedged-tor-legs.sh phases/install.sh phases/provision.sh phases/setup-defaults.sh phases/media.sh phases/rig.sh phases/rigmedia.sh phases/fault.sh phases/reset.sh phases/image-upgrade.sh phases/crossupdate.sh phases/stack.sh phases/tor-heal.sh phases/pool-heal.sh) +function_files=(lib/core.sh wizard-redirect-leg.sh phases/boot.sh phases/update-spare-slot.sh phases/update.sh phases/update-dashboard.sh phases/update-healthgate-leg.sh phases/update-wedged-tor-legs.sh phases/install-initial.sh phases/install-rig.sh phases/install-reinstall.sh phases/install-fresh-start.sh phases/install-restore-preboot.sh phases/install-restore.sh phases/install.sh phases/provision-initial.sh phases/provision-reboot.sh phases/provision-power-cut.sh phases/provision-migration.sh phases/provision.sh phases/setup-defaults.sh phases/media.sh phases/rig.sh phases/rigmedia.sh phases/fault.sh phases/reset-config.sh phases/reset-slot.sh phases/reset.sh phases/image-upgrade.sh phases/crossupdate.sh phases/stack.sh phases/tor-heal.sh phases/pool-heal.sh) expected_modules="${modules[*]}" actual_modules="$(sed -n 's|^source "$SCRIPT_DIR/\([a-z/-]*\.sh\)".*|\1|p' "$HERE/run.sh" | tr '\n' ' ' | sed 's/ $//')" [ "$actual_modules" = "$expected_modules" ] || { echo "os module order mismatch: $actual_modules" >&2 exit 1 } -expected_functions='ok bad info it_warn it_err have _ssh _control_requests_drained _wait_ssh _boot_id _wait_new_boot _reboot_wait _ssh_unreachable_reason _marker _dash_marker_served _wait_dhcp_ip _wait_setup_page _build_image _build_bundle _stage_bundle _install_cmd _commit_cmd _boot_spare_cmd _install_and_boot_cmd _rollback_cmd require_host require_probe_key_matches_image require_clean_bench cleanup serial_has wait_serial redirect_location_matches wizard_redirect_probe phase_wizard_redirect phase_dashboard_redirect phase_boot _secure_boot_guest_leg _vm_boot_disk _update_spare_slot_uncommitted phase_update _wizard_provision_capture _os_step _serve_update_dir _leg4_srv_stop phase_update_dashboard _update_healthgate_leg_body phase_update_healthgate_leg _restore_target_preboot_verdict _restore_installer_preboot_verdict phase_install _provision_reboot_gate_committed phase_provision phase_setup_defaults _make_media_stick _attach_media_stick _detach_media_stick _media_stick_has_config phase_media _rig_mining_up phase_rig _rigmedia_remove_target _rigmedia_stage_image _rigmedia_hash _rigmedia_containers _rigmedia_journal _rigmedia_before_hash_or_cleanup _rigmedia_after_hash_or_cleanup _rigmedia_containers_or_cleanup _rigmedia_journal_or_cleanup _rigmedia_quiesce _rigmedia_quiesce_or_cleanup _rigmedia_fail_cleanup phase_rigmedia phase_fault _reset_config_shutdown_passed _reset_config_wait_empty _phase_reset_config _reset_slot_snapshot _reset_slot_wait _reset_slot_good_stack _reset_slot_observe _reset_slot_rearm _phase_reset_slot phase_reset _image_upgrade_input_failure _image_upgrade_input_run _image_upgrade_inputs_valid _image_upgrade_node_v4 _image_upgrade_prepare_inputs _image_upgrade_sign_wrong_key _image_upgrade_stage_guest _image_upgrade_clear_guest_inputs _image_upgrade_read_guest_failure _image_upgrade_read_miner_readiness phase_image_upgrade phase_crossupdate stack_browser_config _stack_run_integration _provision_remote_node_coordinator _stack_container_restart_leg phase_stack phase_tor_heal phase_p2pool_heal' +expected_functions='ok bad info it_warn it_err have _ssh _control_requests_drained _wait_ssh _boot_id _wait_new_boot _reboot_wait _ssh_unreachable_reason _marker _dash_marker_served _wait_dhcp_ip _wait_setup_page _build_image _build_bundle _stage_bundle _install_cmd _commit_cmd _boot_spare_cmd _install_and_boot_cmd _rollback_cmd require_host require_probe_key_matches_image require_clean_bench cleanup serial_has wait_serial redirect_location_matches wizard_redirect_probe phase_wizard_redirect phase_dashboard_redirect phase_boot _secure_boot_guest_leg _vm_boot_disk _update_spare_slot_uncommitted phase_update _wizard_provision_capture _os_step _serve_update_dir _leg4_srv_stop phase_update_dashboard _update_healthgate_leg_body phase_update_healthgate_leg _wedged_tor_plant _wedged_tor_still_wedged _wedged_marker_served _wedged_tor_advisory_wait _update_wedged_tor_reboot_leg _update_wedged_tor_update_leg phase_update_wedged_tor_legs _restore_target_preboot_verdict _restore_installer_preboot_verdict phase_install _provision_reboot_gate_committed phase_provision phase_setup_defaults _make_media_stick _attach_media_stick _detach_media_stick _media_stick_has_config phase_media _rig_mining_up phase_rig _rigmedia_remove_target _rigmedia_stage_image _rigmedia_hash _rigmedia_containers _rigmedia_journal _rigmedia_before_hash_or_cleanup _rigmedia_after_hash_or_cleanup _rigmedia_containers_or_cleanup _rigmedia_journal_or_cleanup _rigmedia_quiesce _rigmedia_quiesce_or_cleanup _rigmedia_fail_cleanup phase_rigmedia phase_fault _reset_config_shutdown_passed _reset_config_wait_empty _phase_reset_config _reset_slot_snapshot _reset_slot_wait _reset_slot_good_stack _reset_slot_observe _reset_slot_rearm _phase_reset_slot phase_reset _image_upgrade_input_failure _image_upgrade_input_run _image_upgrade_inputs_valid _image_upgrade_node_v4 _image_upgrade_prepare_inputs _image_upgrade_sign_wrong_key _image_upgrade_stage_guest _image_upgrade_clear_guest_inputs _image_upgrade_read_guest_failure _image_upgrade_read_miner_readiness phase_image_upgrade phase_crossupdate stack_browser_config _stack_run_integration _provision_remote_node_coordinator _stack_container_restart_leg phase_stack phase_tor_heal phase_p2pool_heal' actual_functions="$(for module in "${function_files[@]}"; do sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)() {.*/\1/p' "$HERE/$module"; done | grep -vE '^_phase_(install|provision)_|^_monerod_(height|evidence)$' | tr '\n' ' ' | sed 's/ $//')" [ "$actual_functions" = "$expected_functions" ] || { echo "os function order or completeness mismatch" >&2 @@ -43,6 +43,8 @@ source "$HERE/phases/update.sh" || exit $? source "$HERE/phases/update-dashboard.sh" || exit $? # shellcheck source=tests/os/phases/update-healthgate-leg.sh source "$HERE/phases/update-healthgate-leg.sh" || exit $? +# shellcheck source=tests/os/phases/update-wedged-tor-legs.sh +source "$HERE/phases/update-wedged-tor-legs.sh" || exit $? # shellcheck source=tests/os/phases/install.sh source "$HERE/phases/install.sh" || exit $? source "$HERE/phases/provision.sh" || exit $? @@ -79,13 +81,11 @@ grep -Fq '"$SCRIPT_DIR/../integration/run.sh" --host' "$HERE/phases/stack.sh" || exit 1 } trap - EXIT -if ( +if ! ( PITHEAD_OS_MONERO_NODE_HOST=node.example PITHEAD_OS_MONERO_RPC_PORT=18081 PITHEAD_OS_MONERO_ZMQ_PORT=18083 \ PITHEAD_OS_TARI_NODE_HOST=tari.example PITHEAD_REGISTRY=registry.example _image_upgrade_inputs_valid ); then - : -else echo "image-upgrade rejected the complete remote-node contract" >&2 exit 1 fi diff --git a/tests/stack/appliance/test-appliance-boot-network-advisory.sh b/tests/stack/appliance/test-appliance-boot-network-advisory.sh new file mode 100644 index 0000000000..ab4cbe8509 --- /dev/null +++ b/tests/stack/appliance/test-appliance-boot-network-advisory.sh @@ -0,0 +1,368 @@ +#!/usr/bin/env bash +: "${STACK_SUITE:?is unset: this file is a tests/stack/run.sh fragment, not a script — run tests/stack/run.sh}" +echo "== unit: gate_tor_transport_verdict reads tor's OWN transport state from its healthcheck (#4049) ==" +_bnv_verdict() { + ( + # shellcheck disable=SC1091 + source "$ROOT/os/overlay/pithead-boot-stack-health" + docker() { + case "$*" in + "compose ps -aq tor") printf '%s' "$BNV_PS" ;; + inspect*) printf '%s' "$BNV_INSPECT" ;; + esac + } + gate_tor_transport_verdict + ) +} +assert_eq "tor running with a passing healthcheck is up" \ + "$(BNV_PS='torcid +' BNV_INSPECT='running healthy' _bnv_verdict)" "up" +assert_eq "tor running but stuck short of bootstrapped (unhealthy) is wedged — the #3052 stall, not a crash" \ + "$(BNV_PS='torcid +' BNV_INSPECT='running unhealthy' _bnv_verdict)" "wedged" +assert_eq "tor running but still starting is wedged too (the gate cannot know it will ever pass)" \ + "$(BNV_PS='torcid +' BNV_INSPECT='running starting' _bnv_verdict)" "wedged" +assert_eq "a tor with no healthcheck at all is down, never wedged (the wedge verdict needs the probe)" \ + "$(BNV_PS='torcid +' BNV_INSPECT='running none' _bnv_verdict)" "down" +assert_eq "an exited tor is down: an engine or slot fault, and the fallback stays worth spending" \ + "$(BNV_PS='torcid +' BNV_INSPECT='exited unhealthy' _bnv_verdict)" "down" +assert_eq "no tor container is down" \ + "$(BNV_PS='' BNV_INSPECT='running healthy' _bnv_verdict)" "down" +assert_eq "a failing docker inspect is down, never a guess" \ + "$(BNV_PS='torcid +' BNV_INSPECT='' _bnv_verdict)" "down" + +echo "== unit: a failed up with tor wedged reaches the gate window instead of spending the fallback (#4049) ==" +_bnv_up_failed() { + ( + # shellcheck disable=SC1090 + source "$ROOT/os/overlay/pithead-boot" 2>/dev/null + _v=$1 + gate_tor_transport_verdict() { printf '%s\n' "$_v"; } + fail_boot() { + echo "fail_boot:$1" + exit 0 + } + fail_boot_contended() { + echo "contended:$1" + exit 0 + } + boot_up_failed "$2" + echo continues + ) +} +assert_eq "up failed on 'dependency tor is unhealthy' (wedged): the boot goes on to the gate window" \ + "$(_bnv_up_failed wedged 1)" "continues" +assert_contains "up failed with tor down: the slot is at fault and fail_boot still fires" \ + "$(_bnv_up_failed down 1)" "fail_boot:the stack could not be brought up" +assert_contains "up failed with tor up: the slot is at fault and fail_boot still fires" \ + "$(_bnv_up_failed up 1)" "fail_boot:the stack could not be brought up" +assert_contains "a lock timeout stays contention even while wedged" \ + "$(_bnv_up_failed wedged 75)" "contended:the stack could not be brought up" + +echo "== unit: gate_blocked_only_by_network commits only on faults the previous version carries too (#4049) ==" +BNV_BRANCH_CHAINM="Monero node is NOT following the chain; mining sits on a stale tip: 0 outgoing peers in 10 min — next: check the network" +BNV_BRANCH_SAT="Tor's circuit-build-time history is saturated and clearnet egress is down. When auto-heal is enabled, its final step requests host-gated state recovery." +BNV_BRANCH_DOWNM="monerod is down (created) — a chain node down means the slot is not healthy to commit" +BNV_BRANCH_NOTRW="wallet-rpc is not ready (Up 2 minutes (starting)) — a chain node must be up and healthy to commit" +BNV_BRANCH_EGRESS="Egress firewall rules are MISSING — clearnet escapes around Tor are possible" +BNV_BRANCH_CERT="The dashboard certificate does not cover: fd00::1" +BNV_BRANCH_P2U="p2pool is running but unhealthy (Up 3 hours (unhealthy))" +BNV_BRANCH_TORLINE="container tor: running but UNHEALTHY (Tor health: bootstrap progress=95 tag=circuit_create.)" +_bnv_dj() { + local checks="" s m + while [ $# -ge 2 ]; do + s=$1 + m=$2 + shift 2 + checks="$checks${checks:+,}{\"status\":\"$s\",\"message\":\"$m\"}" + done + printf '{"version":"t","exit":1,"summary":{"ok":0,"warn":0,"fail":0},"checks":[%s]}\n' "$checks" +} +mk_tmpdir _BNV +_bnv_net() { + if [ "$4" = NOFILE ]; then rm -f "$_BNV/doctor.json"; else printf '%s\n' "$3" >"$_BNV/doctor.json"; fi + ( + # shellcheck disable=SC1090 + source "$ROOT/os/overlay/pithead-boot" 2>/dev/null + BOOT_DOCTOR_JSON="$_BNV/doctor.json" + gate_blocked_only_by_network "$1" "$2" && printf 'advisory:%s\n' "$GATE_NETWORK_ADVISORY" || echo not + ) +} +_BNV_OUT=$(_bnv_net wedged "container monerod: created +$BNV_BRANCH_TORLINE" "$(_bnv_dj fail "$BNV_BRANCH_DOWNM" fail "$BNV_BRANCH_SAT")" J) +assert_contains "wedged tor: chain nodes down and the saturated history are the network, not the slot" "$_BNV_OUT" "advisory:" +assert_contains "the advisory names the saturated tor history" "$_BNV_OUT" "saturated and clearnet egress is down" +assert_contains "the advisory names the down chain node" "$_BNV_OUT" "monerod is down" +assert_contains "the advisory carries the unhealthy tor row" "$_BNV_OUT" "container tor: running but UNHEALTHY" +assert_eq "the chain verdict is the network even with tor up (this box has no peers, nothing is crashed)" \ + "$(_bnv_net up '' "$(_bnv_dj fail "$BNV_BRANCH_CHAINM")" J)" "advisory:$BNV_BRANCH_CHAINM" +assert_eq "the wallet-rpc not-ready shape is allowed while wedged (it waits on monerod, tor waits on nothing)" \ + "$(_bnv_net wedged '' "$(_bnv_dj fail "$BNV_BRANCH_NOTRW")" J)" "advisory:$BNV_BRANCH_NOTRW" +assert_eq "a chain node down with tor UP is the slot (crash loop, network up: the fallback must still fire)" \ + "$(_bnv_net up '' "$(_bnv_dj fail "$BNV_BRANCH_DOWNM")" J)" "not" +assert_eq "a chain node down with tor DOWN is the slot (nothing network is proven when the engine is dead)" \ + "$(_bnv_net down '' "$(_bnv_dj fail "$BNV_BRANCH_DOWNM")" J)" "not" +assert_eq "the saturated history with tor down is not advice (tor not running is never the wedge)" \ + "$(_bnv_net down '' "$(_bnv_dj fail "$BNV_BRANCH_SAT")" J)" "not" +assert_eq "the saturated history with tor wedged is the network" \ + "$(_bnv_net wedged '' "$(_bnv_dj fail "$BNV_BRANCH_SAT")" J)" "advisory:$BNV_BRANCH_SAT" +assert_eq "a wedged box with a MISSING egress firewall still falls back (fail-open privacy is the slot's)" \ + "$(_bnv_net wedged '' "$(_bnv_dj fail "$BNV_BRANCH_SAT" fail "$BNV_BRANCH_EGRESS")" J)" "not" +assert_eq "a wedged box whose certificate does not cover a name still falls back (#1265 owns that path)" \ + "$(_bnv_net wedged '' "$(_bnv_dj fail "$BNV_BRANCH_SAT" fail "$BNV_BRANCH_CERT")" J)" "not" +assert_eq "p2pool running-but-unhealthy while wedged still falls back (a miner crash is not tor's gate)" \ + "$(_bnv_net wedged '' "$(_bnv_dj fail "$BNV_BRANCH_SAT" fail "$BNV_BRANCH_P2U")" J)" "not" +assert_eq "the tor row alone while wedged is enough to advise (doctor may hold no fail at all)" \ + "$(_bnv_net wedged "$BNV_BRANCH_TORLINE" "$(_bnv_dj)" J)" "advisory:$BNV_BRANCH_TORLINE" +assert_eq "the tor row while tor is UP is a contradiction, not advice" \ + "$(_bnv_net up "$BNV_BRANCH_TORLINE" "$(_bnv_dj)" J)" "not" +assert_eq "one non-network row vetoes the whole window (caddy exited is the slot)" \ + "$(_bnv_net wedged "$BNV_BRANCH_TORLINE +container caddy: exited" "$(_bnv_dj fail "$BNV_BRANCH_SAT")" J)" "not" +assert_eq "a crash-looping p2pool row vetoes the window even while wedged" \ + "$(_bnv_net wedged "container p2pool: restarting (possible crash loop — check logs)" "$(_bnv_dj fail "$BNV_BRANCH_SAT")" J)" "not" +assert_eq "a restarting chain node fail vetoes the window even while wedged (a crash loop is the slot, not the wedge)" \ + "$(_bnv_net wedged '' "$(_bnv_dj fail "monerod is down (Restarting (1) 5 seconds ago) — a chain node down means the slot is not healthy to commit")" J)" "not" +assert_eq "a restarting chain node row vetoes the window even while wedged" \ + "$(_bnv_net wedged "container monerod: restarting (possible crash loop — check logs)" "$(_bnv_dj fail "$BNV_BRANCH_SAT")" J)" "not" +assert_eq "no fails and no blocking rows leaves nothing to advise (a healthy gate passes on its own)" \ + "$(_bnv_net wedged '' "$(_bnv_dj)" J)" "not" +assert_eq "warns are not fails: nothing to advise" \ + "$(_bnv_net wedged '' "$(_bnv_dj ok 'a' warn 'b')" J)" "not" +assert_eq "no doctor file at all refuses the advisory commit" \ + "$(_bnv_net wedged '' '' NOFILE)" "not" +assert_eq "a malformed doctor file refuses the advisory commit" \ + "$(_bnv_net wedged '' 'not json' J)" "not" +_BNV_LONG=$(printf 'x%.0s' $(seq 700)) +assert_eq "the advisory is bounded so one wall of text cannot flood the banner" \ + "$(_bnv_net wedged '' "$(_bnv_dj fail "${BNV_BRANCH_SAT}${_BNV_LONG}")" J | awk '{print length($0) - 9}')" "480" + +echo "== unit: doctor's own messages stay word-for-word what the classifier matches (#4049) ==" +assert_eq "the Monero chain FAIL the classifier allows is doctor's message, verbatim at source" \ + "$(grep -c 'dr_fail "Monero node is NOT following the chain; mining sits on a stale tip:' "$ROOT/lib/pithead/05-doctor-checks.sh")" "1" +assert_eq "the Tari chain FAIL the classifier allows is doctor's message, verbatim at source" \ + "$(grep -c 'dr_fail "Tari node is NOT following the chain; merge-mined Tari work is wasted:' "$ROOT/lib/pithead/05-doctor-checks.sh")" "1" +assert_eq "the saturated-history FAIL both arms of which the classifier allows is doctor's message at source" \ + "$(grep -c "dr_fail_surface \"Tor's circuit-build-time history is saturated and clearnet egress is down" "$ROOT/lib/pithead/21-doctor-stack-checks.sh")" "1" +assert_eq "the down shape the classifier allows is the revenue verdict's own" \ + "$(grep -c "printf 'fail:%s is down (%s) — a chain node down means the slot is not healthy to commit" "$ROOT/lib/pithead/21-doctor-stack-checks.sh")" "1" +assert_eq "the not-ready half of that shape, pinned too" \ + "$(grep -c "printf 'fail:%s is not ready (%s) — a chain node must be up and healthy to commit" "$ROOT/lib/pithead/21-doctor-stack-checks.sh")" "1" +assert_eq "the classifier's wedged name set is doctor's chain-container set, one list not two" \ + "$(grep -c "container tor: '\\* | 'container monerod: '\\* | 'container tari: '\\* | 'container wallet-rpc: '\\* | 'container tari-wallet: '\\*" "$ROOT/os/overlay/pithead-boot-stack-health")" "1" +assert_eq "the source of that name set stays what doctor itself declares" \ + "$(grep -c 'REVENUE_CHAIN_CONTAINERS="monerod tari wallet-rpc tari-wallet"' "$ROOT/lib/pithead/21-doctor-stack-checks.sh")" "1" + +echo "== unit: boot's own blocker render feeds the classifier without restating it (#4049) ==" +mk_tmpdir _BNV2 +cat >"$_BNV2/status.log" <"$_BNV2/doctor.json" +_BNV_PIPE=$( + ( + cd "$_BNV2" || exit 1 + # shellcheck disable=SC1091 + source "$ROOT/os/overlay/pithead-boot-stack-health" + BOOT_STATUS_LOG="$_BNV2/status.log" + BOOT_DOCTOR_JSON="$_BNV2/doctor.json" + _blocked=$(boot_status_blocking) + gate_blocked_only_by_network up "$_blocked" && echo "advisory:$GATE_NETWORK_ADVISORY" || echo not + ) +) +assert_contains "the chain row as boot renders it classifies as the network (sed render bound to the matcher)" "$_BNV_PIPE" "container monero: chain" +assert_contains "the render keeps the detail text the matcher stops before" "$_BNV_PIPE" "NOT following the chain" +cat >>"$_BNV2/status.log" <"$_BNV2/doctor.json" +_BNV_PIPE2=$( + ( + cd "$_BNV2" || exit 1 + # shellcheck disable=SC1091 + source "$ROOT/os/overlay/pithead-boot-stack-health" + BOOT_STATUS_LOG="$_BNV2/status.log" + BOOT_DOCTOR_JSON="$_BNV2/doctor.json" + _blocked=$(boot_status_blocking) + gate_blocked_only_by_network wedged "$_blocked" && echo "advisory:$GATE_NETWORK_ADVISORY" || echo not + ) +) +assert_contains "with tor wedged the rendered tor row is network too" "$_BNV_PIPE2" "container tor: running but UNHEALTHY" +printf '%s\n' " ✗ wallet-rpc created" >"$_BNV2/status.log" +_BNV_PIPE3=$( + ( + cd "$_BNV2" || exit 1 + # shellcheck disable=SC1091 + source "$ROOT/os/overlay/pithead-boot-stack-health" + BOOT_STATUS_LOG="$_BNV2/status.log" + BOOT_DOCTOR_JSON="$_BNV2/doctor.json" + _blocked=$(boot_status_blocking) + gate_blocked_only_by_network up "$_blocked" && echo "advisory:$GATE_NETWORK_ADVISORY" || echo not + ) +) +assert_eq "with tor UP a created wallet-rpc is the slot, and the real render reaches the matcher" "$_BNV_PIPE3" "not" +rm -rf "$_BNV2" + +echo "== unit: gate_network_advisory_commit commits the slot and names the fault; anything else stays uncommitted (#4049) ==" +_bnv_commit() { + ( + cd "$_BNV" || exit 1 + # shellcheck disable=SC1090 + source "$ROOT/os/overlay/pithead-boot" 2>/dev/null + BOOT_DOCTOR_JSON="$_BNV/doctor.json" + BOOT_STATUS_LOG="$_BNV/status.log" + OS_INFLIGHT="$_BNV/in-flight.json" + OS_STATE_DIR="$_BNV/state" + hold_chain=0 + migration_fingerprint= + rauc() { printf 'rauc %s\n' "$*" >>"$_BNV/rauc.log"; } + curl() { + cat >/dev/null + printf '%s %s' "$BNV_CODE" "$BNV_SIZE" + } + docker() { + case "$*" in + "compose ps -aq tor") printf 'torcid\n' ;; + inspect*) printf 'running unhealthy\n' ;; + esac + } + gate_network_advisory_commit + ) +} +_bnv_commit_reset() { + rm -f "$_BNV/miner.log" "$_BNV/rauc.log" "$_BNV/in-flight.json" "$_BNV/.boot-gate-failures" + rm -rf "$_BNV/state" + printf '9.9.9\n' >"$_BNV/VERSION" + printf 'HOST_IP=localhost\nDASHBOARD_AUTH_HASH_B64=hash\nDASHBOARD_DATA_DIR=%s/dash\n' "$_BNV" >"$_BNV/.env" + mkdir -p "$_BNV/dash" + cat >"$_BNV/pithead" <<'STUB' +#!/usr/bin/env bash +stamp_config_version() { :; } +[ "${BASH_SOURCE[0]}" != "$0" ] && exit 0 +case "$1" in +doctor) + cat doctor-fixture.json + grep -q '"status":"fail"' doctor-fixture.json && exit 1 + ;; +local-miner) echo local-miner >>miner.log ;; +status) + cat status-fixture.log + grep -q '✗\|UNHEALTHY' status-fixture.log && exit 1 + ;; +esac +exit 0 +STUB + chmod +x "$_BNV/pithead" +} +_bnv_wedge_setup() { + _bnv_commit_reset + printf '%s\n' "$(_bnv_dj fail "$BNV_BRANCH_DOWNM" fail "$BNV_BRANCH_SAT")" >"$_BNV/doctor-fixture.json" + printf '✗ monerod created\n⚠ tor running but UNHEALTHY (Tor health: bootstrap progress=95 tag=circuit_create.)\n' >"$_BNV/status-fixture.log" + printf '{"from":"1.0.0","to":"9.9.9"}\n' >"$_BNV/in-flight.json" + : >"$_BNV/.boot-gate-failures" +} +_bnv_wedge_setup +_BNV_OUT=$(BNV_CODE=401 BNV_SIZE=0 _bnv_commit) +assert_rc "wedged network, dashboard serving: the boot commits instead of spending the fallback" "$?" "0" +assert_contains "the commit names the fault on the console so the journal does too" "$_BNV_OUT" "this machine's network, not the slot" +assert_contains "the console line says the slot commits with the fault recorded as advisory" "$_BNV_OUT" "commits with the fault recorded as advisory" +assert_eq "the on-box miner step runs after the advisory commit, as after a normal one" "$(cat "$_BNV/miner.log" 2>/dev/null)" "local-miner" +assert_eq "the booted slot is committed (rauc mark-good ran)" "$(cat "$_BNV/rauc.log")" "rauc status mark-good" +assert_eq "the update verdict outcome is updated (the OS update landed through the wedge)" \ + "$(jq -r '.verdict.outcome' "$_BNV/state/os-update-state.json")" "updated" +assert_contains "the update verdict carries the network fault as advisory" \ + "$(jq -r '.verdict.advisory[0]' "$_BNV/state/os-update-state.json")" "saturated and clearnet egress is down" +assert_eq "the in-flight flag is consumed" "$(test -f "$_BNV/in-flight.json" && echo yes || echo no)" "no" +assert_eq "the boot-failure counter is cleared, so a later real fault still gets its one reboot" \ + "$(test -f "$_BNV/.boot-gate-failures" && echo yes || echo no)" "no" +_bnv_wedge_setup +_BNV_OUT=$(BNV_CODE=000 BNV_SIZE=0 _bnv_commit) +assert_rc "no dashboard answer means no commit, whatever the network story (serving is a product promise)" "$?" "1" +assert_eq "rauc never ran" "$(test -f "$_BNV/rauc.log" && echo yes || echo no)" "no" +assert_eq "the in-flight flag survives a refused commit (fail_boot still gets to name it)" \ + "$(test -f "$_BNV/in-flight.json" && echo yes || echo no)" "yes" +_bnv_commit_reset +printf '%s\n' "$(_bnv_dj fail "$BNV_BRANCH_SAT" fail "$BNV_BRANCH_EGRESS")" >"$_BNV/doctor-fixture.json" +printf '⚠ tor running but UNHEALTHY (x)\n' >"$_BNV/status-fixture.log" +BNV_CODE=401 BNV_SIZE=0 _bnv_commit >/dev/null +assert_rc "a wedged box with a slot-class fail among the blockers stays uncommitted" "$?" "1" +assert_eq "rauc never ran there either" "$(test -f "$_BNV/rauc.log" && echo yes || echo no)" "no" +assert_eq "and the miner step never ran on a refused commit" "$(test -f "$_BNV/miner.log" && echo yes || echo no)" "no" +_bnv_commit_reset +printf '%s\n' "$(_bnv_dj ok 'all good')" >"$_BNV/doctor-fixture.json" +: >"$_BNV/status-fixture.log" +BNV_CODE=200 BNV_SIZE=120 _bnv_commit >/dev/null +assert_rc "a world with no failing check has nothing to advise: the ordinary gate pass owns it, not this path" "$?" "1" +assert_eq "and nothing is committed on that path" "$(test -f "$_BNV/rauc.log" && echo yes || echo no)" "no" +_bnv_commit_reset +printf '%s\n' "$(_bnv_dj fail "$BNV_BRANCH_SAT")" >"$_BNV/doctor-fixture.json" +printf '⚠ tor running but UNHEALTHY (x)\n' >"$_BNV/status-fixture.log" +BNV_CODE=401 BNV_SIZE=0 _bnv_commit >/dev/null +assert_rc "with no in-flight update flag the commit still stands and publishes no verdict" "$?" "0" +assert_eq "and no verdict file is written outside an update" "$(test -f "$_BNV/state/os-update-state.json" && echo yes || echo no)" "no" +rm -rf "$_BNV" + +echo "== unit: boot_publish_os_update_verdict keeps the success-half semantics it was extracted with (#4049) ==" +mk_tmpdir _BNV3 +_bnv_publish() { + ( + cd "$_BNV3" || exit 1 + # shellcheck disable=SC1091 + source "$ROOT/os/overlay/pithead-boot-stack-health" + OS_INFLIGHT="$_BNV3/in-flight.json" + OS_STATE_DIR="$_BNV3/state" + boot_publish_os_update_verdict "$2" + ) +} +printf '9.9.9\n' >"$_BNV3/VERSION" +printf '{"from":"1.0.0","to":"9.9.9"}\n' >"$_BNV3/in-flight.json" +_bnv_publish x 'the fault' >/dev/null +assert_eq "the verdict names the update landed" "$(jq -r '.verdict.outcome' "$_BNV3/state/os-update-state.json")" "updated" +assert_eq "the advisory array carries the fault" "$(jq -r '.verdict.advisory[0]' "$_BNV3/state/os-update-state.json")" "the fault" +printf '{"from":"1.0.0","to":"9.9.9"}\n' >"$_BNV3/in-flight.json" +_bnv_publish x '' >/dev/null +assert_eq "no advisory stays an empty array (the healthy pass is unchanged)" \ + "$(jq -c '.verdict.advisory' "$_BNV3/state/os-update-state.json")" "[]" +assert_eq "the flag is consumed whatever the advisory" "$(test -f "$_BNV3/in-flight.json" && echo yes || echo no)" "no" +printf '{"from":"1.0.0","to":"8.0.0"}\n' >"$_BNV3/in-flight.json" +rm -rf "$_BNV3/state" +_bnv_publish x '' >/dev/null +assert_eq "an in-flight flag naming another version publishes no updated verdict (unchanged semantics)" \ + "$(test -f "$_BNV3/state/os-update-state.json" && echo yes || echo no)" "no" +assert_eq "and that flag is still consumed (unchanged semantics)" "$(test -f "$_BNV3/in-flight.json" && echo yes || echo no)" "no" +rm -f "$_BNV3/in-flight.json" +_bnv_publish x '' >/dev/null +assert_rc "no in-flight flag is a silent no-op" "$?" "0" +rm -rf "$_BNV3" + +echo "== wiring: only the window end consults the network advisory before spending the fallback (#4049) ==" +_BNV_TAIL=$(tail -n 2 "$ROOT/os/overlay/pithead-boot") +assert_eq "the 16-minute window ends in the classifier, and only then in fail_boot" \ + "$_BNV_TAIL" \ + 'if [ "$(gate_tor_transport_verdict)" = wedged ] && gate_network_advisory_commit; then exit 0; fi +fail_boot "the stack never became healthy (serving + doctor + status)"' +_BNV_UPF=$(sed -n '/^boot_up_failed()/,/^}/p' "$ROOT/os/overlay/pithead-boot") +_BNV_L1=$(printf '%s\n' "$_BNV_UPF" | grep -n fail_boot_contended | head -1 | cut -d: -f1) +_BNV_L3=$(printf '%s\n' "$_BNV_UPF" | grep -n ' fail_boot ' | head -1 | cut -d: -f1) +assert_eq "an up failure still exits for contention before anything else" \ + "$([ "$_BNV_L1" -lt "$_BNV_L3" ] && echo before)" "before" +assert_eq "an up failure spends the fallback on the spot — only the end of the window classifies, so a dead image cannot commit while tor is merely starting" \ + "$(printf '%s\n' "$_BNV_UPF" | grep -c gate_network_advisory_commit)" "0" +assert_eq "the healthy pass publishes its verdict through the shared function, so both halves cannot drift" \ + "$(grep -c 'boot_publish_os_update_verdict "\$gate_advisory"' "$ROOT/os/overlay/pithead-boot")" "1" +assert_eq "the window-timeout exit carries the classifier exactly once" \ + "$(grep -c 'gate_network_advisory_commit' "$ROOT/os/overlay/pithead-boot")" "1" +assert_eq "the certificate-only trigger stays exactly as #1265 wrote it (this change adds no other mid-loop advisory)" \ + "$(grep -c 'gate_blocked_only_by_cert; then' "$ROOT/os/overlay/pithead-boot")" "1" +assert_eq "the boot gate's three-signal pass path is unchanged by this change (regression pin)" \ + "$(grep -c 'if gate_ready "${code:-000}" "${size:-0}"; then' "$ROOT/os/overlay/pithead-boot")" "1" + +unset -f _bnv_verdict _bnv_dj _bnv_net _bnv_commit _bnv_commit_reset _bnv_wedge_setup _bnv_publish +unset _BNV _BNV2 _BNV3 _BNV_OUT _BNV_PIPE _BNV_PIPE2 _BNV_PIPE3 _BNV_TAIL _BNV_UPF _BNV_L1 _BNV_L2 _BNV_L3 _BNV_LONG +unset BNV_PS BNV_INSPECT BNV_CODE BNV_SIZE BNV_BRANCH_CHAINM BNV_BRANCH_SAT BNV_BRANCH_DOWNM BNV_BRANCH_NOTRW +unset BNV_BRANCH_EGRESS BNV_BRANCH_CERT BNV_BRANCH_P2U BNV_BRANCH_TORLINE diff --git a/tests/stack/appliance/test-appliance-cert-advisory.sh b/tests/stack/appliance/test-appliance-cert-advisory.sh index 8ff4dae1a2..d67db6a451 100644 --- a/tests/stack/appliance/test-appliance-cert-advisory.sh +++ b/tests/stack/appliance/test-appliance-cert-advisory.sh @@ -183,18 +183,23 @@ echo "== unit: the gate loop commits on the advisory and the verdict carries it # and by the `updated` verdict's jq naming `advisory`. Mutation run: delete the advisory line -> # red; write the verdict without `advisory` -> red. BOOTSCRIPT="$ROOT/os/overlay/pithead-boot" +STACKHEALTH="$ROOT/os/overlay/pithead-boot-stack-health" bl_line() { grep -n -F -- "$1" "$BOOTSCRIPT" | head -1 | cut -d: -f1; } +hv_line() { grep -n -F -- "$1" "$STACKHEALTH" | head -1 | cut -d: -f1; } l_remint=$(bl_line ' gate_remint_cert || true') l_adv=$(bl_line ' gate_cert_advisory_ready && gate_pass=1') l_pass=$(bl_line ' if [ "$gate_pass" = 1 ]; then') l_say=$(bl_line "with that recorded as advisory; run './pithead apply' on the machine to re-mint") -l_verdict=$(bl_line 'advisory:(if $a == "" then [] else [$a] end)') +l_call=$(bl_line 'boot_publish_os_update_verdict "$gate_advisory"') +l_verdict=$(hv_line 'advisory:(if $a == "" then [] else [$a] end)') +l_fn=$(hv_line 'boot_publish_os_update_verdict() {') +l_next=$(hv_line 'gate_network_advisory_commit() {') assert_eq "every anchor is present" \ - "$([ -n "$l_remint" ] && [ -n "$l_adv" ] && [ -n "$l_pass" ] && [ -n "$l_say" ] && [ -n "$l_verdict" ] && echo all)" "all" + "$([ -n "$l_remint" ] && [ -n "$l_adv" ] && [ -n "$l_pass" ] && [ -n "$l_say" ] && [ -n "$l_call" ] && [ -n "$l_verdict" ] && echo all)" "all" assert_eq "re-mint, then the advisory check, then the one commit condition, then the console line, then the verdict" \ - "$([ "${l_remint:-0}" -lt "${l_adv:-0}" ] && [ "${l_adv:-0}" -lt "${l_pass:-0}" ] && [ "${l_pass:-0}" -lt "${l_say:-0}" ] && [ "${l_say:-0}" -lt "${l_verdict:-0}" ] && echo ordered)" "ordered" + "$([ "${l_remint:-0}" -lt "${l_adv:-0}" ] && [ "${l_adv:-0}" -lt "${l_pass:-0}" ] && [ "${l_pass:-0}" -lt "${l_say:-0}" ] && [ "${l_say:-0}" -lt "${l_call:-0}" ] && [ "${l_fn:-0}" -lt "${l_verdict:-0}" ] && [ "${l_verdict:-0}" -lt "${l_next:-0}" ] && echo ordered)" "ordered" assert_eq "the console line reports the advisory only when there is one, and names the remedy that now works" \ "$(grep -c "doctor reports \${gate_advisory:-healthy}\${gate_advisory:+ as its only failing check} — booted slot committed\${gate_advisory:+ with that recorded as advisory; run './pithead apply' on the machine to re-mint}" "$BOOTSCRIPT")" "1" assert_eq "there is exactly ONE commit path — the advisory does not duplicate the commit block" "$(grep -c 'rauc status mark-good' "$BOOTSCRIPT")" "2" -unset -f ar_run ap_line ga_run bl_line -unset CA AP GA RS COVER DJ_COVER rs_out rf_out BOOTSCRIPT l_hold l_units l_refresh l_nothing l_release l_remint l_adv l_pass l_say l_verdict +unset -f ar_run ap_line ga_run bl_line hv_line +unset CA AP GA RS COVER DJ_COVER rs_out rf_out BOOTSCRIPT STACKHEALTH l_hold l_units l_refresh l_nothing l_release l_remint l_adv l_pass l_say l_call l_verdict l_fn l_next diff --git a/tests/stack/run.sh b/tests/stack/run.sh index 55e820c8c6..46879bc8d2 100755 --- a/tests/stack/run.sh +++ b/tests/stack/run.sh @@ -207,10 +207,8 @@ if in_block 2; then _d0=$((PASS + FAIL)) && source "$HERE/test-tor-egress-boot.sh" && domain_ran test-tor-egress-boot.sh "$_d0" "$?" || domain_ran test-tor-egress-boot.sh "$_d0" "$?" # shellcheck source=tests/stack/test-tor-egress-check.sh disable=SC2015 _d0=$((PASS + FAIL)) && source "$HERE/test-tor-egress-check.sh" && domain_ran test-tor-egress-check.sh "$_d0" "$?" || domain_ran test-tor-egress-check.sh "$_d0" "$?" - # shellcheck source=tests/stack/control/test-control-core.sh disable=SC2015 _d0=$((PASS + FAIL)) && source "$HERE/control/test-control-core.sh" && domain_ran test-control-core.sh "$_d0" "$?" || domain_ran test-control-core.sh "$_d0" "$?" - # shellcheck source=tests/stack/secrets/test-secrets-masking.sh disable=SC2015 _d0=$((PASS + FAIL)) && source "$HERE/secrets/test-secrets-masking.sh" && domain_ran test-secrets-masking.sh "$_d0" "$?" || domain_ran test-secrets-masking.sh "$_d0" "$?" fi @@ -327,6 +325,8 @@ if in_block 5; then _d0=$((PASS + FAIL)) && source "$HERE/appliance/test-appliance-boot-stack-health.sh" && domain_ran test-appliance-boot-stack-health.sh "$_d0" "$?" || domain_ran test-appliance-boot-stack-health.sh "$_d0" "$?" # shellcheck source=tests/stack/appliance/test-appliance-cert-advisory.sh disable=SC2015 _d0=$((PASS + FAIL)) && source "$HERE/appliance/test-appliance-cert-advisory.sh" && domain_ran test-appliance-cert-advisory.sh "$_d0" "$?" || domain_ran test-appliance-cert-advisory.sh "$_d0" "$?" + # shellcheck source=tests/stack/appliance/test-appliance-boot-network-advisory.sh disable=SC2015 + _d0=$((PASS + FAIL)) && source "$HERE/appliance/test-appliance-boot-network-advisory.sh" && domain_ran test-appliance-boot-network-advisory.sh "$_d0" "$?" || domain_ran test-appliance-boot-network-advisory.sh "$_d0" "$?" # shellcheck source=tests/stack/appliance/test-appliance-boot-release.sh disable=SC2015 _d0=$((PASS + FAIL)) && source "$HERE/appliance/test-appliance-boot-release.sh" && domain_ran test-appliance-boot-release.sh "$_d0" "$?" || domain_ran test-appliance-boot-release.sh "$_d0" "$?" From 9cf6f9fa989030cafbcecfc4919d23326fea21c0 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <328836012+pithead-developer[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:55:48 -0600 Subject: [PATCH 034/112] =?UTF-8?q?stack:=20fix=20#4063,=20#4064=20?= =?UTF-8?q?=E2=80=94=20monerod=20re-dial=20after=20Tor=20restart,=20Restar?= =?UTF-8?q?t=20all,=20gated=20Reset=20Tor=20state=20(#4094)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * stack: fix #4063, #4064 — guarantee monerod re-dial after a Tor restart; Restart all and gated Reset Tor state Co-Authored-By: Claude Sonnet 5.5 * stack: harden restart and Tor reset after review (#4063, #4064) Co-Authored-By: Claude Sonnet 5.5 * tests: fix #4063 — clear the reset backups between applies; allow the lifecycle label helper Co-Authored-By: Claude Sonnet 5.5 * tests: register the stack-actions integration module in the run-modules selftest (#4063) Co-Authored-By: Claude Sonnet 5.5 * CHANGELOG: tidy merge (#4063) Co-Authored-By: Claude Sonnet 5.5 * tests: run the restart-tor re-dial row on every box, add tari ordering and dashboard result readability rows (#4063, #4064) Co-Authored-By: Claude Sonnet 5.5 * tests: a late-lock restart rejection leaves the restart cooldown unused (#4063) Co-Authored-By: Claude Opus 5.5 * dashboard: put Reset Tor state below the tor card's recent log so the card's keyboard order stays checks then log (#4063) Co-Authored-By: Claude Opus 5.5 * stack: a bare restart restarts a running tari after Tor is bootstrapped (#4064) The bench row for #4064 showed tari started before tor after Restart all: tari depends on tor being healthy but has no restart coupling, so compose restart gave no ordering. Co-Authored-By: Claude Sonnet 5.5 * stack: restart a running tari after Tor on a bare restart via stack_redial_after_restart; keep files within budget (#4064) Co-Authored-By: Claude Sonnet 5.5 * stack: restart the tari container after Tor whenever it exists, not only when it is running (#4064) Co-Authored-By: Claude Sonnet 5.5 * docs: give Restart all and Reset Tor their own subsection beside Restart a service (#4063) Co-Authored-By: Claude Opus 5.5 * control: svc-restart of tor re-dials monerod once Tor is bootstrapped (#4063) The dashboard's per-service Tor restart now runs the same bootstrap wait and monerod re-dial as './pithead restart tor', under the svc-restart lock, and reports failed when Tor never bootstraps. The browser waits as long as Reset Tor state for that one service. Co-Authored-By: Claude Opus 5.5 * docs: the svc-restart tor wait holds the lock (#4063) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: pithead-developer[bot] <4933481+pithead-developer[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 --- .github/workflows/shell.yml | 1 + CHANGELOG.md | 7 + Makefile | 1 + .../web/static/system/diagview.mjs | 10 +- .../web/static/system/stackactions.mjs | 192 +++++++++++++++ .../web/views/diagnostics_views.py | 28 +++ .../frontend/system/diagview-restart.test.mjs | 15 +- .../frontend/system/stackactions.test.mjs | 219 ++++++++++++++++++ .../tests/web/views/test_diagnostics_views.py | 74 ++++++ docs/dashboard.md | 46 +++- docs/dev/file-budget.tsv | 2 +- docs/operations.md | 4 +- lib/pithead/01-lifecycle.sh | 25 +- .../44-control-upgrade-and-lifecycle.sh | 36 ++- lib/pithead/46c-control-svc-restart.sh | 8 + lib/pithead/47-os-update-helpers.sh | 28 +++ lib/pithead/48b-control-tor-recover.sh | 44 +++- lib/pithead/49-control-request-loop.sh | 11 + tests/integration/lib/run-hardening.sh | 3 + tests/integration/lib/run-stack-actions.sh | 66 ++++++ tests/integration/lib/run-svc-restart.sh | 12 +- tests/integration/run.sh | 2 + .../selftest/selftest-run-modules.sh | 6 +- .../control/test-control-lifecycle-verbs.sh | 83 ++++++- tests/stack/lib.sh | 3 + tests/stack/lib/verdict-label-determinism.sh | 1 + tests/stack/lifecycle/recovery.sh | 12 + tests/stack/lifecycle/restart-order.sh | 21 ++ tests/stack/standalone/test_tor_reset.sh | 157 +++++++++++++ tests/stack/test-lifecycle.sh | 2 + 30 files changed, 1062 insertions(+), 57 deletions(-) create mode 100644 dashboard/mining_dashboard/web/static/system/stackactions.mjs create mode 100644 dashboard/tests/frontend/system/stackactions.test.mjs create mode 100644 tests/integration/lib/run-stack-actions.sh create mode 100644 tests/stack/lifecycle/restart-order.sh create mode 100755 tests/stack/standalone/test_tor_reset.sh diff --git a/.github/workflows/shell.yml b/.github/workflows/shell.yml index 1fc481c123..a3f27fcd70 100644 --- a/.github/workflows/shell.yml +++ b/.github/workflows/shell.yml @@ -134,6 +134,7 @@ jobs: bash tests/stack/standalone/test_tor_recovery.sh bash tests/stack/standalone/test_tor_bootstrap_recovery.sh bash tests/stack/standalone/test_tor_heal_outage_recovery.sh + bash tests/stack/standalone/test_tor_reset.sh - name: Run real-image data-reset suite # Real ext4 damage against the product's own repair escalation (#1062). Unprivileged — # e2fsprogs on plain files — and it hard-fails rather than skips when CI lacks the tools. diff --git a/CHANGELOG.md b/CHANGELOG.md index 96cccaf7b8..2655a9a84e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,10 @@ per the process in [`docs/dev/releasing.md`](docs/dev/releasing.md). ### Added +- The Service diagnostics card has a **Restart all** button (typed `RESTART`, refused during an OS + update, an uncommitted slot, a held host lock or a restart in the last two minutes, and riding out the dashboard's own restart) and a + **Reset Tor state** button on the Tor card that runs the existing gated Tor recovery with its own + 30-minute budget and returns the gate's refusal reason (#4064, #4063). - The dashboard and the configuration view now open on a sign-in page instead of the browser's password prompt. It has a "Remember me" box (30 days, renewed while in use; otherwise the session ends when the browser closes or after 8 hours idle) and a "Sign out" button. Changing the password @@ -28,6 +32,9 @@ per the process in [`docs/dev/releasing.md`](docs/dev/releasing.md). previous version unspent for a copy that is genuinely broken. That includes the case where `compose up` itself refuses because Tor is unhealthy: the boot now goes on to the gate window instead of rebooting at once (#4049). +- `./pithead restart tor`, a bare `restart` and the dashboard's restart now wait for Tor to report + bootstrapped and then restart a running monerod themselves, so it re-dials through the new Tor + instead of staying at 0 peers when compose did not cycle it (#4063); a bare restart and Restart all then also restart the tari container, when the stack has one, so it starts after Tor (#4064). - A dashboard tab left open across a restart, rollback or update now reloads itself: it notices a changed version or the first successful refresh after the disconnected banner, shows "Pithead was updated or restarted. Reloading…" and reloads once the dashboard answers, at most once every 2 diff --git a/Makefile b/Makefile index 18c75b6529..e2247a3b5d 100644 --- a/Makefile +++ b/Makefile @@ -29,6 +29,7 @@ test-stack: pithead ## pithead shell test suite bash tests/stack/standalone/test_tor_recovery_info.sh bash tests/stack/standalone/test_tor_bootstrap_recovery.sh bash tests/stack/standalone/test_tor_heal_outage_recovery.sh + bash tests/stack/standalone/test_tor_reset.sh bash tests/stack/standalone/test_data_reset.sh bash tests/stack/standalone/test_directory_linebreaks.sh bash tests/stack/standalone/test_os_update_recovery.sh diff --git a/dashboard/mining_dashboard/web/static/system/diagview.mjs b/dashboard/mining_dashboard/web/static/system/diagview.mjs index 10e82f04cd..b7d3461799 100644 --- a/dashboard/mining_dashboard/web/static/system/diagview.mjs +++ b/dashboard/mining_dashboard/web/static/system/diagview.mjs @@ -11,6 +11,7 @@ import { Component, html } from "../app/preact.mjs"; import { controlFetch, staleError } from "../config/controlclient.mjs"; +import { RestartAllControl, TOR_RESET_POLL_MAX, TorResetControl } from "./stackactions.mjs"; const CONTROL_HEADERS = { "Content-Type": "application/json", "X-Pithead-Control": "1" }; const DIAG_POLL_MS = 2000; @@ -223,7 +224,12 @@ export class DiagnosticsPanel extends Component { async runRestart(service) { this.setRestart(service, { phase: "waiting", result: null }); try { - const result = await runDiag("svc-restart", { container: service }, `the ${service} restart`); + const result = await runDiag( + "svc-restart", + { container: service }, + `the ${service} restart`, + service === "tor" ? TOR_RESET_POLL_MAX : undefined, + ); this.setRestart(service, { phase: result.status === "applied" ? "done" : "failed", result, @@ -326,6 +332,7 @@ export class DiagnosticsPanel extends Component { } ${this.renderLog(service.name)} ${this.renderRestart(service.name)} + ${service.name === "tor" ? html`<${TorResetControl} run=${runDiag} />` : null} `; } @@ -347,6 +354,7 @@ export class DiagnosticsPanel extends Component { below; open a service's recent log only when you need it.

    + <${RestartAllControl} /> ${ healthPhase === "waiting" ? html`

    Waiting for the host to return the health check…

    ` diff --git a/dashboard/mining_dashboard/web/static/system/stackactions.mjs b/dashboard/mining_dashboard/web/static/system/stackactions.mjs new file mode 100644 index 0000000000..922833d672 --- /dev/null +++ b/dashboard/mining_dashboard/web/static/system/stackactions.mjs @@ -0,0 +1,192 @@ +import { Component, html } from "../app/preact.mjs"; +import { controlFetch, staleError } from "../config/controlclient.mjs"; + +const CONTROL_HEADERS = { "Content-Type": "application/json", "X-Pithead-Control": "1" }; + +export const RESTART_ALL_WORD = "RESTART"; +export const RESTART_ALL_POLL_MS = 2000; +export const RESTART_ALL_POLL_MAX = 300; +export const TOR_RESET_POLL_MAX = 450; + +export async function awaitRestartResult(id, { onOffline, onWaiting, pollMs, max } = {}) { + for (let i = 0; i < (max ?? RESTART_ALL_POLL_MAX); i++) { + await new Promise((resolve) => setTimeout(resolve, pollMs ?? RESTART_ALL_POLL_MS)); + let res; + try { + res = await fetch(`/api/control/result?id=${encodeURIComponent(id)}`); + } catch { + if (onOffline) onOffline(); + continue; + } + if (res.status === 202) { + if (onWaiting) onWaiting(); + continue; + } + if ([502, 503, 504].includes(res.status)) { + if (onOffline) onOffline(); + continue; + } + if (!res.ok) throw new Error(`Could not read the restart result: HTTP ${res.status}`); + try { + return await res.json(); + } catch { + throw new Error("Could not read the restart result: the host returned an unreadable result."); + } + } + return null; +} + +export async function submitRestartAll(confirm) { + const res = await controlFetch("/api/control/restart", { + method: "POST", + headers: CONTROL_HEADERS, + body: JSON.stringify({ confirm }), + }); + if (res.status === 401 || res.status === 403) throw staleError(); + if (!res.ok && res.status !== 202) + throw new Error(`Could not submit the restart: HTTP ${res.status}`); + let id; + try { + ({ id } = await res.json()); + } catch { + id = null; + } + if (typeof id !== "string" || !id) + throw new Error("Could not submit the restart: the host returned no request id."); + return id; +} + +export class RestartAllControl extends Component { + constructor(props) { + super(props); + this.state = { phase: "idle", text: "", message: "", offline: false }; + } + + async restart() { + this.setState({ phase: "restarting", message: "", offline: false }); + try { + const id = await submitRestartAll(RESTART_ALL_WORD); + const result = await awaitRestartResult(id, { + onOffline: () => this.setState({ offline: true }), + onWaiting: () => this.setState({ offline: false }), + }); + if (result === null) { + this.setState({ + phase: "failed", + message: + "The stack has not answered within 10 minutes of the restart. Check the machine, then reload this page.", + }); + } else if (result.status === "applied") { + this.setState({ phase: "done", message: "The stack restarted." }); + (this.props.reload || (() => window.location.reload()))(); + } else { + this.setState({ + phase: "failed", + message: result.error || result.note || "The host did not restart the stack.", + }); + } + } catch (error) { + this.setState({ phase: "failed", message: String(error.message || error) }); + } + } + + render() { + const { phase, text, message, offline } = this.state; + const busy = phase === "restarting"; + return html`
    + + ${ + phase === "confirming" + ? html`
    +

    Restart the whole stack. Mining stops briefly, this dashboard goes offline and comes + back on its own, and the machine itself is not rebooted.

    + +
    + + +
    +
    ` + : null + } + ${ + busy + ? html`

    ${ + offline + ? "The dashboard is offline while the stack restarts. This page reloads when it is back…" + : "Waiting for the host to restart the stack…" + }

    ` + : null + } + ${phase === "done" ? html`

    ${message}

    ` : null} + ${phase === "failed" ? html`

    ${message}

    ` : null} +
    `; + } +} + +export class TorResetControl extends Component { + constructor(props) { + super(props); + this.state = { phase: "idle", message: "" }; + } + + async reset() { + this.setState({ phase: "running", message: "" }); + try { + const result = await this.props.run( + "tor-reset", + {}, + "the Tor state reset", + TOR_RESET_POLL_MAX, + ); + if (result.status === "applied") { + this.setState({ + phase: "done", + message: "Tor state was reset, Tor restarted and monerod re-dialled through it.", + }); + } else { + this.setState({ + phase: "refused", + message: result.error || result.note || "The host did not reset the Tor state.", + }); + } + } catch (error) { + this.setState({ phase: "refused", message: String(error.message || error) }); + } + } + + render() { + const { phase, message } = this.state; + return html`
    + + ${ + phase === "confirming" + ? html`
    +

    This discards Tor's circuit history: the saved state file is moved aside as a backup, + Tor restarts and every Tor circuit rebuilds, and monerod re-dials its peers. Onion + addresses are kept.

    +

    The host can refuse. It resets only when the history is saturated and Tor or monerod + is stalled, Tor auto-heal is on, no other host operation is running, and the cooldown has + passed; the reason is shown here.

    +
    + + +
    +
    ` + : null + } + ${ + phase === "running" + ? html`

    Waiting for the host to reset the Tor state — this can take several minutes…

    ` + : null + } + ${phase === "done" ? html`

    ${message}

    ` : null} + ${phase === "refused" ? html`

    ${message}

    ` : null} +
    `; + } +} diff --git a/dashboard/mining_dashboard/web/views/diagnostics_views.py b/dashboard/mining_dashboard/web/views/diagnostics_views.py index e60a555802..2f52112399 100644 --- a/dashboard/mining_dashboard/web/views/diagnostics_views.py +++ b/dashboard/mining_dashboard/web/views/diagnostics_views.py @@ -131,6 +131,32 @@ async def handle_onion_key(request): return web.json_response({"id": rid, "status": "pending"}, status=202) +async def handle_restart_all(request): + _require_control_header(request) + try: + body = await request.json() + except Exception: + raise web.HTTPBadRequest(text="Body must be JSON.") from None + if not isinstance(body, dict) or body.get("confirm") != "RESTART": + raise web.HTTPBadRequest(text="'confirm' must be the word RESTART.") + try: + rid = control_service.submit("restart", actor=request.headers.get("X-Auth-User", "")) + except Exception: + logger.exception("Error submitting restart request") + return web.json_response({"error": "Failed to submit the restart request."}, status=500) + return web.json_response({"id": rid, "status": "pending"}, status=202) + + +async def handle_tor_reset(request): + _require_control_header(request) + try: + rid = control_service.submit("tor-reset", actor=request.headers.get("X-Auth-User", "")) + except Exception: + logger.exception("Error submitting tor-reset request") + return web.json_response({"error": "Failed to submit the Tor reset request."}, status=500) + return web.json_response({"id": rid, "status": "pending"}, status=202) + + async def handle_support_bundle(request): _require_control_header(request) hours = None @@ -163,6 +189,8 @@ def control_routes(): web.post("/api/control/diag-logs", handle_diag_logs), web.post("/api/control/svc-restart", handle_svc_restart), web.post("/api/control/onion-client-key", handle_onion_key), + web.post("/api/control/restart", handle_restart_all), + web.post("/api/control/tor-reset", handle_tor_reset), web.post("/api/control/support-bundle", handle_support_bundle), web.get( "/api/control/support-bundle-download", download_views.handle_support_bundle_download diff --git a/dashboard/tests/frontend/system/diagview-restart.test.mjs b/dashboard/tests/frontend/system/diagview-restart.test.mjs index e42ea4b09e..8a1bd6e37c 100644 --- a/dashboard/tests/frontend/system/diagview-restart.test.mjs +++ b/dashboard/tests/frontend/system/diagview-restart.test.mjs @@ -42,7 +42,8 @@ const restartPost = (opts) => JSON.parse(opts.body); test("every restartable service shows a Restart button and the four platform services show none", () => { const out = renderToString(inst().render()); - assert.equal((out.match(/]*>Restart [a-z0-9-]+/g) || []).length, DIAG_RESTARTABLE.length); + const named = [...out.matchAll(/]*>Restart ([a-z0-9-]+)/g)].map((m) => m[1]).filter((n) => n !== "all"); + assert.deepEqual(named.sort(), [...DIAG_RESTARTABLE].sort()); for (const service of ["wallet-rpc", "tari-wallet", "tor", "monerod"]) { assert.match(out, new RegExp(`]*>Restart ${service}\\b`)); } @@ -87,6 +88,18 @@ test("a confirmed restart posts the closed request once, disables the button, an assert.equal(posts[0].headers["X-Pithead-Control"], "1"); }); +test("a tor restart waits out the host's Tor bootstrap and monerod re-dial, which outlast the usual diagnostics wait", async () => { + let polls = 0; + const fetchStub = async (url) => { + if (url === "/api/control/svc-restart") return { status: 202, ok: false, json: async () => ({ id: ID }) }; + polls += 1; + return polls < 150 ? { status: 202, ok: false } : okResult({ status: "applied", container: "tor" }); + }; + const panel = inst(); + await withFastPoll(fetchStub, () => panel.runRestart("tor")); + assert.equal(panel.state.restarts.tor.phase, "done"); +}); + test("a host refusal or failure is shown verbatim as the restart result", async () => { for (const status of ["rejected", "failed"]) { const error = `host said no ${status}`; diff --git a/dashboard/tests/frontend/system/stackactions.test.mjs b/dashboard/tests/frontend/system/stackactions.test.mjs new file mode 100644 index 0000000000..93e72ecde4 --- /dev/null +++ b/dashboard/tests/frontend/system/stackactions.test.mjs @@ -0,0 +1,219 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { installFreshness } from "../../../mining_dashboard/web/static/app/freshness.mjs"; +import { DiagnosticsPanel } from "../../../mining_dashboard/web/static/system/diagview.mjs"; +import { + RESTART_ALL_POLL_MAX, + RestartAllControl, + TOR_RESET_POLL_MAX, + TorResetControl, + awaitRestartResult, +} from "../../../mining_dashboard/web/static/system/stackactions.mjs"; +import { renderToString } from "../helpers/render.mjs"; + +installFreshness({ + reload() {}, + store: { getItem: () => null, setItem() {} }, + fetchFn: async () => ({ ok: false }), + sleep: () => new Promise(() => {}), +}); + +const ID = "22222222-2222-4222-8222-222222222222"; +const json = (status, body) => ({ status, ok: status < 300, json: async () => body }); + +async function withStubs(fetchStub, fn) { + const realFetch = globalThis.fetch; + const realTimeout = globalThis.setTimeout; + globalThis.fetch = fetchStub; + globalThis.setTimeout = (cb) => { + cb(); + return 0; + }; + try { + return await fn(); + } finally { + globalThis.fetch = realFetch; + globalThis.setTimeout = realTimeout; + } +} + +function inst(Cls, props = {}, state = {}) { + const c = new Cls(props); + c.props = props; + c.state = { ...c.state, ...state }; + c.setState = (next) => { + const patch = typeof next === "function" ? next(c.state, c.props) : next; + c.state = { ...c.state, ...patch }; + }; + return c; +} + +const view = (c) => renderToString(c.render()); + +test("Restart all asks for the typed word and says what will happen", () => { + const c = inst(RestartAllControl, {}, { phase: "confirming", text: "" }); + const out = view(c); + assert.match(out, /Mining stops briefly/); + assert.match(out, /goes offline/); + assert.match(out, /not rebooted/); + assert.match(out, /]*disabled[^>]*>Restart the stack/); + c.state.text = "RESTART"; + assert.doesNotMatch(view(c), /]*disabled[^>]*>Restart the stack/); + c.state.text = "restart"; + assert.match(view(c), /]*disabled[^>]*>Restart the stack/); +}); + +test("awaitRestartResult rides out the offline window and returns the host result", async () => { + const replies = [ + () => { + throw new TypeError("offline"); + }, + () => json(502, {}), + () => json(202, {}), + () => json(200, { status: "applied" }), + ]; + const seen = []; + const result = await withStubs( + () => replies.shift()(), + () => + awaitRestartResult(ID, { + onOffline: () => seen.push("offline"), + onWaiting: () => seen.push("waiting"), + }), + ); + assert.deepEqual(result, { status: "applied" }); + assert.deepEqual(seen, ["offline", "offline", "waiting"]); +}); + +test("awaitRestartResult gives up at its named budget instead of polling forever", async () => { + let calls = 0; + const result = await withStubs( + () => { + calls += 1; + throw new TypeError("offline"); + }, + () => awaitRestartResult(ID), + ); + assert.equal(result, null); + assert.equal(calls, RESTART_ALL_POLL_MAX); + assert.ok(RESTART_ALL_POLL_MAX > 40); +}); + +test("Restart all submits the typed word, shows offline, then reloads on the applied result", async () => { + let reloaded = 0; + const c = inst(RestartAllControl, { reload: () => reloaded++ }); + const calls = []; + const replies = [ + json(202, { id: ID, status: "pending" }), + () => { + throw new TypeError("offline"); + }, + json(200, { status: "applied" }), + ]; + await withStubs( + (url, init) => { + calls.push([url, init && init.body]); + const next = replies.shift(); + return typeof next === "function" ? next() : next; + }, + () => c.restart(), + ); + assert.deepEqual(calls[0], ["/api/control/restart", JSON.stringify({ confirm: "RESTART" })]); + assert.equal(c.state.phase, "done"); + assert.equal(reloaded, 1); +}); + +test("Restart all shows the host's refusal verbatim and does not reload", async () => { + let reloaded = 0; + const c = inst(RestartAllControl, { reload: () => reloaded++ }); + const reason = "an OS update is in progress (installing) — try again later"; + const replies = [json(202, { id: ID }), json(200, { status: "rejected", error: reason })]; + await withStubs(() => replies.shift(), () => c.restart()); + assert.equal(c.state.phase, "failed"); + assert.equal(reloaded, 0); + assert.ok(view(c).includes(reason)); +}); + +test("Restart all prints a clear message when the stack has not returned", async () => { + const c = inst(RestartAllControl, { reload: () => assert.fail("must not reload") }); + let first = true; + await withStubs( + () => { + if (first) { + first = false; + return json(202, { id: ID }); + } + throw new TypeError("offline"); + }, + () => c.restart(), + ); + assert.equal(c.state.phase, "failed"); + assert.match(view(c), /has not answered within 10 minutes/); +}); + +test("Restart all reports a submit failure", async () => { + const c = inst(RestartAllControl); + await withStubs(() => json(500, {}), () => c.restart()); + assert.equal(c.state.phase, "failed"); + assert.match(view(c), /HTTP 500/); + const d = inst(RestartAllControl); + await withStubs(() => json(403, {}), () => d.restart()); + assert.match(view(d), /out of date/); +}); + +test("Reset Tor state has its own confirmation naming what it discards and that it can refuse", () => { + const c = inst(TorResetControl, { run: async () => ({}) }, { phase: "confirming" }); + const out = view(c); + assert.match(out, /discards Tor's circuit history/); + assert.match(out, /host can refuse/); + assert.match(out, /Cancel/); +}); + +test("Reset Tor state runs the reset verb with a long wait and shows the result", async () => { + const calls = []; + const c = inst(TorResetControl, { + run: async (...args) => { + calls.push(args); + return { status: "applied" }; + }, + }); + await c.reset(); + assert.deepEqual(calls, [["tor-reset", {}, "the Tor state reset", TOR_RESET_POLL_MAX]]); + assert.equal(c.state.phase, "done"); + assert.match(view(c), /Tor state was reset/); +}); + +test("Reset Tor state shows a gate refusal verbatim and a thrown wait as a refusal", async () => { + const reason = "[WARNING] Tor recovery refused: the persistent six-hour cooldown is active."; + const c = inst(TorResetControl, { run: async () => ({ status: "failed", error: reason }) }); + await c.reset(); + assert.equal(c.state.phase, "refused"); + assert.ok(view(c).includes(reason)); + const d = inst(TorResetControl, { + run: async () => { + throw new Error("Stopped waiting for the Tor state reset."); + }, + }); + await d.reset(); + assert.match(view(d), /Stopped waiting/); +}); + +test("Reset Tor state is disabled while it runs", () => { + const c = inst(TorResetControl, { run: async () => ({}) }, { phase: "running" }); + assert.match(view(c), /]*disabled[^>]*>Reset Tor state/); +}); + +test("the diagnostics card carries Restart all, and Reset Tor state only on the tor card", () => { + const panel = inst(DiagnosticsPanel, { enabled: true }); + const out = renderToString(panel.render()); + assert.match(out, /Restart all/); + assert.equal(out.match(/Reset Tor state/g).length, 1); + const torSection = out.slice(out.indexOf(">tor<"), out.indexOf(">monerod<")); + assert.match(torSection, /Reset Tor state/); +}); + +test("a disabled control channel shows neither button", () => { + const out = renderToString(inst(DiagnosticsPanel, { enabled: false }).render()); + assert.doesNotMatch(out, /Restart all|Reset Tor state/); +}); diff --git a/dashboard/tests/web/views/test_diagnostics_views.py b/dashboard/tests/web/views/test_diagnostics_views.py index 71c3feccf1..bebd79b272 100644 --- a/dashboard/tests/web/views/test_diagnostics_views.py +++ b/dashboard/tests/web/views/test_diagnostics_views.py @@ -209,6 +209,80 @@ async def test_a_spool_failure_is_a_500_that_names_no_path(self, diag_client, mo assert "nonexistent" not in json.dumps(await resp.json()) +class TestStackActionRoutes: + async def test_both_routes_404_when_the_control_channel_is_off( + self, aiohttp_client, monkeypatch + ): + monkeypatch.setattr(control_service.config, "DASHBOARD_CONTROL_ENABLED", False) + sm = StateManager(db_path=":memory:") + cli = await aiohttp_client(create_app(sm, {})) + try: + for path in ("/api/control/restart", "/api/control/tor-reset"): + resp = await cli.post(path, headers=CONTROL_HEADERS, json={"confirm": "RESTART"}) + assert resp.status == 404, path + finally: + sm.close() + + @pytest.mark.parametrize("path", ["/api/control/restart", "/api/control/tor-reset"]) + async def test_both_require_the_control_header(self, diag_client, spool, path): + resp = await diag_client.post(path, json={"confirm": "RESTART"}) + assert resp.status == 403 + assert list((spool / "requests").glob("*.json")) == [] + + @pytest.mark.parametrize( + "payload", + [{}, {"confirm": "restart"}, {"confirm": "APPLY"}, {"confirm": True}, [], "RESTART"], + ) + async def test_restart_all_needs_the_typed_word(self, diag_client, spool, payload): + resp = await diag_client.post("/api/control/restart", headers=CONTROL_HEADERS, json=payload) + assert resp.status == 400 + assert list((spool / "requests").glob("*.json")) == [] + + async def test_restart_all_rejects_a_non_json_body(self, diag_client, spool): + resp = await diag_client.post( + "/api/control/restart", headers=CONTROL_HEADERS, data="RESTART" + ) + assert resp.status == 400 + assert list((spool / "requests").glob("*.json")) == [] + + async def test_restart_all_spools_the_closed_restart_verb(self, diag_client, spool): + resp = await diag_client.post( + "/api/control/restart", + headers={**CONTROL_HEADERS, "X-Auth-User": "admin"}, + json={"confirm": "RESTART"}, + ) + assert resp.status == 202 + body = await resp.json() + assert body["status"] == "pending" + assert spooled(spool) == {"id": body["id"], "action": "restart", "actor": "admin"} + + async def test_tor_reset_spools_the_closed_reset_verb(self, diag_client, spool): + resp = await diag_client.post( + "/api/control/tor-reset", headers={**CONTROL_HEADERS, "X-Auth-User": "admin"} + ) + assert resp.status == 202 + body = await resp.json() + assert spooled(spool) == {"id": body["id"], "action": "tor-reset", "actor": "admin"} + + @pytest.mark.parametrize( + ("path", "kwargs"), + [ + ("/api/control/restart", {"json": {"confirm": "RESTART"}}), + ("/api/control/tor-reset", {}), + ], + ) + async def test_a_spool_failure_is_a_500_that_names_no_path( + self, diag_client, monkeypatch, path, kwargs + ): + def boom(request): + raise OSError("/secret/path") + + monkeypatch.setattr(request_spool, "write", boom) + resp = await diag_client.post(path, headers=CONTROL_HEADERS, **kwargs) + assert resp.status == 500 + assert "/secret/path" not in await resp.text() + + class TestSvcRestart: async def test_requires_the_control_header(self, diag_client, spool): resp = await diag_client.post("/api/control/svc-restart", json={"container": "tor"}) diff --git a/docs/dashboard.md b/docs/dashboard.md index 8adaba2ca5..c0ff4d1d78 100644 --- a/docs/dashboard.md +++ b/docs/dashboard.md @@ -1554,10 +1554,11 @@ that is gone from the dashboard, and the host's own `control.log` — which the ### Service diagnostics -Two read-only questions you can ask the host and one recovery action, in the same card stack as -the config editor and under the same `dashboard.control.enabled` flag. The two questions change -nothing: they run a check and report, which is why neither asks you to confirm. The restart does -change the machine and always asks first (see [Restart a service](#restart-a-service)). +Two read-only questions you can ask the host and three recovery actions, in the same card stack +as the config editor and under the same `dashboard.control.enabled` flag. The two questions change +nothing: they run a check and report, which is why neither asks you to confirm. The actions change +the machine and always ask first: restarting one service (see [Restart a service](#restart-a-service)), +and **Restart all** and **Reset Tor state** (see [Restart all and reset Tor](#restart-all-and-reset-tor)). **Run health check** runs the host's own `pithead doctor` and shows what it found — the same checks the CLI prints, failures first, with the host's summary counts above them. This is the one @@ -1595,15 +1596,19 @@ page you are reading or the proxy in front of it would cut off the answer. The b confirmation naming what else is interrupted (restarting `tor` also restarts `monerod`; restarting `monerod` interrupts `wallet-rpc`; a wallet pauses its sync and payouts briefly), and sends nothing until you confirm. The button stays disabled while the host works, then shows the result or the -host's reason for refusing. +host's reason for refusing. A `tor` restart can take several minutes, because the host waits for +Tor to report bootstrapped before it restarts `monerod`. The host decides, not the dashboard. It restarts only a service on its fixed list, with `docker compose restart ` under the same lock as `apply`, `upgrade` and `backup`. It refuses, with a reason and without queueing, while another of those operations holds the lock, while the LAN-only source rule for a published port is not in place, and when the same service was -restarted in the last 120 seconds. Every request is recorded in the control audit log with the -actor, the action `svc-restart`, the service and the outcome (`started`, `rejected`, `applied` or -`failed`). +restarted in the last 120 seconds. After a `tor` restart it waits up to five minutes, still +holding the lock, for Tor to report bootstrapped, then restarts a running `monerod` so it re-dials +its peers through the new circuits, as `./pithead restart tor` does. If Tor does not bootstrap in +that time, or `monerod` cannot be restarted, the result is `failed` and says to restart `monerod` +once Tor is healthy. Every request is recorded in the control audit log with the actor, the action +`svc-restart`, the service and the outcome (`started`, `rejected`, `applied` or `failed`). One thing reads differently here than at a terminal: the report is redacted on its way to the browser, so where `pithead doctor` prints your dashboard's onion address in full, this panel shows @@ -1646,6 +1651,31 @@ daemon, use the support bundle or the console. If you pick a service the host will not read logs for, the host refuses and the panel shows its reason as-is rather than guessing at one. +#### Restart all and reset Tor + +**Restart all** restarts every container of the stack through the host's `restart` verb. It asks +you to type `RESTART`, and it says that mining stops briefly, that the dashboard goes offline and +comes back on its own, and that the machine is not rebooted. The page then shows an offline state, +polls the host's result every two seconds for up to ten minutes, and reloads when the restart +finished; if the stack has not answered by then it says so and leaves the page for you to reload. +The host refuses, and the panel shows its reason, while an OS update is downloading, installing, +verifying or waiting for its reboot, while the new slot is still being committed (a restart then +could roll the machine back), and while another host operation (a config apply, backup, restore or +upgrade) holds the mutation lock; it reports busy instead of queueing. Every request is audited +with its actor, action and status, and a second request inside two minutes of the last is rejected with the time left. After the restart the host waits for Tor to report bootstrapped +and restarts monerod so it re-dials through the new Tor, then restarts the tari container, when the stack has one, so it starts after Tor. The restart verb is available on the DIY +stack and the appliance. + +**Reset Tor state**, on the Tor card, asks the host to run the same gated `tor-recover apply` that +the Tor auto-heal uses, as the signed-in user instead of `tor-heal`. Its confirmation names what it +discards (Tor's circuit history, moved aside as a backup; onion addresses are kept) and that the +host can refuse. Every gate stays in force: `tor.auto_heal` must be on, the circuit history must +be saturated, a stalled Monero or Tor bootstrap must corroborate it, no other host operation may +hold the lock, and the six-hour recovery cooldown applies. A refusal comes back as the gate's own +sentence in the panel. The button also has its own 30-minute budget: a repeat inside it is +rejected with the time left, so it cannot be pressed repeatedly. A successful reset restarts Tor +and re-dials a running monerod. + ## Backup view **Backup** is its own entry in the toggle above the chart, beside Simple, Advanced and diff --git a/docs/dev/file-budget.tsv b/docs/dev/file-budget.tsv index 0d5972634c..4f77a7acd3 100644 --- a/docs/dev/file-budget.tsv +++ b/docs/dev/file-budget.tsv @@ -14,7 +14,7 @@ dashboard/mining_dashboard/service/storage_service.py 785 dashboard/mining_dashboard/service/workers/worker_config_store.py 422 dashboard/mining_dashboard/service/xvb/algo_service.py 558 dashboard/mining_dashboard/sim/donation_model.py 539 -dashboard/mining_dashboard/web/server.py 630 +dashboard/mining_dashboard/web/server.py 627 dashboard/mining_dashboard/web/static/app/chart.mjs 663 dashboard/mining_dashboard/web/static/app/logic.mjs 534 dashboard/mining_dashboard/web/static/config/configview.mjs 555 diff --git a/docs/operations.md b/docs/operations.md index f200b118d7..5c410b4440 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -12,7 +12,7 @@ separately, [below](#appliance-only-commands). | `./pithead apply` | Preview and apply `config.json` changes. Warns before disruptive ones and recreates only what changed. `-y` / `--yes` skips the prompt. | | `./pithead up` | Start the stack. | | `./pithead down` | Stop the stack. | -| `./pithead restart [tor\|monerod]` | Restart the stack, or one container. `restart tor` rebuilds circuits when Tor clearnet egress is stuck (#424) — every Tor circuit drops and rebuilds, mining onions included, and a local monerod restarts right after tor is healthy again so it re-dials its peers (#972). `restart monerod` re-dials peers on its own when the node reports not synchronized after a Tor restart. See [Tor egress broken while mining works](#troubleshooting). | +| `./pithead restart [tor\|monerod]` | Restart the stack, or one container. `restart tor` rebuilds circuits when Tor clearnet egress is stuck (#424) — every Tor circuit drops and rebuilds, mining onions included, and a local monerod restarts once the host has seen tor report bootstrapped (it polls for up to five minutes, then fails and names `restart monerod` instead of re-dialling a dead Tor) so it re-dials its peers (#972, #4063). A bare `restart` re-dials monerod the same way after the whole stack restarts. `restart monerod` re-dials peers on its own when the node reports not synchronized after a Tor restart. See [Tor egress broken while mining works](#troubleshooting). | | `./pithead upgrade` | Re-render the generated config, then **pull** (release bundle) or **rebuild** (source checkout) the images and restart. Run after downloading a newer bundle or a `git pull`. | | `./pithead logs [service]` | Follow logs for all containers, or a single service (e.g. `logs p2pool`). | | `./pithead status` | Show container status and health-check every expected service. Warns about anything down/unhealthy and exits non-zero if so (handy for cron/monitoring). Profile-aware, and treats a stopped `p2pool`/`xmrig-proxy` as intentional during a node-down failover or while the miner is held until the chains sync. | @@ -1030,7 +1030,7 @@ check) WARNs on the live state. Fix: ``` Stack operations don't need the manual step: compose restarts monerod automatically whenever it -restarts or recreates tor (`up`, `apply`, `upgrade`, `restart tor`), and the final `tor.auto_heal` container restart does the same. NEWNYM does not restart monerod. (#972) +restarts or recreates tor (`up`, `apply`, `upgrade`), and `restart tor` and a bare `restart` (and so the dashboard's Restart all) wait for Tor to report bootstrapped and then restart a running monerod themselves, whether or not compose already cycled it (a bare `restart` then restarts the tari container too, when the stack has one, so it starts after Tor instead of alongside it); the final `tor.auto_heal` container restart restarts monerod itself once Tor is running. NEWNYM does not restart monerod. (#972, #4063) The dashboard also covers a Tor start it did not see happen, with or without `tor.auto_heal` (#4076). It notes every start of the tor container (an operator, `./pithead`, Docker or an diff --git a/lib/pithead/01-lifecycle.sh b/lib/pithead/01-lifecycle.sh index 97c8ede21e..ae1a693d90 100644 --- a/lib/pithead/01-lifecycle.sh +++ b/lib/pithead/01-lifecycle.sh @@ -340,6 +340,20 @@ stack_down_except_caddy() { mutation_lock_release } +stack_redial_monerod() { + local i polls="${PITHEAD_TOR_REDIAL_POLLS:-60}" tor_health + for ((i = 0; i <= polls; i++)); do + tor_health=$(docker inspect tor --format '{{.State.Health.Status}}' 2>/dev/null) || tor_health= + [ "$tor_health" = healthy ] && break + [ "$i" -lt "$polls" ] && sleep "${PITHEAD_TOR_REDIAL_POLL_S:-5}" + done + [ "$tor_health" = healthy ] || error "Tor did not report bootstrapped within the wait (or its health could not be read), so monerod was not restarted and may hold dead peer connections. Once Tor is healthy, run './pithead restart monerod'." + if [ "$(docker inspect monerod --format '{{.State.Running}}' 2>/dev/null)" = true ]; then + log "Tor is bootstrapped; restarting monerod so it re-dials its peers through Tor..." + docker compose restart monerod + fi +} + stack_restart() { # [tor|monerod] # Reject a bad argument BEFORE taking the lock (#1342). Validating inside the window makes a # typo wait out someone else's backup — up to PITHEAD_LOCK_TIMEOUT — only to be told it was a @@ -357,18 +371,13 @@ stack_restart() { # [tor|monerod] "") log "Restarting stack..." docker compose restart + stack_redial_after_restart log "Stack restarted." ;; tor) - # Manual leg of the #424 guard self-heal: restart ONLY tor so it rebuilds circuits - # when clearnet exits are stuck (the doctor Tor clearnet-egress check WARNs on this). - # Tor takes no args from .env, so a plain restart is safe (other containers go - # through apply/upgrade, whose recreate applies current args, #273). Compose then - # restarts monerod right after tor is healthy again (depends_on restart: true, #972): - # monerod does NOT re-peer on its own after a tor restart kills its SOCKS - # connections — it can sit at 0 in / 0 out peers for hours; p2pool re-peers fine. - log "Restarting the tor container to rebuild circuits — ALL Tor circuits drop and rebuild (mining onions included; p2pool re-peers on its own, and a local monerod is restarted alongside so it re-dials)..." + log "Restarting the tor container to rebuild circuits — ALL Tor circuits drop and rebuild (mining onions included; p2pool re-peers on its own, and a local monerod is restarted once Tor is bootstrapped so it re-dials)..." docker compose restart tor + stack_redial_monerod log "tor restarted. Verify egress recovered: './pithead doctor' (Tor clearnet-egress check)." ;; monerod) diff --git a/lib/pithead/44-control-upgrade-and-lifecycle.sh b/lib/pithead/44-control-upgrade-and-lifecycle.sh index 574e1b3b9f..9ec98e7110 100644 --- a/lib/pithead/44-control-upgrade-and-lifecycle.sh +++ b/lib/pithead/44-control-upgrade-and-lifecycle.sh @@ -358,34 +358,28 @@ control_upgrade() { # fi } -# Validate + dispatch one CLAIMED request file. Trusts no byte of it: must be JSON, only the keys -# id/action/config/actor/version, the id must be a UUID (it becomes the result/staged FILENAME — -# anything else is rejected before it can touch a path), and the action one of the three known verbs. -# Lifecycle verbs for the Telegram control commands (#338): the only two host actions the bot can -# trigger, both FIXED — `restart` runs `$0 restart` (recreate the running stack) and `apply` runs -# `$0 apply -y` (re-render + re-apply the CURRENT on-disk config.json). The container's `action` -# string only SELECTS between these two hardcoded commands; nothing from the request is ever -# interpolated into a command, and `apply` here carries no config change (the default-deny config -# allowlist is only relevant to a config-editing commit, not a re-apply of the source of truth). -# Since #2076 removed the Telegram control commands, NOTHING produces a restart/apply intent: the -# dashboard never submits either verb. The dispatch is kept because it is where "a spool writer -# cannot run an arbitrary host command" is proven and tested (tests/stack/control/ -# test-control-lifecycle-verbs.sh), and because the spool already accepts the far more powerful -# `commit`, so removing these two buys no boundary. This side records the actor and outcome in the -# same tamper-evidence audit log. control_lifecycle() { # local verb="$1" id="$2" actor="$3" cdir="$4" rc=0 - local logf="$cdir/staged/.$id.log" + local logf="$cdir/staged/.$id.log" refusal="" + [ "$verb" != restart ] || refusal=$(control_restart_refusal "$cdir") + if [ -n "$refusal" ]; then + control_write_result "$cdir/results" "$id" "$(jq -n --arg a "$verb" --arg e "$refusal" '{status:"rejected",action:$a,error:$e,ts:(now|floor)}')" + control_audit "$cdir/audit/control.log" "$id" "$actor" "$verb" "rejected" + return 0 + fi + [ "$verb" != restart ] || date +%s >"$cdir/restart-at" control_audit "$cdir/audit/control.log" "$id" "$actor" "$verb" "started" - # ${PITHEAD_SELF:-$0} is this script (run_chain uses the same handle); the verb is a FIXED - # literal picked by the case, never a string from the request. local self="${PITHEAD_SELF:-$0}" case "$verb" in - restart) "$self" restart >"$logf" 2>&1 || rc=$? ;; + restart) PITHEAD_LOCK_TIMEOUT=0 "$self" restart >"$logf" 2>&1 || rc=$? ;; apply) "$self" apply -y >"$logf" 2>&1 || rc=$? ;; - *) return 0 ;; # unreachable: the dispatch already gated the verb + *) return 0 ;; esac - if [ "$rc" -eq 0 ]; then + if [ "$verb" = restart ] && [ "$rc" -eq "$PITHEAD_EX_LOCK_TIMEOUT" ]; then + rm -f "$cdir/restart-at" + control_write_result "$cdir/results" "$id" "$(jq -n --arg a "$verb" '{status:"rejected",action:$a,error:"another host operation took the lock first — nothing was restarted; try again once it has finished.",ts:(now|floor)}')" + control_audit "$cdir/audit/control.log" "$id" "$actor" "$verb" "rejected" + elif [ "$rc" -eq 0 ]; then control_write_result "$cdir/results" "$id" "$(jq -n --arg a "$verb" '{status:"applied",action:$a,ts:(now|floor)}')" control_audit "$cdir/audit/control.log" "$id" "$actor" "$verb" "applied" else diff --git a/lib/pithead/46c-control-svc-restart.sh b/lib/pithead/46c-control-svc-restart.sh index 628bfc0aac..48ecab4ae9 100644 --- a/lib/pithead/46c-control-svc-restart.sh +++ b/lib/pithead/46c-control-svc-restart.sh @@ -2,6 +2,7 @@ readonly PITHEAD_SVC_RESTART_SERVICES="tor monerod wallet-rpc tari tari-wallet p readonly PITHEAD_SVC_RESTART_COOLDOWN_S=120 readonly PITHEAD_SVC_RESTART_EX_GUARD=11 readonly PITHEAD_SVC_RESTART_EX_COOLDOWN=12 +readonly PITHEAD_SVC_RESTART_EX_REDIAL=13 control_svc_restart_locked() ( local cdir="$1" service="$2" logf="$3" stamp last now @@ -15,6 +16,7 @@ control_svc_restart_locked() ( [ $((now - last)) -ge "$PITHEAD_SVC_RESTART_COOLDOWN_S" ] || exit "$PITHEAD_SVC_RESTART_EX_COOLDOWN" docker compose restart "$service" >"$logf" 2>&1 || exit 1 printf '%s\n' "$now" >"$stamp" + [ "$service" != tor ] || (stack_redial_monerod) >>"$logf" 2>&1 || exit "$PITHEAD_SVC_RESTART_EX_REDIAL" ) control_svc_restart() { @@ -43,6 +45,12 @@ control_svc_restart() { "$PITHEAD_EX_LOCK_TIMEOUT") error="Another pithead operation is in progress; try again when it has finished." ;; "$PITHEAD_SVC_RESTART_EX_GUARD") error="The LAN-only source rule for the published ports is not in place, so a restart is refused. Run './pithead up' on the host." ;; "$PITHEAD_SVC_RESTART_EX_COOLDOWN") error="$service was restarted less than ${PITHEAD_SVC_RESTART_COOLDOWN_S}s ago; wait before restarting it again." ;; + "$PITHEAD_SVC_RESTART_EX_REDIAL") + control_write_result "$results" "$id" "$(jq -n '{status:"failed",action:"svc-restart",container:"tor",error:"tor restarted, but Tor did not report bootstrapped within the wait or monerod could not be restarted, so monerod may still hold dead peer connections. Restart monerod once Tor is healthy.",ts:(now|floor)}')" + control_audit "$auditf" "$id" "$actor" "svc-restart" "failed" "$service" + rm -f "$logf" + return 0 + ;; *) error="The restart of $service failed on the host: $(tail -c 1500 "$logf" 2>/dev/null | bundle_redact_log)" control_write_result "$results" "$id" "$(jq -n --arg s "$service" --arg e "$error" '{status:"failed",action:"svc-restart",container:$s,error:$e,ts:(now|floor)}')" diff --git a/lib/pithead/47-os-update-helpers.sh b/lib/pithead/47-os-update-helpers.sh index 2cc37b5624..428594f81b 100644 --- a/lib/pithead/47-os-update-helpers.sh +++ b/lib/pithead/47-os-update-helpers.sh @@ -152,3 +152,31 @@ os_verify_bundle_reason() { # fi return 0 } + +CONTROL_RESTART_COOLDOWN_S=120 + +control_restart_refusal() { # ; echoes the reason, empty = proceed + local step to last=0 now + now=$(date +%s) + [ ! -f "$1/restart-at" ] || [ -L "$1/restart-at" ] || read -r last <"$1/restart-at" || last=0 + [[ "$last" =~ ^[0-9]+$ ]] || last=0 + if [ "$last" -le "$now" ] && [ $((now - last)) -lt "$CONTROL_RESTART_COOLDOWN_S" ]; then + printf 'a restart was already requested %s seconds ago — nothing was restarted; try again in %s seconds.' "$((now - last))" "$((CONTROL_RESTART_COOLDOWN_S - (now - last)))" + return 0 + fi + step=$(jq -r '.step // ""' "$1/results/os-update-state.json" 2>/dev/null) || step="" + to=$(jq -r '.to // ""' "$(os_update_inflight_file)" 2>/dev/null) || to="" + case "$step" in + downloading | installing | verifying | reboot-pending) + printf 'an OS update is in progress (%s) — restarting the stack now could interrupt it. Nothing was restarted; try again once the update has finished.' "$step" + return 0 + ;; + esac + if [ -n "$to" ] && [ "$(os_running_version)" = "$to" ]; then + printf 'the installed OS update v%s is still being committed — restarting now could roll the machine back. Nothing was restarted; try again once it is committed.' "$to" + return 0 + fi + if ! (PITHEAD_LOCK_TIMEOUT=0 mutation_lock_acquire restart) >/dev/null 2>&1; then + printf 'another host operation (a config apply, backup, restore or upgrade) is running — nothing was restarted; try again once it has finished.' + fi +} diff --git a/lib/pithead/48b-control-tor-recover.sh b/lib/pithead/48b-control-tor-recover.sh index 4a8b1b93bd..a581437c60 100644 --- a/lib/pithead/48b-control-tor-recover.sh +++ b/lib/pithead/48b-control-tor-recover.sh @@ -1,7 +1,5 @@ -# Host control wrapper for the existing gated Tor recovery (#3118). -control_tor_recover() { # - local cdir="$1" id="$2" actor="$3" output status detail - # Isolate exit-on-contention and require_deployed failures from the request loop. +control_tor_recover() { # [action] + local cdir="$1" id="$2" actor="$3" action="${4:-tor-recover}" output status detail if output=$( (tor_recover apply) 2>&1); then status=applied detail="" @@ -10,6 +8,40 @@ control_tor_recover() { # detail=$(printf '%s\n' "$output" | bundle_redact_log | tail -c 4096) [ -n "$detail" ] || detail="Tor recovery refused or failed host verification" fi - control_write_result "$cdir/results" "$id" "$(jq -n --arg status "$status" --arg error "$detail" '{status:$status,action:"tor-recover",error:$error,ts:(now|floor)}')" - control_audit "$cdir/audit/control.log" "$id" "$actor" tor-recover "$status" + control_write_result "$cdir/results" "$id" "$(jq -n --arg status "$status" --arg action "$action" --arg error "$detail" '{status:$status,action:$action,error:$error,ts:(now|floor)}')" + control_audit "$cdir/audit/control.log" "$id" "$actor" "$action" "$status" +} + +CONTROL_TOR_RESET_COOLDOWN_S=1800 + +control_tor_reset() { # + local cdir="$1" id="$2" actor="$3" stamp="$1/tor-reset-at" last=0 now error="" + now=$(date +%s) + if [ -L "$stamp" ]; then + last=invalid + elif [ -f "$stamp" ]; then + read -r last <"$stamp" || last=invalid + fi + if ! [[ "$last" =~ ^[0-9]+$ ]]; then + error="the Reset Tor state record is invalid, so the reset was not attempted" + elif [ "$last" -le "$now" ] && [ $((now - last)) -lt "$CONTROL_TOR_RESET_COOLDOWN_S" ]; then + error="Reset Tor state was already requested $(((now - last) / 60)) minutes ago — wait $(((CONTROL_TOR_RESET_COOLDOWN_S - (now - last) + 59) / 60)) more minutes before asking again" + fi + if [ -n "$error" ]; then + control_write_result "$cdir/results" "$id" "$(jq -n --arg e "$error" '{status:"rejected",action:"tor-reset",error:$e,ts:(now|floor)}')" + control_audit "$cdir/audit/control.log" "$id" "$actor" tor-reset rejected + elif ! printf '%s\n' "$now" >"$stamp"; then + control_write_result "$cdir/results" "$id" "$(jq -n '{status:"failed",action:"tor-reset",error:"the Reset Tor state record could not be written",ts:(now|floor)}')" + control_audit "$cdir/audit/control.log" "$id" "$actor" tor-reset failed + else + control_tor_recover "$cdir" "$id" "$actor" tor-reset + fi +} + +stack_redial_after_restart() { + stack_redial_monerod + if [ -n "$(docker inspect tari --format '{{.State.Running}}' 2>/dev/null)" ]; then + log "Restarting tari so it starts after Tor is bootstrapped, not alongside it..." + docker compose restart tari + fi } diff --git a/lib/pithead/49-control-request-loop.sh b/lib/pithead/49-control-request-loop.sh index 86d4f151fd..7a47f708d4 100644 --- a/lib/pithead/49-control-request-loop.sh +++ b/lib/pithead/49-control-request-loop.sh @@ -113,6 +113,17 @@ control_process_request() { # control_tor_recover "$cdir" "$id" "$actor" fi ;; + tor-reset) + if [ "$(env_get TOR_AUTO_HEAL 2>/dev/null)" != true ]; then + control_write_result "$cdir/results" "$id" "$(jq -n '{status:"rejected",action:"tor-reset",error:"Tor auto-heal is off (TOR_AUTO_HEAL), so the Tor state reset is unavailable",ts:(now|floor)}')" + control_audit "$cdir/audit/control.log" "$id" "$actor" "$action" rejected + elif [ "$(jq -r 'keys | sort == ["action","actor","id"]' "$file")" != true ] || [ "$actor" = tor-heal ]; then + control_write_result "$cdir/results" "$id" "$(jq -n '{status:"rejected",action:"tor-reset",error:"invalid reset request",ts:(now|floor)}')" + control_audit "$cdir/audit/control.log" "$id" "$actor" "$action" rejected + else + control_tor_reset "$cdir" "$id" "$actor" + fi + ;; tor-history) # Read-only (#3052): reports only whether Tor's circuit-history state is saturated. if [ "$(env_get TOR_AUTO_HEAL 2>/dev/null)" != true ] || diff --git a/tests/integration/lib/run-hardening.sh b/tests/integration/lib/run-hardening.sh index 2375e936b8..da4cfe9017 100644 --- a/tests/integration/lib/run-hardening.sh +++ b/tests/integration/lib/run-hardening.sh @@ -132,6 +132,7 @@ run_hardening() { # gate: recovery is only asserted when the onion was reachable to begin with. # (Reachability is INBOUND; the clearnet-EXIT half of #424 is not externally observable and # stays with the doctor egress check, which is the stack self-checking its own egress.) + _hardening_restart_tor_redial_rows local pre_onion=0 if [ "$(env_on_box DASHBOARD_ONION_ADDRESS)" = "placeholder" ] || [ -z "$(env_on_box DASHBOARD_ONION_ADDRESS)" ]; then it_skip_leg "dashboard onion external reachability (#424/#343)" "onion not provisioned on this box" @@ -273,6 +274,8 @@ run_hardening() { assert_contains "control mutation audited (#33)" \ "$(rx "cat $(quote_arg "$cdir/audit/control.log") 2>/dev/null")" '"action":"commit"' + _hardening_stack_action_rows "$cdir" + local port_before port_after occupied_port port_rc=0 snapshot_rc=0 occupied_port="$(env_on_box HOST_PORT)" occupied_port="${occupied_port:-443}" diff --git a/tests/integration/lib/run-stack-actions.sh b/tests/integration/lib/run-stack-actions.sh new file mode 100644 index 0000000000..7f4b8f8596 --- /dev/null +++ b/tests/integration/lib/run-stack-actions.sh @@ -0,0 +1,66 @@ +# shellcheck shell=bash +: "${INTEGRATION_RUN_SUITE:?source via the suite runner}" +_container_started_ns() { # + rx "date -d \"\$(docker inspect $1 --format '{{.State.StartedAt}}')\" +%s%N" +} + +_monerod_started_after_tor() { #