Repository navigation
feat: add node status helpers for package healthchecks #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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' | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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}" "$@" | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.