mirror of
https://github.com/mulgadc/spinifex.git
synced 2026-10-19 19:01:42 +00:00
8e11908dfb
* fix: report CPU and memory pressure in the EKS control-plane health diagnostic An unhealthy control plane reported readyz, etcd reachability and etcd-disk free space. When etcd goes unreachable with disk:ok and no OOM kill, that set cannot distinguish a starved guest from a genuine etcd fault, so add the loadavg and MemAvailable that separate them. An empty /readyz body also rendered as readyz:[none], which reads as "no subcheck failed" when it means the probe never answered. Report that as unreachable instead. * fix: sample the node's load, not just the runner host's Every runner agent runs on one host while their nodes sit on several, so the existing sample measured the runner's host and was labelled as the hypervisor. It happens to coincide when the node is on that same host and misleads otherwise. Relabel it and add a node-side sample, which is where the guests are actually scheduled and so where a starved guest shows up. * feat: build the mkosi EKS image in CI and give its control plane telemetry The Ubuntu/systemd EKS image is what customers run, and nothing built it: the composition existed in mkosi-build.sh's image_profiles table but had no caller, so a change that broke it was found by hand or not at all. Cell-25 builds the Alpine image, which leaves the published one with no gate. Add a Makefile target beside the Alpine one and a job in the existing path-filtered image workflow. The guest also collected nothing. k3s has served embedded-etcd metrics on 127.0.0.1:2381 since the daemon started setting etcd-expose-metrics, and no collector ever read them, so an etcd stall was only ever visible as "etcd:unreachable" in the state report — which cannot separate a slow disk from a dead one. Ship otelcol-contrib pinned to the version the cluster hosts already run, scraping etcd and guest host metrics. The unit is gated on ConditionPathExists for its endpoint file rather than started unconditionally: whether the control-plane guest can reach the sink from the isolated CP VPC is unverified, and a collector with nowhere to export is a restart loop, not telemetry. * fix: report etcd fsync latency in the control-plane health diagnostic disk:ok measures free space, which says nothing about how long a write takes. etcd stalls on fsync latency long before it runs out of room, and this guest's disk is an EBS volume served by viperblock, so a fsync is a network round trip. An unhealthy control plane reporting healthy memory and disk was uninterpretable without it. Derived from the histogram's sum and count rather than a bucket percentile: two greps against an interpolation this script has no business doing, and the difference between a healthy single-digit reading and a stalled one is an order of magnitude, not a tail. Rides the state report's existing gateway path, so it needs no route the CP VPC does not already grant, and lands on both images because the script is shared. The scrape's failure is guarded explicitly. Under set -e a bare assignment from a curl against a port nothing answers aborts the whole diagnosis, dropping the reason field exactly when it is wanted. * feat: publish etcd fsync on every control-plane report, not only failing ones A figure that appears only once the apiserver is already unhealthy has no baseline to be read against, which is the same gap a passing cell that uploads no journal leaves: the number is unanchored when it finally arrives. Move the scrape into its own helper, emit it on healthy reports too, and carry it as a typed field rather than only inside the reason string. Slowness is logged, never gated. observe() decides cluster health, and a working cluster on a slow disk is working — returning an issue there would fail customers' clusters on a latency threshold. The warning is latched on the transition instead, because the control plane republishes on its own timer and a line every interval is how a real signal gets tuned out. An absent sample is not a fast one. Too few fsyncs to average, an etcd serving no metrics and an older AMI all arrive as nil, and the field is omitted rather than defaulted so none of them can be read as healthy. The minimum sample count is the same lesson as the slow-shard floor: a mean over three fsyncs on a just-started etcd is a number with no meaning. * fix: log an etcd fsync baseline and name the two no-sample cases apart A healthy cluster logs no health lines, so the fsync figure reached the daemon on every report and was never surfaced — a passing cell left nothing for a later slow reading to be compared against. Log the first known sample. Split the "unknown" sentinel into nometrics (etcd served none) and warmup (too few fsyncs to average): different faults, different fixes. The payload guard now tests for a number rather than the sentinel word, so a future sentinel cannot leak into the JSON as a bare value. * feat: measure fdatasync latency in the diskperf gate The two pinned profiles are buffered-bypassing throughput jobs at queue depth 32. Neither measures the cost of making a write durable, which is what a consensus datastore pays per raft entry and stalls on long before it runs short of bandwidth. A 5ms barrier on bare metal went unseen as a result. syncwrite-4k is the etcd-shaped profile: sequential 4k, queue depth 1, fdatasync every write, buffered psync so the sync has a page cache to flush. fio reports the sync distribution apart from the write stream, so the parser reads it separately — gating on write clat would score the time to reach the cache and call it durability. No figures captured on this hardware yet, so the baseline entry is zero and the job records without gating. * fix: use the real otelcol checksums asset name in the EKS server image The checksums file is named for the release repo and the distribution and carries no version, unlike the tarball beside it. The guessed name 404'd and took the image build with it. * fix: extract otelcol as root in the EKS server image The upstream tarball records its build uid (runner/docker, 1001:118), which does not exist in the image. tar running as root tries to restore it and fails outright rather than degrading, taking the build with it. --------- Co-authored-by: Ben Duncan <5178243+benduncan@users.noreply.github.com>
188 lines
9.2 KiB
Bash
Executable File
188 lines
9.2 KiB
Bash
Executable File
#!/bin/sh
|
|
set -eu
|
|
|
|
# mulga-eks-state-report — publishes K3s server health to the spinifex cluster
|
|
# reconciler through the AWS gateway. The apiserver binds the VPC node-ip,
|
|
# unreachable from the host-side daemon, so the daemon cannot probe /healthz
|
|
# directly — this report carries {healthz, node_count}. eks-gateway-publish
|
|
# SigV4-signs the POST to the gateway, which relays it onto the management NATS
|
|
# bus the daemon shares; the VM never speaks NATS directly.
|
|
#
|
|
# Subject (gateway-side): eks.state.{accountID}.{clusterName}.server
|
|
# Payload: JSON { healthz: "ok"|"fail", node_count: N, ts: <unix-seconds> }
|
|
#
|
|
# Reads gateway creds + cluster identity from the cloud-init-seeded first-boot
|
|
# env (same vars k3s-first-boot.sh publishes its bootstrap artifacts with). Run
|
|
# as a loop by the mulga-eks-state-report OpenRC service when
|
|
# STATE_REPORT_INTERVAL is set; one-shot otherwise (e.g. a manual invocation).
|
|
|
|
ENVFILE=${ENVFILE:-/etc/spinifex-eks/first-boot.env}
|
|
[ -f "${ENVFILE}" ] || { logger -t mulga-eks-state-report "${ENVFILE} missing — exiting"; exit 0; }
|
|
# set -a so the sourced KEY=value lines are exported to the eks-gateway-publish
|
|
# child (it reads EKS_ACCOUNT_ID etc. from its environment); a bare source
|
|
# leaves them unexported and the helper exits "--account-id is required".
|
|
set -a
|
|
# shellcheck disable=SC1090
|
|
. "${ENVFILE}"
|
|
set +a
|
|
|
|
# EKS_ACCESS_KEY/EKS_SECRET_KEY are optional: when absent, eks-gateway-publish
|
|
# signs with IMDS instance-role credentials via the AWS SDK default chain.
|
|
: "${EKS_GATEWAY_URL:?}"
|
|
: "${EKS_ACCOUNT_ID:?}"
|
|
: "${EKS_CLUSTER_NAME:?}"
|
|
|
|
KUBECONFIG=${KUBECONFIG:-/etc/rancher/k3s/k3s.yaml}
|
|
export KUBECONFIG
|
|
|
|
# Diagnostic knobs (overridable for the unit test). ETCD_DB_DIR is the embedded
|
|
# etcd data dir whose free space we check; DISK_MIN_KB is the low-space threshold.
|
|
ETCD_DB_DIR=${ETCD_DB_DIR:-/var/lib/rancher/k3s/server/db}
|
|
DISK_MIN_KB=${DISK_MIN_KB:-262144}
|
|
|
|
# diagnose emits a compact, JSON-safe reason for an unhealthy apiserver by
|
|
# reading the ground truth only reachable from inside the guest: the failing
|
|
# /readyz subchecks, etcd reachability, etcd-disk free space, and host pressure.
|
|
diagnose() {
|
|
# apiserver prints "[+]name ok" for passing subchecks and "[-]name failed"
|
|
# for failing ones. An empty body means the probe never answered, which is a
|
|
# different fault from "every subcheck passed" and must not read the same.
|
|
readyz=$(kubectl get --raw='/readyz?verbose' 2>/dev/null)
|
|
if [ -z "${readyz}" ]; then
|
|
failed=unreachable
|
|
else
|
|
failed=$(printf '%s\n' "${readyz}" \
|
|
| awk '/^\[-\]/{sub(/^\[-\]/,""); sub(/[[:space:]].*$/,""); printf "%s%s", sep, $0; sep=" "}')
|
|
[ -n "${failed}" ] || failed=none
|
|
fi
|
|
|
|
if kubectl get --raw='/healthz/etcd' 2>/dev/null | grep -q '^ok$'; then
|
|
etcd=ok
|
|
else
|
|
etcd=unreachable
|
|
fi
|
|
|
|
avail_kb=$(df -Pk "${ETCD_DB_DIR}" 2>/dev/null | awk 'NR==2{print $4}')
|
|
if [ -n "${avail_kb}" ] && [ "${avail_kb}" -lt "${DISK_MIN_KB}" ] 2>/dev/null; then
|
|
disk="low:${avail_kb}k"
|
|
else
|
|
disk=ok
|
|
fi
|
|
|
|
# etcd stalls under CPU or memory pressure long before it faults on its own,
|
|
# so an unhealthy CP reporting disk:ok is uninterpretable without these two.
|
|
load=$(awk '{print $1}' "${LOADAVG_FILE:-/proc/loadavg}" 2>/dev/null)
|
|
memavail_kb=$(awk '/^MemAvailable:/{print $2}' "${MEMINFO_FILE:-/proc/meminfo}" 2>/dev/null)
|
|
[ -n "${load}" ] || load=unknown
|
|
[ -n "${memavail_kb}" ] || memavail_kb=unknown
|
|
|
|
printf 'readyz:[%s]; etcd:%s; disk:%s; fsync:%sms; load:%s; memavail:%sk' \
|
|
"${failed}" "${etcd}" "${disk}" "$(etcd_fsync_ms)" "${load}" "${memavail_kb}"
|
|
}
|
|
|
|
# etcd_fsync_ms prints the mean WAL fsync in milliseconds, or "nometrics" when
|
|
# etcd served none, or "warmup" when it has not done enough to average.
|
|
#
|
|
# disk:ok in diagnose() is free space, which says nothing about how long a write
|
|
# takes. etcd stalls on fsync latency long before it runs out of room, and this
|
|
# guest's disk is an EBS volume served by viperblock, so a fsync here is a
|
|
# network round trip. Healthy is single-digit milliseconds.
|
|
#
|
|
# Mean rather than a percentile: the histogram's _sum and _count are two greps,
|
|
# where a bucket percentile is an interpolation this script has no business
|
|
# doing, and a stall shows as an order of magnitude rather than a tail.
|
|
etcd_fsync_ms() {
|
|
# `|| metrics=` is load-bearing under set -e: a scrape against a port
|
|
# nothing answers exits non-zero, and a bare assignment would abort the
|
|
# caller — dropping the diagnosis exactly when it is wanted.
|
|
metrics=$(curl -fsS --max-time 2 "${ETCD_METRICS_URL:-http://127.0.0.1:2381/metrics}" 2>/dev/null) || metrics=
|
|
# "etcd served nothing" and "etcd has not done enough work yet" have
|
|
# different fixes — the first is a missing endpoint, the second is a guest
|
|
# that just booted — so they must not read the same. Collapsing both to one
|
|
# word is the mistake readyz:[none] made.
|
|
if [ -z "${metrics}" ]; then
|
|
echo nometrics
|
|
return
|
|
fi
|
|
# A minimum sample count, not just a non-zero one. A mean over the handful
|
|
# of fsyncs a just-started etcd has done is a number with no meaning, and
|
|
# reporting it invites the same mistake as judging a throughput floor on a
|
|
# 297-byte object.
|
|
fsync=$(printf '%s\n' "${metrics}" | awk -v min="${FSYNC_MIN_COUNT:-100}" '
|
|
/^etcd_disk_wal_fsync_duration_seconds_sum/ {sum=$2}
|
|
/^etcd_disk_wal_fsync_duration_seconds_count/ {count=$2}
|
|
END {if (count >= min) printf "%.1f", (sum / count) * 1000}')
|
|
[ -n "${fsync}" ] || fsync=warmup
|
|
echo "${fsync}"
|
|
}
|
|
|
|
publish_report() {
|
|
# Probe /healthz through the node's admin kubeconfig (apiserver runs
|
|
# anonymous-auth=false, CIS): an unauthenticated curl would return 401.
|
|
reason=
|
|
nodegroup_ready='{}'
|
|
if kubectl get --raw='/healthz' 2>/dev/null | grep -q '^ok$'; then
|
|
health=ok
|
|
# Count Ready nodes only — k3s retains terminated workers as NotReady
|
|
# until manually pruned, so a raw node count never drops on scale-down.
|
|
node_count=$(kubectl get nodes --no-headers 2>/dev/null | awk '$2=="Ready"' | wc -l | tr -d ' ')
|
|
# Per-nodegroup Ready breakdown: -L appends the node's
|
|
# eks.amazonaws.com/nodegroup label as the last column ("<none>" when
|
|
# absent, e.g. the control-plane node itself). Grouping by that label —
|
|
# rather than only totalling — lets each nodegroup's own Ready-gate be
|
|
# scoped to its own workers instead of the cluster-wide count, so one
|
|
# nodegroup's Ready nodes can never mask another's stuck launch.
|
|
nodegroup_ready=$(kubectl get nodes --no-headers -L eks.amazonaws.com/nodegroup 2>/dev/null \
|
|
| awk '$2=="Ready" && $NF!="<none>"{c[$NF]++} END{sep=""; printf "{"; for (k in c) {printf "%s\"%s\":%d", sep, k, c[k]; sep=","}; printf "}"}')
|
|
[ -n "${nodegroup_ready}" ] || nodegroup_ready='{}'
|
|
else
|
|
health=fail
|
|
node_count=0
|
|
# Strip quotes/backslashes/newlines so the reason is safe to embed in the
|
|
# JSON payload without a real encoder.
|
|
reason=$(diagnose | tr -d '"\\' | tr '\n' ' ')
|
|
# Verbose block to the host-captured serial console — the only channel an
|
|
# operator can read when the wedged guest has no shell access.
|
|
{
|
|
echo "=== mulga-eks CP unhealthy $(date -u +%Y-%m-%dT%H:%M:%SZ) cluster=${EKS_CLUSTER_NAME} ==="
|
|
echo "reason: ${reason}"
|
|
kubectl get --raw='/readyz?verbose' 2>&1 | grep -E '^\[-\]' || true
|
|
echo "=== end mulga-eks CP diag ==="
|
|
} > "${CONSOLE:-/dev/console}" 2>&1 || true
|
|
fi
|
|
# fsync goes out on every report, healthy or not. A figure that only appears
|
|
# once the control plane is already failing has no baseline to be read
|
|
# against, which is the same gap a passing cell that uploads no journal
|
|
# leaves. Emitted as a bare JSON number, or omitted entirely when unknown so
|
|
# a missing sample is never mistaken for a fast one.
|
|
fsync_field=
|
|
fsync_ms=$(etcd_fsync_ms)
|
|
# Tested for being a number rather than against the sentinel words: this
|
|
# emits a bare JSON value, so anything non-numeric reaching it produces a
|
|
# payload the daemon cannot parse at all. A new sentinel must not be able
|
|
# to break the report by being added.
|
|
case "${fsync_ms}" in
|
|
'' | *[!0-9.]*) : ;;
|
|
*) fsync_field=$(printf '"fsync_ms":%s,' "${fsync_ms}") ;;
|
|
esac
|
|
if [ -n "${reason}" ]; then
|
|
payload=$(printf '{"healthz":"%s","node_count":%s,"nodegroup_ready":%s,%s"reason":"%s","ts":%s}' \
|
|
"${health}" "${node_count}" "${nodegroup_ready}" "${fsync_field}" "${reason}" "$(date +%s)")
|
|
else
|
|
payload=$(printf '{"healthz":"%s","node_count":%s,"nodegroup_ready":%s,%s"ts":%s}' \
|
|
"${health}" "${node_count}" "${nodegroup_ready}" "${fsync_field}" "$(date +%s)")
|
|
fi
|
|
printf '%s' "${payload}" | eks-gateway-publish -channel state 2>&1 \
|
|
| logger -t mulga-eks-state-report
|
|
}
|
|
|
|
# STATE_REPORT_INTERVAL set → run forever (service mode); unset → one-shot.
|
|
if [ -n "${STATE_REPORT_INTERVAL:-}" ] && [ "${STATE_REPORT_INTERVAL}" -gt 0 ] 2>/dev/null; then
|
|
while true; do
|
|
publish_report
|
|
sleep "${STATE_REPORT_INTERVAL}"
|
|
done
|
|
else
|
|
publish_report
|
|
fi
|