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/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2476791498..ef2643b5a7 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@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 with: version: "0.12.13" checksum: 745765a3b6e360ad76743599ae5c42e9278c7edf8bbff9fc76d05bf2623a04dd @@ -289,8 +289,7 @@ jobs: body=$(cat report.md) # Exact title match over the open list, NOT `--search`: the search index lags issue # creation by minutes, so a search-based dedup files a second issue on the next run. - n=$(gh issue list --state open --limit 200 --json number,title \ - --jq "map(select(.title == \"$TITLE\")) | .[0].number // empty") + n=$(bash scripts/watch/find-open-issue.sh "$TITLE") # A run that could not do its job must not DELETE the "last fully successful" date — # that date is the only thing separating "failed once this morning" from "has been dead # for six weeks". Stamp it on success, carry it forward on failure (pin-watch pattern). @@ -346,7 +345,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@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 with: version: "0.12.13" checksum: 745765a3b6e360ad76743599ae5c42e9278c7edf8bbff9fc76d05bf2623a04dd @@ -390,7 +389,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@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 with: version: "0.12.13" checksum: 745765a3b6e360ad76743599ae5c42e9278c7edf8bbff9fc76d05bf2623a04dd @@ -430,7 +429,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@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 with: version: "0.12.13" checksum: 745765a3b6e360ad76743599ae5c42e9278c7edf8bbff9fc76d05bf2623a04dd diff --git a/.github/workflows/pin-watch.yml b/.github/workflows/pin-watch.yml index 650c6da5da..5c75865053 100644 --- a/.github/workflows/pin-watch.yml +++ b/.github/workflows/pin-watch.yml @@ -80,8 +80,7 @@ jobs: Review the component upgrade issues and newer Tari prereleases before changing pins. BODY ) - n=$(gh issue list --state open --limit 200 --json number,title \ - --jq "map(select(.title == \"$TITLE\")) | .[0].number // empty") + n=$(bash scripts/watch/find-open-issue.sh "$TITLE") if [ "$RC" != "0" ] && [ -n "$n" ]; then prev=$(gh issue view "$n" --json body --jq .body | grep -a "^_Last fully successful check:" || true) if [ -n "$prev" ]; then diff --git a/.github/workflows/scheduled-run-watch.yml b/.github/workflows/scheduled-run-watch.yml index c6873e0421..f4bb6e938d 100644 --- a/.github/workflows/scheduled-run-watch.yml +++ b/.github/workflows/scheduled-run-watch.yml @@ -117,8 +117,7 @@ jobs: body=$(cat report.md) # Exact title match over the open list, NOT `--search`: the search index lags issue # creation by minutes, so a search-based dedup files a second issue on the next run. - n=$(gh issue list --state open --limit 200 --json number,title \ - --jq "map(select(.title == \"$TITLE\")) | .[0].number // empty") + n=$(bash scripts/watch/find-open-issue.sh "$TITLE") # A run that could not do its job must not DELETE the "last fully successful" date — # that date is the only thing separating "failed once this morning" from "has been dead # for six weeks". Stamp it on success, carry it forward on failure (pin-watch pattern). diff --git a/.github/workflows/shell.yml b/.github/workflows/shell.yml index 226a613899..a2e564c8b6 100644 --- a/.github/workflows/shell.yml +++ b/.github/workflows/shell.yml @@ -133,6 +133,8 @@ jobs: 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_lifecycle_receipts.sh + bash tests/stack/standalone/test_tor_unsaturated_reset.sh + bash tests/stack/standalone/test_tor_reset.sh - name: Run onion runtime convergence contract run: bash tests/stack/standalone/test_onion_runtime.sh - name: Prove the interrupted-build diagnostic fails on RC3 @@ -203,6 +205,8 @@ jobs: run: python3 tests/stack/standalone/test_clearnet_attestation.py - name: Run stratum port preflight contract run: python3 tests/stack/standalone/test_stratum_port.py + - name: Run Quadlet image provenance contract + run: python3 tests/stack/standalone/test_quadlet_provenance.py - name: Test-inventory drift check run: bash tests/inventory.sh > /dev/null - name: Run integration harness self-test diff --git a/.github/workflows/tor-bump.yml b/.github/workflows/tor-bump.yml new file mode 100644 index 0000000000..4514207277 --- /dev/null +++ b/.github/workflows/tor-bump.yml @@ -0,0 +1,112 @@ +name: Tor pin bump + +on: + schedule: + - cron: "17 5 * * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + bump: + name: Open a PR when Alpine carries a newer tor + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: develop + persist-credentials: false + - name: Detect a newer tor in the Alpine repository + id: detect + run: bash scripts/watch/tor-bump.sh detect >>"$GITHUB_OUTPUT" + - name: Push the bump and open its PR + if: steps.detect.outputs.stale == 'true' + env: + GH_TOKEN: ${{ github.token }} + CURRENT: ${{ steps.detect.outputs.current }} + LATEST: ${{ steps.detect.outputs.latest }} + BRANCH: ${{ steps.detect.outputs.branch }} + run: | + set -Eeuo pipefail + branch="bot/tor-${LATEST}" + state="$(gh pr list --state all --head "$branch" --json state \ + --jq 'map(.state) | if index("OPEN") then "OPEN" elif length > 0 then .[0] else "none" end')" + if [ "$state" = OPEN ]; then + echo "PR for ${LATEST} is already open" + exit 0 + fi + if [ "$state" != none ]; then + echo "PR for ${LATEST} is ${state}; not reopening it" + exit 0 + fi + pre=no + if git ls-remote --exit-code --heads origin "$branch" >/dev/null 2>&1; then + pre=yes + git fetch origin "$branch" + git checkout -B "$branch" FETCH_HEAD + else + git checkout -B "$branch" + fi + bash scripts/watch/tor-bump.sh apply "$LATEST" + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add build/tor/Dockerfile + committed=no + if ! git diff --cached --quiet; then + git commit -m "build/tor: bump the Tor pin to ${LATEST}" + committed=yes + fi + if [ "$pre" = no ] && [ "$committed" = no ]; then + echo "the pin or the index moved during this run; nothing to propose" + exit 0 + fi + gh auth setup-git + if [ "$committed" = yes ]; then + git push origin "$branch" + fi + cat >pr-body.md < Maintenance section, with typed confirmation and host-side cooldowns (#2384). - Opt-in payout confirmation through a remote Monero node: `monero.view_key` with `monero.mode: remote` starts the view-only wallet against the configured node, through Tor under the Privacy profile. Earnings names the reason when tracking is incomplete. Tari stays local-node only (#2866). -- The appliance update channel is read as untrusted data: https-only fetches to the release hosts - over Tor with remote DNS, response size caps, release-tag validation before any URL or path, and - stale or replayed channel reporting in Check for updates (#4011). ### Fixed @@ -29,9 +26,6 @@ per the process in [`docs/dev/releasing.md`](docs/dev/releasing.md). ### Security -- The appliance rootfs builds Compose and Cosign with Go 1.26.11, clearing CVE-2026-97054 - in both binaries' standard library (#4265), and builds Compose v5.7.2, whose containerd v2.4.2 - clears CVE-2026-95839 (#4291). - The Alpine images pull the patched musl past their digest-pinned base (CVE-2026-107891, #3929). - The Ubuntu and Debian image builds list apt, and the dashboard image and the appliance rootfs also zlib1g, in their install lists, pulling the distro's security builds past the digest-pinned @@ -39,6 +33,219 @@ per the process in [`docs/dev/releasing.md`](docs/dev/releasing.md). - The appliance rootfs raises golang.org/x/net to 0.62.0 in the Cosign and Docker Compose it builds, clearing CVE-2026-78661 in both binaries (#3931). +## [2.0.4] - 2026-11-24 + +Pithead 2.0.4 is a patch release after 2.0.3. It bakes RigForge 1.19.0 into the appliance image +(read the RigForge-only note below before updating such a rig), moves XvB donation mining to the EU +server, adds a sign-in page, a windowed support-bundle and log export, per-service and Restart all +buttons in Service diagnostics, and a Tor auto-heal that no longer stalls, stops serving stratum work +when the node cannot make valid work so rigs fail over to their backup pool, labels where each rig +mines, and clears the image-scan findings in the Go toolchain and containerd. + +It adds and removes no Pithead configuration keys. It changes these defaults: `monero.out_peers` from +48 to 24 (#4078), `xvb.url` to the EU server with a saved NA host moved on the next apply (#4308), Tor's +`SocksPort` binds the bridge address instead of the wildcard address (#4047), and Caddy moves to 2.11.9. + +### Added + +- `./pithead support-bundle` on a Docker host takes `--since` and `--until` (or `--hours`) and writes the + same windowed `.zip` and manifest as the appliance: every container's full log for the window instead of + the last 200 lines, the DIY egress and LAN-guard units from the journal, and an engine or journal that + cannot be read recorded in the manifest (#4130). +- The appliance support bundle (the **Support bundle** card and `pithead recovery-bundle`) now carries state snapshots beside the journal: `doctor.json`, monerod, Tari and P2Pool status, Tor control-port and guard state (never a key), network, time, container (exit codes and image digests), RAUC, boot-slot and coredump records, Caddy access logs for the window with credentials removed, the files saved under `/data/pithead/support/`, a `/data/pithead` marker listing, and an uncapped dashboard history export with `ping_failures` and the control audit events. Every step has a time limit and the whole collection a total limit; a step that times out or fails is recorded in `manifest.json` and the bundle is still produced (#4128). +- 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 + ends every session, wrong passwords are rate-limited, and scripts keep using HTTP basic auth with + the same credentials (#4089). On a full data disk an existing session still passes the gate, a + restarted dashboard still starts and reports `db_healthy:false`, and signing in says the data disk is + full instead of failing with a server error (#4199). +- The dashboard's **Export logs** card (Backup tab) has a time-frame picker (last 1 h, 6 h, 24 h, 72 h or 7 days, or a custom start and end), shows how far back the logs reach and flags a range that goes further, and collects and downloads the `support-bundle-.zip` with one click, showing the window the manifest recorded. It is always available, on the appliance and on DIY, whether or not `dashboard.control.enabled` is on: with the switch off the host runner serves only the export, and config editing, restart and the other control actions stay off. With a dashboard password set, every export route needs the login (#4129). +- The appliance update channel is read as untrusted data: https-only fetches to the release hosts + over Tor with remote DNS, response size caps, release-tag validation before any URL or path, and + stale or replayed channel reporting in Check for updates (#4011). The appliance rootfs also carries + the on-demand Tor client the rig update will use in 2.0.5 (#4139). +- The Service diagnostics card has a **Restart** button for each of tor, monerod, wallet-rpc, tari, + tari-wallet, p2pool and xmrig-proxy. It goes through the host control channel, is refused while the + LAN guard is not ready or the host lock is busy, allows one restart per service every 120 seconds + and is audited (#4062). +- The header shows **Mining paused here** and its reason (stratum closed, node out of sync, node syncing or + P2Pool isolated) with the number of rigs on a backup pool, and the dashboard shows a **Monero node + offline** banner when monerod is red or, with `tor.auto_heal` on, when Tor egress has been down past + the 15-minute window. The banner needs no Tor to display (#4073, #4079). +- The Workers table says where each rig mines: "on backup pool", "not connected to this Pithead" or + "mining location unknown". Rigs mining elsewhere no longer count in Workers Alive or Total Hashrate, + a `DOWN` row explains itself, the rig's own hashrate has a separate "Rig telemetry 1m" column, and a + proxy client with no rig name is listed as an unnamed proxy worker (#4071, #4072). +- Failed Healthchecks pings are recorded in a ring table and shown on the health page, without the + ping URL (#4037). + +### Changed + +- When P2Pool or monerod cannot make valid work (a peerless monerod that still reports synchronized, a + monerod stalled behind P2Pool's peers, P2Pool without peers or ZMQ, or a monerod, p2pool or tor + container down or unhealthy), the dashboard now stops `xmrig-proxy` after a debounce so rigs fail + over to their backup pool, and readmits them only when every trigger has been clear for 60 seconds. + Before, only an unreachable node stopped the proxy. The log names every trigger that held the proxy + and why readmission stayed blocked (#4046, #4165). After a stack recreate the proxy can stay stopped + for minutes even though every service is healthy; the root-cause fix is planned for 2.0.5 (#4138, + #4160). +- The Healthchecks.io ping runs in its own task every 60 seconds with a 30-second hard deadline and a + fresh-circuit retry, so a stalled collector or a long apply no longer reads as a down server, and the + Tor healer's first repair comes after 5 minutes of failure instead of 15 (#4135). +- Tor's `SocksPort` binds the bridge address instead of the wildcard address and `WarnUnsafeSocks 0` + silences the IP-only SOCKS warnings that monerod and Tari gossip dials produced several times a + minute (#4047). +- Caddy is updated from 2.11.7 to 2.11.9. +- XvB donation mining now defaults to `eu.xmrvsbeast.com:4247`, because XMRvsBeast is retiring its NA servers. A saved `xvb.url` on `na.xmrvsbeast.com` (any port) is moved to the EU host with the same port on the next apply, the prior file is kept as `config.json.bak-xvb-na`, a custom host is left alone, and Tor routing is unchanged (#4308). +- The appliance support bundle (the dashboard's **Support bundle** card and `pithead recovery-bundle`) is now one `.zip` for a chosen start and end time (`--since` and `--until` on the CLI, `since` and `until` on the control request; `hours` still works). It holds the whole system journal, the kernel log, the boot list and a journal per Pithead and quadlet unit read from the installed unit files, redacted, with a `manifest.json` that records the windows, the oldest retained entry, the journald usage and every truncated, empty, missing or failed file. Oversize files keep their oldest and newest lines instead of the bundle being refused, and the journald cap is raised from 200 MiB to 400 MiB to cover 168 hours at the log volume reported for a loaded test box (#4127). +- The appliance image bakes RigForge 1.19.0. Its prebuilt XMRig is the same 6.26.0 pin with the zero donation default and minimum, so a fresh image and an upgraded rig start mining without an XMRig rebuild; the vendored RigForge contract fixtures move to v1.19.0 with the pin (#4230, #4300). + +### Fixed + +- After an apply or restart that restarts monerod, the dashboard no longer stops `xmrig-proxy` about + 90 seconds after monerod is synchronized again. The "P2Pool reports monerod is not synchronized" + guard now counts only a line from the last 30 seconds, instead of any line from the last 2 minutes + (#4138). +- A rig whose miner stays at zero hashrate or without a pool connection for 120 seconds (for example after the coordinator's stratum port restarts) now has its XMRig restarted by `pithead-miner-recovery`, at most once every 300 seconds (#4387). +- On the appliance, a built-in miner that lost its stratum connection because `xmrig-proxy` was + recreated (an apply, a compose restart or a recovery-boot migration) is restarted at once instead + of after five minutes of idle readings. The root cause of the stall is still not established + (#3375). +- On the appliance, opening **Set up again** on a committed slot no longer leaves the boot-slot try + flag raised, so powering off or rebooting without choosing no longer boots the previous release + (#3960). +- P2Pool with no incoming or outgoing peers for 15 minutes is restarted with a 20, 40 and 80 minute + backoff, at most three times a day, with an audit row and a warning when the cap is reached. A + monerod with no outgoing peers for 5 minutes after any Tor start is restarted once per Tor start, + with or without `tor.auto_heal` (#4077, #4076). +- On the appliance, when the boot health gate cannot clear the chain-service migration hold it prints + a FAULT line naming the recovery and releases the chain services anyway, instead of leaving node, + P2Pool and proxy down with nothing in the boot journal (#3983). +- A release now tags and bundles exactly the commit that was gated: publish refuses if HEAD moved or the + tree is dirty, a tag already on origin or an already-promoted registry tag stops the cut, and the + tag is created on the gated commit (release tooling only). +- 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). +- `./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). +- The Tor egress auto-heal no longer stalls when the host refuses NEWNYM. A rejected refresh now + spends its rung and the ladder moves on to a host-gated state reset and then a Tor restart, + capped at four per rolling day, instead of repeating NEWNYM forever. `tor-recover` accepts a + sustained outage, a wedged control port or a stalled bootstrap as reset reasons when egress is + still down, the heal reads Tor's control-port circuit state, and giving up is written to the + host audit log. Past the cap the heal keeps probing every 15 minutes and re-alerts at most once + an hour, naming the outage length, until one recovery notice on egress returning (#4075). +- 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). +- Rig upgrade, Adopt rig, Backup, the onion client-key request and the service diagnostics show the + same stale-page message and reload instead of `HTTP 401`, `HTTP 403` or a browser network error, and + show the server's text for other failures (#4059). +- Payout confirmation skips a scan when the view-only wallet does not hold the configured payout address, + so an address change no longer files the old wallet's payouts under the new address or alerts on them. +- XvB request failures no longer write the payout address or the submit URL into the dashboard log. +- The setup wizard keeps a worker's `api_token` instead of dropping it. +- The setup wizard's failed screen no longer breaks when the host's error text ends in a cut-off character. +- A failed write when applying a configuration change from the dashboard returns a server error and is + logged, instead of reporting "Body must be JSON". +- 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). +- 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). +- The Service diagnostics card's log and health-check controls are styled as buttons instead of plain + text (#4109). +- A configuration whose data directories are nested (for example `p2pool.data_dir` containing + `monero.data_dir`) is refused, naming both keys, instead of letting a reset of one wipe the other. +- A data directory written with a trailing slash (`/srv/`, `/home/user/`) is held to the same system, + home and mount-root refusal as the same path without one. +- `./pithead config-reset` now also removes the Tari wallet database volume, whose password lives only in + the removed `.env`, so Tari payout confirmation no longer breaks after a reset. +- The `curl | bash` installer reattaches the terminal before `./pithead setup`, and stops with a clear + message when none is available. +- A hand-edited `dashboard.secure` of `"TRUE"`, `1` or `"yes"` now renders the TLS Caddyfile, matching + `doctor`, instead of silently serving plain HTTP. + +### Security + +- The appliance rootfs builds Docker Compose and Cosign with Go 1.26.11, clearing CVE-2026-97054 + in both binaries' standard library (#4265), and builds Compose v5.7.2, whose containerd v2.4.2 + clears CVE-2026-95839 (#4291, #4279). + +### Notes + +- **RigForge-only appliances: 2.0.4 changes the rig — RigForge 1.19.0.** RigForge 1.19.0 seeds + `tor_socks5` `127.0.0.1:9050` on an appliance rig and fails closed when nothing listens there, and + the appliance rig runs no Tor proxy at that address. A rig therefore refuses `upgrade --check`, the + XMRig clone and a remote upgrade, and `doctor` warns on its `tor-socks5` row. The rig rewrites its miner + config on every boot without `tor_socks5`, so an override set on the rig does not persist. RigForge also refuses a `DONATION` above 0 while `tor_socks5` is set, because the donation pool + would dial direct, and this applies to a saved value too: a 2.0.3 rig with `DONATION` above 0 stops + mining after the update, because its miner setup fails on the next boot. Before updating such a rig, + set `DONATION` to 0 in the dashboard's Workers view. A rig + with `DONATION` 0 keeps mining on the prebuilt miner. `threads` is now honored and capped, so a rig + that mined every core before this settles at the capped count after the next apply, with a lower + hashrate (rigforge#588 and rigforge#632). A validated + `xmrig` config overlay plus configurable RandomX modes give owners control over miner settings. The baked XMRig is unchanged + (6.26.0, zero donation default and minimum), so the built-in miner and upgraded rigs keep mining + without a rebuild. Updating a rig still needs the USB stick, and re-flashing a rig that runs from + its stick wipes its setup and token, so it must be adopted again. Updating rigs from the Pithead + dashboard is planned for 2.0.5 (#1837). + +### Known issues in 2.0.4 + +The [known issues listed for 2.0.3](https://github.com/p2pool-starter-stack/pithead/blob/main/CHANGELOG.md#known-issues-in-203), +including those it carries over from 2.0.2, 2.0.1 and 2.0.0, still apply, except #3960, #3987 +and #3998, which are fixed above, and the RigForge `threads` issue (rigforge#588), which RigForge +1.19.0 fixes (see the RigForge-only note above). #3375 is closed: the restarts above mitigate it, +but its cause is not established, so the stall can recur. These five are new, and each is planned +for 2.0.5: + +- After a stack recreate (an apply, an update, a reboot or Restart all), the dashboard can stop + `xmrig-proxy` and leave it stopped for minutes after every service is healthy, so rigs mine on + their backup pool or not at all. A test saw it stay stopped for at least 4.6 minutes. The cause is + not found. The dashboard log names the reason it stopped the proxy and the time it was readmitted, + and the support bundle carries that log. No workaround has been established (#4138, #4160). +- After a Tor restart, Tor can sit at "Bootstrapped 95%" for about an hour. Monerod, Tari and P2Pool + have no Tor until it ends, and a second restart does not help because it keeps the same guards. + The healer, an update or a reboot can trigger it. Alerts travel over Tor, so the outage can be + silent. The cause is inferred, not confirmed (#4121). +- Tor's cached directory can go stale on an appliance that has run for days. After a restart Tor can + stay at "Requesting descriptors" for many minutes, or clearnet probes can pass while onion peers + fail and leave Tari or monerod without peers, and Tor auto-heal sees nothing wrong or its last + step does not cure it. Appliance owners have no shell for the manual cure (#4261). +- A monerod that keeps live outgoing peers but stores no new block is not restarted on its own. Use + Service diagnostics' **Restart** button for monerod (#4192). +- The support-bundle download is proven on appliance hardware for a baseline stack and with Tor + wedged, but not yet with monerod stopped. The bundle is meant to record the monerod snapshot as + unavailable and still complete, and that is untested on the appliance (#4131). + ## [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/Makefile b/Makefile index bef6fc9666..89048fc0da 100644 --- a/Makefile +++ b/Makefile @@ -35,6 +35,8 @@ test-stack: pithead ## pithead shell test suite bash tests/stack/standalone/test_tor_diagnostics.sh bash tests/stack/standalone/test_tor_heal_outage_recovery.sh bash tests/stack/standalone/test_tor_lifecycle_receipts.sh + bash tests/stack/standalone/test_tor_unsaturated_reset.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 @@ -43,6 +45,7 @@ test-stack: pithead ## pithead shell test suite bash tests/stack/standalone/test_grub_hugepages_real.sh python3 tests/stack/standalone/test_clearnet_attestation.py python3 tests/stack/standalone/test_stratum_port.py + python3 tests/stack/standalone/test_quadlet_provenance.py test-netwatch: ## netwatch passive flow-audit: classifier verdicts + the test-tool coverage guard (no bench, no network) @# Tier 1 on purpose. The capture needs a bench; the JUDGEMENT does not, and the judgement is @@ -75,6 +78,8 @@ test-tools: pithead python3 tests/stack/standalone/test_tor_saturated_fixture.py python3 tests/stack/standalone/test_monero_download.py python3 tests/stack/standalone/test_appliance_release_docs.py + bash scripts/watch/tor-bump.sh --self-test + bash tests/watch/test-find-open-issue.sh sed -n '/^ shell-block:$$/,/^ shell-fragment:$$/p' .github/workflows/shell.yml | grep -Eq '^ timeout-minutes: 15( |$$)' sed -n '/^ shell-fragment:$$/,/^ shell:$$/p' .github/workflows/shell.yml | grep -Eq '^ timeout-minutes: 12( |$$)' sed -n '/^ shell:$$/,/^ shell-standalone:$$/p' .github/workflows/shell.yml | grep -Eq '^ timeout-minutes: 5( |$$)' @@ -122,6 +127,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) @@ -159,7 +166,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 os/overlay/pithead-tor \ 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/VERSION b/VERSION index 50ffc5aa7f..2165f8f9b6 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.0.3 +2.0.4 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 a9c080ec47..821bb2aa2e 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/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/tor/Dockerfile b/build/tor/Dockerfile index c67d5bb32c..b628d66140 100644 --- a/build/tor/Dockerfile +++ b/build/tor/Dockerfile @@ -1,8 +1,10 @@ # Pinned to a named minor version by digest (#135, #373). The digest is authoritative; the tag # names the Alpine minor line (3.24) so Dependabot's patch-update policy has a real version to track. -FROM alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6 +FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf -RUN apk add --no-cache --upgrade libcrypto3 libssl3 musl musl-utils tor netcat-openbsd +ARG TOR_VERSION=0.4.9.17-r0 +RUN apk add --no-cache --upgrade libcrypto3 libssl3 musl musl-utils "tor=${TOR_VERSION}" netcat-openbsd \ + && tor --version | grep -F "Tor version ${TOR_VERSION%-r*}." COPY torrc.template /etc/tor/torrc.template COPY entrypoint.sh /usr/local/bin/tor-entrypoint.sh diff --git a/build/tor/control-signal.sh b/build/tor/control-signal.sh index eee4f459c5..662c1c8ef7 100644 --- a/build/tor/control-signal.sh +++ b/build/tor/control-signal.sh @@ -1,9 +1,23 @@ #!/bin/sh # Fixed, cookie-authenticated circuit refresh for the host control runner. set -eu -[ "${1:-}" = NEWNYM ] && [ "$#" -eq 1 ] || exit 2 +case "${1:-}" in NEWNYM | STATUS) ;; *) exit 2 ;; esac +[ "$#" -eq 1 ] || exit 2 cookie=$(xxd -p -c 256 "${TOR_COOKIE_FILE:-/var/lib/tor/control_auth_cookie}" | tr -d '\n') [ -n "$cookie" ] || exit 1 +if [ "$1" = STATUS ]; then + reply=$(printf 'AUTHENTICATE %s\r\nGETINFO status/circuit-established circuit-status\r\nQUIT\r\n' "$cookie" | + nc -w 3 127.0.0.1 9051) || exit 1 + printf '%s\n' "$reply" | tr -d '\r' | awk ' + NR == 1 { if ($0 != "250 OK") exit 1; next } + /^250-status\/circuit-established=[01]$/ { split($0, a, "="); est = a[2]; next } + /^250\+circuit-status=$/ { listing = 1; next } + listing && $0 == "." { listing = 0; next } + listing { if ($2 == "LAUNCHED" || $2 == "EXTENDED") pending++; next } + END { if (est == "") exit 1; printf "circuit-established=%s pending=%d\n", est, pending + 0 } + ' + exit +fi reply=$(printf 'AUTHENTICATE %s\r\nSIGNAL NEWNYM\r\n' "$cookie" | nc -w 3 127.0.0.1 9051) || exit 1 [ "$(printf '%s\n' "$reply" | grep -c '^250 OK')" -eq 2 ] || exit 1 diff --git a/build/tor/torrc.template b/build/tor/torrc.template index 626faba36c..1ad0dd1a7f 100644 --- a/build/tor/torrc.template +++ b/build/tor/torrc.template @@ -3,9 +3,8 @@ DataDirectory /var/lib/tor # --- Network Interfaces --- -# SOCKS5 proxy interface for routing container traffic through Tor -# Binds to 0.0.0.0 to accept connections from other services in the Docker network -SocksPort 0.0.0.0:9050 +SocksPort __NETWORK_PREFIX__.25:9050 +WarnUnsafeSocks 0 # Control interface. No other container uses it: Tari reaches Tor through the SOCKS port only, and # its onion is the Tari hidden service the entrypoint appends (#2653). Bind explicitly to this @@ -37,6 +36,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/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/config.reference.json b/config.reference.json index 4347aae5ce..9bfce3b20d 100644 --- a/config.reference.json +++ b/config.reference.json @@ -18,7 +18,7 @@ }, "xvb": { "enabled": false, - "url": "na.xmrvsbeast.com:4247", + "url": "eu.xmrvsbeast.com:4247", "donor_id": "auto", "donation_level": "auto", "tor": true, @@ -48,7 +48,7 @@ "zmq_port": 18083 }, "prep_blocks_threads": "auto", - "out_peers": 48, + "out_peers": 24, "data_dir": "auto", "mem_limit": "auto", "backup_nodes": [] diff --git a/dashboard/Dockerfile b/dashboard/Dockerfile index d0d5048209..568cb4f8ce 100644 --- a/dashboard/Dockerfile +++ b/dashboard/Dockerfile @@ -4,7 +4,7 @@ # uv's own CVEs into image scans, #282). uv lives only in the build/test stages. # ========================================================================== # Pinned by digest (#135) so the python:3.11-slim tag can't be silently re-pointed. -FROM python:3.11-slim@sha256:e41613d42d4891e4930f79523f93f81bbc7632584ec65e36ab055f41a800b41e AS base +FROM python:3.11-slim@sha256:07d4824036af339fa1b6ef769cc99d9c10a141769538b52b3b597c84f7a7b535 AS base # Run from a project venv on PATH (so entrypoint.sh's `python3` resolves to it); use the # digest-pinned base interpreter (never let uv download a different Python); compile bytecode and @@ -32,6 +32,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ libpcre2-8-0 \ libsqlite3-0 \ libssl3t64 \ + libzstd1 \ openssl \ openssl-provider-legacy \ perl-base \ diff --git a/dashboard/README.md b/dashboard/README.md index 022feb0a72..d12c6e3dfb 100644 --- a/dashboard/README.md +++ b/dashboard/README.md @@ -16,6 +16,29 @@ 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 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 @@ -53,7 +76,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/client/rig_reply.py b/dashboard/mining_dashboard/client/rig_reply.py new file mode 100644 index 0000000000..361b0438bc --- /dev/null +++ b/dashboard/mining_dashboard/client/rig_reply.py @@ -0,0 +1,86 @@ +from mining_dashboard.helper.utils import finite_number, plausible_rate, safe_text + +_TEXT_MAX = 1024 +_NUMBER_MAX = 2**63 - 1 +_DEPTH_MAX = 16 + + +def _flag(value): + return value if isinstance(value, bool) else None + + +def _text(limit): + return lambda value: safe_text(value, limit) + + +def _clipped(limit): + def clip(value): + if not isinstance(value, str): + return None + return "".join(char if char.isprintable() else " " for char in value[:limit]) + + return clip + + +_SHAPE = { + "uptime": finite_number, + "kind": _text(64), + "generated_at": _text(64), + "hashrate": {"total": [plausible_rate]}, + "connection": {"uptime": finite_number, "pool": _text(255)}, + "rigforge": { + "version": _text(64), + "stamp": _text(256), + "xmrig_api": _text(64), + "tune": {"target": _text(64), "autotune": {"next": _text(64)}}, + "power": {"watts": finite_number, "hs_per_watt": finite_number}, + "health": { + "governor": _text(64), + "throttling": _flag, + "hugepages_total": finite_number, + "firmware": {"board": _text(128)}, + }, + "watchdog": { + "mode": _text(64), + "thermal_hold": _flag, + "temp_c": finite_number, + "max_temp_c": finite_number, + }, + "control": {"change_id": _text(64), "status": _text(64), "reason": _clipped(500)}, + "config": {}, + "config_meta": {}, + }, +} + + +def _shaped(value, shape): + if isinstance(shape, dict): + if not isinstance(value, dict): + return None + for key, rule in shape.items(): + if key in value: + value[key] = _shaped(value[key], rule) + if value[key] is None: + del value[key] + return value + if isinstance(shape, list): + return [_shaped(item, shape[0]) for item in value] if isinstance(value, list) else None + return shape(value) + + +def _bounded(value, depth=0): + if depth > _DEPTH_MAX: + return None + if isinstance(value, dict): + return {key[:_TEXT_MAX]: _bounded(item, depth + 1) for key, item in value.items()} + if isinstance(value, list): + return [_bounded(item, depth + 1) for item in value] + if isinstance(value, str): + return safe_text(value[:_TEXT_MAX], _TEXT_MAX) + if isinstance(value, bool) or value is None: + return value + return value if -_NUMBER_MAX <= value <= _NUMBER_MAX else 0 + + +def usable_reply(payload): + return _bounded(_shaped(payload, _SHAPE)) diff --git a/dashboard/mining_dashboard/client/xmrig_client.py b/dashboard/mining_dashboard/client/xmrig_client.py index 744910a4c9..5f3853449a 100644 --- a/dashboard/mining_dashboard/client/xmrig_client.py +++ b/dashboard/mining_dashboard/client/xmrig_client.py @@ -4,6 +4,7 @@ import time from mining_dashboard.client.rig_config_meta import parse_config_meta +from mining_dashboard.client.rig_reply import usable_reply from mining_dashboard.client.rigforge_freshness import STALE_AFTER_S, feed_age from mining_dashboard.config.config import ( API_TIMEOUT, @@ -416,13 +417,10 @@ async def get_stats(self, ip, name): headers = self._auth_header(name_token, "") try: - async with self.session.get(url, headers=headers, timeout=API_TIMEOUT) as response: + async with self.session.get( + url, headers=headers, timeout=API_TIMEOUT, allow_redirects=False + ) as response: if response.status == 200: - # The bounded async read was worked out here (#1347) and lifted into - # ``bounded_read`` by #1360 — one contract, one implementation; the - # ``bytearray``/short-read rationale lives in ``helper/http.py``. Overflow is a - # refusal for THIS rig only, never an exception that takes the poll down for - # every other worker, so it is caught here, not by the blanket handler below. try: body = await bounded_read( response.content, @@ -434,6 +432,7 @@ async def get_stats(self, ip, name): return {"api_ok": False, "adopted": adopted} payload = json.loads(body) if isinstance(payload, dict): + payload = usable_reply(payload) self._warned.pop(host, None) # recovered — allow the next failure to log payload["api_ok"], payload["adopted"] = True, adopted return payload diff --git a/dashboard/mining_dashboard/client/xvb_client.py b/dashboard/mining_dashboard/client/xvb_client.py index 3018376955..f684f6236b 100644 --- a/dashboard/mining_dashboard/client/xvb_client.py +++ b/dashboard/mining_dashboard/client/xvb_client.py @@ -1,5 +1,6 @@ import logging import re +import time from datetime import UTC, datetime from typing import Any @@ -7,8 +8,8 @@ from mining_dashboard.config.config import XVB_HTTP_PROXY as TOR_SOCKS_PROXY from mining_dashboard.config.config import XVB_SUBMIT_URL -from mining_dashboard.helper.http import bounded_get -from mining_dashboard.helper.utils import parse_hashrate +from mining_dashboard.helper.http import bounded_get, request_failure_class +from mining_dashboard.helper.utils import parse_hashrate, plausible_rate # The four donor tiers XvB publishes an expected per-player reward for. These are exactly the tier # keys in TIER_DEFAULTS, so build_xvb_calc maps a tier straight to its estimate by key (#118). @@ -52,6 +53,10 @@ def parse_reward_estimates(text): # fabricated rows for our (publicly derivable) masked wallet in a single sync. _WINNERS_MAX_LINES = 5000 _WINNERS_MAX_WINS = 200 +_WINNERS_MAX_FUTURE_S = 3600 +_WINNERS_MAX_HEIGHT = 10**12 +_XVB_MAX_FAIL_COUNT = 1000 +_XVB_MAX_HASHRATE = 1e12 # The hashrate token in a winners row, e.g. "4203.5kH/s" — value and unit, no space between them. _REGEX_WINNER_HASHRATE = re.compile(r"([\d.]+)\s*([kKmMgG]?H/s)?$") @@ -88,8 +93,11 @@ def parse_winners(text, wallet_address): height = int(fields[4]) except ValueError: continue + if ts > time.time() + _WINNERS_MAX_FUTURE_S or not 0 <= height <= _WINNERS_MAX_HEIGHT: + continue hr_match = _REGEX_WINNER_HASHRATE.match(fields[3]) hashrate = parse_hashrate(hr_match.group(1), hr_match.group(2)) if hr_match else 0.0 + hashrate = plausible_rate(hashrate, _XVB_MAX_HASHRATE) or 0.0 wins.append( { "ts": ts, @@ -182,8 +190,9 @@ def __init__(self, wallet_address, tor_proxy=None, submit_url=None): # Pre-compile regex patterns self.REGEX_FAIL_COUNT = re.compile(r"Fail Count:\s*(\d+)", re.IGNORECASE) - self.REGEX_HR_1H = re.compile(r"1hr avg:\s*([\d\.]+)\s*([kKmMgG]?H/s)?", re.IGNORECASE) - self.REGEX_HR_24H = re.compile(r"24hr avg:\s*([\d\.]+)\s*([kKmMgG]?H/s)?", re.IGNORECASE) + number = r"(\d+(?:\.\d+)?)(?!\d|\.[\d.eE]|[eE])\s*([kKmMgG]?H/s)?" + self.REGEX_HR_1H = re.compile(r"1hr avg:\s*" + number, re.IGNORECASE) + self.REGEX_HR_24H = re.compile(r"24hr avg:\s*" + number, re.IGNORECASE) def get_stats(self) -> dict[str, Any] | None: """ @@ -212,7 +221,7 @@ def get_stats(self) -> dict[str, Any] | None: ) return None except requests.RequestException as e: - self.logger.error(f"Network error while fetching XvB stats: {e}") + self.logger.error(f"Network error while fetching XvB stats: {request_failure_class(e)}") return None except Exception as e: self.logger.error(f"Unexpected error in XvB client: {e}") @@ -242,7 +251,9 @@ def get_reward_estimates(self) -> dict[str, float] | None: return None return estimates except requests.RequestException as e: - self.logger.error(f"Network error while fetching XvB reward estimates: {e}") + self.logger.error( + f"Network error while fetching XvB reward estimates: {request_failure_class(e)}" + ) return None except Exception as e: self.logger.error(f"Unexpected error fetching XvB reward estimates: {e}") @@ -277,7 +288,9 @@ def get_recent_wins(self) -> dict[str, Any] | None: "round_stats": parse_round_stats(response.text), } except requests.RequestException as e: - self.logger.error(f"Network error while fetching XvB winners: {e}") + self.logger.error( + f"Network error while fetching XvB winners: {request_failure_class(e)}" + ) return None except Exception as e: self.logger.error(f"Unexpected error fetching XvB winners: {e}") @@ -352,40 +365,35 @@ def register(self): ) return REG_ERROR except requests.RequestException as e: - self.logger.error(f"Network error while registering with XvB: {e}") + self.logger.error( + f"Network error while registering with XvB: {request_failure_class(e)}" + ) return REG_ERROR except Exception as e: self.logger.error(f"Unexpected error during XvB registration: {e}") return REG_ERROR + def _average(self, regex, html_text): + match = regex.search(html_text) + return plausible_rate(parse_hashrate(*match.groups()), _XVB_MAX_HASHRATE) if match else None + def _parse_html(self, html_text) -> dict[str, Any] | None: """ Parses raw HTML content to extract mining statistics. """ try: - stats = {"fail_count": 0, "avg_1h": 0.0, "avg_24h": 0.0} - - # Extract Fail Count fail_match = self.REGEX_FAIL_COUNT.search(html_text) - if fail_match: - stats["fail_count"] = int(fail_match.group(1)) - - # Extract Hashrate Averages - hr1_match = self.REGEX_HR_1H.search(html_text) - hr24_match = self.REGEX_HR_24H.search(html_text) - - if hr1_match: - stats["avg_1h"] = parse_hashrate(hr1_match.group(1), hr1_match.group(2)) - - if hr24_match: - stats["avg_24h"] = parse_hashrate(hr24_match.group(1), hr24_match.group(2)) - - if not fail_match and not hr1_match: + fail_count = int(fail_match.group(1).lstrip("0")[:9] or 0) if fail_match else 0 + avg_1h = self._average(self.REGEX_HR_1H, html_text) + if not fail_match and avg_1h is None: self.logger.warning( "Parsing Warning: Critical stats not found in XvB response. HTML structure may have changed." ) return None - + stats = {"fail_count": min(fail_count, _XVB_MAX_FAIL_COUNT)} + if avg_1h is not None: + avg_24h = self._average(self.REGEX_HR_24H, html_text) + stats.update(avg_1h=avg_1h, avg_24h=avg_24h or 0.0) return stats except Exception as e: diff --git a/dashboard/mining_dashboard/collector/logs.py b/dashboard/mining_dashboard/collector/logs.py index 30ccce3706..52e7d76b8b 100644 --- a/dashboard/mining_dashboard/collector/logs.py +++ b/dashboard/mining_dashboard/collector/logs.py @@ -59,7 +59,7 @@ def _log_cap(tail): _monero_client = MoneroClient() -async def fetch_docker_logs(container_name, tail=None): +async def fetch_docker_logs(container_name, tail=None, since=None): """ Fetches logs from a container via the Docker Socket Proxy. Handles the Docker binary stream format (multiplexed stdout/stderr). @@ -75,6 +75,8 @@ async def fetch_docker_logs(container_name, tail=None): # Docker Engine API: /containers/{id}/logs url = f"{base_url}/containers/{container_name}/logs" params = {"stdout": 1, "stderr": 1, "tail": tail} + if since is not None: + params["since"] = int(since) try: async with aiohttp.ClientSession() as session: diff --git a/dashboard/mining_dashboard/collector/pools.py b/dashboard/mining_dashboard/collector/pools.py index 1c436c71c8..5f2864ec71 100644 --- a/dashboard/mining_dashboard/collector/pools.py +++ b/dashboard/mining_dashboard/collector/pools.py @@ -1,6 +1,9 @@ import json import os +import re +import time +from mining_dashboard.collector.logs import fetch_docker_logs from mining_dashboard.config.config import ( NETWORK_STATS_PATH, P2P_STATS_PATH, @@ -10,6 +13,12 @@ TARI_STATS_PATH, ) +_UNSYNCED = "monerod is not synchronized" +UNSYNCED_LOOKBACK_SEC = 30 +_AHEAD_RE = re.compile( + r"peer (\S+) is ahead on mainchain \(height (\d{1,20}), your height (\d{1,20})\)" +) + # Last-good parse per stats-file path, mirroring how `_merge_proxy_summary` keeps the last-good # proxy totals (#141). p2pool rewrites these files in place, so a poll can catch one mid-write; # `{}` on that read would replay to every caller as "the counter just dropped to zero" (#547). @@ -169,3 +178,21 @@ def get_tari_stats(): "difficulty": t.get("difficulty", 0), } return {"active": False} + + +async def get_p2pool_log_signals(window_sec=120): + now = time.time() + lines = await fetch_docker_logs("p2pool", tail=500, since=now - window_sec) + # p2pool repeats it every second while waiting, so only a recent line means still unsynced. + recent = await fetch_docker_logs("p2pool", tail=500, since=now - UNSYNCED_LOOKBACK_SEC) + if any(batch and batch[0].startswith("Error") for batch in (lines, recent)): + return None + lags = {} + for match in map(_AHEAD_RE.search, lines): + if match: + lag = int(match[2]) - int(match[3]) + lags[match[1]] = max(lag, lags.get(match[1], 0)) + return { + "lag": sorted(lags.values())[-2] if len(lags) >= 2 else 0, + "monerod_unsynced": any(_UNSYNCED in line for line in recent), + } diff --git a/dashboard/mining_dashboard/config/config.py b/dashboard/mining_dashboard/config/config.py index 75a3031e5a..235a4c3e08 100644 --- a/dashboard/mining_dashboard/config/config.py +++ b/dashboard/mining_dashboard/config/config.py @@ -312,12 +312,10 @@ def current_worker_endpoints(): NODE_DOWN_AFTER_SEC = int(os.environ.get("NODE_DOWN_AFTER_SEC", 90)) NODE_RECOVERY_AFTER_SEC = int(os.environ.get("NODE_RECOVERY_AFTER_SEC", 60)) -# Peer-loss staleness (#972): a reachable monerod reporting `synchronized: false` must persist -# this long before the out-of-sync alert fires. 10 minutes rides out normal tip-lag blips AND -# the coupled monerod restart after a tor recreate (compose depends_on restart / tor_heal), so -# only a node that genuinely failed to re-peer alarms. Env-only (tests/mini-stack), not a -# config.json knob — nobody should have to tune a detector. NODE_STALE_AFTER_SEC = int(os.environ.get("NODE_STALE_AFTER_SEC", 600)) +MINING_GUARD_GRACE_SEC = int(os.environ.get("MINING_GUARD_GRACE_SEC", 600)) +P2POOL_ZMQ_STALE_SEC = int(os.environ.get("P2POOL_ZMQ_STALE_SEC", 600)) +P2POOL_LAG_BLOCKS = int(os.environ.get("P2POOL_LAG_BLOCKS", 5)) # --- Healthchecks.io dead-man's switch (Issue #79) --- # Optional external liveness monitor. Set a ping URL and the dashboard loop pings it every cycle; diff --git a/dashboard/mining_dashboard/config/defaults.json b/dashboard/mining_dashboard/config/defaults.json index 62b4d70d99..1ef60e3576 100644 --- a/dashboard/mining_dashboard/config/defaults.json +++ b/dashboard/mining_dashboard/config/defaults.json @@ -18,7 +18,7 @@ }, "xvb": { "enabled": false, - "url": "na.xmrvsbeast.com:4247", + "url": "eu.xmrvsbeast.com:4247", "donor_id": "auto", "donation_level": "auto", "tor": true, @@ -48,7 +48,7 @@ "zmq_port": 18083 }, "prep_blocks_threads": "auto", - "out_peers": 48, + "out_peers": 24, "data_dir": "auto", "mem_limit": "auto", "backup_nodes": [] diff --git a/dashboard/mining_dashboard/helper/http.py b/dashboard/mining_dashboard/helper/http.py index d3983a7996..18aaecf67d 100644 --- a/dashboard/mining_dashboard/helper/http.py +++ b/dashboard/mining_dashboard/helper/http.py @@ -18,6 +18,7 @@ """ import json +import time import requests @@ -72,7 +73,9 @@ def raise_for_status(self): raise requests.HTTPError(f"HTTP {self.status_code}") -def bounded_request(method, url, max_bytes=MAX_RESPONSE_BYTES, timeout=20, session=None, **kwargs): +def bounded_request( + method, url, max_bytes=MAX_RESPONSE_BYTES, timeout=20, session=None, deadline=None, **kwargs +): """``requests`` with a hard response-size cap, for any method. ``session`` takes a caller's own ``requests.Session`` so bounding a read never costs it the @@ -85,9 +88,12 @@ def bounded_request(method, url, max_bytes=MAX_RESPONSE_BYTES, timeout=20, sessi through unchanged; raises exactly what ``requests`` raises otherwise. """ caller = getattr(session if session is not None else requests, method.lower()) + stop_at = time.monotonic() + deadline if deadline is not None else None with caller(url, stream=True, timeout=timeout, **kwargs) as resp: chunks, size = [], 0 for chunk in resp.iter_content(chunk_size=65536): + if stop_at is not None and time.monotonic() > stop_at: + raise requests.Timeout(f"response not complete within {deadline}s: {url}") size += len(chunk) if size > max_bytes: raise ResponseTooLarge(f"response body exceeded {max_bytes} bytes: {url}") diff --git a/dashboard/mining_dashboard/helper/utils.py b/dashboard/mining_dashboard/helper/utils.py index c17308f4d8..c470f49d84 100644 --- a/dashboard/mining_dashboard/helper/utils.py +++ b/dashboard/mining_dashboard/helper/utils.py @@ -6,6 +6,19 @@ from mining_dashboard.config.config import TIER_DEFAULTS, XVB_STATS_STALE_AFTER_S +def finite_number(value, limit=1e15): + ok = isinstance(value, int | float) and not isinstance(value, bool) + return value if ok and -limit <= value <= limit else None + + +def plausible_rate(value, limit=1e8): + return value if finite_number(value, limit) is not None and value >= 0 else None + + +def safe_text(value, limit=64): + return value if isinstance(value, str) and len(value) <= limit and value.isprintable() else None + + def parse_hashrate(val_str, unit_str=None): """ Converts a numeric string and an optional unit suffix into raw hashes per second (H/s). diff --git a/dashboard/mining_dashboard/main.py b/dashboard/mining_dashboard/main.py index 5e52d1bc9c..6da8128be9 100644 --- a/dashboard/mining_dashboard/main.py +++ b/dashboard/mining_dashboard/main.py @@ -49,6 +49,7 @@ async def start_background_tasks(app): app["algo_task"] = asyncio.create_task(algo_service.run()) app["telegram_task"] = asyncio.create_task(telegram_bot.run()) app["xvb_standby_task"] = asyncio.create_task(xvb_standby.run()) + app["healthchecks_task"] = asyncio.create_task(data_service.healthchecks.run()) async def cleanup_background_tasks(app): """Stops background tasks and closes resources on shutdown.""" @@ -56,11 +57,13 @@ async def cleanup_background_tasks(app): app["algo_task"].cancel() app["telegram_task"].cancel() app["xvb_standby_task"].cancel() + app["healthchecks_task"].cancel() await asyncio.gather( app["data_task"], app["algo_task"], app["telegram_task"], app["xvb_standby_task"], + app["healthchecks_task"], return_exceptions=True, ) if "state_manager" in app: diff --git a/dashboard/mining_dashboard/service/auth_sessions.py b/dashboard/mining_dashboard/service/auth_sessions.py new file mode 100644 index 0000000000..55d7ce6d2b --- /dev/null +++ b/dashboard/mining_dashboard/service/auth_sessions.py @@ -0,0 +1,115 @@ +import hashlib +import secrets +import sqlite3 +import time + +IDLE_SECONDS = 8 * 3600 +REMEMBER_SECONDS = 30 * 86400 +COOKIE_REFRESH_SECONDS = 86400 +TOUCH_SECONDS = 60 +MAX_SESSIONS = 64 + + +def create_schema(store): + for _ in range(2): + if store._conn is None: + return + try: + with store._db_lock, store._conn: + store._conn.execute( + "CREATE TABLE IF NOT EXISTS dashboard_sessions " + "(id TEXT PRIMARY KEY, username TEXT NOT NULL, epoch TEXT NOT NULL, " + "remember INTEGER NOT NULL, created REAL NOT NULL, touched REAL NOT NULL, " + "cookie_set REAL NOT NULL)" + ) + return + except sqlite3.Error as e: + store._db_error("Session Schema Error", e) + + +def _write(store, sql, params): + try: + with store._db_lock: + conn = store._conn + if conn is None: + return + with conn: + conn.execute(sql, params) + except sqlite3.Error as e: + store._db_error("Session Write Error", e) + + +def _digest(token): + return hashlib.sha256(token.encode()).hexdigest() + + +def lifetime(remember): + return REMEMBER_SECONDS if remember else IDLE_SECONDS + + +def _prune(conn, now): + conn.execute( + "DELETE FROM dashboard_sessions WHERE " + "(remember = 1 AND touched <= ?) OR (remember = 0 AND touched <= ?)", + (now - REMEMBER_SECONDS, now - IDLE_SECONDS), + ) + + +def issue(store, username, epoch, remember): + token = secrets.token_urlsafe(32) + now = time.time() + try: + with store._db_lock: + conn = store._conn + if conn is None: + raise sqlite3.OperationalError("session store has no connection") + with conn: + _prune(conn, now) + conn.execute("DELETE FROM dashboard_sessions WHERE epoch != ?", (epoch,)) + conn.execute( + "DELETE FROM dashboard_sessions WHERE id IN " + "(SELECT id FROM dashboard_sessions ORDER BY touched DESC LIMIT -1 OFFSET ?)", + (MAX_SESSIONS - 1,), + ) + conn.execute( + "INSERT INTO dashboard_sessions VALUES (?, ?, ?, ?, ?, ?, ?)", + (_digest(token), username, epoch, int(remember), now, now, now), + ) + except sqlite3.Error as e: + store._db_error("Session Write Error", e) + raise + return token + + +def validate(store, token, epoch) -> tuple[str, bool, bool] | None: + if not token or len(token) > 128 or not epoch: + return None + now = time.time() + try: + with store._db_lock: + conn = store._conn + if conn is None: + return None + row = conn.execute( + "SELECT * FROM dashboard_sessions WHERE id=?", (_digest(token),) + ).fetchone() + except sqlite3.Error as e: + store._db_error("Session Read Error", e) + return None + if not row: + return None + if row["epoch"] != epoch or row["touched"] <= now - lifetime(row["remember"]): + _write(store, "DELETE FROM dashboard_sessions WHERE id=?", (row["id"],)) + return None + refresh = bool(row["remember"]) and now - row["cookie_set"] >= COOKIE_REFRESH_SECONDS + if now - row["touched"] >= TOUCH_SECONDS or refresh: + _write( + store, + "UPDATE dashboard_sessions SET touched=?, cookie_set=? WHERE id=?", + (now, now if refresh else row["cookie_set"], row["id"]), + ) + return row["username"], bool(row["remember"]), refresh + + +def revoke(store, token): + _write(store, "DELETE FROM dashboard_sessions WHERE id=?", (_digest(token),)) diff --git a/dashboard/mining_dashboard/service/data_gates.py b/dashboard/mining_dashboard/service/data_gates.py index 1d2506b3e8..f677f58318 100644 --- a/dashboard/mining_dashboard/service/data_gates.py +++ b/dashboard/mining_dashboard/service/data_gates.py @@ -2,8 +2,15 @@ import logging import os import stat +import time from mining_dashboard.config.config import DISK_PATH +from mining_dashboard.service.health.mining_guard import ( + container_triggers, + log_triggers, + monero_triggers, + p2pool_triggers, +) logger = logging.getLogger("DataService") @@ -41,6 +48,12 @@ def chain_synced(sync): class DataGateMixin: + _rejected_at = None + _readmit_wait = None + _stop_logged = False + _start_failed = False + _persisted_logged = False + def _restore_sync_gate(self): """Tari-only resets preserve an earned release; full resets revoke it.""" self.sync_gate_monero_only = bool(self.latest_data.get("sync_gate_monero_only", False)) @@ -71,31 +84,111 @@ async def _worker_monero_down(self, primary_sync, primary_down): return primary_down if self.miner_released: self.monero_pool_health.ever_up = True - usable = await asyncio.to_thread(self.monero_backups.usable, primary_sync) - return self.monero_pool_health.update(usable) + serving = await asyncio.to_thread(self.monero_backups.serving, primary_sync) + self.monero_on_backup = serving == "backup" + return self.monero_pool_health.update(serving is not None) + + async def _update_mining_guard(self, monero_sync, p2pool_stats): + from mining_dashboard.collector import pools + + health = monero_sync.get("health") or {} + triggers = monero_triggers(health, monero_sync) + if self.monero_on_backup: + triggers = {key: (False, label, grace) for key, (_, label, grace) in triggers.items()} + triggers.update(p2pool_triggers(p2pool_stats.get("p2p") or {})) + triggers.update(container_triggers(await _runtime().get_container_health())) + triggers.update( + log_triggers(await pools.get_p2pool_log_signals(), health.get("advance_age_sec")) + ) + self.mining_guard.update(triggers) + + def _rejection_reasons(self, monero_down, tari_down): + reasons = [] + if self.mining_guard.pause: + reasons.append(self.mining_guard.pause["reason"]) + pending = [k for k in self.mining_guard.holding_keys if k not in self.mining_guard.active] + if pending: + reasons.append("also holding inside its grace: " + ", ".join(pending)) + if monero_down: + reasons.append("Monero node unreachable past the debounce") + if _runtime().TARI_REQUIRED and tari_down: + reasons.append("Tari node unreachable past the debounce") + return "; ".join(reasons) or "required node unreachable" + + def _readmit_blockers(self): + blockers = [] + monero_health = self.monero_pool_health if self.monero_backups.nodes else self.monero_health + if not monero_health.healthy: + blockers.append("Monero node not yet confirmed healthy") + if _runtime().TARI_REQUIRED and not self.tari_health.healthy: + blockers.append("Tari node not yet confirmed healthy") + if self.mining_guard.holding: + blockers.append( + "guard triggers still holding or recovering: " + + ", ".join(self.mining_guard.holding_keys) + ) + return "; ".join(blockers) async def _apply_worker_rejection(self, monero_down, tari_down=False): - required_down = monero_down or (_runtime().TARI_REQUIRED and tari_down) + container = _runtime().REJECT_WORKERS_CONTAINER + required_down = ( + monero_down + or (_runtime().TARI_REQUIRED and tari_down) + or bool(self.mining_guard.active) + ) if required_down: - if not self.workers_rejected: + self._readmit_wait = None + if self.workers_rejected and self._rejected_at is None and not self._persisted_logged: + self._persisted_logged = True logger.warning( - f"Required node unreachable — stopping {_runtime().REJECT_WORKERS_CONTAINER} so workers " - f"fail over to their backup pools." + f"{container} was already stopped when this dashboard started (persisted " + f"workers_rejected); still held by: {self._rejection_reasons(monero_down, tari_down)}." ) - if await self.docker_control.stop(_runtime().REJECT_WORKERS_CONTAINER): + if not self.workers_rejected: + if not self._stop_logged: + self._stop_logged = True + logger.warning( + f"Mining work is not valid ({self._rejection_reasons(monero_down, tari_down)}) — " + f"stopping {container} so workers fail over to their backup pools." + ) + if await self.docker_control.stop(container): self.workers_rejected = True + self._stop_logged = False + self._rejected_at = time.monotonic() return + self._stop_logged = False monero_health = self.monero_pool_health if self.monero_backups.nodes else self.monero_health - recovered = monero_health.healthy and ( - not _runtime().TARI_REQUIRED or self.tari_health.healthy + recovered = ( + monero_health.healthy + and (not _runtime().TARI_REQUIRED or self.tari_health.healthy) + and not self.mining_guard.holding ) - if self.workers_rejected and recovered: + if not self.workers_rejected: + return + if not recovered: + blockers = self._readmit_blockers() + if blockers != self._readmit_wait: + self._readmit_wait = blockers + logger.info(f"{container} stays stopped: {blockers}") + return + if await self.docker_control.start(container): + self.workers_rejected = False + since = self._rejected_at + self._rejected_at = None + self._readmit_wait = None + self._start_failed = False + elapsed = ( + f"{int(time.monotonic() - since)}s after it was stopped" + if since is not None + else "after a stop that predates this dashboard process" + ) logger.info( - f"Required nodes recovered — starting {_runtime().REJECT_WORKERS_CONTAINER} to readmit workers." + f"Required nodes recovered — started {container} to readmit workers, {elapsed}." ) - if await self.docker_control.start(_runtime().REJECT_WORKERS_CONTAINER): - self.workers_rejected = False + elif not self._start_failed: + self._start_failed = True + logger.warning(f"Readmitting workers failed: {container} did not start; retrying.") async def _stop_gate_containers(self, quiet): """Stop every ``SYNC_GATE_CONTAINERS`` container; shared by the #35 sync gate and the diff --git a/dashboard/mining_dashboard/service/data_helpers.py b/dashboard/mining_dashboard/service/data_helpers.py index 8d1dbd16ef..e50d8caa4f 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 from mining_dashboard.service.workers.donation import reported_level @@ -192,18 +193,7 @@ 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 = extra_stats.get("api_ok") if extra_stats else None @@ -214,7 +204,9 @@ def _merge_direct_stats(workers, results, active_pool_port): 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" @@ -224,9 +216,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) @@ -234,16 +226,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 @@ -263,7 +249,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/data_service.py b/dashboard/mining_dashboard/service/data_service.py index f3b65bd8a5..655edb2df7 100644 --- a/dashboard/mining_dashboard/service/data_service.py +++ b/dashboard/mining_dashboard/service/data_service.py @@ -312,16 +312,12 @@ async def run(self): monero_sync["stale"] = monero_stale self._observe_monero(monero_sync) - # 4. Sync gate (Issue #35): hold p2pool + xmrig-proxy until the required - # chain(s) first sync, then release. monerod must be synced; Tari must be - # synced too unless it's non-blocking. #31's runtime failover only applies - # once released — before that there are no workers to fail over, and it - # keeps the two features from both driving xmrig-proxy. await self._apply_sync_gate( monero_synced and (tari_synced or not TARI_REQUIRED or self.sync_gate_monero_only) ) if self.miner_released: + await self._update_mining_guard(monero_sync, p2pool_stats) await self._apply_worker_rejection( worker_monero_down if self.monero_backups.nodes else monero_down, tari_down, @@ -475,6 +471,8 @@ async def run(self): "global_sync": global_sync, "tari_syncing_passive": tari_syncing_passive, "workers_rejected": self.workers_rejected, + "stratum_closed": self.workers_rejected, + "mining_pause": self.mining_guard.pause, "miner_released": self.miner_released, "sync_gate_monero_only": self.sync_gate_monero_only, "miner_held": self.miner_held, @@ -565,20 +563,9 @@ async def run(self): ) self._last_worker_capture = now_ts - # 6b. Healthchecks.io dead-man's switch (Issue #79). Ping each cycle so the - # external monitor alerts on the *absence* of a ping if the host ever dies - # (power loss, crash, NIC death) — a pure "is the stack alive" liveness signal. - # Node-health alerting (a node down while the box is up) is out of scope here; - # that's the Telegram alerter's job (#121). The client throttles and fails - # silently; `enabled` is just "a ping URL is set", so an unconfigured stack - # never pings. - 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) + 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 9d71893d9d..b08ebbd0e2 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 @@ -25,9 +26,13 @@ WorkerLifecycle, ) from mining_dashboard.service.health.degradation import DegradationMonitor +from mining_dashboard.service.health.mining_guard import MiningGuard from mining_dashboard.service.health.monero_backups import MoneroBackups 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 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 @@ -156,6 +161,7 @@ def __init__(self, state_manager, proxy_client, xvb_client): self.monero_health = NodeHealthMonitor() self.monero_backups = MoneroBackups() self.monero_pool_health = NodeHealthMonitor() + self.monero_on_backup = False self.tari_health = NodeHealthMonitor( down_after=TARI_NODE_DOWN_AFTER_SEC, ever_up=TARI_MODE != "off" ) @@ -175,7 +181,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 @@ -206,12 +214,21 @@ def __init__(self, state_manager, proxy_client, xvb_client): # to restart tor when clearnet egress is stuck on a failing guard; the recovery # note rides the Telegram notifier, which works again exactly when the heal worked. self.tor_healer = TorEgressHealer( - self.docker_control, notify=self.alert_service.tor_heal_alert + self.docker_control, + notify=self.alert_service.tor_heal_alert, + ping_failing_since=lambda: self.healthchecks.failing_since, + ) + 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. 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. @@ -222,6 +239,7 @@ def __init__(self, state_manager, proxy_client, xvb_client): # True while we've stopped the proxy to reject workers. Persisted in the snapshot so # a dashboard restart mid-outage still readmits workers once the node recovers. self.workers_rejected = False + self.mining_guard = MiningGuard() # Hold the miner (p2pool + xmrig-proxy) until the required chain(s) finish syncing # (Issue #35). One-way latch: `miner_released` flips True the first time the gate is @@ -258,11 +276,14 @@ 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): - """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/data_xvb_sync.py b/dashboard/mining_dashboard/service/data_xvb_sync.py index c3436a3e02..4227b6d7e5 100644 --- a/dashboard/mining_dashboard/service/data_xvb_sync.py +++ b/dashboard/mining_dashboard/service/data_xvb_sync.py @@ -50,7 +50,13 @@ async def _sync_xvb_stats(self): real_xvb_stats = await asyncio.to_thread(self.xvb_client.get_stats) if not real_xvb_stats: return # fetch failed — keep the last reading + last_update frozen so #311 can detect it + if "avg_1h" not in real_xvb_stats: + stored = await asyncio.to_thread(self.state_manager.get_xvb_stats) + if real_xvb_stats["fail_count"] <= stored.get("fail_count", 0): + return await asyncio.to_thread(self.state_manager.update_xvb_stats, **real_xvb_stats) + if "avg_1h" not in real_xvb_stats: + return logger.info(f"External Sync: XvB Stats Updated (1h={real_xvb_stats['avg_1h']:.0f} H/s)") # v1.7 telemetry backbone (#196 Wave-0): persist the XvB scalars as a time series, wall- diff --git a/dashboard/mining_dashboard/service/health/diagnostics_service.py b/dashboard/mining_dashboard/service/health/diagnostics_service.py index 5d386fded1..8d60349129 100644 --- a/dashboard/mining_dashboard/service/health/diagnostics_service.py +++ b/dashboard/mining_dashboard/service/health/diagnostics_service.py @@ -54,3 +54,26 @@ def submit_diag_logs(container: str, lines: int, actor: str = "") -> str: "lines": lines, } ) + + +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 = "", since=None, until=None) -> str: + intent = {"id": str(uuid.uuid4()), "action": "support-bundle", "actor": actor} + if hours is not None: + intent["hours"] = hours + if since is not None: + intent["since"] = since + if until is not None: + intent["until"] = until + return request_spool.write(intent) + + +def submit_support_range(actor: str = "") -> str: + return request_spool.write( + {"id": str(uuid.uuid4()), "action": "support-bundle-range", "actor": actor} + ) diff --git a/dashboard/mining_dashboard/service/health/mining_guard.py b/dashboard/mining_dashboard/service/health/mining_guard.py new file mode 100644 index 0000000000..cd8984f535 --- /dev/null +++ b/dashboard/mining_dashboard/service/health/mining_guard.py @@ -0,0 +1,167 @@ +import time + +from mining_dashboard.config.config import ( + MINING_GUARD_GRACE_SEC, + NODE_DOWN_AFTER_SEC, + NODE_RECOVERY_AFTER_SEC, + P2POOL_LAG_BLOCKS, + P2POOL_ZMQ_STALE_SEC, +) + +LAG_STALL_SEC = 900 +UNKNOWN_AFTER_SEC = 600 +GUARDED_CONTAINERS = (("monerod", "Monero node"), ("p2pool", "P2Pool"), ("tor", "Tor")) + + +def monero_triggers(health, sync): + reasons = health.get("reasons") or [] + return { + "monero_unhealthy": ( + health.get("level") == "red" and bool(reasons), + "Monero node unhealthy: " + "; ".join(reasons), + 0, + ), + "monero_peers": ( + health.get("peers_out") == 0, + "Monero node has 0 outgoing peers", + MINING_GUARD_GRACE_SEC, + ), + "monero_unsynced": ( + sync.get("synchronized") is False, + "Monero node reports it is not synchronized", + MINING_GUARD_GRACE_SEC, + ), + } + + +def p2pool_triggers(p2p): + if not p2p.get("uptime"): + return {} + out_peers, in_peers = p2p.get("out_peers", 0), p2p.get("in_peers", 0) + zmq_age = p2p.get("zmq_active", 0) + return { + "p2pool_peers": ( + not out_peers and not in_peers, + "P2Pool has no sidechain peers", + MINING_GUARD_GRACE_SEC, + ), + "p2pool_zmq": ( + zmq_age > P2POOL_ZMQ_STALE_SEC, + f"P2Pool has received no ZMQ messages for {int(zmq_age // 60)} min", + NODE_DOWN_AFTER_SEC, + ), + } + + +def log_triggers(signals, advance_age): + if signals is None: + return {} + triggers = { + "p2pool_monerod": ( + signals["monerod_unsynced"], + "P2Pool reports monerod is not synchronized", + NODE_DOWN_AFTER_SEC, + ) + } + if advance_age is not None: + triggers["p2pool_lag"] = ( + signals["lag"] >= P2POOL_LAG_BLOCKS and advance_age >= LAG_STALL_SEC, + f"Monero node is {signals['lag']} blocks behind P2Pool's peers", + NODE_DOWN_AFTER_SEC, + ) + return triggers + + +def container_triggers(states): + triggers = {} + for name, label in GUARDED_CONTAINERS: + state = states.get(name) + if state is None: + continue + if not state["running"]: + problem = "is not running" + elif state["restarting"]: + problem = "is restarting" + elif state["health"] in ("starting", "unhealthy"): + problem = f"is {state['health']}" + else: + problem = None + triggers[f"{name}_container"] = ( + problem is not None, + f"{label} container {problem}", + NODE_DOWN_AFTER_SEC, + ) + return triggers + + +class MiningGuard: + def __init__( + self, + clock=time.monotonic, + wall=time.time, + recovery_after=NODE_RECOVERY_AFTER_SEC, + ): + self._clock = clock + self._wall = wall + self._recovery_after = recovery_after + self._holding_since = {} + self._holding_wall = {} + self._clear_since = {} + self._unknown_since = {} + self.active = {} + + def _forget(self, key): + for table in ( + self._holding_since, + self._holding_wall, + self._clear_since, + self._unknown_since, + self.active, + ): + table.pop(key, None) + + def update(self, triggers): + now = self._clock() + for key in set(self._holding_since) | set(self.active) | set(triggers): + if key not in triggers: + if key in self._holding_since or key in self.active: + unknown = self._unknown_since.setdefault(key, now) + if now - unknown >= UNKNOWN_AFTER_SEC: + self._forget(key) + continue + self._unknown_since.pop(key, None) + holds, label, grace = triggers[key] + if holds: + self._clear_since.pop(key, None) + first = self._holding_since.setdefault(key, now) + since = self._holding_wall.setdefault(key, self._wall()) + if key in self.active: + self.active[key]["label"] = label + elif now - first >= grace: + self.active[key] = {"label": label, "since": since} + continue + self._holding_since.pop(key, None) + self._holding_wall.pop(key, None) + if key in self.active: + first = self._clear_since.setdefault(key, now) + if now - first >= self._recovery_after: + del self.active[key] + del self._clear_since[key] + + @property + def holding(self): + return bool(self._holding_since) or bool(self.active) + + @property + def holding_keys(self): + return sorted(set(self._holding_since) | set(self.active)) + + @property + def pause(self): + if not self.active: + return None + ordered = sorted(self.active.values(), key=lambda t: t["since"]) + return { + "reason": "; ".join(t["label"] for t in ordered), + "since": ordered[0]["since"], + } diff --git a/dashboard/mining_dashboard/service/health/monero_backups.py b/dashboard/mining_dashboard/service/health/monero_backups.py index a436af1225..100d3905f5 100644 --- a/dashboard/mining_dashboard/service/health/monero_backups.py +++ b/dashboard/mining_dashboard/service/health/monero_backups.py @@ -83,14 +83,14 @@ def __init__(self): MoneroClient(f"http://{url_host}:{node['rpc_port']}", user, password) ) - def usable(self, primary_sync): + def serving(self, primary_sync): if ( primary_sync.get("reachable") is True and synced(primary_sync) and zmq_publisher(*self.primary) ): - return True + return "primary" for node, client in zip(self.nodes, self.clients, strict=True): if synced(client.get_sync_status()) and zmq_publisher(node["host"], node["zmq_port"]): - return True - return False + return "backup" + return None 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/mining_dashboard/service/health/node_alert.py b/dashboard/mining_dashboard/service/health/node_alert.py new file mode 100644 index 0000000000..182f77a88a --- /dev/null +++ b/dashboard/mining_dashboard/service/health/node_alert.py @@ -0,0 +1,66 @@ +from mining_dashboard.service.health.tor_heal import ( + BROKEN_AFTER_SEC, + COOLDOWN_SEC, + EXHAUSTED_PROBE_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 is past its cap after {MAX_ATTEMPTS} attempts: no more disruptive " + f"action this outage; it probes every {_minutes(EXHAUSTED_PROBE_SEC)} minutes and " + f"re-alerts hourly until Tor recovers. {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/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/mining_dashboard/service/health/tor_heal.py b/dashboard/mining_dashboard/service/health/tor_heal.py index 2a23989fc0..7f22cf57c7 100644 --- a/dashboard/mining_dashboard/service/health/tor_heal.py +++ b/dashboard/mining_dashboard/service/health/tor_heal.py @@ -1,11 +1,3 @@ -"""Bounded Tor clearnet recovery when tor.auto_heal is enabled. - -Corroborate failed probes on isolated circuits and two targets before bounded NEWNYM requests. -For saturated history, the final step requests host-gated tor-recover, including its persistent -six-hour cooldown and identity checks. Heal-only host requests do not require general dashboard -control or a login. Otherwise a final restart re-dials local Monero. -""" - import asyncio import logging import time @@ -27,20 +19,22 @@ logger = logging.getLogger("TorHeal") -# Independent targets: any response on either fresh circuit proves clearnet egress works. PROBE_URL = "https://www.google.com/generate_204" SECOND_PROBE_URL = "https://www.cloudflare.com/cdn-cgi/trace" PROBE_TIMEOUT_SEC = 15 -# Fixed, bounded cadence and attempt budget for this opt-in recovery. PROBE_INTERVAL_SEC = 5 * 60 # active probe cadence (only while the heal is enabled) -BROKEN_AFTER_SEC = 15 * 60 # sustained failure before the first action +FIRST_ACTION_AFTER_SEC = 5 * 60 +BROKEN_AFTER_SEC = 15 * 60 +FAST_PROBE_SEC = 60 COOLDOWN_SEC = 30 * 60 # minimum gap between actions -MAX_ATTEMPTS = 3 # two circuit refreshes, then one container restart -# Consecutive OK probes required to declare an outage OVER once we've spent an action. A single -# lucky 204 must NOT close the outage: under the issue's own scenario (overloaded Tor, egress -# flapping) that would refill the budget and clear the cooldown every blip. -RECOVERY_CONFIRM_PROBES = 2 # ~10 min sustained egress before the budget resets +NEWNYM_ATTEMPTS = 2 +MAX_ATTEMPTS = 4 +MAX_DISRUPTIVE_PER_DAY = 4 +DISRUPTIVE_WINDOW_SEC = 24 * 3600 +EXHAUSTED_PROBE_SEC = 15 * 60 +RE_ALERT_SEC = 60 * 60 +RECOVERY_CONFIRM_PROBES = 2 # Tor's stop: SIGTERM, `t` seconds of grace, then SIGKILL. Docker holds the request open until the # container is down, and a wedged Tor took over 60 s (#3032). The HTTP timeout outlasts grace + kill. TOR_STOP_GRACE_SEC = 15 @@ -68,10 +62,9 @@ def __init__( notify=None, clock=time.monotonic, restart_monerod=None, + ping_failing_since=None, ): self.enabled = TOR_AUTO_HEAL if enabled is None else enabled - # Cycle monerod after a successful tor restart (#972) — only when the node is local - # (a remote monerod has no container here and keeps its own tor). if restart_monerod is None: restart_monerod = MONERO_NODE_HOST == LOCAL_MONERO_HOST self._restart_monerod = restart_monerod @@ -79,12 +72,17 @@ def __init__( self._probe = probe or self._probe_egress self._notify = notify # optional async callable(text) — the Telegram one-off self._clock = clock + self._ping_failing_since = ping_failing_since self._last_probe = None # probe-cadence throttle + self._was_pinging_badly = False self._failing_since = None # start of the current unbroken failure streak self._attempts = 0 # recovery actions spent on the current outage self._last_attempt = None # cooldown anchor self._ok_streak = 0 # consecutive OK probes (sustained-recovery counter, post-restart) - self._warned_exhausted = False # give-up warning is logged once per outage, not every probe + self._warned_exhausted = False + self._exhausted_alerted_at = None + self._past_cap = False + self._disruptive = [] self._pending_recovery = None self._tor_started = None # last seen Tor container start (epoch); None until observed self._own_restart = False # the healer restarted Tor since that reading @@ -94,18 +92,20 @@ def __init__( self._failure_evidence = "" self._recovery_step = None self._newnym_unconfirmed = False # last NEWNYM round got no applied result + self._newnym_retried = False self._history_since = None self._history_outage = None self._clear_history = False self._pending_history = None # read-only tor-history request awaiting its result self._warned_saturated = False # saturated-history alert is sent once per outage - self.saturated_history = False # latest host reading, for status surfaces + self.saturated_history = False + self.circuits_wedged = False if self.enabled: logger.info( - "Tor egress self-heal enabled: probing every %ds; recovery after %dm " + "Tor egress self-heal enabled: probing every %ds; first recovery after %dm " "broken, max %d attempts %dm apart.", PROBE_INTERVAL_SEC, - BROKEN_AFTER_SEC // 60, + FIRST_ACTION_AFTER_SEC // 60, MAX_ATTEMPTS, COOLDOWN_SEC // 60, ) @@ -128,17 +128,11 @@ def _probe_egress() -> tuple[bool, str]: return False, "; ".join(evidence) def decide(self, ok, now): - """Fold a probe into outage state; return heal, exhausted, recovered, or None. - - Recovery requires two corroborated successes.""" if ok: if self._attempts == 0 and not self._newnym_unconfirmed and not self.saturated_history: - # A healthy probe clears a blip that never reached a recovery action. self._failing_since = None self._ok_streak = 0 return None - # Two successes confirm recovery; a lone response during a flapping outage - # preserves the attempt budget and cooldown, including rejected NEWNYM rounds. self._ok_streak += 1 if self._ok_streak < RECOVERY_CONFIRM_PROBES: return None @@ -147,31 +141,35 @@ def decide(self, ok, now): self._last_attempt = None self._ok_streak = 0 self._warned_exhausted = False + self._exhausted_alerted_at = None + self._past_cap = False return "recovered" - # ok is False — any failure breaks a would-be recovery streak. self._ok_streak = 0 if self._failing_since is None: - self._failing_since = now - # Transient blip guard: not broken until the failure streak spans the threshold. - if (now - self._failing_since) < BROKEN_AFTER_SEC: + hint = self._ping_failing_since() if self._ping_failing_since else None + self._failing_since = hint if hint is not None and hint < now else now + threshold = FIRST_ACTION_AFTER_SEC if self._attempts == 0 else BROKEN_AFTER_SEC + if (now - self._failing_since) < threshold: return None - # Retry cap: past the budget we never restart again this outage — warn instead. - if self._attempts >= MAX_ATTEMPTS: - return "exhausted" - # Cooldown: give the previous action time to prove itself. if self._last_attempt is not None and (now - self._last_attempt) < COOLDOWN_SEC: return None + if self._attempts >= MAX_ATTEMPTS: + self._past_cap = True + return "exhausted" + if self._attempts >= NEWNYM_ATTEMPTS: + self._disruptive = [t for t in self._disruptive if now - t < DISRUPTIVE_WINDOW_SEC] + if len(self._disruptive) >= MAX_DISRUPTIVE_PER_DAY: + self._past_cap = True + return "exhausted" + self._disruptive.append(now) self._attempts += 1 self._last_attempt = now + self._warned_exhausted = False + self._exhausted_alerted_at = None + self._past_cap = False return "heal" async def _observe_tor_start(self) -> None: - """Start a fresh outage window when Tor restarted without the healer's doing. - - A restart by the operator, ``./pithead`` or Docker is a recovery the healer did not - perform, so the old clock, budget and cooldown no longer describe the Tor that is running. - A restart the healer issued itself is adopted into the baseline and keeps counting. A Tor that - restarts more often than BROKEN_AFTER_SEC (a crash loop) therefore never reaches an action.""" started = (await get_container_health()).get(self.CONTAINER, {}).get("started_at") if started is None: return @@ -182,12 +180,15 @@ async def _observe_tor_start(self) -> None: self._last_attempt = None self._ok_streak = 0 self._warned_exhausted = False + self._exhausted_alerted_at = None + self._past_cap = False self._newnym_unconfirmed = False + self._newnym_retried = False + self.circuits_wedged = False self._tor_started = started self._own_restart = False def refund_attempt(self): - """Refund an unconfirmed NEWNYM; keep the ongoing outage clock.""" if self._attempts > 0: self._attempts -= 1 self._last_attempt = None @@ -228,7 +229,14 @@ async def check(self) -> None: if not self.enabled: return now = self._clock() - if self._last_probe is not None and (now - self._last_probe) < PROBE_INTERVAL_SEC: + hint = self._ping_failing_since() if self._ping_failing_since else None + pinging_badly = self._attempts == 0 and hint is not None + interval = FAST_PROBE_SEC if pinging_badly else PROBE_INTERVAL_SEC + if self._past_cap: + interval = EXHAUSTED_PROBE_SEC + onset = pinging_badly and not self._was_pinging_badly + self._was_pinging_badly = pinging_badly + if not onset and self._last_probe is not None and (now - self._last_probe) < interval: return self._last_probe = now try: @@ -247,9 +255,11 @@ async def check(self) -> None: self._pending_refresh = None self._pending_since = None if result.get("status") != "applied": - # An unconfirmed NEWNYM never escalates to the disruptive restart; the - # saturated-history reading below tells the operator what will help. - self.refund_attempt() + if result.get("status") == "rejected": + self._attempts = max(self._attempts, NEWNYM_ATTEMPTS) + elif not self._newnym_retried: + self._newnym_retried = True + self.refund_attempt() self._last_attempt = now self._newnym_unconfirmed = True logger.warning( @@ -263,20 +273,24 @@ async def check(self) -> None: self._recovery_step = "NEWNYM" probe = await asyncio.to_thread(self._probe) ok, evidence = probe + if self._attempts: + self._request_history() + if not ok and self.circuits_wedged: + evidence = f"{evidence}; control port reports wedged circuits" if not ok: self._failure_evidence = evidence outage_minutes = (now - self._failing_since) / 60 if self._failing_since else 0 action = self.decide(ok, now) if action == "heal": - self._request_history() # Read on the first round, then refresh each round. - if self._attempts < MAX_ATTEMPTS: + self._request_history() + if self._attempts <= NEWNYM_ATTEMPTS: logger.warning( "Tor clearnet egress failed for %.0f minutes: %s. " "Requesting NEWNYM (%d/%d).", outage_minutes, evidence, self._attempts, - MAX_ATTEMPTS - 1, + NEWNYM_ATTEMPTS, ) try: self._pending_refresh = control_service.submit( @@ -291,7 +305,7 @@ async def check(self) -> None: return self._pending_since = now return - if self.saturated_history: + if self._attempts == NEWNYM_ATTEMPTS + 1: self._host_receipt = await self._tor_begin("recover") try: self._pending_recovery = control_service.submit( @@ -319,8 +333,6 @@ async def check(self) -> None: request_timeout=TOR_STOP_REQUEST_TIMEOUT_SEC, ) started = await self._ensure_tor_running(stopped) - # False means unconfirmed, not unissued: a timed-out POST may have mutated - # the daemon. Keep the attempt and cooldown even when both responses are lost. self._recovery_step = ( "Tor restart" if stopped and started @@ -353,17 +365,46 @@ async def check(self) -> None: "monerod' (#972)." ) elif action == "exhausted": - # Keep diagnostics and undelivered warnings alive without another mutation. if self._history_since is None or now - self._history_since >= COOLDOWN_SEC: self._request_history() if not self._warned_exhausted: self._warned_exhausted = True logger.warning( - "Tor clearnet egress is STILL broken after %d recovery attempts: %s. " + "Tor clearnet egress is STILL broken after %d recovery attempts " + "(%d disruptive in the last day, cap %d): %s. " "No more automatic action; run './pithead doctor' for current evidence.", - MAX_ATTEMPTS, + self._attempts, + len(self._disruptive), + MAX_DISRUPTIVE_PER_DAY, + evidence, + ) + try: + control_service.submit("tor-heal-exhausted", actor="tor-heal") + except OSError: + logger.warning("Tor heal exhaustion could not be audited by the host") + if self._exhausted_alerted_at is None or ( + now - self._exhausted_alerted_at >= RE_ALERT_SEC + ): + self._exhausted_alerted_at = now + logger.warning( + "Tor auto-heal is past its cap (%d attempts, %d disruptive in the last " + "day, cap %d) with egress still broken %.0f minutes into the outage; " + "probing every %d minutes and re-alerting hourly until it recovers: %s", + self._attempts, + len(self._disruptive), + MAX_DISRUPTIVE_PER_DAY, + outage_minutes, + EXHAUSTED_PROBE_SEC // 60, evidence, ) + if self._notify is not None: + await self._notify( + f"\U0001f9c5 Tor auto-heal is past its cap: {self._attempts} attempts " + f"spent ({len(self._disruptive)} disruptive in the last day, " + f"cap {MAX_DISRUPTIVE_PER_DAY}); outage {outage_minutes:.0f} minutes; " + f"probing every {EXHAUSTED_PROBE_SEC // 60} minutes and re-alerting " + f"hourly until Tor recovers. Failed probes {evidence}." + ) elif action == "recovered": logger.info( "Tor clearnet egress recovered following %s: failed probes %s; recovery probe %s", @@ -372,9 +413,11 @@ async def check(self) -> None: evidence, ) self._newnym_unconfirmed = False + self._newnym_retried = False self._warned_saturated = False self._pending_history = None self.saturated_history = False + self.circuits_wedged = False if self._history_outage is not None: self._history_outage = None self._clear_history = True diff --git a/dashboard/mining_dashboard/service/health/tor_heal_history.py b/dashboard/mining_dashboard/service/health/tor_heal_history.py index 52186572b3..275af460f1 100644 --- a/dashboard/mining_dashboard/service/health/tor_heal_history.py +++ b/dashboard/mining_dashboard/service/health/tor_heal_history.py @@ -9,6 +9,8 @@ logger = logging.getLogger("TorHeal") +PENDING_CIRCUIT_LIMIT = 64 + class TorHistoryMixin: tor_snapshot = None @@ -53,10 +55,17 @@ async def _read_history(self) -> None: self._clear_history = False return if result.get("status") != "applied": + self.circuits_wedged = False logger.warning("Tor circuit-history reading was refused or unavailable") return if isinstance(result.get("tor"), dict): self.tor_snapshot = result["tor"] + pending = result.get("pending_circuits") + self.circuits_wedged = result.get("circuit_established") is False or ( + isinstance(pending, int) + and not isinstance(pending, bool) + and pending >= PENDING_CIRCUIT_LIMIT + ) saturated = result.get("saturated") is True self.saturated_history = saturated if not saturated: @@ -91,14 +100,14 @@ async def _read_recovery(self, now): if result is not None and result.get("status") == "applied": self._recovery_step = "host-gated Tor state recovery" self._recovery_notice = ( - "Tor heal reset saturated circuit history and guards through tor-recover; " + "Tor heal reset circuit state and guards through tor-recover; " "the host verified its evidence, onion identities and six-hour cooldown." ) else: self._own_restart = False # nothing restarted Tor; a later restart is not ours detail = (result or {}).get("error", "host result unconfirmed") self._recovery_step = "Tor state recovery unconfirmed" - self._recovery_notice = f"Tor state recovery refused or failed: {detail}. No fallback restart was attempted." + self._recovery_notice = f"Tor state recovery refused or failed: {detail}. The next heal round restarts Tor." if self._recovery_notice is not None: logger.warning("%s", self._recovery_notice) notice = self._recovery_notice + self._snapshot_suffix() 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_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/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/service/network/egress.py b/dashboard/mining_dashboard/service/network/egress.py index 8388b9d2ef..01db893f70 100644 --- a/dashboard/mining_dashboard/service/network/egress.py +++ b/dashboard/mining_dashboard/service/network/egress.py @@ -123,7 +123,7 @@ def compute_egress_posture( "firewalled": True, "conns": [ {"to": "upstream pool (local p2pool stratum)", "route": LOCAL}, - # XvB donation mining dials na.xmrvsbeast.com via the proxy's per-pool socks5 (#166). + # XvB donation mining dials eu.xmrvsbeast.com via the proxy's per-pool socks5 (#166). {"to": "XvB donation pool", "route": xvb}, {"to": "dev donation", "route": INACTIVE}, # --donate-level 0 (#166) ], diff --git a/dashboard/mining_dashboard/service/notify/healthchecks.py b/dashboard/mining_dashboard/service/notify/healthchecks.py index c60e7f0163..6d96866f06 100644 --- a/dashboard/mining_dashboard/service/notify/healthchecks.py +++ b/dashboard/mining_dashboard/service/notify/healthchecks.py @@ -1,32 +1,12 @@ -"""Healthchecks.io dead-man's-switch pinger (Issue #79). - -A thin, self-contained client the data loop calls once per cycle to ping a unique -Healthchecks.io URL. The value is in what *stops* happening: if the host dies, the -dashboard dies with it, the pings stop, and Healthchecks.io fires an alert on the absence -of a ping — evaluated on *their* servers, so it survives the very outage (power loss, kernel -panic, NIC death) an in-stack notifier can't report from a dead machine. - -Design notes: -- **Off until configured.** No ``ping_url`` → the client is a no-op: :meth:`ping` returns - immediately, opens no socket, and logs nothing. Setting a URL is what turns it on. -- **Always over Tor.** The ping rides the bridge Tor SOCKS proxy so the endpoint sees a Tor - exit, not the host IP — it's never a clearnet beacon. -- **Fails silently, but rejection is loud.** A ping that can't *reach* the endpoint (offline, or - Tor momentarily down) is logged at DEBUG only, consistent with the stack's offline check - discipline (#59). A ping the endpoint *rejects* (non-2xx — a revoked or typo'd URL) is a - different failure mode: it doesn't self-heal, so it logs a WARNING, once, on the transition - from OK to rejected (and an INFO on recovery) — #560. -- **Throttled.** :data:`interval` is a floor between pings; the loop calls every cycle but we - only hit the network once per interval. The throttle clock only advances on a *successful* - send, so while offline we keep retrying every cycle rather than backing off. - -Manual setup: the operator pastes the full ping URL from Healthchecks.io (hosted or a -Tor-reachable self-hosted instance). Auto-provisioning via the Management API (which would -mean storing a powerful API key) is intentionally left out — see ``docs/monitoring.md``. -""" - +import asyncio +import json import logging +import subprocess +import sys +import threading import time +import uuid +from types import SimpleNamespace import requests @@ -36,44 +16,88 @@ from mining_dashboard.config.config import ( NOTIFICATION_PROXY as TOR_SOCKS_PROXY, ) -from mining_dashboard.helper.http import bounded_get logger = logging.getLogger("Healthchecks") -# A ping is a tiny request; keep the timeout short so a hung endpoint can't stall the loop's -# worker thread for long. Healthchecks.io recommends GET/HEAD/POST to the ping URL. _PING_TIMEOUT_SEC = 10 - -# Throttle floor between pings (the loop runs faster, but we only hit the network this often). Fixed, -# not configurable: 60s pairs with the recommended 1-min Healthchecks period, and no operator needs -# to tune a dead-man's-switch cadence. +_PING_DEADLINE_SEC = 25 +_PING_HARD_LIMIT_SEC = 30 _PING_INTERVAL_SEC = 60 +_PING_MIN_GAP_SEC = 5 -class HealthchecksClient: - """Pings a Healthchecks.io check on a throttle; safe to call every loop cycle.""" +async def _in_daemon_thread(fn): + loop = asyncio.get_running_loop() + fut = loop.create_future() + + def settle(setter, value): + if not fut.done(): + setter(value) + + def work(): + try: + result = fn() + except Exception as e: + loop.call_soon_threadsafe(settle, fut.set_exception, e) + else: + loop.call_soon_threadsafe(settle, fut.set_result, result) + + threading.Thread(target=work, daemon=True).start() + return await fut + + +class PingFailure(requests.RequestException): + def __init__(self, reason, name): + super().__init__(name) + self.reason = reason + self.name = name + + +def _fetch(url, timeout, deadline, proxies=None): + request = { + "url": url, + "proxy": (proxies or {}).get("https"), + "timeout": timeout, + "deadline": deadline, + } + try: + done = subprocess.run( + [sys.executable, "-m", "mining_dashboard.service.notify.healthchecks_child"], + input=json.dumps(request), + capture_output=True, + text=True, + timeout=_PING_HARD_LIMIT_SEC, + ) + except subprocess.TimeoutExpired: + raise PingFailure("tor_socks" if proxies else "connect", "Timeout") from None + try: + out = json.loads(done.stdout) + except ValueError: + raise PingFailure("connect", "ChildError") from None + if "status" in out: + return SimpleNamespace(status_code=out["status"]) + raise PingFailure(out["reason"], out["name"]) + +class HealthchecksClient: def __init__( self, ping_url, 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. - # Anything that isn't an http(s) URL is treated as unset (a no-op), never a silent bad ping. url = (ping_url or "").strip() self.url = url.rstrip("/") if url.startswith(("http://", "https://")) else "" self.enabled = bool(self.url) self.interval = max(0, int(interval_seconds or 0)) - # Route the ping over the bridge Tor SOCKS (socks5h, so the host resolves through Tor too), - # so the endpoint sees a Tor exit, not the host IP. tor_proxy is a test seam; from_config - # always injects it. + self._tor_proxy = tor_proxy self._proxies = {"http": tor_proxy, "https": tor_proxy} if tor_proxy else None self._clock = clock - 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 + self._record_failure = record_failure + self._last_ping_ok = None + self.failing_since = None if self.enabled: logger.info( @@ -82,60 +106,106 @@ 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): - """Whether enough time has passed since the last successful ping to send another.""" - if self._last_ping is None: - return True - return (now - self._last_ping) >= self.interval + def _isolated_proxies(self): + if not self._tor_proxy: + return None + proxy = self._tor_proxy.replace("://", f"://{uuid.uuid4().hex}:isolate@", 1) + return {"http": proxy, "https": proxy} def ping(self) -> bool: - """Send one liveness heartbeat if due. Never raises. - - This is a pure dead-man's switch: it only reports that the stack (this dashboard loop) is - alive. Node-health alerting — monerod/Tari down while the box is up — is out of scope and - handled in-stack by the Telegram alerter (#121), which can say more than a red check can. - - Returns ``True`` if a request was sent and accepted (2xx), else ``False`` (not configured, - throttled, the request failed, or the endpoint rejected it — a revoked/typo'd URL, #560). - """ if not self.url: return False now = self._clock() - if not self._due(now): - return False + for attempt in range(2): + proxies = self._proxies if attempt == 0 else self._isolated_proxies() + try: + resp = _fetch( + self.url, + timeout=_PING_TIMEOUT_SEC, + deadline=_PING_DEADLINE_SEC, + proxies=proxies, + ) + if 200 <= resp.status_code < 300: + if self._last_ping_ok is False: + logger.info("Healthchecks ping recovered.") + self._last_ping_ok = True + self.failing_since = None + return True + self.failing_since = None + self._record("http_status", f"HTTP {resp.status_code}") + if attempt == 0 and resp.status_code >= 500: + continue + if self._last_ping_ok is not False: + logger.warning("Healthchecks ping rejected: HTTP %s.", resp.status_code) + self._last_ping_ok = False + return False + except requests.RequestException as e: + logger.debug("Healthchecks ping failed (offline?): %s", e) + self._record(_failure_class(e, proxies is not None), _failure_name(e)) + except Exception as e: # pragma: no cover + logger.debug("Healthchecks unexpected error: %s", e) + self._record("connect", type(e).__name__) + return False + if self.failing_since is None: + self.failing_since = now + return False + + async def run(self): + if not self.enabled: + return + while True: + started = time.monotonic() + try: + await _in_daemon_thread(self.ping) + except asyncio.CancelledError: + raise + except Exception as e: + logger.debug("Healthchecks ping task error: %s", e) + await asyncio.sleep( + max( + min(self.interval, _PING_MIN_GAP_SEC), + self.interval - (time.monotonic() - started), + ) + ) + def _record(self, reason, detail=""): + if not self._record_failure: + return try: - resp = bounded_get(self.url, timeout=_PING_TIMEOUT_SEC, proxies=self._proxies) - if 200 <= resp.status_code < 300: - if self._last_ping_ok is False: - logger.info( - "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 - 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) - return False - except Exception as e: # pragma: no cover - defensive; never break the loop - logger.debug("Healthchecks unexpected error: %s", e) - return False + self._record_failure(time.time(), reason, detail) + except Exception: # noqa: S110 + pass + + +def _failure_name(exc): + return exc.name if isinstance(exc, PingFailure) else type(exc).__name__ + + +def _failure_class(exc, via_proxy=False): + if isinstance(exc, PingFailure): + return exc.reason + 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/notify/healthchecks_child.py b/dashboard/mining_dashboard/service/notify/healthchecks_child.py new file mode 100644 index 0000000000..e6a0157d05 --- /dev/null +++ b/dashboard/mining_dashboard/service/notify/healthchecks_child.py @@ -0,0 +1,30 @@ +import json +import sys + +import requests + +from mining_dashboard.helper.http import bounded_get +from mining_dashboard.service.notify.healthchecks import _failure_class + + +def main(): + request = json.load(sys.stdin) + proxy = request["proxy"] + proxies = {"http": proxy, "https": proxy} if proxy else None + try: + resp = bounded_get( + request["url"], + timeout=request["timeout"], + deadline=request["deadline"], + proxies=proxies, + ) + out = {"status": resp.status_code} + except requests.RequestException as e: + out = {"reason": _failure_class(e, proxies is not None), "name": type(e).__name__} + except Exception as e: + out = {"reason": "connect", "name": type(e).__name__} + sys.stdout.write(json.dumps(out)) + + +if __name__ == "__main__": + main() diff --git a/dashboard/mining_dashboard/service/payout_sync.py b/dashboard/mining_dashboard/service/payout_sync.py index 165d905923..79d69a406e 100644 --- a/dashboard/mining_dashboard/service/payout_sync.py +++ b/dashboard/mining_dashboard/service/payout_sync.py @@ -25,6 +25,7 @@ import logging import time +from mining_dashboard.config import config from mining_dashboard.config.config import ( MONERO_WALLET_ADDRESS, TARI_WALLET_ADDRESS, @@ -60,6 +61,11 @@ async def sync_monero(state_manager, wallet_client, alert_service): wallet_id = configured_wallet_id(chain) if wallet_id is None: return False + addresses = await asyncio.to_thread(wallet_client.payout_addresses) + if addresses is None: + return False + if config.MONERO_WALLET_ADDRESS.strip() not in addresses: + return True min_height = await asyncio.to_thread(state_manager.get_payout_max_height, chain, wallet_id) payouts, answered = await asyncio.to_thread(wallet_client.scan, min_height) if not answered or not payouts: @@ -81,6 +87,11 @@ async def sync_tari(state_manager, tari_wallet_client, alert_service): wallet_id = configured_wallet_id(chain) if wallet_id is None: return False + addresses, match = await tari_wallet_client.payout_addresses(config.TARI_WALLET_ADDRESS) + if addresses is None: + return False + if not match: + return True min_height = await asyncio.to_thread(state_manager.get_payout_max_height, chain, wallet_id) payouts, answered = await tari_wallet_client.scan(min_height) if not answered or not payouts: diff --git a/dashboard/mining_dashboard/service/storage_schema.py b/dashboard/mining_dashboard/service/storage_schema.py index 44f4f74746..1df8198039 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. @@ -243,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 @@ -263,6 +273,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 +287,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 @@ -333,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/service/workers/worker_change_audit.py b/dashboard/mining_dashboard/service/workers/worker_change_audit.py index b6d178ab86..761bebb434 100644 --- a/dashboard/mining_dashboard/service/workers/worker_change_audit.py +++ b/dashboard/mining_dashboard/service/workers/worker_change_audit.py @@ -216,7 +216,9 @@ async def note_revision_drift(svc, worker_row, extra_stats, cap, window_sec): one of the ceiling's ``_WORKERS_MAX`` slots, the same slot a later real detection starts from. """ worker = (worker_row or {}).get("name") or "" - meta = parse_config_meta(((extra_stats or {}).get("rigforge") or {}).get("config_meta")) + rf = (extra_stats or {}).get("rigforge") + rf = rf if isinstance(rf, dict) else {} + meta = parse_config_meta(rf.get("config_meta")) if not worker or not meta: return now = time.time() @@ -227,7 +229,7 @@ async def note_revision_drift(svc, worker_row, extra_stats, cap, window_sec): if first_over: await record_cap_marker(svc, worker, cap, "revision-drift") return - version = ((extra_stats or {}).get("rigforge") or {}).get("version") + version = rf.get("version") valid = isinstance(version, str) and version.isascii() and version.isprintable() version = version if valid and 0 < len(version) <= _MAX_VERSION_LEN else None drift = await asyncio.to_thread(svc.state_manager.note_worker_revision, worker, meta, version) diff --git a/dashboard/mining_dashboard/service/xvb/algo_service.py b/dashboard/mining_dashboard/service/xvb/algo_service.py index fc8a884263..c6a795f278 100644 --- a/dashboard/mining_dashboard/service/xvb/algo_service.py +++ b/dashboard/mining_dashboard/service/xvb/algo_service.py @@ -77,7 +77,7 @@ async def switch_miners(self, mode, state_label=None): Configures the upstream pool priority for the XMRig Proxy. """ # The local p2pool pool dials direct (it's on the bridge). The XvB pool routes through Tor by - # default (#166) — its per-pool `socks5` makes the proxy reach na.xmrvsbeast.com via Tor + # default (#166) — its per-pool `socks5` makes the proxy reach eu.xmrvsbeast.com via Tor # (DNS resolved proxy-side), so donation mining doesn't expose the home IP. `xvb.tor: false` # opts out. Only the XvB pool gets `socks5`; the local pool never does. p2pool_pool = { diff --git a/dashboard/mining_dashboard/service/xvb/steering_projection.py b/dashboard/mining_dashboard/service/xvb/steering_projection.py index d532cc672d..91dbf4d89e 100644 --- a/dashboard/mining_dashboard/service/xvb/steering_projection.py +++ b/dashboard/mining_dashboard/service/xvb/steering_projection.py @@ -23,13 +23,14 @@ def won_round_live(state_manager, hold_s, now=None, logger=None) -> bool: this holds. Fails open to False (normal steering) on any read error — the hold is a yield optimization, never a safety path.""" try: - since = (now if now is not None else time.time()) - hold_s + now = now if now is not None else time.time() + since = now - hold_s wins = state_manager.get_raffle_wins(since=since) + return isinstance(wins, list) and any(since <= w["ts"] <= now + 60 for w in wins) except Exception as e: if logger is not None: logger.debug(f"Raffle-win read failed; steering normally: {e}") return False - return isinstance(wins, list) and len(wins) > 0 def max_donation_fraction(current_hr, window_duration, p2pool_stats, reserve_factor, max_fraction): diff --git a/dashboard/mining_dashboard/web/auth.py b/dashboard/mining_dashboard/web/auth.py new file mode 100644 index 0000000000..0e9efab9d0 --- /dev/null +++ b/dashboard/mining_dashboard/web/auth.py @@ -0,0 +1,221 @@ +import asyncio +import base64 +import ipaddress +import logging +import sqlite3 +import time +from pathlib import Path + +import aiohttp +from aiohttp import web + +from mining_dashboard.service import auth_sessions + +logger = logging.getLogger("WebAuth") + +COOKIE = "pithead_session" +VERIFY_URL = "http://127.0.0.1:8001/" +EPOCH_HEADER = "X-Pithead-Auth-Epoch" +REFRESH_HEADER = "X-Pithead-Session-Refresh" +LOGIN_TEMPLATE = Path(__file__).parent / "templates" / "login.html" +FAILURE_LIMIT = 5 +FAILURE_WINDOW = 60 +MAX_TRACKED_CLIENTS = 1024 +MAX_CONCURRENT_VERIFY = 4 +MAX_LOGIN_BYTES = 4096 +MAX_FIELD_CHARS = 256 + + +class Attempts: + def __init__(self): + self._failures = {} + + def retry_after(self, key, now=None): + now = time.monotonic() if now is None else now + recent = [t for t in self._failures.get(key, ()) if now - t < FAILURE_WINDOW] + if recent: + self._failures[key] = recent + else: + self._failures.pop(key, None) + if len(recent) < FAILURE_LIMIT: + return 0 + return max(1, int(FAILURE_WINDOW - (now - recent[0])) + 1) + + def failed(self, key, now=None): + now = time.monotonic() if now is None else now + if key not in self._failures and len(self._failures) >= MAX_TRACKED_CLIENTS: + self._failures.pop(next(iter(self._failures))) + self._failures.setdefault(key, []).append(now) + + +def trusted_proxy(request) -> bool: + try: + return ipaddress.ip_address(request.remote).is_loopback + except (ValueError, TypeError): + return False + + +def client_key(request): + forwarded = request.headers.get("X-Forwarded-For", "").split(",")[0].strip() + if trusted_proxy(request) and forwarded: + try: + return str(ipaddress.ip_address(forwarded)) + except ValueError: + pass + return request.remote or "unknown" + + +def secure(request): + return request.secure or ( + trusted_proxy(request) and request.headers.get("X-Forwarded-Proto") == "https" + ) + + +def _set_cookie(request, response, token, remember): + response.set_cookie( + COOKIE, + token, + max_age=auth_sessions.REMEMBER_SECONDS if remember else None, + httponly=True, + samesite="Strict", + secure=secure(request), + path="/", + ) + + +def annotate(request, state): + state["auth_user"] = request.headers.get("X-Auth-User", "") + state["auth_session"] = bool(request.cookies.get(COOKIE)) + return state + + +async def login_page(request): + return web.FileResponse(LOGIN_TEMPLATE, headers={"Cache-Control": "no-store"}) + + +async def _verify(request, username, password): + raw = f"{username}:{password}".encode() + headers = {"Authorization": "Basic " + base64.b64encode(raw).decode()} + timeout = aiohttp.ClientTimeout(total=5) + async with aiohttp.ClientSession(timeout=timeout) as http: + async with http.get( + request.app["auth"]["verify_url"], headers=headers, allow_redirects=False + ) as resp: + if resp.status == 204: + return True + if resp.status == 401: + return False + raise aiohttp.ClientError("unexpected verifier status") + + +async def login(request): + epoch = request.headers.get(EPOCH_HEADER, "") + if not epoch: + raise web.HTTPNotFound() + if request.content_length is None or request.content_length > MAX_LOGIN_BYTES: + raise web.HTTPBadRequest(text="Invalid login request.") + try: + data = await request.json() + except ValueError: + raise web.HTTPBadRequest(text="Invalid login request.") from None + if not isinstance(data, dict): + raise web.HTTPBadRequest(text="Invalid login request.") + username, password, remember = data.get("username"), data.get("password"), data.get("remember") + if not (isinstance(username, str) and isinstance(password, str)): + raise web.HTTPBadRequest(text="Invalid login request.") + if len(username) > MAX_FIELD_CHARS or len(password) > MAX_FIELD_CHARS or ":" in username: + return web.json_response({"error": "Invalid username or password."}, status=401) + + attempts, key = request.app["auth"]["attempts"], client_key(request) + wait = attempts.retry_after(key) + if wait or request.app["auth"]["busy"] >= MAX_CONCURRENT_VERIFY: + raise web.HTTPTooManyRequests( + text="Too many sign-in attempts. Try again shortly.", + headers={"Retry-After": str(wait or FAILURE_WINDOW)}, + ) + request.app["auth"]["busy"] += 1 + try: + ok = await _verify(request, username, password) + except (aiohttp.ClientError, TimeoutError): + logger.warning("Sign-in verifier unreachable") + raise web.HTTPServiceUnavailable(text="Sign-in is temporarily unavailable.") from None + finally: + request.app["auth"]["busy"] -= 1 + if not ok: + attempts.failed(key) + logger.warning("Failed dashboard sign-in from %s", key) + return web.json_response({"error": "Invalid username or password."}, status=401) + + remember = remember is True + try: + token = await asyncio.to_thread( + auth_sessions.issue, request.app["state_manager"], username, epoch, remember + ) + except sqlite3.Error: + logger.warning("Sign-in refused: the session store cannot write") + return web.json_response( + {"error": "The data disk is full, so sign-in cannot save your session."}, + status=503, + headers={"Cache-Control": "no-store"}, + ) + response = web.json_response({"ok": True}, headers={"Cache-Control": "no-store"}) + _set_cookie(request, response, token, remember) + return response + + +async def logout(request): + token = request.cookies.get(COOKIE, "") + if token: + await asyncio.to_thread(auth_sessions.revoke, request.app["state_manager"], token) + response = web.json_response({"ok": True}, headers={"Cache-Control": "no-store"}) + response.del_cookie(COOKIE, path="/", httponly=True, samesite="Strict", secure=secure(request)) + return response + + +def _wants_page(request): + uri = request.headers.get("X-Forwarded-Uri", "") + return ( + request.headers.get("X-Forwarded-Method", "GET") == "GET" + and "text/html" in request.headers.get("Accept", "") + and not uri.startswith("/api/") + ) + + +async def check(request): + session = await asyncio.to_thread( + auth_sessions.validate, + request.app["state_manager"], + request.cookies.get(COOKIE, ""), + request.headers.get(EPOCH_HEADER, ""), + ) + if session is None: + if _wants_page(request): + raise web.HTTPSeeOther("/login", headers={"Cache-Control": "no-store"}) + raise web.HTTPUnauthorized(text="Authentication required.") + username, _, refresh = session + headers = {"X-Auth-User": username, "Cache-Control": "no-store"} + if refresh: + headers[REFRESH_HEADER] = "1" + return web.Response(status=204, headers=headers) + + +@web.middleware +async def refresh_middleware(request, handler): + response = await handler(request) + token = request.cookies.get(COOKIE, "") + if token and request.headers.get(REFRESH_HEADER) == "1": + _set_cookie(request, response, token, True) + return response + + +def setup(app): + auth_sessions.create_schema(app["state_manager"]) + app["auth"] = {"attempts": Attempts(), "busy": 0, "verify_url": VERIFY_URL} + app.add_routes( + [ + web.get("/login", login_page), + web.post("/api/auth/login", login), + web.post("/api/auth/logout", logout), + web.get("/api/auth/check", check), + ] + ) diff --git a/dashboard/mining_dashboard/web/server.py b/dashboard/mining_dashboard/web/server.py index 51d7b5e0f5..e18b4588d9 100644 --- a/dashboard/mining_dashboard/web/server.py +++ b/dashboard/mining_dashboard/web/server.py @@ -4,6 +4,7 @@ import mimetypes import os import re +import uuid from aiohttp import web @@ -14,7 +15,7 @@ from mining_dashboard.service.health.update_checker import parse_semver from mining_dashboard.service.metrics import build_metrics, share_reject_pct from mining_dashboard.service.workers import worker_adopt, worker_refresh -from mining_dashboard.web import fleet_upgrade_views +from mining_dashboard.web import auth, fleet_upgrade_views from mining_dashboard.web.config_commit import approval_envelope, config_request from mining_dashboard.web.miner_connection import handle_miner_connection from mining_dashboard.web.views import diagnostics_views, download_views, log_views, sovereign_views @@ -42,21 +43,18 @@ async def handle_index(request): async def handle_state(request): - """The dashboard's data API. Pull shared state, delegate to the view layer, and return - the assembled state object as JSON (or a sanitized 500 on failure).""" app = request.app data = app["latest_data"] state_mgr = app["state_manager"] range_arg = request.query.get("range", "all") - # Optional manual-zoom window (Issue #47); malformed from/to falls back to the preset range. window = parse_window(request.query.get("from"), request.query.get("to")) - # Hashrate-averaging window for the chart (#168); unknown/missing falls back to the default. avg_window = canonical_window(request.query.get("avg")) try: - return web.json_response(build_state(data, state_mgr, range_arg, window, avg_window)) + return web.json_response( + auth.annotate(request, build_state(data, state_mgr, range_arg, window, avg_window)) + ) except Exception: - # Log the full error server-side; never leak exception details to the browser. logger.exception("Error building dashboard state") return web.json_response({"error": "Failed to build dashboard state."}, status=500) @@ -122,12 +120,6 @@ async def handle_metrics(request): return web.Response(text="Failed to render metrics.", status=500, content_type="text/plain") -# --- Dashboard control channel (#33) --------------------------------------------------------- -# Registered only when DASHBOARD_CONTROL_ENABLED (absent routes 404 when the feature is off). -# Every mutating POST must carry this custom header: a cross-site header forces a CORS preflight, -# which the self-only CSP origin never grants (a cheap CSRF guard, same spirit as the CSP below). -# The actor is Caddy's authenticated X-Auth-User (header_up overwrites any client value). - CONTROL_HEADER = "X-Pithead-Control" @@ -181,11 +173,15 @@ async def handle_control_commit(request): _require_control_header(request) body = await config_request(request) try: - actor = request.headers.get("X-Auth-User", "") approval = approval_envelope(body) + if body.get("id"): + uuid.UUID(body["id"]) + except Exception: + raise web.HTTPBadRequest(text="Body must be JSON with a valid intent 'id'.") from None + try: rid = control_service.submit( "commit", - actor=actor, + actor=request.headers.get("X-Auth-User", ""), intent_id=body.get("id"), # #719: the operator's typed confirmation for an in-scope disruptive change. It is # friction, not a secret — the host gate requires it before a CONFIRM row proceeds. @@ -193,7 +189,8 @@ async def handle_control_commit(request): approval=approval, ) except Exception: - raise web.HTTPBadRequest(text="Body must be JSON with a valid intent 'id'.") from None + logger.exception("Error submitting control commit") + return web.json_response({"error": "Failed to submit the commit request."}, status=500) # The preview result (same id) is still on disk; wait for the runner to overwrite it. res = await control_service.wait_result(rid, done=lambda r: r.get("status") != "previewed") if res is None: @@ -575,16 +572,14 @@ async def _cancel_bg_tasks(app): def create_app(state_manager, latest_data_ref, notify=None): - """Factory to create the web app instance.""" - app = web.Application(middlewares=[security_headers_middleware]) + app = web.Application(middlewares=[security_headers_middleware, auth.refresh_middleware]) app["state_manager"] = state_manager app["latest_data"] = latest_data_ref app["notify"] = notify app["_fleet"] = {} - # Fire-and-forget recorder tasks (worker-upgrade, #1014) — tracked so they can't be - # garbage-collected mid-flight and so shutdown can cancel any still in progress. app["_bg_tasks"] = set() app.on_cleanup.append(_cancel_bg_tasks) + auth.setup(app) app.add_routes( [ @@ -594,6 +589,7 @@ def create_app(state_manager, latest_data_ref, notify=None): web.get("/api/xvb-standby", handle_xvb_standby), web.get("/metrics", handle_metrics), web.get("/api/access", handle_access_log), + *diagnostics_views.support_routes(), ] ) # Control channel (#33): routes exist only when the feature is on — off means 404, not 403. @@ -615,9 +611,7 @@ def create_app(state_manager, latest_data_ref, notify=None): web.get("/api/control/backup-download", download_views.handle_backup_download), web.post("/api/control/os-update", handle_control_os_update), web.post("/api/control/power", handle_control_power), - 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(), ] ) if config.DASHBOARD_MODE in ("api", "both"): diff --git a/dashboard/mining_dashboard/web/static/app/components.mjs b/dashboard/mining_dashboard/web/static/app/components.mjs index 31792a0ce0..d6f206663d 100644 --- a/dashboard/mining_dashboard/web/static/app/components.mjs +++ b/dashboard/mining_dashboard/web/static/app/components.mjs @@ -3,8 +3,10 @@ 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 { SupportBundlePanel } from "../system/supportbundle.mjs"; import { SyncView } from "../system/syncview.mjs"; import { MinerConnection } from "../workers/minerconnection.mjs"; import { WorkersTable } from "../workers/workertable.mjs"; @@ -103,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} />
` : null } ${ @@ -134,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} />
` } `; @@ -147,6 +149,7 @@ export function App({ state, connected, recoveryNeeded = false, + reloading = null, ui, onRange, onSort, @@ -186,7 +189,9 @@ export function App({ return html`<${Fragment}> <${Header} state=${state} theme=${ui.theme} onTheme=${onTheme} />
+ <${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/app/header.mjs b/dashboard/mining_dashboard/web/static/app/header.mjs index 2caafce598..79759150e9 100644 --- a/dashboard/mining_dashboard/web/static/app/header.mjs +++ b/dashboard/mining_dashboard/web/static/app/header.mjs @@ -4,7 +4,19 @@ import { OsUpdateControl } from "../system/osupdate.mjs"; import { html } from "./preact.mjs"; import { Badges, cVar, HighUsage, ThemeSwitcher, UpdateBadge, VersionBadge } from "./ui.mjs"; -// --- Top bar ------------------------------------------------------------------------- +async function signOut() { + try { + await fetch("/api/auth/logout", { method: "POST" }); + } finally { + location.assign("/login"); + } +} + +function SignOut({ state }) { + if (!state.auth_session) return null; + return html``; +} 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/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/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 62204e42bd..d603230b0e 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)); @@ -400,6 +400,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" @@ -444,12 +445,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/configwarnings.mjs b/dashboard/mining_dashboard/web/static/config/configwarnings.mjs index 97df26f632..6be7797fae 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.bot_token": "Telegram bot token changing — a wrong token stops every Telegram alert, the tamper alarms included, and another bot's token sends them to that bot's owner.", "telegram.chat_id": 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.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/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/login.js b/dashboard/mining_dashboard/web/static/login.js new file mode 100644 index 0000000000..9e7b6c17cd --- /dev/null +++ b/dashboard/mining_dashboard/web/static/login.js @@ -0,0 +1,41 @@ +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 { + const body = await response.json().catch(() => null); + fail( + body && body.error ? body.error : "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/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/network/onionurl.mjs b/dashboard/mining_dashboard/web/static/network/onionurl.mjs index dfcd1822ac..bcbf4427d8 100644 --- a/dashboard/mining_dashboard/web/static/network/onionurl.mjs +++ b/dashboard/mining_dashboard/web/static/network/onionurl.mjs @@ -21,6 +21,7 @@ import { Component, html } from "../app/preact.mjs"; import { pollResult } from "../config/configview.mjs"; +import { controlFetch, requirePreviewResponse } from "../config/controlclient.mjs"; const CONTROL_HEADERS = { "Content-Type": "application/json", "X-Pithead-Control": "1" }; // The host answers this one out of .env with no daemon work, so it returns in a drain cycle, not @@ -29,14 +30,12 @@ const KEY_POLL_MAX = 30; const KEY_TIMEOUT = "Stopped waiting for the client key. Check that the pithead-control unit is running, then try again."; -// POST the intent, then poll past the runner's interim status to a terminal result. Exported for -// node --test: this network flow is the logic, and OnionUrl only maps its outcome onto UI state. export async function fetchClientKey() { - const res = await fetch("/api/control/onion-client-key", { + const res = await controlFetch("/api/control/onion-client-key", { method: "POST", headers: CONTROL_HEADERS, }); - if (!res.ok && res.status !== 202) throw new Error(`HTTP ${res.status}`); + await requirePreviewResponse(res); const { id } = await res.json(); return await pollResult(id, "running", KEY_POLL_MAX, KEY_TIMEOUT); } diff --git a/dashboard/mining_dashboard/web/static/sovereign/machines-donation.mjs b/dashboard/mining_dashboard/web/static/sovereign/machines-donation.mjs index 1f44b9c0bc..60eee02642 100644 --- a/dashboard/mining_dashboard/web/static/sovereign/machines-donation.mjs +++ b/dashboard/mining_dashboard/web/static/sovereign/machines-donation.mjs @@ -25,7 +25,7 @@ export class DonationControl extends Component { render({ worker, rigConfig, earnings, canEdit }, { choice, review, confirm, busy, result }) { const current = rigDonation(worker, rigConfig); const selected = choice ?? current.configured ?? current.reported; - const hashrate = Number(worker?.h15) || Number(worker?.h60); + const hashrate = Number(worker?.telemetry_h15) || Number(worker?.h15) || Number(worker?.h60); const cost = dailyCost(choice ?? 0, hashrate, earnings?.available ? earnings.coeff_day : 0); return html`
Support the XMRig developers diff --git a/dashboard/mining_dashboard/web/static/sovereign/machines-model.mjs b/dashboard/mining_dashboard/web/static/sovereign/machines-model.mjs index ed170c3ee9..469bbbfc75 100644 --- a/dashboard/mining_dashboard/web/static/sovereign/machines-model.mjs +++ b/dashboard/mining_dashboard/web/static/sovereign/machines-model.mjs @@ -6,10 +6,16 @@ export const SORTS = { hashrate: "Hashrate", }; +export function rigRate(worker) { + return ( + [worker?.telemetry_h60, worker?.h60, worker?.h15].map(Number).find((rate) => rate > 0) ?? 0 + ); +} + export function rigView(worker) { const online = worker?.status === "online"; - const hashrate = Number(worker?.h60); - const reporting = online && Number.isFinite(hashrate) && hashrate > 0; + const hashrate = rigRate(worker); + const reporting = online && hashrate > 0; const behind = worker?.rigforge_update?.available === true; const status = !online ? "Offline" : behind ? "Behind" : "Mining"; const note = online diff --git a/dashboard/mining_dashboard/web/static/sovereign/overview.mjs b/dashboard/mining_dashboard/web/static/sovereign/overview.mjs index 75a6ca7ea1..a40d968682 100644 --- a/dashboard/mining_dashboard/web/static/sovereign/overview.mjs +++ b/dashboard/mining_dashboard/web/static/sovereign/overview.mjs @@ -1,5 +1,6 @@ import { Component, html } from "../app/preact.mjs"; import { verdictText } from "../system/osverdict.mjs"; +import { rigRate } from "./machines-model.mjs"; import { OverviewChart } from "./overview-chart.mjs"; import { activityEntries, @@ -85,7 +86,7 @@ export function Overview({ state, connected, range, window, onRange, onWindow, f const readings = state?.overview; const workers = state?.workers || []; const mining = workers.filter( - (worker) => worker.status === "online" && number(worker.h60) && worker.h60 > 0, + (worker) => worker.status === "online" && rigRate(worker) > 0, ).length; const last = state?.overview?.last_payout; const issues = attention(state); diff --git a/dashboard/mining_dashboard/web/static/styles/config.css b/dashboard/mining_dashboard/web/static/styles/config.css index da542f7155..1f41cb2ebe 100644 --- a/dashboard/mining_dashboard/web/static/styles/config.css +++ b/dashboard/mining_dashboard/web/static/styles/config.css @@ -72,15 +72,21 @@ margin: 15px 0; } .config-actions .btn-toggle, -.config-modal-actions .btn-toggle { +.config-modal-actions .btn-toggle, +.diag-card .btn-toggle { border: 1px solid var(--border); border-radius: 6px; } .config-actions .btn-toggle:disabled, -.config-modal-actions .btn-toggle:disabled { +.config-modal-actions .btn-toggle:disabled, +.diag-card .btn-toggle:disabled { opacity: 0.5; cursor: not-allowed; } +.diag-card .btn-toggle:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} .config-modal { box-sizing: border-box; width: min(640px, calc(100% - 32px)); 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/static/system/backupview.mjs b/dashboard/mining_dashboard/web/static/system/backupview.mjs index a4e8e75fda..14582d870a 100644 --- a/dashboard/mining_dashboard/web/static/system/backupview.mjs +++ b/dashboard/mining_dashboard/web/static/system/backupview.mjs @@ -12,6 +12,7 @@ import { Modal } from "../app/modal.mjs"; import { Component, createRef, html } from "../app/preact.mjs"; import { failureLog } from "../config/applyfailure.mjs"; import { pollResult } from "../config/configview.mjs"; +import { controlFetch, requirePreviewResponse } from "../config/controlclient.mjs"; import { fmtEpoch } from "./securityview.mjs"; const CONTROL_HEADERS = { "Content-Type": "application/json", "X-Pithead-Control": "1" }; @@ -21,12 +22,12 @@ const BACKUP_TIMEOUT = const APPLIANCE_BACKUP_TIMEOUT = "Stopped waiting for the backup. The host keeps trying, but this dashboard did not return; restart the appliance to recover the normal startup path, then check Backup again."; -// POST the backup intent, then poll past the runner's interim "running" to a terminal result. -// Exported for node --test — this network flow is the logic; BackupPanel only maps its outcome -// onto UI state. export async function runBackup(appliance = false) { - const res = await fetch("/api/control/backup", { method: "POST", headers: CONTROL_HEADERS }); - if (!res.ok && res.status !== 202) throw new Error(`HTTP ${res.status}`); + const res = await controlFetch("/api/control/backup", { + method: "POST", + headers: CONTROL_HEADERS, + }); + await requirePreviewResponse(res); const { id } = await res.json(); const timeout = appliance ? APPLIANCE_BACKUP_TIMEOUT : BACKUP_TIMEOUT; const result = await pollResult(id, "running", BACKUP_POLL_MAX, timeout); diff --git a/dashboard/mining_dashboard/web/static/system/diagview.mjs b/dashboard/mining_dashboard/web/static/system/diagview.mjs index d9d3429894..cd3d071957 100644 --- a/dashboard/mining_dashboard/web/static/system/diagview.mjs +++ b/dashboard/mining_dashboard/web/static/system/diagview.mjs @@ -10,6 +10,8 @@ // its fixed allowlist. Preact interpolation is the final output-escaping boundary in the browser. import { Component, html } from "../app/preact.mjs"; +import { controlFetch, staleError } from "../config/controlclient.mjs"; +import { RestartAllControl, TOR_RESET_POLL_MAX, TorResetControl } from "./stackactions.mjs"; import { TorSnapshotTable } from "./torsnapshot.mjs"; const CONTROL_HEADERS = { "Content-Type": "application/json", "X-Pithead-Control": "1" }; @@ -36,9 +38,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], @@ -69,24 +80,15 @@ export class DiagnosticWaitTimeout extends Error { } } -// Diagnostics do not write an intermediate `running` result: HTTP 202 means only that no durable -// result exists yet. Keep that uncertainty instead of borrowing the upgrade flow's version copy or -// calling the runner wedged from elapsed time alone. export async function runDiag(path, body, label = "the diagnostics request", max = DIAG_POLL_MAX) { - let res; - try { - res = await fetch(`/api/control/${path}`, { - method: "POST", - headers: CONTROL_HEADERS, - body: JSON.stringify(body || {}), - }); - } catch { - throw new Error( - `Could not submit ${label}: the dashboard could not reach the control service.`, - ); - } + const res = await controlFetch(`/api/control/${path}`, { + method: "POST", + headers: CONTROL_HEADERS, + body: JSON.stringify(body || {}), + }); + if (res.status === 401 || res.status === 403) throw staleError(); if (!res.ok && res.status !== 202) - throw new Error(`Could not submit ${label}: HTTP ${res.status}`); + throw new Error(`Could not submit ${label}: ${(await res.text()) || `HTTP ${res.status}`}`); let id; try { ({ id } = await res.json()); @@ -104,6 +106,7 @@ export async function runDiag(path, body, label = "the diagnostics request", max continue; } if (result.status === 202 || [502, 503, 504].includes(result.status)) continue; + if (result.status === 401 || result.status === 403) throw staleError(); if (!result.ok) throw new Error(`Could not read ${label}: HTTP ${result.status}`); try { return await result.json(); @@ -167,7 +170,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() { @@ -215,6 +218,62 @@ 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`, + service === "tor" ? TOR_RESET_POLL_MAX : undefined, + ); + 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.

`; @@ -273,6 +332,8 @@ export class DiagnosticsPanel extends Component { : html`

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

` } ${this.renderLog(service.name)} + ${this.renderRestart(service.name)} + ${service.name === "tor" ? html`<${TorResetControl} run=${runDiag} />` : null} `; } @@ -288,12 +349,13 @@ export class DiagnosticsPanel extends Component { const groups = groupDoctorRows(haveReport ? healthResult.doctor : null); const reportRows = haveReport ? doctorRows(healthResult.doctor) : []; const summary = haveReport ? doctorSummary(healthResult.doctor) : null; - return html`
+ return html`

Service diagnostics

Run the host's read-only health check once. Every service and the machine checks appear 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/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/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/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/static/system/supportbundle.mjs b/dashboard/mining_dashboard/web/static/system/supportbundle.mjs new file mode 100644 index 0000000000..fb593cba31 --- /dev/null +++ b/dashboard/mining_dashboard/web/static/system/supportbundle.mjs @@ -0,0 +1,230 @@ +import { Component, html } from "../app/preact.mjs"; + +const CONTROL_HEADERS = { "Content-Type": "application/json", "X-Pithead-Control": "1" }; +const POLL_MS = 2000; +const BUNDLE_POLL_MAX = 450; +const RANGE_POLL_MAX = 15; +const RANGE_CACHE_MS = 300000; +let rangeCache = null; +const BUNDLE_TIMEOUT = + "Stopped waiting for the support bundle. The host keeps collecting, but this dashboard did not return; reload, then export again only after the earlier request has finished."; + +export const DEFAULT_HOURS = 72; +export const PRESETS = [ + { hours: 1, label: "Last 1 hour" }, + { hours: 6, label: "Last 6 hours" }, + { hours: 24, label: "Last 24 hours" }, + { hours: 72, label: "Last 72 hours" }, + { hours: 168, label: "Last 7 days" }, +]; + +const stripMs = (d) => d.toISOString().replace(/\.\d{3}Z$/, "Z"); +const shown = (iso) => String(iso).replace("T", " ").replace("Z", " UTC"); + +export function requestWindow({ preset, since, until }, now = new Date()) { + if (preset !== "custom") return { body: { hours: preset } }; + const start = new Date(since); + const end = new Date(until); + if (!since || !until || Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) { + return { error: "Invalid range: choose both a start and an end time." }; + } + if (start >= end) return { error: "Invalid range: the start must be before the end." }; + if (end > now) return { error: "Invalid range: the end cannot be in the future." }; + return { body: { since: stripMs(start), until: stripMs(end) } }; +} + +export function reachNote(oldest, body, now = new Date()) { + if (!oldest || !(body.since || body.hours)) return null; + const from = body.since ? new Date(body.since) : new Date(now.getTime() - body.hours * 3600000); + if (from >= new Date(oldest)) return null; + return `The logs on this system only reach back to ${shown(oldest)}. The bundle will start there.`; +} + +async function pollSupport(id, max, timeoutMessage) { + for (let i = 0; i < max; i++) { + await new Promise((r) => setTimeout(r, POLL_MS)); + let res; + try { + res = await fetch(`/api/control/support-bundle-result?id=${encodeURIComponent(id)}`); + } catch { + continue; + } + if (res.status === 202 || [502, 503, 504].includes(res.status)) continue; + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const out = await res.json(); + if (out.status === "running") continue; + return out; + } + throw new Error(timeoutMessage); +} + +async function submit(path, body) { + const res = await fetch(path, { + method: "POST", + headers: CONTROL_HEADERS, + body: JSON.stringify(body), + }); + if (res.status === 400) { + throw new Error(`Invalid range: ${(await res.text()).trim() || "the request was refused."}`); + } + if (!res.ok && res.status !== 202) throw new Error(`HTTP ${res.status}`); + return (await res.json()).id; +} + +export async function runSupportBundle(body) { + const id = await submit("/api/control/support-bundle", body); + const result = await pollSupport(id, BUNDLE_POLL_MAX, BUNDLE_TIMEOUT); + return { id, ...result }; +} + +export async function fetchOldest() { + const id = await submit("/api/control/support-bundle-range", {}); + const result = await pollSupport(id, RANGE_POLL_MAX, ""); + return result.status === "applied" ? result.oldest || null : null; +} + +export function bundleHref(id) { + return `/api/control/support-bundle-download?id=${encodeURIComponent(id)}`; +} + +export async function downloadBundle(id, name) { + const res = await fetch(bundleHref(id)); + if (!res.ok) { + throw new Error( + `The bundle was collected but the download is unavailable (HTTP ${res.status}). It is kept for about an hour; export again.`, + ); + } + const url = URL.createObjectURL(await res.blob()); + const a = document.createElement("a"); + a.href = url; + a.download = name; + document.body.appendChild(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 60000); +} + +export class SupportBundlePanel extends Component { + constructor(props) { + super(props); + this.state = { + phase: "idle", + preset: DEFAULT_HOURS, + since: "", + until: "", + oldest: null, + id: null, + result: null, + error: null, + }; + } + + loadOldest() { + if (this.asked) return; + this.asked = true; + if (rangeCache && Date.now() - rangeCache.at < RANGE_CACHE_MS) { + this.setState({ oldest: rangeCache.oldest }); + return; + } + fetchOldest() + .then((oldest) => { + rangeCache = { oldest, at: Date.now() }; + this.setState({ oldest }); + }) + .catch(() => {}); + } + + async run() { + const win = requestWindow(this.state); + if (win.error) { + this.setState({ phase: "failed", error: win.error }); + return; + } + this.setState({ phase: "collecting", error: null, result: null }); + try { + const out = await runSupportBundle(win.body); + if (out.status !== "applied") { + this.setState({ + phase: "failed", + error: out.error || "The host did not complete the bundle.", + }); + return; + } + this.setState({ id: out.id, result: out }); + await downloadBundle(out.id, out.archive); + this.setState({ phase: "done" }); + } catch (e) { + this.setState({ phase: "failed", error: e.message || String(e) }); + } + } + + render() { + const { phase, preset, oldest, id, result, error } = this.state; + const busy = phase === "collecting"; + const note = reachNote(oldest, requestWindow(this.state).body || {}); + return html`
+

Export logs

+

Collect one redacted zip of the system journal for a bug report: every Pithead + service and container, the kernel log, the boot list, dashboard health history, versions + and the configuration's key shape. Passwords, wallet addresses, tokens and onion + addresses are removed on the host before the zip is written. Nothing leaves the box + until the download starts.

+

${ + oldest + ? `Logs on this system reach back to ${shown(oldest)}.` + : "Pick a time frame to see how far back the logs reach." + }

+ + ${ + preset === "custom" + ? html` + +

Custom times are in this browser's time zone.

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

${note}

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

Collecting on the host — this can take a few minutes. The download starts by itself when it is ready.

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

Downloaded + ${result.archive} — ${result.effective_since ? "window" : "requested window"} + ${shown(result.effective_since || result.since)} to + ${shown(result.effective_until || result.until)}${ + result.journal_short + ? ", shorter than you asked: the logs do not reach back further" + : "" + }. Download again (kept for about an hour).

` + : null + } +
`; + } +} diff --git a/dashboard/mining_dashboard/web/static/workers/workeradopt.mjs b/dashboard/mining_dashboard/web/static/workers/workeradopt.mjs index eb690b8215..dec76f3791 100644 --- a/dashboard/mining_dashboard/web/static/workers/workeradopt.mjs +++ b/dashboard/mining_dashboard/web/static/workers/workeradopt.mjs @@ -1,6 +1,10 @@ import { Component, html } from "../app/preact.mjs"; import { pollResult } from "../config/configview.mjs"; -import { controlCommitResult } from "../config/controlclient.mjs"; +import { + controlCommitResult, + controlFetch, + requirePreviewResponse, +} from "../config/controlclient.mjs"; import { buildAdoptedConfig, buildRemovedConfig, @@ -68,8 +72,8 @@ export class AdoptRigForm extends Component { } this.setState({ busy: true, result: null, preview: null, confirmText: "" }); try { - const cfgRes = await fetch("/api/config"); - if (!cfgRes.ok) throw new Error(`HTTP ${cfgRes.status}`); + const cfgRes = await controlFetch("/api/config"); + await requirePreviewResponse(cfgRes); const liveConfig = await cfgRes.json(); if (host && hostIsInternal(host, liveConfig?.network?.subnet)) { this.setState({ @@ -83,12 +87,12 @@ export class AdoptRigForm extends Component { return; } const proposed = build(liveConfig); - const res = await fetch("/api/control/preview", { + const res = await controlFetch("/api/control/preview", { method: "POST", headers: CONTROL_HEADERS, body: JSON.stringify({ config: proposed }), }); - if (!res.ok && res.status !== 202) throw new Error(`HTTP ${res.status}`); + await requirePreviewResponse(res); let out = await res.json(); if (out.status === "pending") out = { id: out.id, ...(await pollResult(out.id)) }; if (out.status === "rejected") { @@ -113,12 +117,12 @@ export class AdoptRigForm extends Component { const { preview, confirmText } = this.state; this.setState({ busy: true }); try { - const res = await fetch("/api/control/commit", { + const res = await controlFetch("/api/control/commit", { method: "POST", headers: CONTROL_HEADERS, body: JSON.stringify({ id: preview.id, confirm: confirmText }), }); - if (!res.ok && res.status !== 202) throw new Error(`HTTP ${res.status}`); + await requirePreviewResponse(res); const committed = await controlCommitResult(res, preview.id, pollResult); this.setState({ busy: false, preview: null, confirmText: "", result: committed }); if (committed.status === "applied" && this.props.onAdopted) this.props.onAdopted(); 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/static/workers/workerupgrade.mjs b/dashboard/mining_dashboard/web/static/workers/workerupgrade.mjs index 9c2ad68cfc..1f30b7a1a7 100644 --- a/dashboard/mining_dashboard/web/static/workers/workerupgrade.mjs +++ b/dashboard/mining_dashboard/web/static/workers/workerupgrade.mjs @@ -7,6 +7,7 @@ import { Component, html } from "../app/preact.mjs"; import { STATUS_META } from "../config/confighistory.mjs"; +import { controlFetch, requirePreviewResponse, staleError } from "../config/controlclient.mjs"; export const CONTROL_HEADERS = { "Content-Type": "application/json", "X-Pithead-Control": "1" }; const POLL_MS = 2000; @@ -32,7 +33,9 @@ export async function pollWorkerResult(id, max = POLL_MAX) { continue; } if (res.status === 202) continue; - if (!res.ok) return { status: "error", error: `HTTP ${res.status}` }; + if (res.status === 401 || res.status === 403) + return { status: "error", error: String(staleError()) }; + if (!res.ok) return { status: "error", error: (await res.text()) || `HTTP ${res.status}` }; const out = await res.json(); if (out.status && out.status !== "running") return out; } @@ -67,18 +70,16 @@ export class RigUpgrade extends Component { this.state = { upgArmed: false, upgBusy: false, upgResult: null }; } - // One-click rig upgrade (#597). POSTs {worker, version} only — the version is the badge's - // latest, a proposal the HOST re-derives and the rig bounds; this client never picks a target. - // 202 means spooled: poll with the long budget (the rig may rebuild its miner, ~10 min). async upgrade() { const version = this.props.update.latest; this.setState({ upgArmed: false, upgBusy: true, upgResult: { status: "running" } }); try { - const res = await fetch("/api/control/worker-upgrade", { + const res = await controlFetch("/api/control/worker-upgrade", { method: "POST", headers: CONTROL_HEADERS, body: JSON.stringify({ worker: this.props.name, version }), }); + await requirePreviewResponse(res); let out = await res.json(); if (res.status === 202 && out.id) out = await pollWorkerResult(out.id, UPGRADE_POLL_MAX); this.setState({ upgBusy: false, upgResult: out }); 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/mining_dashboard/web/views/diagnostics_views.py b/dashboard/mining_dashboard/web/views/diagnostics_views.py index 9312ffc017..3be595f9f0 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). @@ -108,3 +129,119 @@ 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_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 + window = {} + 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.") + for key in ("since", "until"): + if key in body: + value = body[key] + if not isinstance(value, str) or not 0 < len(value) <= 40: + raise web.HTTPBadRequest(text=f"'{key}' must be an RFC 3339 time string.") + window[key] = value + try: + rid = diagnostics_service.submit_support_bundle( + hours, request.headers.get("X-Auth-User", ""), **window + ) + 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) + + +async def handle_support_range(request): + _require_control_header(request) + try: + rid = diagnostics_service.submit_support_range(request.headers.get("X-Auth-User", "")) + except Exception: + logger.exception("Error submitting support-bundle-range request") + return web.json_response({"error": "Failed to submit the request."}, status=500) + return web.json_response({"id": rid, "status": "pending"}, status=202) + + +SUPPORT_RESULT_KEYS = ( + "status", + "error", + "archive", + "since", + "until", + "hours", + "oldest", + "effective_since", + "effective_until", + "journal_short", + "ts", +) + + +async def handle_support_result(request): + try: + res = control_service.result(request.query.get("id", "")) + except ValueError: + raise web.HTTPBadRequest(text="'id' must be a UUID.") from None + if res is None: + return web.json_response({"status": "pending"}, status=202) + return web.json_response({k: res[k] for k in SUPPORT_RESULT_KEYS if k in res}) + + +def support_routes(): + from mining_dashboard.web.views import download_views + + return [ + web.post("/api/control/support-bundle", handle_support_bundle), + web.post("/api/control/support-bundle-range", handle_support_range), + web.get("/api/control/support-bundle-result", handle_support_result), + web.get( + "/api/control/support-bundle-download", download_views.handle_support_bundle_download + ), + ] + + +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/restart", handle_restart_all), + web.post("/api/control/tor-reset", handle_tor_reset), + ] diff --git a/dashboard/mining_dashboard/web/views/download_views.py b/dashboard/mining_dashboard/web/views/download_views.py index 359fc34a12..fd9a504324 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}.zip") + return web.FileResponse( + path, headers={"Content-Disposition": f'attachment; filename="{archive_name}"'} + ) diff --git a/dashboard/mining_dashboard/web/views/infra_views.py b/dashboard/mining_dashboard/web/views/infra_views.py index 6b0644dcb7..fbf215ea8f 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, @@ -180,15 +178,19 @@ 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": 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"), "donate_level": worker.get("donate_level"), "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/mining_dashboard/web/views/paused_badge.py b/dashboard/mining_dashboard/web/views/paused_badge.py new file mode 100644 index 0000000000..a82cf3c2ff --- /dev/null +++ b/dashboard/mining_dashboard/web/views/paused_badge.py @@ -0,0 +1,29 @@ +from mining_dashboard.config.config import monero_is_local +from mining_dashboard.service.mining_verdict import BACKUP + + +def _paused_reason(data, metrics): + if data.get("stratum_closed"): + pause = data.get("mining_pause") + return f"stratum closed ({pause['reason']})" if pause else "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 [] + 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" + return [{"text": text, "variant": "bad"}] diff --git a/dashboard/mining_dashboard/web/views/views.py b/dashboard/mining_dashboard/web/views/views.py index c04c9c78d5..75dcd301d2 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.host_resources import build_host_resources from mining_dashboard.service.metrics import build_metrics @@ -56,6 +57,7 @@ ) from mining_dashboard.web.views.monero_view import build_monero from mining_dashboard.web.views.overview_views import build_mining_activity, build_overview +from mining_dashboard.web.views.paused_badge import paused_badges from mining_dashboard.web.views.series_views import ( _gauge_series, # noqa: F401 — re-export for worker_detail.py _mode_palette, @@ -242,10 +244,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( @@ -297,6 +297,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"])) disk_growth = state_mgr.get_disk_growth() @@ -378,6 +379,8 @@ 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, data.get("shares", []), diff --git a/dashboard/mining_dashboard/web/views/xvb_views.py b/dashboard/mining_dashboard/web/views/xvb_views.py index b28d6d5bd0..fc3c8849c6 100644 --- a/dashboard/mining_dashboard/web/views/xvb_views.py +++ b/dashboard/mining_dashboard/web/views/xvb_views.py @@ -166,14 +166,16 @@ def build_badges(data, metrics, mode_variant, db_healthy=True, wallet_change=Non if metrics.tari.down: badges.append({"text": "Tari DOWN", "variant": "bad"}) if data.get("workers_rejected"): + pause = data.get("mining_pause") or {} + since = time.strftime("%H:%M UTC", time.gmtime(pause.get("since", 0))) badges.append( { "text": "Workers rejected", "variant": "bad", - "title": "Workers rejected so they fail over to their backup pools", + "title": "Workers rejected so they fail over to their backup pools" + + (f": {pause['reason']} (since {since})" if pause else ""), } ) - # Miner held until required chain(s) finish their initial sync (Issue #35). if data.get("miner_held"): badges.append( { @@ -182,8 +184,6 @@ def build_badges(data, metrics, mode_variant, db_healthy=True, wallet_change=Non "title": "p2pool and xmrig-proxy are held until the required chains finish syncing", } ) - # Fail-closed miner hold on an unrecoverable health failure (Issue #490), opt-in via - # dashboard.fail_closed. Distinct from the sync-gate badge above — this fires post-sync. if data.get("fail_closed_held"): badges.append( { diff --git a/dashboard/mining_dashboard/wizard/server.py b/dashboard/mining_dashboard/wizard/server.py index 3ae1be5493..5d0af57039 100644 --- a/dashboard/mining_dashboard/wizard/server.py +++ b/dashboard/mining_dashboard/wizard/server.py @@ -23,6 +23,7 @@ """ import asyncio +import contextlib import hmac import json import math @@ -100,10 +101,9 @@ def handoff_dir() -> str: def _spool_read(name: str, directory: str | None = None) -> str | None: """Blocking on purpose: single-operator page, tiny local files.""" path = os.path.join(directory or spool_dir(), name) - if not os.path.exists(path): - return None - with open(path) as f: + with contextlib.suppress(FileNotFoundError), open(path, errors="replace") as f: return f.read().strip() + return None def _spool_json(name: str) -> dict: diff --git a/dashboard/mining_dashboard/wizard_config.py b/dashboard/mining_dashboard/wizard_config.py index 9adb15825b..adf53b8cf1 100644 --- a/dashboard/mining_dashboard/wizard_config.py +++ b/dashboard/mining_dashboard/wizard_config.py @@ -12,7 +12,7 @@ _XVB_ALIASES = ("enabled", "url", "donor_id") _XVB_ALIAS_V1_DEFAULTS = {"enabled": True, "url": "na.xmrvsbeast.com:4247", "donor_id": "auto"} -_WORKER_FIELDS = {"name", "host", "port", "control_port", "token", "watts"} +_WORKER_FIELDS = {"name", "host", "port", "control_port", "token", "api_token", "watts"} MACHINE_NAME_RULE = ( "Name this machine: 1–63 lowercase letters, digits or hyphens, starting and ending " diff --git a/dashboard/pyproject.toml b/dashboard/pyproject.toml index d892edf622..fdc6ac2b9a 100644 --- a/dashboard/pyproject.toml +++ b/dashboard/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "mining-dashboard" -version = "2.0.3" +version = "2.0.4" description = "Monitoring dashboard and XvB switching engine for Pithead" readme = "README.md" requires-python = ">=3.11" @@ -38,7 +38,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.6", "pre-commit>=4.6.2"] [tool.setuptools.packages.find] include = ["mining_dashboard*"] 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/diagnostics.test.mjs b/dashboard/tests/browser/diagnostics.test.mjs index dce89b44f2..e81cc4d1b8 100644 --- a/dashboard/tests/browser/diagnostics.test.mjs +++ b/dashboard/tests/browser/diagnostics.test.mjs @@ -89,3 +89,125 @@ test("a failed service-log read displays its reason and can be retried", async ( expect(request.postDataJSON()).toEqual({ container: "tor", lines: 200 }); } }); + +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, + browserName, + ui, + }) => { + const nextKey = browserName === "webkit" && process.platform === "darwin" ? "Alt+Tab" : "Tab"; + await mount(ui); + await page.evaluate( + (t) => document.documentElement.setAttribute("data-theme", t), + theme.toLowerCase(), + ); + await page.locator("summary", { hasText: "Recent log" }).first().click(); + await page.clock.install(); + await page.route("**/api/control/diag-logs", (route) => + route.fulfill({ status: 202, json: { id: "log-1" } }), + ); + await page.route("**/api/control/result?**", (route) => + route.fulfill({ json: { status: "applied", lines: "tor ready" } }), + ); + const run = page.getByRole("button", { name: "Run health check" }); + const show = page.getByRole("button", { name: "Show recent log" }).first(); + const refresh = page.getByRole("button", { name: "Refresh recent log" }); + const heading = page.getByRole("heading", { name: "Service diagnostics" }); + const section = page.locator("h3").first(); + const assertButton = async (control, start, tabs) => { + await expect(control).toHaveCSS("border-top-width", "1px"); + await expect(control).toHaveCSS("border-top-style", "solid"); + await expect(control).toHaveCSS("border-top-left-radius", "6px"); + await start.click(); + for (let n = 0; n < tabs; n++) await page.keyboard.press(nextKey); + await expect(control).toBeFocused(); + await expect(control).toHaveCSS("outline-style", "solid"); + await expect(control).toHaveCSS("outline-width", "2px"); + }; + await assertButton(run, heading, 1); + await expect(run).toHaveClass(/active/); + await assertButton(show, section, 2); + await expect(show).not.toHaveClass(/active/); + await show.click(); + await page.clock.fastForward(2000); + await expect(refresh).toHaveCount(1); + await assertButton(refresh, section, 2); + await expect(refresh).not.toHaveClass(/active/); + await page.evaluate(() => { + for (const b of document.querySelectorAll("button")) b.disabled = true; + }); + for (const control of [run, refresh]) { + await expect(control).toHaveCSS("opacity", "0.5"); + await expect(control).toHaveCSS("cursor", "not-allowed"); + } + }); +} + +test("toggle-group segments stay borderless", async ({ page, ui }) => { + await ui.open(); + const segment = page.getByRole("group", { name: "Dashboard view" }).getByRole("button").first(); + await expect(segment).toHaveCSS("border-top-width", "0px"); +}); 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/browser/onion.test.mjs b/dashboard/tests/browser/onion.test.mjs index 830d264ee1..f0d3147c71 100644 --- a/dashboard/tests/browser/onion.test.mjs +++ b/dashboard/tests/browser/onion.test.mjs @@ -61,7 +61,7 @@ test("a refused client-key request displays the failure and can be retried", asy let attempts = 0; await page.route("**/api/control/onion-client-key", (route) => ++attempts === 1 - ? route.fulfill({ status: 403 }) + ? route.fulfill({ status: 500, body: "control spool is full" }) : route.fulfill({ status: 202, json: { id: "key-retry" } }), ); await page.route("**/api/control/result?id=key-retry", (route) => @@ -70,11 +70,11 @@ test("a refused client-key request displays the failure and can be retried", asy await ui.open(); const reveal = page.getByRole("button", { name: "Show client key", exact: true }); await reveal.click(); - await expect(page.getByText("HTTP 403", { exact: true })).toBeVisible(); + await expect(page.getByText("control spool is full", { exact: true })).toBeVisible(); await expect(reveal).toBeEnabled(); await reveal.click(); await expect(page.getByText("Client authorization is disabled.", { exact: true })).toBeVisible(); - await expect(page.getByText("HTTP 403", { exact: true })).toHaveCount(0); + await expect(page.getByText("control spool is full", { exact: true })).toHaveCount(0); await expect(page.getByRole("heading", { name: "Tor client key" })).toHaveCount(0); expect(attempts).toBe(2); }); 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/browser/support-bundle.test.mjs b/dashboard/tests/browser/support-bundle.test.mjs new file mode 100644 index 0000000000..4f7d7d3f05 --- /dev/null +++ b/dashboard/tests/browser/support-bundle.test.mjs @@ -0,0 +1,159 @@ +import { readFile } from "node:fs/promises"; + +import { manifestZip, readZip } from "../frontend/helpers/zip.mjs"; +import { expect, test } from "./fixtures.mjs"; + +const mount = (ui) => + ui.mount(` +import { SupportBundlePanel } from '/static/system/supportbundle.mjs'; +render(html\`<\${SupportBundlePanel} />\`, document.getElementById('fixture')); +`); + +const ID = "33333333-3333-4333-8333-333333333333"; +const NAME = "support-bundle-20261115T120000Z.zip"; + +async function fakeHost(page, { oldest, outcome }) { + const posts = []; + posts.ranged = 0; + await page.route("**/api/control/support-bundle-range", async (route) => { + posts.ranged++; + await route.fulfill({ status: 202, json: { id: "range-1" } }); + }); + await page.route("**/api/control/support-bundle", async (route) => { + posts.push(route.request().postDataJSON()); + await route.fulfill({ status: 202, json: { id: ID } }); + }); + await page.route("**/api/control/support-bundle-result?**", async (route) => { + const id = new URL(route.request().url()).searchParams.get("id"); + if (id === "range-1") return route.fulfill({ json: { status: "applied", oldest } }); + const body = posts.at(-1); + await route.fulfill({ json: outcome(body) }); + }); + await page.route("**/api/control/support-bundle-download?**", async (route) => { + const { since, until } = posts.at(-1); + await route.fulfill({ + body: manifestZip({ since, until, oldest }), + headers: { + "Content-Type": "application/zip", + "Content-Disposition": `attachment; filename="${NAME}"`, + }, + }); + }); + return posts; +} + +const applied = (body) => ({ + status: "applied", + archive: NAME, + since: body.since, + until: body.until, + effective_since: body.since, + effective_until: body.until, + journal_short: false, +}); + +test("one click on a custom range collects and downloads a zip holding that window", async ({ + page, + ui, +}) => { + const oldest = "2020-01-01T00:00:00Z"; + const posts = await fakeHost(page, { oldest, outcome: applied }); + await mount(ui); + await page.getByLabel("Time frame").selectOption("custom"); + await expect( + page.getByText("Logs on this system reach back to 2020-01-01 00:00:00 UTC"), + ).toBeVisible(); + await page.locator('input[name="since"]').fill("2026-11-15T09:00"); + await page.locator('input[name="until"]').fill("2026-11-15T11:00"); + const download = page.waitForEvent("download"); + await page.getByRole("button", { name: "Export logs" }).click(); + const file = await download; + + expect(file.suggestedFilename()).toMatch(/^support-bundle-\d{8}T\d{6}Z\.zip$/); + const body = posts[0]; + expect(Date.parse(body.since)).toBe(new Date("2026-11-15T09:00").getTime()); + expect(Date.parse(body.until)).toBe(new Date("2026-11-15T11:00").getTime()); + const files = readZip(await readFile(await file.path())); + const manifest = JSON.parse(files["bundle/manifest.json"]); + expect(manifest.window.requested).toEqual({ since: body.since, until: body.until }); + expect(manifest.window.effective).toEqual({ since: body.since, until: body.until }); + expect(files["bundle/journal/all.log"]).toContain("marker"); + await expect(page.getByText("Downloaded")).toBeVisible(); + await expect(page.getByText(NAME).first()).toBeVisible(); +}); + +test("a preset sends its hours and a range past the oldest log is flagged first", async ({ + page, + ui, +}) => { + const oldest = new Date(Date.now() - 3 * 3600 * 1000).toISOString().replace(/\.\d{3}Z$/, "Z"); + const posts = await fakeHost(page, { + oldest, + outcome: (body) => ({ + ...applied({ since: oldest, until: oldest }), + journal_short: !!body.hours, + }), + }); + await mount(ui); + await expect(page.getByText("Pick a time frame to see how far back")).toBeVisible(); + expect(posts.ranged).toBe(0); + await page.getByLabel("Time frame").selectOption("1"); + await expect(page.getByText("Logs on this system reach back to")).toBeVisible(); + await expect(page.getByRole("note")).toHaveCount(0); + await page.getByLabel("Time frame").selectOption("6"); + await expect(page.getByRole("note")).toBeVisible(); + const download = page.waitForEvent("download"); + await page.getByRole("button", { name: "Export logs" }).click(); + await download; + expect(posts[0]).toEqual({ hours: 6 }); + await expect(page.getByText("shorter than you asked")).toBeVisible(); +}); + +test("an invalid range is refused with a clear message and sends nothing", async ({ page, ui }) => { + const posts = await fakeHost(page, { oldest: null, outcome: applied }); + await mount(ui); + await page.getByLabel("Time frame").selectOption("custom"); + await page.locator('input[name="since"]').fill("2026-11-15T11:00"); + await page.locator('input[name="until"]').fill("2026-11-15T09:00"); + await page.getByRole("button", { name: "Export logs" }).click(); + await expect(page.getByRole("alert")).toContainText("the start must be before the end"); + expect(posts.length).toBe(0); +}); + +test("a host rate limit and a failed collect each show their own message", async ({ page, ui }) => { + let mode = "rejected"; + await fakeHost(page, { + oldest: null, + outcome: () => + mode === "rejected" + ? { + status: "rejected", + error: + "a support bundle was collected less than a minute ago — wait for the download window, then retry.", + } + : { + status: "failed", + error: "the host could not collect a support bundle — nothing was written.", + }, + }); + await mount(ui); + const exportButton = page.getByRole("button", { name: "Export logs" }); + await exportButton.click(); + await expect(page.getByRole("alert")).toContainText("less than a minute ago"); + mode = "failed"; + await exportButton.click(); + await expect(page.getByRole("alert")).toContainText("could not collect a support bundle"); +}); + +test("a collected bundle whose download is gone says the download is unavailable", async ({ + page, + ui, +}) => { + await fakeHost(page, { oldest: null, outcome: applied }); + await page.route("**/api/control/support-bundle-download?**", (route) => + route.fulfill({ status: 404, body: "gone" }), + ); + await mount(ui); + await page.getByRole("button", { name: "Export logs" }).click(); + await expect(page.getByRole("alert")).toContainText("download is unavailable (HTTP 404)"); +}); 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/client/test_rig_reply.py b/dashboard/tests/client/test_rig_reply.py new file mode 100644 index 0000000000..c65c59b6eb --- /dev/null +++ b/dashboard/tests/client/test_rig_reply.py @@ -0,0 +1,210 @@ +import json + +import pytest + +from mining_dashboard.client.rig_reply import usable_reply +from mining_dashboard.client.xmrig_client import ( + XMRigWorkerClient, + parse_rigforge, + parse_worker_control_status, +) +from mining_dashboard.service import mining_verdict as mv +from mining_dashboard.service.data_helpers import _merge_direct_stats +from mining_dashboard.service.workers.worker_change_audit import note_revision_drift + +BIG = "9" * 400 +LONG = "v" * 900_000 + +HOSTILE = [ + '{"hashrate": null}', + '{"hashrate": "x"}', + '{"hashrate": {"total": ["a", "b", "c"]}}', + '{"hashrate": {"total": [NaN, Infinity, 1e308]}}', + '{"hashrate": {"total": [true, "5", null]}}', + '{"hashrate": {"total": [1e999, 1.7e308, -1.7e308]}}', + '{"hashrate": {"total": [@, 1, 1]}}'.replace("@", BIG), + '{"uptime": "@"}'.replace("@", BIG), + '{"uptime": @}'.replace("@", BIG), + '{"uptime": Infinity}', + '{"kind": ["proxy"]}', + '{"connection": null}', + '{"connection": {"uptime": "5", "pool": ["x"]}}', + '{"connection": {"uptime": 5, "pool": "h:@"}}'.replace("@", "9" * 5000), + '{"connection": {"uptime": 5, "pool": "host\\u202e:3333"}}', + '{"rigforge": "x"}', + '{"rigforge": [1]}', + '{"rigforge": 5}', + '{"rigforge": {"tune": "x"}}', + '{"rigforge": {"tune": {"autotune": [1]}}}', + '{"rigforge": {"power": "x"}}', + '{"rigforge": {"watchdog": "x"}}', + '{"rigforge": {"health": "x"}}', + '{"rigforge": {"health": {"firmware": [1]}}}', + '{"rigforge": {"version": "@"}}'.replace("@", LONG), + '{"rigforge": {"health": {"governor": "x\\n\\u202eperformance"}}}', + '{"rigforge": {"power": {"watts": "300", "hs_per_watt": "9"}}}', + '{"rigforge": {"power": {"watts": NaN, "hs_per_watt": 1e999}}}', + '{"rigforge": {"watchdog": {"mode": "enabled", "temp_c": "hot", "max_temp_c": true}}}', + '{"rigforge": {"config": "x"}}', + '{"rigforge": {"config": {"DONATION": 1e999, "pools": [{"url": "@"}]}}}'.replace("@", LONG), + '{"rigforge": {"config": {"pools": [{"url": "h\\n:1", "user": "a\\u202eb"}], "x": "a\\tb"}}}', + '{"rigforge": {"config_meta": "x"}}', + '{"rigforge": {"config_meta": {"revision": @}}}'.replace("@", BIG), + '{"rigforge": {"control": "x"}}', + '{"rigforge": {"control": {"change_id": 5, "status": ["applied"]}}}', + '{"rigforge": {"control": {"change_id": "x", "status": "applied", "reason": "@"}}}'.replace( + "@", LONG + ), +] + + +def _row(name): + return { + "name": name, + "ip": "10.0.0.1", + "status": "online", + "h10": 1, + "h60": 2, + "h15": 3, + "uptime": 0, + } + + +def _reply(raw): + reply = usable_reply(json.loads(raw)) + reply["api_ok"], reply["adopted"] = True, False + return reply + + +@pytest.mark.parametrize("raw", HOSTILE, ids=lambda raw: raw[:48]) +async def test_hostile_reply_reaches_no_reader_unchecked(raw): + reply = _reply(raw) + good = {"api_ok": True, "uptime": 50, "hashrate": {"total": [4, 5, 6]}} + + await note_revision_drift(None, {"name": ""}, reply, cap=1, window_sec=60) + parse_worker_control_status(reply) + mv.mining_verdict(reply, ("127.0.0.1",), 3333) + [bad, ok] = _merge_direct_stats([_row("bad"), _row("ok")], [reply, good], "3333") + + assert (ok["telemetry_h10"], ok["telemetry_h60"], ok["telemetry_h15"]) == (4, 5, 6) + assert ok["uptime"] == 50 + assert len(json.dumps(bad, allow_nan=False)) < 20_000 + for key in ("uptime", "telemetry_h10", "telemetry_h60", "telemetry_h15"): + assert type(bad.get(key, 0)) in (int, float), key + assert bad["mining"]["pool"] is None or bad["mining"]["pool"].isprintable() + + +@pytest.mark.parametrize("block", ['"x"', "[1]", "5"]) +async def test_revision_drift_ignores_a_rigforge_block_that_is_not_an_object(block): + raw = json.loads('{"api_ok": true, "rigforge": @}'.replace("@", block)) + await note_revision_drift(None, {"name": "rig"}, raw, cap=1, window_sec=60) + + +def test_wrong_types_are_dropped_and_real_values_kept(): + reply = _reply( + '{"uptime": "9", "rigforge": {"version": 5, "stamp": "@", "power": {"watts": "300"},' + ' "health": {"governor": "performance", "throttling": "no", "firmware": {"board": "B650"}},' + ' "watchdog": {"mode": "enabled", "temp_c": 61, "thermal_hold": false}}}'.replace( + "@", "s" * 200 + ) + ) + assert "uptime" not in reply + block = parse_rigforge(reply) + assert block["version"] is None and block["stamp"] == "s" * 200 + assert block["power"] == {"watts": None, "hs_per_watt": None} + assert block["health"]["governor"] == "performance" and block["health"]["board"] == "B650" + assert block["health"]["throttling"] is None + assert block["watchdog"]["temp_c"] == 61 and block["watchdog"]["thermal_hold"] is False + + +def test_unread_values_are_bounded_and_a_long_reason_is_clipped(): + reply = _reply( + '{"extra": {"n": 1e999, "s": "@"}, "rigforge": {"config": {"DONATION": 1e999},' + ' "control": {"change_id": "c1", "status": "failed", "reason": "#"}}}'.replace( + "@", LONG + ).replace("#", "r" * 900) + ) + assert reply["extra"] == {"n": 0, "s": "v" * 1024} + assert reply["rigforge"]["config"]["DONATION"] == 0 + assert parse_worker_control_status(reply)["reason"] == "r" * 500 + + +def test_reported_rates_above_the_plausible_limit_or_below_zero_are_dropped(): + reply = _reply('{"hashrate": {"total": [1e9, -5, 1234.5]}}') + [row] = _merge_direct_stats([_row("rig")], [reply], "3333") + assert (row["telemetry_h10"], row["telemetry_h60"], row["telemetry_h15"]) == (0, 0, 1234.5) + + +def test_windows_the_miner_has_not_filled_yet_keep_their_place(): + reply = _reply('{"hashrate": {"total": [1234.5, null, null]}}') + [row] = _merge_direct_stats([_row("rig")], [reply], "3333") + assert (row["telemetry_h10"], row["telemetry_h60"], row["telemetry_h15"]) == (1234.5, 0, 0) + + +def test_a_deeply_nested_reply_is_cut_off_without_an_error(): + nested = "x" + for _ in range(900): + nested = [nested] + depth, value = 0, usable_reply({"extra": nested})["extra"] + while isinstance(value, list): + depth, value = depth + 1, value[0] + assert depth == 16 and value is None + + +def test_unlisted_text_with_control_characters_is_dropped(): + reply = _reply('{"extra": "a\\u202eb", "rigforge": {"config": {"pools": [{"url": "h\\n:1"}]}}}') + assert reply["extra"] is None + assert reply["rigforge"]["config"]["pools"] == [{"url": None}] + + +def test_a_control_reason_with_line_breaks_is_kept_on_one_line(): + reply = _reply( + '{"rigforge": {"control": {"change_id": "c", "status": "failed", "reason": "a\\nb"}}}' + ) + assert parse_worker_control_status(reply)["reason"] == "a b" + + +def test_a_large_unlisted_counter_is_kept(): + assert _reply('{"results": {"hashes_total": 4000000000000000000}}')["results"] == { + "hashes_total": 4000000000000000000 + } + + +class _Response: + def __init__(self, status, payload): + self.status, self._raw, self.content = status, json.dumps(payload).encode(), self + + async def read(self, n=-1): + chunk, self._raw = self._raw[:n], self._raw[n:] + return chunk + + +class _Get: + def __init__(self, response): + self._response = response + + async def __aenter__(self): + return self._response + + async def __aexit__(self, *exc): + return False + + +class _Session: + def __init__(self, first, followed=None): + self._first, self._followed = first, followed + + def get(self, url, headers=None, timeout=None, allow_redirects=True): + return _Get(self._followed if allow_redirects and self._followed else self._first) + + +async def test_a_redirect_from_a_rig_is_not_followed(): + followed = _Response(200, {"kind": "internal", "uptime": 777}) + client = XMRigWorkerClient(_Session(_Response(302, {}), followed)) + assert await client.get_stats("10.0.0.1", "rig1") == {"api_ok": False, "adopted": False} + + +async def test_get_stats_returns_the_checked_reply(): + session = _Session(_Response(200, {"uptime": float("inf"), "rigforge": "x", "kind": "proxy"})) + reply = await XMRigWorkerClient(session).get_stats("10.0.0.1", "rig1") + assert reply == {"kind": "proxy", "api_ok": True, "adopted": False} diff --git a/dashboard/tests/client/test_summary_size_cap.py b/dashboard/tests/client/test_summary_size_cap.py index 6242090a7e..c876892637 100644 --- a/dashboard/tests/client/test_summary_size_cap.py +++ b/dashboard/tests/client/test_summary_size_cap.py @@ -67,7 +67,7 @@ class FakeSession: def __init__(self, response): self._response = response - def get(self, url, headers=None, timeout=None): + def get(self, url, headers=None, timeout=None, allow_redirects=True): return FakeGet(self._response) diff --git a/dashboard/tests/client/test_xmrig_client.py b/dashboard/tests/client/test_xmrig_client.py index 077389fbd7..8d26ccb4a9 100644 --- a/dashboard/tests/client/test_xmrig_client.py +++ b/dashboard/tests/client/test_xmrig_client.py @@ -90,7 +90,7 @@ def __init__(self, response=None, exc=None): self._exc = exc self.calls = [] - def get(self, url, headers=None, timeout=None): + def get(self, url, headers=None, timeout=None, allow_redirects=True): self.calls.append((url, headers)) return FakeGet(self._response, self._exc) diff --git a/dashboard/tests/client/test_xvb_client.py b/dashboard/tests/client/test_xvb_client.py index 71790851a2..5f1ae90855 100644 --- a/dashboard/tests/client/test_xvb_client.py +++ b/dashboard/tests/client/test_xvb_client.py @@ -372,3 +372,18 @@ def test_hashrate_units(self): stats = client._parse_html("1hr avg: 2 MH/s\n24hr avg: 1 GH/s") assert stats["avg_1h"] == 2_000_000.0 assert stats["avg_24h"] == 1_000_000_000.0 + + +@pytest.mark.parametrize( + "method", ["get_stats", "get_reward_estimates", "get_recent_wins", "register"] +) +def test_request_errors_never_log_the_wallet(method, caplog): + wallet = "4" + "Z" * 94 + client = XvbClient(wallet, submit_url=_SUBMIT) + error = requests.ConnectionError(f"HTTPSConnectionPool: /?address={wallet}") + with patch.object(xvb_mod, "bounded_get", side_effect=error): + with patch.object(xvb_mod.requests, "post", side_effect=error): + with caplog.at_level("DEBUG"): + getattr(client, method)() + assert "connection error" in caplog.text + assert wallet not in caplog.text diff --git a/dashboard/tests/client/test_xvb_untrusted.py b/dashboard/tests/client/test_xvb_untrusted.py new file mode 100644 index 0000000000..6c3832ff35 --- /dev/null +++ b/dashboard/tests/client/test_xvb_untrusted.py @@ -0,0 +1,89 @@ +from datetime import UTC, datetime, timedelta + +import pytest + +from mining_dashboard.client.xvb_client import XvbClient, parse_winners + +WALLET = "48M2j8GjINNERPARTd8KgGBwa" +ROW = "48M2j8Gj...d8KgGBwa\t{when}\t{rate}\t{height}\t\t{block}\t1/1\t1\tdonor\n" + + +@pytest.mark.parametrize( + "page", + [ + "24hr avg: 5 kH/s", + "1hr avg: " + "9" * 400 + " H/s", + "1hr avg: -5 kH/s", + "1hr avg: . H/s", + "1hr avg: 5.5.5 H/s", + "1hr avg: 1e5 H/s", + "1hr avg: 1.e5 H/s", + "1hr avg: 1..2 H/s", + "1hr avg: 2000 GH/s", + ], +) +def test_a_page_with_no_fail_count_and_no_usable_1h_average_is_no_reading(page): + assert XvbClient("49abc")._parse_html(page) is None + + +@pytest.mark.parametrize( + ("page", "fail_count"), + [ + ("Fail Count: 0\n24hr avg: 5 kH/s", 0), + ("Fail Count: 5", 5), + ("Fail Count: 5\n1hr avg: 999999GH/s", 5), + ("Fail Count: 0\n1hr avg: -5 kH/s", 0), + ("Fail Count: 2 1hr avg: 1.2.3.4 H/s", 2), + ("Fail Count: " + "9" * 400 + "\n1hr avg: . H/s", 1000), + ("Fail Count: 00000000005", 5), + ], +) +def test_a_fail_count_is_kept_when_the_1h_average_is_unusable(page, fail_count): + assert XvbClient("49abc")._parse_html(page) == {"fail_count": fail_count} + + +def test_a_fail_count_above_the_limit_is_clamped_not_rejected(): + stats = XvbClient("49abc")._parse_html("Fail Count: 5000\n1hr avg: 5 kH/s") + assert stats == {"fail_count": 1000, "avg_1h": 5000.0, "avg_24h": 0.0} + + +def test_a_number_that_ends_a_sentence_is_read(): + stats = XvbClient("49abc")._parse_html("Fail Count: 0. 1hr avg: 123.") + assert stats == {"fail_count": 0, "avg_1h": 123.0, "avg_24h": 0.0} + + +def test_a_missing_fail_count_still_reads_as_zero(): + stats = XvbClient("49abc")._parse_html("1hr avg: 5 kH/s.") + assert stats == {"fail_count": 0, "avg_1h": 5000.0, "avg_24h": 0.0} + + +def test_an_unusable_24h_figure_falls_back_to_zero(): + page = "Fail Count: 1\n1hr avg: 5 kH/s\n24hr avg: " + "9" * 400 + " H/s" + assert XvbClient("49abc")._parse_html(page) == { + "fail_count": 1, + "avg_1h": 5000.0, + "avg_24h": 0.0, + } + + +def test_winners_rows_with_an_absurd_height_or_rate_are_bounded(): + when = "2026-07-18 20:41:38" + text = ROW.format(when=when, rate="1kH/s", height="9" * 400, block="blk1") + ROW.format( + when=when, rate="9" * 400 + "H/s", height=5, block="blk2" + ) + assert parse_winners(text, WALLET) == [ + {"ts": 1784407298.0, "hashrate": 0.0, "height": 5, "block_id": "blk2", "tier": "donor"} + ] + + +def test_a_winner_rate_above_the_plausible_limit_reads_as_zero(): + text = ROW.format(when="2026-07-18 20:41:38", rate="2000GH/s", height=5, block="blk") + assert [win["hashrate"] for win in parse_winners(text, WALLET)] == [0.0] + + +def test_winners_rows_dated_in_the_future_are_dropped(): + future = (datetime.now(UTC) + timedelta(days=365)).strftime("%Y-%m-%d %H:%M:%S") + text = ROW.format(when=future, rate="1kH/s", height=1, block="ahead") + ROW.format( + when="2026-07-18 20:41:38", rate="1kH/s", height=2, block="past" + ) + assert [win["block_id"] for win in parse_winners(text, WALLET)] == ["past"] diff --git a/dashboard/tests/collector/test_logs.py b/dashboard/tests/collector/test_logs.py index 93043b2cce..7ffb1e8a55 100644 --- a/dashboard/tests/collector/test_logs.py +++ b/dashboard/tests/collector/test_logs.py @@ -86,6 +86,20 @@ async def test_success(self): out = await logs.fetch_docker_logs("monerod") assert out == ["hello"] + async def test_since_is_sent_to_the_engine(self): + session = MagicMock() + session.get.return_value = _AsyncCM(_FakeResp(200, _frame("hello"))) + with patch.object(logs.aiohttp, "ClientSession", return_value=_AsyncCM(session)): + await logs.fetch_docker_logs("p2pool", tail=5, since=1234.9) + assert session.get.call_args.kwargs["params"]["since"] == 1234 + + async def test_since_is_omitted_by_default(self): + session = MagicMock() + session.get.return_value = _AsyncCM(_FakeResp(200, _frame("hello"))) + with patch.object(logs.aiohttp, "ClientSession", return_value=_AsyncCM(session)): + await logs.fetch_docker_logs("monerod") + assert "since" not in session.get.call_args.kwargs["params"] + async def test_non_200_returns_error(self): session = MagicMock() session.get.return_value = _AsyncCM(_FakeResp(404)) diff --git a/dashboard/tests/collector/test_pools.py b/dashboard/tests/collector/test_pools.py index 7f64f48635..913fd722ad 100644 --- a/dashboard/tests/collector/test_pools.py +++ b/dashboard/tests/collector/test_pools.py @@ -1,5 +1,7 @@ import json -from unittest.mock import patch +from unittest.mock import AsyncMock, patch + +import pytest import mining_dashboard.collector.pools as pools from mining_dashboard.collector.pools import ( @@ -10,12 +12,14 @@ get_tari_stats, ) from mining_dashboard.config.config import ( + NODE_DOWN_AFTER_SEC, P2P_STATS_PATH, POOL_STATS_PATH, SECOND_PER_BLOCK_MAIN, STRATUM_STATS_PATH, ) from mining_dashboard.service.data_helpers import _shares_to_record +from mining_dashboard.service.health.mining_guard import MiningGuard, log_triggers class TestDetectPoolType: @@ -224,3 +228,78 @@ def test_never_read_case_unchanged(self, tmp_path, monkeypatch): assert "pplns_window" not in s["pool"] recorded, baseline = _shares_to_record(None, s["pool"]["shares_found"]) assert (recorded, baseline) == (0, 0) + + +class TestP2PoolLogSignals: + AHEAD = "NOTICE P2PServer peer {} is ahead on mainchain (height {}, your height {}). Is your monerod stuck or lagging?" + + async def _signals(self, lines): + with patch.object(pools, "fetch_docker_logs", AsyncMock(return_value=lines)) as fetch: + signals = await pools.get_p2pool_log_signals(120) + return signals, fetch + + async def test_lag_needs_two_distinct_peers_and_takes_the_smaller_claim(self): + lines = [ + self.AHEAD.format("1.2.3.4:37889", 3500480, 3500000), + "other", + self.AHEAD.format("5.6.7.8:37889", 3500300, 3500000), + self.AHEAD.format("5.6.7.8:37889", 3500010, 3500000), + ] + signals, fetch = await self._signals(lines) + assert signals["lag"] == 300 + wide, recent = fetch.await_args_list + assert wide.args == recent.args == ("p2pool",) + assert 0 < wide.kwargs["since"] < recent.kwargs["since"] + + async def test_one_peer_alone_is_not_enough(self): + lines = [self.AHEAD.format("1.2.3.4:37889", 9999999999, 3500000)] * 5 + assert (await self._signals(lines))[0]["lag"] == 0 + + async def test_oversized_digits_do_not_match(self): + lines = [self.AHEAD.format(p, "9" * 40, 1) for p in ("a:1", "b:1")] + assert (await self._signals(lines))[0]["lag"] == 0 + + async def test_monerod_not_synchronized_line_is_seen(self): + lines = ["WARNING monerod is not synchronized, trying again in 1 second"] + assert (await self._signals(lines))[0] == {"lag": 0, "monerod_unsynced": True} + + async def test_quiet_log_is_a_clean_reading(self): + assert (await self._signals([]))[0] == {"lag": 0, "monerod_unsynced": False} + + async def test_unreadable_logs_are_no_verdict(self): + assert (await self._signals(["Error: Could not retrieve logs (Status 404)"]))[0] is None + + async def test_an_unreadable_recent_window_is_no_verdict(self): + error = ["Error: Connection to Docker Proxy failed."] + with patch.object(pools, "fetch_docker_logs", AsyncMock(side_effect=[["other"], error])): + assert await pools.get_p2pool_log_signals(120) is None + + UNSYNCED = "INFO monerod is not synchronized, trying again in 1 second" + + async def _first_stop(self, warning_times, poll_times): + clock = {"now": 0.0} + + async def fetch(name, tail=None, since=None): + return [self.UNSYNCED for ts in warning_times if since <= ts <= clock["now"]] + + guard = MiningGuard(clock=lambda: clock["now"], wall=lambda: clock["now"]) + with ( + patch.object(pools, "fetch_docker_logs", fetch), + patch.object(pools.time, "time", lambda: clock["now"]), + ): + for now in poll_times: + clock["now"] = float(now) + guard.update(log_triggers(await pools.get_p2pool_log_signals(), None)) + if guard.active: + return now + return None + + @pytest.mark.parametrize("poll_every", [10, 30]) + async def test_an_ended_restart_burst_does_not_stop_the_proxy(self, poll_every): + burst = [1000.0 + i for i in range(12)] + assert await self._first_stop(burst, range(1018, 1400, poll_every)) is None + + async def test_a_monerod_that_stays_unsynced_still_stops_the_proxy(self): + stream = [1000.0 + i for i in range(600)] + stop = await self._first_stop(stream, range(1005, 1400, 10)) + assert stop is not None and stop - 1005 >= NODE_DOWN_AFTER_SEC diff --git a/dashboard/tests/config/test_donation_config.py b/dashboard/tests/config/test_donation_config.py new file mode 100644 index 0000000000..da2a9c7693 --- /dev/null +++ b/dashboard/tests/config/test_donation_config.py @@ -0,0 +1,36 @@ +import importlib +import os +from unittest.mock import patch + + +def _reload_config(): + import mining_dashboard.config.config as cfg + + return importlib.reload(cfg) + + +class TestDonationConfig: + def teardown_method(self): + _reload_config() + + def test_donation_defaults_are_dark(self): + env = {k: v for k, v in os.environ.items() if not k.startswith("DONATION_")} + with patch.dict(os.environ, env, clear=True): + cfg = _reload_config() + assert (cfg.DONATION_ENABLED, cfg.DONATION_PERCENT, cfg.DONATION_TOR_ENABLED) == ( + False, + 0.0, + True, + ) + + def test_donation_env_override(self): + env = { + "DONATION_ENABLED": "true", + "DONATION_PERCENT": "2.5", + "DONATION_TOR_ENABLED": "false", + } + with patch.dict(os.environ, env): + cfg = _reload_config() + assert cfg.DONATION_ENABLED is True + assert cfg.DONATION_PERCENT == 2.5 + assert cfg.DONATION_TOR_ENABLED is False diff --git a/dashboard/tests/conftest.py b/dashboard/tests/conftest.py index fb61a77374..867e0cfcda 100644 --- a/dashboard/tests/conftest.py +++ b/dashboard/tests/conftest.py @@ -1,4 +1,5 @@ import asyncio +import sqlite3 from types import SimpleNamespace import pytest @@ -47,3 +48,36 @@ async def yield_poll(_delay): monkeypatch.setattr( "mining_dashboard.service.control_service.asyncio", SimpleNamespace(sleep=yield_poll) ) + + +@pytest.fixture +def full_disk(monkeypatch): + def make(store, statements=("INSERT", "UPDATE", "DELETE", "CREATE"), message=None): + if isinstance(statements, str): + statements = (statements,) + inner = store._conn + + class FullDiskConnection: + def execute(self, sql, *args, **kwargs): + if sql.lstrip().upper().startswith(tuple(statements)): + if message: + raise sqlite3.DatabaseError(message) + raise sqlite3.OperationalError("database or disk is full") + return inner.execute(sql, *args, **kwargs) + + def cursor(self): + return inner.cursor() + + def close(self): + return inner.close() + + def __enter__(self): + inner.__enter__() + return self + + def __exit__(self, *exc): + return inner.__exit__(*exc) + + monkeypatch.setattr(store, "_conn", FullDiskConnection()) + + return make 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, /