Repository navigation
Expand file tree
/
Copy pathcloud-init.sh.tmpl
More file actions
436 lines (371 loc) · 16 KB
/
Copy pathcloud-init.sh.tmpl
File metadata and controls
436 lines (371 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#!/bin/bash -x
# Decode the complete configuration as data, never as shell substitutions.
if [[ $(whoami) == root ]]; then
base64 -d > /home/ubuntu/runner-config.json <<'CONFIG'
${CONFIG_B64}
CONFIG
chown ubuntu:ubuntu /home/ubuntu/runner-config.json
chmod 600 /home/ubuntu/runner-config.json
fi
if [[ $(whoami) == root ]]; then
echo "Applying Network Fix: Detecting interface and ignoring MAC mismatch..."
ETH_DEV=$(ip -o link show up | awk -F': ' '{print $2}' | grep -vE "^(lo|docker|veth|br|virbr)" | head -n 1)
echo "Detected primary interface: $ETH_DEV"
if [[ -z "$ETH_DEV" ]]; then
echo "WARNING: Could not detect interface, falling back to enp3s0"
ETH_DEV="enp3s0"
fi
cat <<EOF > /etc/netplan/99-force-dhcp.yaml
network:
version: 2
ethernets:
$ETH_DEV:
dhcp4: true
dhcp6: false
match:
name: $ETH_DEV
set-name: $ETH_DEV
EOF
rm -f /etc/netplan/50-cloud-init.yaml
chmod 600 /etc/netplan/99-force-dhcp.yaml
netplan apply
ip link set $ETH_DEV up
echo "Waiting for DHCP on $ETH_DEV..."
sleep 5
fi
if [[ $(whoami) == root ]]; then
# temporary hack to disable coredump to prevent OOM
systemctl mask systemd-coredump.socket
systemctl daemon-reload
systemctl stop systemd-coredump.socket
echo "Respawning myself as non root"
chmod 777 $0 # yay
# use su instead of su to let new shell able to use ulimit
exec su ubuntu -c "bash $0"
fi
# If the network is still not ready after MAX_WAIT seconds,
# force a reboot to retry the initialization process.
MAX_WAIT=120
WAITED=0
while ! ip route get 10.1.0.1 >/dev/null 2>&1; do
echo "Waiting for network..."
sleep 2
WAITED=$((WAITED+2))
if [ "$WAITED" -ge "$MAX_WAIT" ]; then
echo "Network not ready after $MAX_WAIT seconds, rebooting..."
sudo shutdown -h now
exit 0
fi
done
cloud_image_serial=$(cat /etc/cloud/build.info |grep serial|awk '{print $2}')
runner_image_version=$(cat /imagegeneration/imagedata.json|jq .[1].detail|grep -oP "Version: [\d\.]+"|awk '{print $2}')
set +x
payload_file=/home/ubuntu/runner-config.json
RUNNER_NAME=$(jq -r '.settings.runner_name[:64]' "$payload_file")
RUNNERGROUP=$(jq -r '.settings.runner_group // ""' "$payload_file")
RUNNER_URL=$(jq -r '.payload.registration.url' "$payload_file")
RUNNER_LABELS=$(jq -r '.payload.registration.labels | join(",")' "$payload_file")
REGISTRATION_TOKEN=$(jq -r '.payload.registration.token' "$payload_file")
DOCKER_USER=$(jq -r '.settings.docker_user // ""' "$payload_file")
DOCKER_PASS=$(jq -r '.settings.docker_pass // ""' "$payload_file")
RUNNER_VER=$(jq -r '.settings.runner_version' "$payload_file")
dd_host="10.1.0.1"
metric_tag() { printf '%s' "$1" | tr '|,: \r\n' '______'; }
function send_metrics() {
metrics="github.actions.$1:$${2:-1}|$${3:-c}|#runner_group:$(metric_tag "$RUNNERGROUP"),#runner_image_version:$runner_image_version,#cloud_image_serial:$cloud_image_serial"
if [[ ! -z "$4" ]]; then metrics="$metrics,$4"; fi
echo "Send metrics $metrics to $dd_host"
echo -n "$metrics" > /dev/udp/$dd_host/8125
}
function send_logs() {
local entry
entry=$(jq -cn --arg event "$1" --arg detail "$${2:-}" \
--arg runner "$RUNNER_NAME" --arg group "$RUNNERGROUP" \
--arg image "$${runner_image_version:-unknown}" --arg serial "$${cloud_image_serial:-unknown}" \
'{runner_name: $runner, runner_group: $group,
runner_image_version: $image, cloud_image_serial: $serial} + {($event): $detail}')
echo "Send logs $entry to $dd_host"
echo -n "$entry" > /dev/udp/$dd_host/10518
}
echo "Runner: $RUNNER_NAME"
send_metrics runners.started
# GHASR-97: a booted VM is not a usable runner. This gauge used to report "1"
# unconditionally, so a VM whose runner never started, or had crashed, still
# looked healthy to monitoring. Report the liveness of Runner.Listener instead,
# and emit an explicit 0 rather than going silent so the pool size stays
# alertable.
function runner_is_up() {
pgrep -f '[R]unner\.Listener' >/dev/null
}
function send_up_gauge() {
while true; do
if runner_is_up; then
send_metrics runners.up "1" "g" "#runner_name:$RUNNER_NAME"
else
send_metrics runners.up "0" "g" "#runner_name:$RUNNER_NAME"
fi
sleep 30
done
}
send_up_gauge &
echo "Dropping traffic to metadata endpoint to avoid timeout"
sudo iptables -I OUTPUT -d 169.254.169.254/32 -j REJECT --reject-with icmp-port-unreachable
# echo "Making it faster on cheap SSDs"
sudo mount -o remount,defaults,nobarrier / /
# echo "Creating swapfile"
#sudo fallocate -l 2G /swapfile
#sudo chmod 600 /swapfile
#sudo mkswap /swapfile
#sudo swapon /swapfile
#sudo sysctl -w vm.swappiness=20
#echo "TEMP replace moby with docker"
#sudo apt remove -y moby*
#sudo mkdir -m 0755 -p /etc/apt/keyrings
#curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
#echo \
# "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
# "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \
# sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
#sudo apt-get update
#sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
echo "Making docker socket less secure"
sudo chmod 777 /var/run/docker.sock
# GHASR-92 / GHASR-95: trust the two per-host pull-through caches. Both serve
# plain HTTP on the internal gateway (registry-ghcr.internal:5556 and
# registry-dockerhub.internal:5555 -> 10.1.0.1, resolved via libvirt DNS), so
# docker must treat them as insecure registries. Merge into any existing
# daemon.json rather than clobbering it.
#
# The two caches are reached differently:
# - ghcr: by rewriting the image name (the Kong-ee vars.GHCR_REGISTRY switch),
# so insecure-registries is all docker needs from us.
# - Docker Hub: by registry-mirrors, so image names in workflows stay as-is.
# Both keys are required — with only registry-mirrors docker does not error,
# it silently falls back to upstream and the cache never gets a hit.
echo "Configuring pull-through caches as insecure registries"
sudo mkdir -p /etc/docker
existing_daemon=$(cat /etc/docker/daemon.json 2>/dev/null)
# treat missing/empty/invalid json as {} so a bad file can't wipe the config
if ! echo "$existing_daemon" | jq -e . >/dev/null 2>&1; then
existing_daemon='{}'
fi
merged_daemon=$(echo "$existing_daemon" | jq '
.["insecure-registries"] = ((.["insecure-registries"] // []) + ["registry-ghcr.internal:5556", "registry-dockerhub.internal:5555"] | unique)
| .["registry-mirrors"] = ((.["registry-mirrors"] // []) + ["http://registry-dockerhub.internal:5555"] | unique)
')
# only overwrite if jq produced valid output, otherwise leave the file untouched
if [[ -n "$merged_daemon" ]]; then
echo "$merged_daemon" | sudo tee /etc/docker/daemon.json > /dev/null
sudo systemctl restart docker
fi
# socket perms are reset by the restart above
sudo chmod 777 /var/run/docker.sock
if [[ ! -z "$DOCKER_USER" && ! -z "$DOCKER_PASS" ]]; then
echo "Login docker"
echo "$DOCKER_PASS" | docker login --username $DOCKER_USER --password-stdin
fi
echo "Update source"
#sudo sysctl net.ipv6.conf.all.disable_ipv6=1
sudo sed -i 's/azure\.archive\.ubuntu\.com\/ubuntu/mirror\.hetzner\.com\/ubuntu\/packages/' /etc/apt/sources.list
sudo sed -i 's/archive\.ubuntu\.com\/ubuntu/mirror\.hetzner\.com\/ubuntu\/packages/' /etc/apt/sources.list
sudo sed -i 's/security\.ubuntu\.com\/ubuntu/mirror\.hetzner\.com\/ubuntu\/packages/' /etc/apt/sources.list
echo "Start installing actions runner $RUNNER_VER"
echo "User $USER, UID: $(id)"
# Re-source the env vars to evaluate variables like $HOME
source /etc/environment
cd # goto my home
mkdir actions-runner && cd actions-runner
ARCH=$(arch)
if [[ $ARCH == "x86_64" ]]; then ARCH=x64
else ARCH=arm64
fi
cat << 'EOF' > start.sh
#!/bin/bash
date +%s%3N > /tmp/job_start.ts
EOF
cat << 'EOF' > stop.sh
#!/bin/bash
now_ts=$(date +%s%3N)
start_ts=$(cat /tmp/job_start.ts)
job_duration_ms=$((now_ts - start_ts))
payload_file=/home/ubuntu/runner-config.json
ARCH=$(arch)
if [[ $ARCH == "x86_64" ]]; then ARCH=x64
else ARCH=arm64
fi
tags=$(jq -r '[["runner_group", .settings.runner_group],
["repo", env.GITHUB_REPOSITORY], ["workflow", env.GITHUB_WORKFLOW],
["job", env.GITHUB_JOB]]
| map(.[0] + ":" + ((.[1] // "unknown") | tostring | gsub("[|,\r\n ]"; "_"))) | join(",")' "$payload_file")
function send_metrics() {
metrics="github.actions.$1:$${2:-1}|$${3:-c}|#$tags,arch:$ARCH"
echo "Send metrics $metrics to 10.1.0.1"
echo -n "$metrics" > /dev/udp/10.1.0.1/8125
}
send_metrics jobs.repo
send_metrics jobs.duration $job_duration_ms "ms|@1"
EOF
curl -o actions-runner-linux-$${ARCH}-$RUNNER_VER.tar.gz -L https://github.com/actions/runner/releases/download/v$RUNNER_VER/actions-runner-linux-$${ARCH}-$RUNNER_VER.tar.gz
tar xzf ./actions-runner-linux-$${ARCH}-$RUNNER_VER.tar.gz
sudo mkdir /work
sudo chown $USER /work
cat /imagegeneration/imagedata.json|jq ".[1].detail |= .+ \"\nCloud Image Serial: $cloud_image_serial\"" > .setup_info
# Keep registration ephemeral on the first attempt; do not patch .runner later.
args=(--unattended --replace --ephemeral --name "$RUNNER_NAME" --work /work --url "$RUNNER_URL")
if [[ -n $RUNNER_LABELS ]]; then args+=(--labels "$RUNNER_LABELS"); fi
if jq -e '.payload.schema_version == 2' "$payload_file" >/dev/null; then args+=(--no-default-labels); fi
if [[ -n $RUNNERGROUP ]]; then args+=(--runnergroup "$RUNNERGROUP"); fi
if ! ./config.sh "$${args[@]}" --token "$REGISTRATION_TOKEN"; then
unset REGISTRATION_TOKEN
send_logs bootstrap_failed 'Runner registration failed'
sudo poweroff
exit 1
fi
unset REGISTRATION_TOKEN
if [[ ! -f /home/ubuntu/actions-runner/.runner ]]; then
send_logs bootstrap_failed 'Runner configuration is missing'
sudo poweroff
exit 1
fi
send_metrics runners.registered
provision_duration_ms=$(awk '{print $1*1000}' /proc/uptime)
send_metrics runner.provision_duration $provision_duration_ms "ms|@1"
# GHASR-97: Runner.Listener can wedge after it has claimed a job — the process
# stays alive on an established but dead broker connection, never times out and
# never retries. GitHub drops the runner on heartbeat timeout, but the host sees
# the domain as running and never rebuilds it, so the worker is lost for good.
#
# Detect that specific state and power off. loop.sh then rebuilds the VM through
# the same path a normally finished job takes.
#
# The two guards below are what keep this from repeating the mistake of the IRQ
# watchdog it replaces, which could not tell a wedged VM from an idle one:
# - only a runner that already claimed a job can wedge this way, so an idle
# runner never matches;
# - a job genuinely in progress has a Runner.Worker, so it is left alone.
function runner_watchdog() {
diag_dir=/home/ubuntu/actions-runner/_diag
stall_limit=600
while true; do
sleep 60
diag=$(ls -t $diag_dir/Runner_*.log 2>/dev/null | head -n 1)
if [[ -z $diag ]]; then
continue
fi
if ! grep -q 'Acknowledging runner request' "$diag"; then
continue
fi
if pgrep -f '[R]unner\.Worker' >/dev/null; then
continue
fi
age=$(( $(date +%s) - $(stat -c %Y "$diag") ))
if [[ $age -gt $stall_limit ]]; then
send_metrics runners.anomaly "1" "c" "#runner_name:$RUNNER_NAME,#type:listener_stalled"
send_logs runner_log "Listener stalled $age seconds after claiming a job, powering off for rebuild"
sleep 2 # let the UDP metric leave before the interface goes down
sudo poweroff
return
fi
done
}
runner_watchdog &
# GHASR-97: the watchdog above only covers a listener that wedges after claiming
# a job. A listener that never reaches "Listening for Jobs" is equally invisible
# to the host, so bound the provisioning phase too. A healthy VM gets there in
# well under a minute, which makes ten minutes a deliberately loose bound.
function provision_watchdog() {
sleep 600
if ! grep -qs 'Listening for Jobs' /home/ubuntu/actions-runner/_diag/Runner_*.log; then
send_metrics runners.anomaly "1" "c" "#runner_name:$RUNNER_NAME,#type:never_listening"
send_logs runner_log "Runner never reached 'Listening for Jobs', powering off for rebuild"
sleep 2
sudo poweroff
fi
}
provision_watchdog &
# GHASR-107: measured on a live runner, the listener acknowledges the job 1.9s
# before Runner.Worker exists, so the ack is the only signal that beats pgrep.
# It sits behind a server flag, so keep JobDispatcher's own line as a fallback.
function claim_count() {
grep -hoE "Acknowledging runner request|Job request [0-9]+ for plan " \
/home/ubuntu/actions-runner/_diag/Runner_*.log 2>/dev/null | wc -l
}
# A claim is never removed from the log, so this answers "has this runner been
# handed a job at all", which is what the idle deadline needs. Waiting on one
# specific claim has to compare counts instead - see await_worker_or_recycle.
function job_in_flight() {
[[ -f /tmp/job_start.ts ]] && return 0
pgrep -f '[R]unner\.Worker' >/dev/null && return 0
[[ $(claim_count) -gt 0 ]]
}
# GHASR-107: a claimed job owns the VM, and finishing it powers the VM off. Bound
# that handoff so a claim that never produces a worker cannot park the VM here
# forever waiting for something that is not coming.
#
# The deadline has to clear a healthy retry storm, or it kills a job that was
# still coming. GetJobMessageAsync is wrapped in RetryRequest with maxAttempts=5
# and a 5-15s backoff, over an HTTP layer whose SendTimeout is 100s, so the
# worst case a working runner can legitimately spend here is 5*100 + 4*15 = 560s.
#
# A 404/409/422 on that fetch sends the listener back to listening, so the claim
# can evaporate and the runner go on serving. Restart the wait on a fresh claim
# rather than powering off underneath it, and re-check right before giving up.
function await_worker_or_recycle() {
local limit=900 seen deadline now
seen=$(claim_count)
deadline=$(( $(date +%s) + limit ))
while true; do
pgrep -f '[R]unner\.Worker' >/dev/null && return
now=$(claim_count)
if [[ $now -gt $seen ]]; then
seen=$now
deadline=$(( $(date +%s) + limit ))
fi
[[ $(date +%s) -ge $deadline ]] && break
sleep 10
done
send_metrics runners.anomaly "1" "c" "#runner_name:$RUNNER_NAME,#type:claim_without_worker"
send_logs runner_log "Job claimed but no worker started within $limit seconds, powering off for rebuild"
sleep 2 # let the UDP metric leave before the interface goes down
sudo poweroff
}
# GHASR-107: a warm spare stays dispatchable until the instant it powers off, so
# confirm it is still idle over a window rather than once, and jitter the
# deadline so spares booted together do not expire into one burst of work.
function idle_watchdog() {
local waited=$((300 + RANDOM % 120))
sleep $waited
for _ in 1 2 3; do
if job_in_flight; then
send_metrics runners.anomaly "1" "c" "#runner_name:$RUNNER_NAME,#type:idle_timeout_aborted"
send_logs runner_log 'Job claimed while the idle timer fired, cancelling recycle'
await_worker_or_recycle
return
fi
sleep 5
done
send_metrics runners.anomaly "1" "c" "#runner_name:$RUNNER_NAME,#type:idle_timeout"
send_logs runner_log "No job started within $waited seconds of listening, powering off for reassignment"
sleep 2 # let the UDP metric leave before the interface goes down
sudo poweroff
}
export ACTIONS_RUNNER_HOOK_JOB_STARTED=/home/ubuntu/actions-runner/start.sh
export ACTIONS_RUNNER_HOOK_JOB_COMPLETED=/home/ubuntu/actions-runner/stop.sh
idle_watchdog_started=false
IFS=$'\r\n'
./run.sh | grep --line-buffered -vE "^[ \t|/_\\()',\.\-]*$" | grep --line-buffered -vF 'Self-hosted runner registration' | while read -r line; do
echo "$line"
send_logs runner_log "$line"
if [[ $idle_watchdog_started == false && "$line" == *"Listening for Jobs"* ]]; then
idle_watchdog_started=true
idle_watchdog &
fi
done
# GHASR-97: capture run.sh's status before anything else runs. This used to read
# $? after the IFS assignment, so it was always 0. PIPESTATUS[0] preserves
# run.sh's own status across the log-forwarding pipeline.
status=$${PIPESTATUS[0]}
IFS=$' \t\n'
if [[ $status -eq 0 ]]; then send_metrics jobs.completed; fi
send_logs runner_exit $status
sudo poweroff