Skip to content
Merged
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
19 changes: 19 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Test

on:
pull_request:

permissions:
contents: read

jobs:
node-status-tools:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- name: Test with dash
run: sh test/node_status_tools_test.sh

- name: Test with busybox ash
run: docker run --rm -v "$PWD:/w" -w /w alpine:3 sh -c 'apk add -q jq curl && sh test/node_status_tools_test.sh'
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
57 changes: 57 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,60 @@ ADD https://raw.githubusercontent.com/dappnode/staker-package-scripts/${STAKER_S

. /etc/profile
```

## Node status tools

`node_status_tools.sh` holds the shared helpers for a package's Docker healthcheck script that prints a node status report: one compact JSON line, the last line of stdout, describing what the node is doing (state, phase, progress, blocks, peers, issues). Each package keeps its client-specific logic in its own script; these functions only call the node's JSON-RPC or HTTP API on `127.0.0.1` with short timeouts, read Prometheus metrics and print a report that always respects the size and field limits. They are POSIX `sh` (busybox ash, dash), depend only on `curl` and `jq` (1.6 or later), define functions only and print nothing on failure.

```Docker
ADD ${STAKER_SCRIPTS_URL}/node_status_tools.sh /etc/profile.d/
```

Environment: `NS_RPC_PORT` is the JSON-RPC port used by `ns_rpc` (default `8545`), `NS_TIMEOUT` the timeout in seconds of every request, also used as connect timeout (default `3`).

| Function | Arguments | Output (stdout) | Exit status |
| --- | --- | --- | --- |
| `ns_rpc` | `<method> [params_json]` (default `[]`) | The JSON `result`, compact (`false` and `null` are valid results) | 0 ok, 1 no answer / not JSON / `error` in the reply, 2 invalid arguments |
| `ns_http_get` | `<url>` starting with `http://127.0.0.1` or `http://localhost` | The body | 0 ok, 1 request failed or status not 2xx, 2 URL not local |
| `ns_metric` | `<name> [label=value ...]`, Prometheus text on stdin | Value of the first sample of `name` carrying all given labels, as a plain number (`2.4E7` gives `24000000`) | 0 found, 1 absent or NaN/Inf, 2 no name |
| `ns_hex_to_dec` | `<0x… or decimal>` | Decimal integer, up to 2^63-1 | 0 ok, 1 anything else |
| `ns_json_get` | `<json> [jq_filter]` (default `.`) | `jq -r` output (compact for objects), nothing when null or absent | 0 ok, non-zero for empty or invalid JSON or a failing filter |
| `ns_block_head` | none | `height=<n> headTime=<n>` of the latest block, to pass unquoted to `ns_emit` | 0 ok, 1 no answer or no block |
| `ns_emit` | `<state> [key=value ...]` | The report as one JSON line | 0 for `starting`, `syncing`, `synced`; 1 for `error`; 2 invalid state (nothing printed) |

`ns_emit` states are `starting`, `syncing`, `synced` and `error`. Keys: `phase`, `progress`, `height`, `headTime`, `position`, `target`, `unit`, `peers`, `awaitingTarget` (only `true` is emitted), `background`, plus repeatable `issue=<text>` and `detail=<Label>:<Value>`. It adds `"version":1`, drops empty, invalid and unknown values (unknown keys are reported on stderr), accepts hex quantities for `height`, `headTime`, `position`, `target` and `peers`, rounds `progress` to one decimal within 0-99.9 (0-100 when `synced`), cuts `phase` and `background` to 60 characters, `unit` to 20, issues to 120 (at most 5) and detail labels and values to 40 and 120 (at most 8), and drops details, then issues, until the line fits in 2,048 bytes. When a key is given twice the last value wins. End the script with `ns_emit ...; exit $?`.

Example only, the healthcheck script of an execution client (the metric name is illustrative):

