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
+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