refactor: gitea runners
runner nix smoke / nix label and flake smoke (push) Failing after 1m22s
runner ubuntu smoke / ubuntu-latest label smoke (push) Successful in 0s

This commit is contained in:
2026-10-03 12:30:42 +00:00
parent e215c11b0b
commit be4ea774b2
14 changed files with 1463 additions and 626 deletions
+6 -2
View File
@@ -26,8 +26,12 @@ Region order for fallback: `nbg1`, then `fsn1`, then `hel1`.
The legacy Kubernetes persistent pool is disabled (`replicas: 0`) and has no
registered labels. All listed labels are handled by the VM controller. After a
successful job, a bootstrapped VM remains running and idle until its next hourly
lifetime boundary, capped by label TTL. A queued job from same repository with
same label reuses it without another VM creation or budget reservation.
lifetime boundary, capped by its original hard TTL. Before becoming generic
idle, its repository runner registration is disabled, deleted, and confirmed
absent. A queued job from any allowed repository may claim a VM with an exact
compatible server type, location, architecture, and image profile. The
controller rebuilds it from that clean image and registers a fresh runner
identity; reuse creates no second VM or budget reservation.
Operational details: `infra/gitea-runners/runbook.md` and
`package/gitea-runner-controller/decide.sh`.
+29 -13
View File
@@ -576,20 +576,36 @@ only, never to a lower-RAM server type. Current Hetzner public pricing for
Germany/Finland CCX53 is 0.8550 EUR/hour excluding IPv4, so one 480-minute
allocation reserves 6.84 EUR against the controller budget before VM creation.
These are maximum lifetimes. Failed, cancelled, skipped, and unbootstrapped jobs
still trigger immediate VM teardown; failed jobs retain pre-destroy diagnostics.
After a successful job, its bootstrapped VM stays running until next hourly
boundary measured from original VM creation, capped by profile TTL. Same-repo,
same-label queued work can atomically claim that idle VM. Reuse preserves
original Hetzner labels and runner name, creates no server, fetches no new
registration token, and makes no second budget reservation. Idle VMs are still
billed: controller deletes them at slot expiry and never relies on stopping a
server to avoid charges.
These are maximum lifetimes. Unbootstrapped or profile-invalid VMs trigger
immediate teardown; failed jobs retain pre-destroy diagnostics. A healthy,
bootstrapped terminal VM may stay running until the next hourly boundary
measured from original VM creation, capped by its original hard TTL.
Reuse retains runner host filesystem and registration identity. It is therefore
restricted to same repository and exact label inside this trusted-only pool;
allowed repositories must not run untrusted fork or pull-request code. A failed
or otherwise non-successful job is never reused.
Retention first enters a durable retirement state. The controller disables the
exact repository runner registration, deletes it, and confirms its absence
before clearing repository, label, and runner ownership into generic idle. A
queued job from any allowed repository can atomically claim generic idle only
when persisted server type, location, architecture, and image match one of the
job label's candidates. The VM then remains unschedulable while Hetzner rebuilds
its root disk from that clean image. Controller verifies rebuild action and
server identity, current image/profile, and current IP before fetching a fresh
destination-repository token and bootstrapping a new runner name. Old runner
registration and filesystem are never reused.
For every creation and reuse rebuild, the controller generates a unique SSH
host key, injects it through authenticated Hetzner `user_data`, and pins that
exact public key before sending a registration token. Shared image host keys
and trust-on-first-use are not used. Runner images must process Hetzner
cloud-init `write_files` during create and rebuild; verify this image gate before
dispatching jobs. If host-key injection fails, bootstrap remains fail-closed.
Reuse preserves original Hetzner VM creation time, hard TTL, and budget charge;
it creates no server and makes no second reservation. Provider or registration
uncertainty remains in a non-schedulable durable state, and unrecoverable rebuild
uncertainty destroys the VM. Idle VMs are still billed: controller deletes them
at slot expiry and never relies on stopping a server to avoid charges. Allowed
repositories remain trusted-only and must not run untrusted fork or pull-request
code.
Active and idle VMs are deleted at profile hard TTL without grace. Idle reuse is
allowed only when at least one configured reconcile interval remains before both
+253 -89
View File
@@ -40,7 +40,14 @@ gcr_sweep_ttl() {
fi
gcr_log info --ns=sweep "idle slot expired job=$job_id vm=$vm_id"
if [ -n "$vm_id" ] && [ "$vm_id" != "null" ] && [ "$vm_id" != "0" ]; then
if gcr_vm_cleanup_start "$job_id" "$attempt" "$rec" idle-expired false; then
if ! gcr_vm_cleanup_intent "$job_id" "$attempt" "$rec" \
idle-expired false; then
gcr_lock_release idle-pool
continue
fi
cleanup_rec="$(gcr_record_get "$job_id" "$attempt")"
gcr_lock_release idle-pool
if gcr_vm_cleanup_pending "$job_id" "$attempt" "$cleanup_rec"; then
gcr_event "vm-destroyed" "$job_id" \
"{\"vm_id\":$vm_id,\"reason\":\"idle-expired\"}"
else
@@ -49,12 +56,15 @@ gcr_sweep_ttl() {
fi
else
gcr_record_del "$job_id" "$attempt"
gcr_lock_release idle-pool
fi
gcr_lock_release idle-pool
continue
fi
[ "$status" = "vm_active" ] || [ "$status" = "pending_vm" ] || continue
case "$status" in
create_pending|pending_vm|vm_active|retiring_vm|rebuild_pending|rebuild_requesting|rebuild_running) ;;
*) continue ;;
esac
ttl_min="$(gcr_record_field "$rec" ttl_min)"
case "$ttl_min" in ''|*[!0-9]*) continue ;; esac
@@ -65,7 +75,7 @@ gcr_sweep_ttl() {
gcr_lock_acquire "$key" || continue
rec="$(gcr_record_get "$job_id" "$attempt")"
case "$(gcr_record_field "$rec" status)" in
pending_vm|vm_active) ;;
create_pending|pending_vm|vm_active|retiring_vm|rebuild_pending|rebuild_requesting|rebuild_running) ;;
*) gcr_lock_release "$key"; continue ;;
esac
ttl_min="$(gcr_record_field "$rec" ttl_min)"
@@ -83,7 +93,8 @@ gcr_sweep_ttl() {
gcr_log warn --ns=sweep "TTL exceeded job=$job_id age=${age}s max=${max_sec}s"
if [ -n "$vm_id" ] && [ "$vm_id" != "null" ] && [ "$vm_id" != "0" ]; then
ip="$(gcr_vm_public_ip "$vm_id" || true)"
gcr_vm_collect_diagnostics "$vm_id" "$ip" "$job_id" ttl || true
gcr_vm_collect_diagnostics "$vm_id" "$ip" "$job_id" ttl \
"$attempt" || true
if gcr_vm_cleanup_start "$job_id" "$attempt" "$rec" ttl false; then
gcr_event "vm-destroyed" "$job_id" \
"{\"vm_id\":$vm_id,\"reason\":\"ttl\"}"
@@ -101,29 +112,22 @@ gcr_sweep_ttl() {
}
gcr_sweep_orphan_vms() {
gcr_lock_acquire admission || return 0
vms_json="$(gcr_vm_list_managed)" || {
gcr_lock_release admission
return 0
}
if ! gcr_lock_acquire idle-pool; then
gcr_lock_release admission
return 0
fi
vms_json="$(gcr_vm_list_managed)" || return 0
count="$(printf '%s' "$vms_json" | jq 'length')"
i=0
while [ "$i" -lt "$count" ]; do
vm="$(printf '%s' "$vms_json" | jq -c ".[$i]")"
vm_id="$(printf '%s' "$vm" | jq -r '.id')"
vm_name="$(printf '%s' "$vm" | jq -r '.name // ""')"
jid="$(printf '%s' "$vm" | jq -r '.labels["gcr.job-id"] // ""')"
att="$(printf '%s' "$vm" | jq -r '.labels["gcr.run-attempt"] // ""')"
if ! gcr_record_exists_for_vm_id "$vm_id"; then
if ! gcr_record_exists_for_vm_owner "$vm_id" "$vm_name" "$jid" "$att"; then
gcr_log warn --ns=sweep "orphan VM $vm_id job=$jid attempt=$att -> destroy"
cleanup_job="${jid:-orphan-$vm_id}"
cleanup_attempt="${att:-0}"
cleanup_rec="$(jq -n --arg j "$cleanup_job" --arg a "$cleanup_attempt" \
--arg v "$vm_id" --arg vn "$(printf '%s' "$vm" | jq -r '.name // ""')" \
--arg v "$vm_id" --arg vn "$vm_name" \
'{job_id:$j, run_attempt:$a, repo:"", label:"", created_at:"0",
ttl_min:0, vm_id:($v|tonumber), vm_name:$vn,
bootstrapped:false, status:"cleanup_pending"}')"
@@ -137,8 +141,6 @@ gcr_sweep_orphan_vms() {
fi
i=$((i + 1))
done
gcr_lock_release idle-pool
gcr_lock_release admission
}
gcr_alloc_deferred() {
@@ -193,20 +195,11 @@ gcr_alloc_deferred() {
if [ "$claim_status" -eq 0 ]; then
reused="$(gcr_record_get "$job_id" "$attempt")"
vm_id="$(gcr_record_field "$reused" vm_id)"
if gcr_vm_runner_service "$vm_id" start \
&& gcr_vm_runner_service "$vm_id" health \
&& gcr_gitea_runner_disabled "$repo" "$(gcr_record_field "$reused" vm_name)" false; then
reused="$(gcr_record_get "$job_id" "$attempt")"
reused="$(printf '%s' "$reused" | jq -c '.bootstrapped = true | del(.reused_vm)')"
gcr_record_put "$job_id" "$attempt" "$reused"
else
gcr_gitea_runner_disabled "$repo" "$(gcr_record_field "$reused" vm_name)" true || true
gcr_event "vm-reuse-start-failed" "$job_id" "{\"vm_id\":$vm_id,\"via\":\"deferred-retry\"}"
fi
gcr_lock_release admission
gcr_lock_release "$key"
gcr_event "vm-reused" "$job_id" "{\"vm_id\":$vm_id,\"label\":\"$label\",\"via\":\"deferred-retry\"}"
gcr_log info --ns=alloc "deferred job=$job_id reused vm=$vm_id"
gcr_event "vm-rebuild-queued" "$job_id" \
"{\"vm_id\":$vm_id,\"label\":\"$label\",\"via\":\"deferred-retry\"}"
gcr_log info --ns=alloc "deferred job=$job_id claimed vm=$vm_id for rebuild"
return 0
fi
if [ "$claim_status" -eq 2 ]; then
@@ -215,32 +208,46 @@ gcr_alloc_deferred() {
return 0
fi
reg_token="$(gcr_gitea_registration_token "$repo")" || {
gcr_lock_release admission
gcr_lock_release "$key"
return 0
}
vm_name="gcr-${job_id}-${attempt}"
created_at="$(gcr_now_epoch)"
create_status=0
created="$(gcr_vm_create "$vm_name" "$label" "$server_type" "$ttl_min" \
"$reg_token" "$job_id" "$attempt" "$repo")" || create_status="$?"
if [ "$create_status" -ne 0 ] || [ -z "$created" ]; then
gcr_lock_release admission
gcr_lock_release "$key"
return 0
fi
set -- $created
vm_id="$1"; actual_server_type="$2"; actual_rate="$3"
if ! gcr_vm_record_created "$job_id" "$attempt" "$repo" "$label" \
"$created_at" "$vm_id" "$vm_name" "$ttl_min" \
"$actual_server_type" "$actual_rate"; then
create_pending="$(printf '%s' "$rec" | jq -c \
--arg t "$created_at" --arg ttl "$ttl_min" --arg vn "$vm_name" \
'.created_at = $t | .ttl_min = ($ttl | tonumber)
| .vm_id = "" | .vm_name = $vn | .runner_name = $vn
| .bootstrapped = false | .status = "create_pending"')"
if ! gcr_record_put "$job_id" "$attempt" "$create_pending"; then
gcr_lock_release admission
gcr_lock_release "$key"
return 0
fi
gcr_lock_release admission
create_status=0
created="$(gcr_vm_create "$vm_name" "$label" "$server_type" "$ttl_min" \
"" "$job_id" "$attempt" "$repo")" || create_status="$?"
if [ "$create_status" -ne 0 ] || [ -z "$created" ]; then
if [ "$create_status" -ne 2 ]; then
retry_rec="$(printf '%s' "$create_pending" | jq -c \
'.ttl_min = null | .vm_id = "" | .vm_name = ""
| .runner_name = "" | .status = "deferred"')"
if ! gcr_record_put "$job_id" "$attempt" "$retry_rec"; then
gcr_log error --ns=alloc \
"failed restoring deferred state job=$job_id after create failure"
fi
fi
gcr_lock_release "$key"
return 0
fi
set -- $created
vm_id="$1"; actual_server_type="$2"; actual_rate="$3"
actual_location="${4:-}"; actual_arch="${5:-}"; actual_image="${6:-}"
if ! gcr_vm_record_created "$job_id" "$attempt" "$repo" "$label" \
"$created_at" "$vm_id" "$vm_name" "$ttl_min" \
"$actual_server_type" "$actual_rate" "$actual_location" \
"$actual_arch" "$actual_image"; then
gcr_lock_release "$key"
return 0
fi
gcr_lock_release "$key"
gcr_event "vm-created" "$job_id" "{\"vm_id\":$vm_id,\"label\":\"$label\",\"ttl_min\":$ttl_min,\"via\":\"deferred-retry\"}"
gcr_log info --ns=alloc "deferred job=$job_id allocated vm=$vm_id"
@@ -254,15 +261,10 @@ gcr_sweep_cleanup_pending() {
attempt="$(gcr_record_field "$rec" run_attempt)"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || continue
if ! gcr_lock_acquire admission; then
gcr_lock_release "$key"
continue
fi
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ "$(gcr_record_field "$rec" status)" = "cleanup_pending" ]; then
gcr_vm_cleanup_pending "$job_id" "$attempt" "$rec" || true
fi
gcr_lock_release admission
gcr_lock_release "$key"
done
}
@@ -275,13 +277,8 @@ gcr_sweep_create_ambiguous() {
attempt="$(gcr_record_field "$rec" run_attempt)"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || continue
if ! gcr_lock_acquire admission; then
gcr_lock_release "$key"
continue
fi
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ "$(gcr_record_field "$rec" status)" != "create_ambiguous" ]; then
gcr_lock_release admission
gcr_lock_release "$key"
continue
fi
@@ -291,25 +288,47 @@ gcr_sweep_create_ambiguous() {
"$(gcr_record_field "$rec" label)" \
"$(gcr_record_field "$rec" server_type)" \
"$(gcr_record_field "$rec" candidate_location)" \
"$(gcr_record_field "$rec" candidate_arch)")" || find_status="$?"
"$(gcr_record_field "$rec" candidate_arch)" \
"$(gcr_record_field "$rec" image_id)")" || find_status="$?"
case "$find_status" in
0)
rec="$(printf '%s' "$rec" | jq -c --arg vm "$found_vm_id" \
'.vm_id = ($vm | tonumber)
| .status = "pending_vm"
| .bootstrapped = false
| del(.create_http, .create_curl_status,
.candidate_location, .candidate_arch)')"
rec="$(printf '%s' "$rec" | jq -c --arg vm "$found_vm_id" \
'.vm_id = ($vm | tonumber)
| .status = "pending_vm"
| .bootstrapped = false
| .runner_name = .vm_name
| .location = .candidate_location
| .arch = .candidate_arch
| del(.create_http, .create_curl_status,
.candidate_location, .candidate_arch,
.budget_reservation_key,
.budget_reservation_charged)')"
if gcr_record_put "$job_id" "$attempt" "$rec"; then
gcr_event "vm-create-recovered" "$job_id" \
"{\"vm_id\":$found_vm_id,\"label\":\"$(gcr_record_field "$rec" label)\"}"
fi
;;
1)
reservation_key="$(gcr_record_field "$rec" budget_reservation_key)"
refund_budget=true
if [ -n "$reservation_key" ]; then
refund_budget=false
if ! gcr_lock_acquire budget; then
gcr_lock_release "$key"
continue
fi
if gcr_budget_transaction_committed "$reservation_key" \
&& ! gcr_budget_transaction_committed \
"rollback-$reservation_key"; then
refund_budget=true
fi
gcr_lock_release budget
fi
rec="$(printf '%s' "$rec" | jq -c \
--argjson refund "$refund_budget" \
'.status = "cleanup_pending"
| .cleanup_reason = "ambiguous-create-absent"
| .cleanup_refund_budget = true
| .cleanup_refund_budget = $refund
| .cleanup_vm_destroyed = true
| .cleanup_budget_released = false')"
if gcr_record_put "$job_id" "$attempt" "$rec"; then
@@ -318,7 +337,155 @@ gcr_sweep_create_ambiguous() {
;;
2) ;;
esac
gcr_lock_release admission
gcr_lock_release "$key"
done
}
gcr_sweep_retiring_vms() {
for f in $(gcr_active_records); do
rec="$(cat "$f")"
[ "$(gcr_record_field "$rec" status)" = "retiring_vm" ] || continue
job_id="$(gcr_record_field "$rec" job_id)"
attempt="$(gcr_record_field "$rec" run_attempt)"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || continue
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ "$(gcr_record_field "$rec" status)" = "retiring_vm" ]; then
retire_status=0
gcr_vm_retire_pending "$job_id" "$attempt" "$rec" || retire_status="$?"
case "$retire_status" in
0|2) ;;
*) gcr_log warn --ns=sweep "retirement retry failed job=$job_id" ;;
esac
fi
gcr_lock_release "$key"
done
}
gcr_rebuild_cleanup() {
rebuild_cleanup_job="$1"; rebuild_cleanup_attempt="$2"
rebuild_cleanup_rec="$3"; rebuild_cleanup_reason="$4"
rebuild_cleanup_vm="$(gcr_record_field "$rebuild_cleanup_rec" vm_id)"
if gcr_vm_cleanup_start "$rebuild_cleanup_job" "$rebuild_cleanup_attempt" \
"$rebuild_cleanup_rec" "$rebuild_cleanup_reason" false; then
gcr_event "vm-destroyed" "$rebuild_cleanup_job" \
"{\"vm_id\":$rebuild_cleanup_vm,\"reason\":\"$rebuild_cleanup_reason\"}"
else
gcr_event "vm-cleanup-pending" "$rebuild_cleanup_job" \
"{\"vm_id\":$rebuild_cleanup_vm,\"reason\":\"$rebuild_cleanup_reason\"}"
fi
}
gcr_reconcile_rebuild() {
rebuild_job="$1"; rebuild_attempt="$2"; rebuild_rec="$3"
rebuild_state="$(gcr_record_field "$rebuild_rec" status)"
rebuild_vm="$(gcr_record_field "$rebuild_rec" vm_id)"
if [ "$rebuild_state" = "rebuild_requesting" ]; then
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" "$rebuild_rec" \
rebuild-request-uncertain
return 0
fi
rebuild_repo="$(gcr_record_field "$rebuild_rec" repo)"
rebuild_job_state="$(gcr_gitea_job_state "$rebuild_repo" "$rebuild_job")" \
|| return 0
case "$rebuild_job_state" in
completed:*)
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" "$rebuild_rec" \
job-completed-before-rebuild
return 0
;;
esac
rebuild_image="$(gcr_record_field "$rebuild_rec" rebuild_image_id)"
if [ "$rebuild_image" != "$(gcr_record_field "$rebuild_rec" image_id)" ] \
|| ! gcr_idle_profile_compatible "$rebuild_rec" \
"$(gcr_record_field "$rebuild_rec" label)"; then
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" "$rebuild_rec" \
rebuild-profile-invalid
return 0
fi
if [ "$rebuild_state" = "rebuild_pending" ]; then
gcr_vm_host_key_prepare "$rebuild_job" "$rebuild_attempt" || return 1
rebuild_user_data="$(gcr_vm_host_key_userdata \
"$rebuild_job" "$rebuild_attempt")" || return 1
rebuild_requesting="$(printf '%s' "$rebuild_rec" | jq -c \
--arg now "$(gcr_now_epoch)" \
'.status = "rebuild_requesting"
| .rebuild_request_state = "requesting"
| .rebuild_requested_at = ($now | tonumber)')" || return 1
gcr_record_put "$rebuild_job" "$rebuild_attempt" "$rebuild_requesting" \
|| return 1
rebuild_action="$(gcr_vm_rebuild_request "$rebuild_vm" "$rebuild_image" \
"$rebuild_user_data")" \
|| {
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" \
"$rebuild_requesting" rebuild-request-uncertain
return 0
}
rebuild_rec="$(printf '%s' "$rebuild_requesting" | jq -c \
--arg action "$rebuild_action" \
'.status = "rebuild_running"
| .rebuild_request_state = "accepted"
| .rebuild_action_id = ($action | tonumber)')" || return 1
if ! gcr_record_put "$rebuild_job" "$rebuild_attempt" "$rebuild_rec"; then
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" \
"$rebuild_requesting" rebuild-action-state-write-failed
return 0
fi
gcr_event "vm-rebuild-started" "$rebuild_job" \
"{\"vm_id\":$rebuild_vm,\"action_id\":$rebuild_action}"
fi
rebuild_action="$(gcr_record_field "$rebuild_rec" rebuild_action_id)"
rebuild_action_state="$(gcr_vm_rebuild_action_status \
"$rebuild_vm" "$rebuild_action")" || {
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" "$rebuild_rec" \
rebuild-action-uncertain
return 0
}
[ "$rebuild_action_state" = success ] || return 0
rebuild_ip="$(gcr_vm_verify_rebuilt "$rebuild_vm" \
"$(gcr_record_field "$rebuild_rec" server_type)" \
"$(gcr_record_field "$rebuild_rec" location)" \
"$(gcr_record_field "$rebuild_rec" arch)" "$rebuild_image")" || {
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" "$rebuild_rec" \
rebuild-server-verification-failed
return 0
}
rebuild_ready="$(printf '%s' "$rebuild_rec" | jq -c \
--arg ip "$rebuild_ip" --arg now "$(gcr_now_epoch)" \
'.status = "pending_vm" | .bootstrapped = false | .ip = $ip
| .last_rebuild_action_id = .rebuild_action_id
| .last_rebuild_completed_at = ($now | tonumber)
| del(.rebuild_image_id, .rebuild_action_id,
.rebuild_request_state, .rebuild_requested_at)')" || return 1
gcr_record_put "$rebuild_job" "$rebuild_attempt" "$rebuild_ready" || return 1
gcr_event "vm-rebuild-completed" "$rebuild_job" \
"{\"vm_id\":$rebuild_vm,\"action_id\":$rebuild_action,\"ip\":\"$rebuild_ip\"}"
}
gcr_sweep_rebuilds() {
for f in $(gcr_active_records); do
rec="$(cat "$f")"
case "$(gcr_record_field "$rec" status)" in
rebuild_pending|rebuild_requesting|rebuild_running) ;;
*) continue ;;
esac
job_id="$(gcr_record_field "$rec" job_id)"
attempt="$(gcr_record_field "$rec" run_attempt)"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || continue
rec="$(gcr_record_get "$job_id" "$attempt")"
case "$(gcr_record_field "$rec" status)" in
rebuild_pending|rebuild_requesting|rebuild_running)
gcr_reconcile_rebuild "$job_id" "$attempt" "$rec" || \
gcr_log error --ns=sweep "rebuild reconcile failed job=$job_id"
;;
esac
gcr_lock_release "$key"
done
}
@@ -334,7 +501,6 @@ gcr_retry_deferred() {
}
gcr_sweep_stale_runners() {
gcr_lock_acquire idle-pool || return 0
oldIFS="$IFS"
IFS=,
for allowed_repo in ${GCR_ALLOWED_REPOS:-}; do
@@ -366,9 +532,9 @@ gcr_sweep_stale_runners() {
# Runner name stays tied to original VM across later job assignments.
rest="${rname#gcr-}"
jid="${rest%-*}"
if ! gcr_record_exists_for_vm_name "$rname"; then
gcr_log warn --ns=sweep "stale repo=$repo registration id=$rid name=$rname -> delete"
if gcr_gitea_delete_runner "$repo" "$rid"; then
if ! gcr_record_exists_for_runner "$repo" "$rname"; then
gcr_log warn --ns=sweep "stale repo=$repo registration id=$rid name=$rname -> retire"
if gcr_gitea_deregister_runner_exact "$repo" "$rname"; then
gcr_event "stale-runner-deleted" "${jid:-unknown}" "{\"repo\":\"$repo\",\"runner_id\":$rid,\"name\":\"$rname\"}"
else
gcr_log error --ns=sweep "failed deleting repo=$repo runner id=$rid"
@@ -383,7 +549,6 @@ EOF
IFS=,
done
IFS="$oldIFS"
gcr_lock_release idle-pool
}
# Runs SSH-push bootstrap for VMs that were created but not yet provisioned.
@@ -407,20 +572,8 @@ gcr_bootstrap_pending() {
repo="$(gcr_record_field "$rec" repo)"
label="$(gcr_record_field "$rec" label)"
vm_id="$(gcr_record_field "$rec" vm_id)"
runner_name="$(gcr_record_field "$rec" vm_name)"
if [ "$(gcr_record_field "$rec" reused_vm)" = "true" ]; then
if gcr_vm_runner_service "$vm_id" start \
&& gcr_vm_runner_service "$vm_id" health \
&& gcr_gitea_runner_disabled "$repo" "$runner_name" false; then
rec="$(printf '%s' "$rec" | jq -c '.bootstrapped = true | del(.reused_vm)')"
gcr_record_put "$job_id" "$attempt" "$rec"
else
gcr_gitea_runner_disabled "$repo" "$runner_name" true || true
fi
gcr_lock_release "$key"
continue
fi
runner_name="$(gcr_record_field "$rec" runner_name)"
[ -n "$runner_name" ] || runner_name="$(gcr_record_field "$rec" vm_name)"
state="$(gcr_gitea_job_state "$repo" "$job_id")" || {
gcr_lock_release "$key"
@@ -434,7 +587,8 @@ gcr_bootstrap_pending() {
completed:success|completed:cancelled|completed:skipped) ;;
*)
ip="$(gcr_vm_public_ip "$vm_id" || true)"
gcr_vm_collect_diagnostics "$vm_id" "$ip" "$job_id" "$state" || true
gcr_vm_collect_diagnostics "$vm_id" "$ip" "$job_id" \
"$state" "$attempt" || true
;;
esac
if gcr_vm_cleanup_start "$job_id" "$attempt" "$rec" \
@@ -467,9 +621,17 @@ gcr_bootstrap_pending() {
continue
}
ttl_min="$(gcr_record_field "$rec" ttl_min)"
known_hosts_file="$(gcr_vm_known_hosts_file \
"$job_id" "$attempt" "$ip")" || {
gcr_log warn --ns=alloc \
"host-key pin unavailable vm=$vm_id job=$job_id"
gcr_lock_release "$key"
continue
}
gcr_log info --ns=alloc "bootstrapping vm=$vm_id ip=$ip job=$job_id"
if gcr_vm_bootstrap_ssh "$ip" "$label" "$reg_token" "$runner_name"; then
if gcr_vm_bootstrap_ssh "$ip" "$label" "$reg_token" "$runner_name" \
"$known_hosts_file"; then
rec="$(printf '%s' "$rec" | jq -c '.bootstrapped = true | .ip = $ip' --arg ip "$ip")"
gcr_record_put "$job_id" "$attempt" "$rec"
gcr_event "vm-bootstrapped" "$job_id" "{\"vm_id\":$vm_id,\"ip\":\"$ip\"}"
@@ -524,10 +686,12 @@ gcr_reap_finished_jobs() {
gcr_tick() {
gcr_sweep_create_ambiguous
gcr_sweep_cleanup_pending
gcr_sweep_retiring_vms
gcr_sweep_ttl
gcr_reap_finished_jobs
gcr_sweep_orphan_vms
gcr_retry_deferred
gcr_sweep_rebuilds
gcr_bootstrap_pending
gcr_sweep_stale_runners
}
+4 -2
View File
@@ -162,7 +162,9 @@ gcr_count_active() {
for f in $(gcr_active_records); do
status="$(gcr_record_field "$(cat "$f")" status)"
case "$status" in
pending_vm|vm_active|cleanup_pending|create_ambiguous) count=$((count + 1)) ;;
create_pending|create_ambiguous|pending_vm|vm_active|retiring_vm|rebuild_pending|rebuild_requesting|rebuild_running|cleanup_pending)
count=$((count + 1))
;;
esac
done
printf '%s' "$count"
@@ -174,7 +176,7 @@ gcr_count_active_repo() {
for f in $(gcr_active_records); do
rec="$(cat "$f")"
case "$(gcr_record_field "$rec" status)" in
pending_vm|vm_active|cleanup_pending|create_ambiguous) ;;
create_pending|create_ambiguous|pending_vm|vm_active|retiring_vm|rebuild_pending|rebuild_requesting|rebuild_running|cleanup_pending) ;;
*) continue ;;
esac
[ "$(gcr_record_field "$rec" repo)" = "$repo" ] && count=$((count + 1))
+2 -2
View File
@@ -9,7 +9,7 @@
gawk,
gnugrep,
gnused,
openssl,
python3,
openssh,
}:
let
@@ -34,7 +34,7 @@ let
gawk
gnugrep
gnused
openssl
python3
openssh
];
+92 -15
View File
@@ -2,14 +2,31 @@
# Gitea API wrappers for gitea-runner-controller.
# Requires: GCR_GITEA_URL, GITEA_REGISTRATION_TOKEN_FILE, GITEA_ADMIN_TOKEN_FILE
gcr_gitea_curl() {
gcr_gitea_admin_token >/dev/null || return 1
gitea_auth_header="$(mktemp "${TMPDIR:-/tmp}/gcr-gitea-auth.XXXXXX")" \
|| return 1
chmod 0600 "$gitea_auth_header"
if ! printf 'Authorization: token ' > "$gitea_auth_header" \
|| ! tr -d '\n' < "$GITEA_ADMIN_TOKEN_FILE" >> "$gitea_auth_header" \
|| ! printf '\n' >> "$gitea_auth_header"; then
rm -f "$gitea_auth_header"
return 1
fi
gitea_curl_status=0
curl -H "@$gitea_auth_header" "$@" || gitea_curl_status="$?"
rm -f "$gitea_auth_header"
return "$gitea_curl_status"
}
gcr_gitea_registration_token() {
repo="$1"
token="$(gcr_gitea_admin_token)" || return 1
gcr_gitea_admin_token >/dev/null || return 1
owner="${repo%%/*}"
name="${repo#*/}"
curl -fsS -X POST -H "Authorization: token $token" \
gcr_gitea_curl -fsS -X POST \
"$GCR_GITEA_URL/api/v1/repos/$owner/$name/actions/runners/registration-token" \
| jq -r '.token'
| jq -er '.token | select(type == "string" and length > 0)'
}
gcr_gitea_admin_token() {
@@ -23,21 +40,34 @@ gcr_gitea_admin_token() {
# gcr_gitea_list_runners REPO — prints "id name" lines for repo runners.
gcr_gitea_list_runners() {
repo="$1"
token="$(gcr_gitea_admin_token)" || return 1
gcr_gitea_admin_token >/dev/null || return 1
owner="${repo%%/*}"
name="${repo#*/}"
curl -fsS -H "Authorization: token $token" \
"$GCR_GITEA_URL/api/v1/repos/$owner/$name/actions/runners" \
| jq -r '.runners[]? | "\(.id) \(.name)"'
page=1
while :; do
runner_page="$(gcr_gitea_curl -fsS \
"$GCR_GITEA_URL/api/v1/repos/$owner/$name/actions/runners?page=$page&limit=50")" \
|| return 1
printf '%s' "$runner_page" | jq -e \
'.runners | select(type == "array")
| all(.[]; (.id | type) == "number" and (.name | type) == "string")' \
>/dev/null || return 1
printf '%s' "$runner_page" \
| jq -r '.runners[] | "\(.id) \(.name)"' || return 1
runner_count="$(printf '%s' "$runner_page" | jq -er '.runners | length')" \
|| return 1
[ "$runner_count" -lt 50 ] && return 0
page=$((page + 1))
done
}
# gcr_gitea_list_org_repos OWNER — prints fully-qualified repository names.
gcr_gitea_list_org_repos() {
owner="$1"
token="$(gcr_gitea_admin_token)" || return 1
gcr_gitea_admin_token >/dev/null || return 1
page=1
while :; do
repos="$(curl -fsS -H "Authorization: token $token" \
repos="$(gcr_gitea_curl -fsS \
"$GCR_GITEA_URL/api/v1/orgs/$owner/repos?page=$page&limit=50")" || return 1
printf '%s' "$repos" | jq -r '.[]? | .full_name'
count="$(printf '%s' "$repos" | jq 'length')" || return 1
@@ -49,30 +79,77 @@ gcr_gitea_list_org_repos() {
# gcr_gitea_job_state REPO JOB_ID — prints "<status>:<conclusion>".
gcr_gitea_job_state() {
repo="$1"; job_id="$2"
token="$(gcr_gitea_admin_token)" || return 1
gcr_gitea_admin_token >/dev/null || return 1
owner="${repo%%/*}"
name="${repo#*/}"
curl -fsS -H "Authorization: token $token" \
gcr_gitea_curl -fsS \
"$GCR_GITEA_URL/api/v1/repos/$owner/$name/actions/jobs/$job_id" \
| jq -r '.status + ":" + (.conclusion // "")'
}
gcr_gitea_delete_runner() {
repo="$1"; id="$2"
token="$(gcr_gitea_admin_token)" || return 1
gcr_gitea_admin_token >/dev/null || return 1
owner="${repo%%/*}"
name="${repo#*/}"
curl -fsS -X DELETE -H "Authorization: token $token" \
gcr_gitea_curl -fsS -X DELETE \
"$GCR_GITEA_URL/api/v1/repos/$owner/$name/actions/runners/$id"
}
# Remove exactly one repository-scoped runner identity and confirm absence.
# A failed/ambiguous DELETE is safe only when a fresh list proves the exact
# name disappeared. Duplicate exact names fail closed for durable retry.
gcr_gitea_deregister_runner_exact() {
dereg_repo="$1"; dereg_name="$2"
[ -n "$dereg_repo" ] && [ -n "$dereg_name" ] || return 1
dereg_runners="$(gcr_gitea_list_runners "$dereg_repo")" || return 1
dereg_count=0
dereg_id=""
while read -r dereg_candidate_id dereg_candidate_name; do
[ "${dereg_candidate_name:-}" = "$dereg_name" ] || continue
case "$dereg_candidate_id" in ''|*[!0-9]*) return 1 ;; esac
dereg_count=$((dereg_count + 1))
dereg_id="$dereg_candidate_id"
done <<EOF
$dereg_runners
EOF
case "$dereg_count" in
0) return 0 ;;
1) ;;
*)
gcr_log error --ns=gitea \
"duplicate exact runner registrations repo=$dereg_repo name=$dereg_name"
return 1
;;
esac
if ! gcr_gitea_set_runner_disabled "$dereg_repo" "$dereg_id" true; then
gcr_log warn --ns=gitea \
"failed disabling runner repo=$dereg_repo name=$dereg_name"
return 1
fi
if ! gcr_gitea_delete_runner "$dereg_repo" "$dereg_id"; then
gcr_log warn --ns=gitea \
"runner DELETE uncertain repo=$dereg_repo name=$dereg_name; confirming"
fi
dereg_runners="$(gcr_gitea_list_runners "$dereg_repo")" || return 1
while read -r dereg_candidate_id dereg_candidate_name; do
[ "${dereg_candidate_name:-}" != "$dereg_name" ] || return 1
done <<EOF
$dereg_runners
EOF
return 0
}
gcr_gitea_set_runner_disabled() {
repo="$1"; id="$2"; disabled="$3"
case "$disabled" in true|false) ;; *) return 1 ;; esac
token="$(gcr_gitea_admin_token)" || return 1
gcr_gitea_admin_token >/dev/null || return 1
owner="${repo%%/*}"
name="${repo#*/}"
curl -fsS -X PATCH -H "Authorization: token $token" \
gcr_gitea_curl -fsS -X PATCH \
-H 'Content-Type: application/json' --data "{\"disabled\":$disabled}" \
"$GCR_GITEA_URL/api/v1/repos/$owner/$name/actions/runners/$id" >/dev/null
}
+360 -103
View File
@@ -28,18 +28,81 @@ gcr_hcloud_token() {
tr -d '\n' < "$HCLOUD_TOKEN_FILE"
}
gcr_vm_host_key_path() {
printf '%s/ssh-host-keys/%s' "$GCR_STATE_DIR" "$(gcr_alloc_key "$1" "$2")"
}
gcr_vm_host_key_prepare() {
host_key_path="$(gcr_vm_host_key_path "$1" "$2")"
if [ -s "$host_key_path" ] && [ -s "$host_key_path.pub" ]; then
return 0
fi
rm -f "$host_key_path" "$host_key_path.pub"
ssh-keygen -q -t ed25519 -N '' -C '' -f "$host_key_path" || return 1
chmod 0600 "$host_key_path"
chmod 0644 "$host_key_path.pub"
}
gcr_vm_host_key_userdata() {
host_key_path="$(gcr_vm_host_key_path "$1" "$2")"
[ -s "$host_key_path" ] && [ -s "$host_key_path.pub" ] || return 1
host_private_b64="$(base64 < "$host_key_path" | tr -d '\n')" || return 1
host_public_b64="$(base64 < "$host_key_path.pub" | tr -d '\n')" || return 1
cat <<EOF
#cloud-config
write_files:
- path: /etc/ssh/ssh_host_ed25519_key
owner: root:root
permissions: '0600'
encoding: b64
content: $host_private_b64
- path: /etc/ssh/ssh_host_ed25519_key.pub
owner: root:root
permissions: '0644'
encoding: b64
content: $host_public_b64
runcmd:
- [ sh, -c, 'systemctl restart sshd.service 2>/dev/null || systemctl restart ssh.service' ]
EOF
}
gcr_vm_known_hosts_file() {
known_job="$1"; known_attempt="$2"; known_ip="$3"
known_key_path="$(gcr_vm_host_key_path "$known_job" "$known_attempt")"
[ -s "$known_key_path.pub" ] || return 1
known_type="$(cut -d' ' -f1 < "$known_key_path.pub")"
known_key="$(cut -d' ' -f2 < "$known_key_path.pub")"
[ -n "$known_type" ] && [ -n "$known_key" ] || return 1
known_file="$known_key_path.known_hosts"
known_tmp="$(mktemp "$GCR_STATE_DIR/ssh-host-keys/.known-hosts.XXXXXX")" \
|| return 1
printf '%s %s %s\n' "$known_ip" "$known_type" "$known_key" > "$known_tmp" \
|| { rm -f "$known_tmp"; return 1; }
chmod 0600 "$known_tmp"
mv -f "$known_tmp" "$known_file" || return 1
printf '%s' "$known_file"
}
# All request state flows through files/exit codes, never command substitution
# ($( ) runs in a subshell and would strand GCR_REQ_FAILED/GCR_LAST_HTTP).
gcr_hcloud_req() {
# gcr_hcloud_req METHOD PATH [JSON_BODY]
# Body written to $GCR_LAST_BODY; exit 0 only on HTTP 2xx.
method="$1"; path="$2"; body="${3:-}"
token="$(gcr_hcloud_token)" || return 1
gcr_hcloud_token >/dev/null || return 1
GCR_LAST_BODY="$(mktemp "${TMPDIR:-/tmp}/gcr-resp.XXXXXX")"
auth_header="$(mktemp "${TMPDIR:-/tmp}/gcr-hcloud-auth.XXXXXX")" || return 1
chmod 0600 "$auth_header"
if ! printf 'Authorization: Bearer ' > "$auth_header" \
|| ! tr -d '\n' < "$HCLOUD_TOKEN_FILE" >> "$auth_header" \
|| ! printf '\n' >> "$auth_header"; then
rm -f "$auth_header"
return 1
fi
curl_status=0
if [ -n "$body" ]; then
code="$(printf '%s' "$body" | curl -sS -X "$method" \
-H "Authorization: Bearer $token" \
-H "@$auth_header" \
-H 'Content-Type: application/json' \
--data-binary @- \
-o "$GCR_LAST_BODY" \
@@ -47,11 +110,12 @@ gcr_hcloud_req() {
"$GCR_API$path")" || curl_status="$?"
else
code="$(curl -sS -X "$method" \
-H "Authorization: Bearer $token" \
-H "@$auth_header" \
-o "$GCR_LAST_BODY" \
-w '%{http_code}' \
"$GCR_API$path")" || curl_status="$?"
fi
rm -f "$auth_header"
case "$code" in ''|*[!0-9]*) code=000 ;; esac
GCR_LAST_CURL_STATUS="$curl_status"
GCR_LAST_HTTP="$code"
@@ -65,16 +129,29 @@ gcr_hcloud_req() {
}
gcr_vm_list_managed() {
if gcr_hcloud_req GET "/servers?label_selector=gitea-runner-controller%3Dmanaged&per_page=50"; then
jq -S '.servers' "$GCR_LAST_BODY"
fi
managed_servers='[]'
managed_page=1
while :; do
gcr_hcloud_req GET \
"/servers?label_selector=gitea-runner-controller%3Dmanaged&per_page=50&page=$managed_page" \
|| return 1
managed_servers="$(jq -c --argjson current "$managed_servers" \
'$current + (.servers // [])' "$GCR_LAST_BODY")" || return 1
managed_next="$(jq -r '.meta.pagination.next_page // 0' "$GCR_LAST_BODY")" \
|| return 1
case "$managed_next" in
0|null) printf '%s' "$managed_servers" | jq -S .; return 0 ;;
''|*[!0-9]*) return 1 ;;
*) managed_page="$managed_next" ;;
esac
done
}
# Exact deterministic create identity. Exit 0 = one match (prints id),
# 1 = confirmed absent, 2 = lookup failed or identity invariant violated.
gcr_vm_find_created() {
find_name="$1"; find_job="$2"; find_attempt="$3"; find_label="$4"
find_type="$5"; find_location="$6"; find_arch="$7"
find_type="$5"; find_location="$6"; find_arch="$7"; find_image="${8:-}"
if ! gcr_hcloud_req GET "/servers?name=$find_name"; then
return 2
fi
@@ -82,6 +159,7 @@ gcr_vm_find_created() {
--arg name "$find_name" --arg job "$find_job" --arg attempt "$find_attempt" \
--arg label "$find_label" --arg type "$find_type" \
--arg location "$find_location" --arg arch "$find_arch" \
--arg image "$find_image" \
'[.servers[] | select(
.name == $name
and .labels["gitea-runner-controller"] == "managed"
@@ -90,6 +168,7 @@ gcr_vm_find_created() {
and .labels["gcr.label"] == $label
and .labels["gcr.location"] == $location
and .labels["gcr.arch"] == $arch
and ($image == "" or .labels["gcr.image-id"] == $image)
and ((.server_type.name // .server_type) == $type))]' \
"$GCR_LAST_BODY")" || return 2
find_count="$(printf '%s' "$find_matches" | jq 'length')" || return 2
@@ -112,17 +191,26 @@ gcr_vm_record_create_ambiguous() {
ambiguous_job="$4"; ambiguous_attempt="$5"; ambiguous_repo="$6"
ambiguous_type="$7"; ambiguous_rate="$8"; ambiguous_location="$9"
shift 9; ambiguous_arch="$1"; ambiguous_http="$2"; ambiguous_curl="$3"
ambiguous_image="${4:-}"
ambiguous_budget_key="${5:-}"
ambiguous_budget_reserved="${6:-false}"
case "$ambiguous_budget_reserved" in true|false) ;; *) return 1 ;; esac
ambiguous_rec="$(jq -n --arg j "$ambiguous_job" --arg a "$ambiguous_attempt" \
--arg r "$ambiguous_repo" --arg l "$ambiguous_label" \
--arg t "$(gcr_now_epoch)" --arg vn "$ambiguous_name" \
--arg ttl "$ambiguous_ttl" --arg st "$ambiguous_type" \
--arg rate "$ambiguous_rate" --arg loc "$ambiguous_location" \
--arg arch "$ambiguous_arch" --arg http "$ambiguous_http" \
--arg curl "$ambiguous_curl" \
--arg curl "$ambiguous_curl" --arg image "$ambiguous_image" \
--arg budget_key "$ambiguous_budget_key" \
--argjson budget_reserved "$ambiguous_budget_reserved" \
'{job_id:$j, run_attempt:$a, repo:$r, label:$l,
created_at:$t, ttl_min:($ttl|tonumber), vm_id:"", vm_name:$vn,
server_type:$st, budget_rate:$rate, candidate_location:$loc,
candidate_arch:$arch, create_http:$http, create_curl_status:$curl,
candidate_arch:$arch, image_id:$image,
create_http:$http, create_curl_status:$curl,
budget_reservation_key:$budget_key,
budget_reservation_charged:$budget_reserved,
bootstrapped:false,
status:"create_ambiguous"}')"
gcr_record_put "$ambiguous_job" "$ambiguous_attempt" "$ambiguous_rec"
@@ -229,11 +317,14 @@ runcmd:
}
# gcr_vm_create NAME LABEL SERVER_TYPE TTL_MIN REG_TOKEN JOB_ID ATTEMPT REPO
# Caller holds admission lock. Reserves each affordable candidate before its
# create request; prints new server id, actual server type, and reserved rate.
# Reserves each affordable candidate under the short-lived budget lock, then
# releases it before provider I/O. Prints id, type, rate, location, arch, image.
gcr_vm_create() {
vm_name="$1"; label="$2"; ttl_min="$4"
reg_token="$5"; job_id="$6"; attempt="$7"; repo="$8"
create_nonce="${GCR_CREATE_NONCE:-$$-$(gcr_now_epoch)}"
gcr_vm_host_key_prepare "$job_id" "$attempt" || return 1
host_user_data="$(gcr_vm_host_key_userdata "$job_id" "$attempt")" || return 1
ttl_min="$(gcr_label_ttl "$label")" || return 1
candidates="$(gcr_label_candidates "$label")" || return 1
@@ -242,19 +333,34 @@ gcr_vm_create() {
[ -n "${candidate_type:-}" ] || continue
candidate_n=$((candidate_n + 1))
candidate_rate="$(gcr_server_hourly_rate "$candidate_type")" || continue
image_id="$(gcr_image_id_for_arch "$candidate_arch" "$label")" || {
gcr_log warn --ns=hcloud \
"skip candidate[$candidate_n] label=$label arch=$candidate_arch no image"
continue
}
budget_key="create-$(gcr_alloc_key "$job_id" "$attempt")-$create_nonce-$candidate_n"
if ! gcr_vm_record_create_ambiguous "$vm_name" "$label" "$ttl_min" \
"$job_id" "$attempt" "$repo" "$candidate_type" "$candidate_rate" \
"$candidate_loc" "$candidate_arch" not-requested 0 "$image_id" \
"$budget_key" false; then
return 1
fi
gcr_lock_acquire budget || return 1
if ! gcr_budget_can_add "$candidate_rate" "$ttl_min"; then
gcr_lock_release budget
gcr_log info --ns=hcloud "skip candidate[$candidate_n] label=$label type=$candidate_type over budget"
continue
fi
if ! gcr_budget_add "$candidate_rate" "$ttl_min"; then
if ! gcr_budget_add "$candidate_rate" "$ttl_min" "$budget_key"; then
gcr_lock_release budget
gcr_log error --ns=hcloud "budget reservation write failed label=$label type=$candidate_type"
return 1
fi
image_id="$(gcr_image_id_for_arch "$candidate_arch" "$label")" || {
gcr_log warn --ns=hcloud "skip candidate[$candidate_n] label=$label arch=$candidate_arch no image"
gcr_budget_sub "$candidate_rate" "$ttl_min" || return 1
continue
}
gcr_lock_release budget
budget_rec="$(gcr_record_get "$job_id" "$attempt")"
budget_rec="$(printf '%s' "$budget_rec" | jq -c \
'.budget_reservation_charged = true')" || return 2
gcr_record_put "$job_id" "$attempt" "$budget_rec" || return 2
payload="$(jq -n \
--arg name "$vm_name" \
--arg stype "$candidate_type" \
@@ -268,42 +374,66 @@ gcr_vm_create() {
--arg ts "$(date -u '+%s')" \
--arg ttl "$ttl_min" \
--arg ssh_key_id "${GCR_HCLOUD_SSH_KEY_ID:-}" \
--arg user_data "$host_user_data" \
--arg repo_safe "$(printf '%s' "$repo" | tr '/:' '--')" \
'{name:$name, server_type:$stype, image:$image, location:$loc,
start_after_create:true,
'{name:$name, server_type:$stype, image:$image, location:$loc,
user_data:$user_data,
start_after_create:true,
ssh_keys:(if $ssh_key_id == "" then [] else [$ssh_key_id | tonumber] end),
labels:{
"gitea-runner-controller":"managed",
"gcr.job-id":$jid, "gcr.run-attempt":$att,
"gcr.repo":$repo_safe, "gcr.label":$label,
"gcr.arch":$arch, "gcr.location":$loc,
"gcr.created-at":$ts, "gcr.ttl-min":$ttl}}')"
"gcr.repo":$repo_safe, "gcr.label":$label,
"gcr.arch":$arch, "gcr.location":$loc,
"gcr.image-id":$image,
"gcr.created-at":$ts, "gcr.ttl-min":$ttl}}')"
gcr_log info --ns=hcloud "try candidate[$candidate_n] label=$label type=$candidate_type arch=$candidate_arch loc=$candidate_loc"
if gcr_hcloud_req POST /servers "$payload"; then
printf '%s %s %s\n' \
"$(jq -r '.server.id' "$GCR_LAST_BODY")" "$candidate_type" "$candidate_rate"
return 0
created_id="$(jq -er '.server.id | select(type == "number")' \
"$GCR_LAST_BODY")" || created_id=""
if [ -n "$created_id" ]; then
printf '%s %s %s %s %s %s\n' "$created_id" "$candidate_type" \
"$candidate_rate" "$candidate_loc" "$candidate_arch" "$image_id"
return 0
fi
create_http="${GCR_LAST_HTTP:-000}"
create_curl="${GCR_LAST_CURL_STATUS:-0}"
if ! gcr_vm_record_create_ambiguous "$vm_name" "$label" "$ttl_min" \
"$job_id" "$attempt" "$repo" "$candidate_type" "$candidate_rate" \
"$candidate_loc" "$candidate_arch" "$create_http" "$create_curl" \
"$image_id" "$budget_key" true; then
gcr_log error --ns=hcloud \
"cannot persist malformed successful create job=$job_id type=$candidate_type"
fi
return 2
fi
create_http="${GCR_LAST_HTTP:-000}"
create_curl="${GCR_LAST_CURL_STATUS:-0}"
find_status=0
found_vm_id="$(gcr_vm_find_created "$vm_name" "$job_id" "$attempt" \
"$label" "$candidate_type" "$candidate_loc" "$candidate_arch")" \
"$label" "$candidate_type" "$candidate_loc" "$candidate_arch" \
"$image_id")" \
|| find_status="$?"
if [ "$find_status" -eq 0 ]; then
printf '%s %s %s\n' "$found_vm_id" "$candidate_type" "$candidate_rate"
printf '%s %s %s %s %s %s\n' "$found_vm_id" "$candidate_type" \
"$candidate_rate" "$candidate_loc" "$candidate_arch" "$image_id"
return 0
fi
if [ "$find_status" -eq 1 ] \
&& gcr_create_explicitly_rejected "$create_http"; then
if ! gcr_budget_sub "$candidate_rate" "$ttl_min"; then
gcr_lock_acquire budget || return 1
if ! gcr_budget_sub "$candidate_rate" "$ttl_min" \
"rollback-$budget_key"; then
gcr_lock_release budget
gcr_log error --ns=hcloud "budget reservation rollback failed label=$label type=$candidate_type"
return 1
fi
gcr_lock_release budget
else
if ! gcr_vm_record_create_ambiguous "$vm_name" "$label" "$ttl_min" \
"$job_id" "$attempt" "$repo" "$candidate_type" "$candidate_rate" \
"$candidate_loc" "$candidate_arch" "$create_http" "$create_curl"; then
"$candidate_loc" "$candidate_arch" "$create_http" "$create_curl" \
"$image_id" "$budget_key" true; then
gcr_log error --ns=hcloud "cannot persist ambiguous create job=$job_id type=$candidate_type"
fi
return 2
@@ -348,17 +478,22 @@ gcr_vm_cleanup_pending() {
cleanup_rate="$(gcr_record_field "$cleanup_rec" budget_rate)"
cleanup_ttl="$(gcr_record_field "$cleanup_rec" ttl_min)"
cleanup_refund_key="$(gcr_alloc_key "$cleanup_job" "$cleanup_attempt")"
gcr_budget_refund_once "$cleanup_refund_key" "$cleanup_rate" "$cleanup_ttl" \
|| return 1
gcr_lock_acquire budget || return 1
if ! gcr_budget_refund_once "$cleanup_refund_key" "$cleanup_rate" \
"$cleanup_ttl"; then
gcr_lock_release budget
return 1
fi
gcr_lock_release budget
cleanup_rec="$(printf '%s' "$cleanup_rec" | jq -c '.cleanup_budget_released = true')"
gcr_record_put "$cleanup_job" "$cleanup_attempt" "$cleanup_rec" || return 1
fi
gcr_record_del "$cleanup_job" "$cleanup_attempt"
}
# Persist intent before DELETE. Normal lifecycle teardown never changes budget;
# failed creation passes REFUND_BUDGET=true to release its unused reservation.
gcr_vm_cleanup_start() {
# Persist cleanup ownership without provider I/O. Callers can use this while a
# short-lived coordination lock is held, release it, then run cleanup_pending.
gcr_vm_cleanup_intent() {
cleanup_job="$1"; cleanup_attempt="$2"; cleanup_source="$3"
cleanup_reason="$4"; cleanup_refund="$5"
cleanup_rec="$(printf '%s' "$cleanup_source" | jq -c \
@@ -368,7 +503,17 @@ gcr_vm_cleanup_start() {
| .cleanup_refund_budget = $refund
| .cleanup_vm_destroyed = false
| .cleanup_budget_released = false')"
gcr_record_put "$cleanup_job" "$cleanup_attempt" "$cleanup_rec" || return 1
gcr_record_put "$cleanup_job" "$cleanup_attempt" "$cleanup_rec"
}
# Persist intent before DELETE. Normal lifecycle teardown never changes budget;
# failed creation passes REFUND_BUDGET=true to release its unused reservation.
gcr_vm_cleanup_start() {
cleanup_job="$1"; cleanup_attempt="$2"; cleanup_source="$3"
cleanup_reason="$4"; cleanup_refund="$5"
gcr_vm_cleanup_intent "$cleanup_job" "$cleanup_attempt" "$cleanup_source" \
"$cleanup_reason" "$cleanup_refund" || return 1
cleanup_rec="$(gcr_record_get "$cleanup_job" "$cleanup_attempt")"
gcr_vm_cleanup_pending "$cleanup_job" "$cleanup_attempt" "$cleanup_rec"
}
@@ -378,13 +523,17 @@ gcr_vm_record_created() {
record_job="$1"; record_attempt="$2"; record_repo="$3"; record_label="$4"
record_created="$5"; record_vm_id="$6"; record_vm_name="$7"
record_ttl="$8"; record_type="$9"; shift 9; record_rate="$1"
record_location="${2:-}"; record_arch="${3:-}"; record_image="${4:-}"
record_rec="$(jq -n --arg j "$record_job" --arg a "$record_attempt" \
--arg r "$record_repo" --arg l "$record_label" --arg t "$record_created" \
--arg v "$record_vm_id" --arg vn "$record_vm_name" --arg ttl "$record_ttl" \
--arg st "$record_type" --arg rate "$record_rate" \
--arg loc "$record_location" --arg arch "$record_arch" \
--arg image "$record_image" \
'{job_id:$j, run_attempt:$a, repo:$r, label:$l,
created_at:$t, ttl_min:($ttl|tonumber), vm_id:($v|tonumber),
vm_name:$vn, server_type:$st, budget_rate:$rate,
vm_name:$vn, runner_name:$vn, server_type:$st, budget_rate:$rate,
location:$loc, arch:$arch, image_id:$image,
bootstrapped:false, status:"pending_vm"}')"
gcr_record_put "$record_job" "$record_attempt" "$record_rec" && return 0
@@ -405,6 +554,67 @@ gcr_vm_public_ip() {
fi
}
# POST rebuild starts an asynchronous clean-image replacement. Output is the
# validated action id; every malformed or mismatched response is uncertain.
gcr_vm_rebuild_request() {
rebuild_vm_id="$1"; rebuild_image_id="$2"; rebuild_user_data="${3:-}"
case "$rebuild_vm_id" in ''|0|*[!0-9]*) return 1 ;; esac
[ -n "$rebuild_image_id" ] || return 1
rebuild_payload="$(jq -n --arg image "$rebuild_image_id" \
--arg user_data "$rebuild_user_data" \
'{image:$image, user_data:$user_data}')" || return 1
gcr_hcloud_req POST "/servers/$rebuild_vm_id/actions/rebuild" \
"$rebuild_payload" || return 1
jq -er --arg vm "$rebuild_vm_id" \
'.action
| select((.id | type) == "number")
| select(.command == "rebuild")
| select(.status == "running" or .status == "success")
| select([.resources[]? | select(.type == "server") | (.id | tostring)] == [$vm])
| .id' "$GCR_LAST_BODY"
}
# Prints running or success. Provider-reported errors and malformed/mismatched
# action data fail closed; caller owns the durable cleanup transition.
gcr_vm_rebuild_action_status() {
rebuild_vm_id="$1"; rebuild_action_id="$2"
case "$rebuild_vm_id:$rebuild_action_id" in
*[!0-9:]*|0:*|*:0|:*|*::*|*:) return 1 ;;
esac
gcr_hcloud_req GET "/actions/$rebuild_action_id" || return 1
rebuild_status="$(jq -er --arg vm "$rebuild_vm_id" \
--arg action "$rebuild_action_id" \
'.action
| select((.id | tostring) == $action)
| select(.command == "rebuild")
| select([.resources[]? | select(.type == "server") | (.id | tostring)] == [$vm])
| .status
| select(. == "running" or . == "success" or . == "error")' \
"$GCR_LAST_BODY")" || return 1
[ "$rebuild_status" != error ] || return 1
printf '%s' "$rebuild_status"
}
# Successful action is insufficient by itself: verify provider server identity,
# immutable profile, clean image, running state, and current public IP.
gcr_vm_verify_rebuilt() {
verify_vm_id="$1"; verify_type="$2"; verify_location="$3"
verify_arch="$4"; verify_image="$5"
gcr_hcloud_req GET "/servers/$verify_vm_id" || return 1
jq -er --arg vm "$verify_vm_id" --arg type "$verify_type" \
--arg location "$verify_location" --arg arch "$verify_arch" \
--arg image "$verify_image" \
'.server
| select((.id | tostring) == $vm)
| select(.status == "running")
| select((.server_type.name // "") == $type)
| select((.server_type.architecture // "") == $arch)
| select((.datacenter.location.name // "") == $location)
| select((.image.id | tostring) == $image)
| .public_net.ipv4.ip
| select(type == "string" and length > 0)' "$GCR_LAST_BODY"
}
# Stop idle runners so Gitea cannot schedule work before atomic reuse claim.
# The controller starts the service only after the claim record is written.
gcr_vm_runner_service() {
@@ -417,11 +627,13 @@ gcr_vm_runner_service() {
ip="$(gcr_vm_public_ip "$vm_id")" || return 1
[ -n "$ip" ] || return 1
test -n "${GCR_SSH_PRIVKEY_FILE:-}" && test -r "$GCR_SSH_PRIVKEY_FILE" || return 1
test -n "${GCR_SSH_KNOWN_HOSTS_FILE:-}" \
&& test -r "$GCR_SSH_KNOWN_HOSTS_FILE" || return 1
key_tmp="$(mktemp "${TMPDIR:-/tmp}/gcr-runner-sshkey.XXXXXX")"
cat "$GCR_SSH_PRIVKEY_FILE" > "$key_tmp"
printf '\n' >> "$key_tmp"
chmod 0600 "$key_tmp"
ssh_opts="-i $key_tmp -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=5 -o BatchMode=yes"
ssh_opts="-i $key_tmp -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$GCR_SSH_KNOWN_HOSTS_FILE -o ConnectTimeout=5 -o BatchMode=yes"
if timeout 30 ssh $ssh_opts "root@$ip" "$service_command"; then
rm -f "$key_tmp"
return 0
@@ -431,7 +643,7 @@ gcr_vm_runner_service() {
}
gcr_vm_collect_diagnostics() {
vm_id="$1"; ip="$2"; job_id="$3"; reason="$4"
vm_id="$1"; ip="$2"; job_id="$3"; reason="$4"; diag_attempt="${5:-}"
[ "${GCR_DESTROY_DIAGNOSTICS:-1}" = "1" ] || return 0
[ -n "$ip" ] || return 0
@@ -439,13 +651,22 @@ gcr_vm_collect_diagnostics() {
gcr_log warn --ns=hcloud "skip diagnostics vm=$vm_id job=$job_id reason=$reason: SSH key unavailable"
return 0
}
diag_known_hosts="${GCR_SSH_KNOWN_HOSTS_FILE:-}"
if [ -n "$diag_attempt" ]; then
diag_known_hosts="$(gcr_vm_known_hosts_file \
"$job_id" "$diag_attempt" "$ip")" || diag_known_hosts=""
fi
test -n "$diag_known_hosts" && test -r "$diag_known_hosts" || {
gcr_log warn --ns=hcloud "skip diagnostics vm=$vm_id job=$job_id reason=$reason: SSH host key unavailable"
return 0
}
key_tmp="$(mktemp "${TMPDIR:-/tmp}/gcr-diag-sshkey.XXXXXX")"
cat "$GCR_SSH_PRIVKEY_FILE" > "$key_tmp"
printf '\n' >> "$key_tmp"
chmod 0600 "$key_tmp"
timeout_sec="${GCR_DESTROY_DIAGNOSTICS_TIMEOUT_SEC:-20}"
ssh_opts="-i $key_tmp -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=5 -o BatchMode=yes"
ssh_opts="-i $key_tmp -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$diag_known_hosts -o ConnectTimeout=5 -o BatchMode=yes"
diag_out="$(mktemp "${TMPDIR:-/tmp}/gcr-diag-out.XXXXXX")"
gcr_log warn --ns=hcloud "pre-destroy diagnostics begin vm=$vm_id ip=$ip job=$job_id reason=$reason timeout=${timeout_sec}s"
@@ -472,83 +693,105 @@ gcr_vm_collect_diagnostics() {
return 0
}
# Finish a terminal job under its allocation lock. Healthy bootstrapped VMs
# become idle until their existing billing boundary; every unsafe transition
# uses durable cleanup_pending teardown instead.
# Retry durable repository-runner retirement. Generic idle is written only
# after exact-name absence is confirmed and the persisted VM profile is valid.
gcr_vm_retire_pending() {
retire_job="$1"; retire_attempt="$2"; retire_rec="$3"
[ "$(gcr_record_field "$retire_rec" status)" = "retiring_vm" ] || return 1
retire_vm_id="$(gcr_record_field "$retire_rec" vm_id)"
retire_expires="$(gcr_record_field "$retire_rec" idle_expires_at)"
retire_created="$(gcr_record_field "$retire_rec" created_at)"
retire_ttl="$(gcr_record_field "$retire_rec" ttl_min)"
case "$retire_vm_id:$retire_expires:$retire_created:$retire_ttl" in
*[!0-9:]*|0:*|:*|*::*|*:) return 1 ;;
esac
retire_now="$(gcr_now_epoch)"
retire_hard_expires="$((retire_created + retire_ttl * 60))"
if [ "$retire_now" -ge "$retire_expires" ] \
|| [ "$retire_now" -ge "$retire_hard_expires" ]; then
gcr_vm_cleanup_start "$retire_job" "$retire_attempt" "$retire_rec" \
retirement-expired false
return "$?"
fi
retire_repo="$(gcr_record_field "$retire_rec" retirement_repo)"
retire_runner="$(gcr_record_field "$retire_rec" retirement_runner_name)"
if ! gcr_gitea_deregister_runner_exact "$retire_repo" "$retire_runner"; then
gcr_log warn --ns=gitea \
"runner retirement pending job=$retire_job repo=$retire_repo name=$retire_runner"
return 2
fi
retire_idle="$(printf '%s' "$retire_rec" | jq -c \
'.status = "idle_vm"
| .repo = "" | .label = "" | .runner_name = ""
| .bootstrapped = false
| del(.retirement_repo, .retirement_runner_name)')" || return 1
gcr_record_put "$retire_job" "$retire_attempt" "$retire_idle" || return 1
gcr_event "vm-idle" "$retire_job" \
"{\"vm_id\":$retire_vm_id,\"expires_at\":$retire_expires}"
return 0
}
# Finish a terminal job under its allocation lock. Registration retirement is
# durable; every unsafe or incompatible transition uses cleanup_pending.
gcr_vm_finish_terminal() {
finish_job="$1"; finish_attempt="$2"; finish_rec="$3"; finish_state="$4"
finish_via="${5:-webhook}"
finish_vm_id="$(gcr_record_field "$finish_rec" vm_id)"
if [ -n "$finish_vm_id" ] && [ "$finish_vm_id" != "null" ] \
&& [ "$finish_vm_id" != "0" ]; then
case "$finish_state" in
completed:success|completed:cancelled|completed:skipped) ;;
completed:*)
finish_ip="$(gcr_vm_public_ip "$finish_vm_id" || true)"
gcr_vm_collect_diagnostics "$finish_vm_id" "$finish_ip" \
"$finish_job" "$finish_state" || true
;;
esac
fi
if finish_idle_rec="$(gcr_record_idle_json "$finish_rec")"; then
gcr_lock_acquire idle-pool || return 2
finish_repo="$(gcr_record_field "$finish_rec" repo)"
finish_runner="$(gcr_record_field "$finish_rec" vm_name)"
if ! gcr_vm_runner_service "$finish_vm_id" health; then
gcr_lock_release idle-pool
finish_cleanup_reason=idle-health-failed
elif ! gcr_gitea_runner_disabled "$finish_repo" "$finish_runner" true \
|| ! gcr_vm_runner_service "$finish_vm_id" stop; then
gcr_lock_release idle-pool
finish_cleanup_reason=idle-stop-failed
elif ! gcr_record_put "$finish_job" "$finish_attempt" "$finish_idle_rec"; then
gcr_lock_release idle-pool
finish_cleanup_reason=idle-state-write-failed
else
finish_expires="$(gcr_record_field "$finish_idle_rec" idle_expires_at)"
gcr_lock_release idle-pool
gcr_event "vm-idle" "$finish_job" \
"{\"vm_id\":$finish_vm_id,\"expires_at\":$finish_expires,\"via\":\"$finish_via\"}"
gcr_log info --ns=sweep \
"job=$finish_job terminal ($finish_state), retaining vm=$finish_vm_id until $finish_expires"
case "$finish_vm_id" in
''|0|null|*[!0-9]*)
gcr_record_del "$finish_job" "$finish_attempt"
return 0
fi
;;
esac
if gcr_vm_cleanup_start "$finish_job" "$finish_attempt" "$finish_rec" \
"$finish_cleanup_reason" false; then
gcr_event "vm-destroyed" "$finish_job" \
"{\"vm_id\":$finish_vm_id,\"reason\":\"$finish_cleanup_reason\",\"via\":\"$finish_via\"}"
else
gcr_event "vm-cleanup-pending" "$finish_job" \
"{\"vm_id\":$finish_vm_id,\"reason\":\"$finish_cleanup_reason\",\"via\":\"$finish_via\"}"
fi
return 0
fi
case "$finish_state" in
completed:success|completed:cancelled|completed:skipped) ;;
completed:*)
finish_ip="$(gcr_vm_public_ip "$finish_vm_id" || true)"
gcr_vm_collect_diagnostics "$finish_vm_id" "$finish_ip" \
"$finish_job" "$finish_state" "$finish_attempt" || true
;;
esac
if [ -n "$finish_vm_id" ] && [ "$finish_vm_id" != "null" ] \
&& [ "$finish_vm_id" != "0" ]; then
if gcr_vm_cleanup_start "$finish_job" "$finish_attempt" "$finish_rec" \
"$finish_state" false; then
gcr_event "vm-destroyed" "$finish_job" \
"{\"vm_id\":$finish_vm_id,\"reason\":\"$finish_state\",\"via\":\"$finish_via\"}"
if finish_retiring_rec="$(gcr_record_retiring_json "$finish_rec")" \
&& gcr_idle_profile_compatible "$finish_retiring_rec" \
"$(gcr_record_field "$finish_rec" label)"; then
if ! gcr_record_put "$finish_job" "$finish_attempt" "$finish_retiring_rec"; then
finish_cleanup_reason=retirement-state-write-failed
else
gcr_event "vm-cleanup-pending" "$finish_job" \
"{\"vm_id\":$finish_vm_id,\"reason\":\"$finish_state\",\"via\":\"$finish_via\"}"
gcr_event "vm-retiring" "$finish_job" \
"{\"vm_id\":$finish_vm_id,\"via\":\"$finish_via\"}"
gcr_vm_retire_pending "$finish_job" "$finish_attempt" \
"$finish_retiring_rec"
return "$?"
fi
else
gcr_record_del "$finish_job" "$finish_attempt"
finish_cleanup_reason=idle-profile-invalid
fi
if gcr_vm_cleanup_start "$finish_job" "$finish_attempt" "$finish_rec" \
"$finish_cleanup_reason" false; then
gcr_event "vm-destroyed" "$finish_job" \
"{\"vm_id\":$finish_vm_id,\"reason\":\"$finish_cleanup_reason\",\"via\":\"$finish_via\"}"
else
gcr_event "vm-cleanup-pending" "$finish_job" \
"{\"vm_id\":$finish_vm_id,\"reason\":\"$finish_cleanup_reason\",\"via\":\"$finish_via\"}"
fi
return 0
}
# Bootstrap delivery is SSH-push from the controller. The MicroOS snapshot's
# cloud-init cannot fetch user-data (Hetzner datasource DHCP failure), so the
# controller drives provisioning over SSH using GCR_SSH_PRIVKEY_FILE, whose
# public half is authorized on every ephemeral VM (project ssh-key injection).
# Package bootstrap is SSH-pushed because image provisioning over cloud-init is
# not reliable enough for the full install. Cloud-init is limited to installing
# the controller-generated per-lifecycle SSH host key; strict verification must
# succeed before this token-bearing payload is sent.
gcr_bootstrap_script() {
# gcr_bootstrap_script LABEL REG_TOKEN TTL_MIN RUNNER_NAME -> POSIX sh payload
label="$1"; reg_token="$2"; ttl_min="$3"; runner_name="$4"
reg_token_b64="$(printf '%s' "$reg_token" | base64 | tr -d '\n')" \
|| return 1
nix_conf='accept-flake-config = true
experimental-features = nix-command flakes
http2 = false
@@ -581,9 +824,6 @@ CFGEOF
cat > /usr/local/sbin/gcr-runner-start <<STARTEOF
#!/bin/sh
set -eu
if [ ! -f /var/lib/gitea-runner/.runner ]; then
/usr/local/bin/gitea-runner register --no-interactive --instance $GCR_GITEA_URL --token $reg_token --name $runner_name --labels $label:host --config /etc/gitea-runner/config.yaml
fi
exec /usr/local/bin/gitea-runner daemon --config /etc/gitea-runner/config.yaml
STARTEOF
chmod 0700 /usr/local/sbin/gcr-runner-start
@@ -662,6 +902,18 @@ chmod 0755 /usr/local/bin/gitea-runner
INSEOF
chmod 0700 /usr/local/sbin/gcr-install
/usr/local/sbin/gcr-install
token_file=/run/gcr-registration-token
umask 077
printf '%s' '$reg_token_b64' | base64 -d > "\$token_file"
trap 'rm -f "\$token_file"' EXIT HUP INT TERM
if [ ! -s /var/lib/gitea-runner/.runner ]; then
/usr/local/bin/gitea-runner register --no-interactive \
--instance '$GCR_GITEA_URL' --token "\$(cat "\$token_file")" \
--name '$runner_name' --labels '$label:host' \
--config /etc/gitea-runner/config.yaml
fi
rm -f "\$token_file"
trap - EXIT HUP INT TERM
systemctl daemon-reload
systemctl enable --now gitea-runner.service
BSEOF
@@ -670,15 +922,20 @@ BSEOF
# gcr_vm_bootstrap_ssh IP LABEL REG_TOKEN — blocking; returns ssh exit status.
gcr_vm_bootstrap_ssh() {
ip="$1"; label="$2"; reg_token="$3"; runner_name="$4"
known_hosts_file="${5:-${GCR_SSH_KNOWN_HOSTS_FILE:-}}"
test -n "${GCR_SSH_PRIVKEY_FILE:-}" && test -r "$GCR_SSH_PRIVKEY_FILE" || {
gcr_log error --ns=hcloud "GCR_SSH_PRIVKEY_FILE missing or unreadable"
return 1
}
test -n "$known_hosts_file" && test -r "$known_hosts_file" || {
gcr_log error --ns=hcloud "SSH known-hosts file missing or unreadable"
return 1
}
key_tmp="$(mktemp "${TMPDIR:-/tmp}/gcr-sshkey.XXXXXX")"
cat "$GCR_SSH_PRIVKEY_FILE" > "$key_tmp"
printf '\n' >> "$key_tmp"
chmod 0600 "$key_tmp"
SSH_OPTS="-i $key_tmp -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=5 -o BatchMode=yes"
SSH_OPTS="-i $key_tmp -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$known_hosts_file -o ConnectTimeout=5 -o BatchMode=yes"
waited=0
until ssh $SSH_OPTS "root@$ip" true 2>/dev/null; do
+239 -29
View File
@@ -9,6 +9,8 @@
gcr_state_init() {
test -n "${GCR_STATE_DIR:-}" || { echo "GCR_STATE_DIR is not set" >&2; return 1; }
mkdir -p "$GCR_STATE_DIR/jobs" "$GCR_STATE_DIR/budget"
mkdir -p "$GCR_STATE_DIR/ssh-host-keys"
chmod 0700 "$GCR_STATE_DIR/ssh-host-keys"
touch "$GCR_STATE_DIR/events.jsonl"
}
@@ -20,16 +22,37 @@ gcr_record_path() {
printf '%s/jobs/%s.json' "$GCR_STATE_DIR" "$(gcr_alloc_key "$1" "$2")"
}
# mkdir(2) atomicity guard. Owner metadata lets a new controller process
# recover locks stranded by a crashed webhook or reconciler process.
# Atomic hard-link publication includes owner metadata before lock visibility.
# Legacy directory locks remain readable for safe upgrade/recovery.
gcr_lock_owner_read() {
if [ -f "$1" ]; then
cat "$1" 2>/dev/null || true
else
cat "$1/owner" 2>/dev/null || true
fi
}
gcr_lock_publish() {
gcr_publish_dir="$1"
gcr_publish_tmp="$gcr_publish_dir.owner.$$"
rm -f "$gcr_publish_tmp"
printf '%s %s\n' "$$" "$(gcr_now_epoch)" > "$gcr_publish_tmp" || return 1
if ln -T "$gcr_publish_tmp" "$gcr_publish_dir" 2>/dev/null; then
rm -f "$gcr_publish_tmp"
return 0
fi
rm -f "$gcr_publish_tmp"
return 1
}
gcr_lock_takeover() {
gcr_takeover_dir="$1"
gcr_takeover_old="$gcr_takeover_dir.reclaim.$$"
# Rename is atomic: exactly one reclaimer can move the observed stale
# directory. Never rm -rf the active lock pathname during recovery.
rm -rf "$gcr_takeover_old"
mv "$gcr_takeover_dir" "$gcr_takeover_old" 2>/dev/null || return 1
if mkdir "$gcr_takeover_dir" 2>/dev/null; then
printf '%s %s\n' "$$" "$(gcr_now_epoch)" > "$gcr_takeover_dir/owner"
if gcr_lock_publish "$gcr_takeover_dir"; then
rm -rf "$gcr_takeover_old"
return 0
fi
@@ -40,12 +63,11 @@ gcr_lock_takeover() {
gcr_lock_acquire() {
gcr_lock_key="$1"
gcr_lock_dir="$(printf '%s/jobs/.lock.%s' "$GCR_STATE_DIR" "$gcr_lock_key")"
if mkdir "$gcr_lock_dir" 2>/dev/null; then
printf '%s %s\n' "$$" "$(gcr_now_epoch)" > "$gcr_lock_dir/owner"
if gcr_lock_publish "$gcr_lock_dir"; then
return 0
fi
gcr_lock_owner="$(cat "$gcr_lock_dir/owner" 2>/dev/null || true)"
gcr_lock_owner="$(gcr_lock_owner_read "$gcr_lock_dir")"
if [ -z "$gcr_lock_owner" ]; then
# A crash between mkdir and owner write leaves no PID. Give a live
# creator a short initialization window, then unblock hard TTL work.
@@ -71,7 +93,11 @@ gcr_lock_acquire() {
}
gcr_lock_release() {
rm -rf "$(printf '%s/jobs/.lock.%s' "$GCR_STATE_DIR" "$1")"
gcr_release_dir="$(printf '%s/jobs/.lock.%s' "$GCR_STATE_DIR" "$1")"
gcr_release_owner="$(gcr_lock_owner_read "$gcr_release_dir")"
set -- $gcr_release_owner
[ "${1:-}" = "$$" ] || return 0
rm -rf "$gcr_release_dir"
}
gcr_record_get() {
@@ -88,6 +114,9 @@ gcr_record_put() {
gcr_record_del() {
rm -f "$(gcr_record_path "$1" "$2")"
rm -f "$GCR_STATE_DIR/ssh-host-keys/$(gcr_alloc_key "$1" "$2")" \
"$GCR_STATE_DIR/ssh-host-keys/$(gcr_alloc_key "$1" "$2").pub" \
"$GCR_STATE_DIR/ssh-host-keys/$(gcr_alloc_key "$1" "$2").known_hosts"
}
gcr_record_field() {
@@ -98,9 +127,10 @@ gcr_now_epoch() {
date -u '+%s'
}
# Healthy bootstrapped VMs remain reusable until next billing-hour boundary,
# but never beyond profile hard TTL. Prints updated idle record when safe.
gcr_record_idle_json() {
# Healthy bootstrapped VMs can enter registration retirement until the next
# billing-hour boundary, but never beyond original hard TTL. The VM is not
# generic idle until the old repository registration is confirmed absent.
gcr_record_retiring_json() {
gcr_idle_rec="$1"
[ "$(gcr_record_field "$gcr_idle_rec" bootstrapped)" = "true" ] || return 1
@@ -124,21 +154,40 @@ gcr_record_idle_json() {
[ "$gcr_idle_expires" -le "$gcr_idle_hard_expires" ] \
|| gcr_idle_expires="$gcr_idle_hard_expires"
gcr_idle_repo="$(gcr_record_field "$gcr_idle_rec" repo)"
gcr_idle_runner="$(gcr_record_field "$gcr_idle_rec" runner_name)"
[ -n "$gcr_idle_runner" ] \
|| gcr_idle_runner="$(gcr_record_field "$gcr_idle_rec" vm_name)"
[ -n "$gcr_idle_repo" ] && [ -n "$gcr_idle_runner" ] || return 1
printf '%s' "$gcr_idle_rec" | jq -c \
--arg now "$gcr_idle_now" --arg expires "$gcr_idle_expires" \
'.status = "idle_vm"
--arg repo "$gcr_idle_repo" --arg runner "$gcr_idle_runner" \
'.status = "retiring_vm"
| .bootstrapped = false
| .retirement_repo = $repo
| .retirement_runner_name = $runner
| .idle_since = ($now | tonumber)
| .idle_expires_at = ($expires | tonumber)'
}
# Compatibility alias for callers using the old helper name. Output follows
# the new fail-closed retirement contract, not the old directly-idle contract.
gcr_record_idle_json() {
gcr_record_retiring_json "$1"
}
gcr_idle_record_unexpired() {
gcr_idle_rec="$1"
[ "$(gcr_record_field "$gcr_idle_rec" status)" = "idle_vm" ] || return 1
[ "$(gcr_record_field "$gcr_idle_rec" bootstrapped)" = "true" ] || return 1
gcr_idle_now="$(gcr_now_epoch)"
gcr_idle_vm_id="$(gcr_record_field "$gcr_idle_rec" vm_id)"
gcr_idle_vm_name="$(gcr_record_field "$gcr_idle_rec" vm_name)"
gcr_idle_type="$(gcr_record_field "$gcr_idle_rec" server_type)"
gcr_idle_location="$(gcr_record_field "$gcr_idle_rec" location)"
gcr_idle_arch="$(gcr_record_field "$gcr_idle_rec" arch)"
gcr_idle_image="$(gcr_record_field "$gcr_idle_rec" image_id)"
gcr_idle_expires="$(gcr_record_field "$gcr_idle_rec" idle_expires_at)"
gcr_idle_created="$(gcr_record_field "$gcr_idle_rec" created_at)"
gcr_idle_ttl="$(gcr_record_field "$gcr_idle_rec" ttl_min)"
@@ -147,11 +196,42 @@ gcr_idle_record_unexpired() {
esac
case "$gcr_idle_vm_id" in ''|0|*[!0-9]*) return 1 ;; esac
[ -n "$gcr_idle_vm_name" ] || return 1
[ -n "$gcr_idle_type" ] && [ -n "$gcr_idle_location" ] \
&& [ -n "$gcr_idle_arch" ] && [ -n "$gcr_idle_image" ] || return 1
gcr_idle_hard_expires="$((gcr_idle_created + gcr_idle_ttl * 60))"
[ "$gcr_idle_now" -lt "$gcr_idle_expires" ] \
&& [ "$gcr_idle_now" -lt "$gcr_idle_hard_expires" ]
}
# Generic idle reuse is profile-based, never repository- or label-based. The
# exact persisted server tuple and clean image must be valid for the new label.
gcr_idle_profile_compatible() {
gcr_compat_rec="$1"; gcr_compat_label="$2"
gcr_compat_type="$(gcr_record_field "$gcr_compat_rec" server_type)"
gcr_compat_location="$(gcr_record_field "$gcr_compat_rec" location)"
gcr_compat_arch="$(gcr_record_field "$gcr_compat_rec" arch)"
gcr_compat_image="$(gcr_record_field "$gcr_compat_rec" image_id)"
[ -n "$gcr_compat_type" ] && [ -n "$gcr_compat_location" ] \
&& [ -n "$gcr_compat_arch" ] && [ -n "$gcr_compat_image" ] || return 1
gcr_compat_wanted_image="$(gcr_image_id_for_arch \
"$gcr_compat_arch" "$gcr_compat_label")" || return 1
[ "$gcr_compat_image" = "$gcr_compat_wanted_image" ] || return 1
while read -r gcr_compat_candidate_type gcr_compat_candidate_location \
gcr_compat_candidate_arch; do
[ -n "${gcr_compat_candidate_type:-}" ] || continue
if [ "$gcr_compat_candidate_type" = "$gcr_compat_type" ] \
&& [ "$gcr_compat_candidate_location" = "$gcr_compat_location" ] \
&& [ "$gcr_compat_candidate_arch" = "$gcr_compat_arch" ]; then
return 0
fi
done <<EOF
$(gcr_label_candidates "$gcr_compat_label")
EOF
return 1
}
gcr_idle_record_usable() {
gcr_idle_rec="$1"
gcr_idle_record_unexpired "$gcr_idle_rec" || return 1
@@ -174,26 +254,32 @@ gcr_claim_idle() {
for gcr_claim_file in $(gcr_active_records); do
gcr_claim_rec="$(cat "$gcr_claim_file")"
[ "$(gcr_record_field "$gcr_claim_rec" status)" = "idle_vm" ] || continue
[ "$(gcr_record_field "$gcr_claim_rec" repo)" = "$gcr_claim_repo" ] || continue
[ "$(gcr_record_field "$gcr_claim_rec" label)" = "$gcr_claim_label" ] || continue
gcr_idle_record_usable "$gcr_claim_rec" || continue
gcr_idle_profile_compatible "$gcr_claim_rec" "$gcr_claim_label" || continue
gcr_claim_old_job="$(gcr_record_field "$gcr_claim_rec" job_id)"
gcr_claim_old_attempt="$(gcr_record_field "$gcr_claim_rec" run_attempt)"
gcr_claim_vm_id="$(gcr_record_field "$gcr_claim_rec" vm_id)"
gcr_claim_image="$(gcr_record_field "$gcr_claim_rec" image_id)"
gcr_record_vm_owned_elsewhere "$gcr_claim_vm_id" \
"$gcr_claim_old_job" "$gcr_claim_old_attempt" && continue
gcr_claim_now="$(gcr_now_epoch)"
gcr_claim_new="$(printf '%s' "$gcr_claim_rec" | jq -c \
--arg job "$gcr_claim_job" --arg attempt "$gcr_claim_attempt" \
--arg repo "$gcr_claim_repo" --arg label "$gcr_claim_label" \
--arg runner "gcr-${gcr_claim_job}-${gcr_claim_attempt}" \
--arg image "$gcr_claim_image" \
--arg now "$gcr_claim_now" \
'.job_id = $job | .run_attempt = $attempt
| .repo = $repo | .label = $label | .status = "pending_vm"
| .repo = $repo | .label = $label | .runner_name = $runner
| .status = "rebuild_pending"
| .bootstrapped = false
| .reused_vm = true
| .assigned_at = ($now | tonumber)
| del(.idle_since, .idle_expires_at)')"
| .rebuild_image_id = $image
| .rebuild_action_id = ""
| .rebuild_request_state = "pending"
| .assigned_at = ($now | tonumber)
| del(.idle_since, .idle_expires_at,
.retirement_repo, .retirement_runner_name)')"
if ! gcr_record_put "$gcr_claim_job" "$gcr_claim_attempt" "$gcr_claim_new"; then
gcr_lock_release idle-pool
return 1
@@ -216,11 +302,44 @@ gcr_record_exists_for_vm_id() {
return 1
}
gcr_record_exists_for_vm_name() {
gcr_lookup="$1"
# Provider sweeps also honor deterministic create ownership before vm_id is
# known locally. This closes the POST-success/state-write race without locks.
gcr_record_exists_for_vm_owner() {
gcr_owner_vm_id="$1"; gcr_owner_vm_name="$2"
gcr_owner_job="$3"; gcr_owner_attempt="$4"
gcr_record_exists_for_vm_id "$gcr_owner_vm_id" && return 0
[ -n "$gcr_owner_job" ] && [ -n "$gcr_owner_attempt" ] || return 1
gcr_owner_rec="$(gcr_record_get "$gcr_owner_job" "$gcr_owner_attempt")"
[ -n "$gcr_owner_rec" ] || return 1
[ "$(gcr_record_field "$gcr_owner_rec" vm_name)" = "$gcr_owner_vm_name" ] \
|| return 1
case "$(gcr_record_field "$gcr_owner_rec" status)" in
create_pending|create_ambiguous|pending_vm|vm_active|retiring_vm|idle_vm|rebuild_pending|rebuild_requesting|rebuild_running|cleanup_pending)
return 0
;;
esac
return 1
}
gcr_record_exists_for_runner() {
gcr_lookup_repo="$1"; gcr_lookup_runner="$2"
for gcr_lookup_file in $(gcr_active_records); do
[ "$(gcr_record_field "$(cat "$gcr_lookup_file")" vm_name)" = "$gcr_lookup" ] \
&& return 0
gcr_lookup_rec="$(cat "$gcr_lookup_file")"
case "$(gcr_record_field "$gcr_lookup_rec" status)" in
retiring_vm)
gcr_lookup_owner_repo="$(gcr_record_field "$gcr_lookup_rec" retirement_repo)"
gcr_lookup_owner_runner="$(gcr_record_field "$gcr_lookup_rec" retirement_runner_name)"
;;
create_pending|pending_vm|vm_active|rebuild_pending|rebuild_requesting|rebuild_running)
gcr_lookup_owner_repo="$(gcr_record_field "$gcr_lookup_rec" repo)"
gcr_lookup_owner_runner="$(gcr_record_field "$gcr_lookup_rec" runner_name)"
;;
*) continue ;;
esac
if [ "$gcr_lookup_owner_repo" = "$gcr_lookup_repo" ] \
&& [ "$gcr_lookup_owner_runner" = "$gcr_lookup_runner" ]; then
return 0
fi
done
return 1
}
@@ -247,6 +366,7 @@ gcr_event() {
# Exit-code contract: 0 = remains under budget, 1 = would exceed cap.
gcr_budget_can_add() {
rate="$1"; ttl_min="$2"
gcr_budget_recover_pending || return 1
month="$(date -u '+%Y-%m')"
file="$GCR_STATE_DIR/budget/$month"
current="$(cat "$file" 2>/dev/null || echo 0)"
@@ -272,25 +392,115 @@ gcr_budget_write() {
fi
}
# Caller holds admission lock and has already checked gcr_budget_can_add.
# Caller holds budget lock. Transaction intent makes aggregate updates
# recoverable when a process exits between the total write and commit marker.
gcr_budget_add() {
rate="$1"; ttl_min="$2"
if [ "$#" -ge 3 ]; then
budget_txn_key="$3"
else
budget_key_tmp="$(mktemp "$GCR_STATE_DIR/budget/.transaction-key.XXXXXX")" \
|| return 1
budget_txn_key="add-${budget_key_tmp##*.transaction-key.}"
rm -f "$budget_key_tmp"
fi
gcr_budget_recover_pending || return 1
month="$(date -u '+%Y-%m')"
file="$GCR_STATE_DIR/budget/$month"
current="$(cat "$file" 2>/dev/null || echo 0)"
projected="$(awk -v c="$current" -v r="$rate" -v t="$ttl_min" 'BEGIN {printf "%.4f", c + r * t / 60}')"
gcr_budget_write "$file" "$projected"
gcr_budget_transaction "$budget_txn_key" "$current" "$projected"
}
# Caller holds admission lock and is rolling back a matching budget addition.
# Caller holds budget lock and is rolling back a matching budget addition.
gcr_budget_sub() {
rate="$1"; ttl_min="$2"
if [ "$#" -ge 3 ]; then
budget_txn_key="$3"
else
budget_key_tmp="$(mktemp "$GCR_STATE_DIR/budget/.transaction-key.XXXXXX")" \
|| return 1
budget_txn_key="sub-${budget_key_tmp##*.transaction-key.}"
rm -f "$budget_key_tmp"
fi
gcr_budget_recover_pending || return 1
month="$(date -u '+%Y-%m')"
file="$GCR_STATE_DIR/budget/$month"
current="$(cat "$file" 2>/dev/null || echo 0)"
projected="$(awk -v c="$current" -v r="$rate" -v t="$ttl_min" \
'BEGIN {v = c - r * t / 60; if (v < 0) v = 0; printf "%.4f", v}')"
gcr_budget_write "$file" "$projected"
gcr_budget_transaction "$budget_txn_key" "$current" "$projected"
}
gcr_budget_transaction() {
budget_txn_key="$1"; budget_txn_before="$2"; budget_txn_after="$3"
case "$budget_txn_key" in ''|*[!A-Za-z0-9_.-]*) return 1 ;; esac
budget_txn_month="$(date -u '+%Y-%m')"
budget_txn_file="$GCR_STATE_DIR/budget/$budget_txn_month"
budget_txn_root="$GCR_STATE_DIR/budget/transactions/$budget_txn_month"
budget_txn_dir="$budget_txn_root/$budget_txn_key"
mkdir -p "$budget_txn_root" || return 1
if [ -d "$budget_txn_dir" ]; then
gcr_budget_transaction_recover "$budget_txn_key"
return "$?"
fi
mkdir "$budget_txn_dir" 2>/dev/null || return 1
printf '%s\n' "$budget_txn_before" > "$budget_txn_dir/before" || return 1
printf '%s\n' "$budget_txn_after" > "$budget_txn_dir/after" || return 1
if ! gcr_budget_write "$budget_txn_file" "$budget_txn_after"; then
budget_txn_current="$(cat "$budget_txn_file" 2>/dev/null || echo 0)"
if [ "$budget_txn_current" = "$budget_txn_before" ]; then
rm -rf "$budget_txn_dir"
fi
return 1
fi
printf 'committed\n' > "$budget_txn_dir/status" || return 1
}
gcr_budget_transaction_recover() {
budget_recover_key="$1"
budget_recover_month="$(date -u '+%Y-%m')"
budget_recover_dir="$GCR_STATE_DIR/budget/transactions/$budget_recover_month/$budget_recover_key"
[ -d "$budget_recover_dir" ] || return 1
[ "$(cat "$budget_recover_dir/status" 2>/dev/null || true)" != committed ] \
|| return 0
budget_recover_before="$(cat "$budget_recover_dir/before" 2>/dev/null || true)"
budget_recover_after="$(cat "$budget_recover_dir/after" 2>/dev/null || true)"
if [ -z "$budget_recover_before" ] || [ -z "$budget_recover_after" ]; then
# Both metadata files are written before the aggregate total. A crash
# before either file completes therefore cannot have changed budget.
rm -rf "$budget_recover_dir"
return 0
fi
budget_recover_file="$GCR_STATE_DIR/budget/$budget_recover_month"
budget_recover_current="$(cat "$budget_recover_file" 2>/dev/null || echo 0)"
if [ "$budget_recover_current" = "$budget_recover_before" ]; then
gcr_budget_write "$budget_recover_file" "$budget_recover_after" || return 1
elif [ "$budget_recover_current" != "$budget_recover_after" ]; then
return 1
fi
printf 'committed\n' > "$budget_recover_dir/status" || return 1
}
gcr_budget_recover_pending() {
budget_pending_month="$(date -u '+%Y-%m')"
budget_pending_root="$GCR_STATE_DIR/budget/transactions/$budget_pending_month"
[ -d "$budget_pending_root" ] || return 0
for budget_pending_dir in "$budget_pending_root"/*; do
[ -d "$budget_pending_dir" ] || continue
budget_pending_key="${budget_pending_dir##*/}"
gcr_budget_transaction_recover "$budget_pending_key" || return 1
done
}
gcr_budget_transaction_committed() {
budget_committed_key="$1"
budget_committed_month="$(date -u '+%Y-%m')"
budget_committed_dir="$GCR_STATE_DIR/budget/transactions/$budget_committed_month/$budget_committed_key"
[ -d "$budget_committed_dir" ] || return 1
gcr_budget_transaction_recover "$budget_committed_key" || return 1
[ "$(cat "$budget_committed_dir/status" 2>/dev/null || true)" = committed ]
}
# Claim is durable before credit. Existing claim means credit is consumed:
@@ -315,10 +525,10 @@ gcr_budget_refund_once() {
if ! printf '%s %s\n' "$refund_rate" "$refund_ttl" > "$refund_claim/intent"; then
return 1
fi
gcr_budget_sub "$refund_rate" "$refund_ttl" || return 1
gcr_budget_sub "$refund_rate" "$refund_ttl" "refund-$refund_key" || return 1
printf 'refunded\n' > "$refund_claim/status" || return 1
}
gcr_active_records() {
grep -El '"status"[[:space:]]*:[[:space:]]*"(pending_vm|vm_active|idle_vm|deferred|cleanup_pending|create_ambiguous)"' "$GCR_STATE_DIR"/jobs/*.json 2>/dev/null || true
grep -El '"status"[[:space:]]*:[[:space:]]*"(create_pending|create_ambiguous|pending_vm|vm_active|retiring_vm|idle_vm|rebuild_pending|rebuild_requesting|rebuild_running|deferred|cleanup_pending)"' "$GCR_STATE_DIR"/jobs/*.json 2>/dev/null || true
}
+67 -35
View File
@@ -59,7 +59,12 @@ gcr_read_request() {
esac
[ "$content_length" -le 65536 ] || { gcr_respond 413 "payload too large"; exit 0; }
gcr_body="$(head -c "$content_length")"
GCR_BODY_FILE="$(mktemp "${TMPDIR:-/tmp}/gcr-webhook-body.XXXXXX")" \
|| return 1
chmod 0600 "$GCR_BODY_FILE"
trap 'rm -f "$GCR_BODY_FILE"' EXIT HUP INT TERM
head -c "$content_length" > "$GCR_BODY_FILE" || return 1
gcr_body="$(cat "$GCR_BODY_FILE")"
}
gcr_verify_signature() {
@@ -67,10 +72,18 @@ gcr_verify_signature() {
gcr_log error --ns=webhook "GITEA_WEBHOOK_SECRET_FILE missing"
return 1
}
secret="$(cat "$GITEA_WEBHOOK_SECRET_FILE")"
expected="$(printf '%s' "$gcr_body" \
| openssl dgst -sha256 -hmac "$secret" -hex \
| awk '{print $NF}')"
test -r "${GCR_BODY_FILE:-}" || return 1
expected="$(python3 - "$GITEA_WEBHOOK_SECRET_FILE" "$GCR_BODY_FILE" <<'PY'
import hashlib
import hmac
import pathlib
import sys
secret = pathlib.Path(sys.argv[1]).read_bytes().rstrip(b"\n")
body = pathlib.Path(sys.argv[2]).read_bytes()
print(hmac.new(secret, body, hashlib.sha256).hexdigest())
PY
)" || return 1
# NOTE(yukkop): shell string compare is not constant-time; acceptable here
# because the secret is high-entropy and bodies are signed, not encrypted.
[ "$expected" = "$gcr_hdr_signature" ]
@@ -154,20 +167,11 @@ gcr_alloc() {
reused="$(gcr_record_get "$job_id" "$attempt")"
vm_id="$(gcr_record_field "$reused" vm_id)"
vm_name="$(gcr_record_field "$reused" vm_name)"
if gcr_vm_runner_service "$vm_id" start \
&& gcr_vm_runner_service "$vm_id" health \
&& gcr_gitea_runner_disabled "$repo" "$vm_name" false; then
reused="$(gcr_record_get "$job_id" "$attempt")"
reused="$(printf '%s' "$reused" | jq -c '.bootstrapped = true | del(.reused_vm)')"
gcr_record_put "$job_id" "$attempt" "$reused"
else
gcr_gitea_runner_disabled "$repo" "$vm_name" true || true
gcr_event "vm-reuse-start-failed" "$job_id" "{\"vm_id\":$vm_id}"
fi
gcr_lock_release admission
gcr_lock_release "$key"
gcr_event "vm-reused" "$job_id" "{\"vm_id\":$vm_id,\"label\":\"$label\"}"
RESPONSE_CODE=202; RESPONSE_BODY="reused $vm_name"
gcr_event "vm-rebuild-queued" "$job_id" \
"{\"vm_id\":$vm_id,\"label\":\"$label\"}"
RESPONSE_CODE=202; RESPONSE_BODY="rebuilding $vm_name"
return 0
fi
if [ "$claim_status" -eq 2 ]; then
@@ -184,20 +188,25 @@ gcr_alloc() {
return 0
fi
reg_token="$(gcr_gitea_registration_token "$repo")" || {
gcr_record_del "$job_id" "$attempt"
gcr_lock_release admission
gcr_lock_release "$key"
gcr_event "token-error" "$job_id" "{}"
RESPONSE_CODE=202; RESPONSE_BODY="registration token unavailable"
return 0
}
vm_name="gcr-${job_id}-${attempt}"
created_at="$(gcr_now_epoch)"
create_pending="$(jq -n --arg j "$job_id" --arg a "$attempt" \
--arg r "$repo" --arg l "$label" --arg t "$created_at" \
--arg ttl "$ttl_min" --arg vn "$vm_name" \
'{job_id:$j, run_attempt:$a, repo:$r, label:$l,
created_at:$t, ttl_min:($ttl|tonumber), vm_id:"", vm_name:$vn,
runner_name:$vn, bootstrapped:false, status:"create_pending"}')"
if ! gcr_record_put "$job_id" "$attempt" "$create_pending"; then
gcr_lock_release admission
gcr_lock_release "$key"
RESPONSE_CODE=202; RESPONSE_BODY="VM state write failed"
return 0
fi
gcr_lock_release admission
create_status=0
created="$(gcr_vm_create "$vm_name" "$label" "$server_type" "$ttl_min" \
"$reg_token" "$job_id" "$attempt" "$repo")" || create_status="$?"
"" "$job_id" "$attempt" "$repo")" || create_status="$?"
if [ "$create_status" -ne 0 ]; then
if [ "$create_status" -eq 2 ]; then
gcr_event "vm-create-ambiguous" "$job_id" "{}"
@@ -207,21 +216,27 @@ gcr_alloc() {
gcr_event "vm-create-failed" "$job_id" "{}"
RESPONSE_CODE=202; RESPONSE_BODY="VM creation failed"
fi
gcr_lock_release admission
gcr_lock_release "$key"
return 0
fi
set -- $created
vm_id="$1"; actual_server_type="$2"; actual_rate="$3"
actual_location="${4:-}"; actual_arch="${5:-}"; actual_image="${6:-}"
if ! gcr_vm_record_created "$job_id" "$attempt" "$repo" "$label" \
"$created_at" "$vm_id" "$vm_name" "$ttl_min" \
"$actual_server_type" "$actual_rate"; then
gcr_lock_release admission
"$actual_server_type" "$actual_rate" "$actual_location" \
"$actual_arch" "$actual_image"; then
created_rec="$(gcr_record_get "$job_id" "$attempt")"
gcr_vm_record_create_ambiguous "$vm_name" "$label" "$ttl_min" \
"$job_id" "$attempt" "$repo" "$actual_server_type" \
"$actual_rate" "$actual_location" "$actual_arch" \
"${GCR_LAST_HTTP:-201}" "${GCR_LAST_CURL_STATUS:-0}" \
"$actual_image" \
"$(gcr_record_field "$created_rec" budget_reservation_key)" true || true
gcr_lock_release "$key"
RESPONSE_CODE=202; RESPONSE_BODY="VM state write failed"
return 0
fi
gcr_lock_release admission
gcr_lock_release "$key"
gcr_event "vm-created" "$job_id" "{\"vm_id\":$vm_id,\"label\":\"$label\",\"ttl_min\":$ttl_min}"
@@ -230,6 +245,7 @@ gcr_alloc() {
gcr_deallocate() {
job_id="$1"; attempt="$2"; new_status="$3"
expected_repo="${4:-}"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || return 0
@@ -239,6 +255,13 @@ gcr_deallocate() {
gcr_lock_release "$key"
return 0
fi
if [ -n "$expected_repo" ] \
&& [ "$(gcr_record_field "$rec" repo)" != "$expected_repo" ]; then
gcr_log warn --ns=alloc \
"repository mismatch for terminal job=$job_id expected=$expected_repo"
gcr_lock_release "$key"
return 0
fi
case "$(gcr_record_field "$rec" status)" in
pending_vm|vm_active) ;;
@@ -259,10 +282,17 @@ gcr_deallocate() {
}
gcr_mark_in_progress() {
job_id="$1"; attempt="$2"
job_id="$1"; attempt="$2"; expected_repo="${3:-}"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || return 0
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ -n "$expected_repo" ] \
&& [ "$(gcr_record_field "$rec" repo)" != "$expected_repo" ]; then
gcr_log warn --ns=alloc \
"repository mismatch for in-progress job=$job_id expected=$expected_repo"
gcr_lock_release "$key"
return 0
fi
case "$(gcr_record_field "$rec" status)" in
pending_vm|vm_active)
rec="$(printf '%s' "$rec" | jq -c '.status = "vm_active"')"
@@ -292,7 +322,8 @@ gcr_handle_webhook() {
repo="$(printf '%s' "$gcr_body" | jq -r '.repository.full_name // ""')"
labels_json="$(printf '%s' "$gcr_body" | jq -c '.workflow_job.labels // []')"
[ -n "$action" ] || { gcr_respond 400 "malformed payload"; exit 0; }
[ -n "$action" ] && [ -n "$repo" ] \
|| { gcr_respond 400 "malformed payload"; exit 0; }
case "$job_id:$attempt" in
*[!0-9:]*|:*|*::*|*:|0:*)
gcr_respond 400 "malformed payload"; exit 0
@@ -305,11 +336,12 @@ gcr_handle_webhook() {
gcr_log info --ns=alloc "queued job=$job_id repo=$repo code=$RESPONSE_CODE $RESPONSE_BODY"
;;
in_progress)
gcr_mark_in_progress "$job_id" "$attempt"
gcr_mark_in_progress "$job_id" "$attempt" "$repo"
RESPONSE_CODE=204
;;
completed)
gcr_deallocate "$job_id" "$attempt" "completed:${conclusion:-unknown}"
gcr_deallocate "$job_id" "$attempt" \
"completed:${conclusion:-unknown}" "$repo"
RESPONSE_CODE=204
;;
*)
@@ -33,9 +33,11 @@ let
nativeBuildInputs = [
pkgs.coreutils
pkgs.dash
pkgs.gawk
pkgs.gnugrep
pkgs.gnused
pkgs.jq
pkgs.openssh
];
LOG_SH = ../../../package/gitea-runner-controller/log.sh;
STATE_SH = ../../../package/gitea-runner-controller/state.sh;
@@ -88,15 +88,23 @@ gcr_hcloud_req() {
}
created="$(gcr_vm_create gcr-9001-1 gross-nix-x86-highmem ccx53 480 reg-token 9001 1 hectic-lab/util.nix)"
test "$created" = '9001 ccx53 0.8550'
test "$created" = '9001 ccx53 0.8550 hel1 amd64 424242'
gcr_record_del 9001 1
test "$(wc -l < "$calls" | tr -d ' ')" = '3'
jq -e 'select(.server_type == "ccx53" and .location == "nbg1" and .labels["gcr.arch"] == "amd64" and .labels["gcr.label"] == "gross-nix-x86-highmem" and .labels["gcr.ttl-min"] == "480")' "$calls" >/dev/null
jq -e 'select(.server_type == "ccx53" and .location == "nbg1" and
(.user_data | startswith("#cloud-config\n")) and
(.user_data | contains("/etc/ssh/ssh_host_ed25519_key")) and
.labels["gcr.arch"] == "amd64" and
.labels["gcr.image-id"] == "424242" and
.labels["gcr.label"] == "gross-nix-x86-highmem" and
.labels["gcr.ttl-min"] == "480")' "$calls" >/dev/null
jq -e 'select(.server_type == "ccx53" and .location == "fsn1" and .labels["gcr.arch"] == "amd64")' "$calls" >/dev/null
jq -e 'select(.server_type == "ccx53" and .location == "hel1" and .labels["gcr.arch"] == "amd64")' "$calls" >/dev/null
if jq -e 'select(.server_type != "ccx53" or .labels["gcr.arch"] != "amd64")' "$calls" >/dev/null; then
printf 'highmem VM creation attempted non-ccx53 or non-amd64 candidate\n' >&2
exit 1
fi
gcr_record_del 9001 1
# Standard allocation charges actual fallback type after cx23 capacity failures.
rm -f "$calls" "$GCR_STATE_DIR/budget/$(date -u '+%Y-%m')"
@@ -129,6 +137,9 @@ test "$(wc -l < "$GCR_STATE_DIR/lookups" | tr -d ' ')" = '3'
jq -e -s 'map(.server_type) == ["cx23", "cx23", "cx23", "cx33"]' "$calls" >/dev/null
test "$(gcr_server_hourly_rate cx33)" = '0.008'
test "$(cat "$GCR_STATE_DIR/budget/$(date -u '+%Y-%m')")" = '0.0640'
jq -e 'select(.server_type == "cx33" and .location == "nbg1" and
.arch == "amd64" and .image_id == "424242")' \
"$(gcr_record_path 9002 1)" >/dev/null
# Ambiguous 5xx response adopts only exact deterministic managed identity.
gcr_record_del 9002 1
@@ -142,7 +153,7 @@ gcr_hcloud_req() {
return 1
fi
GCR_LAST_HTTP=200
printf '%s\n' '{"servers":[{"id":9010,"name":"gcr-9010-1","server_type":{"name":"cx23"},"labels":{"gitea-runner-controller":"managed","gcr.job-id":"9010","gcr.run-attempt":"1","gcr.label":"nix","gcr.location":"nbg1","gcr.arch":"amd64"}}]}' > "$GCR_LAST_BODY"
printf '%s\n' '{"servers":[{"id":9010,"name":"gcr-9010-1","server_type":{"name":"cx23"},"labels":{"gitea-runner-controller":"managed","gcr.job-id":"9010","gcr.run-attempt":"1","gcr.label":"nix","gcr.location":"nbg1","gcr.arch":"amd64","gcr.image-id":"424242"}}]}' > "$GCR_LAST_BODY"
}
gcr_alloc 9010 1 hectic-lab/util.nix '["nix"]'
test "$RESPONSE_BODY" = 'allocated gcr-9010-1'
@@ -183,7 +194,7 @@ gcr_hcloud_req() {
test "$1" = GET
GCR_LAST_BODY="$GCR_STATE_DIR/last-body.json"
GCR_LAST_HTTP=200
printf '%s\n' '{"servers":[{"id":9012,"name":"gcr-9012-1","server_type":{"name":"cx23"},"labels":{"gitea-runner-controller":"managed","gcr.job-id":"9012","gcr.run-attempt":"1","gcr.label":"nix","gcr.location":"nbg1","gcr.arch":"amd64"}}]}' > "$GCR_LAST_BODY"
printf '%s\n' '{"servers":[{"id":9012,"name":"gcr-9012-1","server_type":{"name":"cx23"},"labels":{"gitea-runner-controller":"managed","gcr.job-id":"9012","gcr.run-attempt":"1","gcr.label":"nix","gcr.location":"nbg1","gcr.arch":"amd64","gcr.image-id":"424242"}}]}' > "$GCR_LAST_BODY"
}
gcr_vm_destroy() { printf 'unexpected-destroy %s\n' "$1" >> "$GCR_STATE_DIR/ambiguity-destroys"; return 1; }
gcr_sweep_create_ambiguous
@@ -191,6 +202,9 @@ recovered_rec="$(gcr_record_get 9012 1)"
test "$(gcr_record_field "$recovered_rec" status)" = pending_vm
test "$(gcr_record_field "$recovered_rec" vm_id)" = 9012
test "$(gcr_record_field "$recovered_rec" server_type)" = cx23
test "$(gcr_record_field "$recovered_rec" location)" = nbg1
test "$(gcr_record_field "$recovered_rec" arch)" = amd64
test "$(gcr_record_field "$recovered_rec" image_id)" = 424242
test "$(gcr_record_field "$recovered_rec" budget_rate)" = 0.004
test "$(cat "$GCR_STATE_DIR/budget/$(date -u '+%Y-%m')")" = '0.0320'
test ! -e "$GCR_STATE_DIR/ambiguity-destroys"
@@ -219,6 +233,25 @@ test "$(wc -l < "$calls" | tr -d ' ')" = '3'
jq -e -s 'all(.server_type == "cx23")' "$calls" >/dev/null
test "$(cat "$GCR_STATE_DIR/budget/$(date -u '+%Y-%m')")" = '0.0000'
# Crash recovery completes a transaction exactly once when the aggregate is at
# either durable endpoint, and discards metadata never followed by a write.
month="$(date -u '+%Y-%m')"
txn_root="$GCR_STATE_DIR/budget/transactions/$month"
mkdir -p "$txn_root/recover-after"
printf '0.0000\n' > "$txn_root/recover-after/before"
printf '0.0320\n' > "$txn_root/recover-after/after"
printf '0.0000\n' > "$GCR_STATE_DIR/budget/$month"
gcr_budget_recover_pending
test "$(cat "$GCR_STATE_DIR/budget/$month")" = 0.0320
test "$(cat "$txn_root/recover-after/status")" = committed
gcr_budget_recover_pending
test "$(cat "$GCR_STATE_DIR/budget/$month")" = 0.0320
mkdir -p "$txn_root/incomplete"
printf '0.0320\n' > "$txn_root/incomplete/before"
gcr_budget_recover_pending
test ! -e "$txn_root/incomplete"
# Deferred allocation keeps cleanup ownership and reservation across failed
# DELETE, failed post-DELETE state update, and cleanup-owned 404 retry.
rm -f "$calls" "$GCR_STATE_DIR/budget/$(date -u '+%Y-%m')"
@@ -231,7 +264,7 @@ gcr_record_put() {
count="$(cat "$record_put_count" 2>/dev/null || echo 0)"
count=$((count + 1))
printf '%s\n' "$count" > "$record_put_count"
case "$count" in 1|3|5|8) return 1 ;; esac
case "$count" in 4|6|8|11) return 1 ;; esac
tmp="$(mktemp "$(dirname "$(gcr_record_path "$1" "$2")")/.tmp.XXXXXX")"
printf '%s\n' "$3" > "$tmp"
mv -f "$tmp" "$(gcr_record_path "$1" "$2")"
@@ -10,310 +10,363 @@ set -eu
. "$WEBHOOK_SH"
gcr_state_init
export GCR_ALLOWED_REPOS='hinterland/hearth'
export GCR_CONCURRENCY_CAP=2
export GCR_PER_REPO_CAP=1
export GCR_ALLOWED_REPOS='hinterland/hearth,hectic-lab/util.nix'
export GCR_CONCURRENCY_CAP=3
export GCR_PER_REPO_CAP=2
export GCR_RECONCILE_INTERVAL_SEC=60
export GCR_NIX_IMAGE_ID=424242
export GCR_IMAGE_ID=313131
NOW=2800
gcr_now_epoch() { printf '%s' "$NOW"; }
# Gitea API hardening: strict token schema, complete pagination, malformed-list
# rejection, and disable-before-delete retirement.
export GCR_GITEA_URL=https://gitea.example.test
export GITEA_ADMIN_TOKEN_FILE="$GCR_STATE_DIR/admin-token"
printf 'admin-token\n' > "$GITEA_ADMIN_TOKEN_FILE"
hardening_calls="$GCR_STATE_DIR/hardening-calls"
curl_mode=malformed-token
curl() {
for arg do url="$arg"; done
printf '%s\n' "$url" >> "$hardening_calls"
case "$curl_mode" in
malformed-token) printf '{"token":42}\n' ;;
hostile-token) printf '%s\n' '{"token":"odd $ token"}' ;;
paginated)
case "$url" in
*page=1*) jq -cn '{runners:[range(1;51) | {id:.,name:("runner-" + tostring)}]}' ;;
*page=2*) printf '{"runners":[{"id":51,"name":"runner-51"}]}\n' ;;
*) return 1 ;;
esac
;;
malformed-page) printf '{"runners":[{"id":"bad","name":"runner"}]}\n' ;;
*) return 1 ;;
esac
}
if gcr_gitea_registration_token hinterland/hearth >/dev/null 2>&1; then
printf 'malformed registration token must fail closed\n' >&2
exit 1
fi
curl_mode=hostile-token
test "$(gcr_gitea_registration_token hinterland/hearth)" = "odd \$ token"
rm -f "$hardening_calls"
curl_mode=paginated
runners="$(gcr_gitea_list_runners hinterland/hearth)"
test "$(printf '%s\n' "$runners" | wc -l | tr -d ' ')" = 51
printf '%s\n' "$runners" | grep -q '^1 runner-1$'
printf '%s\n' "$runners" | grep -q '^51 runner-51$'
grep -q 'page=1&limit=50$' "$hardening_calls"
grep -q 'page=2&limit=50$' "$hardening_calls"
curl_mode=malformed-page
if gcr_gitea_list_runners hinterland/hearth >/dev/null 2>&1; then
printf 'malformed runner list must fail closed\n' >&2
exit 1
fi
retire_calls="$GCR_STATE_DIR/retire-calls"
gcr_gitea_list_runners() { printf '17 gcr-77-1\n'; }
gcr_gitea_set_runner_disabled() {
printf 'disable %s %s %s\n' "$1" "$2" "$3" >> "$retire_calls"
return 1
}
gcr_gitea_delete_runner() {
printf 'delete %s %s\n' "$1" "$2" >> "$retire_calls"
}
if gcr_gitea_deregister_runner_exact hinterland/hearth gcr-77-1; then
printf 'disable failure must retain runner identity\n' >&2
exit 1
fi
test "$(cat "$retire_calls")" = 'disable hinterland/hearth 17 true'
export GCR_NIX_VERSION=2.24.11
export GCR_NIX_TARBALL_SHA256=sha256
export GCR_ARM_NIX_TARBALL_SHA256=sha256
export GCR_ACT_RUNNER_VERSION=0.2.11
export GCR_ACT_RUNNER_SHA256=sha256
bootstrap="$(gcr_bootstrap_script nix "odd \$ token" 480 gcr-77-1)"
encoded="$(printf '%s' "odd \$ token" | base64 | tr -d '\n')"
printf '%s\n' "$bootstrap" | grep -Fq "printf '%s' '$encoded' | base64 -d"
printf '%s\n' "$bootstrap" | grep -Fq 'if [ ! -s /var/lib/gitea-runner/.runner ]; then'
start_script="$(printf '%s\n' "$bootstrap" | sed -n \
'/cat > \/usr\/local\/sbin\/gcr-runner-start/,/STARTEOF/p')"
if printf '%s\n' "$start_script" | grep -Fq "odd \$ token"; then
printf 'registration token must not persist in runner start script\n' >&2
exit 1
fi
calls="$GCR_STATE_DIR/calls"
gcr_budget_add() { printf 'budget\n' >> "$calls"; }
gcr_gitea_registration_token() { printf 'token'; printf 'token\n' >> "$calls"; }
gcr_gitea_registration_token() {
printf 'token\n' >> "$calls"
printf 'fresh-token'
}
gcr_vm_create() {
printf 'create\n' >> "$calls"
gcr_budget_add 0.032 180
printf '99 cx53 0.032'
printf '99 cx53 0.032 nbg1 amd64 424242'
}
gcr_vm_destroy() { printf 'destroy vm=%s\n' "$1" >> "$calls"; }
gcr_vm_runner_service() { printf 'runner %s vm=%s\n' "$2" "$1" >> "$calls"; }
gcr_gitea_runner_disabled() { printf 'runner-disabled %s %s\n' "$2" "$3" >> "$calls"; }
original='{"job_id":"301","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":1000,"ttl_min":480,"vm_id":71,"vm_name":"gcr-301-1","bootstrapped":true,"status":"vm_active"}'
gcr_record_put 301 1 "$original"
gcr_deallocate 301 1 completed:success
jq -e 'select(.status == "idle_vm" and .idle_expires_at == 4600)' \
"$(gcr_record_path 301 1)" >/dev/null
idle_once="$(gcr_record_get 301 1)"
NOW=3000
gcr_deallocate 301 1 completed:success
test "$(gcr_record_get 301 1)" = "$idle_once"
NOW=2800
# Exact elapsed hours keep current boundary instead of extending another hour.
exact='{"job_id":"300","run_attempt":"1","repo":"hinterland/hearth","label":"gross-x86","created_at":1000,"ttl_min":180,"vm_id":70,"vm_name":"gcr-300-1","bootstrapped":true,"status":"vm_active"}'
gcr_record_put 300 1 "$exact"
NOW=4600
gcr_deallocate 300 1 completed:success
jq -e 'select(.status == "idle_vm" and .idle_expires_at == 4600)' \
"$(gcr_record_path 300 1)" >/dev/null
gcr_record_del 300 1
NOW=2800
gcr_deallocate 301 1 completed:success
jq -e 'select(.status == "idle_vm" and .idle_expires_at == 4600)' \
"$(gcr_record_path 301 1)" >/dev/null
# Exact billing boundary must expire now, not roll into another paid hour.
NOW=4600
boundary='{"job_id":"302","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":1000,"ttl_min":480,"vm_id":74,"vm_name":"gcr-302-1","bootstrapped":true,"status":"vm_active"}'
test "$(gcr_record_idle_json "$boundary" | jq -r '.idle_expires_at')" = 4600
NOW=2800
gcr_alloc 302 1 hinterland/hearth '["gross-nix-x86-perf"]'
test "$RESPONSE_BODY" = 'reused gcr-301-1'
test ! -e "$(gcr_record_path 301 1)"
jq -e 'select(.job_id == "302" and .vm_id == 71 and
.vm_name == "gcr-301-1" and .status == "pending_vm" and
.created_at == 1000 and .assigned_at == 2800)' \
"$(gcr_record_path 302 1)" >/dev/null
test "$(grep -Ec '^(budget|token|create)$' "$calls" || true)" = 0
# Failed post-start health check keeps runner disabled and record retryable.
retry_idle='{"job_id":"315","run_attempt":"1","repo":"hinterland/hearth","label":"gross-arm","created_at":1000,"ttl_min":180,"vm_id":79,"vm_name":"gcr-315-1","bootstrapped":true,"status":"idle_vm","idle_since":2000,"idle_expires_at":4600}'
gcr_record_put 315 1 "$retry_idle"
export GCR_PER_REPO_CAP=2
FAIL_HEALTH=1
gcr_vm_runner_service() {
printf 'runner %s vm=%s\n' "$2" "$1" >> "$calls"
[ "$2" = health ] && [ "$FAIL_HEALTH" = 1 ] && return 1
printf 'runner-service vm=%s action=%s\n' "$1" "$2" >> "$calls"
return 0
}
gcr_alloc 316 1 hinterland/hearth '["gross-arm"]'
retry_rec="$(gcr_record_get 316 1)"
test "$(gcr_record_field "$retry_rec" bootstrapped)" = false
test "$(gcr_record_field "$retry_rec" reused_vm)" = true
grep -q '^runner start vm=79$' "$calls"
grep -q '^runner health vm=79$' "$calls"
grep -q '^runner-disabled gcr-315-1 true$' "$calls"
if grep -q '^runner-disabled gcr-315-1 false$' "$calls"; then
printf 'unhealthy reused runner must never become schedulable\n' >&2
gcr_gitea_runner_disabled() {
printf 'obsolete-runner-toggle %s %s %s\n' "$1" "$2" "$3" >> "$calls"
return 1
}
# Terminal registration is retired exactly before VM becomes generic idle.
runner_present=1
gcr_gitea_list_runners() {
printf 'list-runners repo=%s\n' "$1" >> "$calls"
[ "$runner_present" -eq 0 ] || printf '17 gcr-301-1\n'
}
gcr_gitea_delete_runner() {
printf 'delete-runner repo=%s id=%s\n' "$1" "$2" >> "$calls"
runner_present=0
}
gcr_gitea_set_runner_disabled() {
printf 'disable-runner repo=%s id=%s value=%s\n' \
"$1" "$2" "$3" >> "$calls"
}
original='{"job_id":"301","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":1000,"ttl_min":480,"vm_id":71,"vm_name":"gcr-301-1","runner_name":"gcr-301-1","server_type":"cx53","budget_rate":"0.032","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":true,"status":"vm_active"}'
gcr_record_put 301 1 "$original"
gcr_deallocate 301 1 completed:success
idle="$(gcr_record_get 301 1)"
jq -e 'select(.status == "idle_vm" and .idle_expires_at == 4600 and
.repo == "" and .label == "" and .runner_name == "" and
.bootstrapped == false and .created_at == 1000 and .ttl_min == 480 and
.server_type == "cx53" and .location == "nbg1" and .arch == "amd64" and
.image_id == "424242")' "$(gcr_record_path 301 1)" >/dev/null
test "$(grep -c '^list-runners repo=hinterland/hearth$' "$calls")" = 2
grep -q '^disable-runner repo=hinterland/hearth id=17 value=true$' "$calls"
grep -q '^delete-runner repo=hinterland/hearth id=17$' "$calls"
test "$(grep -E '^(disable-runner|delete-runner)' "$calls")" = 'disable-runner repo=hinterland/hearth id=17 value=true
delete-runner repo=hinterland/hearth id=17'
test "$(gcr_count_active)" = 0
if grep -Eq '^(runner-service .*start|destroy|budget|token|create)' "$calls"; then
printf 'retirement must not restart, destroy, charge, or fetch a token\n' >&2
exit 1
fi
FAIL_HEALTH=0
gcr_record_del 316 1
gcr_record_del 301 1
# Expired idle capacity is never claimed; normal allocation then charges once.
expired='{"job_id":"303","run_attempt":"1","repo":"hinterland/hearth","label":"gross-x86","created_at":1000,"ttl_min":180,"vm_id":72,"vm_name":"gcr-303-1","bootstrapped":true,"status":"idle_vm","idle_since":2000,"idle_expires_at":2800}'
gcr_record_put 303 1 "$expired"
NOW=2800
export GCR_PER_REPO_CAP=2
gcr_alloc 304 1 hinterland/hearth '["gross-x86"]'
test "$RESPONSE_BODY" = 'allocated gcr-304-1'
jq -e 'select(.vm_id == 99 and .status == "pending_vm")' \
"$(gcr_record_path 304 1)" >/dev/null
test "$(grep -c '^budget$' "$calls")" = 1
# Failed deregistration remains durable, active, and unclaimable until retry.
retire_list_count="$GCR_STATE_DIR/retire-list-count"
printf '0\n' > "$retire_list_count"
gcr_gitea_list_runners() {
retire_lists="$(cat "$retire_list_count")"
retire_lists=$((retire_lists + 1))
printf '%s\n' "$retire_lists" > "$retire_list_count"
printf 'list-retry %s\n' "$retire_lists" >> "$calls"
[ "$retire_lists" -gt 1 ] || return 1
}
pending_retire='{"job_id":"302","run_attempt":"1","repo":"hinterland/hearth","label":"nix","created_at":1000,"ttl_min":480,"vm_id":72,"vm_name":"gcr-302-1","runner_name":"gcr-302-1","server_type":"cx23","budget_rate":"0.004","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":true,"status":"vm_active"}'
gcr_record_put 302 1 "$pending_retire"
gcr_deallocate 302 1 completed:success
test "$(gcr_record_field "$(gcr_record_get 302 1)" status)" = retiring_vm
test "$(gcr_count_active)" = 1
gcr_lock_acquire "$(gcr_alloc_key 399 1)"
if gcr_claim_idle 399 1 hectic-lab/util.nix nix; then
printf 'retiring VM must not be claimable\n' >&2
exit 1
fi
gcr_lock_release "$(gcr_alloc_key 399 1)"
gcr_sweep_retiring_vms
test "$(gcr_record_field "$(gcr_record_get 302 1)" status)" = idle_vm
test "$(gcr_count_active)" = 0
gcr_record_del 302 1
gcr_record_put 301 1 "$idle"
# Compatible job in another repository claims generic idle by persisted profile.
gcr_gitea_list_runners() { :; }
gcr_alloc 303 1 hectic-lab/util.nix '["gross-nix-x86-perf"]'
test "$RESPONSE_BODY" = 'rebuilding gcr-301-1'
test ! -e "$(gcr_record_path 301 1)"
claimed="$(gcr_record_get 303 1)"
jq -e 'select(.job_id == "303" and .repo == "hectic-lab/util.nix" and
.label == "gross-nix-x86-perf" and .vm_id == 71 and
.vm_name == "gcr-301-1" and .runner_name == "gcr-303-1" and
.status == "rebuild_pending" and .bootstrapped == false and
.rebuild_image_id == "424242" and .rebuild_action_id == "" and
.created_at == 1000 and .ttl_min == 480 and .assigned_at == 2800)' \
"$(gcr_record_path 303 1)" >/dev/null
test "$(grep -Ec '^(budget|token|create)$' "$calls" || true)" = 0
test "$(gcr_count_active)" = 1
test "$(gcr_count_active_repo hectic-lab/util.nix)" = 1
# Rebuild intent and action id are durable around provider request and polling.
gcr_gitea_job_state() { printf 'queued:'; }
gcr_hcloud_req() {
method="$1"; path="$2"; body="${3:-}"
test ! -e "$GCR_STATE_DIR/jobs/.lock.admission"
test ! -e "$GCR_STATE_DIR/jobs/.lock.idle-pool"
GCR_LAST_BODY="$GCR_STATE_DIR/last-body.json"
case "$method:$path" in
POST:/servers/71/actions/rebuild)
jq -e 'select(.image == "424242" and
(.user_data | startswith("#cloud-config\n")) and
(.user_data | contains("/etc/ssh/ssh_host_ed25519_key")) and
keys == ["image", "user_data"])' <<EOF >/dev/null
$body
EOF
request_rec="$(gcr_record_get 303 1)"
test "$(gcr_record_field "$request_rec" status)" = rebuild_requesting
test -z "$(gcr_record_field "$request_rec" rebuild_action_id)"
printf '%s\n' '{"action":{"id":501,"status":"running","command":"rebuild","resources":[{"id":71,"type":"server"}]}}' > "$GCR_LAST_BODY"
;;
GET:/actions/501)
poll_rec="$(gcr_record_get 303 1)"
test "$(gcr_record_field "$poll_rec" status)" = rebuild_running
test "$(gcr_record_field "$poll_rec" rebuild_action_id)" = 501
printf '%s\n' '{"action":{"id":501,"status":"success","command":"rebuild","resources":[{"id":71,"type":"server"}]}}' > "$GCR_LAST_BODY"
;;
GET:/servers/71)
printf '%s\n' '{"server":{"id":71,"status":"running","server_type":{"name":"cx53","architecture":"amd64"},"datacenter":{"location":{"name":"nbg1"}},"image":{"id":424242},"public_net":{"ipv4":{"ip":"192.0.2.71"}}}}' > "$GCR_LAST_BODY"
;;
*) return 1 ;;
esac
}
gcr_sweep_rebuilds
ready="$(gcr_record_get 303 1)"
jq -e 'select(.status == "pending_vm" and .bootstrapped == false and
.last_rebuild_action_id == 501 and .ip == "192.0.2.71" and
.created_at == 1000 and .ttl_min == 480 and .budget_rate == "0.032")' \
"$(gcr_record_path 303 1)" >/dev/null
if grep -q '^token$' "$calls"; then
printf 'registration token must not be fetched before rebuild succeeds\n' >&2
exit 1
fi
gcr_vm_public_ip() { printf '192.0.2.71'; }
gcr_vm_bootstrap_ssh() {
test -r "$5"
grep -Eq "^$1 ssh-ed25519 [A-Za-z0-9+/=]+$" "$5"
printf 'bootstrap ip=%s label=%s token=%s runner=%s\n' \
"$1" "$2" "$3" "$4" >> "$calls"
}
gcr_bootstrap_pending
bootstrapped="$(gcr_record_get 303 1)"
test "$(gcr_record_field "$bootstrapped" bootstrapped)" = true
test "$(grep -c '^token$' "$calls")" = 1
test "$(grep -c '^create$' "$calls")" = 1
gcr_sweep_ttl
grep -q 'destroy vm=72' "$calls"
test ! -e "$(gcr_record_path 303 1)"
# Busy pool lock defers instead of racing into paid allocation.
export GCR_CONCURRENCY_CAP=3
export GCR_PER_REPO_CAP=3
gcr_lock_acquire idle-pool
gcr_alloc 305 1 hinterland/hearth '["gross-arm"]'
test "$RESPONSE_BODY" = 'deferred: idle pool busy'
test "$(gcr_record_field "$(gcr_record_get 305 1)" status)" = deferred
test "$(grep -c '^create$' "$calls")" = 1
gcr_lock_release idle-pool
# Claim needs at least one reconcile interval before slot and hard expiry.
export GCR_RECONCILE_INTERVAL_SEC=60
near_expiry='{"job_id":"313","run_attempt":"1","repo":"hinterland/hearth","label":"gross-mixed-econ","created_at":1000,"ttl_min":180,"vm_id":78,"vm_name":"gcr-313-1","bootstrapped":true,"status":"idle_vm","idle_since":2000,"idle_expires_at":2860}'
gcr_record_put 313 1 "$near_expiry"
NOW=2801
gcr_lock_acquire "$(gcr_alloc_key 314 1)"
if gcr_claim_idle 314 1 hinterland/hearth gross-mixed-econ; then
printf 'near-expiry VM must not be reused\n' >&2
grep -q '^bootstrap ip=192.0.2.71 label=gross-nix-x86-perf token=fresh-token runner=gcr-303-1$' "$calls"
if grep -q '^bootstrap .*runner=gcr-301-1$' "$calls"; then
printf 'old runner identity must never be bootstrapped\n' >&2
exit 1
fi
gcr_lock_release "$(gcr_alloc_key 314 1)"
test -e "$(gcr_record_path 313 1)"
test ! -e "$(gcr_record_path 314 1)"
gcr_record_del 313 1
NOW=2800
# Two concurrent claims transfer one VM once; original labels/name stay safe.
race_idle='{"job_id":"306","run_attempt":"1","repo":"hinterland/hearth","label":"gross-arm","created_at":1000,"ttl_min":180,"vm_id":73,"vm_name":"gcr-306-1","bootstrapped":true,"status":"idle_vm","idle_since":2000,"idle_expires_at":4600}'
gcr_record_put 306 1 "$race_idle"
# Incompatible image/profile remains idle and normal allocation creates anew.
incompatible='{"job_id":"304","run_attempt":"1","repo":"","label":"","created_at":1000,"ttl_min":180,"vm_id":73,"vm_name":"gcr-304-1","runner_name":"","server_type":"cx53","budget_rate":"0.032","location":"nbg1","arch":"amd64","image_id":"313131","bootstrapped":false,"status":"idle_vm","idle_since":2000,"idle_expires_at":4600}'
gcr_record_put 304 1 "$incompatible"
gcr_alloc 305 1 hectic-lab/util.nix '["nix"]'
test "$RESPONSE_BODY" = 'allocated gcr-305-1'
test -e "$(gcr_record_path 304 1)"
jq -e 'select(.status == "pending_vm" and .location == "nbg1" and
.arch == "amd64" and .image_id == "424242")' \
"$(gcr_record_path 305 1)" >/dev/null
test "$(grep -c '^create$' "$calls")" = 1
gcr_record_del 304 1
gcr_record_del 305 1
# Uncertain rebuild POST destroys VM and never fetches target repository token.
uncertain='{"job_id":"306","run_attempt":"1","repo":"hectic-lab/util.nix","label":"nix","created_at":1000,"ttl_min":480,"vm_id":74,"vm_name":"gcr-306-old","runner_name":"gcr-306-1","server_type":"cx23","budget_rate":"0.004","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":false,"status":"rebuild_pending","rebuild_image_id":"424242","rebuild_action_id":"","rebuild_request_state":"pending"}'
gcr_record_put 306 1 "$uncertain"
token_count_before="$(grep -c '^token$' "$calls")"
gcr_hcloud_req() {
test "$1:$2" = 'POST:/servers/74/actions/rebuild'
test "$(gcr_record_field "$(gcr_record_get 306 1)" status)" = rebuild_requesting
GCR_LAST_HTTP=500
return 1
}
gcr_sweep_rebuilds
test ! -e "$(gcr_record_path 306 1)"
grep -q '^destroy vm=74$' "$calls"
test "$(grep -c '^token$' "$calls")" = "$token_count_before"
# Crash after durable request intent is unrecoverably ambiguous: destroy
# without issuing another rebuild request.
requesting='{"job_id":"307","run_attempt":"1","repo":"hectic-lab/util.nix","label":"nix","created_at":1000,"ttl_min":480,"vm_id":75,"vm_name":"gcr-307-old","runner_name":"gcr-307-1","server_type":"cx23","budget_rate":"0.004","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":false,"status":"rebuild_requesting","rebuild_image_id":"424242","rebuild_action_id":"","rebuild_request_state":"requesting"}'
gcr_record_put 307 1 "$requesting"
gcr_hcloud_req() { printf 'unexpected-provider-request\n' >> "$calls"; return 1; }
gcr_sweep_rebuilds
test ! -e "$(gcr_record_path 307 1)"
grep -q '^destroy vm=75$' "$calls"
if grep -q '^unexpected-provider-request$' "$calls"; then
printf 'ambiguous rebuild intent must not be replayed\n' >&2
exit 1
fi
# Pool lock contention defers instead of racing into paid allocation.
gcr_lock_acquire idle-pool
gcr_alloc 308 1 hectic-lab/util.nix '["nix"]'
test "$RESPONSE_BODY" = 'deferred: idle pool busy'
test "$(gcr_record_field "$(gcr_record_get 308 1)" status)" = deferred
gcr_lock_release idle-pool
gcr_record_del 308 1
# Transitional states count toward caps; generic idle does not.
for status in retiring_vm rebuild_pending rebuild_requesting rebuild_running; do
rec="$(printf '%s' "$uncertain" | jq -c --arg s "$status" '.status = $s')"
gcr_record_put 309 1 "$rec"
test "$(gcr_count_active)" = 2
gcr_record_del 309 1
done
test "$(gcr_count_active)" = 1
gcr_record_del 303 1
test "$(gcr_count_active)" = 0
# Two concurrent compatible claims transfer one VM once.
race_idle='{"job_id":"310","run_attempt":"1","repo":"","label":"","created_at":1000,"ttl_min":480,"vm_id":76,"vm_name":"gcr-310-1","runner_name":"","server_type":"cx23","budget_rate":"0.004","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":false,"status":"idle_vm","idle_since":2000,"idle_expires_at":4600}'
gcr_record_put 310 1 "$race_idle"
claim_script="$GCR_STATE_DIR/claim.sh"
cat > "$claim_script" <<'EOF'
#!/bin/dash
set -eu
. "$STATE_SH"
. "$DECIDE_SH"
. "$HCLOUD_SH"
gcr_now_epoch() { printf '2800'; }
key="$(gcr_alloc_key "$1" 1)"
gcr_lock_acquire "$key"
if gcr_claim_idle "$1" 1 hinterland/hearth gross-arm; then
printf 'reused\n' > "$GCR_STATE_DIR/result-$1"
if gcr_claim_idle "$1" 1 hectic-lab/util.nix nix; then
printf 'claimed\n' > "$GCR_STATE_DIR/result-$1"
else
printf 'missed\n' > "$GCR_STATE_DIR/result-$1"
fi
gcr_lock_release "$key"
EOF
dash "$claim_script" 307 & first=$!
dash "$claim_script" 308 & second=$!
GCR_NIX_IMAGE_ID=424242 dash "$claim_script" 311 & first=$!
GCR_NIX_IMAGE_ID=424242 dash "$claim_script" 312 & second=$!
wait "$first"
wait "$second"
reused_count=0
for result in "$GCR_STATE_DIR"/result-*; do
[ "$(cat "$result")" = reused ] && reused_count=$((reused_count + 1))
done
test "$reused_count" = 1
test ! -e "$(gcr_record_path 306 1)"
owner=""
for job in 307 308; do
test "$(grep -lc '^claimed$' "$GCR_STATE_DIR"/result-* | wc -l | tr -d ' ')" = 1
test ! -e "$(gcr_record_path 310 1)"
owner_count=0
for job in 311 312; do
rec="$(gcr_record_get "$job" 1)"
if [ -n "$rec" ]; then
test "$(gcr_record_field "$rec" vm_id)" = 73
test "$(gcr_record_field "$rec" vm_name)" = gcr-306-1
owner="$job"
fi
done
test -n "$owner"
gcr_vm_list_managed() {
printf 'list\n' >> "$GCR_STATE_DIR/list-calls"
printf '[{"id":73,"labels":{"gcr.job-id":"306","gcr.run-attempt":"1"}}]'
}
gcr_gitea_list_runners() { printf '17 gcr-306-1\n'; }
gcr_gitea_delete_runner() { printf 'delete repo=%s runner=%s\n' "$1" "$2" >> "$calls"; }
before_destroy="$(grep -c '^destroy vm=73$' "$calls" || true)"
gcr_lock_acquire admission
gcr_sweep_orphan_vms
test ! -e "$GCR_STATE_DIR/list-calls"
gcr_lock_release admission
gcr_sweep_orphan_vms
test "$(wc -l < "$GCR_STATE_DIR/list-calls" | tr -d ' ')" = 1
gcr_sweep_stale_runners
after_destroy="$(grep -c '^destroy vm=73$' "$calls" || true)"
test "$before_destroy" = "$after_destroy"
if grep -q '^delete repo=.* runner=17$' "$calls"; then
printf 'reused VM runner registration must not be swept as stale\n' >&2
exit 1
fi
# Interrupted destination-first transfer leaves duplicate state, never a VM
# deletion: sweep drops superseded idle source and keeps active destination.
duplicate_idle='{"job_id":"309","run_attempt":"1","repo":"hinterland/hearth","label":"gross-arm","created_at":1000,"ttl_min":180,"vm_id":75,"vm_name":"gcr-309-1","bootstrapped":true,"status":"idle_vm","idle_since":2000,"idle_expires_at":2800}'
duplicate_active='{"job_id":"310","run_attempt":"1","repo":"hinterland/hearth","label":"gross-arm","created_at":1000,"ttl_min":180,"vm_id":75,"vm_name":"gcr-309-1","bootstrapped":true,"status":"pending_vm"}'
gcr_record_put 309 1 "$duplicate_idle"
gcr_record_put 310 1 "$duplicate_active"
gcr_sweep_ttl
test ! -e "$(gcr_record_path 309 1)"
test -e "$(gcr_record_path 310 1)"
if grep -q '^destroy vm=75$' "$calls"; then
printf 'superseded idle record must not destroy reassigned VM\n' >&2
exit 1
fi
# Delayed old-job in_progress delivery cannot reactivate idle ownership.
late_idle='{"job_id":"311","run_attempt":"1","repo":"hinterland/hearth","label":"gross-arm","created_at":1000,"ttl_min":180,"vm_id":76,"vm_name":"gcr-311-1","bootstrapped":true,"status":"idle_vm","idle_since":2000,"idle_expires_at":4600}'
gcr_record_put 311 1 "$late_idle"
gcr_mark_in_progress 311 1
test "$(gcr_record_field "$(gcr_record_get 311 1)" status)" = idle_vm
# Crash-stranded locks are reclaimed by dead owner PID; live contention remains.
mkdir "$GCR_STATE_DIR/jobs/.lock.stale-test"
if gcr_lock_acquire stale-test; then
printf 'pre-existing lock must not be reclaimed\n' >&2
exit 1
fi
rm -rf "$GCR_STATE_DIR/jobs/.lock.stale-test"
mkdir "$GCR_STATE_DIR/jobs/.lock.crashed-test"
printf '999999 1\n' > "$GCR_STATE_DIR/jobs/.lock.crashed-test/owner"
gcr_lock_acquire crashed-test
gcr_lock_release crashed-test
# Concurrent recovery of one dead lock admits exactly one owner.
mkdir "$GCR_STATE_DIR/jobs/.lock.crashed-race"
printf '999999 1\n' > "$GCR_STATE_DIR/jobs/.lock.crashed-race/owner"
reclaim_script="$GCR_STATE_DIR/reclaim.sh"
cat > "$reclaim_script" <<'EOF'
#!/bin/dash
set -eu
. "$STATE_SH"
if gcr_lock_acquire crashed-race; then
printf 'acquired\n' > "$GCR_STATE_DIR/reclaim-$1"
sleep 1
gcr_lock_release crashed-race
else
printf 'busy\n' > "$GCR_STATE_DIR/reclaim-$1"
fi
EOF
dash "$reclaim_script" first & first=$!
dash "$reclaim_script" second & second=$!
wait "$first"
wait "$second"
test "$(grep -lc '^acquired$' "$GCR_STATE_DIR"/reclaim-* | wc -l | tr -d ' ')" = 1
mkdir "$GCR_STATE_DIR/jobs/.lock.crashed-test"
printf '999999 1\n' > "$GCR_STATE_DIR/jobs/.lock.crashed-test/owner"
gcr_lock_acquire crashed-test
gcr_lock_release crashed-test
for job in 307 308 310 311; do
[ -z "$rec" ] || owner_count=$((owner_count + 1))
[ -z "$rec" ] || test "$(gcr_record_field "$rec" status)" = rebuild_pending
gcr_record_del "$job" 1
done
ttl_record='{"job_id":"312","run_attempt":"1","repo":"hinterland/hearth","label":"gross-x86","created_at":1000,"ttl_min":180,"vm_id":77,"vm_name":"gcr-312-1","bootstrapped":true,"status":"vm_active"}'
gcr_record_put 312 1 "$ttl_record"
gcr_vm_public_ip() { printf '192.0.2.%s' "$1"; }
gcr_vm_collect_diagnostics() {
printf 'diag vm=%s job=%s reason=%s\n' "$1" "$3" "$4" >> "$calls"
}
NOW=11799
gcr_sweep_ttl
test -e "$(gcr_record_path 312 1)"
NOW=11800
gcr_sweep_ttl
test ! -e "$(gcr_record_path 312 1)"
grep -q '^diag vm=77 job=312 reason=ttl$' "$calls"
grep -q '^destroy vm=77$' "$calls"
test "$owner_count" = 1
# Admission lock serializes cap check and creation across webhook processes.
ADMISSION_STATE="$GCR_STATE_DIR/admission-state"
mkdir "$ADMISSION_STATE"
admission_script="$ADMISSION_STATE/allocate.sh"
cat > "$admission_script" <<'EOF'
#!/bin/dash
set -eu
. "$LOG_SH"
. "$STATE_SH"
. "$DECIDE_SH"
. "$HCLOUD_SH"
. "$WEBHOOK_SH"
gcr_now_epoch() { printf '2000'; }
gcr_budget_add() { printf 'budget %s\n' "$1" >> "$GCR_STATE_DIR/admission-calls"; }
gcr_gitea_registration_token() { printf token; }
gcr_vm_create() {
sleep 1
printf 'create %s\n' "$6" >> "$GCR_STATE_DIR/admission-calls"
gcr_budget_add 0.032 180
printf '%s cx53 0.032' "$6"
}
gcr_vm_destroy() { :; }
gcr_state_init
gcr_alloc "$1" 1 hinterland/hearth '["gross-x86"]'
EOF
old_state="$GCR_STATE_DIR"
GCR_STATE_DIR="$ADMISSION_STATE" \
GCR_ALLOWED_REPOS=hinterland/hearth \
GCR_CONCURRENCY_CAP=1 \
GCR_PER_REPO_CAP=1 \
dash "$admission_script" 401 & first=$!
GCR_STATE_DIR="$ADMISSION_STATE" \
GCR_ALLOWED_REPOS=hinterland/hearth \
GCR_CONCURRENCY_CAP=1 \
GCR_PER_REPO_CAP=1 \
dash "$admission_script" 402 & second=$!
wait "$first"
wait "$second"
GCR_STATE_DIR="$ADMISSION_STATE"
test "$(grep -c '^create ' "$GCR_STATE_DIR/admission-calls")" = 1
active_count="$(gcr_count_active)"
test "$active_count" = 1
deferred_count="$(grep -El '"status"[[:space:]]*:[[:space:]]*"deferred"' \
"$GCR_STATE_DIR"/jobs/*.json | wc -l | tr -d ' ')"
test "$deferred_count" = 1
GCR_STATE_DIR="$old_state"
# Crash-stranded locks are reclaimed; live/ownerless locks remain closed.
mkdir "$GCR_STATE_DIR/jobs/.lock.ownerless"
if gcr_lock_acquire ownerless; then
printf 'fresh ownerless lock must not be reclaimed\n' >&2
exit 1
fi
rm -rf "$GCR_STATE_DIR/jobs/.lock.ownerless"
mkdir "$GCR_STATE_DIR/jobs/.lock.crashed"
printf '999999 1\n' > "$GCR_STATE_DIR/jobs/.lock.crashed/owner"
gcr_lock_acquire crashed
gcr_lock_release crashed
# Original hard TTL remains authoritative after cross-repository assignment.
ttl_rebuild='{"job_id":"313","run_attempt":"1","repo":"hectic-lab/util.nix","label":"nix","created_at":1000,"ttl_min":480,"vm_id":77,"vm_name":"gcr-313-old","runner_name":"gcr-313-1","server_type":"cx23","budget_rate":"0.004","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":false,"status":"rebuild_running","rebuild_image_id":"424242","rebuild_action_id":700,"rebuild_request_state":"accepted"}'
gcr_record_put 313 1 "$ttl_rebuild"
NOW=29799
gcr_sweep_ttl
test -e "$(gcr_record_path 313 1)"
NOW=29800
gcr_sweep_ttl
test ! -e "$(gcr_record_path 313 1)"
grep -q '^destroy vm=77$' "$calls"
@@ -11,6 +11,7 @@ set -eu
gcr_state_init
calls="$GCR_STATE_DIR/calls"
gcr_now_epoch() { printf '1800'; }
export GCR_NIX_IMAGE_ID=424242
gcr_gitea_job_state() {
case "$2" in
@@ -33,29 +34,21 @@ gcr_vm_destroy() {
printf 'destroy vm=%s\n' "$1" >> "$calls"
}
gcr_vm_runner_service() {
printf 'runner %s vm=%s\n' "$2" "$1" >> "$calls"
gcr_gitea_deregister_runner_exact() {
printf 'deregister repo=%s runner=%s\n' "$1" "$2" >> "$calls"
}
gcr_gitea_runner_disabled() {
printf 'disabled runner=%s value=%s\n' "$2" "$3" >> "$calls"
}
record_success='{"job_id":"101","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":"0","ttl_min":480,"vm_id":41,"vm_name":"gcr-101-1","bootstrapped":true,"status":"vm_active"}'
record_failure='{"job_id":"102","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":"1","ttl_min":480,"vm_id":42,"vm_name":"gcr-102-1","bootstrapped":true,"status":"vm_active"}'
record_success='{"job_id":"101","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":"0","ttl_min":480,"vm_id":41,"vm_name":"gcr-101-1","runner_name":"gcr-101-1","server_type":"cx53","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":true,"status":"vm_active"}'
record_failure='{"job_id":"102","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":"1","ttl_min":480,"vm_id":42,"vm_name":"gcr-102-1","runner_name":"gcr-102-1","server_type":"cx53","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":true,"status":"vm_active"}'
gcr_record_put 101 1 "$record_success"
gcr_record_put 102 1 "$record_failure"
gcr_reap_finished_jobs
grep -q 'diag vm=42 ip=192.0.2.42 job=102 reason=completed:failure' "$calls"
grep -q 'runner health vm=42' "$calls"
grep -q 'disabled runner=gcr-102-1 value=true' "$calls"
grep -q 'runner stop vm=42' "$calls"
test "$(grep -E '^(diag vm=42|runner health vm=42|disabled runner=gcr-102-1|runner stop vm=42)' "$calls")" = 'diag vm=42 ip=192.0.2.42 job=102 reason=completed:failure
runner health vm=42
disabled runner=gcr-102-1 value=true
runner stop vm=42'
grep -q 'deregister repo=hinterland/hearth runner=gcr-102-1' "$calls"
test "$(grep -E '^(diag vm=42|deregister repo=hinterland/hearth runner=gcr-102-1)' "$calls")" = 'diag vm=42 ip=192.0.2.42 job=102 reason=completed:failure
deregister repo=hinterland/hearth runner=gcr-102-1'
if grep -q 'diag vm=41' "$calls"; then
printf 'success job should not collect diagnostics\n' >&2
exit 1
@@ -79,7 +72,7 @@ gcr_reap_finished_jobs
test "$(gcr_record_get 101 1)" = "$idle_once"
# Skipped terminal jobs follow same healthy retention policy without diagnostics.
record_skipped='{"job_id":"105","run_attempt":"1","repo":"hinterland/hearth","label":"nix","created_at":"1","ttl_min":480,"vm_id":45,"vm_name":"gcr-105-1","bootstrapped":true,"status":"vm_active"}'
record_skipped='{"job_id":"105","run_attempt":"1","repo":"hinterland/hearth","label":"nix","created_at":"1","ttl_min":480,"vm_id":45,"vm_name":"gcr-105-1","runner_name":"gcr-105-1","server_type":"cx23","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":true,"status":"vm_active"}'
gcr_record_put 105 1 "$record_skipped"
gcr_reap_finished_jobs
test "$(gcr_record_field "$(gcr_record_get 105 1)" status)" = idle_vm
@@ -101,10 +94,6 @@ gcr_vm_destroy() {
printf 'destroy-failed vm=%s\n' "$1" >> "$calls"
return 1
}
gcr_vm_runner_service() {
printf 'runner %s vm=%s\n' "$2" "$1" >> "$calls"
[ "$1" != 44 ] || [ "$2" != stop ]
}
gcr_reap_finished_jobs
test "$(gcr_record_field "$(gcr_record_get 104 1)" status)" = cleanup_pending
test "$(gcr_count_active)" = 1
@@ -117,7 +106,7 @@ grep -q '^destroy-retry vm=44$' "$calls"
calls_ip_fail="$GCR_STATE_DIR/calls-ip-fail"
calls="$calls_ip_fail"
record_ip_fail='{"job_id":"103","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":"1","ttl_min":480,"vm_id":43,"vm_name":"gcr-103-1","bootstrapped":true,"status":"vm_active"}'
record_ip_fail='{"job_id":"103","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":"1","ttl_min":480,"vm_id":43,"vm_name":"gcr-103-1","runner_name":"gcr-103-1","server_type":"cx53","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":true,"status":"vm_active"}'
gcr_record_put 103 1 "$record_ip_fail"
gcr_gitea_job_state() {
@@ -130,11 +119,6 @@ gcr_gitea_job_state() {
gcr_vm_public_ip() {
return 1
}
gcr_vm_runner_service() {
printf 'runner %s vm=%s\n' "$2" "$1" >> "$calls"
return 1
}
gcr_vm_destroy() {
printf 'destroy vm=%s\n' "$1" >> "$calls"
}
@@ -142,6 +126,9 @@ gcr_vm_destroy() {
gcr_reap_finished_jobs
grep -q 'diag vm=43 ip= job=103 reason=completed:failure' "$calls_ip_fail"
grep -q 'runner health vm=43' "$calls_ip_fail"
grep -q 'destroy vm=43' "$calls_ip_fail"
test ! -e "$(gcr_record_path 103 1)"
grep -q 'deregister repo=hinterland/hearth runner=gcr-103-1' "$calls_ip_fail"
test "$(gcr_record_field "$(gcr_record_get 103 1)" status)" = idle_vm
if grep -q 'destroy vm=43' "$calls_ip_fail"; then
printf 'diagnostic IP lookup failure must not bypass safe deregistration\n' >&2
exit 1
fi
@@ -11,6 +11,7 @@ set -eu
gcr_state_init
calls="$GCR_STATE_DIR/calls"
gcr_now_epoch() { printf '1800'; }
export GCR_NIX_IMAGE_ID=424242
gcr_vm_public_ip() {
printf '192.0.2.%s' "$1"
@@ -24,16 +25,12 @@ gcr_vm_destroy() {
printf 'destroy vm=%s\n' "$1" >> "$calls"
}
gcr_vm_runner_service() {
printf 'runner %s vm=%s\n' "$2" "$1" >> "$calls"
gcr_gitea_deregister_runner_exact() {
printf 'deregister repo=%s runner=%s\n' "$1" "$2" >> "$calls"
}
gcr_gitea_runner_disabled() {
printf 'disabled runner=%s value=%s\n' "$2" "$3" >> "$calls"
}
record_success='{"job_id":"201","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":"0","ttl_min":480,"vm_id":51,"vm_name":"gcr-201-1","bootstrapped":true,"status":"vm_active"}'
record_failure='{"job_id":"202","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":"1","ttl_min":480,"vm_id":52,"vm_name":"gcr-202-1","bootstrapped":true,"status":"vm_active"}'
record_success='{"job_id":"201","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":"0","ttl_min":480,"vm_id":51,"vm_name":"gcr-201-1","runner_name":"gcr-201-1","server_type":"cx53","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":true,"status":"vm_active"}'
record_failure='{"job_id":"202","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":"1","ttl_min":480,"vm_id":52,"vm_name":"gcr-202-1","runner_name":"gcr-202-1","server_type":"cx53","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":true,"status":"vm_active"}'
gcr_record_put 201 1 "$record_success"
gcr_record_put 202 1 "$record_failure"
@@ -41,13 +38,9 @@ gcr_deallocate 201 1 completed:success
gcr_deallocate 202 1 completed:failure
grep -q 'diag vm=52 ip=192.0.2.52 job=202 reason=completed:failure' "$calls"
grep -q 'runner health vm=52' "$calls"
grep -q 'disabled runner=gcr-202-1 value=true' "$calls"
grep -q 'runner stop vm=52' "$calls"
test "$(grep -E '^(diag vm=52|runner health vm=52|disabled runner=gcr-202-1|runner stop vm=52)' "$calls")" = 'diag vm=52 ip=192.0.2.52 job=202 reason=completed:failure
runner health vm=52
disabled runner=gcr-202-1 value=true
runner stop vm=52'
grep -q 'deregister repo=hinterland/hearth runner=gcr-202-1' "$calls"
test "$(grep -E '^(diag vm=52|deregister repo=hinterland/hearth runner=gcr-202-1)' "$calls")" = 'diag vm=52 ip=192.0.2.52 job=202 reason=completed:failure
deregister repo=hinterland/hearth runner=gcr-202-1'
if grep -q 'diag vm=51' "$calls"; then
printf 'success webhook should not collect diagnostics\n' >&2
exit 1
@@ -71,7 +64,8 @@ gcr_record_del 201 1
gcr_lock_acquire "$(gcr_alloc_key 205 1)"
gcr_claim_idle 205 1 hinterland/hearth gross-nix-x86-perf
gcr_lock_release "$(gcr_alloc_key 205 1)"
jq -e 'select(.job_id == "205" and .vm_id == 52 and .status == "pending_vm" and .reused_vm == true)' \
jq -e 'select(.job_id == "205" and .vm_id == 52 and
.status == "rebuild_pending" and .runner_name == "gcr-205-1")' \
"$(gcr_record_path 205 1)" >/dev/null
gcr_record_del 205 1
gcr_record_put 201 1 "$idle_once"
@@ -79,7 +73,7 @@ gcr_deallocate 201 1 completed:success
test "$(gcr_record_get 201 1)" = "$idle_once"
# Cancelled terminal jobs use same retention policy without failure diagnostics.
record_cancelled='{"job_id":"207","run_attempt":"1","repo":"hinterland/hearth","label":"nix","created_at":"1","ttl_min":480,"vm_id":57,"vm_name":"gcr-207-1","bootstrapped":true,"status":"vm_active"}'
record_cancelled='{"job_id":"207","run_attempt":"1","repo":"hinterland/hearth","label":"nix","created_at":"1","ttl_min":480,"vm_id":57,"vm_name":"gcr-207-1","runner_name":"gcr-207-1","server_type":"cx23","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":true,"status":"vm_active"}'
gcr_record_put 207 1 "$record_cancelled"
gcr_deallocate 207 1 completed:cancelled
test "$(gcr_record_field "$(gcr_record_get 207 1)" status)" = idle_vm
@@ -90,25 +84,19 @@ fi
calls_ip_fail="$GCR_STATE_DIR/calls-ip-fail"
calls="$calls_ip_fail"
record_ip_fail='{"job_id":"203","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":"1","ttl_min":480,"vm_id":53,"vm_name":"gcr-203-1","bootstrapped":true,"status":"vm_active"}'
record_ip_fail='{"job_id":"203","run_attempt":"1","repo":"hinterland/hearth","label":"gross-nix-x86-perf","created_at":"1","ttl_min":480,"vm_id":53,"vm_name":"gcr-203-1","runner_name":"gcr-203-1","server_type":"cx53","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":true,"status":"vm_active"}'
gcr_record_put 203 1 "$record_ip_fail"
gcr_vm_public_ip() {
return 1
}
gcr_vm_runner_service() {
printf 'runner %s vm=%s\n' "$2" "$1" >> "$calls"
return 1
}
gcr_deallocate 203 1 completed:failure
grep -q 'diag vm=53 ip= job=203 reason=completed:failure' "$calls_ip_fail"
grep -q 'runner health vm=53' "$calls_ip_fail"
grep -q 'destroy vm=53' "$calls_ip_fail"
test ! -e "$(gcr_record_path 203 1)"
if grep -q 'disabled runner=gcr-203-1' "$calls_ip_fail"; then
printf 'unhealthy terminal runner must not enter idle shutdown path\n' >&2
grep -q 'deregister repo=hinterland/hearth runner=gcr-203-1' "$calls_ip_fail"
test "$(gcr_record_field "$(gcr_record_get 203 1)" status)" = idle_vm
if grep -q 'destroy vm=53' "$calls_ip_fail"; then
printf 'diagnostic IP lookup failure must not bypass safe deregistration\n' >&2
exit 1
fi
@@ -119,10 +107,6 @@ gcr_vm_destroy() {
printf 'destroy-failed vm=%s\n' "$1" >> "$calls_ip_fail"
return 1
}
gcr_vm_runner_service() {
printf 'runner %s vm=%s\n' "$2" "$1" >> "$calls"
[ "$2" != stop ]
}
gcr_deallocate 204 1 completed:failure
cleanup_rec="$(gcr_record_get 204 1)"
test "$(gcr_record_field "$cleanup_rec" status)" = cleanup_pending
@@ -153,11 +137,12 @@ if grep -q '^unexpected-runner 56$' "$calls_ip_fail"; then
fi
# Gitea emits zero-based run_attempt values for initial workflow jobs.
next_body='{"action":"queued","workflow_job":{"id":331,"run_attempt":0,"labels":["nix"]},"repository":{"full_name":"hinterland/hearth"}}'
gcr_read_request() {
gcr_hdr_event_type=workflow_job
gcr_hdr_delivery=test-delivery
gcr_hdr_signature=test-signature
gcr_body='{"action":"queued","workflow_job":{"id":331,"run_attempt":0,"labels":["nix"]},"repository":{"full_name":"hinterland/hearth"}}'
gcr_body="$next_body"
}
gcr_verify_signature() { :; }
gcr_alloc() {
@@ -170,3 +155,18 @@ gcr_respond() { printf '%s:%s\n' "$1" "$2" > "$GCR_STATE_DIR/response"; }
gcr_handle_webhook
test "$(cat "$GCR_STATE_DIR/allocation")" = '331:0:hinterland/hearth:["nix"]'
test "$(cat "$GCR_STATE_DIR/response")" = '202:allocated'
# Signed lifecycle events from another or missing repository cannot mutate an
# existing allocation with the same numeric job identity.
bound='{"job_id":"332","run_attempt":"1","repo":"hinterland/hearth","label":"nix","created_at":"1","ttl_min":480,"vm_id":58,"vm_name":"gcr-332-1","runner_name":"gcr-332-1","server_type":"cx23","location":"nbg1","arch":"amd64","image_id":"424242","bootstrapped":true,"status":"pending_vm"}'
gcr_record_put 332 1 "$bound"
next_body='{"action":"in_progress","workflow_job":{"id":332,"run_attempt":1,"labels":["nix"]},"repository":{"full_name":"other/repo"}}'
gcr_handle_webhook
test "$(gcr_record_field "$(gcr_record_get 332 1)" status)" = pending_vm
next_body='{"action":"completed","workflow_job":{"id":332,"run_attempt":1,"conclusion":"success","labels":["nix"]},"repository":{"full_name":"other/repo"}}'
gcr_handle_webhook
test "$(gcr_record_field "$(gcr_record_get 332 1)" status)" = pending_vm
next_body='{"action":"completed","workflow_job":{"id":332,"run_attempt":1,"conclusion":"success","labels":["nix"]},"repository":{}}'
gcr_handle_webhook
test "$(cat "$GCR_STATE_DIR/response")" = '400:malformed payload'
test "$(gcr_record_field "$(gcr_record_get 332 1)" status)" = pending_vm