```Shell
#!/bin/sh
. /etc/profile.d/node_status_tools.sh

# The JSON-RPC does not answer yet: the client is still starting
if ! syncing=$(ns_rpc eth_syncing); then
ns_emit starting phase="Opening database"
exit $?
fi

peers=$(ns_json_get "$(ns_rpc net_peerCount)" .)
metrics=$(ns_http_get http://127.0.0.1:6060/debug/metrics/prometheus)
txindex=$(printf '%s\n' "$metrics" | ns_metric txindex_progress)

# eth_syncing is false once the client follows the head
if [ "$syncing" = "false" ]; then
background=""
[ -n "$txindex" ] && background="Indexing transactions"
ns_emit synced peers="$peers" background="$background"
exit $?
fi

current=$(ns_json_get "$syncing" .currentBlock)
highest=$(ns_json_get "$syncing" .highestBlock)
awaiting=""
[ "$highest" = "0x0" ] && awaiting=true
ns_emit syncing phase="Downloading blocks" position="$current" target="$highest" \
peers="$peers" awaitingTarget="$awaiting" detail="Highest block:$(ns_hex_to_dec "$highest")"
exit $?
```

Run the tests with `sh test/node_status_tools_test.sh`.
232 changes: 232 additions & 0 deletions scripts/node_status_tools.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
#!/bin/sh

# Node status tools
#
# Shared helpers for the healthcheck script of a staker package that prints a
# node status report: one compact JSON line describing what the node is doing.
# Each package keeps its client-specific logic; these functions only call the
# local node, read Prometheus metrics and print the report.
#
# POSIX sh (busybox ash, dash). Depends on curl and jq only. Defines functions
# only, so it is safe to source from /etc/profile.d/. The functions are silent:
# they report failure through their exit status, never on stdout.
#
# Environment:
# NS_RPC_PORT: JSON-RPC port on 127.0.0.1 used by ns_rpc (default 8545)
# NS_TIMEOUT: Timeout in seconds for each request, also used as the connect timeout (default 3)

# Call a JSON-RPC method of the local node and print the JSON "result"
# Example: ns_rpc eth_getBlockByNumber '["latest", false]'
#
# Arguments:
# $1: Method
# $2: Params as a JSON array (default [])
# Returns 0 and prints the raw JSON result (compact; "false" or "null" are valid
# results), 1 when the node does not answer, the reply is not JSON or carries an
# "error", 2 on invalid arguments. Prints nothing on failure.
ns_rpc() {
[ -n "${1:-}" ] || return 2
_ns_body=$(jq -cn --arg m "$1" --argjson p "${2:-[]}" \
'{jsonrpc: "2.0", id: 1, method: $m, params: $p}' 2>/dev/null) || return 2
_ns_reply=$(_ns_curl -H 'Content-Type: application/json' --data "$_ns_body" \
"http://127.0.0.1:${NS_RPC_PORT:-8545}") || return 1
_ns_result=$(printf '%s\n' "$_ns_reply" | jq -c \
'if type == "object" and has("result") and .error == null then .result else error("no result") end' \
2>/dev/null) || return 1
[ -n "$_ns_result" ] || return 1
printf '%s\n' "$_ns_result"
}

# GET a local URL and print the body
# Example: ns_http_get http://127.0.0.1:6060/debug/metrics/prometheus
#
# Arguments:
# $1: URL, must start with http://127.0.0.1 or http://localhost
# Returns 0 and prints the body, 1 when the request fails or the status is not
# 2xx (nothing printed), 2 for a URL that is not local.
ns_http_get() {
case ${1:-} in
*@*) ;;
http://127.0.0.1 | http://127.0.0.1[:/]* | http://localhost | http://localhost[:/]*)
_ns_reply=$(_ns_curl "$1") || return 1
printf '%s\n' "$_ns_reply"
return 0
;;
esac
echo "[ERROR - node-status] ns_http_get only calls 127.0.0.1 or localhost" >&2
return 2
}

