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
+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
;;
*)