-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget-env
executable file
·1449 lines (1318 loc) · 56.2 KB
/
get-env
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
PROJECT_NAME=MLAppDeploy
K3S_CHANNEL=v1.21
SECRET='MLAPPDEPLOY-SECRET'
REGISTRY_PORT=25000
if [ "$0" == "bash" ]
then
CMD="curl -sfL https://onetop21.github.io/MLAppDeploy/get-env | bash -s -"
else
CMD="bash $0"
fi
function ColorEcho {
COLOR="\033[0m"
if [[ "$1" == "ERROR" ]]; then
COLOR="\033[0;31m"
shift;
elif [[ "$1" == "WARN" ]]; then
COLOR="\033[0;33m"
shift;
elif [[ "$1" == "INFO" ]]; then
COLOR="\033[0;32m"
shift;
elif [[ "$1" == "DEBUG" ]]; then
COLOR="\033[0;34m"
shift;
fi
echo -e "$COLOR$@\033[0m"
}
# Base Functions
function Prompt {
local MESSAGE
local DEFAULT
local PASSWORD
local REGEX
local HIDDENDEF
for ARG in "$@"; do
local IDX=$((IDX+1))
if [[ $ARG =~ ^([a-z]+:)*(.*)$ ]]; then
case ${BASH_REMATCH[1]} in
message:) MESSAGE=${BASH_REMATCH[2]};;
default:) DEFAULT=${BASH_REMATCH[2]};;
password:) PASSWORD=${BASH_REMATCH[2]};;
regex:) REGEX=${BASH_REMATCH[2]};;
*)
case $IDX in
1) MESSAGE=$ARG;;
2) DEFAULT=$ARG;;
esac
;;
esac
fi
done
if [ ${DEFAULT:0:1} == "@" ]
then
DEFAULT=${DEFAULT:1}
HIDDENDEF=1
fi
while [[ ! "$RESULT" =~ $REGEX ]]
do
read -p "$MESSAGE$([ ! $HIDDENDEF ] && [ $DEFAULT ] && echo " [$DEFAULT]"): " $([ $PASSWORD ] && echo -s) -e RESULT
[ -z $RESULT ] && RESULT=$DEFAULT
done
echo ${RESULT,,}
}
function PrintStep {
STEP=$((STEP+1))
ColorEcho INFO "[$STEP/$MAX_STEP] $@"
}
function GetPrivileged {
ColorEcho WARN "Request sudo privileged."
sudo ls >> /dev/null 2>&1
if [[ ! "$?" == "0" ]]; then
exit 1
fi
}
function IsInstalled {
which $1 >> /dev/null 2>&1
}
function IsInstalledAptPkg {
[ $(apt list --installed -a $1 2>&1 | grep installed | wc -l) -eq 0 ] && return 1
return 0
}
function IsInstalledPipPkg {
[ $(pip freeze | grep -E ^$1== 2>&1 | wc -l) -eq 0 ] && return 1
return 0
}
function IsWSL2 {
[ $(uname -r | grep microsoft-standard | wc -l) -eq 0 ] && return 1
return 0
}
function HostIP {
if IsWSL2
then
PS='(Get-NetIPConfiguration | Where-Object {
$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.Status -ne "Disconnected"
}).IPv4Address.IPAddress'
IP=$(powershell.exe -c $PS)
echo "${IP%%[[:cntrl:]]}"
else
hostname -I | awk '{print $1}'
fi
}
function RequiresFromApt {
[ ! $SILENT ] && printf "Check requires [$1]... "
if IsInstalledAptPkg $1 || IsInstalled ${2:-$1}
then
[ ! $SILENT ] && ColorEcho DEBUG OK || :
else
[ ! $SILENT ] && ColorEcho WARN Install $1.
sudo apt install -y $1
fi
}
function RequiresFromPip {
[ ! $SILENT ] && printf "Check requires [$1]... "
if IsInstalledPipPkg $1 || IsInstalled ${2:-$1}
then
[ ! $SILENT ] && ColorEcho DEBUG OK || :
else
[ ! $SILENT ] && ColorEcho WARN Install ${2:-$1}.
pip3 install ${2:-$1}
fi
}
function UninstallOnSnapWithWarning {
if IsInstalled snap
then
if [[ $(snap list $1 >> /dev/null 2>&1 ; echo $?) == '0' ]]; then
ColorEcho WARN "Need to remove $1 from Snapcraft."
read -n1 -r -p "If you want to stop installation, Press CTRL+C to break, otherwise any key to continue."
sudo snap remove --purge $1
fi
fi
}
function InstallDocker {
if ! VerifyDocker
then
printf "Install Docker... "
#UninstallOnSnapWithWarning docker
if ! IsInstalled docker
then
# below script from https://docs.docker.com/engine/install/ubuntu/
# Uninstall old version
sudo apt-get remove -y docker docker-engine docker.io containerd runc
# Update package manager
sudo apt-get update
# Install package to use repository over HTTPS
sudo apt-get install -y \
apt-transport-https \
ca-certificates \
curl \
gnupg-agent \
software-properties-common
# Add official GPG key
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
# Verify fingerprint
sudo apt-key fingerprint 0EBFCD88
# Add docker repository
sudo add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) \
stable" -y
# Update added docker repository
sudo apt-get update
# Install docker community version (latest)
sudo apt-get install -y docker-ce docker-ce-cli containerd.io
# Add user to docker group
sudo adduser $USER docker
fi
if ! VerifyDocker
then
ColorEcho WARN "Failed to operate docker."
sudo systemctl status docker.service
exit 1
fi
ColorEcho DEBUG Succeeded
fi
}
function RemoveDocker {
# Clean : https://docs.docker.com/engine/install/ubuntu/#uninstall-docker-engine
sudo apt-get purge docker-ce docker-ce-cli containerd.io -y
sudo rm -rf /var/lib/docker
}
function VerifyDocker {
sudo docker run -i --rm $@ hello-world >> /dev/null 2>&1
}
function InstallNVIDIAContainerRuntime {
# https://github.com/NVIDIA/nvidia-container-runtime
# Add the package repositories
curl -s -L https://nvidia.github.io/nvidia-container-runtime/gpgkey | \
sudo apt-key add -
distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
curl -s -L https://nvidia.github.io/nvidia-container-runtime/$distribution/nvidia-container-runtime.list | \
sudo tee /etc/apt/sources.list.d/nvidia-container-runtime.list
sudo apt-get update
# Install nvidia-container-runtime
sudo apt-get install -y nvidia-container-runtime
}
function NVIDIAContainerRuntimeConfiguration {
sudo mkdir -p /etc/docker
# # Read Daemon.json
# CONFIG=`sudo cat /etc/docker/daemon.json`
# # Check nvidia runtime in daemon.json
# if [ "$(echo $CONFIG | jq '.runtimes.nvidia')" == "null" ];
# then
# CONFIG=`echo $CONFIG | jq '.runtimes.nvidia={"path":"nvidia-container-runtime", "runtimeArgs":[]}'`
# fi
# #echo $CONFIG | jq . | sudo dd status=none of=/etc/docker/daemon.json
# echo $CONFIG | jq . | sudo sponge /etc/docker/daemon.json
! sudo test -f /etc/docker/daemon.json && echo {} | sudo sponge /etc/docker/daemon.json
if [ ! $(sudo cat /etc/docker/daemon.json | jq '.runtimes.nvidia // empty' >> /dev/null 2>&1) ]
then
sudo cat /etc/docker/daemon.json | jq '.runtimes.nvidia={"path":"nvidia-container-runtime", "runtimeArgs":[]} | ."default-runtime"="nvidia"' | sudo sponge /etc/docker/daemon.json
fi
}
function GetContainerdNVIDIATemplateFile {
#sudo wget https://raw.githubusercontent.com/baidu/ote-stack/master/deployments/k3s/config.toml.tmpl -O /var/lib/rancher/k3s/agent/etc/containerd/config.toml.tmpl
sudo mkdir -p /var/lib/rancher/k3s/agent/etc/containerd
if [ -f assets/nvidia-containerd.config.toml.tmpl ]
then
sudo cp assets/nvidia-containerd.config.toml.tmpl /var/lib/rancher/k3s/agent/etc/containerd/config.toml.tmpl
else
sudo wget https://onetop21.github.io/MLAppDeploy/assets/nvidia-containerd.config.toml.tmpl -O /var/lib/rancher/k3s/agent/etc/containerd/config.toml.tmpl
#sudo wget https://raw.githubusercontent.com/onetop21/MLAppDeploy/master/scripts/nvidia-containerd.config.toml.tmpl -O /var/lib/rancher/k3s/agent/etc/containerd/config.toml.tmpl
fi
}
function IsInstalledCluster {
HOST=$(HostIP)
if $(kubectl get node >> /dev/null 2>&1)
then
for IP in $(kubectl get node -o jsonpath="{range .items[*].status}{.addresses[?(.type=='InternalIP')].address}{end}")
do
if [ $IP == $HOST ]
then
return 0
fi
done
fi
return 1
}
function IsDeployed {
local KIND=${1:-pod}; shift
local COUNT=0
for LABEL in $@
do
COUNT=$((COUNT+$(kubectl get -A $KIND -l $LABEL -o name | wc -l)))
done
[ "$COUNT" -eq 0 ] && return 1
return 0
}
function HasHelmRepo {
VALUE=$1
COUNT_NAME=$(helm repo list -o json | jq .[].name -r | grep -e ^${VALUE}$ | wc -l)
COUNT_REPO=$(helm repo list -o json | jq .[].url -r | grep -e ^${VALUE}$ | wc -l)
COUNT=$((COUNT_NAME+COUNT_REPO))
[ $COUNT -ne 0 ] && return 0 || return 1
}
# JWT
#
# JWT Encoder Bash Script
#
# Static header fields.
JWT_HEADER='{
"typ": "JWT",
"alg": "HS256",
"kid": "0001",
"iss": "Bash JWT Generator"
}'
Base64Encode()
{
declare input=${1:-$(</dev/stdin)}
# Use `tr` to URL encode the output from base64.
printf '%s' "${input}" | base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n'
}
Base64Decode()
{
declare input=${1:-$(</dev/stdin)}
# A standard base64 string should always be `n % 4 == 0`. We made the base64
# string URL safe when we created the JWT, which meant removing the `=`
# signs that are there for padding. Now we must add them back to get the
# proper length.
remainder=$((${#input} % 4));
if [ $remainder -eq 1 ];
then
>2& echo "fatal error. base64 string is unexepcted length"
elif [[ $remainder -eq 2 || $remainder -eq 3 ]];
then
input="${input}$(for i in `seq $((4 - $remainder))`; do printf =; done)"
fi
printf '%s' "${input}" | base64 --decode
}
ToJSON() {
declare input=${1:-$(</dev/stdin)}
printf '%s' "${input}" | jq -c .
}
HMACSHA256Encode()
{
declare input=${1:-$(</dev/stdin)}
printf '%s' "${input}" | openssl dgst -binary -sha256 -hmac "${SECRET}"
}
VerifySignature()
{
declare header_and_payload=${1}
expected=$(echo "${header_and_payload}" | HMACSHA256Encode | Base64Encode)
actual=${2}
if [ "${expected}" = "${actual}" ]
then
return 0
else
return 1
fi
}
VerifyExpired()
{
exp=$(echo "${1}" | Base64Decode | jq .exp)
cur=$(date +%s)
if [ $cur -le $exp ]
then
return 0
else
return 1
fi
}
GenerateToken()
{
# Use jq to set the dynamic `iat` and `exp`
# fields on the header using the current time.
# `iat` is set to now, and `exp` is now + 180 seconds(3mins).
header=$(
echo "${JWT_HEADER}" | jq --arg time_str "$(date +%s)" \
'
($time_str | tonumber) as $time_num
| .iat=$time_num
| .exp=($time_num + 180)
'
)
CONTAINER_RUNTIME_VERSION=$(kubectl get node -o yaml | yq ".items[] | select(.metadata.name == \"$HOSTNAME\") | .status.nodeInfo.containerRuntimeVersion" -r)
CONTAINER_RUNTIME=${CONTAINER_RUNTIME_VERSION%://*}
RUNTIME_VERSION=${CONTAINER_RUNTIME_VERSION#*://}
payload="{
\"url\": \"$(HostIP)\",
\"token\": \"$(sudo cat /var/lib/rancher/k3s/server/node-token)\"
}"
# Encode
header_base64=$(echo "${header}" | ToJSON | Base64Encode)
payload_base64=$(echo "${payload}" | ToJSON | Base64Encode)
header_payload=$(echo "${header_base64}.${payload_base64}")
signature=$(echo "${header_payload}" | HMACSHA256Encode | Base64Encode)
if [[ "$CONTAINER_RUNTIME" == "docker" ]]
then
echo "${header_payload}.${signature}" --docker
else
echo "${header_payload}.${signature}"
fi
}
ParseToken()
{
# Read the token from stdin
declare token=${1:-$(</dev/stdin)};
IFS='.' read -ra pieces <<< "$token"
declare header=${pieces[0]}
declare payload=${pieces[1]}
declare signature=${pieces[2]}
if VerifySignature "${header}.${payload}" "${signature}"
then
if VerifyExpired "${header}"
then
#echo "Header"
#echo "${header}" | base64_decode | jq
#echo "Payload"
#echo "${payload}" | base64_decode | jq
echo "${payload}" | Base64Decode
else
echo {}
fi
else
echo {}
fi
}
# Usage/Help
function UsageHeader {
ColorEcho INFO "MLAppDeploy Environment Installer (based k3s)"
if [ $1 ]; then
ColorEcho WARN "Usage"
ColorEcho " $ $CMD $1 [ARGS...]"
fi
}
function MainUsage {
UsageHeader
ColorEcho WARN "Commands"
ColorEcho " install : Install lightweight kubernetes(k3s) for MLAppDeploy."
ColorEcho " join-token : Get token to join."
ColorEcho " uninstall : Uninstall k3s."
ColorEcho " registry : Install docker registry v2 (master node only)."
ColorEcho " docker : Install docker community edition with gpu container runtime."
ColorEcho " datastore : Install minio(s3 compatible)/mongodb server."
ColorEcho " cli : Install MLAD Command-Line Interface."
ColorEcho " status : Show MLAppDeploy environment status."
ColorEcho " help : Print help message."
exit 1
}
function InstallUsage {
UsageHeader install
ColorEcho WARN "Arguments"
ColorEcho " -t, --join-token=[TOKEN] : Token to join as a worker node."
ColorEcho " --docker : Use docker runtime (default: containerd)."
ColorEcho " -h, --help : This page"
exit 1
}
function JoinTokenUsage {
UsageHeader join-token
ColorEcho WARN "Arguments"
ColorEcho " -h, --help : This page"
exit 1
}
function UninstallUsage {
UsageHeader uninstall
ColorEcho WARN "Arguments"
ColorEcho " -h, --help : This page"
exit 1
}
function DeployUsage {
UsageHeader deploy
ColorEcho WARN "Arguments"
ColorEcho " -h, --help : This page"
exit 1
}
function DockerUsage {
UsageHeader docker
ColorEcho WARN "Arguments"
ColorEcho " -h, --help : This page"
exit 1
}
function RegistryUsage {
UsageHeader registry
ColorEcho WARN "Arguments"
#ColorEcho " -p, --port : Port number of private docker registry."
ColorEcho " -h, --help : This page"
exit 1
}
function DatastoreUsage {
UsageHeader datastore
ColorEcho WARN "Arguments"
ColorEcho " --install=[PRODUCT] : Data storages to install. (default: all)."
ColorEcho " all, minio, mongo"
ColorEcho " --minio-port=[PORT] : Port number of minio API server(default: 9000)."
ColorEcho " --console-port=[PORT] : Port number of minio console UI(default: 9001)."
ColorEcho " --mongo-port=[PORT] : Port number of mongodb server(default: 27017)."
ColorEcho " -h, --help : This page"
exit 1
}
function CLIUsage {
UsageHeader cli
ColorEcho WARN "Arguments"
ColorEcho " -h, --help : This page"
exit 1
}
function StatusUsage {
UsageHeader status
ColorEcho WARN "Arguments"
ColorEcho " -h, --help : This page"
exit 1
}
# Base Command
eval set -- "$@"
while [ $# -ne 0 ]; do
case "$1" in
install)
INSTALL=1
shift
break
;;
join-token)
JOIN_TOKEN=1
shift
break
;;
uninstall)
UNINSTALL=1
break
;;
deploy)
DEPLOY=1
shift
break
;;
docker)
DOCKER=1
shift
break
;;
registry)
REGISTRY=1
shift
break
;;
datastore)
DATASTORE=1
shift
break
;;
cli)
CLI=1
shift
break
;;
status)
STATUS=1
shift
break
;;
esac
shift
done
if [ $INSTALL ]; then
OPTIONS=$(getopt -o t:h --long docker,join-token:,help -- "$@")
[ $? -eq 0 ] || InstallUsage
eval set -- "$OPTIONS"
while true; do
case "$1" in
--docker)
DOCKER_RUNTIME=1
;;
-t|--join-token) shift
RAW_TOKEN=$1
;;
-h|--help)
InstallUsage
;;
--)
shift
break
;;
esac
shift
done
elif [ $JOIN_TOKEN ]; then
OPTIONS=$(getopt -o h --long help -- "$@")
[ $? -eq 0 ] || JoinTokenUsage
eval set -- "$OPTIONS"
while true; do
case "$1" in
-h|--help)
JoinTokenUsage
;;
--)
shift
break
;;
esac
shift
done
elif [ $UNINSTALL ]; then
OPTIONS=$(getopt -o h --long help -- "$@")
[ $? -eq 0 ] || UninstallUsage
eval set -- "$OPTIONS"
while true; do
case "$1" in
-h|--help)
UninstallUsage
;;
--)
shift
break
;;
esac
shift
done
elif [ $DOCKER ]; then
OPTIONS=$(getopt -o h --long help -- "$@")
[ $? -eq 0 ] || DockerUsage
eval set -- "$OPTIONS"
while true; do
case "$1" in
-h|--help)
DockerUsage
;;
--)
shift
break
;;
esac
shift
done
elif [ $REGISTRY ]; then
OPTIONS=$(getopt -o h --long help -- "$@")
[ $? -eq 0 ] || RegistryUsage
eval set -- "$OPTIONS"
while true; do
case "$1" in
-h|--help)
RegistryUsage
;;
--)
shift
break
;;
esac
shift
done
elif [ $DATASTORE ]; then
declare -A DATASTORE_PORTS=(["minio:server"]=9000 ["minio:console"]=9001 ["mongo"]=27017)
declare -A DATASTORE_AVAILABLES=(["minio"]= ["mongo"]=)
DATASTORE_PRODUCTS=()
OPTIONS=$(getopt -o h --long install:,minio-port:,console-port:,mongo-port:,help -- "$@")
[ $? -eq 0 ] || DatastoreUsage
eval set -- "$OPTIONS"
while true; do
case "$1" in
--install) shift
if [ -v DATASTORE_AVAILABLES[$1] ]
then
DATASTORE_PRODUCTS+=("$1")
else
ColorEcho WARN "$1 is not support product."
fi
;;
--minio-port) shift
DATASTORE_PORTS[minio:server]=$1
;;
--console-port) shift
DATASTORE_PORTS[minio:console]=$1
;;
--mongo-port) shift
DATASTORE_PORTS[mongo]=$1
;;
-h|--help)
DatastoreUsage
;;
--)
shift
break
;;
esac
shift
done
[ ${#DATASTORE_PRODUCTS[@]} -eq 0 ] && DATASTORE_PRODUCTS+=(${!DATASTORE_AVAILABLES[@]})
elif [ $CLI ]; then
OPTIONS=$(getopt -o h --long help -- "$@")
[ $? -eq 0 ] || CLIUsage
eval set -- "$OPTIONS"
while true; do
case "$1" in
-h|--help)
CLIUsage
;;
--)
shift
break
;;
esac
shift
done
elif [ $STATUS ]; then
OPTIONS=$(getopt -o h --long help -- "$@")
[ $? -eq 0 ] || StatusUsage
eval set -- "$OPTIONS"
while true; do
case "$1" in
-h|--help)
StatusUsage
;;
--)
shift
break
;;
esac
shift
done
else
MainUsage
fi
# Main Script
# Requires for environment installer
{
IsInstalled sudo || \
{
apt update &&
apt install sudo -y
}
} && \
SILENT=1 RequiresFromApt curl && \
DEBIAN_FRONTEND=noninteractive sudo apt-get install -y --no-install-recommends tzdata >> /dev/null 2>&1 && \
SILENT=1 RequiresFromApt jq && \
{
IsInstalled python3 && \
[ $(python3 -c 'import sys; print(sys.version_info[1])') -lt 6 ] && \
{
SILENT=1 RequiresFromApt software-properties-common && \
sudo add-apt-repository ppa:deadsnakes/ppa -y && \
sudo apt update && \
SILENT=1 RequiresFromApt python3.7 python3
} || :
} && \
{
IsInstalled pip3 || {
SILENT=1 RequiresFromApt python3-pip pip && \
python3 -m pip install -U pip
}
} && \
SILENT=1 RequiresFromPip yq && \
SILENT=1 RequiresFromApt moreutils sponge || \
{
ColorEcho ERROR "Failed to prepare requirements."
for REQ in sudo curl jq sponge yq
do
if IsInstalled $REQ
then
ColorEcho WARN "[✔] $REQ is installed."
else
ColorEcho WARN "[❌] $REQ is not installed."
fi
done
exit 1
}
# Parse join token
if [ $RAW_TOKEN ]; then
# Worker Mode
payload=$(ParseToken $RAW_TOKEN)
if [ $payload ]
then
MASTER_IP=$(echo $payload | jq .url -r)
TOKEN=$(echo $payload | jq .token -r)
else
ColorEcho ERROR "Failed to parse token. Invalid or expired token."
exit 1
fi
fi
STEP=0
if [ $INSTALL ]
then
if IsWSL2
then
MAX_STEP=3
if ! IsInstalled docker
then
ColorEcho INFO "Need to install Docker Desktop yourself on WSL2."
ColorEcho INFO "Visit and Refer this URL: https://docs.docker.com/docker-for-windows/wsl/"
exit 1
fi
if IsInstalled kubectl
then
ColorEcho INFO "Need to install kubernetes on Docker Desktop yourself."
ColorEcho INFO "Visit and Refer this URL: https://docs.docker.com/docker-for-windows/#kubernetes"
exit 1
fi
if IsInstalledCluster
then
ColorEcho WARN "Check kubernetes status or kubeconfig."
exit 1
fi
ColorEcho INFO "Ready to install MLAppDeploy on your WSL2."
else
GetPrivileged
MAX_STEP=$((DOCKER_RUNTIME+4))
[ $DOCKER_RUNTIME ] && {
PrintStep Install Docker Engine.
InstallDocker
}
# Step 2: Install NVIDIA Container Runtine
PrintStep Install NVIDIA Container Runtime.
# Check Nvidia Driver status
if ! IsInstalled nvidia-smi
then
ColorEcho WARN "Cannot find NVIDIA Graphic Card."
else
if IsInstalled nvidia-container-runtime
then
ColorEcho INFO "Already installed NVIDIA container runtime."
else
ColorEcho INFO "Install NVIDIA container runtime."
InstallNVIDIAContainerRuntime
fi
if IsInstalled nvidia-container-runtime
then
ColorEcho INFO "Configure to use NVIDIA container runtime."
if [ $DOCKER_RUNTIME ]
then
# Register nvidia container runtime to docker
NVIDIAContainerRuntimeConfiguration
else
# Register nvidia container runtime to containerd
GetContainerdNVIDIATemplateFile
fi
else
ColorEcho ERROR "Failed to install NVIDIA container runtime."
ColorEcho ERROR "Pass this installation..."
ColorEcho ERROR "If you want to use GPU on node, install NVIDIA container runtime at this node manually."
fi
fi
# Step 3: Install requires
PrintStep "Install required pacakges."
SILENT=1 RequiresFromApt nfs-common || {
ColorEcho WARN Failed to install requires [nfs-common].
ColorEcho INFO This system cannot use nfs-mount.
ColorEcho INFO If you want to use nfs-mount, install manually.
}
# Step 4: Prepare Insecure registy environment
PrintStep "Register insecure registry."
[ -z $MASTER_IP ] && MASTER_IP=$(HostIP)
if [ $DOCKER_RUNTIME ]
then
sudo mkdir -p /etc/docker
! sudo test -f /etc/docker/daemon.json && echo {} | sudo sponge /etc/docker/daemon.json
if [ ! $(sudo cat /etc/docker/daemon.json | yq ".\"insecure-registries\" | index(\"$MASTER_IP:$REGISTRY_PORT\") // empty" >> /dev/null 2>&1) ]
then
sudo cat /etc/docker/daemon.json | yq ".\"insecure-registries\"+=[\"$MASTER_IP:$REGISTRY_PORT\"]" | sudo sponge /etc/docker/daemon.json
fi
else
sudo mkdir -p /etc/rancher/k3s/
! sudo test -f /etc/rancher/k3s/registries.yaml && echo {} | sudo sponge /etc/rancher/k3s/registries.yaml
if [ ! $(sudo cat /etc/rancher/k3s/registries.yaml | yq ".mirror.\"$MASTER_IP:$REGISTRY_PORT\".endpoint | index(\"http://$MASTER_IP:$REGISTRY_PORT\") // empty" >> /dev/null 2>&1) ]
then
sudo cat /etc/rancher/k3s/registries.yaml | yq ".mirror.\"$MASTER_IP:$REGISTRY_PORT\".endpoint+=[\"http://$MASTER_IP:$REGISTRY_PORT\"]" -y | sudo sponge /etc/rancher/k3s/registries.yaml
fi
fi
[ $DOCKER_RUNTIME ] && sudo systemctl restart docker.service
# Step 4: Install Kubernetes
PrintStep "Install Kubernetes."
if ! IsInstalledCluster
then
if IsInstalled k3s
then
bash $CMD uninstall
fi
if [ -z $RAW_TOKEN ]
then
# # Add priviledged for getting token
# ColorEcho INFO "Set priviledge for getting token by worker."
# echo "$USER ALL=NOPASSWD: $(which cat)" | sudo tee /etc/sudoers.d/$USER-k3s-token >> /dev/null 2>&1
# Install k3s server
INSTALL_K3S_EXEC="--disable=traefik --write-kubeconfig-mode 644"
[ $DOCKER_RUNTIME ] && INSTALL_K3S_EXEC+=" --docker"
curl -sfL https://get.k3s.io | INSTALL_K3S_CHANNEL=$K3S_CHANNEL \
INSTALL_K3S_EXEC=$INSTALL_K3S_EXEC \
sh -
# Prepare kubeconfig
KUBECONFIG_DIR=$HOME/.kube
KUBECONFIG_PATH=$KUBECONFIG_DIR/config
KUBECONFIG_MLAD=$KUBECONFIG_DIR/config.mlad
sudo cat /etc/rancher/k3s/k3s.yaml | yq '.clusters[0].name="MLAppDeploy"|.users[0].name="MLAppDeploy"|.contexts[0].name="MLAppDeploy"|.contexts[0].context.cluster="MLAppDeploy"|.contexts[0].context.user="MLAppDeploy"' -y | sponge $KUBECONFIG_MLAD
[ $? -eq 0 ] && {
KUBECONFIG="$KUBECONFIG_MLAD:$KUBECONFIG_PATH" kubectl config view --flatten | sponge $KUBECONFIG_PATH
kubectl config use-context MLAppDeploy
kubectl config get-contexts
} || {
ColorEcho ERROR "Failed to install lightweight kubernetes (k3s)."
exit 1
}
else
# # Add priviledged for getting token
# ColorEcho INFO "Set priviledge for getting token by worker."
# echo "$USER ALL=NOPASSWD: ALL" | sudo tee /etc/sudoers.d/$USER-k3s-token >> /dev/null 2>&1
# cat /dev/zero | ssh-keygen -q -N "" >> /dev/null 2>&1
# ssh-copy-id -o 'UserKnownHostsFile=/dev/null' -o 'StrictHostKeyChecking=no' -f [email protected] >> /dev/null 2>&1
# ssh-copy-id -o 'UserKnownHostsFile=/dev/null' -o 'StrictHostKeyChecking=no' -f $MASTER_USER@$MASTER_IP >> /dev/null 2>&1
# Install k3s agent
INSTALL_K3S_EXEC=""
[ $DOCKER_RUNTIME ] && INSTALL_K3S_EXEC+=" --docker"
curl -sfL https://get.k3s.io | INSTALL_K3S_CHANNEL=$K3S_CHANNEL \
INSTALL_K3S_EXEC=$INSTALL_K3S_EXEC K3S_URL=https://$MASTER_IP:6443 K3S_TOKEN=$TOKEN \
sh -
ColorEcho INFO "Finish join worker node with $MASTER_IP."
fi
else
ColorEcho "Already installed kubernetes."
fi
fi
elif [ $JOIN_TOKEN ]
then
ALL_TOKENS=$(GenerateToken)
JWT_TOKEN=$(echo $ALL_TOKENS | cut -d ' ' -f1)
TOKEN_PARAMS=$(echo $ALL_TOKENS | cut -d ' ' -f2-)
echo Generated Token: $JWT_TOKEN
echo
echo To add a worker to this cluster, run the following command in 30-mins :
echo $ $CMD install --join-token $JWT_TOKEN $TOKEN_PARAMS
echo
exit 0
elif [ $UNINSTALL ]
then
if IsWSL2
then
ColorEcho ERROR "Cannot support remove kubernetes on WSL2."
exit 1
fi
GetPrivileged
MAX_STEP=1
PrintStep "Uninstall Kubernetes."
if [[ $(which k3s-uninstall.sh >> /dev/null 2>&1; echo $?) == "0" ]]; then
ColorEcho INFO "Uninstall master node."
sudo k3s-uninstall.sh
elif [[ $(which k3s-agent-uninstall.sh >> /dev/null 2>&1; echo $?) == "0" ]]; then
ColorEcho INFO "Uninstall worker node."
sudo k3s-agent-uninstall.sh
echo "Need to run below command at master node:"
echo "$ kubectl delete node $HOSTNAME"
else
if [[ $(kubectl version >> /dev/null 2>&1; echo $?) == "0" ]]; then
ColorEcho ERROR "No have permission to remove kubernetes."
else
ColorEcho INFO "Already removed kubernetes."
fi
fi
elif [ $DOCKER ]
then
if IsWSL2
then
MAX_STEP=1
if ! IsInstalled docker
then
ColorEcho INFO "Need to install Docker Desktop yourself on WSL2."
ColorEcho INFO "Visit and Refer this URL: https://docs.docker.com/docker-for-windows/wsl/"
exit 1