# Read Prometheus text exposition from stdin and print the value of the first
# sample of a metric whose labels include all the given pairs
# Example: ns_metric chain_head_block < metrics.txt
# Example: ns_metric beacon_sync_status 'network=mainnet' < metrics.txt
#
# Arguments:
# $1: Metric name
# $2...: Optional label=value pairs the sample must carry
# Returns 0 and prints the value as a plain JSON number (2.4E7 -> 24000000), 1
# when no sample matches or the first matching sample is NaN or infinite, 2
# without a metric name.
ns_metric() {
[ -n "${1:-}" ] || return 2
_ns_name=$1
shift
jq -enRr --arg n "$_ns_name" '
def unescape: gsub("\\\\(?<c>.)"; if .c == "n" then "\n" else .c end);
def labels: [match("([a-zA-Z_][a-zA-Z0-9_]*)[ \t]*=[ \t]*\"((?:[^\"\\\\]|\\\\.)*)\""; "g")
| {key: .captures[0].string, value: (.captures[1].string | unescape)}] | from_entries;
($ARGS.positional | map(split("=") | {key: .[0], value: (.[1:] | join("="))})) as $want
| first(inputs
| select(startswith($n))
| capture("^(?<name>[a-zA-Z_:][a-zA-Z0-9_:]*)(\\{(?<labels>.*)\\})?[ \t]+(?<value>[^ \t]+)([ \t]+-?[0-9]+)?[ \t]*$")
| select(.name == $n)
| select((.labels // "" | labels) as $have | all($want[]; .value == $have[.key])))
| .value
| select(test("^[-+]?([0-9]+[.]?[0-9]*|[.][0-9]+)([eE][-+]?[0-9]+)?$"))
| ltrimstr("+") | tonumber + 0
| select(isinfinite | not)
' --args "$@" 2>/dev/null || return 1
}

# Convert a hex quantity (0x...) to decimal, or pass a decimal integer through
# Example: ns_hex_to_dec 0x6553f100 -> 1700000000
#
# Arguments:
# $1: Hex quantity or decimal integer, up to 2^63-1
# Returns 0 and prints the decimal integer without leading zeros, 1 for
# anything else (empty, negative, fractional, too large).
ns_hex_to_dec() {
_ns_value=${1:-}
case $_ns_value in
0[xX]*)
_ns_value=${_ns_value#??}
case $_ns_value in '' | *[!0-9a-fA-F]*) return 1 ;; esac
_ns_value=${_ns_value#"${_ns_value%%[!0]*}"}
# 15 hex digits always fit in 63 bits; 16 only when the first one is 0-7
if [ "${#_ns_value}" -gt 16 ]; then return 1; fi
if [ "${#_ns_value}" -eq 16 ]; then
case $_ns_value in [0-7]*) ;; *) return 1 ;; esac
fi
printf '%d\n' "0x${_ns_value:-0}"
;;
'' | *[!0-9]*)
return 1
;;
*)
_ns_value=${_ns_value#"${_ns_value%%[!0]*}"}
printf '%s\n' "${_ns_value:-0}"
;;
esac
}

# Print a field of a JSON document (jq -r, compact for objects and arrays)
# Example: ns_json_get "$block" .number
#
# Arguments:
# $1: JSON document
# $2: jq filter (default .)
# Returns 0 and prints the value, or prints nothing when it is null or absent;
# non-zero when the document is empty or not JSON or the filter fails.
ns_json_get() {
[ -n "${1:-}" ] || return 1
printf '%s\n' "$1" | jq -rc "(${2:-.}) | if . == null then empty else . end" 2>/dev/null
}

# Print the latest block of the local execution client as height=<n> headTime=<n>,
# ready to pass to ns_emit unquoted: ns_emit syncing $head
#
# Returns 0 and prints both values as decimals, 1 when the node does not answer
# or has no block.
ns_block_head() {
_ns_block=$(ns_rpc eth_getBlockByNumber '["latest", false]') || return 1
_ns_height=$(ns_hex_to_dec "$(ns_json_get "$_ns_block" .number)") || return 1
_ns_time=$(ns_hex_to_dec "$(ns_json_get "$_ns_block" .timestamp)") || return 1
printf 'height=%s headTime=%s\n' "$_ns_height" "$_ns_time"
}

