Files
hearth/package/gitea-runner-controller/hcloud.sh
T
yukkop c6a504c951
runner nix smoke / nix label and flake smoke (push) Canceled after 0s
runner ubuntu smoke / ubuntu-latest label smoke (push) Canceled after 0s
fix: gitea controller
2026-11-03 15:17:38 +00:00

1109 lines
46 KiB
Bash

#!/bin/dash
# Hetzner Cloud API wrappers for gitea-runner-controller.
# Requires: HCLOUD_TOKEN_FILE, GCR_HETZNER_LOCATION, GCR_IMAGE_ID,
# GCR_ACT_RUNNER_VERSION, GCR_ACT_RUNNER_SHA256, GCR_NIX_VERSION,
# GCR_NIX_TARBALL_SHA256, GCR_GITEA_URL
# All VMs carry the tag pair gitea-runner-controller=managed plus gcr.* metadata.
GCR_API="https://api.hetzner.cloud/v1"
gcr_image_id_for_arch() {
arch="$1"; label="${2:-}"
nix_image=0
case "$label" in nix|gross-nix-*) nix_image=1 ;; esac
case "$arch:$nix_image" in
amd64:0) [ -n "${GCR_IMAGE_ID:-}" ] && printf '%s' "$GCR_IMAGE_ID" ;;
arm64:0) [ -n "${GCR_ARM_IMAGE_ID:-}" ] && printf '%s' "$GCR_ARM_IMAGE_ID" ;;
amd64:1) [ -n "${GCR_NIX_IMAGE_ID:-}" ] && printf '%s' "$GCR_NIX_IMAGE_ID" ;;
arm64:1) [ -n "${GCR_ARM_NIX_IMAGE_ID:-}" ] && printf '%s' "$GCR_ARM_NIX_IMAGE_ID" ;;
*) return 1 ;;
esac
}
gcr_hcloud_token() {
test -n "${HCLOUD_TOKEN_FILE:-}" && test -r "$HCLOUD_TOKEN_FILE" || {
gcr_log error --ns=hcloud "HCLOUD_TOKEN_FILE missing or unreadable"
return 1
}
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_pair_valid() {
host_key_path="$1"
[ -s "$host_key_path" ] && [ -s "$host_key_path.pub" ] || return 1
derived_public="$(ssh-keygen -y -f "$host_key_path" 2>/dev/null)" || return 1
derived_public="$(printf '%s\n' "$derived_public" | awk 'NR == 1 {print $1 " " $2}')"
expected_public="$(awk 'NR == 1 {print $1 " " $2}' "$host_key_path.pub")"
[ -n "$derived_public" ] && [ "$derived_public" = "$expected_public" ]
}
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
if ! gcr_vm_host_key_pair_valid "$host_key_path"; then
gcr_log error --ns=hcloud "existing SSH host-key pair is invalid job=$1 attempt=$2"
return 1
fi
chmod 0600 "$host_key_path"
chmod 0644 "$host_key_path.pub"
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_pair_valid "$host_key_path"
}
gcr_vm_host_key_userdata() {
host_key_path="$(gcr_vm_host_key_path "$1" "$2")"
gcr_vm_host_key_pair_valid "$host_key_path" || {
gcr_log error --ns=hcloud "SSH host-key pair is invalid job=$1 attempt=$2"
return 1
}
host_public_key="$(awk 'NR == 1 {print $1 " " $2}' "$host_key_path.pub")" \
|| return 1
[ -n "$host_public_key" ] || return 1
cat <<EOF
#cloud-config
# Replace image keys with this VM's unique controller-generated key.
ssh_deletekeys: true
ssh_genkeytypes: [ed25519]
ssh_keys:
ed25519_private: |
$(sed 's/^/ /' "$host_key_path")
ed25519_public: $host_public_key
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")"
gcr_vm_host_key_pair_valid "$known_key_path" || {
gcr_log error --ns=hcloud "cannot pin invalid SSH host-key pair job=$known_job attempt=$known_attempt"
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:-}"
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 "@$auth_header" \
-H 'Content-Type: application/json' \
--data-binary @- \
-o "$GCR_LAST_BODY" \
-w '%{http_code}' \
"$GCR_API$path")" || curl_status="$?"
else
code="$(curl -sS -X "$method" \
-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"
if [ "$curl_status" -ne 0 ]; then
gcr_log warn --ns=hcloud "transport failed path=$path curl=$curl_status http=$code"
return 1
fi
case "$code" in 2??) return 0 ;; esac
gcr_log warn --ns=hcloud "request failed path=$path http=$code body=$(head -c 200 "$GCR_LAST_BODY" | gcr_redact)"
return 1
}
gcr_vm_list_managed() {
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_image="${8:-}"
if ! gcr_hcloud_req GET "/servers?name=$find_name"; then
return 2
fi
find_matches="$(jq -c \
--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"
and .labels["gcr.job-id"] == $job
and .labels["gcr.run-attempt"] == $attempt
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
case "$find_count" in
0) return 1 ;;
1) printf '%s' "$find_matches" | jq -r '.[0].id' ;;
*) return 2 ;;
esac
}
gcr_create_explicitly_rejected() {
case "$1" in
400|401|403|404|405|409|412|422|423) return 0 ;;
*) return 1 ;;
esac
}
gcr_vm_record_create_ambiguous() {
ambiguous_name="$1"; ambiguous_label="$2"; ambiguous_ttl="$3"
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 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, 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"
}
gcr_vm_build_userdata() {
vm_name="$1"; label="$2"; reg_token="$3"
nix_conf='accept-flake-config = true
experimental-features = nix-command flakes
http2 = false
substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
sandbox = false'
runner_config="log:
level: info
runner:
file: /var/lib/gitea-runner/.runner
capacity: 1
timeout: $(printf '%s' "$(gcr_label_profile "$label")" | awk '{print $2}')m
insecure: false
fetch_timeout: 5s
fetch_interval: 2s
labels:
- \"$label:host\""
ssh_key_block=""
if [ -n "${GCR_DEBUG_SSH_PUBKEY:-}" ]; then
ssh_key_block=" - path: /root/.ssh/authorized_keys
permissions: '0600'
content: |
$GCR_DEBUG_SSH_PUBKEY"
fi
# NOTE(yukkop): token reaches only this VM's Hetzner metadata service and
# is used for initial registration, not for later idle-slot assignments.
printf '%s' "#cloud-config
write_files:
$ssh_key_block
- path: /etc/ssh/sshd_config.d/99-gcr-root.conf
permissions: '0644'
content: |
PermitRootLogin prohibit-password
PubkeyAuthentication yes
- path: /etc/nix/nix.conf
content: |
$(printf '%s\n' "$nix_conf" | sed 's/^/ /')
- path: /etc/gitea-runner/config.yaml
content: |
$(printf '%s\n' "$runner_config" | sed 's/^/ /')
- path: /etc/systemd/system/gitea-runner.service
content: |
[Unit]
Description=Gitea on-demand Actions runner
After=network-online.target gcr-bootstrap.service
Requires=gcr-bootstrap.service
[Service]
Type=simple
Environment=GITEA_INSTANCE_URL=$GCR_GITEA_URL
Environment=GITEA_RUNNER_REGISTRATION_TOKEN=$reg_token
ExecStart=/usr/local/bin/act_runner daemon --config /etc/gitea-runner/config.yaml
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
- path: /etc/systemd/system/gcr-bootstrap.service
content: |
[Unit]
Description=Bootstrap gitea-runner for ephemeral CI job
After=network-online.target
Wants=network-online.target
Before=gitea-runner.service
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/usr/local/sbin/gcr-bootstrap
[Install]
WantedBy=multi-user.target
- path: /usr/local/sbin/gcr-bootstrap
permissions: '0700'
content: |
#!/bin/sh
set -eu
exec > /var/log/gcr-bootstrap.log 2>&1
curl -fsSL \"https://nixos.org/releases/nix/$GCR_NIX_VERSION/nix-$GCR_NIX_VERSION-x86_64-linux.tar.xz\" -o /tmp/nix.tar.xz
printf '%s /tmp/nix.tar.xz\n' \"$GCR_NIX_TARBALL_SHA256\" | sha256sum -c -
tar -xJf /tmp/nix.tar.xz -C /tmp
/tmp/nix-$GCR_NIX_VERSION-x86_64-linux/install --no-daemon
rm -rf /tmp/nix*
curl -fsSL \"https://dl.gitea.com/gitea-runner/$GCR_ACT_RUNNER_VERSION/gitea-runner-$GCR_ACT_RUNNER_VERSION-linux-amd64\" -o /usr/local/bin/gitea-runner
printf '%s /usr/local/bin/gitea-runner\n' \"$GCR_ACT_RUNNER_SHA256\" | sha256sum -c -
chmod 0755 /usr/local/bin/gitea-runner
mkdir -p /var/lib/gitea-runner
runcmd:
- [ sh, -c, 'systemctl enable --now sshd.service 2>/dev/null || systemctl enable --now ssh 2>/dev/null || true' ]
- [ sh, -c, 'systemctl restart sshd.service 2>/dev/null || systemctl restart ssh 2>/dev/null || true' ]
- [ systemctl, enable, --now, gitea-runner.service ]
"
}
# gcr_vm_create NAME LABEL SERVER_TYPE TTL_MIN REG_TOKEN JOB_ID ATTEMPT REPO
# 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
candidate_n=0
while read -r candidate_type candidate_loc candidate_arch; do
[ -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" "$budget_key"; then
gcr_lock_release budget
gcr_log error --ns=hcloud "budget reservation write failed label=$label type=$candidate_type"
return 1
fi
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" \
--arg image "$image_id" \
--arg loc "$candidate_loc" \
--arg jid "$job_id" \
--arg att "$attempt" \
--arg repo "$repo" \
--arg label "$label" \
--arg arch "$candidate_arch" \
--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,
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.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
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" \
"$image_id")" \
|| find_status="$?"
if [ "$find_status" -eq 0 ]; then
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
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" \
"$image_id" "$budget_key" true; then
gcr_log error --ns=hcloud "cannot persist ambiguous create job=$job_id type=$candidate_type"
fi
return 2
fi
if [ "$candidate_n" -le 3 ]; then
sleep 5
else
sleep 1
fi
done <<EOF
$candidates
EOF
return 1
}
# gcr_vm_destroy SERVER_ID — success means DELETE returned HTTP 2xx.
gcr_vm_destroy() {
if ! gcr_hcloud_req DELETE "/servers/$1"; then
gcr_log warn --ns=hcloud "destroy failed or already gone: server $1"
return 1
fi
}
# Only cleanup records establish prior ownership, making DELETE 404 a
# confirmed-absent success rather than an ambiguous lookup failure.
gcr_vm_destroy_owned() {
gcr_vm_destroy "$1" && return 0
[ "${GCR_LAST_HTTP:-}" = "404" ]
}
# Caller holds the lifecycle path's existing ownership locks.
gcr_vm_cleanup_pending() {
cleanup_job="$1"; cleanup_attempt="$2"; cleanup_rec="$3"
cleanup_vm_id="$(gcr_record_field "$cleanup_rec" vm_id)"
if [ "$(gcr_record_field "$cleanup_rec" cleanup_vm_destroyed)" != "true" ]; then
gcr_vm_destroy_owned "$cleanup_vm_id" || return 1
cleanup_rec="$(printf '%s' "$cleanup_rec" | jq -c '.cleanup_vm_destroyed = true')"
gcr_record_put "$cleanup_job" "$cleanup_attempt" "$cleanup_rec" || return 1
fi
if [ "$(gcr_record_field "$cleanup_rec" cleanup_refund_budget)" = "true" ] \
&& [ "$(gcr_record_field "$cleanup_rec" cleanup_budget_released)" != "true" ]; then
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_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 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 \
--arg reason "$cleanup_reason" --argjson refund "$cleanup_refund" \
'.status = "cleanup_pending"
| .cleanup_reason = $reason
| .cleanup_refund_budget = $refund
| .cleanup_vm_destroyed = false
| .cleanup_budget_released = false')"
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"
}
# Caller holds allocation and admission locks. A failed primary write first
# persists cleanup ownership; reservation is released only after destroy.
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, 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
if ! gcr_vm_cleanup_start "$record_job" "$record_attempt" "$record_rec" \
state-write-failed true; then
cleanup_rec="$(gcr_record_get "$record_job" "$record_attempt")"
[ "$(gcr_record_field "$cleanup_rec" status)" = "cleanup_pending" ] && return 1
gcr_log error --ns=alloc "cannot persist cleanup record job=$record_job vm=$record_vm_id"
return 1
fi
return 1
}
gcr_vm_public_ip() {
# gcr_vm_public_ip SERVER_ID -> ipv4 or empty
if gcr_hcloud_req GET "/servers/$1"; then
jq -r '.server.public_net.ipv4.ip // ""' "$GCR_LAST_BODY"
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
rebuild_action_id="$(jq -er --arg vm "$rebuild_vm_id" \
'.action
| select((.id | type) == "number")
| select(.command == "rebuild_server")
| select(.status == "running" or .status == "success")
| select([.resources[]? | select(.type == "server") | (.id | tostring)] == [$vm])
| .id' "$GCR_LAST_BODY")" || {
gcr_log warn --ns=hcloud \
"rebuild response validation failed server=$rebuild_vm_id expected_command=rebuild_server"
return 1
}
printf '%s' "$rebuild_action_id"
}
# 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_server")
| select([.resources[]? | select(.type == "server") | (.id | tostring)] == [$vm])
| .status
| select(. == "running" or . == "success" or . == "error")' \
"$GCR_LAST_BODY")" || {
gcr_log warn --ns=hcloud \
"rebuild action validation failed server=$rebuild_vm_id action=$rebuild_action_id expected_command=rebuild_server"
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
verify_ip="$(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((.location.name // .datacenter.location.name // "") == $location)
| select((.image.id | tostring) == $image)
| .public_net.ipv4.ip
| select(type == "string" and length > 0)' "$GCR_LAST_BODY")" || {
gcr_log warn --ns=hcloud \
"rebuilt server validation failed server=$verify_vm_id expected_type=$verify_type expected_location=$verify_location expected_arch=$verify_arch expected_image=$verify_image"
return 1
}
printf '%s' "$verify_ip"
}
# 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() {
vm_id="$1"; action="$2"
ip="$(gcr_vm_public_ip "$vm_id")" || return 1
[ -n "$ip" ] || return 1
gcr_vm_runner_service_pinned "$ip" \
"${GCR_SSH_KNOWN_HOSTS_FILE:-}" "$action"
}
gcr_vm_runner_service_pinned() {
ip="$1"; known_hosts_file="$2"; action="$3"
case "$action" in
start|stop) service_command="systemctl $action gitea-runner.service" ;;
health) service_command="systemctl is-active --quiet gitea-runner.service" ;;
*) return 1 ;;
esac
test -n "${GCR_SSH_PRIVKEY_FILE:-}" && test -r "$GCR_SSH_PRIVKEY_FILE" || return 1
test -n "$known_hosts_file" && test -r "$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=yes -o UserKnownHostsFile=$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
fi
rm -f "$key_tmp"
return 1
}
gcr_vm_collect_diagnostics() {
vm_id="$1"; ip="$2"; job_id="$3"; reason="$4"; diag_attempt="${5:-}"
[ "${GCR_DESTROY_DIAGNOSTICS:-1}" = "1" ] || return 0
[ -n "$ip" ] || return 0
test -n "${GCR_SSH_PRIVKEY_FILE:-}" && test -r "$GCR_SSH_PRIVKEY_FILE" || {
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=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"
if timeout -k 5 "$timeout_sec" ssh $ssh_opts "root@$ip" \
'set +e
export LC_ALL=C
printf "== time ==\n"; date -u
printf "== uptime ==\n"; uptime
printf "== memory ==\n"; free -h
printf "== disk ==\n"; df -h / /nix /var/lib 2>/dev/null || df -h
printf "== pressure ==\n"; cat /proc/pressure/cpu /proc/pressure/memory /proc/pressure/io 2>/dev/null
printf "== kernel failure signals ==\n"; dmesg -T 2>/dev/null | grep -Ei "out of memory|oom-kill|killed process|no space|I/O error|EXT4-fs error|xfs.*error|nvme.*error" | tail -n 80
printf "== runner service ==\n"; systemctl show gitea-runner.service -p ActiveState -p SubState -p Result -p ExecMainStatus -p ExecMainCode -p NRestarts 2>/dev/null
printf "== bootstrap service ==\n"; systemctl show gcr-bootstrap.service -p ActiveState -p SubState -p Result -p ExecMainStatus -p ExecMainCode 2>/dev/null
printf "== cloud-init ==\n"; if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null | head -n 20; else printf "cloud-init unavailable\\n"; fi
printf "== process sample ==\n"; ps -eo pid,ppid,stat,etime,comm 2>/dev/null | head -n 80' \
> "$diag_out" 2>&1; then
gcr_redact < "$diag_out" >&2
gcr_log warn --ns=hcloud "pre-destroy diagnostics complete vm=$vm_id job=$job_id reason=$reason"
else
gcr_redact < "$diag_out" >&2
gcr_log warn --ns=hcloud "pre-destroy diagnostics failed vm=$vm_id job=$job_id reason=$reason"
fi
rm -f "$key_tmp" "$diag_out"
return 0
}
gcr_ssh_error_category() {
error_text="$(cat "$1")"
case "$error_text" in
*"REMOTE HOST IDENTIFICATION HAS CHANGED"*|*"Host key verification failed"*)
printf 'host-key-verification'
;;
*"Permission denied"*|*"Too many authentication failures"*)
printf 'authentication'
;;
*"Connection refused"*|*"Connection timed out"*|*"Operation timed out"*|\
*"No route to host"*|*"Network is unreachable"*|*"Connection reset"*|\
*"Could not resolve hostname"*|*"Name or service not known"*)
printf 'connectivity-or-sshd'
;;
*"Bad configuration option"*|*"Could not open"*|*"Load key"*)
printf 'ssh-client-error'
;;
*)
printf 'unknown'
;;
esac
}
gcr_ssh_run_captured() {
captured_error_file="$1"; shift
(
if ! ulimit -f 8; then
exit 125
fi
"$@"
) 2>"$captured_error_file"
}
gcr_ssh_temp_cleanup() {
[ -z "${1:-}" ] || rm -f "$1"
[ -z "${2:-}" ] || rm -f "$2"
}
# 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_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)"
retire_delete_not_before="$(gcr_record_field \
"$retire_rec" retirement_delete_not_before)"
case "$retire_delete_not_before" in *[!0-9]*) return 1 ;; esac
retire_status=0
gcr_gitea_deregister_runner_exact "$retire_repo" "$retire_runner" \
"$retire_delete_not_before" \
|| retire_status="$?"
case "$retire_status" in
0) ;;
2)
gcr_log info --ns=gitea \
"busy runner retirement pending job=$retire_job repo=$retire_repo name=$retire_runner"
return 2
;;
3)
retire_delay="${GCR_RECONCILE_INTERVAL_SEC:-60}"
case "$retire_delay" in ''|0|*[!0-9]*) return 1 ;; esac
retire_barrier_now="$(gcr_now_epoch)"
case "$retire_barrier_now" in ''|*[!0-9]*) return 1 ;; esac
retire_delete_not_before="$((retire_barrier_now + retire_delay))"
retire_rec="$(printf '%s' "$retire_rec" | jq -c \
--arg not_before "$retire_delete_not_before" \
'.retirement_delete_not_before = ($not_before | tonumber)')" \
|| return 1
gcr_record_put "$retire_job" "$retire_attempt" "$retire_rec" \
|| return 1
gcr_log info --ns=gitea \
"disabled runner retirement pending job=$retire_job repo=$retire_repo name=$retire_runner"
return 2
;;
*)
gcr_log warn --ns=gitea \
"runner retirement pending job=$retire_job repo=$retire_repo name=$retire_runner"
return 2
;;
esac
if [ "$retire_now" -ge "$retire_expires" ]; then
gcr_vm_cleanup_start "$retire_job" "$retire_attempt" "$retire_rec" \
retirement-expired false
return "$?"
fi
retire_idle="$(printf '%s' "$retire_rec" | jq -c \
'.status = "idle_vm"
| .repo = "" | .label = "" | .runner_name = ""
| .bootstrapped = false
| del(.retirement_repo, .retirement_runner_name,
.retirement_delete_not_before)')" || 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)"
case "$finish_vm_id" in
''|0|null|*[!0-9]*)
gcr_record_del "$finish_job" "$finish_attempt"
return 0
;;
esac
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 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-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
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
}
# 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
substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
sandbox = false'
runner_config="log:
level: info
runner:
file: /var/lib/gitea-runner/.runner
capacity: 1
timeout: ${ttl_min}m
insecure: false
fetch_timeout: 5s
fetch_interval: 2s
labels:
- \"$label:host\""
cat <<BSEOF
exec >/var/log/gcr-bootstrap.log 2>&1
set -eu
mkdir -p /etc/nix /etc/gitea-runner /var/lib/gitea-runner /usr/local/bin
cat > /etc/nix/nix.conf <<'NIXEOF'
$nix_conf
NIXEOF
cat > /etc/gitea-runner/config.yaml <<'CFGEOF'
$runner_config
CFGEOF
cat > /usr/local/sbin/gcr-runner-start <<STARTEOF
#!/bin/sh
set -eu
exec /usr/local/bin/gitea-runner daemon --config /etc/gitea-runner/config.yaml
STARTEOF
chmod 0700 /usr/local/sbin/gcr-runner-start
cat > /etc/systemd/system/gitea-runner.service <<UNITEOF
[Unit]
Description=Gitea on-demand Actions runner
After=network-online.target
[Service]
Type=simple
WorkingDirectory=/var/lib/gitea-runner
Environment=HOME=/var/lib/gitea-runner
ExecStart=/usr/local/sbin/gcr-runner-start
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
UNITEOF
cat > /usr/local/sbin/gcr-install <<INSEOF
#!/bin/sh
set -eu
nix_arch=""
nix_sha=""
case "$label" in
nix|gross-nix-*)
case "\$(uname -m)" in
x86_64)
nix_arch=x86_64-linux
nix_sha="$GCR_NIX_TARBALL_SHA256"
;;
aarch64|arm64)
nix_arch=aarch64-linux
nix_sha="$GCR_ARM_NIX_TARBALL_SHA256"
;;
*)
echo "unsupported arch for Nix bootstrap: $(uname -m)" >&2
exit 1
;;
esac
curl -fsSL "https://releases.nixos.org/nix/nix-$GCR_NIX_VERSION/nix-$GCR_NIX_VERSION-\\\$nix_arch.tar.xz" -o /tmp/nix.tar.xz
printf '%s /tmp/nix.tar.xz\n' "\\\$nix_sha" | sha256sum -c -
tar -xJf /tmp/nix.tar.xz -C /tmp
mkdir -p /nix
getent group nixbld >/dev/null 2>&1 || groupadd --system nixbld
for nixbld_user in 1 2 3 4 5 6 7 8 9 10; do
if ! id "nixbld\\\$nixbld_user" >/dev/null 2>&1; then
useradd --system --no-create-home --shell /usr/sbin/nologin \
--gid nixbld "nixbld\\\$nixbld_user"
fi
usermod --append --groups nixbld "nixbld\\\$nixbld_user"
done
/tmp/nix-$GCR_NIX_VERSION-\\\$nix_arch/install --no-daemon
ln -sf /root/.nix-profile/bin/nix /usr/local/bin/nix
rm -rf /tmp/nix*
;;
esac
case "$label" in
nix|gross-nix-*)
if command -v apt-get >/dev/null 2>&1; then
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq nodejs
fi
;;
esac
case "\$(uname -m)" in
x86_64) runner_arch=amd64 ;;
aarch64|arm64) runner_arch=arm64 ;;
*) echo "unsupported arch for runner bootstrap: \$(uname -m)" >&2; exit 1 ;;
esac
curl -fsSL "https://dl.gitea.com/gitea-runner/$GCR_ACT_RUNNER_VERSION/gitea-runner-$GCR_ACT_RUNNER_VERSION-linux-\\\$runner_arch" -o /usr/local/bin/gitea-runner
if [ "\\\$runner_arch" = amd64 ]; then
printf '%s /usr/local/bin/gitea-runner\n' "$GCR_ACT_RUNNER_SHA256" | sha256sum -c -
fi
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
systemctl disable --now gitea-runner.service 2>/dev/null || true
if [ ! -s /var/lib/gitea-runner/.runner ]; then
/usr/local/bin/gitea-runner register --no-interactive --ephemeral \
--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
BSEOF
}
# gcr_vm_bootstrap_ssh IP LABEL REG_TOKEN RUNNER_NAME KNOWN_HOSTS JOB ATTEMPT VM
# Waits for strict-pinned SSH readiness, then installs and registers without
# starting the daemon. Controller persists exact runner ID before activation.
gcr_vm_bootstrap_ssh() (
ip="$1"; label="$2"; reg_token="$3"; runner_name="$4"
known_hosts_file="${5:-${GCR_SSH_KNOWN_HOSTS_FILE:-}}"
job_id="${6:-}"; attempt="${7:-}"; vm_id="${8:-}"
key_tmp=""
ssh_error_file=""
trap 'gcr_ssh_temp_cleanup "${key_tmp:-}" "${ssh_error_file:-}"' EXIT
trap 'exit 1' HUP INT TERM
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=yes -o UserKnownHostsFile=$known_hosts_file -o ConnectTimeout=5 -o BatchMode=yes"
ssh_error_file="$(mktemp "${TMPDIR:-/tmp}/gcr-ssh-error.XXXXXX")"
chmod 0600 "$ssh_error_file"
waited=0
ssh_status=0
while :; do
if gcr_ssh_run_captured "$ssh_error_file" \
ssh $SSH_OPTS "root@$ip" true; then
break
else
ssh_status="$?"
fi
waited=$((waited + 5))
[ "$waited" -ge 900 ] && {
ssh_category="$(gcr_ssh_error_category "$ssh_error_file")"
gcr_log warn --ns=hcloud \
"SSH readiness failed stage=ssh-readiness category=$ssh_category exit=$ssh_status after=${waited}s ip=$ip"
return 1
}
sleep 5
done
ttl_min="$(printf '%s' "$(gcr_label_profile "$label")" | awk '{print $2}')"
script="$(gcr_bootstrap_script "$label" "$reg_token" "$ttl_min" "$runner_name")"
if printf '%s' "$script" | gcr_ssh_run_captured "$ssh_error_file" \
ssh $SSH_OPTS "root@$ip" sh -s; then
return 0
else
ssh_status="$?"
fi
ssh_category="$(gcr_ssh_error_category "$ssh_error_file")"
if [ "$ssh_status" -eq 255 ]; then
diagnostics_reason=bootstrap-transport-failed
if [ "$ssh_category" = unknown ]; then
ssh_category=ssh-client-error
fi
gcr_log warn --ns=hcloud \
"SSH bootstrap failed stage=ssh-transport category=$ssh_category exit=$ssh_status ip=$ip"
else
diagnostics_reason=bootstrap-command-failed
gcr_log warn --ns=hcloud \
"SSH bootstrap failed stage=remote-bootstrap-command category=remote-bootstrap-command-failed exit=$ssh_status ip=$ip"
fi
if [ -n "$job_id" ] && [ -n "$attempt" ] && [ -n "$vm_id" ]; then
gcr_vm_collect_diagnostics "$vm_id" "$ip" "$job_id" \
"$diagnostics_reason" "$attempt" || true
fi
return 1
)