-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrunner.sh
More file actions
executable file
·1225 lines (1107 loc) · 50.3 KB
/
runner.sh
File metadata and controls
executable file
·1225 lines (1107 loc) · 50.3 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
set -euo pipefail
# 忽略多组织部署时的 orphan 容器警告(同一主机运行多个组织的 runner 是正常场景)
export COMPOSE_IGNORE_ORPHANS=1
ENV_FILE="${ENV_FILE:-.env}"
# ------------------------------- load .env file -------------------------------
if [[ -f "$ENV_FILE" ]]; then
# shellcheck disable=SC2046
export $(grep -v '^[[:space:]]*#' "$ENV_FILE" | grep -v '^[[:space:]]*$' | sed 's/^/export /')
fi
# Organization, REG_TOKEN, etc.
ORG="${ORG:-}"
GH_PAT="${GH_PAT:-}"
REPO="${REPO:-}"
# Runner container related parameters
RUNNER_IMAGE="${RUNNER_IMAGE:-ghcr.io/actions/actions-runner:latest}"
RUNNER_CUSTOM_IMAGE="${RUNNER_CUSTOM_IMAGE:-qc-actions-runner:v0.0.1}"
if [[ -z "${RUNNER_NAME_PREFIX:-}" ]]; then
if [[ -n "${ORG:-}" && -n "${REPO:-}" ]]; then
RUNNER_NAME_PREFIX="$(hostname)-${ORG}-${REPO}-"
elif [[ -n "${ORG:-}" ]]; then
RUNNER_NAME_PREFIX="$(hostname)-${ORG}-"
else
RUNNER_NAME_PREFIX="$(hostname)-"
fi
else
[[ "$RUNNER_NAME_PREFIX" == *- ]] || RUNNER_NAME_PREFIX="${RUNNER_NAME_PREFIX}-"
fi
RUNNER_GROUP="${RUNNER_GROUP:-Default}"
RUNNER_WORKDIR="${RUNNER_WORKDIR:-}"
RUNNER_LABELS="${RUNNER_LABELS:-intel}"
RUNNER_BOARD_COUNT="${RUNNER_BOARD_COUNT:-${RUNNER_BOARD:-2}}"
RUNNER_BOARD="${RUNNER_BOARD_COUNT}"
BOARD_RUNNER_LABELS="${BOARD_RUNNER_LABELS:-board}"
BOARD_RUNNER_DEVICES="${BOARD_RUNNER_DEVICES:-/dev/loop-control,/dev/loop0,/dev/loop1,/dev/loop2,/dev/loop3,/dev/kvm}"
BOARD_RUNNER_GROUP_ADD="${BOARD_RUNNER_GROUP_ADD:-dialout}"
BOARD_RUNNER_VOLUMES="${BOARD_RUNNER_VOLUMES:-}"
BOARD_RUNNER_ENV="${BOARD_RUNNER_ENV:-}"
BOARD_RUNNER_COMMAND="${BOARD_RUNNER_COMMAND:-/home/runner/run.sh}"
DISABLE_AUTO_UPDATE="${DISABLE_AUTO_UPDATE:-false}"
COMPOSE_FILE="${COMPOSE_FILE:-}"
DOCKERFILE_HASH_FILE="${DOCKERFILE_HASH_FILE:-}"
REG_TOKEN_CACHE_FILE="${REG_TOKEN_CACHE_FILE:-}"
REG_TOKEN_CACHE_TTL="${REG_TOKEN_CACHE_TTL:-300}" # seconds, default 5 minutes
# Compose 文件名:未显式设置时自动拼入 ORG/REPO,避免同一主机多组织时文件冲突
# 组织级默认:docker-compose.<org>.yml 仓库级默认:docker-compose.<org>.<repo>.yml
if [[ -z "$COMPOSE_FILE" ]]; then
if [[ -n "${ORG:-}" && -n "${REPO:-}" ]]; then
COMPOSE_FILE="docker-compose.${ORG}.${REPO}.yml"
elif [[ -n "${ORG:-}" ]]; then
COMPOSE_FILE="docker-compose.${ORG}.yml"
else
COMPOSE_FILE="docker-compose.yml"
fi
fi
# Dockerfile hash 文件名:同样根据 ORG/REPO 区分,避免多组织时 hash 冲突
if [[ -z "$DOCKERFILE_HASH_FILE" ]]; then
if [[ -n "${ORG:-}" && -n "${REPO:-}" ]]; then
DOCKERFILE_HASH_FILE=".dockerfile.${ORG}.${REPO}.sha256"
elif [[ -n "${ORG:-}" ]]; then
DOCKERFILE_HASH_FILE=".dockerfile.${ORG}.sha256"
else
DOCKERFILE_HASH_FILE=".dockerfile.sha256"
fi
fi
# REG_TOKEN_CACHE_FILE 文件名:未显式设置时自动拼入 ORG/REPO,避免同一主机多组织时文件冲突
# 组织级默认:.reg_token.cache.<org> 仓库级默认:.reg_token.cache.<org>.<repo>
if [[ -z "$REG_TOKEN_CACHE_FILE" ]]; then
if [[ -n "${ORG:-}" && -n "${REPO:-}" ]]; then
REG_TOKEN_CACHE_FILE=".reg_token.cache.${ORG}.${REPO}"
elif [[ -n "${ORG:-}" ]]; then
REG_TOKEN_CACHE_FILE=".reg_token.cache.${ORG}"
else
REG_TOKEN_CACHE_FILE=".reg_token.cache"
fi
fi
# ------------------------------- Helpers -------------------------------
shell_usage() {
local COLW=48
echo "Usage: ./runner.sh COMMAND [options] Where [options] depend on COMMAND. Available COMMANDs:"
echo
echo "1. Creation commands:"
printf " %-${COLW}s %s\n" "./runner.sh init -n N" "Generate docker-compose.yml then create runners and start"
printf " %-${COLW}s %s\n" "./runner.sh compose" "Regenerate docker-compose.yml with existing generic and board-specific runners"
echo
echo "2. Instance operation commands:"
printf " %-${COLW}s %s\n" "./runner.sh register [${RUNNER_NAME_PREFIX}runner-<id> ...]" "Register specified instances; no args will iterate over all existing instances"
printf " %-${COLW}s %s\n" "./runner.sh start [${RUNNER_NAME_PREFIX}runner-<id> ...]" "Start specified instances (will register if needed); no args will iterate all existing instances"
printf " %-${COLW}s %s\n" "./runner.sh stop [${RUNNER_NAME_PREFIX}runner-<id> ...]" "Stop Runner containers; no args will iterate all existing instances"
printf " %-${COLW}s %s\n" "./runner.sh restart [${RUNNER_NAME_PREFIX}runner-<id> ...]" "Restart specified instances; no args will iterate all existing instances"
printf " %-${COLW}s %s\n" "./runner.sh log ${RUNNER_NAME_PREFIX}runner-<id>" "Follow logs of a specified instance"
echo
echo "3. Query commands:"
printf " %-${COLW}s %s\n" "./runner.sh ps|ls|list|status" "Show container status and registered Runner status"
echo
echo "4. Deletion commands:"
printf " %-${COLW}s %s\n" "./runner.sh rm|remove|delete [${RUNNER_NAME_PREFIX}runner-<id> ...]" "Delete specified instances; no args will delete all (confirmation required, -y to skip)"
printf " %-${COLW}s %s\n" "./runner.sh purge [-y]" "On top of remove, also delete the dynamically generated docker-compose.yml"
echo
echo "5. Image management commands:"
printf " %-${COLW}s %s\n" "./runner.sh image" "Rebuild Docker image based on Dockerfile"
echo
echo "6. Help"
printf " %-${COLW}s %s\n" "./runner.sh help" "Show this help"
echo
echo "Environment variables (from .env or interactive input):"
local KEYW=24
printf " %-${KEYW}s %s\n" "GH_PAT" "Classic PAT (requires admin:org), used for org API and registration token"
printf " %-${KEYW}s %s\n" "ORG" "Organization name or user name (required)"
printf " %-${KEYW}s %s\n" "REPO" "Optional repository name (when set, operate on repo-scoped runners under ORG/REPO instead of organization-wide runners)"
printf " %-${KEYW}s %s\n" "RUNNER_NAME_PREFIX" "Runner name prefix"
printf " %-${KEYW}s %s\n" "RUNNER_IMAGE" "Image used for compose generation (default ghcr.io/actions/actions-runner:latest)"
printf " %-${KEYW}s %s\n" "RUNNER_CUSTOM_IMAGE" "Image tag used for auto-build (can override)"
printf " %-${KEYW}s %s\n" "RUNNER_BOARD_COUNT" "Number of generic board runners to create"
printf " %-${KEYW}s %s\n" "BOARD_RUNNER_LABELS" "Default labels for board runners"
printf " %-${KEYW}s %s\n" "BOARD_RUNNER_DEVICES" "Comma-separated device list for board runners"
printf " %-${KEYW}s %s\n" "BOARD_RUNNER_GROUP_ADD" "Comma-separated extra groups for board runners"
printf " %-${KEYW}s %s\n" "BOARD_RUNNER_VOLUMES" "Semicolon-separated extra volume mounts for board runners"
printf " %-${KEYW}s %s\n" "BOARD_RUNNER_ENV" "Semicolon-separated KEY=VALUE envs for board runners"
printf " %-${KEYW}s %s\n" "BOARD_RUNNER_COMMAND" "Command executed by board runners"
echo
echo "Example workflow runs-on: runs-on: [self-hosted, linux, docker]"
echo
echo "Tips:"
echo "- Compose file is auto-generated per ORG/REPO (e.g., docker-compose.<org>.yml)"
echo "- Re-start/up will reuse existing volumes; Runner configuration and tool caches will not be lost."
}
shell_die() { echo "[ERROR] $*" >&2; exit 1; }
shell_info() { echo "[INFO] $*"; }
shell_warn() { echo "[WARN] $*" >&2; }
shell_prompt_confirm() {
# Return 0 for confirm, 1 for cancel
local prompt="${1:-Confirm? [y/N]} "
read -r -p "$prompt" ans
[[ "$ans" == "y" || "$ans" == "Y" || "$ans" == "yes" || "$ans" == "YES" ]]
}
shell_detect_device_gid() {
local device_path="${1:-}"
[[ -n "$device_path" && -e "$device_path" ]] || return 1
stat -c '%g' "$device_path" 2>/dev/null
}
shell_trim() {
local value="${1:-}"
value="$(printf '%s' "$value" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
printf '%s' "$value"
}
shell_get_indexed_env() {
local key="$1" index="$2" default_value="${3:-}"
local indexed_key="${key}_${index}"
if [[ -n "${!indexed_key-}" ]]; then
printf '%s' "${!indexed_key}"
else
printf '%s' "$default_value"
fi
}
shell_append_csv_yaml_list() {
local file="$1" indent="$2" csv="$3"
local item trimmed
IFS=',' read -r -a _items <<< "$csv"
for item in "${_items[@]}"; do
trimmed="$(shell_trim "$item")"
[[ -n "$trimmed" ]] || continue
printf '%s- %s\n' "$indent" "$trimmed" >> "$file"
done
}
shell_append_device_yaml_list() {
local file="$1" indent="$2" csv="$3"
local item trimmed mapping
IFS=',' read -r -a _items <<< "$csv"
for item in "${_items[@]}"; do
trimmed="$(shell_trim "$item")"
[[ -n "$trimmed" ]] || continue
if [[ "$trimmed" == *:* ]]; then
mapping="$trimmed"
else
mapping="${trimmed}:${trimmed}"
fi
printf '%s- %s\n' "$indent" "$mapping" >> "$file"
done
}
shell_append_semicolon_yaml_list() {
local file="$1" indent="$2" values="$3"
local item trimmed
IFS=';' read -r -a _items <<< "$values"
for item in "${_items[@]}"; do
trimmed="$(shell_trim "$item")"
[[ -n "$trimmed" ]] || continue
printf '%s- %s\n' "$indent" "$trimmed" >> "$file"
done
}
shell_append_semicolon_env_map() {
local file="$1" indent="$2" values="$3"
local item trimmed key value
IFS=';' read -r -a _items <<< "$values"
for item in "${_items[@]}"; do
trimmed="$(shell_trim "$item")"
[[ -n "$trimmed" ]] || continue
[[ "$trimmed" == *"="* ]] || continue
key="$(shell_trim "${trimmed%%=*}")"
value="$(shell_trim "${trimmed#*=}")"
[[ -n "$key" ]] || continue
printf '%s%s: "%s"\n' "$indent" "$key" "$value" >> "$file"
done
}
shell_get_org_and_pat() {
# Fast path when both provided via env/.env
if [[ -n "${ORG:-}" && -n "${GH_PAT:-}" ]]; then
return 0
fi
# Detect interactive TTY; if not interactive, require env values
local has_tty=0
if [[ -t 0 || -t 1 || -t 2 ]]; then has_tty=1; fi
if [[ $has_tty -eq 0 ]]; then
[[ -n "${ORG:-}" && -n "${GH_PAT:-}" ]] || \
shell_die "ORG/GH_PAT cannot be empty (in non-interactive environments provide via env or .env)."
return 0
fi
# Prompt using /dev/tty so it works inside command substitutions
local wrote_env=0
if [[ -z "${ORG:-}" ]]; then
while true; do
if [[ -e /dev/tty ]]; then
printf "Enter organization name (must match github.com): " > /dev/tty
IFS= read -r ORG < /dev/tty || true
else
read -rp "Enter organization name (must match github.com): " ORG || true
fi
ORG="$(printf '%s' "${ORG:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
[[ -n "$ORG" ]] && break
printf "[WARN] Organization name cannot be empty, please try again.\n" > /dev/tty
done
wrote_env=1
fi
if [[ -z "${GH_PAT:-}" ]]; then
while true; do
if [[ -e /dev/tty ]]; then
printf "Enter Classic PAT (admin:org) (input hidden): " > /dev/tty
IFS= read -rs GH_PAT < /dev/tty || true; echo > /dev/tty
else
echo -n "Enter Classic PAT (admin:org) (input hidden): " >&2
read -rs GH_PAT || true; echo >&2
fi
GH_PAT="$(printf '%s' "${GH_PAT:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
[[ -n "$GH_PAT" ]] && break
printf "[WARN] PAT cannot be empty, please try again.\n" > /dev/tty
done
wrote_env=1
fi
# Optional: repository name. If empty, operations default to organization scope.
if [[ -z "${REPO:-}" ]]; then
while true; do
if [[ -e /dev/tty ]]; then
printf "Enter repository name (optional, leave empty to use organization runners): " > /dev/tty
IFS= read -r REPO < /dev/tty || true
else
read -rp "Enter repository name (optional, leave empty to use organization runners): " REPO || true
fi
REPO="$(printf '%s' "${REPO:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
break
done
[[ -n "${REPO:-}" ]] && wrote_env=1
fi
export ORG GH_PAT REPO
# Recalculate RUNNER_NAME_PREFIX if it was auto-generated (not explicitly set by user)
# Same logic as COMPOSE_FILE etc.: check if empty or equals default value (hostname only)
local default_prefix default_org_prefix default_repo_prefix
default_prefix="$(hostname)-"
default_org_prefix="$(hostname)-${ORG}-"
default_repo_prefix="$(hostname)-${ORG}-${REPO}-"
if [[ -z "${RUNNER_NAME_PREFIX:-}" ]] || \
[[ "$RUNNER_NAME_PREFIX" == "$default_prefix" ]] || \
[[ -n "${ORG:-}" && "$RUNNER_NAME_PREFIX" == "$default_org_prefix" ]] || \
[[ -n "${ORG:-}" && -n "${REPO:-}" && "$RUNNER_NAME_PREFIX" == "$default_repo_prefix" ]]; then
if [[ -n "${ORG:-}" && -n "${REPO:-}" ]]; then
RUNNER_NAME_PREFIX="$(hostname)-${ORG}-${REPO}-"
elif [[ -n "${ORG:-}" ]]; then
RUNNER_NAME_PREFIX="$(hostname)-${ORG}-"
else
RUNNER_NAME_PREFIX="$default_prefix"
fi
export RUNNER_NAME_PREFIX
fi
# Recalculate file paths based on newly obtained ORG/REPO
if [[ -z "${COMPOSE_FILE:-}" ]] || [[ "$COMPOSE_FILE" == "docker-compose.yml" ]]; then
if [[ -n "${ORG:-}" && -n "${REPO:-}" ]]; then
COMPOSE_FILE="docker-compose.${ORG}.${REPO}.yml"
elif [[ -n "${ORG:-}" ]]; then
COMPOSE_FILE="docker-compose.${ORG}.yml"
else
COMPOSE_FILE="docker-compose.yml"
fi
export COMPOSE_FILE
fi
if [[ -z "${DOCKERFILE_HASH_FILE:-}" ]] || [[ "$DOCKERFILE_HASH_FILE" == ".dockerfile.sha256" ]]; then
if [[ -n "${ORG:-}" && -n "${REPO:-}" ]]; then
DOCKERFILE_HASH_FILE=".dockerfile.${ORG}.${REPO}.sha256"
elif [[ -n "${ORG:-}" ]]; then
DOCKERFILE_HASH_FILE=".dockerfile.${ORG}.sha256"
else
DOCKERFILE_HASH_FILE=".dockerfile.sha256"
fi
export DOCKERFILE_HASH_FILE
fi
if [[ -z "${REG_TOKEN_CACHE_FILE:-}" ]] || [[ "$REG_TOKEN_CACHE_FILE" == ".reg_token.cache" ]]; then
if [[ -n "${ORG:-}" && -n "${REPO:-}" ]]; then
REG_TOKEN_CACHE_FILE=".reg_token.cache.${ORG}.${REPO}"
elif [[ -n "${ORG:-}" ]]; then
REG_TOKEN_CACHE_FILE=".reg_token.cache.${ORG}"
else
REG_TOKEN_CACHE_FILE=".reg_token.cache"
fi
export REG_TOKEN_CACHE_FILE
fi
# Persist to .env (ENV_FILE) if values were entered interactively
if [[ $wrote_env -eq 1 ]]; then
local env_file="$ENV_FILE" tmp
touch "$env_file"
chmod 600 "$env_file" 2>/dev/null || true
if [[ -n "${ORG:-}" ]]; then
tmp="$(mktemp "${env_file}.tmp.XXXXXX")"
grep -v -E '^[[:space:]]*ORG=' "$env_file" > "$tmp" || true
printf 'ORG=%s\n' "$ORG" >> "$tmp"
mv "$tmp" "$env_file"
fi
if [[ -n "${GH_PAT:-}" ]]; then
tmp="$(mktemp "${env_file}.tmp.XXXXXX")"
grep -v -E '^[[:space:]]*GH_PAT=' "$env_file" > "$tmp" || true
printf 'GH_PAT=%s\n' "$GH_PAT" >> "$tmp"
mv "$tmp" "$env_file"
fi
if [[ -n "${REPO:-}" ]]; then
tmp="$(mktemp "${env_file}.tmp.XXXXXX")"
grep -v -E '^[[:space:]]*REPO=' "$env_file" > "$tmp" || true
printf 'REPO=%s\n' "$REPO" >> "$tmp"
mv "$tmp" "$env_file"
fi
fi
}
# Decide which image to use based on Dockerfile and local images; build if needed; echo the chosen image name
shell_prepare_runner_image() {
local base="ghcr.io/actions/actions-runner:latest"
local current="${RUNNER_IMAGE:-$base}"
local hash_file="${DOCKERFILE_HASH_FILE:-.dockerfile.sha256}"
if [[ -f Dockerfile ]]; then
local new_hash="" old_hash=""
if command -v sha256sum >/dev/null 2>&1; then
new_hash=$(sha256sum Dockerfile | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
new_hash=$(shasum -a 256 Dockerfile | awk '{print $1}')
fi
if [[ -n "$new_hash" ]]; then
[[ -f "$hash_file" ]] && old_hash=$(cat "$hash_file" 2>/dev/null || true)
if [[ "$new_hash" != "$old_hash" ]]; then
shell_info "Detected Dockerfile change, building ${RUNNER_CUSTOM_IMAGE} image" >&2
docker build -t "${RUNNER_CUSTOM_IMAGE}" . 1>&2
echo "$new_hash" > "$hash_file"
shell_info "Build complete. Will use ${RUNNER_CUSTOM_IMAGE} as image" >&2
echo "${RUNNER_CUSTOM_IMAGE}"
return 0
fi
fi
if [[ "$current" == "$base" ]]; then
if command -v docker >/dev/null 2>&1 && docker image inspect "${RUNNER_CUSTOM_IMAGE}" >/dev/null 2>&1; then
# shell_info "Detected existing custom image, prefer ${RUNNER_CUSTOM_IMAGE} as image" >&2
echo "${RUNNER_CUSTOM_IMAGE}"
return 0
fi
fi
echo "$current"
return 0
else
# shell_info "Dockerfile not found, skipping custom image build; using official ${base} as image" >&2
echo "$base"
return 0
fi
}
# Unified "delete all" executor: count -> prompt -> unregister -> local cleanup
shell_delete_all_execute() {
local require_confirm_msg="$1" # empty means no extra confirmation required
local prefix cont_list org_count=0 cont_count=0 resp
prefix="${RUNNER_NAME_PREFIX}runner-"
if command -v jq >/dev/null 2>&1; then
resp=$(github_api GET "/actions/runners?per_page=100" || echo "{}")
org_count=$(echo "$resp" | jq -r --arg p "$prefix" '[.runners[] | select(.name|startswith($p))] | length' 2>/dev/null || echo 0)
else
shell_warn "jq is not installed; cannot count organization runners. Will only remove local containers/volumes and attempt best-effort unregister."
fi
cont_list="$(docker_list_existing_containers)"
if [[ -n "$cont_list" ]]; then cont_count=$(echo "$cont_list" | wc -l | tr -d ' '); fi
shell_info "About to delete ${org_count} runners and ${cont_count} containers and associated volumes on this host"
if [[ -n "$require_confirm_msg" ]]; then
if ! shell_prompt_confirm "$require_confirm_msg"; then
echo "Operation cancelled!"; return 130
fi
fi
# 根据计数条件执行相应的删除操作
[[ "$org_count" -gt 0 ]] && { shell_info "Deleting ${org_count} GitHub runners..."; github_delete_all_runners_with_prefix || true; }
[[ "$cont_count" -gt 0 ]] && { shell_info "Deleting ${cont_count} Docker containers and volumes..."; docker_remove_all_local_containers_and_volumes || true; }
shell_info "Batch deletion complete!"
}
# Ensure REG_TOKEN is present and not older than TTL; echo it
shell_get_reg_token() {
local now ts cached_token
now=$(date +%s)
if [[ -f "$REG_TOKEN_CACHE_FILE" ]]; then
ts=$(head -n1 "$REG_TOKEN_CACHE_FILE" 2>/dev/null || true)
cached_token=$(sed -n '2p' "$REG_TOKEN_CACHE_FILE" 2>/dev/null || true)
if [[ -n "$ts" && -n "$cached_token" && "$ts" =~ ^[0-9]+$ ]]; then
if (( now - ts < REG_TOKEN_CACHE_TTL )); then
REG_TOKEN="$cached_token"
printf '%s\n' "$REG_TOKEN"
return 0
fi
fi
fi
if [[ -n "${REG_TOKEN:-}" && "${REG_TOKEN:-}" != "null" ]]; then
printf '%s\n%s\n' "$now" "$REG_TOKEN" > "$REG_TOKEN_CACHE_FILE"
printf '%s\n' "$REG_TOKEN"
return 0
fi
shell_get_org_and_pat
shell_info "Requesting <${ORG:-${REPO}}> registration token..." >&2
local new_token
new_token="$(github_fetch_reg_token || true)"
[[ -n "$new_token" && "$new_token" != "null" ]] || shell_die "Failed to fetch registration token!"
REG_TOKEN="$new_token"
export REG_TOKEN
printf '%s\n%s\n' "$now" "$REG_TOKEN" > "$REG_TOKEN_CACHE_FILE"
# Keep compose file in sync when fetching a fresh token
printf '%s\n' "$REG_TOKEN"
}
# Update a field in docker-compose.yml under environment (mapping or list styles)
# Usage: shell_update_compose_file KEY VALUE
shell_update_compose_file() {
local key="$1" token="$2"
[[ -n "$key" && -n "$token" ]] || return 0
local file="$COMPOSE_FILE"
[[ -f "$file" ]] || { shell_warn "${file} not found; skip updating ${key}." >&2; return 0; }
local tmpfile updated
tmpfile=$(mktemp "${file}.tmp.XXXXXX") || return 1
updated=0
while IFS= read -r line; do
# Mapping style: KEY: "value" (preserve indentation and spacing)
if [[ "$line" =~ ^[[:space:]]*${key}[[:space:]]*: ]]; then
# Extract leading whitespace and preserve it
local indent="${line%%[^ ]*}"
printf '%s%s: "%s"\n' "$indent" "$key" "$token" >> "$tmpfile"
updated=1
# List style: - KEY="value" (preserve indentation and dash)
elif [[ "$line" =~ ^[[:space:]]*-[[:space:]]*${key}= ]]; then
# Extract leading spaces and dash
local prefix="${line%${key}*}"
printf '%s%s="%s"\n' "$prefix" "$key" "$token" >> "$tmpfile"
updated=1
else
printf '%s\n' "$line" >> "$tmpfile"
fi
done < "$file"
if [[ $updated -eq 1 ]]; then
mv "$tmpfile" "$file"
shell_info "Updated ${key} in ${file}." >&2
else
rm -f "$tmpfile"
shell_warn "${key} key not found in ${file}; ensure your compose defines it under environment." >&2
fi
}
# Helper: Extract an environment variable value for a specific service from docker-compose.yml
# Usage: shell_get_compose_file SERVICE_NAME ENV_KEY
shell_get_compose_file() {
local service="$1" key="$2"
local file="$COMPOSE_FILE"
[[ -f "$file" ]] || return 1
local in_service=0 in_env=0 found=0
while IFS= read -r line; do
# Check if we're entering the target service
if [[ "$line" =~ ^[[:space:]]*${service}:[[:space:]]*$ ]]; then
in_service=1
in_env=0
continue
fi
# If we were in a service and encounter another service at same indentation, exit
if [[ $in_service -eq 1 ]] && [[ "$line" =~ ^[a-zA-Z_] ]] && [[ ! "$line" =~ ^[[:space:]] ]]; then
break
fi
# Check if we're entering the environment block
if [[ $in_service -eq 1 ]] && [[ "$line" =~ ^[[:space:]]*environment:[[:space:]]*$ ]]; then
in_env=1
continue
fi
# If we're in environment section, look for the key
if [[ $in_env -eq 1 ]]; then
# Stop if we encounter a key at lower indentation level (end of environment)
if [[ "$line" =~ ^[a-zA-Z_] ]] || [[ "$line" =~ ^[[:space:]]{0,2}[a-zA-Z_] ]]; then
break
fi
# Match the key in mapping style: KEY: value
if [[ "$line" =~ ^[[:space:]]*${key}:[[:space:]]* ]]; then
# Extract value after the colon, then trim spaces
local value="${line#*:}"
value="$(printf '%s' "$value" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
# Strip matching surrounding quotes if present (both double and single)
if [[ "$value" == \"*\" ]]; then value="${value#\"}"; value="${value%\"}"; fi
if [[ "$value" == \'*\' ]]; then value="${value#\'}"; value="${value%\'}"; fi
[[ -n "$value" ]] && echo "$value"
found=1
break
fi
fi
done < "$file"
[[ $found -eq 1 ]] && return 0 || return 1
}
shell_generate_compose_file() {
local general_count=$1
local board_count="${RUNNER_BOARD_COUNT:-0}"
local extra_proxy_env=()
local kvm_gid="${RUNNER_KVM_GID:-}"
# /dev/kvm 的权限检查是按数字 GID 生效
# 优先使用宿主机当前 /dev/kvm 的实际 GID,必要时允许通过 RUNNER_KVM_GID 覆盖
if [[ -z "$kvm_gid" ]]; then
kvm_gid="$(shell_detect_device_gid /dev/kvm || true)"
fi
if [[ -n "$kvm_gid" ]]; then
shell_info "Using /dev/kvm group id: ${kvm_gid}"
else
kvm_gid="993"
shell_warn "/dev/kvm gid not detected; falling back to legacy gid ${kvm_gid}. Set RUNNER_KVM_GID to override."
fi
[[ -n "${HTTP_PROXY:-}" ]] && extra_proxy_env+=(" HTTP_PROXY: \"${HTTP_PROXY}\"")
[[ -n "${HTTPS_PROXY:-}" ]] && extra_proxy_env+=(" HTTPS_PROXY: \"${HTTPS_PROXY}\"")
[[ -n "${NO_PROXY:-}" ]] && extra_proxy_env+=(" NO_PROXY: \"${NO_PROXY}\"")
# 使用 printf 输出文件头
printf '%s\n' \
"# 自动生成的 Docker Compose 配置" \
"# 机器名: $(hostname)" \
"# 普通 runner 数量: $general_count" \
"# 板子 runner 数量: ${board_count}" \
"" \
"# 基础配置" \
"x-${RUNNER_NAME_PREFIX}runner-base: &runner_base" \
" image: \"${RUNNER_IMAGE}\"" \
" restart: unless-stopped" \
" environment: &runner_env" \
" RUNNER_ORG_URL: \"https://github.com/${ORG}${REPO:+/}${REPO}\"" \
" RUNNER_TOKEN: \"${REG_TOKEN}\"" \
" RUNNER_GROUP: \"${RUNNER_GROUP}\"" \
" RUNNER_REMOVE_ON_STOP: \"false\"" \
" DISABLE_AUTO_UPDATE: \"${DISABLE_AUTO_UPDATE}\"" \
" RUNNER_WORKDIR: \"${RUNNER_WORKDIR}\"" \
"${extra_proxy_env[@]}" \
" network_mode: host" \
" privileged: true" \
"" \
"services:" > "${COMPOSE_FILE}"
# 生成普通 runners
echo " # 普通 runners" >> ${COMPOSE_FILE}
for i in $(seq 1 $general_count); do
printf '%s\n' \
" ${RUNNER_NAME_PREFIX}runner-${i}:" \
" <<: *runner_base" \
" container_name: \"${RUNNER_NAME_PREFIX}runner-${i}\"" \
" command: [\"/home/runner/run.sh\"]" \
" devices:" \
" - /dev/loop-control:/dev/loop-control" \
" - /dev/loop0:/dev/loop0" \
" - /dev/loop1:/dev/loop1" \
" - /dev/loop2:/dev/loop2" \
" - /dev/loop3:/dev/loop3" \
" - /dev/kvm:/dev/kvm" \
" group_add:" \
" - ${kvm_gid}" \
" environment:" \
" <<: *runner_env" \
" RUNNER_NAME: \"${RUNNER_NAME_PREFIX}runner-${i}\"" \
" RUNNER_LABELS: \"${RUNNER_LABELS}\"" \
" volumes:" \
" - ${RUNNER_NAME_PREFIX}runner-${i}-data:/home/runner" \
" - ${RUNNER_NAME_PREFIX}runner-${i}-udev-rules:/etc/udev/rules.d" \
"" >> "${COMPOSE_FILE}"
done
# 只有当 RUNNER_BOARD_COUNT 大于 0 时才生成板子 runners
if [[ "${board_count}" -gt 0 ]]; then
echo " # 板子专用 runners" >> "${COMPOSE_FILE}"
local i board_labels board_devices board_groups board_env board_volumes board_command
for i in $(seq 1 "$board_count"); do
board_labels="$(shell_get_indexed_env "BOARD_RUNNER_LABELS" "$i" "${BOARD_RUNNER_LABELS}")"
board_devices="$(shell_get_indexed_env "BOARD_RUNNER_DEVICES" "$i" "${BOARD_RUNNER_DEVICES}")"
board_groups="$(shell_get_indexed_env "BOARD_RUNNER_GROUP_ADD" "$i" "${BOARD_RUNNER_GROUP_ADD}")"
board_env="$(shell_get_indexed_env "BOARD_RUNNER_ENV" "$i" "${BOARD_RUNNER_ENV}")"
board_volumes="$(shell_get_indexed_env "BOARD_RUNNER_VOLUMES" "$i" "${BOARD_RUNNER_VOLUMES}")"
board_command="$(shell_get_indexed_env "BOARD_RUNNER_COMMAND" "$i" "${BOARD_RUNNER_COMMAND}")"
printf '%s\n' \
" ${RUNNER_NAME_PREFIX}runner-board-${i}:" \
" <<: *runner_base" \
" container_name: \"${RUNNER_NAME_PREFIX}runner-board-${i}\"" \
" command:" \
" - /bin/bash" \
" - -lc" \
" - |" \
" exec ${board_command}" \
" devices:" >> "${COMPOSE_FILE}"
shell_append_device_yaml_list "${COMPOSE_FILE}" " " "${board_devices}"
printf '%s\n' \
" group_add:" \
" - ${kvm_gid}" >> "${COMPOSE_FILE}"
shell_append_csv_yaml_list "${COMPOSE_FILE}" " " "${board_groups}"
printf '%s\n' \
" environment:" \
" <<: *runner_env" \
" RUNNER_NAME: \"${RUNNER_NAME_PREFIX}runner-board-${i}\"" \
" RUNNER_LABELS: \"${board_labels}\"" \
" RUNNER_BOARD_INDEX: \"${i}\"" >> "${COMPOSE_FILE}"
shell_append_semicolon_env_map "${COMPOSE_FILE}" " " "${board_env}"
printf '%s\n' \
" volumes:" \
" - ${RUNNER_NAME_PREFIX}runner-board-${i}-data:/home/runner" \
" - ${RUNNER_NAME_PREFIX}runner-board-${i}-udev-rules:/etc/udev/rules.d" >> "${COMPOSE_FILE}"
shell_append_semicolon_yaml_list "${COMPOSE_FILE}" " " "${board_volumes}"
printf '\n' >> "${COMPOSE_FILE}"
done
fi
# 生成 volumes
echo "volumes:" >> ${COMPOSE_FILE}
for i in $(seq 1 $general_count); do
printf '%s\n' \
" ${RUNNER_NAME_PREFIX}runner-${i}-data:" \
" name: ${RUNNER_NAME_PREFIX}runner-${i}-data" \
" ${RUNNER_NAME_PREFIX}runner-${i}-udev-rules:" \
" name: ${RUNNER_NAME_PREFIX}runner-${i}-udev-rules" >> "${COMPOSE_FILE}"
done
# 只有当 RUNNER_BOARD_COUNT 大于 0 时才生成板子相关的 volumes
if [[ "${board_count}" -gt 0 ]]; then
local i
for i in $(seq 1 "$board_count"); do
printf '%s\n' \
" ${RUNNER_NAME_PREFIX}runner-board-${i}-data:" \
" name: ${RUNNER_NAME_PREFIX}runner-board-${i}-data" \
" ${RUNNER_NAME_PREFIX}runner-board-${i}-udev-rules:" \
" name: ${RUNNER_NAME_PREFIX}runner-board-${i}-udev-rules" >> "${COMPOSE_FILE}"
done
fi
}
# ------------------------------- GitHub API helpers -------------------------------
github_api() {
local method="$1" path="$2" body="${3:-}"
[[ -n "${GH_PAT:-}" ]] || shell_die "GH_PAT is required to call organization-related APIs!"
# If REPO is set, target repo-scoped endpoints under /repos/{ORG}/{REPO}, otherwise org endpoints
local base
if [[ -n "${REPO:-}" ]]; then
base="https://api.github.com/repos/${ORG}/${REPO}"
else
base="https://api.github.com/orgs/${ORG}"
fi
local url="${base}${path}"
if [[ -n "$body" ]]; then
curl -sS -X "$method" -H "Authorization: Bearer ${GH_PAT}" \
-H "Accept: application/vnd.github+json" \
-d "$body" "$url"
else
curl -sS -X "$method" -H "Authorization: Bearer ${GH_PAT}" \
-H "Accept: application/vnd.github+json" \
"$url"
fi
}
github_fetch_reg_token() {
local resp token
resp=$(github_api POST "/actions/runners/registration-token") || return 1
if command -v jq >/dev/null 2>&1; then
token=$(echo "$resp" | jq -r .token)
elif command -v python3 >/dev/null 2>&1; then
token=$(printf '%s' "$resp" | python3 -c 'import sys, json; print(json.load(sys.stdin).get("token", ""))')
else
token=$(echo "$resp" | sed -n 's/.*"token"[[:space:]]*:[[:space:]]*"\([^"[:cntrl:]]*\)".*/\1/p' | head -1)
fi
echo "${token}"
}
github_get_runner_id_by_name() {
local name="$1"
local resp
resp=$(github_api GET "/actions/runners?per_page=100") || return 1
if command -v jq >/dev/null 2>&1; then
echo "$resp" | jq -r --arg n "$name" '.runners[] | select(.name==$n) | .id' | head -1
else
echo "$resp" | grep -A3 -F "\"name\": \"${name}\"" | grep -m1 '"id":' | sed 's/[^0-9]//g' | head -1
fi
}
github_delete_runner_by_id() {
local id="$1"
github_api DELETE "/actions/runners/$id" >/dev/null
}
github_delete_all_runners_with_prefix() {
local prefix="${RUNNER_NAME_PREFIX}runner-"
local resp
resp=$(github_api GET "/actions/runners?per_page=100" || echo "{}")
if command -v jq >/dev/null 2>&1; then
while IFS=$'\t' read -r id name; do
[[ -n "$id" && "$id" != "null" ]] || continue
shell_info "Unregistering from GitHub: $name (id=$id)"
github_delete_runner_by_id "$id" || shell_warn "Failed to unregister $name on GitHub; please remove it manually via the GitHub web UI!"
done < <(echo "$resp" | jq -r --arg p "$prefix" '.runners[] | select(.name|startswith($p)) | "\(.id)\t\(.name)"')
else
shell_warn "jq is not installed; cannot batch-unregister on the organization side; will only remove local containers and volumes."
fi
}
# ------------------------------- Docker Compose wrappers -------------------------------
docker_pick_compose() {
if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
echo "docker compose"
elif command -v docker-compose >/dev/null 2>&1; then
echo "docker-compose"
else
shell_die "docker compose (v2) or docker-compose is not installed."
fi
}
docker_list_existing_containers() {
if [[ -f "$COMPOSE_FILE" ]]; then
$DC -f "$COMPOSE_FILE" ps --services --all | grep -F "${RUNNER_NAME_PREFIX}runner-" || true
else
docker ps -a --filter "name=${RUNNER_NAME_PREFIX}runner-" --format "{{.Names}}" || true
fi
}
docker_print_existing_containers_status() {
if [[ -f "$COMPOSE_FILE" ]]; then
$DC -f "$COMPOSE_FILE" ps -a
return 0
fi
# Fallback: query via docker when compose file is absent
if command -v docker >/dev/null 2>&1; then
docker ps -a --filter "name=${RUNNER_NAME_PREFIX}runner-" --format "table {{.Names}}\t{{.State}}\t{{.Status}}"
else
shell_info "${COMPOSE_FILE} not found and docker command not detected; cannot query status."
fi
}
# Check whether a specific container exists (local docker ps -a name match)
docker_container_exists() {
local name="$1"
if [[ -f "$COMPOSE_FILE" ]]; then
$DC -f "$COMPOSE_FILE" ps --services --all | grep -qx "$name" >/dev/null 2>&1
else
docker ps -a --format '{{.Names}}' | grep -qx "$name" >/dev/null 2>&1
fi
}
docker_remove_all_local_containers_and_volumes() {
if [[ -f "$COMPOSE_FILE" ]]; then
shell_info "Using docker compose down -v to remove all services and volumes"
$DC -f "$COMPOSE_FILE" down -v >/dev/null 2>&1 || true
else
shell_info "Removing containers and volumes with docker commands"
# Remove containers
local containers
containers=$(docker ps -a --filter "name=${RUNNER_NAME_PREFIX}runner-" --format "{{.Names}}" 2>/dev/null || true)
if [[ -n "$containers" ]]; then
echo "$containers" | xargs -r docker rm -f >/dev/null 2>&1 || true
fi
# Remove volumes
local volumes
volumes=$(docker volume ls --filter "name=${RUNNER_NAME_PREFIX}runner-" --format "{{.Name}}" 2>/dev/null || true)
if [[ -n "$volumes" ]]; then
echo "$volumes" | xargs -r docker volume rm >/dev/null 2>&1 || true
fi
fi
}
# Usage:
# docker_runner_register -> auto-detect all runner-* containers and register unconfigured ones
# docker_runner_register runner-1 ... -> register runners with the specified names
docker_runner_register() {
local names=()
if [[ $# -gt 0 ]]; then
names=("$@")
else
mapfile -t names < <(docker_list_existing_containers | sed '/^$/d') || true
fi
if [[ ${#names[@]} -eq 0 ]]; then
shell_info "No Runner containers to register!"
return 0
fi
local cname
for cname in "${names[@]}"; do
if ! docker_container_exists "$cname"; then
shell_warn "Container does not exist: $cname (skipping)"
continue
fi
# Check if already configured
local is_configured=false
if [[ -f "$COMPOSE_FILE" ]]; then
if $DC -f "$COMPOSE_FILE" run --rm --no-deps "$cname" bash -lc 'test -f /home/runner/.runner && test -f /home/runner/.credentials' >/dev/null 2>&1; then
is_configured=true
fi
else
if docker exec "$cname" bash -c 'test -f /home/runner/.runner && test -f /home/runner/.credentials' >/dev/null 2>&1; then
is_configured=true
fi
fi
if $is_configured; then
shell_info "Already configured, skipping registration: $cname"
continue
fi
# Extract RUNNER_LABELS
local labels=""
if [[ -f "$COMPOSE_FILE" ]]; then
labels="$(shell_get_compose_file "$cname" "RUNNER_LABELS")" || labels=""
else
# Fallback: try to get from running container environment
labels="$(docker inspect "$cname" --format='{{range .Config.Env}}{{println .}}{{end}}' 2>/dev/null | grep '^RUNNER_LABELS=' | cut -d= -f2-)" || labels=""
fi
# Sanitize possible surrounding quotes then deduplicate labels
labels="$(printf '%s' "$labels" | sed -e 's/^\"\(.*\)\"$/\1/' -e "s/^'\(.*\)'$/\1/" | awk -F',' '{n=split($0,a,",");o="";for(i=1;i<=n;i++){gsub(/^[ \t]+|[ \t]+$/,"",a[i]);if(a[i]!=""&&!m[a[i]]++){o=(o?o",":"")a[i]}}print o}')"
local cfg_opts=(
"--url" "https://github.com/${ORG}${REPO:+/}${REPO}"
"--token" "${REG_TOKEN}"
"--name" "${cname}"
"--labels" "${labels}"
"--runnergroup" "${RUNNER_GROUP}"
"--unattended" "--replace"
)
[[ -n "${RUNNER_WORKDIR}" ]] && cfg_opts+=("--work" "${RUNNER_WORKDIR}")
[[ "${DISABLE_AUTO_UPDATE}" == "1" ]] && cfg_opts+=("--disableupdate")
shell_info "Registering ${cname} on GitHub with ${cfg_opts[@]}"
# Pass arguments directly to avoid shell quoting issues
if [[ -f "$COMPOSE_FILE" ]]; then
$DC -f "$COMPOSE_FILE" run --rm --no-deps "$cname" /home/runner/config.sh "${cfg_opts[@]}" >/dev/null || shell_warn "Registration failed (container: $cname)"
else
docker exec "$cname" /home/runner/config.sh "${cfg_opts[@]}" >/dev/null || shell_warn "Registration failed (container: $cname)"
fi
done
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
DC=$(docker_pick_compose)
CMD="${1:-help}"; shift || true
case "$CMD" in
# ./runner.sh help|-h|--help
help|-h|--help)
shell_usage
;;
# ./runner.sh ps|ls|list|status
ps|ls|list|status)
shell_get_org_and_pat
echo "--------------------------------- Containers -----------------------------------------"
docker_print_existing_containers_status
echo
echo "--------------------------------- Runners --------------------------------------------"
resp=$(github_api GET "/actions/runners?per_page=100") || shell_die "Failed to fetch runner list."
if command -v jq >/dev/null 2>&1; then
echo "$resp" | jq -r '.runners[] | [.name, .status, (if .busy then "busy" else "idle" end), ( [.labels[].name] | join(","))] | @tsv' \
| grep -E "^${RUNNER_NAME_PREFIX}runner-" \
| awk -F'\t' 'BEGIN{printf("%-40s %-8s %-6s %s\n","NAME","STATUS","BUSY","LABELS")}{printf("%-40s %-8s %-6s %s\n",$1,$2,$3,$4)}'
else
echo "$resp"
fi
echo
shell_info "Due to GitHub limitations, runner list is limited to 100 entries!"
echo
;;
# ./runner.sh init -n|--count N
init)
count=0
if [[ "${1:-}" == "-n" || "${1:-}" == "--count" ]]; then
shift
count="${1:-0}"
shift || true
fi
[[ "$count" =~ ^[0-9]+$ ]] || shell_die "Count must be numeric!"
REG_TOKEN="$(shell_get_reg_token)"
RUNNER_IMAGE="$(shell_prepare_runner_image)";
if [[ "${RUNNER_BOARD_COUNT}" -gt 0 ]]; then
shell_info "Generating $COMPOSE_FILE with $count generic runners and ${RUNNER_BOARD_COUNT} board runners."
else
shell_info "Generating $COMPOSE_FILE with $count generic runners."
fi
shell_generate_compose_file "$count"
$DC -f "$COMPOSE_FILE" up -d "$@";
docker_runner_register
;;
# ./runner.sh compose
compose)
cont_count=0
cont_list="$(docker_list_existing_containers)"
if [[ -n "$cont_list" ]]; then cont_count=$(echo "$cont_list" | wc -l | tr -d ' '); fi
# 计算通用 runner 的数量
if [[ "${RUNNER_BOARD_COUNT}" -gt 0 ]]; then
# 如果启用了板子 runner,则减去 RUNNER_BOARD_COUNT 个板子 runner
generic_count=$(( cont_count - RUNNER_BOARD_COUNT ))
[[ "$generic_count" -ge 0 ]] || generic_count=0
else
# 如果没有启用板子 runner,则所有容器都是通用 runner
generic_count=$cont_count
fi
if [[ "${RUNNER_BOARD_COUNT}" -gt 0 ]]; then
shell_info "Regenerating $COMPOSE_FILE with ${generic_count} existing runners and ${RUNNER_BOARD_COUNT} board runners."
else
shell_info "Regenerating $COMPOSE_FILE with ${generic_count} existing runners."
fi
RUNNER_IMAGE="$(shell_prepare_runner_image)";
REG_TOKEN="$(shell_get_reg_token)"
shell_generate_compose_file "$generic_count"
;;
# ./runner.sh register [${RUNNER_NAME_PREFIX}runner-<id> ...]
register)
REG_TOKEN="$(shell_get_reg_token)"
shell_update_compose_file "RUNNER_TOKEN" "$REG_TOKEN"