# Print the status report as one compact JSON line
# Example: ns_emit syncing phase="Downloading state" progress=42.37 peers=0x19; exit $?
#
# Arguments:
# $1: State: starting, syncing, synced or error
# $2...: key=value pairs. Keys: phase, progress, height, headTime, position,
# target, unit, peers, awaitingTarget, background; issue=<text> and
# detail=<Label>:<Value> may repeat. Empty or invalid values are dropped;
# height, headTime, position, target and peers accept hex quantities.
# Returns 0 for starting, syncing and synced, 1 for error (the report is printed
# in all these cases), 2 for an invalid state (nothing printed).
ns_emit() {
case ${1:-} in
starting | syncing | synced | error) ;;
*)
echo "[ERROR - node-status] ns_emit: invalid state '${1:-}'" >&2
return 2
;;
esac
_ns_state=$1
shift
# Keep only known keys, so jq never sees an argument that looks like an option
_ns_count=$#
while [ "$_ns_count" -gt 0 ]; do
_ns_arg=$1
shift
_ns_count=$((_ns_count - 1))
case $_ns_arg in
phase=* | progress=* | height=* | headTime=* | position=* | target=* | unit=* | peers=* | \
awaitingTarget=* | background=* | issue=* | detail=*)
set -- "$@" "$_ns_arg"
;;
*)
echo "[WARN - node-status] ns_emit: ignoring unknown argument '${_ns_arg%%=*}'" >&2
;;
esac
done
jq -cn --arg state "$_ns_state" '
def opt(f): [f] | .[0];
def text($n): (if length > $n then .[0:$n] else . end) | select(. != "");
def number: select(test("^[-+]?([0-9]+[.]?[0-9]*|[.][0-9]+)([eE][-+]?[0-9]+)?$"))
| ltrimstr("+") | tonumber + 0 | select(isinfinite | not);
def count: if test("^0[xX][0-9a-fA-F]+$")
then .[2:] | ascii_downcase | explode
| reduce .[] as $c (0; . * 16 + (if $c >= 97 then $c - 87 else $c - 48 end))
else number | select(. >= 0 and . == floor) end;
def fit: if (tojson | utf8bytelength) <= 2048 then .
elif .details then .details |= .[:-1] | (if .details == [] then del(.details) else . end) | fit
elif .issues then .issues |= .[:-1] | (if .issues == [] then del(.issues) else . end) | fit
else . end;
[$ARGS.positional[] | split("=") | {k: .[0], v: (.[1:] | join("="))}] as $args
| (if $state == "synced" then 100 else 99.9 end) as $max
| def one($k): [$args[] | select(.k == $k) | .v] | last // "";
{
version: 1,
state: $state,
phase: opt(one("phase") | text(60)),
progress: opt(one("progress") | number | (. * 10 + 0.5 | floor) / 10
| if . <= 0 then 0 elif . > $max then $max else . end),
height: opt(one("height") | count),
headTime: opt(one("headTime") | count),
position: opt(one("position") | count),
target: opt(one("target") | count),
unit: opt(one("unit") | text(20)),
peers: opt(one("peers") | count),
awaitingTarget: opt(one("awaitingTarget") | select(. == "true") | true),
background: opt(one("background") | text(60)),
issues: opt([$args[] | select(.k == "issue") | .v | text(120)] | .[0:5] | select(length > 0)),
details: opt([$args[] | select(.k == "detail") | .v | split(":")
| {label: opt(.[0] | text(40)), value: opt(.[1:] | join(":") | text(120))}
| select(.label != null and .value != null)] | .[0:8] | select(length > 0))
}
| with_entries(select(.value != null))
| fit
' --args "$@" || return 2
[ "$_ns_state" != error ]
}

# INTERNAL FUNCTIONS (Not meant to be called directly)

# curl with the node status timeouts, no proxy, no URL globbing and plain http only
_ns_curl() {
curl -sfg --noproxy '*' --proto '=http' \
--max-time "${NS_TIMEOUT:-3}" --connect-timeout "${NS_TIMEOUT:-3}" "$@"
}
Loading
Loading