From c57972f5ffd4a3349e1bc08847d22603e2624106 Mon Sep 17 00:00:00 2001 From: 3alpha <15694175+3alpha@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:26:38 +0100 Subject: [PATCH] feat(near): report the sync status through the healthcheck The healthcheck prints a status report that says whether the node is synced and what it is doing, declared in the manifest `nodes` field with the status-report probe. --- .github/workflows/node-status-test.yml | 28 ++ README.md | 7 + dappnode_package.json | 11 + docker-compose.yml | 6 + neard_image/Dockerfile | 3 + neard_image/node-status.sh | 184 ++++++++++++ neard_image/start_near.sh | 24 ++ test/node_status_test.sh | 390 +++++++++++++++++++++++++ 8 files changed, 653 insertions(+) create mode 100644 .github/workflows/node-status-test.yml create mode 100644 README.md create mode 100644 neard_image/node-status.sh create mode 100644 test/node_status_test.sh diff --git a/.github/workflows/node-status-test.yml b/.github/workflows/node-status-test.yml new file mode 100644 index 0000000..c9fb964 --- /dev/null +++ b/.github/workflows/node-status-test.yml @@ -0,0 +1,28 @@ +name: Node status test + +on: + pull_request: + +permissions: + contents: read + +jobs: + node-status: + 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 with dash + run: NODE_STATUS_TOOLS=staker-package-scripts/scripts/node_status_tools.sh sh test/node_status_test.sh + + - name: Test with the shell of the image (dash on Ubuntu 22.04, like nearprotocol/nearcore) + run: > + docker run --rm -v "$PWD:/work" -w /work ubuntu:22.04 sh -c + "apt-get update -qq && apt-get install -y -qq jq >/dev/null && + NODE_STATUS_TOOLS=staker-package-scripts/scripts/node_status_tools.sh sh test/node_status_test.sh" diff --git a/README.md b/README.md new file mode 100644 index 0000000..4d57453 --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ +# DAppNode Package NEAR + +DAppNode package of a NEAR node ([nearcore](https://github.com/near/nearcore) `neard`). + +## Node status report + +The package reports the sync status of `neard` (initializing, snapshot download, epoch, header, state and block sync, and whether it is synced with a recent latest block) through the Docker healthcheck of the `near` service, which the Dappnode dashboard reads. The script is [`neard_image/node-status.sh`](neard_image/node-status.sh), installed as `/usr/local/bin/node-status`; its tests are in [`test/node_status_test.sh`](test/node_status_test.sh) (`sh test/node_status_test.sh`, with `dappnode/staker-package-scripts` checked out next to this repository). diff --git a/dappnode_package.json b/dappnode_package.json index 7de53a7..a7d4ccb 100644 --- a/dappnode_package.json +++ b/dappnode_package.json @@ -40,6 +40,17 @@ }, "mainService": "near", "name": "near.dnp.dappnode.eth", + "nodes": { + "near": { + "role": "node", + "network": "near", + "probe": { + "kind": "status-report", + "maxHeadAgeSeconds": 120 + }, + "report": "healthcheck" + } + }, "repository": { "type": "git", "url": "https://github.com/dappnode/DAppNodePackage-NEAR.git" diff --git a/docker-compose.yml b/docker-compose.yml index b92a37f..f507dca 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,6 +9,12 @@ services: volumes: - near:/srv/near restart: unless-stopped + healthcheck: + test: ["CMD", "/usr/local/bin/node-status"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 60s ports: - 24567:24567/tcp - 24567:24567/udp diff --git a/neard_image/Dockerfile b/neard_image/Dockerfile index 123af20..8bf3643 100644 --- a/neard_image/Dockerfile +++ b/neard_image/Dockerfile @@ -17,6 +17,9 @@ RUN apt-get update && DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN RUN curl https://rclone.org/install.sh | bash COPY start_near.sh /usr/local/bin/ +COPY node-status.sh /usr/local/bin/node-status +ADD https://github.com/dappnode/staker-package-scripts/releases/download/v0.1.3/node_status_tools.sh /etc/profile.d/node_status_tools.sh +RUN chmod 755 /usr/local/bin/node-status && chmod 644 /etc/profile.d/node_status_tools.sh # COPY start_api.sh /usr/local/bin/ # COPY nginx.conf /etc/nginx/ COPY supervisord.conf /etc/supervisord/ diff --git a/neard_image/node-status.sh b/neard_image/node-status.sh new file mode 100644 index 0000000..4d2f28a --- /dev/null +++ b/neard_image/node-status.sh @@ -0,0 +1,184 @@ +#!/bin/sh + +# Node status report of the NEAR package, run as the Docker healthcheck of the near service. +# Prints one JSON line (see node_status_tools.sh in dappnode/staker-package-scripts): whether +# neard is synced, how far its sync has come and what it is doing, from its JSON-RPC and +# Prometheus metrics on port 3030 and from the marker start_near.sh leaves while it initializes +# the node or downloads a snapshot. The state is the verdict: synced only when neard says it is +# not syncing AND its latest block is recent. +# +# Environment: +# NODE_STATUS_TOOLS: Helper library to source (default /etc/profile.d/node_status_tools.sh) +# NODE_STATUS_DIR: Directory of the pre-start marker (default /tmp/node-status) + +# Every call gets 2 s, so even a node that stops answering midway stays well inside the 10 s timeout +NS_TIMEOUT=${NS_TIMEOUT:-2} +# shellcheck disable=SC2034 # read by ns_rpc in the helper library +NS_RPC_PORT=3030 + +# shellcheck source=/dev/null +. "${NODE_STATUS_TOOLS:-/etc/profile.d/node_status_tools.sh}" || exit 1 + +PRE_START_MARKER="${NODE_STATUS_DIR:-/tmp/node-status}/pre-start" +METRICS_URL=http://127.0.0.1:3030/metrics + +# Oldest latest block a synced node may have, in seconds. Same value as maxHeadAgeSeconds in +# dappnode_package.json. NEAR makes a block about every 0.6 s; neard's own /health fails after +# 20 s without one (10 x max_block_production_delay). +MAX_HEAD_AGE_SECONDS=120 + +# The JSON-RPC does not answer: neard is opening its database, or start_near.sh is still +# initializing the node or downloading a snapshot. The marker counts only while the +# start_near.sh process it names runs (it becomes neard when it execs it), so a marker left by a +# stopped container never makes a starting node look busy. +report_starting() { + pid="" + phase="" + progress="" + if [ -f "$PRE_START_MARKER" ]; then + while IFS='=' read -r key value; do + case $key in + pid) pid=$value ;; + phase) phase=$value ;; + progress) progress=$value ;; + esac + done <"$PRE_START_MARKER" + case $pid in + '' | *[!0-9]*) phase="" ;; + *) grep -qa start_near "/proc/$pid/cmdline" 2>/dev/null || phase="" ;; + esac + fi + if [ -n "$phase" ]; then + ns_emit starting phase="$phase" progress="$progress" + else + ns_emit starting + fi +} + +# Reads the status result on stdin and prints key=value lines: syncing, height, headTime (unix +# seconds of latest_block_time, RFC 3339 with nanoseconds), fresh (latest block at most +# MAX_HEAD_AGE_SECONDS old), account (validator account, when a validator key is loaded) and +# version. +read_status() { + jq -r --argjson max "$MAX_HEAD_AGE_SECONDS" ' + def line: tostring | gsub("[\r\n]"; " "); + (.sync_info // {}) as $sync + | ($sync.latest_block_time + | if type == "string" then (sub("[.][0-9]+"; "") | try fromdateiso8601 catch null) else null end + | if type == "number" then floor else null end) as $time + | "syncing=\($sync.syncing | line)", + "height=\($sync.latest_block_height // "" | line)", + "headTime=\($time // "")", + "fresh=\($time != null and now - $time <= $max)", + "account=\(.validator_account_id // "" | line)", + "version=\(.version.version // "" | line)" + ' 2>/dev/null +} + +# Reads Prometheus text on stdin and prints the state sync stage of the shards as +# "::". near_state_sync_stage is ShardSyncStatus::repr() per shard: +# 0 header, 1 parts, 2 apply scheduling, 3 apply in progress, 4 apply finalizing, 5 done. +state_sync_stages() { + jq -nRr ' + [inputs | capture("^near_state_sync_stage[{][^}]*[}][ \t]+(?[0-9]+)") | .v | tonumber] as $stages + | (if any($stages[]; . < 2) or $stages == [] then "Downloading state" else "Applying state" end) + + ":\([$stages[] | select(. == 5)] | length):\($stages | length)" + ' 2>/dev/null +} + +if ! status=$(ns_rpc status); then + report_starting + exit $? +fi + +syncing="" +height="" +headTime="" +fresh=false +account="" +version="" +while IFS='=' read -r key value; do + case $key in + syncing) syncing=$value ;; + height) height=$value ;; + headTime) headTime=$value ;; + fresh) fresh=$value ;; + account) account=$value ;; + version) version=$value ;; + esac +done </dev/null && target=$header_head ;; +esac + +case $code in +1) + set -- phase="Waiting for peers" "$@" + ;; +2) + set -- phase="Downloading epoch sync proof" "$@" + ;; +4) + set -- phase="Downloading block headers" position="$header_head" "$@" + ;; +5) + stages=$(printf '%s\n' "$metrics" | state_sync_stages) + set -- phase="${stages%%:*}" "$@" + shards=${stages#*:} + case $shards in + *:0 | '') ;; + *) set -- "$@" detail="Shards synced:${shards%%:*} of ${shards#*:}" ;; + esac + ;; +7) + set -- phase="Downloading blocks" position="$height" target="$target" "$@" + ;; +*) + # Not reported yet (the gauge is refreshed every 10 s) or a code this script does not know + set -- phase="Catching up" "$@" + [ -n "$target" ] && set -- "$@" position="$height" target="$target" + ;; +esac + +ns_emit syncing peers="$peers" "$@" +exit $? diff --git a/neard_image/start_near.sh b/neard_image/start_near.sh index 9c41fa7..eb2c25f 100755 --- a/neard_image/start_near.sh +++ b/neard_image/start_near.sh @@ -6,14 +6,38 @@ FULL_ACCOUNT_ID="$ACCOUNT_ID.$STAKING_CONTRACT_NAME" NEARD_FLAGS=${NEAR_HOME:+--home="$NEAR_HOME"} mkdir -p $NEAR_HOME/data +# Read by the healthcheck (node-status) to report the work done here before neard serves its RPC +NODE_STATUS_DIR=/tmp/node-status +PRE_START_MARKER="${NODE_STATUS_DIR}/pre-start" + +# A marker left by a container that was stopped mid-step must not outlive that run +rm -f "${PRE_START_MARKER}" "${PRE_START_MARKER}.tmp" + +# Records the step this script runs, atomically. The PID of this script vouches for the marker: +# the healthcheck ignores it once this process is gone or has become neard. +# Arguments: phase +mark_pre_start() { + mkdir -p "${NODE_STATUS_DIR}" && + printf 'pid=%s\nphase=%s\nprogress=\n' "$$" "$1" >"${PRE_START_MARKER}.tmp" && + mv -f "${PRE_START_MARKER}.tmp" "${PRE_START_MARKER}" +} + +clear_pre_start() { + rm -f "${PRE_START_MARKER}" "${PRE_START_MARKER}.tmp" +} + if [ ! -f ${NEAR_HOME}/node_key.json ]; then echo "Initializing node, this can take a while..." cmd="neard $NEARD_FLAGS init --chain-id=${CHAIN_ID} ${FULL_ACCOUNT_ID:+--account-id=$FULL_ACCOUNT_ID} --download-genesis --download-config $CONFIG_TYPE" + mark_pre_start "Initializing node" $cmd + clear_pre_start fi if [ "$DOWNLOAD_SNAPSHOT" = "true" ] && [ ! -f "${NEAR_HOME}/data/CURRENT" ]; then + mark_pre_start "Downloading snapshot" curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/fastnear/static/refs/heads/main/down_rclone.sh \ | THREADS=16 DATA_PATH="$NEAR_HOME/data" CHAIN_ID="$CHAIN_ID" RPC_TYPE="fast-rpc" bash + clear_pre_start fi if [ -n "$ACCOUNT_ID" ] && [ -n "$VALIDATOR_PUBLIC_KEY" ] && [ -n "$VALIDATOR_SECRET_KEY" ] diff --git a/test/node_status_test.sh b/test/node_status_test.sh new file mode 100644 index 0000000..f2e0be6 --- /dev/null +++ b/test/node_status_test.sh @@ -0,0 +1,390 @@ +#!/bin/sh + +# Tests for neard_image/node-status.sh (the healthcheck status report) and for the pre-start +# marker written by neard_image/start_near.sh. +# Run from anywhere with any POSIX sh: sh test/node_status_test.sh +# Needs jq, bash (start_near.sh is a bash script) and the helper library of +# dappnode/staker-package-scripts, by default checked out next to this repository (override with +# NODE_STATUS_TOOLS=). neard is stubbed by a curl function. + +cd "$(dirname "$0")/.." || exit 1 +NODE_STATUS_TOOLS=${NODE_STATUS_TOOLS:-../staker-package-scripts/scripts/node_status_tools.sh} +if [ ! -f "$NODE_STATUS_TOOLS" ]; then + echo "Helper library not found: $NODE_STATUS_TOOLS (set NODE_STATUS_TOOLS)" >&2 + exit 1 +fi +NODE_STATUS_TOOLS=$(cd "$(dirname "$NODE_STATUS_TOOLS")" && pwd)/$(basename "$NODE_STATUS_TOOLS") +export NODE_STATUS_TOOLS +SCRIPT=$PWD/neard_image/node-status.sh +ENTRYPOINT=$PWD/neard_image/start_near.sh + +PASS=0 +FAIL=0 +TMP=$(mktemp -d) || exit 1 +NODE_STATUS_DIR="$TMP/status" +export NODE_STATUS_DIR +mkdir -p "$NODE_STATUS_DIR" +HELPER_PIDS="" +# shellcheck disable=SC2329 # called by the EXIT trap +cleanup() { + for pid in $HELPER_PIDS; do kill "$pid" 2>/dev/null; done + rm -rf "$TMP" +} +trap cleanup 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 +} + +# Stubbed neard. STUB_STATUS and STUB_NETWORK: JSON results of status and network_info; empty +# refuses the connection, "error" answers with a JSON-RPC error. STUB_METRICS: body of /metrics, +# which refuses connections when unset. Each call is logged to $TMP/calls as +# " max-time=". +# shellcheck disable=SC2329 # called by the library under test +curl() { + _url="" + _data="" + _max_time="" + while [ $# -gt 0 ]; do + case $1 in + --data) _data=$2 && shift ;; + --max-time) _max_time=$2 && shift ;; + http://*) _url=$1 ;; + esac + shift + done + _method="" + [ -n "$_data" ] && _method=$(printf '%s' "$_data" | jq -r .method) + echo "$_url $_method max-time=$_max_time" >>"$TMP/calls" + case $_url in + */metrics) + [ -n "${STUB_METRICS+set}" ] || return 7 + printf '%s' "$STUB_METRICS" + return 0 + ;; + esac + case $_method in + status) _result=$STUB_STATUS ;; + network_info) _result=$STUB_NETWORK ;; + *) _result="" ;; + esac + case $_result in + "") return 7 ;; + error) printf '{"jsonrpc":"2.0","id":1,"error":{"name":"INTERNAL_ERROR","code":-32000,"message":"Server error"}}' ;; + *) printf '{"jsonrpc":"2.0","id":1,"result":%s}' "$_result" ;; + esac +} + +# Runs the healthcheck script with the stubbed curl: sets OUT (stdout), RC, LINES and CALLS +run_status() { + : >"$TMP/calls" + # shellcheck disable=SC1090 + OUT=$(. "$SCRIPT" 2>"$TMP/stderr") + RC=$? + LINES=$(printf '%s\n' "$OUT" | grep -c .) + CALLS=$(sed 's/ max-time=2$//' "$TMP/calls" | paste -s -d, -) +} + +# report_errors : prints what in the report breaks the status report contract, comma +# separated, or nothing when it follows it +report_errors() { + printf '%s\n' "$1" | jq -r ' + def int: type == "number" and . == floor and . >= 0; + def short($n): type == "string" and length > 0 and length <= $n; + [ + (if .version != 1 then "version" else empty end), + (if (.state | IN("starting", "syncing", "synced", "error")) | not then "state" else empty end), + (keys - ["version", "state", "phase", "progress", "height", "headTime", "position", "target", + "unit", "peers", "awaitingTarget", "background", "issues", "details"] | .[] | "unknown key \(.)"), + (if has("phase") and ((.phase | short(60) | not) or (.phase | endswith("."))) then "phase" else empty end), + (if has("progress") and ((.progress | type) != "number" or .progress < 0 or .progress > 100 + or (.state != "synced" and .progress > 99.9)) then "progress" else empty end), + (["height", "headTime", "position", "target", "peers"][] as $k + | if has($k) and (.[$k] | int | not) then $k else empty end), + (if has("awaitingTarget") and .awaitingTarget != true then "awaitingTarget" else empty end), + (if has("background") and (.background | short(60) | not) then "background" else empty end), + (if has("issues") and ((.issues | type) != "array" or (.issues | length) > 5 + or any(.issues[]; short(120) | not)) then "issues" else empty end), + (if has("details") and ((.details | type) != "array" or (.details | length) > 8 + or any(.details[]; (.label | short(40) | not) or (.value | short(120) | not))) then "details" else empty end), + (if has("progress") and (has("position") or has("target")) then "progress with position" else empty end), + (if (tojson | utf8bytelength) > 2048 then "size" else empty end) + ] | join(", ")' 2>/dev/null || echo "not JSON" +} + +# Fails unless OUT is one JSON object that follows the status report contract, the script printed +# nothing on stderr, called only local addresses with 2 s timeouts and exited 0 +validate() { + _errors=$(report_errors "$OUT") + check "$1: one line" 1 "$LINES" + check "$1: follows the contract" "" "$_errors" + check "$1: exit code" 0 "$RC" + check "$1: nothing on stderr" "" "$(cat "$TMP/stderr")" + check "$1: only local calls with 2 s timeouts" "" "$(grep -v '^http://127\.0\.0\.1:3030[/ ].* max-time=2$' "$TMP/calls")" +} + +# expect +expect() { + run_status + validate "$1" + check "$1: report" "$2" "$OUT" + check "$1: calls" "$3" "$CALLS" +} + +NOW=$(jq -n 'now | floor') + +# status_result [validator account]: +# status result as neard 2.14.1 builds it (core/primitives/src/views.rs StatusResponse) +status_result() { + jq -cn --argjson syncing "$1" --argjson height "$2" --argjson time "$((NOW - $3))" --arg account "${4:-}" '{ + version: {version: "2.14.1", build: "2.14.1", commit: "0ad2bdb2630e85bbacecab2a3b77072c78b46bc6", rustc_version: "1.95.0"}, + chain_id: "mainnet", protocol_version: 88, latest_protocol_version: 88, rpc_addr: "0.0.0.0:3030", + validators: [{account_id: "astro-stakers.poolv1.near"}], + sync_info: { + latest_block_hash: "3jFq579MZgogbbFYec43RWwJKtRVF3jCVzRj1UYBNqsv", latest_block_height: $height, + latest_state_root: "3Z1vanj7TxZnBnz4Lihp1p5KW9LaKVVtfkfKEu2p8nPR", + latest_block_time: ($time | todate | sub("Z$"; ".772410996Z")), syncing: $syncing, + earliest_block_hash: "Cz3kHoz26VvAwXUa4vS26ShUAY8z6oKBiiwVev6kWPDY", earliest_block_height: 226813937, + earliest_block_time: "2026-11-29T21:07:30.025444275Z", epoch_id: "8qbvVhW9xJCa7oSsWuuoj47TdiWCVuVtUqUuX3Cq3oyE", + epoch_start_height: 226900337 + }, + validator_account_id: (if $account == "" then null else $account end), + validator_public_key: (if $account == "" then null else "ed25519:7PGseFbWxvYVgZ89K1uTJKYoKetWs7BJtbyXDzfbAcqX" end), + node_public_key: "ed25519:3Ze5ZbRTyBvD8ar1CrmJ8w5uZFiKXFSmSG4sqfhiWHcy", node_key: null, + uptime_sec: 1536988, genesis_hash: "EPnLgE7iEq9s7yTkos96M3cWymH5avBAPm3qx3NXqR8H" + }' +} + +# network : network_info result (chain/jsonrpc-primitives/src/types/network_info.rs) +network() { + printf '{"active_peers":[],"num_active_peers":%s,"peer_max_count":40,"sent_bytes_per_sec":1,"received_bytes_per_sec":2,"known_producers":[]}' "$1" +} + +# metrics [state sync stage per shard...] +metrics() { + printf '# HELP near_block_height_head Height of the current head of the blockchain\n# TYPE near_block_height_head gauge\nnear_block_height_head 100\n' + printf '# HELP near_header_head_height Height of the header head\n# TYPE near_header_head_height gauge\nnear_header_head_height %s\n' "$2" + _sync=$1 + shift 2 + _shard=0 + for _stage in "$@"; do + printf 'near_state_sync_stage{shard_id="%s"} %s\n' "$_shard" "$_stage" + _shard=$((_shard + 1)) + done + printf '# HELP near_sync_status Node sync status\n# TYPE near_sync_status gauge\nnear_sync_status %s\n' "$_sync" + printf 'near_peer_connections_total 7\n' +} + +# write_marker : marker as start_near.sh writes it +write_marker() { + printf 'pid=%s\nphase=%s\nprogress=%s\n' "$1" "$2" "$3" >"$NODE_STATUS_DIR/pre-start" +} + +# Starts a process whose command line names start_near.sh and sets ENTRYPOINT_PID +start_fake_entrypoint() { + sh -c 'sleep 60; :' start_near.sh >/dev/null 2>&1 & + ENTRYPOINT_PID=$! + HELPER_PIDS="$HELPER_PIDS $ENTRYPOINT_PID" +} + +RPC="http://127.0.0.1:3030 status,http://127.0.0.1:3030 network_info" +ALL="$RPC,http://127.0.0.1:3030/metrics " +VERSION='{"label":"Version","value":"2.14.1"}' + +echo "Contract check" +check "rejects an unknown state" "state" "$(report_errors '{"version":1,"state":"waiting"}')" +check "rejects 100% while syncing" "progress" "$(report_errors '{"version":1,"state":"syncing","progress":100}')" +check "rejects an unknown field" "unknown key percent" "$(report_errors '{"version":1,"state":"synced","percent":3}')" +check "rejects a trailing period" "phase" "$(report_errors '{"version":1,"state":"syncing","phase":"Downloading blocks."}')" +check "rejects a string height" "height" "$(report_errors '{"version":1,"state":"synced","height":"1"}')" +check "rejects progress with position" "progress with position" "$(report_errors '{"version":1,"state":"syncing","progress":1,"position":2}')" +check "rejects text" "not JSON" "$(report_errors 'synced')" +check "accepts a full report" "" "$(report_errors '{"version":1,"state":"syncing","phase":"Downloading blocks","height":1,"position":1,"target":2,"peers":2,"details":[{"label":"A","value":"b"}]}')" + +echo "starting" +STUB_STATUS="" +STUB_NETWORK=$(network 12) +expect "node down" '{"version":1,"state":"starting"}' "http://127.0.0.1:3030 status" +STUB_STATUS=error +expect "status answers an error" '{"version":1,"state":"starting"}' "http://127.0.0.1:3030 status" +STUB_STATUS="" + +start_fake_entrypoint +write_marker "$ENTRYPOINT_PID" "Initializing node" "" +expect "initializing" '{"version":1,"state":"starting","phase":"Initializing node"}' "http://127.0.0.1:3030 status" +write_marker "$ENTRYPOINT_PID" "Downloading snapshot" "" +expect "snapshot download" '{"version":1,"state":"starting","phase":"Downloading snapshot"}' "http://127.0.0.1:3030 status" +write_marker "$ENTRYPOINT_PID" "Downloading snapshot" "100" +run_status +check "snapshot download: progress never 100 while running" "99.9" "$(printf '%s\n' "$OUT" | jq .progress)" + +sleep 60 >/dev/null 2>&1 & +OTHER_PID=$! +HELPER_PIDS="$HELPER_PIDS $OTHER_PID" +write_marker "$OTHER_PID" "Downloading snapshot" "" +expect "marker naming a process that is not start_near.sh (neard after exec)" '{"version":1,"state":"starting"}' "http://127.0.0.1:3030 status" +sh -c 'exit 0' & +DEAD_PID=$! +wait "$DEAD_PID" +write_marker "$DEAD_PID" "Downloading snapshot" "" +expect "marker of a stopped run" '{"version":1,"state":"starting"}' "http://127.0.0.1:3030 status" +write_marker "" "Downloading snapshot" "" +expect "marker without pid" '{"version":1,"state":"starting"}' "http://127.0.0.1:3030 status" +printf 'garbage\n' >"$NODE_STATUS_DIR/pre-start" +expect "garbage marker" '{"version":1,"state":"starting"}' "http://127.0.0.1:3030 status" + +echo "synced" +write_marker "$ENTRYPOINT_PID" "Downloading snapshot" "" +STUB_STATUS=$(status_result false 226927639 5) +HEAD="\"height\":226927639,\"headTime\":$((NOW - 5))" +expect "at the head" "{\"version\":1,\"state\":\"synced\",$HEAD,\"peers\":12,\"details\":[$VERSION]}" "$RPC" +rm -f "$NODE_STATUS_DIR/pre-start" +STUB_STATUS=$(status_result false 226927639 100) +run_status +check "latest block 100 s old is fresh" "synced" "$(printf '%s\n' "$OUT" | jq -r .state)" +STUB_STATUS=$(status_result false 226927639 5 alice.poolv1.near) +expect "validator key loaded" \ + "{\"version\":1,\"state\":\"synced\",$HEAD,\"peers\":12,\"details\":[{\"label\":\"Validator account\",\"value\":\"alice.poolv1.near\"},$VERSION]}" "$RPC" +STUB_STATUS=$(status_result false 226927639 5) +STUB_NETWORK=$(network 0) +expect "no peers is not an issue" "{\"version\":1,\"state\":\"synced\",$HEAD,\"peers\":0,\"details\":[$VERSION]}" "$RPC" +STUB_NETWORK="" +expect "network_info failing" "{\"version\":1,\"state\":\"synced\",$HEAD,\"details\":[$VERSION]}" "$RPC" +STUB_NETWORK=$(network 12) +STUB_STATUS=$(printf '%s\n' "$STUB_STATUS" | jq -c '.sync_info.latest_block_time |= sub("[.][0-9]+"; "")') +expect "block time without fraction" "{\"version\":1,\"state\":\"synced\",$HEAD,\"peers\":12,\"details\":[$VERSION]}" "$RPC" + +echo "freshness" +STUB_STATUS=$(status_result false 226927639 200) +expect "not syncing but the latest block is 200 s old" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Catching up\",\"height\":226927639,\"headTime\":$((NOW - 200)),\"peers\":12,\"details\":[$VERSION]}" "$RPC" +STUB_STATUS=$(status_result false 226927639 5 | jq -c '.sync_info.latest_block_time = "yesterday"') +expect "unreadable block time is never synced" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Catching up\",\"height\":226927639,\"peers\":12,\"details\":[$VERSION]}" "$RPC" +STUB_STATUS=$(status_result false 226927639 5 | jq -c 'del(.sync_info.latest_block_time)') +run_status +check "missing block time is never synced" "syncing" "$(printf '%s\n' "$OUT" | jq -r .state)" + +echo "syncing" +# A node restored from an old snapshot: its head is 2 days old +OLD=$((2 * 86400)) +STUB_STATUS=$(status_result true 226700000 "$OLD") +OLD_HEAD="\"height\":226700000,\"headTime\":$((NOW - OLD))" +STUB_METRICS=$(metrics 7 226927600) +expect "block sync" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Downloading blocks\",$OLD_HEAD,\"position\":226700000,\"target\":226927600,\"peers\":12,\"details\":[$VERSION]}" "$ALL" +STUB_METRICS=$(metrics 7 226700000) +expect "block sync with the header head not ahead" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Downloading blocks\",$OLD_HEAD,\"position\":226700000,\"peers\":12,\"details\":[$VERSION]}" "$ALL" +STUB_METRICS=$(metrics 1 226700000) +STUB_NETWORK=$(network 0) +expect "awaiting peers" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Waiting for peers\",$OLD_HEAD,\"peers\":0,\"details\":[$VERSION]}" "$ALL" +STUB_NETWORK=$(network 12) + +# A fresh node: its head is genesis (mainnet genesis block 9820210, 2020-07-21) +GENESIS_AGE=$((NOW - 1595350551)) +STUB_STATUS=$(status_result true 9820210 "$GENESIS_AGE") +GENESIS="\"height\":9820210,\"headTime\":1595350551" +STUB_METRICS=$(metrics 2 9820210) +expect "epoch sync" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Downloading epoch sync proof\",$GENESIS,\"peers\":12,\"details\":[$VERSION]}" "$ALL" +STUB_METRICS=$(metrics 4 226800000) +expect "header sync" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Downloading block headers\",$GENESIS,\"position\":226800000,\"peers\":12,\"details\":[$VERSION]}" "$ALL" +STUB_METRICS=$(metrics 5 226927000 1 0 5 1 1 1 1 1 5) +expect "state sync downloading parts" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Downloading state\",$GENESIS,\"peers\":12,\"details\":[$VERSION,{\"label\":\"Shards synced\",\"value\":\"2 of 9\"}]}" "$ALL" +STUB_METRICS=$(metrics 5 226927000 3 5 4 2 5 5 5 5 5) +expect "state sync applying" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Applying state\",$GENESIS,\"peers\":12,\"details\":[$VERSION,{\"label\":\"Shards synced\",\"value\":\"6 of 9\"}]}" "$ALL" +STUB_METRICS=$(metrics 5 226927000) +expect "state sync before any shard started" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Downloading state\",$GENESIS,\"peers\":12,\"details\":[$VERSION]}" "$ALL" + +STUB_STATUS=$(status_result true 226700000 "$OLD") +STUB_METRICS=$(metrics 0 226927600) +expect "sync gauge not refreshed yet" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Catching up\",$OLD_HEAD,\"position\":226700000,\"target\":226927600,\"peers\":12,\"details\":[$VERSION]}" "$ALL" +STUB_METRICS=$(metrics 9 226700000) +expect "unknown sync code" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Catching up\",$OLD_HEAD,\"peers\":12,\"details\":[$VERSION]}" "$ALL" +STUB_METRICS='near_block_height_head 226700000' +expect "metrics without the sync gauges" \ + "{\"version\":1,\"state\":\"syncing\",\"phase\":\"Catching up\",$OLD_HEAD,\"peers\":12,\"details\":[$VERSION]}" "$ALL" +unset STUB_METRICS +expect "metrics failing" "{\"version\":1,\"state\":\"syncing\",$OLD_HEAD,\"peers\":12,\"details\":[$VERSION]}" "$ALL" +STUB_METRICS=$(metrics 7 226927600) +STUB_NETWORK=error +expect "stops after network_info fails" "{\"version\":1,\"state\":\"syncing\",$OLD_HEAD,\"details\":[$VERSION]}" "$RPC" +STUB_NETWORK=$(network 12) + +echo "Run as a command" +mkdir -p "$TMP/bin" +printf '#!/bin/sh\nexit 7\n' >"$TMP/bin/curl" +chmod +x "$TMP/bin/curl" +OUT=$(PATH="$TMP/bin:$PATH" sh "$SCRIPT" 2>"$TMP/stderr") +RC=$? +check "command: report" '{"version":1,"state":"starting"}' "$OUT" +check "command: exit code" "0" "$RC" +check "command: nothing on stderr" "" "$(cat "$TMP/stderr")" +OUT=$(NODE_STATUS_TOOLS=/nonexistent sh "$SCRIPT" 2>/dev/null) +RC=$? +check "command: missing helpers print nothing" "" "$OUT" +check "command: missing helpers fail" "true" "$([ "$RC" -ne 0 ] && echo true)" + +echo "start_near.sh pre-start marker" +# start_near.sh with its paths moved under $TMP and neard and curl stubbed: neard init, the +# snapshot download (the script curl fetches) and neard run each record the report of the +# healthcheck at that moment +mkdir -p "$TMP/near" "$TMP/reports" +sed -e "s|/tmp/node-status|$NODE_STATUS_DIR|g" -e "s|/srv/near|$TMP/near|g" "$ENTRYPOINT" >"$TMP/start_near.sh" +cat >"$TMP/bin/neard" <"$TMP/reports/init"; touch "$TMP/near/node_key.json" ;; +*" ping "*) ;; +*" run "*) sh "$SCRIPT" >"$TMP/reports/run"; ls "$NODE_STATUS_DIR" >"$TMP/reports/files_at_run" ;; +esac +EOF +cat >"$TMP/bin/curl" <"%s"\nexit 1\n' "$SCRIPT" "$TMP/reports/snapshot" ;; +*) exit 7 ;; +esac +EOF +chmod +x "$TMP/bin/neard" "$TMP/bin/curl" + +# run_entrypoint : runs the copy of start_near.sh, sets RC +run_entrypoint() { + rm -f "$TMP/reports/"* + PATH="$TMP/bin:$PATH" CHAIN_ID=mainnet DOWNLOAD_SNAPSHOT=$1 bash "$TMP/start_near.sh" >"$TMP/entrypoint.log" 2>&1 + RC=$? +} + +run_entrypoint true +check "first start: init reported" '{"version":1,"state":"starting","phase":"Initializing node"}' "$(cat "$TMP/reports/init")" +check "first start: snapshot download reported" '{"version":1,"state":"starting","phase":"Downloading snapshot"}' "$(cat "$TMP/reports/snapshot")" +check "first start: plain starting once neard runs" '{"version":1,"state":"starting"}' "$(cat "$TMP/reports/run")" +check "first start: no marker left when neard runs" "" "$(cat "$TMP/reports/files_at_run")" +check "first start: failed download still starts neard" "0" "$RC" + +# A marker of a run that was stopped mid-download, naming a live start_near.sh process +start_fake_entrypoint +write_marker "$ENTRYPOINT_PID" "Downloading snapshot" "" +run_entrypoint false +check "restart: stale marker removed" "" "$(cat "$TMP/reports/files_at_run")" +check "restart: plain starting once neard runs" '{"version":1,"state":"starting"}' "$(cat "$TMP/reports/run")" +check "restart: no init or download" "false false" \ + "$([ -e "$TMP/reports/init" ] && echo true || echo false) $([ -e "$TMP/reports/snapshot" ] && echo true || echo false)" + +echo +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ]