Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .github/workflows/node-status-test.yml
Original file line number Diff line number Diff line change
@@ -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"
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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).
11 changes: 11 additions & 0 deletions dappnode_package.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"architectures": [
"linux/amd64"
Expand Down Expand Up @@ -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"
Expand Down
6 changes: 6 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions neard_image/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Expand Down
184 changes: 184 additions & 0 deletions neard_image/node-status.sh
Original file line number Diff line number Diff line change
@@ -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
# "<phase>:<shards done>:<shards>". 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]+(?<v>[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 <<EOF
$(printf '%s\n' "$status" | read_status)
EOF

set -- height="$height" headTime="$headTime"
[ -n "$account" ] && set -- "$@" detail="Validator account:$account"
[ -n "$version" ] && set -- "$@" detail="Version:$version"

# Stop at the first call that fails: each one can take the full timeout
peers=""
rpc_ok=false
if network=$(ns_rpc network_info); then
peers=$(ns_json_get "$network" .num_active_peers) && rpc_ok=true
fi

if [ "$syncing" = false ]; then
if [ "$fresh" = true ]; then
ns_emit synced peers="$peers" "$@"
exit $?
fi
# neard follows the head by its own account, but its latest block is old: the node lost its
# peers or the network stalls, and it has to catch up
ns_emit syncing phase="Catching up" peers="$peers" "$@"
exit $?
fi

metrics=""
[ "$rpc_ok" = true ] && metrics=$(ns_http_get "$METRICS_URL")
if [ -z "$metrics" ]; then
ns_emit syncing peers="$peers" "$@"
exit $?
fi

# near_sync_status is SyncStatus::repr() of the pinned nearcore (chain/client-primitives/src/types.rs),
# refreshed with every status log line (10 s): 0 no sync, 1 awaiting peers, 2 epoch sync,
# 4 header sync, 5 state sync, 7 block sync. Header sync keeps running during block sync, so the
# header head is the block that block sync heads for.
code=$(printf '%s\n' "$metrics" | ns_metric near_sync_status)
header_head=$(printf '%s\n' "$metrics" | ns_metric near_header_head_height)
target=""
case $height in
'' | *[!0-9]*) ;;
*) [ -n "$header_head" ] && [ "$header_head" -gt "$height" ] 2>/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 $?
24 changes: 24 additions & 0 deletions neard_image/start_near.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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" ]
Expand Down
Loading
Loading