diff --git a/.github/workflows/node-status-test.yml b/.github/workflows/node-status-test.yml new file mode 100644 index 0000000..9cba186 --- /dev/null +++ b/.github/workflows/node-status-test.yml @@ -0,0 +1,27 @@ +name: Node status test + +on: + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/checkout@v4 + with: + repository: dappnode/staker-package-scripts + ref: v0.1.3 + path: staker-package-scripts + - name: Test under dash (the shell of the Debian image) + run: sh test/node_status_test.sh + env: + NODE_STATUS_TOOLS: ${{ github.workspace }}/staker-package-scripts/scripts/node_status_tools.sh + - name: Test under dash with the jq of the image (Debian trixie) + run: > + docker run --rm -v "$PWD:/work" -w /work debian:trixie-slim sh -c + "apt-get update -qq && apt-get install -y -qq --no-install-recommends jq >/dev/null && + NODE_STATUS_TOOLS=/work/staker-package-scripts/scripts/node_status_tools.sh sh test/node_status_test.sh" diff --git a/README.md b/README.md index 6a00b62..224ac7e 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,10 @@ by default BTC_TXINDEX is 0, but the installation of the DAppNodePackage will se value larger than 550 (550Mb) , for example BTC_PRUNE=30000 to maintain only 30Gb of full blockchain data. ``` +## Node status report + +The package reports Bitcoin Core's sync status (start-up, header and block download, catching up, index building and assumeutxo background validation) through its Docker healthcheck, which the dappmanager reads to show the node's status. The healthcheck script is [`src/node-status.sh`](src/node-status.sh), installed in the image as `/usr/local/bin/node-status`; it calls the RPC on `127.0.0.1` with the `BTC_RPCUSER` / `BTC_RPCPASSWORD` credentials and uses the shared helpers from `dappnode/staker-package-scripts`. Its test is [`test/node_status_test.sh`](test/node_status_test.sh): run `sh test/node_status_test.sh` with a clone of `staker-package-scripts` next to this repository, or point `NODE_STATUS_TOOLS` at its `scripts/node_status_tools.sh`. + ## License This project is licensed under the GNU General Public License v3.0 - see the [LICENSE](LICENSE) file for details diff --git a/dappnode_package.json b/dappnode_package.json index d08342f..84bb6f6 100644 --- a/dappnode_package.json +++ b/dappnode_package.json @@ -27,6 +27,17 @@ "homepage": "https://github.com/dappnode/DAppNodePackage-bitcoin#readme" }, "name": "bitcoin.dnp.dappnode.eth", + "nodes": { + "bitcoin.dnp.dappnode.eth": { + "role": "node", + "network": "bitcoin", + "probe": { + "kind": "status-report", + "maxHeadAgeSeconds": 7200 + }, + "report": "healthcheck" + } + }, "repository": { "type": "git", "url": "https://github.com/dappnode/DAppNodePackage-bitcoin.git" diff --git a/docker-compose.yml b/docker-compose.yml index 7d744e2..8c162a4 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -20,5 +20,11 @@ services: - BTC_RPCALLOWIP=172.33.0.0/16 - P2P_PORT=8340 restart: always + healthcheck: + test: ["CMD", "/usr/local/bin/node-status"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 60s volumes: bitcoin_data: {} diff --git a/src/Dockerfile b/src/Dockerfile index 9c1dfca..240a86b 100644 --- a/src/Dockerfile +++ b/src/Dockerfile @@ -35,6 +35,15 @@ EXPOSE 8332 8333 18332 18333 28332 28333 COPY --from=binary /bitcoin/bin/bitcoind /usr/local/bin/ +# Node status report printed by the healthcheck, with the shared helpers of dappnode/staker-package-scripts +ARG STAKER_SCRIPTS_VERSION=v0.1.3 +ADD https://github.com/dappnode/staker-package-scripts/releases/download/${STAKER_SCRIPTS_VERSION}/node_status_tools.sh /etc/profile.d/node_status_tools.sh +COPY node-status.sh /usr/local/bin/node-status + +RUN apt-get update && apt-get install -y --no-install-recommends curl jq && \ + rm -rf /var/lib/apt/lists/* && \ + chmod 0755 /usr/local/bin/node-status /etc/profile.d/node_status_tools.sh + ADD ./docker_entrypoint.sh /usr/local/bin/docker_entrypoint.sh RUN chmod a+x /usr/local/bin/docker_entrypoint.sh diff --git a/src/node-status.sh b/src/node-status.sh new file mode 100755 index 0000000..4d86c64 --- /dev/null +++ b/src/node-status.sh @@ -0,0 +1,211 @@ +#!/bin/sh + +# Node status report of the Bitcoin package, run as the Docker healthcheck. +# Prints one JSON line (see the node status contract) telling whether Bitcoin +# Core is synced, which sync phase it is in and how far along. The package +# declares the node with the "status-report" probe, so the state printed here +# is the verdict the dappmanager shows. +# +# Bitcoin Core, as of v32.1: +# - The JSON-RPC needs the credentials the entrypoint writes to bitcoin.conf +# from BTC_RPCUSER and BTC_RPCPASSWORD (no cookie file is written when a +# password is set). They reach curl through its stdin, never its arguments. +# - Until the block index is loaded and the latest blocks are verified, every +# call fails with error -28 (RPC_IN_WARMUP) and a message saying what it does. +# - Initial block download fetches the headers first: blocks stay at 0 while +# the headers are pre-synchronised and downloaded. Then the blocks, whose +# progress verificationprogress estimates by transaction count. +# - initialblockdownload turns false once the tip is less than a day old and +# stays false until a restart, so a node that falls behind later is caught by +# the age of its tip and by the headers it knows ahead of it. +# - Work that goes on at the head: an index (txindex, enabled by this package, +# or one the user adds) building after being turned on, and the background +# validation of an assumeutxo snapshot (backgroundvalidation, v32+). +# +# Environment: +# NODE_STATUS_TOOLS: Path of the shared helpers (default /etc/profile.d/node_status_tools.sh) +# BTC_RPCUSER, BTC_RPCPASSWORD, BTC_RPCPORT: Read by the entrypoint too (defaults dappnode, dappnode, 8332) +# NS_TIMEOUT: Timeout in seconds of the single request (default 5) + +# A single request, so it can wait a little longer than the helpers' default +# while Bitcoin Core holds its main lock to connect a block or flush its cache +NS_TIMEOUT=${NS_TIMEOUT:-5} + +# shellcheck source=/dev/null +. "${NODE_STATUS_TOOLS:-/etc/profile.d/node_status_tools.sh}" || exit 1 + +# Same value as probe.maxHeadAgeSeconds in dappnode_package.json: blocks come +# every 10 minutes on average, gaps of more than 2 hours are very rare +MAX_HEAD_AGE=7200 +# Headers known ahead of the tip that still count as at the head: about an hour +MAX_BLOCKS_BEHIND=6 + +RPC_URL="http://127.0.0.1:${BTC_RPCPORT:-8332}/" +REQUEST='[{"jsonrpc":"2.0","id":"chain","method":"getblockchaininfo"},'\ +'{"jsonrpc":"2.0","id":"net","method":"getnetworkinfo"},'\ +'{"jsonrpc":"2.0","id":"index","method":"getindexinfo"}]' + +# Escape a value for a double-quoted string of a curl config file +curl_quote() { + printf '%s' "$1" | sed 's/[\\"]/\\&/g' +} + +# Send the batch request and print the body followed by the HTTP status on its +# own line. The credentials go to curl as a config file on stdin (printf is a +# shell builtin), so they never show in the process list. Returns curl's exit code. +rpc_batch() { + printf 'user = "%s:%s"\n' "$(curl_quote "${BTC_RPCUSER:-dappnode}")" \ + "$(curl_quote "${BTC_RPCPASSWORD:-dappnode}")" | + curl -sg -K - --noproxy '*' --proto '=http' \ + --max-time "$NS_TIMEOUT" --connect-timeout "$NS_TIMEOUT" \ + -H 'Content-Type: application/json' --data "$REQUEST" \ + -w '\n%{http_code}' "$RPC_URL" +} + +# Print the result (compact JSON) or the error of the reply with id $1 +reply_field() { + printf '%s\n' "$body" | jq -c --arg id "$1" --arg f "$2" \ + 'first(.[] | select(type == "object" and .id == $id)) | .[$f] // empty' 2>/dev/null +} + +# Print the integer value of $1 in the getblockchaininfo result, nothing when absent +chain_int() { + ns_json_get "$chain" ".$1 | select(type == \"number\") | floor" +} + +set -- + +reply=$(rpc_batch) +rc=$? +if [ "$rc" -eq 28 ]; then + # Bitcoin Core accepts connections but does not answer in time: busy, nothing to tell + echo "[ERROR - node-status] Bitcoin Core did not answer within ${NS_TIMEOUT}s" >&2 + exit 1 +fi +if [ "$rc" -ne 0 ]; then + # Nothing listens on the RPC port yet: the node is starting + ns_emit starting + exit $? +fi + +status=${reply##*[!0-9]} +body=${reply%"$status"} +case $status in +200) ;; +401) + ns_emit error issue="Bitcoin Core rejected the RPC credentials" + exit $? + ;; +*) + # 503 when the RPC work queue is full, anything else is unexpected + echo "[ERROR - node-status] Bitcoin Core answered with HTTP status ${status:-none}" >&2 + exit 1 + ;; +esac + +chain=$(reply_field chain result) +if [ -z "$chain" ]; then + error=$(reply_field chain error) + if [ "$(ns_json_get "$error" .code)" = "-28" ]; then + # Warming up; the message says what it does, e.g. "Loading block index…" + phase=$(ns_json_get "$error" '.message | strings | sub("(…|[.])+$"; "") + | select(test("^[A-Za-z][A-Za-z0-9 ,/()-]{0,59}$"))') + ns_emit starting phase="$phase" + exit $? + fi + code=$(ns_json_get "$error" .code) + echo "[ERROR - node-status] getblockchaininfo failed: ${code:-no result}" >&2 + exit 1 +fi + +# Issues Bitcoin Core reports about itself (an array since v28, a string with +# -deprecatedrpc=warnings) +warnings=$(ns_json_get "$chain" '.warnings | if type == "string" then [.] else . end + | .[] | strings | gsub("[[:cntrl:]]+"; " ") | select(test("[^ ]"))') +while IFS= read -r warning; do + [ -n "$warning" ] && set -- "$@" "issue=$warning" +done <&2 + exit 1 +fi +[ -n "$headers" ] && [ "$headers" -lt 0 ] && headers="" +ahead=0 +[ -n "$headers" ] && [ "$headers" -gt "$blocks" ] && ahead=$((headers - blocks)) +age=$(($(date +%s) - head_time)) + +# Work going on next to the sync, most important first +background="" +snapshot=$(ns_json_get "$chain" '.backgroundvalidation | objects') +if [ -n "$snapshot" ]; then + background="Validating UTXO snapshot" + percent=$(ns_json_get "$snapshot" '.verificationprogress | numbers | [. * 1000 | floor / 10, 99.9] | min | tostring + "%"') + [ -n "$percent" ] && set -- "$@" "detail=Snapshot validated:$percent" +fi +indexes=$(ns_json_get "$(reply_field index result)" 'to_entries[] + | select(.value | type == "object" and .synced == false) | "\(.key):\(.value.best_block_height // 0)"') +if [ -n "$indexes" ]; then + count=0 + while IFS=: read -r name height; do + count=$((count + 1)) + case $name in + txindex) job="transaction index" ;; + coinstatsindex) job="coin statistics index" ;; + txospenderindex) job="spent outputs index" ;; + *"block filter index") job="block filter index" ;; + *) job="index" ;; + esac + set -- "$@" "detail=Building $job:at block $height" + done <&2 + exit 1 +fi +SCRIPT=$REPO/src/node-status.sh + +PASS=0 +FAIL=0 +TMP=$(mktemp -d) || exit 1 +trap 'rm -rf "$TMP"' EXIT + +# check +check() { + if [ "$2" = "$3" ]; then + PASS=$((PASS + 1)) + else + FAIL=$((FAIL + 1)) + printf 'FAIL: %s\n expected: %s\n actual: %s\n' "$1" "$2" "$3" + fi +} + +NOW=1764500000 + +# shellcheck disable=SC2329 # called by the script under test +date() { + echo "$NOW" +} + +# Reply entry of the batch for id $1: nothing when $2 is empty, a warm-up +# error for "warmup:", a generic error for "error", else the result $2 +reply_entry() { + case $2 in + "") ;; + warmup:*) jq -cn --arg id "$1" --arg m "${2#warmup:}" '{jsonrpc: "2.0", id: $id, error: {code: -28, message: $m}}' ;; + error) jq -cn --arg id "$1" '{jsonrpc: "2.0", id: $id, error: {code: -1, message: "boom"}}' ;; + *) jq -cn --arg id "$1" --argjson r "$2" '{jsonrpc: "2.0", id: $id, result: $r}' ;; + esac +} + +# Stub curl: records its arguments, URL, timeout and the config it reads on +# stdin, then exits with R_RC when set (7 refused, 28 timeout) or prints the +# batch reply built from R_CHAIN, R_NET and R_INDEX (or R_BODY verbatim) +# followed by the HTTP status R_HTTP, as -w '\n%{http_code}' does. +# shellcheck disable=SC2329 # called by the script under test +curl() { + echo call >>"$TMP/calls" + printf '%s\n' "$*" >>"$TMP/args" + _prev="" _url="" + for _arg in "$@"; do + [ "$_prev" = "--max-time" ] && printf '%s\n' "$_arg" >>"$TMP/timeouts" + [ "$_prev" = "-K" ] && [ "$_arg" = "-" ] && cat >>"$TMP/config" + _prev=$_arg + _url=$_arg + done + printf '%s\n' "$_url" >>"$TMP/urls" + if [ -n "$R_RC" ]; then + printf '\n000' + return "$R_RC" + fi + if [ -n "$R_BODY" ]; then + printf '%s' "$R_BODY" + elif [ "$R_HTTP" = 200 ]; then + { + reply_entry chain "$R_CHAIN" + reply_entry net "$R_NET" + reply_entry index "$R_INDEX" + } | jq -cs . + fi + printf '\n%s' "$R_HTTP" +} + +# getblockchaininfo result: chain_info