This repository has been archived by the owner on Mar 18, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathinstall.sh
executable file
·2892 lines (2514 loc) · 91.9 KB
/
install.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
#!/usr/bin/env sh
# MIT License
#
# Copyright (c) 2022-2023 Carlo Corradini
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Current directory
# shellcheck disable=SC1007
DIRNAME=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
# Load commons
# shellcheck source=scripts/__commons.sh
. "$DIRNAME/scripts/__commons.sh"
# ================
# CONFIGURATION
# ================
# Admin username
ADMIN_USERNAME="admin"
# Admin password
ADMIN_PASSWORD="Password\$0"
# Airgap environment flag
AIRGAP_ENV=false
# Autoscaler username
AUTOSCALER_USERNAME="autoscaler"
# Autoscaler password
AUTOSCALER_PASSWORD="Password\$0"
# Autoscaler version
AUTOSCALER_VERSION=latest
# Benchmark time in seconds
BENCH_TIME=30
# Configuration file
CONFIG_FILE="configs/recluster/config.yaml"
# Initialize cluster
INIT_CLUSTER=false
# K3s configuration file
K3S_CONFIG_FILE="configs/k3s/config.yaml"
# K3s registry configuration file
K3S_REGISTRY_CONFIG_FILE="configs/k3s/registries.yaml"
# K3s version
K3S_VERSION=latest
# Node exporter configuration file
NODE_EXPORTER_CONFIG_FILE="configs/node_exporter/config.yaml"
# Node exporter version
NODE_EXPORTER_VERSION=latest
# Power consumption device api url
PC_DEVICE_API="http://pc.recluster.local/cm?cmnd=status%2010"
# Power consumption interval in seconds
PC_INTERVAL=1
# Power consumption time in seconds
PC_TIME=30
# Power consumption warmup time in seconds
PC_WARMUP=10
# reCluster etc directory
RECLUSTER_ETC_DIR="/etc/recluster"
# reCluster opt directory
RECLUSTER_OPT_DIR="/opt/recluster"
# reCluster certificates directory
RECLUSTER_CERTS_DIR="configs/certs"
# reCluster server environment file
RECLUSTER_SERVER_ENV_FILE="configs/recluster/server.env"
# SSH authorized keys file
SSH_AUTHORIZED_KEYS_FILE="configs/ssh/authorized_keys"
# SSH configuration file
SSH_CONFIG_FILE="configs/ssh/ssh_config"
# SSH server configuration file
SSHD_CONFIG_FILE="configs/ssh/sshd_config"
# User
USER="root"
# ================
# GLOBALS
# ================
# Autoscaler directory
AUTOSCALER_DIR=
# Autoscaler token
AUTOSCALER_TOKEN=
# Configuration
CONFIG=
# K3s configuration
K3S_CONFIG=
# Node exporter configuration
NODE_EXPORTER_CONFIG=
# Node facts
NODE_FACTS='{}'
# Temporary directory
TMP_DIR=
# ================
# CLEANUP
# ================
cleanup() {
# Exit code
_exit_code=$?
[ $_exit_code = 0 ] || WARN "Cleanup exit code $_exit_code"
# Cleanup temporary directory
cleanup_dir "$TMP_DIR"
# Cleanup spinner
cleanup_spinner
exit "$_exit_code"
}
# Trap
trap cleanup INT QUIT TERM EXIT
# ================
# FUNCTIONS
# ================
# Show help message
show_help() {
cat << EOF
Usage: $(basename "$0") [--admin-username <USERNAME>] [--admin-password <PASSWORD>] [--airgap]
[--autoscaler-username <USERNAME>] [--autoscaler-password <PASSWORD>] [--autoscaler-version <VERSION>]
[--bench-time <TIME>] [--certs-dir <DIR>] [--config-file <FILE>] [--help]
[--init-cluster] [--k3s-config-file <FILE>] [--k3s-registry-config-file <FILE>] [--k3s-version <VERSION>]
[--node-exporter-config-file <FILE>] [--node-exporter-version <VERSION>]
[--pc-device-api <URL>] [--pc-interval <TIME>] [--pc-time <TIME>] [--pc-warmup <TIME>]
[--server-env-file <FILE>] [--ssh-authorized-keys-file <FILE>] [--ssh-config-file <FILE>] [--sshd-config-file <FILE>]
[--user <USER>]
$HELP_COMMONS_USAGE
reCluster installation script.
Options:
--admin-username <USERNAME> Admin username
Default: $ADMIN_USERNAME
Values:
Any valid username
--admin-password <PASSWORD> Admin password
Default: $ADMIN_PASSWORD
Values:
Any valid password
--airgap Perform installation in Air-Gap environment
--autoscaler-username <USERNAME> Autoscaler username
Default: $AUTOSCALER_USERNAME
Values:
Any valid username
--autoscaler-password <PASSWORD> Autoscaler password
Default: $AUTOSCALER_PASSWORD
Values:
Any valid password
--autoscaler-version <VERSION> Autoscaler version
Default: $AUTOSCALER_VERSION
Values:
Any Autoscaler version
--bench-time <TIME> Benchmark execution time in seconds
Default: $BENCH_TIME
Values:
Any positive number
--certs-dir <DIR> Server certificates directory
Default: $RECLUSTER_CERTS_DIR
Values:
Any valid directory
--config-file <FILE> Configuration file
Default: $CONFIG_FILE
Values:
Any valid file
--help Show this help message and exit
--init-cluster Initialize cluster components and logic
Enable only when bootstrapping for the first time
--k3s-config-file <FILE> K3s configuration file
Default: $K3S_CONFIG_FILE
Values:
Any valid file
--k3s-registry-config-file <FILE> K3s registry configuration file
Default: $K3S_REGISTRY_CONFIG_FILE
Values:
Any valid file
--k3s-version <VERSION> K3s version
Default: $K3S_VERSION
Values:
Any K3s version
--node-exporter-config-file <FILE> Node exporter configuration file
Default: $NODE_EXPORTER_CONFIG_FILE
Values:
Any valid file
--node-exporter-version <VERSION> Node exporter version
Default: $NODE_EXPORTER_VERSION
Values:
Any Node exporter version
--pc-device-api <URL> Power consumption device api URL
Default: $PC_DEVICE_API
Values:
Any valid URL
--pc-interval <TIME> Power consumption read interval time in seconds
Default: $PC_INTERVAL
Values:
Any positive number
--pc-time <TIME> Power consumption execution time in seconds
Default: $PC_TIME
Values:
Any positive number
--pc-warmup <TIME> Power consumption warmup time in seconds
Default: $PC_WARMUP
Values:
Any positive number
--server-env-file <FILE> Server environment file
Default: $RECLUSTER_SERVER_ENV_FILE
Values:
Any valid file
--ssh-authorized-keys-file <FILE> SSH authorized keys file
Default: $SSH_AUTHORIZED_KEYS_FILE
Values:
Any valid file
--ssh-config-file <FILE> SSH configuration file
Default: $SSH_CONFIG_FILE
Values:
Any valid file
--sshd-config-file <FILE> SSH server configuration file
Default: $SSHD_CONFIG_FILE
Values:
Any valid file
--user <USER> User
Default: $USER
Values:
Any valid user
$HELP_COMMONS_OPTIONS
EOF
}
# Assert init system
assert_init_system() {
if [ -x /sbin/openrc-run ]; then
# OpenRC
INIT_SYSTEM=openrc
elif [ -x /bin/systemctl ] || type systemctl > /dev/null 2>&1; then
# systemd
INIT_SYSTEM=systemd
fi
# Init system check
if [ -n "$INIT_SYSTEM" ]; then
# Supported
DEBUG "Init system is '$INIT_SYSTEM'"
else
# Not supported
FATAL "No supported init system found: 'OpenRC' or 'systemd'"
fi
}
# Assert timezone
assert_timezone() {
_timezone_file="/etc/timezone"
_timezone="Etc/UTC"
[ -f "$_timezone_file" ] || FATAL "Timezone file '$_timezone_file' not found"
_current_timezone=$(cat $_timezone_file)
[ "$_current_timezone" = "$_timezone" ] || FATAL "Timezone is not '$_timezone' but '$_current_timezone'"
}
# Assert user
assert_user() {
id "$USER" > /dev/null 2>&1 || FATAL "User '$USER' does not exists"
}
# Home directory of user
user_home_dir() {
_home_dir=
case $USER in
root) _home_dir="/root" ;;
*) _home_dir="/home/$USER" ;;
esac
printf '%s\n' "$_home_dir"
}
# Create uninstall
create_uninstall() {
_uninstall_script_file="/usr/local/bin/recluster.uninstall.sh"
INFO "Creating uninstall script '$_uninstall_script_file'"
$SUDO tee "$_uninstall_script_file" > /dev/null << EOF
#!/usr/bin/env sh
[ \$(id -u) -eq 0 ] || exec sudo \$0 \$@
if command -v rc-service; then
rc-service k3s-recluster stop
rc-service node_exporter stop
rc-service recluster.server stop
rc-service postgresql stop
rc-service recluster stop
fi
if command -v systemctl; then
systemctl stop k3s-recluster.service
systemctl stop node_exporter.service
systemctl stop recluster.server.service
systemctl stop postgresql.service
systemctl stop recluster.service
fi
[ -x '/usr/local/bin/k3s-recluster-uninstall.sh' ] && /usr/local/bin/k3s-recluster-uninstall.sh
[ -x '/usr/local/bin/node_exporter.uninstall.sh' ] && /usr/local/bin/node_exporter.uninstall.sh
if command -v systemctl; then
systemctl disable recluster.server.service
systemctl disable recluster.service
systemctl reset-failed recluster.server.service
systemctl reset-failed recluster.service
systemctl daemon-reload
fi
if command -v rc-update; then
rc-update delete recluster.server default
rc-update delete recluster default
fi
rm -f /etc/systemd/system/recluster.server.service
rm -f /etc/init.d/recluster.server
rm -f /var/log/recluster.server.log
rm -f /etc/systemd/system/recluster.service
rm -f /etc/init.d/recluster
rm -f /var/log/recluster.log
# Certificates
rm -f /usr/local/share/ca-certificates/registry.crt
rm -f /usr/local/share/ca-certificates/registry.key
update-ca-certificates
rm -rf "$RECLUSTER_ETC_DIR"
rm -rf "$RECLUSTER_OPT_DIR"
remove_uninstall() {
rm -f "$_uninstall_script_file"
}
trap remove_uninstall EXIT
EOF
$SUDO chown root:root "$_uninstall_script_file"
$SUDO chmod 754 "$_uninstall_script_file"
}
# Setup SSH
setup_ssh() {
_ssh_config_file="/etc/ssh/ssh_config"
_ssh_config_dir=$(dirname "$_ssh_config_file")
_sshd_config_file="/etc/ssh/sshd_config"
_sshd_config_dir=$(dirname "$_sshd_config_file")
_ssh_authorized_keys_file="$(user_home_dir)/.ssh/authorized_keys"
_ssh_authorized_keys_dir=$(dirname "$_ssh_authorized_keys_file")
spinner_start "Setting up SSH"
# SSH configuration
INFO "Copying SSH configuration file from '$SSH_CONFIG_FILE' to '$_ssh_config_file'"
[ -d "$_ssh_config_dir" ] || {
WARN "Creating SSH configuration directory '$_ssh_config_dir'"
$SUDO mkdir -p "$_ssh_config_dir"
$SUDO chown root:root "$_ssh_config_dir"
$SUDO chmod 755 "$_ssh_config_dir"
}
yes | $SUDO cp --force "$SSH_CONFIG_FILE" "$_ssh_config_file"
$SUDO chown root:root "$_ssh_config_file"
$SUDO chmod 644 "$_ssh_config_file"
# SSH server configuration
INFO "Copying SSH server configuration file from '$SSHD_CONFIG_FILE' to '$_sshd_config_file'"
[ -d "$_sshd_config_dir" ] || {
WARN "Creating SSH server configuration directory '$_sshd_config_dir'"
$SUDO mkdir -p "$_sshd_config_dir"
$SUDO chown root:root "$_sshd_config_dir"
$SUDO chmod 755 "$_sshd_config_dir"
}
yes | $SUDO cp --force "$SSHD_CONFIG_FILE" "$_sshd_config_file"
$SUDO chown root:root "$_sshd_config_file"
$SUDO chmod 644 "$_sshd_config_file"
# SSH authorized keys
[ -d "$_ssh_authorized_keys_dir" ] || {
WARN "Creating SSH authorized keys directory '$_ssh_authorized_keys_dir'"
$SUDO mkdir -p "$_ssh_authorized_keys_dir"
$SUDO chown "$USER:$USER" "$_ssh_authorized_keys_dir"
$SUDO chmod 700 "$_ssh_authorized_keys_dir"
}
while read -r _ssh_authorized_key; do
INFO "Copying SSH authorized key '$_ssh_authorized_key' to SSH authorized keys '$_ssh_authorized_keys_file'"
printf "%s\n" "$_ssh_authorized_key" | $SUDO tee -a "$_ssh_authorized_keys_file" > /dev/null || FATAL "Error copying SSH authorized key '$_ssh_authorized_key' to SSH authorized keys '$_ssh_authorized_keys_file'"
done << EOF
$(cat "$SSH_AUTHORIZED_KEYS_FILE")
EOF
$SUDO chown "$USER:$USER" "$_ssh_authorized_keys_file"
$SUDO chmod 644 "$_ssh_authorized_keys_file"
# Restart SSH service
case $INIT_SYSTEM in
openrc)
INFO "openrc: Restarting SSH"
$SUDO rc-service sshd restart
;;
systemd)
INFO "systemd: Restarting SSH"
$SUDO systemctl restart ssh
;;
*) FATAL "Unknown init system '$INIT_SYSTEM'" ;;
esac
spinner_stop
}
# Setup certificates
setup_certificates() {
_certs_dir="$RECLUSTER_ETC_DIR/certs"
_ssh_crt_src="$DIRNAME/configs/certs/ssh.crt"
_ssh_crt_dst="$_certs_dir/ssh.crt"
_ssh_key_src="$DIRNAME/configs/certs/ssh.key"
_ssh_key_dst="$_certs_dir/ssh.key"
_token_crt_src="$DIRNAME/configs/certs/token.crt"
_token_crt_dst="$_certs_dir/token.crt"
_token_key_src="$DIRNAME/configs/certs/token.key"
_token_key_dst="$_certs_dir/token.key"
_registry_crt_src="$DIRNAME/configs/certs/registry.crt"
_registry_crt_dst="/usr/local/share/ca-certificates/registry.crt"
_registry_key_src="$DIRNAME/configs/certs/registry.key"
_registry_key_dst="/usr/local/share/ca-certificates/registry.key"
spinner_start "Setting up certificates"
[ -f "$_ssh_crt_src" ] || FATAL "SSH certificate file '$_ssh_crt_src' does not exists"
[ -f "$_ssh_key_src" ] || FATAL "SSH certificate file '$_ssh_key_src' does not exists"
[ -f "$_token_crt_src" ] || FATAL "Token certificate file '$_token_crt_src' does not exists"
[ -f "$_token_key_src" ] || FATAL "Token certificate file '$_token_key_src' does not exists"
[ -f "$_registry_crt_src" ] || FATAL "Registry certificate file '$_registry_crt_src' does not exists"
[ -f "$_registry_key_src" ] || FATAL "Registry certificate file '$_registry_key_src' does not exists"
DEBUG "Creating reCluster certificates directory '$_certs_dir'"
$SUDO rm -rf "$_certs_dir"
$SUDO mkdir "$_certs_dir"
DEBUG "Copying SSH certificate file '$_ssh_crt_src' to '$_ssh_crt_dst'"
yes | $SUDO cp --force "$_ssh_crt_src" "$_ssh_crt_dst"
DEBUG "Copying SSH certificate file '$_ssh_key_src' to '$_ssh_key_dst'"
yes | $SUDO cp --force "$_ssh_key_src" "$_ssh_key_dst"
DEBUG "Copying Token certificate file '$_token_crt_src' to '$_token_crt_dst'"
yes | $SUDO cp --force "$_token_crt_src" "$_token_crt_dst"
DEBUG "Copying Token certificate file '$_token_key_src' to '$_token_key_dst'"
yes | $SUDO cp --force "$_token_key_src" "$_token_key_dst"
DEBUG "Copying Registry certificate file '$_registry_crt_src' to '$_registry_crt_dst'"
yes | $SUDO cp --force "$_registry_crt_src" "$_registry_crt_dst"
DEBUG "Copying Registry certificate file '$_registry_key_src' to '$_registry_key_dst'"
yes | $SUDO cp --force "$_registry_key_src" "$_registry_key_dst"
INFO "Updating reCluster certificates directory '$_certs_dir' permissions"
$SUDO chown --recursive root:root "$_certs_dir"
$SUDO chmod --recursive 600 "$_certs_dir"
INFO "Updating CA certificates"
$SUDO update-ca-certificates
spinner_stop
}
# Read interfaces
read_interfaces() {
ip -details -json link show \
| jq \
'
map(if .linkinfo.info_kind // .link_type == "loopback" then empty else . end)
| map(.name = .ifname)
| map({address, name})
'
}
# Read power consumption
# @param $1 Benchmark PID
read_power_consumption() {
_read_power_consumption() {
download_print "$PC_DEVICE_API" | jq --raw-output '.StatusSNS.ENERGY.Power'
}
_pid=$1
_pcs='[]'
# Standard deviation max tolerance inclusive
_standard_deviation_tolerance=5
# Warmup
sleep "$PC_WARMUP"
# Execute
_end=$(date -ud "$PC_TIME second" +%s)
while [ "$(date -u +%s)" -le "$_end" ]; do
# Current power consumption
_pc=$(_read_power_consumption)
DEBUG "Reading power consumption: ${_pc}W"
# Add current power consumption to list
_pcs=$(printf '%s\n' "$_pcs" | jq --arg pc "$_pc" '. |= . + [$pc | tonumber]')
# Sleep
sleep "$PC_INTERVAL"
done
# Terminate benchmark process
if [ -n "$_pid" ]; then
DEBUG "Terminating benchmark process PID $_pid"
kill -s KILL "$_pid"
# Wait may fail
wait "$_pid" || :
fi
# Check pcs
[ "$(printf '%s\n' "$_pcs" | jq --raw-output 'length')" -ge 2 ] || FATAL "Power consumption readings not enough data"
[ "$(printf '%s\n' "$_pcs" | jq --raw-output 'add')" -ge 1 ] || FATAL "Power consumption readings are below 1W"
# Calculate mean
_mean=$(
printf '%s\n' "$_pcs" \
| jq \
--raw-output \
'
add / length
| . + 0.5
| floor
'
)
[ "$_mean" -ge 1 ] || FATAL "Power consumption mean is below 1W"
DEBUG "Power consumption mean: $_mean"
# Calculate standard deviation
_standard_deviation=$(
printf '%s\n' "$_pcs" \
| jq \
--raw-output \
'
(add / length) as $mean
| (map(. - $mean | . * .) | add) / (length - 1)
| sqrt
'
)
[ "$(printf '%s <= %s' "${_standard_deviation#-}" "$_standard_deviation_tolerance" | bc)" -eq 1 ] || FATAL "Power consumption standard deviation $_standard_deviation exceeds tolerance $_standard_deviation_tolerance"
DEBUG "Power consumption standard deviation: $_standard_deviation"
# Return
RETVAL=$(
jq \
--null-input \
--arg mean "$_mean" \
--arg standard_deviation "$_standard_deviation" \
'{
"mean": $mean,
"standardDeviation": $standard_deviation
}'
)
}
# Decode JWT token
# @param $1 JWT token
decode_token() {
_decode_token() {
printf '%s\n' "$1" | jq --raw-input --arg idx "$2" 'gsub("-";"+") | gsub("_";"/") | split(".") | .[$idx|tonumber] | @base64d | fromjson'
}
_token=$1
DEBUG "Decoding JWT token '$_token'"
# Token header
_token_header=$(_decode_token "$_token" 0)
# Token payload
_token_payload=$(_decode_token "$_token" 1)
# Return
RETVAL=$(
jq \
--null-input \
--argjson header "$_token_header" \
--argjson payload "$_token_payload" \
'
{
"header": $header,
"payload": $payload
}
'
)
}
# Send server request
# @param $1 Request data
# @param $2 Server URL
send_server_request() {
_req_data=$1
_res_data=
if [ -n "$2" ]; then
_server_url=$2
else
_server_url="$(printf '%s\n' "$CONFIG" | jq --exit-status --raw-output '.recluster.server')/graphql"
fi
# Send request
DEBUG "Sending server request data to '$_server_url':" "$_req_data"
case $DOWNLOADER in
curl)
_res_data=$(
curl --fail --silent --location --show-error \
--request POST \
--header 'Content-Type: application/json' \
--data "$_req_data" \
--url "$_server_url"
) || FATAL "Error sending server request to '$_server_url'"
;;
wget)
_res_data=$(
wget --quiet --output-document=- \
--header='Content-Type: application/json' \
--post-data="$_req_data" \
"$_server_url" 2>&1
) || FATAL "Error sending server request to '$_server_url'"
;;
*) FATAL "Unknown downloader '$DOWNLOADER'" ;;
esac
DEBUG "Received server response data from '$_server_url':" "$_res_data"
# Check error response
if printf '%s\n' "$_res_data" | jq --exit-status 'has("errors")' > /dev/null 2>&1; then
FATAL "Server '$_server_url' response data error:" "$_res_data"
fi
# Return
RETVAL=$_res_data
}
# Create server user
# @param $1 Username
# @param $2 Password
create_server_user() {
_username=$1
_password=$2
_user_data=$(
jq \
--null-input \
--compact-output \
--arg username "$_username" \
--arg password "$_password" \
'
{
"username": $username,
"password": $password
}
'
)
_user_req_data=$(
jq \
--null-input \
--compact-output \
--argjson data "$_user_data" \
'
{
"query": "mutation ($data: CreateUserInput!) { createUser(data: $data) { id } }",
"variables": { "data": $data }
}
'
)
_user_res_data=
# Send request
INFO "Creating user '$_username'"
send_server_request "$_user_req_data"
_user_res_data="$(printf '%s\n' "$RETVAL" | jq '.data.createUser')"
# Return
RETVAL=$_user_res_data
}
# Sign in server user
# @param $1 Username
# @param $2 Password
sign_in_server_user() {
_username=$1
_password=$2
_sign_in_req_data=$(
jq \
--null-input \
--compact-output \
--arg username "$_username" \
--arg password "$_password" \
'
{
"query": "mutation ($username: NonEmptyString!, $password: NonEmptyString!) { signIn(username: $username, password: $password) }",
"variables": { "username": $username, "password": $password }
}
'
)
_sign_in_res_data=
# Send request
INFO "Signing in user '$_username'"
send_server_request "$_sign_in_req_data"
_sign_in_res_data=$RETVAL
# Extract token
_token=$(printf '%s\n' "$_sign_in_res_data" | jq --raw-output '.data.signIn')
# Decode token
decode_token "$_token"
_token_decoded=$RETVAL
# Success
INFO "Successfully signed in user '$_username'"
# Return
RETVAL=$(
jq \
--null-input \
--arg token "$_token" \
--argjson decoded "$_token_decoded" \
'
{
"token": $token,
"decoded": $decoded
}
'
)
}
# Read CPU information
read_cpu_info() {
_cpu_info=$(
lscpu --json \
| jq \
'
.lscpu
| map({(.field): .data})
| add
| with_entries(if .key | endswith(":") then .key |= sub(":";"") else . end)
| .Flags /= " "
| .vulnerabilities = (to_entries | map(.key | select(startswith("Vulnerability "))[14:]))
| with_entries(select(.key | startswith("Vulnerability ") | not))
| . + {"architecture": .Architecture}
| . + {"flags": .Flags}
| . + {"cores": (."CPU(s)" | tonumber)}
| . + {"vendor": ."Vendor ID"}
| . + {"family": (."CPU family" | tonumber)}
| . + {"model": (.Model | tonumber)}
| . + {"name": ."Model name"}
| . + {"cacheL1d": (."L1d cache" | split(" ") | .[0] + " " + .[1])}
| . + {"cacheL1i": (."L1i cache" | split(" ") | .[0] + " " + .[1])}
| . + {"cacheL2": (."L2 cache" | split(" ") | .[0] + " " + .[1])}
| . + {"cacheL3": (."L3 cache" | split(" ") | .[0] + " " + .[1])}
| {architecture, flags, cores, vendor, family, model, name, vulnerabilities, cacheL1d, cacheL1i, cacheL2, cacheL3}
'
)
# Convert architecture
_architecture=$(printf '%s\n' "$_cpu_info" | jq --raw-output '.architecture')
case $_architecture in
x86_64) _architecture=amd64 ;;
aarch64) _architecture=arm64 ;;
*) FATAL "CPU architecture '$_architecture' is not supported" ;;
esac
[ "$_architecture" = "$ARCH" ] || FATAL "CPU architecture '$_architecture' does not match architecture '$ARCH'"
# Convert vendor
_vendor=$(printf '%s\n' "$_cpu_info" | jq --raw-output '.vendor')
case $_vendor in
AuthenticAMD) _vendor=amd ;;
GenuineIntel) _vendor=intel ;;
*) FATAL "CPU vendor '$_vendor' not supported" ;;
esac
# Convert cache to bytes
_cache_l1d=$(printf '%s\n' "$_cpu_info" | jq --raw-output '.cacheL1d' | sed -e 's/B.*//' -e 's/[[:space:]]*//g' | numfmt --from=iec-i)
_cache_l1i=$(printf '%s\n' "$_cpu_info" | jq --raw-output '.cacheL1i' | sed -e 's/B.*//' -e 's/[[:space:]]*//g' | numfmt --from=iec-i)
_cache_l2=$(printf '%s\n' "$_cpu_info" | jq --raw-output '.cacheL2' | sed -e 's/B.*//' -e 's/[[:space:]]*//g' | numfmt --from=iec-i)
_cache_l3=$(printf '%s\n' "$_cpu_info" | jq --raw-output '.cacheL3' | sed -e 's/B.*//' -e 's/[[:space:]]*//g' | numfmt --from=iec-i)
# Update
_cpu_info=$(
printf '%s\n' "$_cpu_info" \
| jq \
--arg architecture "$_architecture" \
--arg vendor "$_vendor" \
--arg cachel1d "$_cache_l1d" \
--arg cachel1i "$_cache_l1i" \
--arg cachel2 "$_cache_l2" \
--arg cachel3 "$_cache_l3" \
'
.architecture = ($architecture | ascii_upcase)
| .vendor = ($vendor | ascii_upcase)
| .cacheL1d = ($cachel1d | tonumber)
| .cacheL1i = ($cachel1i | tonumber)
| .cacheL2 = ($cachel2 | tonumber)
| .cacheL3 = ($cachel3 | tonumber)
'
)
# Return
RETVAL=$_cpu_info
}
# Read memory information
read_memory_info() {
_memory_info=$(
grep MemTotal /proc/meminfo \
| sed -e 's/MemTotal://g' -e 's/[[:space:]]*//g' -e 's/B.*//' \
| tr '[:lower:]' '[:upper:]' \
| numfmt --from iec
)
# Return
RETVAL=$_memory_info
}
# Read storage(s) information
read_storages_info() {
_storages_info=$(
lsblk --bytes --json \
| jq \
'
.blockdevices
| map(select((.type == "disk") and (.rm == false)))
| map({name, size})
'
)
# Return
RETVAL=$_storages_info
}
# Read interface(s) information
read_interfaces_info() {
_interfaces_info=$(read_interfaces)
# Cycle interfaces to obtain additional information
while read -r _interface; do
# Name
_iname=$(printf '%s\n' "$_interface" | jq --raw-output '.name')
# Speed
_speed=
# WoL
_wol=""
if [ ! -d "/sys/class/net/$_iname/wireless" ]; then
# Wired interface
_speed=$($SUDO ethtool "$_iname" | grep 'Speed' | sed -e 's/Speed://g' -e 's/[[:space:]]*//g' -e 's/b.*//' | numfmt --from=si)
_wol=$($SUDO ethtool "$_iname" | grep 'Supports Wake-on' | sed -e 's/Supports Wake-on://g' -e 's/[[:space:]]*//g')
else
# Wireless interface
_speed_tx=$($SUDO iwctl station "$_iname" show | grep 'TxBitrate' | sed -e 's/TxBitrate//g' -e 's/[[:space:]]*//g' -e 's/b.*//' | numfmt --from=si)
_speed_rx=$($SUDO iwctl station "$_iname" show | grep 'RxBitrate' | sed -e 's/RxBitrate//g' -e 's/[[:space:]]*//g' -e 's/b.*//' | numfmt --from=si)
_speed=$((_speed = _speed_tx + _speed_rx))
_speed=$((_speed = _speed / 2))
fi
# Update interfaces
_interfaces_info=$(
printf '%s\n' "$_interfaces_info" \
| jq \
--arg iname "$_iname" \
--arg speed "$_speed" \
--arg wol "$_wol" \
'map(if .name == $iname then . + {"speed": $speed | tonumber, "wol": ($wol | split(""))} else . end)'
)
done << EOF
$(printf '%s\n' "$_interfaces_info" | jq --compact-output '.[]')
EOF
# Return
RETVAL=$_interfaces_info
}
# Execute CPU benchmark
run_cpu_bench() {
_run_cpu_bench() {
sysbench --time="$BENCH_TIME" --threads="$1" cpu run \
| grep 'events per second' \
| sed -e 's/events per second://g' -e 's/[[:space:]]*//g' \
| xargs printf "%.0f"
}
_threads=$(grep -c ^processor /proc/cpuinfo)
# Single-thread
DEBUG "Running CPU benchmark in single-thread (1)"
_single_thread=$(_run_cpu_bench 1)
DEBUG "CPU benchmark in single-thread (1): $_single_thread"
# Multi-thread
DEBUG "Running CPU benchmark in multi-thread ($_threads)"
_multi_thread=$(_run_cpu_bench "$_threads")
DEBUG "CPU benchmark in multi-thread ($_threads): $_multi_thread"
# Return
RETVAL=$(
jq \
--null-input \
--argjson singleThread "$_single_thread" \
--argjson multiThread "$_multi_thread" \
'
{
"singleThread": $singleThread,
"multiThread": $multiThread
}
'
)
}
# Execute memory benchmark
run_memory_bench() {
_run_memory_bench() {
_memory_output=$(sysbench --time="$BENCH_TIME" --memory-oper="$1" --memory-access-mode="$2" memory run \
| grep 'transferred' \
| sed -e 's/.*(\(.*\))/\1/' -e 's/B.*//' -e 's/[[:space:]]*//g' \
| numfmt --from=iec-i)
printf '%s\n' $((_memory_output * 8))
}
# Read sequential
DEBUG "Running memory benchmark in read sequential"
_read_seq=$(_run_memory_bench read seq)
DEBUG "Memory benchmark in read sequential: $_read_seq"
# Read random
DEBUG "Running memory benchmark in read random"
_read_rand=$(_run_memory_bench read rnd)
DEBUG "Memory benchmark in read random: $_read_rand"
# Write sequential
DEBUG "Running memory benchmark in write sequential"
_write_seq=$(_run_memory_bench write seq)
DEBUG "Memory benchmark in write sequential: $_write_seq"
# Write random
DEBUG "Running memory benchmark in write random"
_write_rand=$(_run_memory_bench write rnd)
DEBUG "Memory benchmark in write random: $_write_rand"
# Return
RETVAL=$(
jq \
--null-input \
--arg readSeq "$_read_seq" \
--arg readRand "$_read_rand" \
--arg writeSeq "$_write_seq" \
--arg writeRand "$_write_rand" \
'
{
"read": {
"sequential": ($readSeq | tonumber),
"random": ($readRand | tonumber)
},
"write": {
"sequential": ($writeSeq | tonumber),
"random": ($writeRand | tonumber)
}
}
'
)
}
# Execute storage(s) benchmark
run_storages_bench() {
_run_storages_bench() {
# Io operation
_io_opt=
case $1 in
read) _io_opt=$1 ;;
write)
_io_opt=written
# Prepare write benchmark
sysbench fileio cleanup > /dev/null
sysbench fileio prepare > /dev/null
;;