-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.sh
executable file
·1600 lines (1406 loc) · 48.8 KB
/
main.sh
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
#!/bin/bash
#
# Register external instance to Stackguardian platform.
set -o pipefail
#{{{ Environment variables
## main
CONTAINER_ORCHESTRATOR=
LOG_DEBUG=${LOG_DEBUG:=false}
CGROUPSV2_PREVIEW=${CGROUPSV2_PREVIEW:=false}
SG_BASE_API=${SG_BASE_API:="https://api.app.stackguardian.io/api/v1"}
readonly LOG_FILE="/tmp/sg_runner.log"
# static
readonly COMMANDS=( "jq" "crontab" )
# readonly CONTAINER_ORCHESTRATORS=( "docker" "podman" )
readonly CONTAINER_ORCHESTRATORS=( "docker" )
readonly FLUENTBIT_IMAGE="fluent/fluent-bit:2.2.0"
# source .env if exists
# overrides [main] environment variables
[[ -f .env ]] && . .env
## other
readonly SG_DOCKER_NETWORK="sg-net"
# configure diagnostics environment
readonly SG_DIAGNOSTIC_FILE="/tmp/diagnostic.json"
readonly SG_DIAGNOSTIC_TMP_FILE="/tmp/diagnostic.json.tmp"
if [[ ! -e "$SG_DIAGNOSTIC_FILE" ]]; then
touch "$SG_DIAGNOSTIC_FILE"
echo "{}" > "$SG_DIAGNOSTIC_FILE"
fi
## colors for printf
readonly C_RED_BOLD="\033[1;31m"
readonly C_RED="\033[0;31m"
readonly C_GREEN_BOLD="\033[1;32m"
readonly C_GREEN="\033[0;32m"
# readonly C_YELLOW_BOLD="\033[1;33m"
# readonly C_YELLOW="\033[0;33m"
# readonly C_BLUE_BOLD="\033[1;34m"
readonly C_BLUE="\033[0;34m"
readonly C_MAGENTA_BOLD="\033[1;35m"
# readonly C_MAGENTA="\033[0;35m"
# readonly C_CYAN_BOLD="\033[1;36m"
# readonly C_CYAN="\033[0;36m"
readonly C_RESET="\033[0m"
readonly C_BOLD="\033[1m"
#}}}: Environment variables
#{{{ Printing
show_help() { #{{{
cat <<EOF
sg-runner is a script for registration of Private Runner Nodes on Stackguardian.
More information available at: https://docs.stackguardian.io/docs/organisation_settings/private-runner-groups/
Examples:
# Register new runner
./$(basename "$0") register --sg-node-token "some-token" --organization "demo-org" --runner-group "private-runner-group"
# De-Register new runner
./$(basename "$0") deregister --sg-node-token "some-token" --organization "demo-org" --runner-group "private-runner-group"
# Disable cgroupsv2
# ./$(basename "$0") cgropusv2 disable
Available commands:
register [options] Register new Private Runner
deregsiter [options] Deregister existing Private Runner
status Show health status of used services/containers
info Show information about instance/registration
prune Prune container system older than 10 days
cgroupsv2 [enable|disable] Manage cgroups versions (deprecated)
Options:
--sg-node-token '': (required)
The runner node token acquired from Stackguardian platform.
--organization '': (required)
The organization name on Stackguardian platform.
--runner-group '': (required)
The runner group where new runner will be registered.
--no-clean-on-fail
Do not clean up local setup in case of errors during registration.
--ignore-fluentbit-errors
Ignore Fluentbit errors and proceed with the registration process.
--debug
Print more verbose output during command execution.
--force, -f
Execute some commands with force. Skip some sections in case of errors.
Usage:
./$(basename "$0") <command> [options]
EOF
}
#}}}: show_help
log_date() { #{{{
printf "${C_BLUE}[%s]${C_RESET}" "$(date +'%Y-%m-%dT%H:%M:%S')"
}
#}}}: log_date
err() { #{{{
printf "%s ${C_RED_BOLD}ERROR: ${C_RESET}%s${C_BOLD} %s${C_RESET} %s\n" "$(log_date)" "${1}" "${2}" "${@:3}" >&2
}
#}}}: err
log_err() { #{{{
local msg
local err
msg="$(tail -n1 "$LOG_FILE" | cut -d":" -f2-)"
err="$(tail -n1 "$LOG_FILE" | cut -d":" -f1)"
printf "%s ${C_RED_BOLD}ERROR: ${C_RESET}%s${C_BOLD} %s${C_RESET}\n" "$(log_date)" "$err" "$msg" >&2
}
#}}}: log_err
info() { #{{{
printf "%s %s${C_BOLD} %s${C_RESET} %s\n" "$(log_date)" "${1}" "${2}" "${@:3}"
}
#}}}: info
spinner_wait() { #{{{
printf "%s %s${C_BOLD} %s${C_RESET}\r" "$(log_date)" "${1}" "${2}"
}
#}}}: spinner_wait
spinner_msg() { #{{{
local status="$2"
local msg="$3"
if [[ -z "$status" ]]; then
printf "%s %s.. ${C_BOLD}%s${C_RESET}" "$(log_date)" "${1}" "${msg}"
if [[ "$LOG_DEBUG" =~ true|True ]]; then printf "\n"; fi
elif (( status==0 )); then
printf "%s %s.. ${C_GREEN_BOLD}%s${C_RESET}\n" "$(log_date)" "${1}" "${msg:="Done"}"
elif (( status>0 || status<0 )); then
printf "%s %s.. ${C_RED_BOLD}%s${C_RESET}\n" "$(log_date)" "${1}" "${msg:="Failed"}"
fi
}
#}}}: spinner_msg
debug() { #{{{
[[ "$LOG_DEBUG" =~ true|True ]] && \
printf "%s ${C_MAGENTA_BOLD}DEBUG:${C_RESET} %s${C_BOLD} %s${C_RESET} %s\n" "$(log_date)" "${1}" "${2}" "${@:3}"
}
#}}}: debug
debug_variable() { #{{{
[[ "$LOG_DEBUG" =~ true|True ]] && \
[[ -n "${!1}" ]] && \
[[ "${!1}" != "null" ]] && \
printf "%s ${C_MAGENTA_BOLD}DEBUG:${C_RESET} %s${C_BOLD} %s${C_RESET}\n" "$(log_date)" "${1}" "${!1}"
}
#}}}: debug
debug_secret() { #{{{
[[ "$LOG_DEBUG" =~ true|True ]] && \
[[ -n "${!1}" ]] && \
[[ "${!1}" != "null" ]] && \
printf "%s ${C_MAGENTA_BOLD}DEBUG:${C_RESET} %s${C_BOLD} %s${C_RESET}\n" "$(log_date)" "${1}" "${!1:0:5}*****"
}
#}}}: debug
cmd_example() { #{{{
echo
printf "%s${C_BOLD} %s${C_RESET} %s\n" "${1}" "${2}" "${@:3}"
}
#}}}: cmd_example
exit_help() { #{{{
exit_code=$?
(( exit_code!=0 )) && \
printf "\n(Try ${C_BOLD}%s --help${C_RESET} for more information. Use --debug for verbose logs.)\n" "$(basename "${0}")"
}
#}}}: exit_help
#######################################
# Print frame for doctor check.
# Globals:
# None
# Arguments:
# Title
# Contents of frame
# Returns:
# None
# Outputs:
# Write to STDOUT frame with contents
#######################################
doctor_frame() { #{{{
printf " + %s " "${1}"
printf "\n |"
printf "%s" "$2"
# printf "\n |\n"
printf "\n"
}
#}}}: doctor_frame
#######################################
# Print details at the end of registration
# Globals:
# ORGANIZATION_NAME
# RUNNER_GROUP_ID
# RUNNER_ID
# Arguments:
# None
# Outputs:
# Write to STDOUT
#######################################
details_frame() { #{{{
printf " + ${C_BOLD}%s${C_RESET} " "${1}"
printf "\n |\n"
}
#}}}: details_frame
details_item() { #{{{
printf " | * %s: ${C_GREEN_BOLD}%s${C_RESET}\n" "$1" "$2"
}
#}}}: details_item
print_details() { #{{{
echo
details_frame "Registration Details"
# details_item "Registration Date" "$(date +'%Y-%m-%d %H:%M:%S (GMT%z)')"
details_item "Organization" "${ORGANIZATION_ID}"
details_item "Runner Group" "${RUNNER_GROUP_ID}"
echo
details_frame "Host Information"
details_item "Hostaname" "$HOSTNAME"
details_item "Private IP Address" "$(ip route | grep default | cut -d" " -f9)"
details_item "Public IP Address" "$(curl -fSs ifconfig.me)"
echo
details_frame "System Information"
details_item "OS Release" "$(cat /etc/*release | grep -oP '(?<=PRETTY_NAME=").*?(?=")')"
details_item "Uptime" "$(uptime | awk '{gsub(",", "", $3); print $1, $2, $3}')"
details_item "Load Average" "$(uptime | awk -F 'load average:' '{print $2}')"
echo
details_frame "Hardware Information"
details_item "CPU Cores" "$(echo "$(nproc) Core [Used: $(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}' | awk '{printf "%.0f%%", $1}')]")"
details_item "Memory" "$(free -h | awk '/^Mem:/ {printf "%s [Used: %s]\n", $2, $3}')"
details_item "Disk Size" "$(df -h --total | awk '/^total/ {printf "%s [Used: %s]\n", $2, $(NF-1)}')"
echo
}
#}}}: print_details
#}}}: Printing
#{{{ Services
#######################################
# Check fluentbit errors for storage.
# If errors, print and exit.
# Globals:
# None
# Arguments:
# None
# Returns:
# None
# Outputs:
# Write to STDOUT/STDERR
# if successfull/error.
#######################################
check_fluentbit_status() { #{{{
spinner_wait "Starting backend storage check.."
local container_id
local log_file
until [[ -n "$container_id" ]]; do
container_id="$($CONTAINER_ORCHESTRATOR ps -q --filter "name=fluentbit-agent")"
done
debug "Fluentbit container id:" "$container_id"
until [[ -n "$log_file" ]]; do
log_file="$(echo /var/lib/docker/containers/"$container_id"*/*.log)"
[[ ! -e $log_file ]] && unset log_file
done
debug "Fluentbit log file:" "$log_file"
# spinner_msg "Starting backend storage check" 0
timeout=30
tries=0
until (( $(grep -ia -A2 "stream processor started" "$log_file" | wc -l) >= 2 )) || (( tries >= timeout )); do
debug "Try #$((++tries)): No stream processor started message found"
sleep 2
done & spinner "$!" "Waiting for fluentbit logs"
if (( tries < timeout )); then
info "Fluentbit stream processor started successfully, checking for errors"
else
info "Timed out searchnig for stream processor to start in the logs file, perhaps there are lot of logs. Proceeding to check for errors anyway"
fi
timeout=5
tries=0
until (( found_error == 1 )) || (( tries >= timeout )); do
# TODO: Do not run error chesks at all if ignore_fluentbit_errors is set
err_msg="$(grep -iaA4 -m1 -E "\[error.*" "$log_file" | tr -d '\0')"
if [[ -z "$err_msg" ]]; then
debug "Try #$((++tries)): No error messages found."
sleep 2
else
debug "Error messages found."
found_error=1
break
fi
done & spinner "$!" "Checking for any errors in Fluentbit logs"
err_msg="$(grep -iaA4 -m1 -E "\[error.*" "$log_file" | tr -d '\0')"
if [[ -n "$err_msg" ]]; then
if ignore_fluentbit_errors; then
debug "Ignoring Fluentbit error(s) $err_msg"
else
err "Fluentbit encountered error(s)" "$err_msg"
if ! no_clean_on_fail; then
clean_local_setup & spinner "$!" "Starting cleanup"
info "Use --no-clean-on-fail to not clean up after Fluentbit errors are encountered for debugging issues"
else
info ""
info "WARNING:" "If retrying a new registration, do not use --no-clean-on-fail as it leaves the system in an inconsistent state only useful for debugging purposes"
fi
info "Use --ignore-fluentbit-errors to ignore errors and proceed with the registration process"
exit 1
fi
else
info "Storage backend status:" "healthy"
fi
}
#}}}: check_fluentbit_status
#######################################
# Check if specific service.$1 is runing.
# If not try reload or restart.
# Globals:
# None
# Arguments:
# systemctl service
# Returns:
# None
# Outputs:
# Write to STDOUT/STDERR
# if successfull/error.
#######################################
check_systemctl_status() { #{{{
if ! systemctl is-active "$1" >&/dev/null; then
debug "Reloading/Restarting neccessary services.."
if ! systemctl reload-or-restart "$1" 2>/dev/null; then
return 2
fi
return 0
else
return 0
fi
}
#}}}: check_systemctl_status
#######################################
# Check if ecs.service exists
# and if it is healthy and running.
# Globals:
# None
# Arguments:
# None
# Returns:
# 0 if ecs.service does not exists
# Outputs:
# Write to STDOUT/STERR
# if successfull/error.
#######################################
check_systemctl_ecs_status() { #{{{
systemctl status ecs --no-pager >&/dev/null
if [[ "$?" =~ 4|0 ]]; then
return 0
else
check_systemctl_status "ecs"
fi
}
#}}}: check_systemctl_status
#######################################
# Check if container orchestartor exists
# and if it is healthy and running.
# Globals:
# None
# Arguments:
# Container Orchestrator Command
# Returns:
# None
# Outputs:
# Write to STDOUT/STERR
# if successfull/error.
#######################################
check_container_orchestrator() { #{{{
if type "$1" >&/dev/null; then
check_systemctl_status "$1"
return $?
else
return 1
fi
}
#}}}: check_container_orchestrator
#######################################
# Enable/Disable cgroupsv2 (Preview)
# Globals:
# None
# Arguments:
# enable/disable
# Returns:
# None
# Outputs:
# Write to STDOUT/STERR
# if successfull/error.
#######################################
cgroupsv2() { #{{{
local cgroup_toggle
[[ "$1" == "enable" ]] &&
cgroup_toggle=1 || cgroup_toggle=0
if (( cgroup_toggle==0 )); then
info "Switching to" "cgroupsv1"
else
info "Switching to" "cgroupsv2"
fi
info "Reboot required!"
while :; do
read -r -p "$(log_date) Continue.. [Y/n]: " choice
if [[ "${choice:="Y"}" =~ y|Y ]]; then
break
elif [[ "$choice" =~ n|N ]]; then
exit 0
else
info "Unsupported option:" "$choice"
fi
done
if type grubby >&/dev/null; then
grubby --update-kernel=ALL --args="systemd.unified_cgroup_hierarchy=$cgroup_toggle"
else
grub_cmdline="$(grep "GRUB_CMDLINE_LINUX=.*" /etc/default/grub | grep -o '".*"' | tr -d '"')"
debug "GRUB_CMDLINE_LINUX" "$grub_cmdline"
if [[ -n "$grub_cmdline" ]]; then
pattern="(systemd.unified_cgroup_hierarchy)=(.*)"
if [[ $grub_cmdline =~ $pattern ]]; then
pattern=${pattern//(/\\(}
grub_cmdline="$(echo "$grub_cmdline" \
| sed "s/${pattern//)/\\)}/\1=$cgroup_toggle/")"
debug "GRUB_CMDLINE_LINUX switched" "$grub_cmdline"
else
grub_cmdline="$grub_cmdline systemd.unified_cgroup_hierarchy=$cgroup_toggle"
debug "GRUB_CMDLINE_LINUX appended" "$grub_cmdline"
fi
else
grub_cmdline="systemd.unified_cgroup_hierarchy=$cgroup_toggle"
debug "GRUB_CMDLINE_LINUX new" "$grub_cmdline"
fi
sed -i "s/^GRUB_CMDLINE_LINUX=.*/GRUB_CMDLINE_LINUX=\"$grub_cmdline\"/" /etc/default/grub
fi
reboot
exit 0
}
#}}}: cgroupsv2
api_call() { #{{{
# TODO: Support draining of instance
if [[ -n "$1" ]]; then
response=$(curl -i -s \
-X POST \
-H "Authorization: apikey ${SG_NODE_TOKEN}" \
-H "Content-Type: application/json" \
-d "$1" \
"${url}")
else
response=$(curl -i -s \
-X POST \
-H "Authorization: apikey ${SG_NODE_TOKEN}" \
-H "Content-Type: application/json" \
"${url}")
fi
if [[ -z "$response" ]]; then
exit 1
else
full_response="$response"
fi
debug "Response:" \
&& echo "-----" \
&& echo "${response}" \
&& echo "-----"
# get first status code from response
status_code="$(echo "$response" \
| awk '/^HTTP/ {print $2}')"
# actual response data
response="$(echo "$response" \
| awk '/^Response/ {print $2}')"
[[ -z "$response" ]] && \
response="$(echo "$full_response" | sed -n '/^{.*/,$p' | tr '\n' ' ')"
# msg from data
message="$(echo "$response" \
| jq -r '.msg // .message // "Unknown error"')"
# data from data
data="$(echo "$response" \
| jq -r '.data // "Unknown error"')"
if [[ -z "$status_code" ]]; then
err "Unknown status code."
exit 1
elif [ "$status_code" != "200" ] && [ "$status_code" != "201" ] && [ "$status_code" != "100" ]; then
return 1
# TODO: Handle by retrying for 5 mins: ERROR: Could not fetch data from API. 504 Network error communicating with endpoint
else
return 0
fi
}
#}}}: api_call
#######################################
# Run fluentbit $CONTAINER_ORCHESTRATOR container for logging
# Globals:
#
# Arguments:
# AWS_ACCESS_KEY_ID
# AWS_SECRET_ACCESS_KEY
# Outputs:
# Write to STDOUT/STERR
# if successfull/error.
#######################################
# This portion checks whether the STORAGE_BACKEND_TYPE is
# aws_s3 or azure_blob and runs the container accordingly.
########################################
setup_cron() { #{{{
local temp_file
temp_file=$(mktemp -t crontab_XXX.bup)
crontab -l > "$temp_file" 2>/dev/null || echo "" > "$temp_file"
if grep -qi -E "status|prune" "$temp_file"; then
clean_cron
crontab -l > "$temp_file" 2>/dev/null || echo "" > "$temp_file"
fi
{ echo "* * * * * /bin/bash $PWD/main.sh status";
echo "0 */4 * * * /bin/bash $PWD/main.sh prune"
} >> "$temp_file"
/usr/bin/crontab "$temp_file"
}
#}}}: setup_cron
clean_cron() { #{{{
local temp_file
temp_file=$(mktemp -t crontab_XXX.bup)
crontab -l > "$temp_file" 2>/dev/null
if [[ -s "$temp_file" ]]; then
sed -i "\|* * * * * /bin/bash $PWD/main.sh status|d" "$temp_file"
sed -i "\|0 \*\/4 \* \* \* /bin/bash $PWD/main.sh prune|d" "$temp_file"
/usr/bin/crontab "$temp_file"
fi
}
#}}}: clean_cron
#}}}: Services
#{{{ Other
cleanup() { #{{{
printf "\nGraceful shutdown..\n"
[[ -n ${spinner_pid} ]] && kill "${spinner_pid}" >&/dev/null
exit 0
}
#}}}: cleanup
force_exec() { #{{{
[[ "$FORCE_PASS" == true ]] && return 0
return 1
}
#}}}: force_exec
no_clean_on_fail() { #{{{
[[ "$NO_CLEAN_ON_FAIL" == true ]] && return 0
return 1
}
#}}}: no_clean_on_fail
ignore_fluentbit_errors() { #{{{
[[ "$IGNORE_FLUENTBIT_ERRORS" == true ]] && return 0
return 1
}
#}}}: ignore_fluentbit_errors
spinner() { #{{{
local spinner_pid=$1
local msg="$2"
local status="$3"
local log_file="$LOG_FILE"
local delay=0.15
local spinstr='|/-\'
spinner_msg "$msg"
if [[ "${LOG_DEBUG}" =~ false|False ]]; then
while ps a | awk '{print $1}' | grep "${spinner_pid}" >&/dev/null; do
local temp=${spinstr#?}
printf "${C_BOLD}[%c]${C_RESET}" "$spinstr"
local spinstr=$temp${spinstr%"$temp"}
sleep $delay
printf "\b\b\b"
done
else
tail -n0 -f "${log_file}" --pid "${spinner_pid}"
fi
wait "${spinner_pid}"
local exit_code=$?
printf " \b\b\b\b\b\r"
debug "$msg (exit code):" "$exit_code"
if [[ ! "${LOG_DEBUG}" =~ true|True ]]; then
spinner_msg "$msg" "$exit_code"
fi
(( exit_code!=0 )) && log_err && exit $exit_code
return $exit_code
}
#}}}: spinner
clean_local_setup() { #{{{
debug "Stopping services.."
systemctl stop ecs 2>/dev/null
debug "Stopping $CONTAINER_ORCHESTRATOR containers.."
$CONTAINER_ORCHESTRATOR stop ecs-agent fluentbit-agent >&/dev/null
debug "Removing $CONTAINER_ORCHESTRATOR containers.."
$CONTAINER_ORCHESTRATOR rm ecs-agent fluentbit-agent >&/dev/null
debug "Removing $CONTAINER_ORCHESTRATOR network: ${SG_DOCKER_NETWORK}.."
$CONTAINER_ORCHESTRATOR network rm "${SG_DOCKER_NETWORK}" >&/dev/nul
debug "Removing local configuration.."
rm -rf \
/var/log/ecs \
/etc/ecs \
/var/lib/ecs \
./fluent-bit.conf \
volumes/ \
./aws-credentials \
./db-state \
/var/log/registration \
./ssm-binaries \
/var/lib/amazon/ssm \
/root/.aws/credentials >&/dev/null
clean_cron
# Wait for AWS SSM Managed Instance to deregister on AWS side
sleep 10s
return 0
}
#}}}: clean_local_setup
check_variable_value() { #{{{
local variable_name=$1
[[ -z "${!variable_name}" ]] && \
err "Variable can't be empty" "$variable_name" && exit 1
return 0
}
#}}}
# Define a function to append common SERVICE and INPUT blocks
append_common_service_and_input_blocks() {
cat > ./fluent-bit.conf << EOF
[SERVICE]
Flush 1
Log_Level info
Buffer_Chunk_size 1M
Buffer_Max_Size 6M
HTTP_Server On
HTTP_Listen 0.0.0.0
HTTP_PORT 2020
Health_Check On
HC_Errors_Count 5
HC_Retry_Failure_Count 5
HC_Period 5
[INPUT]
Name forward
Listen 0.0.0.0
port 24224
[INPUT]
Name tail
Tag ecsagent
path /var/lib/docker/containers/*/*-json.log
DB /var/log/flb_docker.db
Mem_Buf_Limit 50MB
[INPUT]
Name tail
Tag registrationinfo
path /var/log/registration/*.txt
DB /var/log/flb_docker.db
Mem_Buf_Limit 50MB
EOF
}
# Function to append Azure Blob OUTPUT block in fluent-bit.conf
append_s3_output_block() {
local match=$1
local upload_timeout=$2
local s3_key_format=$3
local extra_config=$4 # Additional config if needed
cat >> ./fluent-bit.conf << EOF
[OUTPUT]
Name s3
Match ${match}
region ${S3_AWS_REGION}
upload_timeout ${upload_timeout}
store_dir_limit_size 2G
total_file_size 250M
retry_limit 20
use_put_object On
compression gzip
bucket ${S3_BUCKET_NAME}
s3_key_format ${s3_key_format}
EOF
if [[ -n "${S3_AWS_ROLE_ARN}" && -n "${S3_AWS_EXTERNAL_ID}" ]]; then
echo " role_arn ${S3_AWS_ROLE_ARN}" >> ./fluent-bit.conf
echo " external_id ${S3_AWS_EXTERNAL_ID}" >> ./fluent-bit.conf
fi
}
#}}}: append_s3_output_block
# Function to append Azure Blob OUTPUT block in fluent-bit.conf
append_azure_blob_output_block() {
local match=$1
local path=$2
local container_name=${3:-system} # Default to 'system' if not provided
cat >> ./fluent-bit.conf << EOF
[OUTPUT]
Name azure_blob
Match ${match}
account_name ${STORAGE_ACCOUNT_NAME}
shared_key ${SHARED_KEY}
blob_type blockblob
path ${path}
container_name ${container_name}
auto_create_container on
tls on
EOF
}
#}}}: append_azure_blob_output_block
#}}}: Other
#{{{ Local configuration
#######################################
# Configure local directories and files.
# Globals:
# ECS_CLUSTER
# LOCAL_AWS_DEFAULT_REGION
# ORGANIZATION_ID
# RUNNER_ID
# RUNNER_GROUP_ID
# Arguments:
# None
# Outputs:
# Writes STDOUT on success.
#######################################
configure_local_data() { #{{{
mkdir -p /var/log/ecs /etc/ecs /var/lib/ecs/data /etc/fluentbit/ /var/log/registration/
rm -rf /etc/ecs/ecs.config > /dev/null
spinner_wait "Configuring local data.."
# ECS_LOG_DRIVER
# ECS_LOG_OPTS
# ECS_DISABLE_IMAGE_CLEANUP true Whether to disable automated image cleanup for the ECS Agent. false false
# ECS_IMAGE_CLEANUP_INTERVAL 30m The time interval between automated image cleanup cycles. If set to less than 10 minutes, the value is ignored. 30m 30m
# ECS_IMAGE_MINIMUM_CLEANUP_AGE 30m The minimum time interval between when an image is pulled and when it can be considered for automated image cleanup. 1h 1h
# NON_ECS_IMAGE_MINIMUM_CLEANUP_AGE
# ECS_NUM_IMAGES_DELETE_PER_CYCLE
# ECS_IMAGE_PULL_BEHAVIOR
# AWS_ACCESS_KEY_ID
# AWS_SECRET_ACCESS_KEY
# AWS_SESSION_TOKEN
# ECS_ALTERNATE_CREDENTIAL_PROFILE
# ECS_IMAGE_PULL_BEHAVIOR=prefer-cached # The behavior used to customize the pull image process. If default is specified, the image will be pulled remotely, if the pull fails then the cached image in the instance will be used. If always is specified, the image will be pulled remotely, if the pull fails then the task will fail. If once is specified, the image will be pulled remotely if it has not been pulled before or if the image was removed by image cleanup, otherwise the cached image in the instance will be used. If prefer-cached is specified, the image will be pulled remotely if there is no cached image, otherwise the cached image in the instance will be used.
# ECS_ENGINE_AUTH_TYPE "docker" | "dockercfg" The type of auth data that is stored in the ECS_ENGINE_AUTH_DATA key.
# ECS_ENGINE_AUTH_DATA
cat > /etc/ecs/ecs.config << EOF
ECS_CLUSTER=${ECS_CLUSTER}
AWS_DEFAULT_REGION=${LOCAL_AWS_DEFAULT_REGION}
ECS_INSTANCE_ATTRIBUTES={"sg_organization": "${ORGANIZATION_NAME}","sg_runner_id": "${RUNNER_ID}", "sg_runner_group_id": "${RUNNER_GROUP_ID}"}
ECS_LOGLEVEL=info
ECS_DISABLE_PRIVILEGED=false
ECS_ENABLE_UNTRACKED_IMAGE_CLEANUP=true
ECS_ENGINE_TASK_CLEANUP_WAIT_DURATION=24h
ECS_IMAGE_CLEANUP_INTERVAL=24h
ECS_IMAGE_MINIMUM_CLEANUP_AGE=1h
NON_ECS_IMAGE_MINIMUM_CLEANUP_AGE=1h
# ECS_ALTERNATE_CREDENTIAL_PROFILE=sg-runner
ECS_TASK_METADATA_RPS_LIMIT=300,400
AWS_EC2_METADATA_DISABLED=true
ECS_LOGFILE=/log/ecs-agent.log
ECS_DATADIR=/data/
ECS_ENABLE_TASK_IAM_ROLE=true
ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST=true
ECS_EXTERNAL=true
EOF
# Configure Fluentbit configuration inside /etc/fluentbit/fluent-bit.conf
if [[ "${STORAGE_BACKEND_TYPE}" == "aws_s3" ]]; then
append_common_service_and_input_blocks
append_s3_output_block "fluentbit" "15s" "/system/fluentbit/fluentbit"
append_s3_output_block "ecsagent" "5m" "/system/ecsagent/ecsagent"
append_s3_output_block "registrationinfo" "2m" "/system/registrationinfo/registrationinfo"
cat >> ./fluent-bit.conf << EOF
[OUTPUT]
Name s3
Match_Regex orgs**
region ${S3_AWS_REGION}
upload_timeout 3s
store_dir_limit_size 2G
total_file_size 250M
retry_limit 20
use_put_object On
compression gzip
bucket ${S3_BUCKET_NAME}
s3_key_format /\$TAG/logs/log
EOF
if [[ -n "${S3_AWS_ROLE_ARN}" && -n "${S3_AWS_EXTERNAL_ID}" ]]; then
echo " role_arn ${S3_AWS_ROLE_ARN}" >> ./fluent-bit.conf
echo " external_id ${S3_AWS_EXTERNAL_ID}" >> ./fluent-bit.conf
fi
elif [[ "${STORAGE_BACKEND_TYPE}" == "azure_blob_storage" ]]; then
append_common_service_and_input_blocks
append_azure_blob_output_block "fluentbit" "fluentbit/log"
append_azure_blob_output_block "ecsagent" "ecsagent/log"
append_azure_blob_output_block "registrationinfo" "registrationinfo/log"
cat >> ./fluent-bit.conf << EOF
[OUTPUT]
Name azure_blob
Match_Regex orgs**
account_name ${STORAGE_ACCOUNT_NAME}
shared_key ${SHARED_KEY}
container_name runner
auto_create_container on
tls on
EOF
fi
spinner_msg "Configuring local data" 0
}
#}}}: configure_local_data
#######################################
# Configure local network.
# Globals:
# SG_DOCKER_NETWORK
# Arguments:
# None
# Outputs:
# Writes STDOUT on success.
#######################################
configure_local_network() { #{{{
spinner_wait "Configuring local network.."
# Create SG_DOCKER_NETWORK $CONTAINER_ORCHESTRATOR network
$CONTAINER_ORCHESTRATOR network create --driver bridge "${SG_DOCKER_NETWORK}" >&/dev/null
bridge_id="br-$($CONTAINER_ORCHESTRATOR network ls -q --filter "name=${SG_DOCKER_NETWORK}")"
iptables \
-I DOCKER-USER \
-i "${bridge_id}" \
-d 169.254.169.254,10.0.0.0/24 \
-j DROP
debug "$CONTAINER_ORCHESTRATOR network ${SG_DOCKER_NETWORK} created."
# Set up necessary rules to enable IAM roles for tasks
sysctl -w net.ipv4.conf.all.route_localnet=1 >/dev/null
sysctl -w net.ipv4.ip_forward=1 >/dev/null
iptables \
-t nat \
-A PREROUTING \
-p tcp \
-d 169.254.170.2 \
--dport 80 \
-j DNAT \
--to-destination 127.0.0.1:51679
iptables \
-t nat \
-A OUTPUT \
-d 169.254.170.2 \
-p tcp \
-m tcp \
--dport 80 \
-j REDIRECT \
--to-ports 51679
spinner_msg "Configuring local network" 0
}
#}}}: configure_local_network
#}}}: Local data functions
#######################################
# Fetch necessary info from API.
# Globals:
# SG_NODE_TOKEN
# ORGANIZATION_ID
# RUNNER_GROUP_ID
# Arguments:
# None
# Outputs:
# Write to STDERR if error and exit.
# Set all neccessary environment variables.
#######################################
fetch_organization_info() { #{{{
local url
local metadata
spinner_wait "Trying to fetch registration data.."
url="${SG_BASE_API}/orgs/${ORGANIZATION_ID}/runnergroups/${RUNNER_GROUP_ID}/register/"
debug "Calling URL:" "${url}"
if api_call; then
spinner_msg "Trying to fetch registration data" 0
spinner_wait "Preparing environment.."
metadata="$(echo "${response}" | jq -r '.data.RegistrationMetadata[0]')"
if [[ "$metadata" == "null" || -z "$metadata" ]]; then
spinner_msg "Preparing environment.." 1
err "API data missing registration metadata."
exit 1
fi
else
spinner_msg "Trying to fetch registration data" 1
err "Could not fetch data from API." "$status_code" "$message"
exit 1
fi
spinner_msg "Preparing environment" 0
## API response values (Registration Metadata)
ECS_CLUSTER="$(echo "${metadata}" | jq -r '.ECSCluster')"
LOCAL_AWS_DEFAULT_REGION="$(echo "${metadata}" | jq -r '.AWSDefaultRegion')"
SSM_ACTIVATION_ID="$(echo "${metadata}" | jq -r '.SSMActivationId')"
SSM_ACTIVATION_CODE="$(echo "${metadata}" | jq -r '.SSMActivationCode')"
for var in ECS_CLUSTER LOCAL_AWS_DEFAULT_REGION SSM_ACTIVATION_ID SSM_ACTIVATION_CODE; do
check_variable_value "$var"
done
debug_variable "ECS_CLUSTER"
debug_variable "LOCAL_AWS_DEFAULT_REGION"
debug_secret "SSM_ACTIVATION_ID"
debug_secret "SSM_ACTIVATION_CODE"
## Everything else
ORGANIZATION_NAME="$(echo "${response}" | jq -r '.data.OrgName')"
ORGANIZATION_ID="$(echo "${response}" | jq -r '.data.OrgId')"
RUNNER_ID="$(echo "${response}" | jq -r '.data.RunnerId')"
RUNNER_GROUP_ID="$(echo "${response}" | jq -r '.data.RunnerGroupId')"
RUNNER_GROUP_ID="${RUNNER_GROUP_ID##*/}"
# TAGS="$(echo "${response}" | jq -r '.data.Tags')"
STORAGE_ACCOUNT_NAME="$(echo "${response}" | jq -r '.data.RunnerGroup.StorageBackendConfig.azureBlobStorageAccountName // empty')"
SHARED_KEY="$(echo "${response}" | jq -r '.data.RunnerGroup.StorageBackendConfig.azureBlobStorageAccessKey // empty')"
STORAGE_BACKEND_TYPE="$(echo "${response}" | jq -r '.data.RunnerGroup.StorageBackendConfig.type // empty')"
S3_BUCKET_NAME="$(echo "${response}" | jq -r '.data.RunnerGroup.StorageBackendConfig.s3BucketName // empty')"
S3_AWS_REGION="$(echo "${response}" | jq -r '.data.RunnerGroup.StorageBackendConfig.awsRegion // empty')"
S3_AWS_ACCESS_KEY_ID="$(echo "${response}" | jq -r '.data.RunnerGroup.StorageBackendConfig.auth.config[0].awsAccessKeyId // empty')"
S3_AWS_SECRET_ACCESS_KEY="$(echo "${response}" | jq -r '.data.RunnerGroup.StorageBackendConfig.auth.config[0].awsSecretAccessKey // empty')"
S3_AWS_ROLE_ARN="$(echo "${response}" | jq -r '.data.RunnerGroup.StorageBackendConfig.auth.config[0].roleArn // empty')"