/
nomad.sh
1852 lines (1836 loc) · 86.2 KB
/
nomad.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
usage_nomad() {
usage "nomad" "nomad helpers" <<EOF
$(helpcmd dir-path \(vault\|client\|server\|plugin\|webfs\))
Gets the corresponding cache directory file path.
$(helpcmd vault \(ci\|world\) login)
Login with your GitHub token. First copy the token by doing:
Your profile -> Settings -> Developer Settings ->
Tokens (Classic) -> Generate New Token (Classic)
and create a new token with only the "read:org" permission.
$(helpcmd vault \(ci\|world\) nomad-token)
Gets the corresponding Nomad token from the chosen Vault
(WARNING: shows secrets!!!).
$(helpcmd vault ci pg-user)
Gets SRE's Postgres server username from Vault
(WARNING: shows secrets!!!).
$(helpcmd vault ci pg-pass)
Gets SRE's Postgres server password from Vault
(WARNING: shows secrets!!!).
$(helpcmd vault world aws-s3-credentials)
Gets Cardano World's AWS S3 crdentials from Vault in JSON
(WARNING: shows secrets!!!).
$(helpcmd agents start SERVER-NAME CLIENT-NAME TASK-DRIVER-NAME)
Start a default 1 server 1 client Nomad cluster.
$(helpcmd agents stop SERVER-NAME CLIENT-NAME TASK-DRIVER-NAME)
Stop the default 1 server 1 client Nomad cluster.
$(helpcmd \(server/client\) state-dir-path NAME)
Location of the Agent's everything folder
$(helpcmd \(server/client\) config-file-path NAME)
Location of the Agent's config file (using only one)
$(helpcmd \(server/client\) configure NAME HTTP-PORT RPC-PORT SERV-PORT)
$(helpcmd \(server/client\) port \(http\|rcp\|serv\) NAME)
Getter for the previously configured ports
$(helpcmd \(server/client\) pid-filepath NAME)
Location of the Agent's "running" flag
$(helpcmd \(server/client\) pids-array NAME)
Search for Agent's PIDs independent of the "running" flag
$(helpcmd \(server/client\) is-running NAME)
True if the "running" flag is present or there are PIDs
$(helpcmd \(server/client\) start NAME)
Must call "configure" first
$(helpcmd \(server/client\) stop NAME)
Stops the Agent but does not clean its files
$(helpcmd \(server/client\) cleanup NAME)
Deletes all logs and state files
$(helpcmd plugin nomad-driver-podman socket-path)
$(helpcmd plugin nomad-driver-podman pid-filepath)
$(helpcmd plugin nomad-driver-podman pid)
$(helpcmd plugin nomad-driver-podman is-running)
$(helpcmd plugin nomad-driver-podman start)
$(helpcmd plugin nomad-driver-podman stop)
$(helpcmd webfs state-dir-path)
$(helpcmd webfs document-root-path)
$(helpcmd webfs add-genesis-dir)
$(helpcmd webfs pid-filepath)
$(helpcmd webfs pids-array)
$(helpcmd webfs is-running)
$(helpcmd webfs start)
$(helpcmd webfs stop)
$(helpcmd nuke)
$(helpcmd job start)
$(helpcmd job stop)
$(helpcmd job monitor)
$(helpcmd job monitor-job-evals)
$(helpcmd job monitor-job-allocs)
$(helpcmd job monitor-alloc-tasks)
$(helpcmd job check-eval-id-placement-failures)
$(helpcmd job monitor-eval-id)
$(helpcmd job monitor-deploy-id)
$(helpcmd job monitor-alloc-id)
$(helpcmd job monitor-alloc-id-task-name)
$(helpcmd job task-name-allocation-id)
EOF
}
publish_default_op='local'
wb_nomad() {
# Note on the use of bash's `local`:
# "Local can only be used within a function; it makes the variable name have a
# visible scope restricted to that function and its children."
# "when declaring and setting a local variable in a single command, apparently
# the order of operations is to first set the variable, and only afterwards
# restrict it to local scope."
# https://tldp.org/LDP/abs/html/localvar.html
local op=${1:-$nomad_default_op}; test $# -gt 0 && shift
case "${op}" in
################################################################################
### dir-path ) #################################################################
################################################################################
dir-path )
local usage="USAGE: wb nomad ${op} vault|server|client|plugin|webfs"
# Calling `wb nomad dir-path XXX` inside a Nix derivation will fail:
# "mkdir: cannot create directory '/homeless-shelter': Permission denied"
local nomad_cache_dir="$(envjqr 'cacheDir')"/nomad
mkdir -p "${nomad_cache_dir}"
local subop=${1:?$usage}; shift
case "${subop}" in
vault )
local vault_dir="${nomad_cache_dir}"/vault
mkdir -p "${vault_dir}"
echo "${vault_dir}"
;;
server )
local nomad_servers_dir="${nomad_cache_dir}"/server
mkdir -p "${nomad_servers_dir}"
echo "${nomad_servers_dir}"
;;
client )
local nomad_clients_dir="${nomad_cache_dir}"/client
mkdir -p "${nomad_clients_dir}"
echo "${nomad_clients_dir}"
;;
plugin )
local plugin_dir="${nomad_cache_dir}"/plugin
mkdir -p "${plugin_dir}"
echo "${plugin_dir}"
;;
webfs )
local webfs_dir="${nomad_cache_dir}"/webfs
mkdir -p "${webfs_dir}"
echo "${webfs_dir}"
;;
* )
usage_nomad
;;
esac
;;
################################################################################
### vault ) ####################################################################
################################################################################
vault )
local usage="USAGE: wb nomad ${op} world|ci"
local vault_dir="$(wb_nomad dir-path vault)"
local entity=${1:?$usage}; shift
case "${entity}" in
####### vault -> ci )###########################################################
ci )
mkdir -p "${vault_dir}"/ci
local login_file="${vault_dir}"/ci/login.json
local vault_address="https://vault.ci.iog.io"
local action=${1:?$usage}; shift
case "${action}" in
login )
msg "First create and copy your GitHub token by doing: "
msg "Your profile -> Settings -> Developer Settings -> Tokens (Classic) -> Generate New Token (Classic)"
msg "and create a new token with only the \"read:org\" permission."
read -p "Hit enter to continue ..."
vault login \
-address="${vault_address}" \
-method=github -path=github-employees \
-no-store -format=json \
> "${login_file}"
;;
enabled )
if test -f "${login_file}"
then
# Fetch token info from vault
local client_token
client_token=$(jq -r '.auth.client_token' "${login_file}")
local token_lookup_response
if token_lookup_response=$(VAULT_TOKEN="${client_token}" vault token lookup -address="${vault_address}" -namespace=perf -format=json)
then
local expire_time
expire_time=$(echo "${token_lookup_response}" | jq -r .data.expire_time)
if test "$(date -u -d "${expire_time}" "+%s")" -ge "$(date -u "+%s")"
then
true
else
rm "${login_file}"
false
fi
else
fatal "Are you logged in to Vault? Call 'wb nomad vault ${entity} login' with your IOHK GitHub token (classic)"
fi
else
false
fi
;;
nomad-token )
if ! wb_nomad vault "${entity}" enabled
then
wb_nomad vault "${entity}" login
fi
local client_token
client_token=$(jq -r '.auth.client_token' "${login_file}")
local nomad_token_json
if nomad_token_json=$(VAULT_TOKEN="${client_token}" vault read -address="${vault_address}" -non-interactive -format=json nomad/creds/perf)
then
echo "${nomad_token_json}" | jq -r .data.secret_id
else
fatal "Unable to fetch Nomad token from Vault"
fi
;;
pg-user )
if ! wb_nomad vault "${entity}" enabled
then
wb_nomad vault "${entity}" login
fi
local client_token
client_token=$(jq -r '.auth.client_token' "${login_file}")
VAULT_TOKEN="${client_token}" vault kv get \
--address="${vault_address}" \
-non-interactive \
-format=json \
kv/postgrest/perf \
| jq -r .data.data.postgrestDbUser
;;
pg-pass )
if ! wb_nomad vault "${entity}" enabled
then
wb_nomad vault "${entity}" login
fi
local client_token
client_token=$(jq -r '.auth.client_token' "${login_file}")
VAULT_TOKEN="${client_token}" vault kv get \
--address="${vault_address}" \
-non-interactive \
-format=json \
kv/postgrest/perf \
| jq -r .data.data.postgrestDbPass
;;
####### vault -> ci -> * )######################################################
* )
usage_nomad
;;
esac
;;
####### vault -> world )########################################################
world )
mkdir -p "${vault_dir}"/world
local login_file="${vault_dir}"/world/login.json
local vault_address="https://vault.world.dev.cardano.org"
local action=${1:?$usage}; shift
case "${action}" in
login )
msg "First create and copy your GitHub token by doing: "
msg "Your profile -> Settings -> Developer Settings -> Tokens (Classic) -> Generate New Token (Classic)"
msg "and create a new token with only the \"read:org\" permission."
read -p "Hit enter to continue ..."
vault login \
-address="${vault_address}" \
-method=github -path=github-employees \
-no-store -format=json \
> "${login_file}"
;;
enabled )
if test -f "${login_file}"
then
local client_token
client_token=$(jq -r '.auth.client_token' "${login_file}")
local token_lookup_response
if token_lookup_response=$(VAULT_TOKEN="${client_token}" vault token lookup -address="${vault_address}" -namespace=perf -format=json)
then
# TODO: I need to check the expiration time?
# echo "${token_lookup_response}" | jq -r .data.expire_time
# 2023-02-19T13:07:26.125306646Z
true
else
fatal "Are you logged in to Vault? Call 'wb nomad vault ${entity} login' with your IOHK GitHub token (classic)"
fi
else
false
fi
;;
nomad-token )
if ! wb_nomad vault "${entity}" enabled
then
wb_nomad vault "${entity}" login
fi
local client_token
client_token=$(jq -r '.auth.client_token' "${login_file}")
local nomad_token_json
if nomad_token_json=$(VAULT_TOKEN="${client_token}" vault read -address="${vault_address}" -non-interactive -format=json nomad/creds/perf)
then
echo "${nomad_token_json}" | jq -r .data.secret_id
else
fatal "Unable to fetch Nomad token from Vault"
fi
;;
aws-s3-credentials )
if ! wb_nomad vault "${entity}" enabled
then
wb_nomad vault "${entity}" login
fi
local client_token
client_token=$(jq -r '.auth.client_token' "${login_file}")
VAULT_TOKEN="${client_token}" vault read \
--address="${vault_address}" \
-format=json \
aws/creds/perf
;;
####### vault -> world -> * )###################################################
* )
usage_nomad
;;
esac
;;
####### vault -> * )############################################################
* )
usage_nomad
;;
esac
;;
################################################################################
### agents ) ###################################################################
################################################################################
agents )
### Start/stop server and client
################################
# The Nomad agent is a long running process which runs on every machine
# that is part of the Nomad cluster. The behavior of the agent depends
# on if it is running in client or server mode. Clients are responsible
# for running tasks, while servers are responsible for managing the
# cluster.
local usage="USAGE: wb nomad ${op} start|stop"
local subop=${1:?$usage}; shift
case "${subop}" in
####### agents -> start )#######################################################
start )
local usage="USAGE:wb nomad ${op} ${subop} SERVER-NAME CLIENT-NAME DRIVER-NAME"
local server_name=${1:?$usage}; shift
local client_name=${1:?$usage}; shift
local task_driver=${1:?$usage}; shift
# Create config files for the server and start it.
if ! wb_nomad server configure "${server_name}" 4646 4647 4648
then
fatal "Failed to configure Nomad server \"${server_name}\""
fi
if ! wb_nomad server start "${server_name}"
then
fatal "Failed to start Nomad server \"${server_name}\""
fi
# Set up the podman driver and start it if it's needed.
if test "${task_driver}" = "podman"
then
# Create config files for the client and the Podman plugin/task driver.
wb_nomad plugin nomad-driver-podman start
fi
# Create config files for the client and start it.
# WARNING: Actually the client is configured to connect to all the
# running servers, so if there are no servers ready the Nomad
# cluster state is uknown (at least to me with the actual config).
if ! wb_nomad client configure "${client_name}" 14646 14647 14648 "${task_driver}"
then
wb_nomad server stop "${server_name}" || true
fatal "Failed to configure Nomad client \"${client_name}\""
fi
# Only the exec driver must be run as root.
if test "${task_driver}" = "exec"
then
# Pass the "root prefix" (command prefix)
if ! wb_nomad client start "${client_name}" "sudo "
then
wb_nomad server stop "${server_name}" || true
fatal "Failed to start Nomad agents"
fi
else
if ! wb_nomad client start "${client_name}"
then
wb_nomad plugin nomad-driver-podman stop || true
wb_nomad server stop "${server_name}" || true
fatal "Failed to start Nomad agents"
fi
fi
;;
####### agents -> stop )########################################################
stop )
local usage="USAGE:wb nomad ${op} ${subop} SERVER-NAME CLIENT-NAME DRIVER-NAME"
local server_name=${1:?$usage}; shift
local client_name=${1:?$usage}; shift
local task_driver=${1:?$usage}; shift
# Collect garbage to avoid orphaned mounts
# https://support.hashicorp.com/hc/en-us/articles/360000654467-Removing-Orphaned-Mounts-from-Nomad-Allocation-Directory
nomad system gc 2>&1 >/dev/null || true
# Stop client
wb_nomad client stop "${client_name}" || true
if test "${task_driver}" = "podman"
then
wb_nomad plugin nomad-driver-podman stop || true
fi
# Stop server
wb_nomad server stop "${server_name}" || true
;;
####### agents -> * )###########################################################
* )
usage_nomad
;;
esac # agents
;;
################################################################################
### server ) ###################################################################
################################################################################
server )
local usage="USAGE: wb nomad ${op} state-dir-path|config-file-path|configure|port|pid-filepath|pids-array|is-running|start|stop"
local subop=${1:?$usage}; shift
case "${subop}" in
####### server -> state-dir-path )##############################################
state-dir-path )
local usage="USAGE: wb nomad ${op} ${subop} SERVER-NAME"
local name=${1:?$usage}; shift
local nomad_servers_dir="$(wb_nomad dir-path server)"
echo "${nomad_servers_dir}"/"${name}"
;;
####### server -> config-file-path )############################################
config-file-path )
local usage="USAGE: wb nomad ${op} ${subop} SERVER-NAME"
local name=${1:?$usage}; shift
local state_dir=$(wb_nomad server state-dir-path "${name}")
echo "${state_dir}"/config/nomad.hcl
;;
####### server -> configure )###################################################
configure )
local usage="USAGE: wb nomad ${op} ${subop} SERVER-NAME HTTP-PORT RPC-PORT SERV-PORT"
local name=${1:?$usage}; shift
# Ports
local http_port=${1:?$usage}; shift
local rpc_port=${1:?$usage}; shift
local serv_port=${1:?$usage}; shift
# Assume the presence of the PID file means "running" because it
# can represent an abnormal exit / uknown state!
if wb_nomad server is-running "${name}"
then
msg "$(red "FATAL: Nomad server \"${name}\" is already running or in an uknown state, call 'wb nomad server stop ${name}' or 'wb nomad nuke' first")"
return 1
else
local state_dir=$(wb_nomad server state-dir-path "${name}")
# Delete previous state if any.
rm -rf "${state_dir}" >/dev/null 2>&1
# Needed folders:
mkdir -p "${state_dir}"/config
mkdir -p "${state_dir}"/data/server
# Store the ports config
echo "{\"http\": ${http_port}, \"rpc\": ${rpc_port}, \"serv\": ${serv_port}}" > "${state_dir}"/ports.json
# Configure
nomad_create_server_config "${name}" \
"${http_port}" "${rpc_port}" "${serv_port}"
fi
;;
####### server -> port )########################################################
port )
local usage="USAGE: wb nomad ${op} ${subop} (http|rcp|serv) SERVER-NAME"
local port=${1:?$usage}; shift
local name=${1:?$usage}; shift
local state_dir=$(wb_nomad server state-dir-path "${name}")
local ports_file="${state_dir}"/ports.json
case "$port" in
http )
jq .http "${ports_file}"
;;
rpc )
jq .rpc "${ports_file}"
;;
serv )
jq .serv "${ports_file}"
;;
* )
false
;;
esac
;;
####### server -> pid-filepath )################################################
pid-filepath )
local usage="USAGE: wb nomad ${op} ${subop} SERVER-NAMENAME"
local name=${1:?$usage}; shift
local state_dir=$(wb_nomad server state-dir-path "${name}")
# Look up PID by Nomad server name
echo "${state_dir}"/nomad.pid
;;
####### server -> pids-array )##################################################
pids-array )
local usage="USAGE: wb nomad ${op} ${subop} SERVER-NAME"
local name=${1:?$usage}; shift
local config_file=$(wb_nomad server config-file-path "${name}")
pgrep --delimiter ' ' --full "nomad.*${config_file}.*"
# Clean up is only done by the `stop` subcommand!
# No `rm "${pid_file}"` if not running.
;;
####### server -> is-running )##################################################
is-running )
local usage="USAGE: wb nomad ${op} ${subop} SERVER-NAMENAME"
local name=${1:?$usage}; shift
local pid_file=$(wb_nomad server pid-filepath "${name}")
local config_file=$(wb_nomad server config-file-path "${name}")
# It's running if we haven't PROPERLY stopped it or PIDs exist!
test -f "${pid_file}" || test $(pgrep --count --full "nomad.*${config_file}.*") -gt 0
;;
####### server -> start )#######################################################
start )
local usage="USAGE: wb nomad ${op} ${subop} SERVER-NAMENAME"
local name=${1:?$usage}; shift
local state_dir=$(wb_nomad server state-dir-path "${name}")
# Checks
if wb_nomad server is-running "${name}"
then
msg "$(red "FATAL: Nomad server \"${name}\" is already running or in an uknown state, call 'wb nomad server stop ${name}' or 'wb nomad nuke' first")"
return 1
fi
# Start `nomad` server".
msg "$(blue Starting) Nomad $(yellow "server \"${name}\"") ..."
local config_file=$(wb_nomad server config-file-path "${name}")
local pid_file=$(wb_nomad server pid-filepath "${name}")
local pid_number
# Start the agent on a new session (`setsid`) so it does not receive
# CTRL+C. It must be properly ended by the workbench's exit trap.
setsid nomad agent \
-config="${config_file}" \
>> "${state_dir}"/stdout \
2>> "${state_dir}"/stderr \
&
pid_number="$!"
echo "${pid_number}" > "${pid_file}"
msg "$(green "Nomad server \"${name}\" started with PID ${pid_number}")"
# Even if Nomad server was already running, try to connect to it!
local i=0 patience=25
local http_port=$(wb_nomad server port http "${name}")
msg "$(blue Waiting) for the listening HTTP server (${patience}s) ..."
until curl -Isf 127.0.0.1:"${http_port}" 2>&1 | head --lines=1 | grep --quiet "HTTP/1.1"
do printf "%3d" $i; sleep 1
i=$((i+1))
if test $i -ge ${patience}
then echo
# Not using `fatal` here, let the caller decide!
msg "$(red "FATAL: Nomad server startup did not succeed")"
msg "$(yellow "port \"127.0.0.1:${http_port}\" not ready")"
msg "$(yellow "Check logs (${state_dir})")"
# Let the "stop" subcommand clean everything!
wb_nomad server stop "${name}"
return 1
fi
echo -ne "\b\b\b"
done >&2
;;
####### server -> stop )########################################################
stop )
# We don't check first if the PID file exists!
# Also clean up, so here do not assume that Nomad is running!
local usage="USAGE: wb nomad ${op} ${subop} SERVER-NAME"
local name=${1:?$usage}; shift
# Stop Nomad server by name
local pids=$(wb_nomad server pids-array "${name}")
for pid_number in ${pids[@]}
do
msg "$(blue Stopping) Nomad $(yellow "server \"${name}\"") process PID ${pid_number} ..."
if ! kill -SIGINT "${pid_number}" >/dev/null 2>&1
then
msg "$(red "Killing PID ${pid_number} failed")"
else
# Wait 15 seconds for the process to fully exit or kill it.
msg "$(blue Wait) up to 15 seconds for PID ${pid_number} to exit"
timeout 15 tail --pid="${pid_number}" -f /dev/null || true
if kill -0 "${pid_number}" >/dev/null 2>&1
then
msg "$(yellow "Timeout killing PID ${pid_number}, trying SIGKILL")"
kill -SIGKILL "${pid_number}" >/dev/null 2>&1 || true
fi
fi
done
# Remove PID file if process was really killed (or wasn't running)!
if test -z $(wb_nomad server pids-array "${name}")
then
local pid_file=$(wb_nomad server pid-filepath "${name}")
if test -f "${pid_file}"
then
rm "${pid_file}"
fi
fi
;;
####### server -> cleanup )#####################################################
cleanup )
local usage="USAGE: wb nomad ${op} ${subop} SERVER-NAMENAME"
local name=${1:?$usage}; shift
if wb_nomad server is-running "${name}"
then
msg "Won't cleanup the running server \"${name}\""
else
local state_dir=$(wb_nomad server state-dir-path "${name}")
rm -rf "${state_dir}" >/dev/null 2>&1 || true
fi
;;
####### server -> * )###########################################################
* )
usage_nomad
;;
esac # server
;;
################################################################################
### client ) ###################################################################
################################################################################
client )
local usage="USAGE: wb nomad ${op} state-dir-path|config-file-path|configure|port|pid-filepath|pids-array|is-running|start|stop"
local subop=${1:?$usage}; shift
case "${subop}" in
####### client -> state-dir-path )##############################################
state-dir-path )
local usage="USAGE: wb nomad ${op} ${subop} CLIENT-NAME"
local name=${1:?$usage}; shift
local nomad_clients_dir="$(wb_nomad dir-path client)"
echo "${nomad_clients_dir}"/"${name}"
;;
####### client -> config-file-path )############################################
config-file-path )
local usage="USAGE: wb nomad ${op} ${subop} CLIENT-NAME"
local name=${1:?$usage}; shift
local state_dir=$(wb_nomad client state-dir-path "${name}")
echo "${state_dir}"/config/nomad.hcl
;;
####### client -> configure )###################################################
configure )
local usage="USAGE: wb nomad ${op} ${subop} CLIENT-NAME HTTP-PORT RPC-PORT SERV-PORT DRIVER-NAME [GENESIS-DIR]"
local name=${1:?$usage}; shift
# Ports
local http_port=${1:?$usage}; shift
local rpc_port=${1:?$usage}; shift
local serv_port=${1:?$usage}; shift
# Unlike the server, the client can have different task drivers!
local task_driver=${1:?$usage}; shift
# Checks
# Assume the presence of the PID file means "running" because it
# can represent an abnormal exit / uknown state!
if wb_nomad client is-running "${name}"
then
# When reusing, remember to check that client is running with
# the needed task driver!
msg "$(red "FATAL: Nomad client \"${name}\" is already running or in an uknown state, call 'wb nomad client stop ${name}' or 'wb nomad nuke' first")"
return 1
else
local state_dir=$(wb_nomad client state-dir-path "${name}")
# Delete previous state if any.
rm -rf "${state_dir}" >/dev/null 2>&1
# Needed folders:
mkdir -p "${state_dir}"/config
mkdir -p "${state_dir}"/data/{client,plugins,alloc}
# Store the ports config
echo "{\"http\": ${http_port}, \"rpc\": ${rpc_port}, \"serv\": ${serv_port}}" > "${state_dir}"/ports.json
# Store tast driver parameter
echo "${task_driver}" > "${state_dir}"/task_driver
# Task driver specific client configuration
if test "${task_driver}" = "podman"
then
local podman_socket_path=$(wb_nomad plugin nomad-driver-podman socket-path)
# Podman Task Driver - Client Requirements:
## "Ensure that Nomad can find the plugin, refer to `plugin_dir`."
### https://www.nomadproject.io/plugins/drivers/podman#client- requirements
## On every call to `wb nomad client configure` the
## available `nomad-driver-podman` is replaced.
# TODO: Somehow move this logic to `wb nomad plugin`
rm -f "${state_dir}"/data/plugins/nomad-driver-podman
ln -s -f "$(which nomad-driver-podman)" "${state_dir}"/data/plugins/nomad-driver-podman
# Create configuration file
nomad_create_client_config "${name}" \
"${http_port}" "${rpc_port}" "${serv_port}" \
"${task_driver}" "${podman_socket_path}"
else
# Create configuration file
nomad_create_client_config "${name}" \
"${http_port}" "${rpc_port}" "${serv_port}" \
"${task_driver}"
fi
fi
;;
####### client -> port )########################################################
port )
local usage="USAGE: wb nomad ${op} ${subop} (http|rcp|serv) CLIENT-NAME"
local port=${1:?$usage}; shift
local name=${1:?$usage}; shift
local state_dir=$(wb_nomad client state-dir-path "${name}")
local ports_file="${state_dir}"/ports.json
case "$port" in
http )
jq .http "${ports_file}"
;;
rpc )
jq .rpc "${ports_file}"
;;
serv )
jq .serv "${ports_file}"
;;
* )
false
;;
esac
;;
####### client -> pid-filepath )################################################
pid-filepath )
local usage="USAGE: wb nomad ${op} ${subop} CLIENT-NAME"
local name=${1:?$usage}; shift
local state_dir=$(wb_nomad client state-dir-path "${name}")
# Look up PID by Nomad client name
echo "${state_dir}"/nomad.pid
;;
####### client -> pids-array )##################################################
pids-array )
local usage="USAGE: wb nomad ${op} ${subop} CLIENT-NAME"
local name=${1:?$usage}; shift
local config_file=$(wb_nomad client config-file-path "${name}")
pgrep --delimiter ' ' --full "nomad.*${config_file}.*"
# Clean up is only done by the `stop` subcommand!
# No `rm "${pid_file}"` if not running.
;;
####### client -> is-running )##################################################
is-running )
local usage="USAGE:wb nomad ${op} ${subop} CLIENT-NAME"
local name=${1:?$usage}; shift
local pid_file=$(wb_nomad client pid-filepath "${name}")
local config_file=$(wb_nomad client config-file-path "${name}")
# It's running if we haven't PROPERLY stopped it or PIDs exist!
test -f "${pid_file}" || test $(pgrep --count --full "nomad.*${config_file}.*") -gt 0
;;
####### client -> start )#######################################################
# Agent is started with `-network-interface lo` if not without a proper
# network connection it fails with the message shown below.
# (Fix added while on a 13:25 hour long non-stop flight)
# {
# "@level": "error",
# "@message": "error starting agent",
# "@module": "agent",
# "@timestamp": "2023-05-07T15:12:34.631345Z",
# "error": "client setup failed: fingerprinting failed: Error while detecting network interface during fingerprinting: No default interface found"
# }
# {
# "@level": "error",
# "@message": "Error starting agent: client setup failed: fingerprinting failed: Error while detecting network interface during fingerprinting: No default interface found",
# "@module": "agent",
# "@timestamp": "2023-05-07T15:12:34.631378Z"
# }
# TODO: Look for a default route first? (same logic Nomad uses)
# ip route list default | head --lines=1 | cut -d " " -f 3
# See also Client config "fingerprint.network.disallow_link_local"
start )
local usage="USAGE: wb nomad ${op} ${subop} CLIENT-NAME [ROOT-PREFIX]"
local name=${1:?$usage}; shift
# A "root" prefix, like "sudo " (blankspace intended).
local root_prefix=""
local state_dir=$(wb_nomad client state-dir-path "${name}")
if test $# -gt 0
then
root_prefix=${1:?$usage}; shift
if test -n "${root_prefix}"
then
echo "${root_prefix}" > "${state_dir}"/root
fi
fi
# Checks
if wb_nomad client is-running "${name}"
then
msg "$(red "FATAL: Nomad client \"${name}\" is already running or in an uknown state, call 'wb nomad client stop ${name}' or 'wb nomad nuke' first")"
return 1
fi
# Start `nomad` client".
msg "$(blue Starting) Nomad $(yellow "client \"${name}\"") ..."
local config_file=$(wb_nomad client config-file-path "${name}")
local pid_file=$(wb_nomad client pid-filepath "${name}")
local pid_number
local cmd_array=("${root_prefix}" "bash" "-c")
# Start the agent on a new session (`setsid`) so it does not receive
# CTRL+C. It must be properly ended by the workbench's exit trap.
pid_number=$(${cmd_array[@]} "setsid nomad agent \
-config="${config_file}" \
-network-interface lo \
>> "${state_dir}"/stdout \
2>> "${state_dir}"/stderr \
& echo \"\$!\"")
echo "${pid_number}" > "${pid_file}"
msg "$(green "Nomad client \"${name}\" started with PID ${pid_number}")"
# Even if Nomad server was already running, try to connect to it!
local i=0 patience=25
local http_port=$(wb_nomad client port http "${name}")
msg "$(blue Waiting) for the listening HTTP server (${patience}s) ..."
until curl -Isf 127.0.0.1:"${http_port}" 2>&1 | head --lines=1 | grep --quiet "HTTP/1.1"
do printf "%3d" $i; sleep 1
i=$((i+1))
if test $i -ge ${patience}
then echo
# Not using `fatal` here, let the caller decide!
msg "$(red "FATAL: Nomad client startup did not succeed")"
msg "$(yellow "port \"127.0.0.1:${http_port}\" not ready")"
msg "$(yellow "Check logs (${state_dir})")"
# Let the "stop" subcommand clean everything!
wb_nomad client stop "${name}"
return 1
fi
echo -ne "\b\b\b"
done >&2
# Now check that the server and client are connected and the
# client as eligible
local i=0 patience=25
msg "$(blue Waiting) until the Nomad server sees the client (${patience}s) ..."
local ans=""
until nomad node status -filter "\"workbench-nomad-client-${name}\" in Name" -json | jq -r '.[0].Status' | grep --quiet "^ready"
do printf "%3d" $i; sleep 1
i=$((i+1))
if test $i -ge ${patience}
then echo
tail "${state_dir}"/stderr
# Not using `fatal` here, let the caller decide!
msg "$(red "FATAL: Nomad client startup did not succeed")"
msg "$(yellow "Nomad client not connected to Nomad server")"
msg "$(yellow "Check logs (${state_dir})")"
# Let the "stop" subcommand clean everything!
wb_nomad client stop "${name}"
return 1
fi
echo -ne "\b\b\b"
done >&2
# TODO: List the known server addresses of the client node.
# nomad node config -servers
local client_id=$(nomad node status -filter "\"workbench-nomad-client-cli1\" in Name" -json | jq -r '.[0].ID')
# TODO: Configure the node?
# nomad node eligibility -enable "${client_id}"
# nomad node drain -disable "${client_id}"
local task_driver=$(cat "${state_dir}"/task_driver)
if test "${task_driver}" == "exec"
then
# Look for "Drivers":{"exec": {"Detected":true,"Healthy":true}}
if ! test $(nomad node status -filter "\"workbench-nomad-client-${name}\" in Name" -json | jq '.[0].Drivers.exec.Detected') = "true"
then
# Not using `fatal` here, let the caller decide!
msg "$(red "FATAL: Task driver \"exec\" was not detected")"
return 1
fi
if ! test $(nomad node status -filter "\"workbench-nomad-client-${name}\" in Name" -json | jq '.[0].Drivers.exec.Healthy') = "true"
then
# Not using `fatal` here, let the caller decide!
msg "$(red "FATAL: Task driver \"exec\" is not healthy")"
return 1
fi
else
# Look for "Drivers":{"podman":{"Detected":true,"Healthy":true}}
if ! test $(nomad node status -filter "\"workbench-nomad-client-${name}\" in Name" -json | jq '.[0].Drivers.podman.Detected') = "true"
then
# Not using `fatal` here, let the caller decide!
msg "$(red "FATAL: Task driver \"podman\" was not detected")"
return 1
fi
if ! test $(nomad node status -filter "\"workbench-nomad-client-${name}\" in Name" -json | jq '.[0].Drivers.podman.Healthy') = "true"
then
# Not using `fatal` here, let the caller decide!
msg "$(red "FATAL: Task driver \"podman\" is not healthy")"
return 1
fi
fi
true
# TODO: Check all the clients connected to the server!
;;
####### client -> stop )########################################################
stop )
# We don't check first if the PID file exists!
# Also clean up, so here do not assume that Nomad is running!
local usage="USAGE: wb nomad ${op} ${subop} CLIENT-NAME"
local name=${1:?$usage}; shift
# Look for the "root" flag with the command prefix (like `sudo `)
local state_dir=$(wb_nomad client state-dir-path "${name}")
local root_prefix
if test -e "${state_dir}"/root
then
root_prefix=$(cat "${state_dir}"/root)
else
root_prefix=""
fi
# Stop Nomad client by name
local pids=$(wb_nomad client pids-array "${name}")
for pid_number in ${pids[@]}
do
msg "$(blue Stopping) Nomad $(yellow "client \"${name}\"") process PID ${pid_number} ..."
local cmd_array=("${root_prefix}" "bash" "-c")
if ! ${cmd_array[@]} "kill -SIGINT ${pid_number}" >/dev/null 2>&1
then
msg "Killing PID ${pid_number} failed"
else
# Wait 15 seconds for the process to fully exit or kill it.
msg "$(blue Wait) up to 30 seconds for PID ${pid_number} to exit"
timeout 30 tail --pid="${pid_number}" -f /dev/null || true
local cmd_array=("${root_prefix}" "bash" "-c")
if ${cmd_array[@]} "kill -0 ${pid_number}" >/dev/null 2>&1
then
msg "$(yellow "Timeout killing PID ${pid_number}, trying SIGKILL")"
local cmd_array=("${root_prefix}" "bash" "-c")
${cmd_array[@]} "kill -SIGKILL ${pid_number}" >/dev/null 2>&1 || true
fi
fi
done
# Remove PID file if process was really killed (or wasn't running)!
if test -z $(wb_nomad client pids-array "${name}")
then
# WHY? The client is keeping some directories mounted!
# Maybe because of the 2 processes it creates (testes running
# only one client instance), I may be killing a child first?
# Or the timeout needs more time?
msg "Unmount any folders left by the client"
local cmd_array=("${root_prefix}" "bash" "-c")
# Command fails when there's nothing to umount!
grep "${state_dir}" /proc/mounts | cut -f2 -d" " | sort -r | ${cmd_array[@]} 'xargs -I "{}" umount -n "{}"' || true
# Now mark as "not running"
local pid_file=$(wb_nomad client pid-filepath "${name}")
if test -f "${pid_file}"
then
rm "${pid_file}"
fi
fi
;;
####### client -> cleanup )#####################################################
cleanup )
local usage="USAGE: wb nomad ${op} ${subop} CLIENT-NAMENAME"
local name=${1:?$usage}; shift
if wb_nomad client is-running "${name}"
then
msg "Won't cleanup the running client \"${name}\""
else
local state_dir=$(wb_nomad client state-dir-path "${name}")
# Look for the "root" flag with the command prefix (like `sudo `)
local root_prefix
if test -e "${state_dir}"/root
then
root_prefix=$(cat "${state_dir}"/root)
else
root_prefix=""
fi
local cmd_array=("${root_prefix}" "bash" "-c")
${cmd_array[@]} "rm -rf ${state_dir}" >/dev/null 2>&1 || true
fi
;;
# Client specific subcommands here (not available for servers):
####### client -> * )###########################################################
* )
usage_nomad
;;
esac # client
;;
################################################################################
### plugin ) ###################################################################
################################################################################
plugin )
local usage="USAGE: wb nomad ${op} nomad-driver-podman"
local plugin=${1:?$usage}; shift
case "${plugin}" in
####### plugin -> nomad-driver-podman )#########################################
nomad-driver-podman )
local usage="USAGE: wb nomad ${op} ${plugin}"
local subop=${1:?$usage}; shift
case "$subop" in
########### plugin -> nomad-driver-podman -> socket-path )######################
socket-path )
# Socket of the process that connects nomad-driver-podman with podman.
# Can't reside inside "$dir", can't use a path longer than 108 characters!
# See: https://man7.org/linux/man-pages/man7/unix.7.html
# char sun_path[108]; /* Pathname */
echo "${XDG_RUNTIME_DIR:-/run/user/$UID}/workbench-podman.sock"
;;
########### plugin -> nomad-driver-podman -> pid-filepath )#####################
pid-filepath )
local plugin_dir="$(wb_nomad dir-path plugin)"
echo "${plugin_dir}"/nomad-driver-podman.pid
;;
########### plugin -> nomad-driver-podman -> pid )##############################
pid )
local pid_file=$(wb_nomad plugin nomad-driver-podman pid-filepath)
if test -f $pid_file
then
local pid_number=$(cat "${pid_file}")
# Check if the process is running
if kill -0 "${pid_number}" >/dev/null 2>&1
then
echo "${pid_number}"
else
rm "${pid_file}"
false
fi
else
false
fi
;;
########### plugin -> nomad-driver-podman -> is-running )#######################
is-running )
wb_nomad plugin nomad-driver-podman pid >/dev/null
;;
########### plugin -> nomad-driver-podman -> start )############################
# Start the `podman` API service needed by `nomad`.
start ) # TODO: Check that it's not already running!
msg "Preparing podman API service for nomad driver \`nomad-driver-podman\` ..."
local podman_socket_path=$(wb_nomad plugin nomad-driver-podman socket-path)
# if test -S "$socket"
# then
# msg "Podman API service was already running"
# else
# The session is kept open waiting for a new connection for 60 seconds.
# https://discuss.hashicorp.com/t/nomad-podman-rhel8-driver-difficulties/21877/4
# `--time`: Time until the service session expires in seconds. Use 0
# to disable the timeout (default 5).
local pid_file=$(wb_nomad plugin nomad-driver-podman pid-filepath)