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
4 changes: 2 additions & 2 deletions docs/heartbeat.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

### Heartbeat

ARC's autoscaling means there is normally no pre-existing "online runner" to check the way the previous design's fallback logic did (querying `/orgs/{org}/actions/runners` for an online match); with `minRunners: 0`, pods exist only while a job is running. To still support falling back to `ubuntu-latest` if the whole fleet goes down, `heartbeat` (an in-cluster Deployment - see `roles/github_runner_arc/tasks/install_platform.yml`) checks every `HEARTBEAT_INTERVAL_SECONDS` (default 180s) that a k3s node and the ARC controller are healthy and that no runner pod has been unschedulable for `HEARTBEAT_UNSCHEDULABLE_AFTER_SECONDS` (default: one interval), since a fleet with nowhere to place a runner only queues the work sent to it, and if so, refreshes a single secret gist with a unix timestamp set `HEARTBEAT_WINDOW_SECONDS` (default 600s) into the future. [`exadev/runner-fallback-action`](https://github.com/ExaDev/runner-fallback-action) reads that gist over the unauthenticated GitHub API and routes to `exadev-runners` while the timestamp is still fresh, or to `ubuntu-latest` otherwise. Every tick, healthy or not, it also writes `fleet-health.json` to the same gist (`HEALTH_GIST_FILE`): whether the fleet is vouched for, the reasons it is not, and any node reporting a pressure condition such as `DiskPressure`. A node under pressure does not make the fleet unhealthy, since the other nodes still serve jobs, but it is named there so lost capacity is visible. See that repo's `docs/spec.md` for the algorithm. It also writes `job-peak-summary.json`, the distribution of the peak memory jobs have measured (job count, how many distinct repositories they came from, the period they cover, median, 95th percentile and maximum in MiB, next to the runner pod's memory limit; the count and period are there because a large job count from one busy repository on one day says little), so whether the pods' request can come down is a lookup there and not a query of the cluster. It holds only figures, never a repository, workflow or job name, because the gist is readable by anyone holding its link.
ARC's autoscaling means there is normally no pre-existing "online runner" to check the way the previous design's fallback logic did (querying `/orgs/{org}/actions/runners` for an online match); with `minRunners: 0`, pods exist only while a job is running. To still support falling back to `ubuntu-latest` if the whole fleet goes down, `heartbeat` (an in-cluster Deployment - see `roles/github_runner_arc/tasks/install_platform.yml`) checks every `HEARTBEAT_INTERVAL_SECONDS` (default 180s) that a k3s node and the ARC controller are healthy and that no runner pod has been unschedulable for `HEARTBEAT_UNSCHEDULABLE_AFTER_SECONDS` (default: one interval), since a fleet with nowhere to place a runner only queues the work sent to it, and that every expected scale set has a listener that has been running for at least `HEARTBEAT_LISTENER_SETTLE_SECONDS` (default: one interval), since the controller deletes and re-creates a listener whenever its scale set's spec changes (the autoscaler's every `maxRunners` patch does), which drops the session with GitHub, and a job queued meanwhile can stay unassigned although the new listener is Running and runners start for other jobs, and if so, refreshes a single secret gist with a unix timestamp set `HEARTBEAT_WINDOW_SECONDS` (default 600s) into the future. [`exadev/runner-fallback-action`](https://github.com/ExaDev/runner-fallback-action) reads that gist over the unauthenticated GitHub API and routes to `exadev-runners` while the timestamp is still fresh, or to `ubuntu-latest` otherwise. Every tick, healthy or not, it also writes `fleet-health.json` to the same gist (`HEALTH_GIST_FILE`): whether the fleet is vouched for, the reasons it is not, and any node reporting a pressure condition such as `DiskPressure`. A node under pressure does not make the fleet unhealthy, since the other nodes still serve jobs, but it is named there so lost capacity is visible. See that repo's `docs/spec.md` for the algorithm. It also writes `job-peak-summary.json`, the distribution of the peak memory jobs have measured (job count, how many distinct repositories they came from, the period they cover, median, 95th percentile and maximum in MiB, next to the runner pod's memory limit; the count and period are there because a large job count from one busy repository on one day says little), so whether the pods' request can come down is a lookup there and not a query of the cluster. It holds only figures, never a repository, workflow or job name, because the gist is readable by anyone holding its link.

`fleet-health.json` also carries `deployed`: the collection version each playbook scope last recorded, so a scope that a run never reached shows as behind the version the fleet repository pins instead of looking like one that is current. The ARC and platform scope (`arc.yml`) records it in the platform namespace's `deployed-state` ConfigMap at the end of a run, as `platform`; each server host (`site.yml`) annotates its own node with `github-runner.exadev.com/deployed-version` once the node has registered, as an entry in `nodes`. A host annotates only its own node, so a `--limit` run never claims a version for hosts it did not touch, and an agent host, which has no API of its own, records nothing and shows `null`. The stamp records what a run applied, not what is running: a pod that failed to start after a run still leaves the stamp, so it complements the health reasons and does not replace them. `arc.yml` does not touch hosts, so a release that changes the Compose directory (the `docker-prune` service was one) shows the nodes behind until `site.yml` runs.

Expand All @@ -21,7 +21,7 @@ Confirm it refreshes: `gh gist view "$HEARTBEAT_GIST_ID"` must show a timestamp

`runner-fallback-action` reroutes silently, so nothing otherwise tells a person that the fleet has no runners. `fleet-health.json` carries what a notifier needs to judge how long that has lasted: `at` (when the heartbeat last wrote), `unhealthy_since` (when it stopped vouching for the fleet, `null` while it does) and `not_ready_nodes` (each node whose Ready condition is not True, whether it is a control-plane server, the `regrade_level` memory-pressure regrading has stepped it to if it has, and since when). The heartbeat carries each onset over from the document its previous tick published, read back from the gist, so a tick that cannot read it restarts the onsets at now, which delays an alert and never raises a false one.

`scripts/fleet-alert.sh` reads that document and announces an outage when any of these has held for at least `FLEET_ALERT_AFTER_SECONDS` (default 900, longer than the heartbeat's own 600 second window): the heartbeat has not written for that long, a control-plane server has not been Ready for that long (except one regrading has stepped down, which is not Ready on purpose), or the heartbeat has not vouched for the fleet for that long (a scale set missing or without a running listener, no ready controller, no Ready node, runner pods that cannot be scheduled; the reasons are in the notification). A worker node that is not Ready is not an outage by itself. An outage is announced once, and a recovery note follows when every condition has cleared. A heartbeat image older than the onset fields makes the script fail with a message saying so, rather than never alerting.
`scripts/fleet-alert.sh` reads that document and announces an outage when any of these has held for at least `FLEET_ALERT_AFTER_SECONDS` (default 900, longer than the heartbeat's own 600 second window): the heartbeat has not written for that long, a control-plane server has not been Ready for that long (except one regrading has stepped down, which is not Ready on purpose), or the heartbeat has not vouched for the fleet for that long (a scale set missing or without a listener that has settled, no ready controller, no Ready node, runner pods that cannot be scheduled; the reasons are in the notification). A worker node that is not Ready is not an outage by itself. An outage is announced once, and a recovery note follows when every condition has cleared. A heartbeat image older than the onset fields makes the script fail with a message saying so, rather than never alerting.

Delivery is independent per channel, and with none configured the script only prints what it found:

Expand Down
16 changes: 13 additions & 3 deletions scripts/heartbeat.sh
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
# - HEARTBEAT_DEPLOYED_VERSION_ANNOTATION: the node annotation holding the collection version the cluster role last applied on that node's host
# - HEARTBEAT_CONTROLLER_NAMESPACE: namespace of the ARC controller's Deployment, when it is not the default actions-runner-controller
# - HEARTBEAT_UNSCHEDULABLE_AFTER_SECONDS: how long a runner pod may stay unschedulable before the heartbeat stops refreshing (default: one heartbeat interval)
# - HEARTBEAT_LISTENER_SETTLE_SECONDS: how long a scale set's listener must have been running before the scale set is vouched for (default: one heartbeat interval)
set -euo pipefail

HEARTBEAT_GH_TOKEN="${HEARTBEAT_GH_TOKEN:?HEARTBEAT_GH_TOKEN must be set (a PAT with gist scope)}"
Expand All @@ -38,6 +39,8 @@ HEARTBEAT_WINDOW_SECONDS="${HEARTBEAT_WINDOW_SECONDS:-600}"
HEARTBEAT_CONTROLLER_NAMESPACE="${HEARTBEAT_CONTROLLER_NAMESPACE:-actions-runner-controller}"
# How long a runner pod may sit unschedulable before the fleet counts as unable to take work: one heartbeat interval (the loop's own, see heartbeat/loop.sh), so the condition has been seen on at least two consecutive ticks and a pod that is merely being placed never trips it.
HEARTBEAT_UNSCHEDULABLE_AFTER_SECONDS="${HEARTBEAT_UNSCHEDULABLE_AFTER_SECONDS:-${HEARTBEAT_INTERVAL_SECONDS:-180}}"
# How long a scale set's listener must have been running before it counts: one heartbeat interval, so a listener the controller has just re-created has been seen on at least two ticks before the scale set is vouched for again.
HEARTBEAT_LISTENER_SETTLE_SECONDS="${HEARTBEAT_LISTENER_SETTLE_SECONDS:-${HEARTBEAT_INTERVAL_SECONDS:-180}}"

healthy=true
reasons=()
Expand All @@ -56,7 +59,7 @@ if ! kubectl get deployment -n "$HEARTBEAT_CONTROLLER_NAMESPACE" -l app.kubernet
healthy=false
fi

# A scale set that is missing, or whose listener is not running, takes no jobs however healthy the nodes and controller look: a failed Helm upgrade once left every scale set deleted while this heartbeat kept vouching for the fleet, so jobs queued on runners that did not exist.
# A scale set that is missing, or whose listener is not running or was only just re-created, takes no jobs however healthy the nodes and controller look: a failed Helm upgrade once left every scale set deleted while this heartbeat kept vouching for the fleet, so jobs queued on runners that did not exist.
for target in $HEARTBEAT_EXPECTED_SCALE_SETS; do
namespace="${target%%/*}"
release="${target#*/}"
Expand All @@ -65,12 +68,19 @@ for target in $HEARTBEAT_EXPECTED_SCALE_SETS; do
healthy=false
continue
fi
listeners="$(kubectl get pods -n "$HEARTBEAT_CONTROLLER_NAMESPACE" \
listener_pods="$(kubectl get pods -n "$HEARTBEAT_CONTROLLER_NAMESPACE" \
-l "actions.github.com/scale-set-name=${release},actions.github.com/scale-set-namespace=${namespace}" \
-o jsonpath='{range .items[*]}{.status.phase}{"\n"}{end}' 2>/dev/null | grep -c '^Running$' || true)"
-o json 2>/dev/null || true)"
# The listener holds the scale set's one session with GitHub, and the controller deletes and re-creates it whenever the scale set's spec changes (the autoscaler's every maxRunners patch does), which drops that session. A job queued while the session was being replaced can sit unassigned for hours although the listener is Running again and runners start for other jobs, so a listener counts only once it has outlived one heartbeat interval: a scale set whose listener keeps being replaced is then not vouched for, and runner-fallback-action routes its jobs to GitHub-hosted runners instead of queueing them.
listeners="$(jq '[.items[]? | select(.status.phase == "Running")] | length' <<< "${listener_pods:-null}")"
settled="$(jq --argjson now "$(date +%s)" --argjson settle "$HEARTBEAT_LISTENER_SETTLE_SECONDS" \
'[.items[]? | select(.status.phase == "Running" and ($now - (.metadata.creationTimestamp | fromdateiso8601)) >= $settle)] | length' <<< "${listener_pods:-null}")"
if [ "$listeners" -lt 1 ]; then
reasons+=("scale set ${target} has no running listener")
healthy=false
elif [ "$settled" -lt 1 ]; then
reasons+=("scale set ${target} has no listener older than ${HEARTBEAT_LISTENER_SETTLE_SECONDS}s")
healthy=false
fi
done

Expand Down
37 changes: 35 additions & 2 deletions tests/unit/test_heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "heartbeat.sh"
UNSCHEDULABLE_AFTER_SECONDS = 180
LISTENER_SETTLE_SECONDS = 180
EXPECTED = ("arc-runners-a/runners-a", "arc-runners-b/runners-b")

# Answers the reads heartbeat.sh makes from FAKE_STATE (a JSON file): whether a node is Ready, whether the controller has a ready replica, and the runner pods.
Expand All @@ -34,7 +35,15 @@
if args[:2] == ["get", "pods"] and "-A" not in args:
selector = args[args.index("-l") + 1]
release = next(part.split("=")[1] for part in selector.split(",") if part.startswith("actions.github.com/scale-set-name"))
sys.stdout.write("Running\\n" * state["listeners"].get(release, 0))
ages = state["listeners"].get(release, [])
if isinstance(ages, str):
sys.stdout.write(ages)
sys.exit(0)
ages = [10000] * ages if isinstance(ages, int) else ages
import datetime
now = datetime.datetime.now(datetime.timezone.utc)
created = lambda age: (now - datetime.timedelta(seconds=age)).strftime("%Y-%m-%dT%H:%M:%SZ")
sys.stdout.write(json.dumps({"items": [{"status": {"phase": "Running"}, "metadata": {"creationTimestamp": created(age)}} for age in ages]}))
sys.exit(0)
if args[:2] == ["get", "pods"]:
sys.stdout.write(json.dumps({"items": state["pods"]}))
Expand Down Expand Up @@ -90,7 +99,7 @@ def tick(
pods: list[dict[str, object]] | None = None,
controller_replicas: int = 1,
scale_sets: tuple[str, ...] = ("runners-a", "runners-b"),
listeners: dict[str, int] | None = None,
listeners: dict[str, int | list[int] | str] | None = None,
configmap: dict[str, str] | None = None,
nodes: list[dict[str, object]] | None = None,
previous: dict[str, object] | None = None,
Expand Down Expand Up @@ -124,6 +133,7 @@ def tick(
"HEARTBEAT_GH_TOKEN": "test-token",
"HEARTBEAT_GIST_ID": "test-gist",
"HEARTBEAT_UNSCHEDULABLE_AFTER_SECONDS": str(UNSCHEDULABLE_AFTER_SECONDS),
"HEARTBEAT_LISTENER_SETTLE_SECONDS": str(LISTENER_SETTLE_SECONDS),
"HEARTBEAT_EXPECTED_SCALE_SETS": " ".join(EXPECTED),
**(env or {}),
}
Expand Down Expand Up @@ -167,6 +177,29 @@ def test_a_scale_set_without_a_running_listener_withholds_the_refresh(self) -> N
self.assertIn("arc-runners-b/runners-b has no running listener", result.stderr)
self.assertWithheld(files)

def test_a_listener_recreated_within_the_settle_time_withholds_the_refresh(self) -> None:
result, files = self.tick(listeners={"runners-a": 1, "runners-b": [LISTENER_SETTLE_SECONDS - 1]})
self.assertEqual(result.returncode, 1)
self.assertIn("arc-runners-b/runners-b has no listener older than", result.stderr)
self.assertWithheld(files)

def test_a_listener_older_than_the_settle_time_does_not_withhold_the_refresh(self) -> None:
result, files = self.tick(listeners={"runners-a": 1, "runners-b": [LISTENER_SETTLE_SECONDS + 1]})
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn(TIMESTAMP_FILE, files)

def test_an_old_listener_vouches_for_the_scale_set_beside_a_new_one(self) -> None:
result, files = self.tick(listeners={"runners-a": 1, "runners-b": [0, LISTENER_SETTLE_SECONDS + 1]})
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn(TIMESTAMP_FILE, files)

def test_unreadable_listener_pods_fail_loudly_instead_of_reading_as_no_listener(self) -> None:
result, files = self.tick(listeners={"runners-a": 1, "runners-b": "not json"})
self.assertNotEqual(result.returncode, 0)
self.assertNotIn("has no running listener", result.stderr)
self.assertIn("parse error", result.stderr)
self.assertNotIn(TIMESTAMP_FILE, files)

def test_a_fleet_of_nothing_but_not_ready_nodes_withholds_the_refresh(self) -> None:
result, files = self.tick(nodes=[self.node("a", None, ready=False), self.node("b", None, ready=False)])
self.assertEqual(result.returncode, 1)
Expand Down
Loading