-
Notifications
You must be signed in to change notification settings - Fork 56
/
vm.bash
850 lines (800 loc) · 29.3 KB
/
vm.bash
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
# shellcheck disable=SC1091
# shellcheck source=command.bash
source "$(dirname "${BASH_SOURCE[0]}")/command.bash"
# shellcheck disable=SC1091
# shellcheck source=distro.bash
source "$(dirname "${BASH_SOURCE[0]}")/distro.bash"
VM_PROMPT=${VM_PROMPT-"\e[38;5;11mroot@vm>\e[0m "}
vm-compose-govm-template() {
(echo "
vms:
- name: ${VM_NAME}
image: ${VM_IMAGE}
cloud: true
ContainerEnvVars:
- KVM_CPU_OPTS=${VM_QEMU_CPUMEM:=-machine pc -smp cpus=4 -m 8G}
- EXTRA_QEMU_OPTS=-monitor unix:/data/monitor,server,nowait ${VM_QEMU_EXTRA}
- USE_NET_BRIDGES=${USE_NET_BRIDGES:-0}
user-data: |
#!/bin/bash
set -e
"
(if [ -n "$VM_EXTRA_BOOTSTRAP_COMMANDS" ]; then
# shellcheck disable=SC2001
sed 's/^/ /g' <<< "${VM_EXTRA_BOOTSTRAP_COMMANDS}"
fi
# shellcheck disable=SC2001
sed 's/^/ /g' <<< "$(distro-bootstrap-commands)")) |
grep -E -v '^ *$'
}
vm-bootstrap() {
distro-bootstrap-commands | vm-pipe-to-file "./e2e-bootstrap.sh"
vm-command "sh ./e2e-bootstrap.sh"
host-wait-vm-ssh-server --timeout 600
}
vm-image-url() {
distro-image-url
}
vm-ssh-user() {
if [ -n "$VM_SSH_USER" ]; then
echo "$VM_SSH_USER"
else
distro-ssh-user
fi
}
vm-check-env() {
# If VM IP address is already defined, govm is not needed.
if [ -n "$VM_IP" ]; then
if [ "x$(vm-command-q "whoami")" != "xroot" ]; then
echo "ERROR:"
echo "ERROR: environment check failed:"
echo "ERROR: cannot run commands (with sudo) when connecting"
echo "ERROR: $SSH $VM_SSH_USER@$VM_IP"
echo "ERROR:"
return 1
fi
return 0
fi
# Check that VM created/managed with govm in this environment.
type -p govm >& /dev/null || {
echo "ERROR:"
echo "ERROR: environment check failed:"
echo "ERROR: govm binary not found."
echo "ERROR:"
echo "ERROR: You can install it using the following commands:"
echo "ERROR:"
echo "ERROR: git clone https://github.com/govm-project/govm"
echo "ERROR: cd govm"
echo "ERROR: go build -o govm"
echo "ERROR: cp -v govm \$GOPATH/bin"
echo "ERROR: docker build . -t govm/govm:latest"
echo "ERROR: cd .."
echo "ERROR:"
return 1
}
docker inspect govm/govm >& /dev/null || {
echo "ERROR:"
echo "ERROR: environment check failed:"
echo "ERROR: govm/govm docker image not present (but govm needs it)."
echo "ERROR:"
echo "ERROR: You can install it using the following commands:"
echo "ERROR:"
echo "ERROR: git clone https://github.com/govm-project/govm"
echo "ERROR: cd govm"
echo "ERROR: docker build . -t govm/govm:latest"
echo "ERROR: cd .."
echo "ERROR:"
return 1
}
if [ ! -e "$SSH_KEY".pub ]; then
echo "ERROR:"
echo "ERROR: environment check failed:"
echo "ERROR: $SSH_KEY.pub SSH public key not found (but govm needs it)."
echo "ERROR:"
echo "ERROR: You can generate it using the following command:"
echo "ERROR:"
echo "ERROR: ssh-keygen"
echo "ERROR:"
return 1
fi
if [ -n "$SSH_AUTH_SOCK" ] && [ -e "$SSH_AUTH_SOCK" ]; then
if ! ssh-add -l | grep -q "$(ssh-keygen -l -f "$SSH_KEY" < /dev/null 2>/dev/null | awk '{print $2}')"; then
if ! ssh-add "$SSH_KEY" < /dev/null; then
echo "ERROR:"
echo "ERROR: environment setup failed:"
echo "ERROR: Failed to load $SSH_KEY SSH key to agent."
echo "ERROR:"
echo "ERROR: Please make sure an SSH agent is running, then"
echo "ERROR: try loading the key using the following command:"
echo "ERROR:"
echo "ERROR: ssh-add $SSH_KEY"
echo "ERROR:"
return 1
fi
fi
else
if host-is-encrypted-ssh-key "$SSH_KEY"; then
echo "ERROR:"
echo "ERROR: environment setup failed:"
echo "ERROR: $SSH_KEY SSH key is encrypted, but agent is not running."
echo "ERROR:"
echo "ERROR: Please make sure an SSH agent is running, then"
echo "ERROR: try loading the key using the following command:"
echo "ERROR:"
echo "ERROR: ssh-add $SSH_KEY"
echo "ERROR:"
return 1
fi
fi
}
vm-check-running-binary() {
local bin_file="$1"
local bin_name
bin_name="$(basename "$bin_file")"
pid_of_bin="$(vm-command-q "pidof $bin_name")"
if [ -f "$bin_file" ] && [ -n "$pid_of_bin" ] && [ "$(vm-command-q "md5sum < /proc/$pid_of_bin/exe")" != "$(md5sum < "$bin_file")" ]; then
echo "WARNING:"
echo "WARNING: Running $bin_name binary is different from"
echo "WARNING: $bin_file"
echo "WARNING: Consider restarting with reinstall_${bin_name//-/_}=1."
echo "WARNING:"
sleep "${warning_delay:-0}"
return 1
fi
return 0
}
vm-check-source-files-changed() {
local bin_change
local src_change
local src_dir="$1"
local bin_file="$2"
bin_change=$(stat --format "%Z" "$bin_file")
src_change=$(find "$src_dir" -name '*.go' -type f -print0 | xargs -0 stat --format "%Z" | sort -n | tail -n 1)
if [[ "$src_change" > "$bin_change" ]]; then
echo "WARNING:"
echo "WARNING: Source files changed, outdated binaries in"
echo "WARNING: $(dirname "$bin_file")/"
echo "WARNING:"
sleep "${warning_delay:-0}"
fi
}
vm-command() { # script API
# Usage: vm-command COMMAND
#
# Execute COMMAND on virtual machine as root.
# Returns the exit status of the execution.
# Environment variable COMMAND_OUTPUT contains what COMMAND printed
# in standard output and error.
#
# Examples:
# vm-command "kubectl get pods"
# vm-command "whoami | grep myuser" || command-error "user is not myuser"
command-start "vm" "$VM_PROMPT" "$1"
if [ "$2" == "bg" ]; then
( $SSH "${VM_SSH_USER}@${VM_IP}" sudo bash -l <<<"$COMMAND" 2>&1 | command-handle-output ;
command-end "${PIPESTATUS[0]}"
) &
command-runs-in-bg
else
$SSH "${VM_SSH_USER}@${VM_IP}" sudo bash -l <<<"$COMMAND" 2>&1 | command-handle-output ;
command-end "${PIPESTATUS[0]}"
fi
return "$COMMAND_STATUS"
}
vm-command-q() {
$SSH "${VM_SSH_USER}@${VM_IP}" sudo bash -l <<<"$1"
}
vm-mem-hotplug() { # script API
# Usage: vm-mem-hotplug MEMORY
#
# Hotplug currently unplugged MEMORY to VM.
# Find unplugged memory with "vm-mem-hw | grep unplugged".
#
# Examples:
# vm-mem-hotplug mem2
local memmatch memline memid memdimm memnode memdriver
memmatch=$1
if [ -z "$memmatch" ]; then
error "missing MEMORY"
return 1
fi
memline="$(vm-mem-hw | grep unplugged | grep "$memmatch")"
if [ -z "$memline" ]; then
error "unplugged memory matching '$memmatch' not found"
return 1
fi
memid="$(awk '{print $1}' <<< "$memline")"
memid=${memid#mem}
memid=${memid%[: ]*}
memdimm="$(awk '{print $2}' <<< "$memline")"
memnode="$(awk '{print $4}' <<< "$memline")"
memnode=${memnode#node}
if [ "$memdimm" == "nvdimm" ]; then
memdriver="nvdimm"
else
memdriver="pc-dimm"
fi
vm-monitor "device_add ${memdriver},id=${memdimm}${memid},memdev=mem${memdimm}_${memid}_node_${memnode},node=${memnode}"
}
vm-mem-hotremove() { # script API
# Usage: vm-mem-hotremove MEMORY
#
# Hotremove currently plugged MEMORY from VM.
# Find plugged memory with "vm-mem-hw | grep ' plugged'".
#
# Examples:
# vm-mem-hotremove mem2
local memmatch memline memid memdimm memnode memdriver
memmatch=$1
if [ -z "$memmatch" ]; then
error "missing MEMORY"
return 1
fi
memline="$(vm-mem-hw | grep \ plugged | grep "$memmatch")"
if [ -z "$memline" ]; then
error "plugged memory matching '$memmatch' not found"
return 1
fi
memid="$(awk '{print $1}' <<< "$memline")"
memid=${memid#mem}
memid=${memid%[: ]*}
memdimm="$(awk '{print $2}' <<< "$memline")"
vm-monitor "device_del ${memdimm}${memid}"
}
vm-mem-hw() { # script API
# Usage: vm-mem-hw
#
# List VM memory hardware with current status.
# See also: vm-mem-hotplug, vm-mem-hotremove
vm-monitor "$(echo info memdev; echo info memory-devices)" | awk '
/memdev: /{
split($2,a,"_");
state[a[2]]="plugged ";
}
/memory backend: membuiltin/{
split($3,a,"_"); backend=1;
type[a[2]]="ram "; state[a[2]]="builtin "; node[a[2]]=a[4];
}
/memory backend: memnvbuiltin/{
split($3,a,"_"); backend=1;
type[a[2]]="nvram "; state[a[2]]="builtin "; node[a[2]]=a[4];
}
/memory backend: memnvdimm/{
split($3,a,"_"); backend=1;
type[a[2]]="nvdimm "; state[a[2]]="unplugged"; node[a[2]]=a[4];
}
/memory backend: memdimm/{
split($3,a,"_"); backend=1;
type[a[2]]="dimm "; state[a[2]]="unplugged"; node[a[2]]=a[4];
}
/size: /{sz=$2/1024/1024; if (backend==1) {size[a[2]]=sz;backend=0;}}
END{
for (m in node) print "mem"m": "type[m]" "state[m]" node"node[m]" size="size[m]"M";
}'
}
vm-monitor() { # script API
# Usage: vm-monitor COMMAND
#
# Execute COMMAND on Qemu monitor.
#
# Example: VM monitor help:
# vm-monitor "help" | less
#
# Example: print memdev objects and plugged in memory devices:
# vm-monitor "info memdev"
# vm-monitor "info memory-devices"
#
# Example: hot plug a NVDIMM to NUMA node 1 when launched with topology
# topology='[{"cores":2,"mem":"2G"},{"nvmem":"4G","dimm":"unplugged"}]':
# vm-monitor "device_add pc-dimm,id=nvdimm0,memdev=nvmem0,node=1"
[ -n "$VM_MONITOR" ] ||
error "VM is not running"
eval "$VM_MONITOR" <<< "$1" | sed 's/\r//g'
if [ "${PIPESTATUS[0]}" != "0" ]; then
error "sending command to Qemu monitor failed"
fi
echo ""
}
vm-wait-process() { # script API
# Usage: vm-wait-process [--timeout TIMEOUT] PROCESS
#
# Wait for a PROCESS (string) to appear in process list (ps -A output).
# The default TIMEOUT is 30 seconds.
local process timeout invalid
timeout=30
while [ "${1#-}" != "$1" ] && [ -n "$1" ]; do
case "$1" in
--timeout)
timeout="$2"
shift; shift
;;
*)
invalid="${invalid}${invalid:+,}\"$1\""
shift
;;
esac
done
if [ -n "$invalid" ]; then
error "invalid options: $invalid"
return 1
fi
process="$1"
vm-run-until --timeout "$timeout" "ps -A | grep -q \"$process\""
}
vm-run-until() { # script API
# Usage: vm-run-until [--timeout TIMEOUT] CMD
#
# Keep running CMD (string) until it exits successfully.
# The default TIMEOUT is 30 seconds.
local cmd timeout invalid
timeout=30
while [ "${1#-}" != "$1" ] && [ -n "$1" ]; do
case "$1" in
--timeout)
timeout="$2"
shift; shift
;;
*)
invalid="${invalid}${invalid:+,}\"$1\""
shift
;;
esac
done
if [ -n "$invalid" ]; then
error "invalid options: $invalid"
return 1
fi
cmd="$1"
if ! vm-command-q "retry=$timeout; until $cmd; do retry=\$(( \$retry - 1 )); [ \"\$retry\" == \"0\" ] && exit 1; sleep 1; done"; then
error "waiting for command \"$cmd\" to exit successfully timed out after $timeout s"
fi
}
vm-write-file() {
local vm_path_file="$1"
local file_content_b64
file_content_b64="$(base64 <<<"$2")"
vm-command-q "mkdir -p $(dirname "$vm_path_file"); echo -n \"$file_content_b64\" | base64 -d > \"$vm_path_file\""
}
vm-put-file() { # script API
# Usage: vm-put-file [--cleanup] [--append] SRC-HOST-FILE DST-VM-FILE
#
# Copy SRC-HOST-FILE to DST-VM-FILE on the VM, removing
# SRC-HOST-FILE if called with the --cleanup flag, and
# appending instead of copying if the --append flag is
# specified.
#
# Example:
# src=$(mktemp) && \
# echo 'Ahoy, Matey...' > $src && \
# vm-put-file --cleanup $src /etc/motd
local cleanup append invalid
while [ "${1#-}" != "$1" ] && [ -n "$1" ]; do
case "$1" in
--cleanup)
cleanup=1
shift
;;
--append)
append=1
shift
;;
*)
invalid="${invalid}${invalid:+,}\"$1\""
shift
;;
esac
done
if [ -n "$cleanup" ] && [ -n "$1" ]; then
# shellcheck disable=SC2064
trap "rm -f \"$1\"" RETURN EXIT
fi
if [ -n "$invalid" ]; then
error "invalid options: $invalid"
return 1
fi
[ "$(dirname "$2")" == "." ] || vm-command-q "[ -d \"$(dirname "$2")\" ]" || vm-command "mkdir -p \"$(dirname "$2")\"" ||
command-error "cannot create vm-put-file destination directory to VM"
host-command "$SCP \"$1\" ${VM_SSH_USER}@${VM_IP}:\"vm-put-file.${1##*/}\"" ||
command-error "failed to copy file to VM"
if [ -z "$append" ]; then
vm-command "mv \"vm-put-file.${1##*/}\" \"$2\"" ||
command-error "failed to rename file"
else
vm-command "touch \"$2\" && cat \"vm-put-file.${1##*/}\" >> \"$2\" && rm -f \"vm-put-file.${1##*/}\"" ||
command-error "failed to append file"
fi
}
vm-put-pkg() { # script API
# Usage: vm-put-pkg [--force] HOST-FILE...
#
# Copies HOST-FILEs from host to vm and installs them.
#
# Examples:
# vm-put-pkg /tmp/kernel.rpm /tmp/myutil.rpm
local host_pkg
local vm_pkgs=""
local force=""
if [ "$1" == "--force" ]; then
force="--force "
shift
fi
for host_pkg in "$@"; do
local vm_pkg="pkgs/$(basename "$host_pkg")"
vm-command-q "mkdir -p $(dirname "$vm_pkg")"
vm-put-file "$host_pkg" "$vm_pkg"
vm_pkgs="$vm_pkgs $vm_pkg"
done
distro-install-pkg-local $force "$vm_pkgs"
}
vm-put-docker-image() { # script API
# Usage: vm-put-docker-image IMAGE
#
# Exports IMAGE from docker images on the host, and
# imports it in the "k8s.io" namespace (visible
# for kubernetes containers) on the vm.
#
# Works with containerd only.
#
# Examples:
# vm-put-docker-image busybox:latest
local image_name="$1"
local image_file_on_vm="images/${image_name//:/__}"
vm-command-q "mkdir -p $(dirname "$image_file_on_vm")"
docker save "$image_name" | vm-pipe-to-file "$image_file_on_vm" ||
error "failed to save and pipe image '$image_name'"
vm-cri-import-image "$image_name" "$image_file_on_vm"
}
vm-pipe-to-file() { # script API
# Usage: vm-pipe-to-file [--append] DST-VM-FILE
#
# Reads stdin and writes the content to DST-VM-FILE, creating any
# intermediate directories necessary.
#
# Example:
# echo 'Ahoy, Matey...' | vm-pipe-to-file /etc/motd
local tmp append
tmp="$(mktemp vm-pipe-to-file.XXXXXX)"
if [ "$1" = "--append" ]; then
append="--append"
shift
fi
cat > "$tmp"
vm-put-file --cleanup $append "$tmp" "$1"
}
vm-sed-file() { # script API
# Usage: vm-sed-file PATH-IN-VM SED-EXTENDED-REGEXP-COMMANDS
#
# Edits the given file in place with the given extended regexp
# sed commands.
#
# Example:
# vm-sed-file /etc/motd 's/Matey/Guybrush Threepwood/'
local file="$1" cmd
shift
for cmd in "$@"; do
vm-command "sed -E -i \"$cmd\" $file" ||
command-error "failed to edit $file with sed"
done
}
vm-set-kernel-cmdline() { # script API
# Usage: vm-set-kernel-cmdline E2E-DEFAULTS
#
# Adds/replaces E2E-DEFAULTS to kernel command line"
#
# Example:
# vm-set-kernel-cmdline nr_cpus=4
# vm-reboot
# vm-command "cat /proc/cmdline"
# launch cri-resmgr
distro-set-kernel-cmdline "$@"
}
vm-reboot() { # script API
# Usage: vm-reboot
#
# Reboots the virtual machine and waits that the ssh server starts
# responding again.
vm-command "reboot"
sleep 5
host-wait-vm-ssh-server
}
vm-setup-proxies() {
distro-setup-proxies
}
vm-networking() {
vm-command-q "touch /etc/hosts; grep -q \$(hostname) /etc/hosts" || {
vm-command "echo \"$VM_IP \$(hostname)\" >>/etc/hosts"
}
vm-setup-proxies
}
vm-install-cri-resmgr() {
prefix=/usr/local
# shellcheck disable=SC2154
if [ "$binsrc" == "github" ]; then
vm-install-golang
vm-install-pkg make
vm-command "go get -d -v github.com/intel/cri-resource-manager"
CRI_RESMGR_SOURCE_DIR=$(awk '/package.*cri-resource-manager/{print $NF}' <<< "$COMMAND_OUTPUT")
vm-command "cd $CRI_RESMGR_SOURCE_DIR && make install && cd -"
elif [ "${binsrc#packages/}" != "$binsrc" ]; then
suf=$(vm-pkg-type)
vm-command "rm -f *.$suf"
local pkg_count
# shellcheck disable=SC2010,SC2126
pkg_count="$(ls "$HOST_PROJECT_DIR/$binsrc"/cri-resource-manager*."$suf" | grep -v dbg | wc -l)"
if [ "$pkg_count" == "0" ]; then
error "installing from $binsrc failed: cannot find cri-resource-manager_*.$suf from $HOST_PROJECT_DIR/$binsrc"
elif [[ "$pkg_count" -gt 1 ]]; then
error "installing from $binsrc failed: expected exactly one cri-resource-manager*.$suf in $HOST_PROJECT_DIR/$binsrc, found $pkg_count alternatives."
fi
host-command "$SCP $HOST_PROJECT_DIR/$binsrc/*.$suf $VM_SSH_USER@$VM_IP:/tmp" || {
command-error "copying *.$suf to vm failed, run \"make cross-$suf\" first"
}
vm-install-pkg "/tmp/cri-resource-manager*.$suf" || {
command-error "installing packages failed"
}
vm-command "systemctl daemon-reload"
elif [ -z "$binsrc" ] || [ "$binsrc" == "local" ]; then
vm-put-file "$BIN_DIR/cri-resmgr" "$prefix/bin/cri-resmgr"
vm-put-file "$BIN_DIR/cri-resmgr-agent" "$prefix/bin/cri-resmgr-agent"
else
error "vm-install-cri-resmgr: unknown binsrc=\"$binsrc\""
fi
}
vm-install-cri-resmgr-agent() {
prefix=/usr/local
local bin_change
local src_change
bin_change=$(stat --format "%Z" "$BIN_DIR/cri-resmgr-agent")
src_change=$(find "$HOST_PROJECT_DIR" -name '*.go' -type f -print0 | xargs -0 stat --format "%Z" | sort -n | tail -n 1)
if [[ "$src_change" > "$bin_change" ]]; then
echo "WARNING:"
echo "WARNING: Source files changed - installing possibly outdated binaries from"
echo "WARNING: $BIN_DIR/"
echo "WARNING:"
sleep "${warning_delay:-0}"
fi
vm-put-file "$BIN_DIR/cri-resmgr-agent" "$prefix/bin/cri-resmgr-agent"
}
vm-cri-import-image() {
local image_name="$1"
local image_tar="$2"
case "$VM_CRI" in
containerd)
vm-command "ctr -n k8s.io images import '$image_tar'" ||
command-error "failed to import \"$image_tar\" on VM"
;;
*)
error "vm-cri-import-image unsupported container runtime: \"$VM_CRI\""
esac
}
vm-install-cri-resmgr-webhook() {
local service=cri-resmgr-webhook
local namespace=cri-resmgr
vm-command-q "\
kubectl delete secret -n ${namespace} cri-resmgr-webhook-secret 2>/dev/null; \
kubectl delete csr ${service}.${namespace} 2>/dev/null; \
kubectl delete -f webhook/mutating-webhook-config.yaml 2>/dev/null; \
kubectl delete -f webhook/webhook-deployment.yaml 2>/dev/null; \
"
local webhook_image_info webhook_image_id webhook_image_repotag webhook_image_tar
webhook_image_info="$(docker images --filter=reference=cri-resmgr-webhook --format '{{.ID}} {{.Repository}}:{{.Tag}} (created {{.CreatedSince}}, {{.CreatedAt}})' | head -n 1)"
if [ -z "$webhook_image_info" ]; then
error "cannot find cri-resmgr-webhook image on host, run \"make images\" and check \"docker images --filter=reference=cri-resmgr-webhook\""
fi
echo "installing webhook to VM from image: $webhook_image_info"
sleep 2
webhook_image_id="$(awk '{print $1}' <<< "$webhook_image_info")"
webhook_image_repotag="$(awk '{print $2}' <<< "$webhook_image_info")"
webhook_image_tar="$(realpath "$OUTPUT_DIR/webhook-image-$webhook_image_id.tar")"
# It is better to export (save) the image with image_repotag rather than image_id
# because otherwise manifest.json RepoTags will be null and containerd will
# remove the image immediately after impoting it as part of garbage collection.
docker image save "$webhook_image_repotag" > "$webhook_image_tar"
vm-put-file "$webhook_image_tar" "webhook/$(basename "$webhook_image_tar")" || {
command-error "copying webhook image to VM failed"
}
vm-cri-import-image cri-resmgr-webhook "webhook/$(basename "$webhook_image_tar")"
# Create a self-signed certificate with SANs
vm-command "openssl req -x509 -newkey rsa:2048 -sha256 -days 365 -nodes -keyout webhook/server-key.pem -out webhook/server-crt.pem -subj '/CN=${service}.${namespace}.svc' -addext 'subjectAltName=DNS:${service},DNS:${service}.${namespace},DNS:${service}.${namespace}.svc'" ||
command-error "creating self-signed certificate failed, requires openssl >= 1.1.1"
# Allow webhook to run on node tainted by cmk=true
sed -e "s|IMAGE_PLACEHOLDER|$webhook_image_repotag|" \
-e 's|^\(\s*\)tolerations:$|\1tolerations:\n\1 - {"key": "cmk", "operator": "Equal", "value": "true", "effect": "NoSchedule"}|g' \
-e 's/imagePullPolicy: Always/imagePullPolicy: Never/' \
< "${HOST_PROJECT_DIR}/cmd/cri-resmgr-webhook/webhook-deployment.yaml" \
| vm-pipe-to-file webhook/webhook-deployment.yaml
# Create secret that contains svc.crt and svc.key for webhook deployment
local server_crt_b64 server_key_b64
server_crt_b64="$(vm-command-q "cat webhook/server-crt.pem" | base64 -w 0)"
server_key_b64="$(vm-command-q "cat webhook/server-key.pem" | base64 -w 0)"
cat <<EOF | vm-pipe-to-file --append webhook/webhook-deployment.yaml
---
apiVersion: v1
kind: Secret
metadata:
name: cri-resmgr-webhook-secret
namespace: cri-resmgr
data:
svc.crt: ${server_crt_b64}
svc.key: ${server_key_b64}
type: Opaque
EOF
local cabundle_b64
cabundle_b64="$server_crt_b64"
sed -e "s/CA_BUNDLE_PLACEHOLDER/${cabundle_b64}/" \
< "${HOST_PROJECT_DIR}/cmd/cri-resmgr-webhook/mutating-webhook-config.yaml" \
| vm-pipe-to-file webhook/mutating-webhook-config.yaml
}
vm-pkg-type() {
distro-pkg-type
}
vm-install-pkg() {
distro-install-pkg "$@"
}
vm-setup-oneshot() {
local util
( distro-refresh-pkg-db ) || true
distro-setup-oneshot
distro-install-utils
# Verify that all required utilities exit on the VM.
for util in pidof killall; do
vm-command-q "command -v $util >/dev/null" || {
error "required command '$util' missing on VM, fix/implement $distro-install-utils()"
}
done
}
vm-install-golang() {
distro-install-golang
}
vm-install-runc() {
local host_runc="$runc_src/runc"
local vm_runc="/usr/sbin/runc"
if [ -n "$runc_src" ]; then
# Check if runc is already installed on VM.
# If it is, replace existing binary with local build."
vm-command 'command -v runc'
if [ -n "$COMMAND_OUTPUT" ] && [ "x$COMMAND_STATUS" == "x0" ]; then
vm_runc="$COMMAND_OUTPUT"
fi
vm-put-file "$host_runc" "$vm_runc"
else
distro-install-runc
fi
}
vm-install-cri() {
distro-install-"$VM_CRI"
distro-config-"$VM_CRI"
if [ "$VM_CRI" == "containerd" ]; then
if [ -n "$containerd_src" ]; then
vm-command "systemctl stop containerd"
for f in ctr containerd containerd-stress containerd-shim containerd-shim-runc-v1 containerd-shim-runc-v2; do
vm-put-file "$containerd_src/bin/$f" "/usr/bin/$f"
done
vm-command "systemctl start containerd"
fi
elif [ "$VM_CRI" == "crio" ]; then
if [ -n "$crio_src" ]; then
vm-command "systemctl stop crio"
for f in crio crio-status pinns; do
vm-put-file "$crio_src/bin/$f" "/usr/bin/$f"
done
vm-command "systemctl enable crio"
vm-command "systemctl start crio"
fi
fi
}
vm-install-containernetworking() {
vm-install-golang
vm-command "GO111MODULE=off go get -d github.com/containernetworking/plugins"
CNI_PLUGINS_SOURCE_DIR="$(awk '/package.*plugins/{print $NF}' <<< "$COMMAND_OUTPUT")"
[ -n "$CNI_PLUGINS_SOURCE_DIR" ] || {
command-error "downloading containernetworking plugins failed"
}
vm-command "pushd \"$CNI_PLUGINS_SOURCE_DIR\" && ./build_linux.sh && mkdir -p /opt/cni && cp -rv bin /opt/cni && popd" || {
command-error "building and installing cri-tools failed"
}
vm-command "rm -rf /etc/cni/net.d && mkdir -p /etc/cni/net.d && cat > /etc/cni/net.d/10-bridge.conf <<EOF
{
\"cniVersion\": \"0.4.0\",
\"name\": \"mynet\",
\"type\": \"bridge\",
\"bridge\": \"cni0\",
\"isGateway\": true,
\"ipMasq\": true,
\"ipam\": {
\"type\": \"host-local\",
\"subnet\": \"$CNI_SUBNET\",
\"routes\": [
{ \"dst\": \"0.0.0.0/0\" }
]
}
}
EOF"
vm-command 'cat > /etc/cni/net.d/20-portmap.conf <<EOF
{
"cniVersion": "0.4.0",
"type": "portmap",
"capabilities": {"portMappings": true},
"snat": true
}
EOF'
vm-command 'cat > /etc/cni/net.d/99-loopback.conf <<EOF
{
"cniVersion": "0.4.0",
"name": "lo",
"type": "loopback"
}
EOF'
}
vm-install-dlv() {
vm-install-golang
vm-install-pkg rsync
vm-command "go get github.com/go-delve/delve/cmd/dlv" || {
command-error "installing delve failed"
}
echo '[ "`id -u`" -eq 0 ] && PATH=$PATH:/root/go/bin' | vm-pipe-to-file /etc/profile.d/root-path-go.sh
vm-command "mkdir -p \"\$HOME/.config/dlv/config.yml.d\""
vm-command "echo 'substitute-path:' > \"\$HOME/.config/dlv/config.yml.d/00-substitute-path\""
}
vm-dlv-add-src() {
local host_src_dir="$1"
[ -d "$host_src_dir" ] || error "vm-dlv-add-src: invalid source directory \"$host_src_dir\", existing go project directory expected"
vm-command "mkdir -p /home/$VM_SSH_USER/src; chmod a+rwX /home/$VM_SSH_USER/src"
host-command "cd \"$host_src_dir/..\" && rsync -avz --include \"*/\" --include \"**/*.go\" --exclude \"*\" \"$(basename "$host_src_dir")\" $VM_SSH_USER@$VM_IP:src/"
vm-command "echo ' - {from: \"$host_src_dir\", to: \"/home/$VM_SSH_USER/src/$(basename "$host_src_dir")\"}' > \"\$HOME/.config/dlv/config.yml.d/01-$(basename "$host_src_dir")\""
vm-dlv-update-config
}
vm-dlv-update-config() {
vm-command "cat \$HOME/.config/dlv/config.yml.d/* > \$HOME/.config/dlv/config.yml"
}
vm-install-k8s() {
distro-install-k8s
distro-restart-$VM_CRI
}
vm-create-singlenode-cluster() {
if ! [ "$(type -t vm-install-cni-$(distro-k8s-cni))" == "function" ]; then
error "invalid CNI: $(distro-k8s-cni)"
fi
vm-create-cluster
vm-command "kubectl taint nodes --all node-role.kubernetes.io/master-"
vm-install-cni-"$(distro-k8s-cni)"
if ! vm-command "kubectl wait --for=condition=Ready node/\$(hostname) --timeout=120s"; then
command-error "kubectl waiting for node readiness timed out"
fi
}
vm-create-cluster() {
vm-command "kubeadm init --pod-network-cidr=$CNI_SUBNET --cri-socket ${k8scri_sock}"
if ! grep -q "initialized successfully" <<< "$COMMAND_OUTPUT"; then
command-error "kubeadm init failed"
fi
vm-command "mkdir -p \$HOME/.kube"
vm-command "cp /etc/kubernetes/admin.conf \$HOME/.kube/config"
vm-command "mkdir -p ~root/.kube"
vm-command "cp /etc/kubernetes/admin.conf ~root/.kube/config"
}
vm-destroy-cluster() {
vm-command "yes | kubeadm reset; rm -f \$HOME/.kube/config ~root/.kube/config /etc/kubernetes"
}
vm-install-cni-cilium() {
if ! vm-command "curl -L --remote-name-all https://github.com/cilium/cilium-cli/releases/latest/download/cilium-linux-amd64.tar.gz && tar xzvfC cilium-linux-amd64.tar.gz /usr/local/bin && cilium install && rm -f cilium-linux-amd64.tar.gz"; then
command-error "installing cilium CNI to Kubernetes failed"
fi
}
vm-install-cni-weavenet() {
vm-command "kubectl apply -f \"https://cloud.weave.works/k8s/net?k8s-version=\$(kubectl version | base64 | tr -d '\n')\""
if ! vm-command "kubectl rollout status --timeout=360s -n kube-system daemonsets/weave-net"; then
command-error "installing weavenet CNI to Kubernetes failed/timed out"
fi
}
vm-install-cni-flannel() {
vm-command "kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml"
if ! vm-command "kubectl rollout status --timeout=360s -n kube-system daemonsets/kube-flannel-ds"; then
command-error "installing flannel CNI to Kubernetes failed/timed out"
fi
}
vm-print-usage() {
echo "- Login VM: ssh $VM_SSH_USER@$VM_IP"
echo "- Stop VM: govm stop $VM_NAME"
echo "- Delete VM: govm delete $VM_NAME"
}
vm-check-env || exit 1