-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.go
1724 lines (1525 loc) · 51 KB
/
main.go
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
package main
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"math"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/alessio/shellescape"
"github.com/cilium/cilium/pkg/mac"
"github.com/containerd/cgroups/v3"
"github.com/containerd/cgroups/v3/cgroup1"
"github.com/containerd/cgroups/v3/cgroup2"
"github.com/digitalocean/go-qemu/qmp"
"github.com/docker/libnetwork/types"
"github.com/jpillora/backoff"
"github.com/kdomanski/iso9660"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/vishvananda/netlink"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"k8s.io/apimachinery/pkg/api/resource"
vmv1 "github.com/neondatabase/autoscaling/neonvm/apis/neonvm/v1"
"github.com/neondatabase/autoscaling/pkg/api"
)
const (
QEMU_BIN = "qemu-system-x86_64"
QEMU_IMG_BIN = "qemu-img"
defaultKernelPath = "/vm/kernel/vmlinuz"
baseKernelCmdline = "panic=-1 init=/neonvm/bin/init memhp_default_state=online_movable console=ttyS1 loglevel=7 root=/dev/vda rw"
rootDiskPath = "/vm/images/rootdisk.qcow2"
runtimeDiskPath = "/vm/images/runtime.iso"
mountedDiskPath = "/vm/images"
qmpUnixSocketForSigtermHandler = "/vm/qmp-sigterm.sock"
logSerialSocket = "/vm/log.sock"
bufferedReaderSize = 4096
sshAuthorizedKeysDiskPath = "/vm/images/ssh-authorized-keys.iso"
sshAuthorizedKeysMountPoint = "/vm/ssh"
swapName = "swapdisk"
defaultNetworkBridgeName = "br-def"
defaultNetworkTapName = "tap-def"
defaultNetworkCIDR = "169.254.254.252/30"
overlayNetworkBridgeName = "br-overlay"
overlayNetworkTapName = "tap-overlay"
// defaultPath is the default path to the resolv.conf that contains information to resolve DNS. See Path().
resolveDefaultPath = "/etc/resolv.conf"
// alternatePath is a path different from defaultPath, that may be used to resolve DNS. See Path().
resolveAlternatePath = "/run/systemd/resolve/resolv.conf"
// cgroupPeriod is the period for evaluating cgroup quota
// in microseconds. Min 1000 microseconds, max 1 second
cgroupPeriod = uint64(100000)
cgroupMountPoint = "/sys/fs/cgroup"
// cpuLimitOvercommitFactor sets the amount above the VM's spec.guest.cpus.use that we set the
// QEMU cgroup's CPU limit to. e.g. if cpuLimitOvercommitFactor = 3 and the VM is using 0.5
// CPUs, we set the cgroup to limit QEMU+VM to 1.5 CPUs.
//
// This exists because setting the cgroup exactly equal to the VM's CPU value is overly
// pessimistic, results in a lot of unused capacity on the host, and particularly impacts
// operations that parallelize between the VM and QEMU, like heavy disk access.
//
// See also: https://neondb.slack.com/archives/C03TN5G758R/p1693462680623239
cpuLimitOvercommitFactor = 4
)
var (
ipv4NumBlock = `(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)`
ipv4Address = `(` + ipv4NumBlock + `\.){3}` + ipv4NumBlock
ipv6Address = `([0-9A-Fa-f]{0,4}:){2,7}([0-9A-Fa-f]{0,4})(%\w+)?`
nsRegexp = regexp.MustCompile(`^\s*nameserver\s*((` + ipv4Address + `)|(` + ipv6Address + `))\s*$`)
nsIPv4Regexpmatch = regexp.MustCompile(`^\s*nameserver\s*((` + ipv4Address + `))\s*$`)
nsIPv6Regexpmatch = regexp.MustCompile(`^\s*nameserver\s*((` + ipv6Address + `))\s*$`)
searchRegexp = regexp.MustCompile(`^\s*search\s*(([^\s]+\s*)*)$`)
detectSystemdResolvConfOnce sync.Once
pathAfterSystemdDetection = resolveDefaultPath
)
// File contains the resolv.conf content and its hash
type resolveFile struct {
Content []byte
Hash string
}
// Get returns the contents of /etc/resolv.conf and its hash
func getResolvConf() (*resolveFile, error) {
return getSpecific(resolvePath())
}
// hashData returns the sha256 sum of src.
// from https://github.com/moby/moby/blob/v20.10.24/pkg/ioutils/readers.go#L52-L59
func hashData(src io.Reader) (string, error) {
h := sha256.New()
if _, err := io.Copy(h, src); err != nil {
return "", err
}
return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
}
// GetSpecific returns the contents of the user specified resolv.conf file and its hash
func getSpecific(path string) (*resolveFile, error) {
resolv, err := os.ReadFile(path)
if err != nil {
return nil, err
}
hash, err := hashData(bytes.NewReader(resolv))
if err != nil {
return nil, err
}
return &resolveFile{Content: resolv, Hash: hash}, nil
}
// GetNameservers returns nameservers (if any) listed in /etc/resolv.conf
func getNameservers(resolvConf []byte, kind int) []string {
nameservers := []string{}
for _, line := range getLines(resolvConf, []byte("#")) {
var ns [][]byte
if kind == types.IP {
ns = nsRegexp.FindSubmatch(line)
} else if kind == types.IPv4 {
ns = nsIPv4Regexpmatch.FindSubmatch(line)
} else if kind == types.IPv6 {
ns = nsIPv6Regexpmatch.FindSubmatch(line)
}
if len(ns) > 0 {
nameservers = append(nameservers, string(ns[1]))
}
}
return nameservers
}
// GetSearchDomains returns search domains (if any) listed in /etc/resolv.conf
// If more than one search line is encountered, only the contents of the last
// one is returned.
func getSearchDomains(resolvConf []byte) []string {
domains := []string{}
for _, line := range getLines(resolvConf, []byte("#")) {
match := searchRegexp.FindSubmatch(line)
if match == nil {
continue
}
domains = strings.Fields(string(match[1]))
}
return domains
}
// getLines parses input into lines and strips away comments.
func getLines(input []byte, commentMarker []byte) [][]byte {
lines := bytes.Split(input, []byte("\n"))
var output [][]byte
for _, currentLine := range lines {
var commentIndex = bytes.Index(currentLine, commentMarker)
if commentIndex == -1 {
output = append(output, currentLine)
} else {
output = append(output, currentLine[:commentIndex])
}
}
return output
}
func resolvePath() string {
detectSystemdResolvConfOnce.Do(func() {
candidateResolvConf, err := os.ReadFile(resolveDefaultPath)
if err != nil {
// silencing error as it will resurface at next calls trying to read defaultPath
return
}
ns := getNameservers(candidateResolvConf, types.IP)
if len(ns) == 1 && ns[0] == "127.0.0.53" {
pathAfterSystemdDetection = resolveAlternatePath
}
})
return pathAfterSystemdDetection
}
func createISO9660runtime(
diskPath string,
command []string,
args []string,
sysctl []string,
env []vmv1.EnvVar,
disks []vmv1.Disk,
enableSSH bool,
swapInfo *vmv1.SwapInfo,
shmsize *resource.Quantity,
) error {
writer, err := iso9660.NewWriter()
if err != nil {
return err
}
defer writer.Cleanup() //nolint:errcheck // Nothing to do with the error, maybe log it ? TODO
if len(sysctl) != 0 {
err = writer.AddFile(bytes.NewReader([]byte(strings.Join(sysctl, "\n"))), "sysctl.conf")
if err != nil {
return err
}
}
if len(command) != 0 {
err = writer.AddFile(bytes.NewReader([]byte(shellescape.QuoteCommand(command))), "command.sh")
if err != nil {
return err
}
}
if len(args) != 0 {
err = writer.AddFile(bytes.NewReader([]byte(shellescape.QuoteCommand(args))), "args.sh")
if err != nil {
return err
}
}
if len(env) != 0 {
envstring := []string{}
for _, e := range env {
envstring = append(envstring, fmt.Sprintf(`export %s=%s`, e.Name, shellescape.Quote(e.Value)))
}
envstring = append(envstring, "")
err = writer.AddFile(bytes.NewReader([]byte(strings.Join(envstring, "\n"))), "env.sh")
if err != nil {
return err
}
}
mounts := []string{
"set -euxo pipefail",
}
if enableSSH {
mounts = append(mounts, "/neonvm/bin/mkdir -p /mnt/ssh")
mounts = append(mounts, "/neonvm/bin/mount -o ro,mode=0644 $(/neonvm/bin/blkid -L ssh-authorized-keys) /mnt/ssh")
}
if swapInfo != nil && (swapInfo.SkipSwapon == nil || !*swapInfo.SkipSwapon) {
mounts = append(mounts, fmt.Sprintf("/neonvm/bin/sh /neonvm/runtime/resize-swap-internal.sh %d", swapInfo.Size.Value()))
}
if len(disks) != 0 {
for _, disk := range disks {
if disk.MountPath != "" {
mounts = append(mounts, fmt.Sprintf(`/neonvm/bin/mkdir -p %s`, disk.MountPath))
}
switch {
case disk.EmptyDisk != nil:
opts := ""
if disk.EmptyDisk.Discard {
opts = "-o discard"
}
mounts = append(mounts, fmt.Sprintf(`/neonvm/bin/mount %s $(/neonvm/bin/blkid -L %s) %s`, opts, disk.Name, disk.MountPath))
// Note: chmod must be after mount, otherwise it gets overwritten by mount.
mounts = append(mounts, fmt.Sprintf(`/neonvm/bin/chmod 0777 %s`, disk.MountPath))
case disk.ConfigMap != nil || disk.Secret != nil:
mounts = append(mounts, fmt.Sprintf(`/neonvm/bin/mount -o ro,mode=0644 $(/neonvm/bin/blkid -L %s) %s`, disk.Name, disk.MountPath))
case disk.Tmpfs != nil:
mounts = append(mounts, fmt.Sprintf(`/neonvm/bin/chmod 0777 %s`, disk.MountPath))
mounts = append(mounts, fmt.Sprintf(`/neonvm/bin/mount -t tmpfs -o size=%d %s %s`, disk.Tmpfs.Size.Value(), disk.Name, disk.MountPath))
default:
// do nothing
}
}
}
if shmsize != nil {
mounts = append(mounts, fmt.Sprintf(`/neonvm/bin/mount -o remount,size=%d /dev/shm`, shmsize.Value()))
}
mounts = append(mounts, "")
err = writer.AddFile(bytes.NewReader([]byte(strings.Join(mounts, "\n"))), "mounts.sh")
if err != nil {
return err
}
if swapInfo != nil {
lines := []string{
`#!/neonvm/bin/sh`,
`set -euxo pipefail`,
// this script may be run as root, so we should avoid potentially-malicious path
// injection
`export PATH="/neonvm/bin"`,
fmt.Sprintf(`swapdisk="$(/neonvm/bin/blkid -L %s)"`, swapName),
// disable swap. Allow it to fail if it's already disabled.
`swapoff "$swapdisk" || true`,
// if the requested size is zero, then... just exit. There's nothing we need to do.
`new_size="$1"`,
`if [ "$new_size" = '0' ]; then exit 0; fi`,
// re-make the swap.
// mkswap expects the size to be given in KiB, so divide the new size by 1K
fmt.Sprintf(`mkswap -L %s "$swapdisk" $(( new_size / 1024 ))`, swapName),
// ... and then re-enable the swap
//
// nb: busybox swapon only supports '-d', not its long form '--discard'.
`swapon -d "$swapdisk"`,
}
err = writer.AddFile(bytes.NewReader([]byte(strings.Join(lines, "\n"))), "resize-swap-internal.sh")
if err != nil {
return err
}
}
outputFile, err := os.OpenFile(diskPath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err != nil {
return err
}
// uid=36(qemu) gid=34(kvm) groups=34(kvm)
err = outputFile.Chown(36, 34)
if err != nil {
return err
}
err = writer.WriteTo(outputFile, "vmruntime")
if err != nil {
return err
}
err = outputFile.Close()
if err != nil {
return err
}
return nil
}
func calcDirUsage(dirPath string) (int64, error) {
stat, err := os.Lstat(dirPath)
if err != nil {
return 0, err
}
size := stat.Size()
if !stat.IsDir() {
return size, nil
}
dir, err := os.Open(dirPath)
if err != nil {
return size, err
}
defer dir.Close()
files, err := dir.Readdir(-1)
if err != nil {
return size, err
}
for _, file := range files {
if file.Name() == "." || file.Name() == ".." {
continue
}
s, err := calcDirUsage(dirPath + "/" + file.Name())
if err != nil {
return size, err
}
size += s
}
return size, nil
}
func createSwap(diskPath string, swapInfo vmv1.SwapInfo) error {
diskSize := swapInfo.Size
tmpRawFile := "swap.raw"
if err := execFg(QEMU_IMG_BIN, "create", "-q", "-f", "raw", tmpRawFile, fmt.Sprintf("%d", diskSize.Value())); err != nil {
return err
}
// Even if swapInfo.SkipSwapon, we still need to mkswap to propagate the label.
if err := execFg("mkswap", "-L", swapName, tmpRawFile); err != nil {
return err
}
if err := execFg(QEMU_IMG_BIN, "convert", "-q", "-f", "raw", "-O", "qcow2", "-o", "cluster_size=2M,lazy_refcounts=on", tmpRawFile, diskPath); err != nil {
return err
}
if err := execFg("rm", "-f", tmpRawFile); err != nil {
return err
}
// uid=36(qemu) gid=34(kvm) groups=34(kvm)
if err := execFg("chown", "36:34", diskPath); err != nil {
return err
}
return nil
}
func createQCOW2(diskName string, diskPath string, diskSize *resource.Quantity, contentPath *string) error {
ext4blocksMin := int64(64)
ext4blockSize := int64(4096)
ext4blockCount := int64(0)
if diskSize != nil {
ext4blockCount = diskSize.Value() / ext4blockSize
} else if contentPath != nil {
dirSize, err := calcDirUsage(*contentPath)
if err != nil {
return err
}
ext4blockCount = int64(math.Ceil(float64(ext4blocksMin) + float64((dirSize / ext4blockSize))))
} else {
return errors.New("diskSize or contentPath should be specified")
}
if contentPath == nil {
if err := execFg("mkfs.ext4", "-q", "-L", diskName, "-b", fmt.Sprintf("%d", ext4blockSize), "ext4.raw", fmt.Sprintf("%d", ext4blockCount)); err != nil {
return err
}
} else {
if err := execFg("mkfs.ext4", "-q", "-L", diskName, "-d", *contentPath, "-b", fmt.Sprintf("%d", ext4blockSize), "ext4.raw", fmt.Sprintf("%d", ext4blockCount)); err != nil {
return err
}
}
if err := execFg(QEMU_IMG_BIN, "convert", "-q", "-f", "raw", "-O", "qcow2", "-o", "cluster_size=2M,lazy_refcounts=on", "ext4.raw", diskPath); err != nil {
return err
}
if err := execFg("rm", "-f", "ext4.raw"); err != nil {
return err
}
// uid=36(qemu) gid=34(kvm) groups=34(kvm)
if err := execFg("chown", "36:34", diskPath); err != nil {
return err
}
return nil
}
func createISO9660FromPath(logger *zap.Logger, diskName string, diskPath string, contentPath string) error {
writer, err := iso9660.NewWriter()
if err != nil {
return err
}
defer writer.Cleanup() //nolint:errcheck // Nothing to do with the error, maybe log it ? TODO
dir, err := os.Open(contentPath)
if err != nil {
return err
}
dirEntrys, err := dir.ReadDir(0)
if err != nil {
return err
}
for _, file := range dirEntrys {
fileName := fmt.Sprintf("%s/%s", contentPath, file.Name())
outputPath := file.Name()
if file.IsDir() {
continue
}
// try to resolve symlink and check resolved file IsDir
resolved, err := filepath.EvalSymlinks(fileName)
if err != nil {
return err
}
resolvedOpen, err := os.Open(resolved)
if err != nil {
return err
}
resolvedStat, err := resolvedOpen.Stat()
if err != nil {
return err
}
if resolvedStat.IsDir() {
continue
}
// run the file handling logic in a closure, so the defers happen within the loop body,
// rather than the outer function.
err = func() error {
logger.Info("adding file to ISO9660 disk", zap.String("path", outputPath))
fileToAdd, err := os.Open(fileName)
if err != nil {
return err
}
defer fileToAdd.Close()
return writer.AddFile(fileToAdd, outputPath)
}()
if err != nil {
return err
}
}
outputFile, err := os.OpenFile(diskPath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err != nil {
return err
}
// uid=36(qemu) gid=34(kvm) groups=34(kvm)
err = outputFile.Chown(36, 34)
if err != nil {
return err
}
err = writer.WriteTo(outputFile, diskName)
if err != nil {
return err
}
err = outputFile.Close()
if err != nil {
return err
}
return nil
}
func checkKVM() bool {
info, err := os.Stat("/dev/kvm")
if err != nil {
return false
}
mode := info.Mode()
return mode&os.ModeCharDevice == os.ModeCharDevice
}
func checkDevTun() bool {
info, err := os.Stat("/dev/net/tun")
if err != nil {
return false
}
mode := info.Mode()
return mode&os.ModeCharDevice == os.ModeCharDevice
}
func runInitScript(logger *zap.Logger, script string) error {
if len(script) == 0 {
return nil
}
// creates a tmp file with the script content
tmpFile, err := os.CreateTemp(os.TempDir(), "init-script-")
if err != nil {
return err
}
defer os.Remove(tmpFile.Name()) // clean up
if _, err := tmpFile.Write([]byte(script)); err != nil {
return err
}
if err := tmpFile.Close(); err != nil {
return err
}
logger.Info("running init script", zap.String("path", tmpFile.Name()))
if err := execFg("/bin/sh", tmpFile.Name()); err != nil {
return err
}
return nil
}
type Config struct {
vmSpecDump string
vmStatusDump string
kernelPath string
appendKernelCmdline string
skipCgroupManagement bool
diskCacheSettings string
}
func newConfig() *Config {
cfg := &Config{
vmSpecDump: "",
vmStatusDump: "",
kernelPath: defaultKernelPath,
appendKernelCmdline: "",
skipCgroupManagement: false,
diskCacheSettings: "cache=none",
}
flag.StringVar(&cfg.vmSpecDump, "vmspec", cfg.vmSpecDump,
"Base64 encoded VirtualMachine json specification")
flag.StringVar(&cfg.vmStatusDump, "vmstatus", cfg.vmStatusDump,
"Base64 encoded VirtualMachine json status")
flag.StringVar(&cfg.kernelPath, "kernelpath", cfg.kernelPath,
"Override path for kernel to use")
flag.StringVar(&cfg.appendKernelCmdline, "appendKernelCmdline",
cfg.appendKernelCmdline, "Additional kernel command line arguments")
flag.BoolVar(&cfg.skipCgroupManagement, "skip-cgroup-management",
cfg.skipCgroupManagement,
"Don't try to manage CPU (use if running alongside container-mgr)")
flag.StringVar(&cfg.diskCacheSettings, "qemu-disk-cache-settings",
cfg.diskCacheSettings, "Cache settings to add to -drive args for VM disks")
flag.Parse()
return cfg
}
func main() {
logger := zap.Must(zap.NewProduction()).Named("neonvm-runner")
if err := run(logger); err != nil {
logger.Fatal("Failed to run", zap.Error(err))
}
}
func run(logger *zap.Logger) error {
cfg := newConfig()
vmSpecJson, err := base64.StdEncoding.DecodeString(cfg.vmSpecDump)
if err != nil {
return fmt.Errorf("failed to decode VirtualMachine Spec dump: %w", err)
}
vmStatusJson, err := base64.StdEncoding.DecodeString(cfg.vmStatusDump)
if err != nil {
return fmt.Errorf("failed to decode VirtualMachine Status dump: %w", err)
}
vmSpec := &vmv1.VirtualMachineSpec{}
if err := json.Unmarshal(vmSpecJson, vmSpec); err != nil {
return fmt.Errorf("failed to unmarshal VM spec: %w", err)
}
var vmStatus vmv1.VirtualMachineStatus
if err := json.Unmarshal(vmStatusJson, &vmStatus); err != nil {
return fmt.Errorf("failed to unmarshal VM Status: %w", err)
}
qemuCPUs := processCPUs(vmSpec.Guest.CPUs)
cpus := []string{}
cpus = append(cpus, fmt.Sprintf("cpus=%d", qemuCPUs.min))
if qemuCPUs.max != nil {
cpus = append(cpus, fmt.Sprintf("maxcpus=%d,sockets=1,cores=%d,threads=1", *qemuCPUs.max, *qemuCPUs.max))
}
initialMemorySize := vmSpec.Guest.MemorySlotSize.Value() * int64(*vmSpec.Guest.MemorySlots.Min)
memory := []string{}
memory = append(memory, fmt.Sprintf("size=%db", initialMemorySize))
if vmSpec.Guest.MemorySlots.Max != nil {
memory = append(memory, fmt.Sprintf("slots=%d", *vmSpec.Guest.MemorySlots.Max-*vmSpec.Guest.MemorySlots.Min))
memory = append(memory, fmt.Sprintf("maxmem=%db", vmSpec.Guest.MemorySlotSize.Value()*int64(*vmSpec.Guest.MemorySlots.Max)))
}
enableSSH := false
if vmSpec.EnableSSH != nil && *vmSpec.EnableSSH {
enableSSH = true
}
// create iso9660 disk with runtime options (command, args, envs, mounts)
sysctl := []string{
"kernel.core_pattern=core",
"kernel.core_uses_pid=1",
}
var shmSize *resource.Quantity
var swapInfo *vmv1.SwapInfo
if vmSpec.Guest.Settings != nil {
sysctl = append(sysctl, vmSpec.Guest.Settings.Sysctl...)
swapInfo, err = vmSpec.Guest.Settings.GetSwapInfo()
if err != nil {
return fmt.Errorf("failed to get SwapInfo from VirtualMachine object: %w", err)
}
// By default, Linux sets the size of /dev/shm to 1/2 of the physical memory. If
// swap is configured, we want to set /dev/shm higher, because we can autoscale
// the memory up.
//
// See https://github.com/neondatabase/autoscaling/issues/800
if swapInfo != nil && swapInfo.Size.Value() > initialMemorySize/2 {
shmSize = &swapInfo.Size
}
}
// Helper function to both log an error and return the result of wrapping it with the message.
//
// This is used below because (*errgroup.Group).Wait() returns at most 1 error, which means
// imprecise usage can hide errors. So, we log the errors before they would be returned, to make
// sure they're always visible.
logWrap := func(msg string, err error) error {
logger.Error(msg, zap.Error(err))
return fmt.Errorf("%s: %w", msg, err)
}
eg := &errgroup.Group{}
eg.Go(func() error {
if err := runInitScript(logger, vmSpec.InitScript); err != nil {
return logWrap("failed to run init script", err)
}
return nil
})
eg.Go(func() error {
if err := createISO9660runtime(
runtimeDiskPath,
vmSpec.Guest.Command,
vmSpec.Guest.Args,
sysctl,
vmSpec.Guest.Env,
vmSpec.Disks,
enableSSH,
swapInfo,
shmSize,
); err != nil {
return logWrap("failed to create iso9660 disk", err)
}
return nil
})
eg.Go(func() error {
// resize rootDisk image of size specified and new size more than current
if err := resizeRootDisk(logger, vmSpec); err != nil {
return logWrap("failed to resize rootDisk", err)
}
return nil
})
var qemuCmd []string
eg.Go(func() error {
var err error
qemuCmd, err = buildQEMUCmd(cfg, logger, vmSpec, &vmStatus, cpus, memory, enableSSH, swapInfo)
if err != nil {
return logWrap("failed to build QEMU command", err)
}
return nil
})
if err := eg.Wait(); err != nil {
return err
}
err = runQEMU(cfg, logger, vmSpec, qemuCmd, qemuCPUs)
if err != nil {
return fmt.Errorf("failed to run QEMU: %w", err)
}
return nil
}
func resizeRootDisk(logger *zap.Logger, vmSpec *vmv1.VirtualMachineSpec) error {
// resize rootDisk image of size specified and new size more than current
type QemuImgOutputPartial struct {
VirtualSize int64 `json:"virtual-size"`
}
// get current disk size by qemu-img info command
qemuImgOut, err := exec.Command(QEMU_IMG_BIN, "info", "--output=json", rootDiskPath).Output()
if err != nil {
return fmt.Errorf("could not get root image size: %w", err)
}
var imageSize QemuImgOutputPartial
if err := json.Unmarshal(qemuImgOut, &imageSize); err != nil {
return fmt.Errorf("failed to unmarshal QEMU image size: %w", err)
}
imageSizeQuantity := resource.NewQuantity(imageSize.VirtualSize, resource.BinarySI)
// going to resize
if !vmSpec.Guest.RootDisk.Size.IsZero() {
if vmSpec.Guest.RootDisk.Size.Cmp(*imageSizeQuantity) == 1 {
logger.Info(fmt.Sprintf("resizing rootDisk from %s to %s", imageSizeQuantity.String(), vmSpec.Guest.RootDisk.Size.String()))
if err := execFg(QEMU_IMG_BIN, "resize", rootDiskPath, fmt.Sprintf("%d", vmSpec.Guest.RootDisk.Size.Value())); err != nil {
return fmt.Errorf("failed to resize rootDisk: %w", err)
}
} else {
logger.Info(fmt.Sprintf("rootDisk.size (%s) is less than than image size (%s)", vmSpec.Guest.RootDisk.Size.String(), imageSizeQuantity.String()))
}
}
return nil
}
func buildQEMUCmd(
cfg *Config,
logger *zap.Logger,
vmSpec *vmv1.VirtualMachineSpec,
vmStatus *vmv1.VirtualMachineStatus,
cpus, memory []string,
enableSSH bool,
swapInfo *vmv1.SwapInfo,
) ([]string, error) {
// prepare qemu command line
qemuCmd := []string{
"-runas", "qemu",
"-machine", "q35",
"-nographic",
"-no-reboot",
"-nodefaults",
"-only-migratable",
"-audiodev", "none,id=noaudio",
"-serial", "pty",
"-serial", "stdio",
"-msg", "timestamp=on",
"-qmp", fmt.Sprintf("tcp:0.0.0.0:%d,server,wait=off", vmSpec.QMP),
"-qmp", fmt.Sprintf("tcp:0.0.0.0:%d,server,wait=off", vmSpec.QMPManual),
"-qmp", fmt.Sprintf("unix:%s,server,wait=off", qmpUnixSocketForSigtermHandler),
"-device", "virtio-serial",
"-chardev", fmt.Sprintf("socket,path=%s,server=on,wait=off,id=log", logSerialSocket),
"-device", "virtserialport,chardev=log,name=tech.neon.log.0",
}
// disk details
qemuCmd = append(qemuCmd, "-drive", fmt.Sprintf("id=rootdisk,file=%s,if=virtio,media=disk,index=0,%s", rootDiskPath, cfg.diskCacheSettings))
qemuCmd = append(qemuCmd, "-drive", fmt.Sprintf("id=runtime,file=%s,if=virtio,media=cdrom,readonly=on,cache=none", runtimeDiskPath))
if enableSSH {
name := "ssh-authorized-keys"
if err := createISO9660FromPath(logger, name, sshAuthorizedKeysDiskPath, sshAuthorizedKeysMountPoint); err != nil {
return nil, fmt.Errorf("Failed to create ISO9660 image: %w", err)
}
qemuCmd = append(qemuCmd, "-drive", fmt.Sprintf("id=%s,file=%s,if=virtio,media=cdrom,cache=none", name, sshAuthorizedKeysDiskPath))
}
if swapInfo != nil {
dPath := fmt.Sprintf("%s/swapdisk.qcow2", mountedDiskPath)
logger.Info("creating QCOW2 image for swap", zap.String("diskPath", dPath))
if err := createSwap(dPath, *swapInfo); err != nil {
return nil, fmt.Errorf("Failed to create swap disk: %w", err)
}
qemuCmd = append(qemuCmd, "-drive", fmt.Sprintf("id=%s,file=%s,if=virtio,media=disk,%s,discard=unmap", swapName, dPath, cfg.diskCacheSettings))
}
for _, disk := range vmSpec.Disks {
switch {
case disk.EmptyDisk != nil:
logger.Info("creating QCOW2 image with empty ext4 filesystem", zap.String("diskName", disk.Name))
dPath := fmt.Sprintf("%s/%s.qcow2", mountedDiskPath, disk.Name)
if err := createQCOW2(disk.Name, dPath, &disk.EmptyDisk.Size, nil); err != nil {
return nil, fmt.Errorf("Failed to create QCOW2 image: %w", err)
}
discard := ""
if disk.EmptyDisk.Discard {
discard = ",discard=unmap"
}
qemuCmd = append(qemuCmd, "-drive", fmt.Sprintf("id=%s,file=%s,if=virtio,media=disk,%s%s", disk.Name, dPath, cfg.diskCacheSettings, discard))
case disk.ConfigMap != nil || disk.Secret != nil:
dPath := fmt.Sprintf("%s/%s.iso", mountedDiskPath, disk.Name)
mnt := fmt.Sprintf("/vm/mounts%s", disk.MountPath)
logger.Info("creating iso9660 image", zap.String("diskPath", dPath), zap.String("diskName", disk.Name), zap.String("mountPath", mnt))
if err := createISO9660FromPath(logger, disk.Name, dPath, mnt); err != nil {
return nil, fmt.Errorf("Failed to create ISO9660 image: %w", err)
}
qemuCmd = append(qemuCmd, "-drive", fmt.Sprintf("id=%s,file=%s,if=virtio,media=cdrom,cache=none", disk.Name, dPath))
default:
// do nothing
}
}
// cpu details
// NB: EnableAcceleration guaranteed non-nil because the k8s API server sets the default for us.
if *vmSpec.EnableAcceleration && checkKVM() {
logger.Info("using KVM acceleration")
qemuCmd = append(qemuCmd, "-enable-kvm")
} else {
logger.Warn("not using KVM acceleration")
}
qemuCmd = append(qemuCmd, "-cpu", "max")
qemuCmd = append(qemuCmd, "-smp", strings.Join(cpus, ","))
// memory details
qemuCmd = append(qemuCmd, "-m", strings.Join(memory, ","))
// default (pod) net details
macDefault, err := defaultNetwork(logger, defaultNetworkCIDR, vmSpec.Guest.Ports)
if err != nil {
return nil, fmt.Errorf("Failed to set up default network: %w", err)
}
qemuCmd = append(qemuCmd, "-netdev", fmt.Sprintf("tap,id=default,ifname=%s,script=no,downscript=no,vhost=on", defaultNetworkTapName))
qemuCmd = append(qemuCmd, "-device", fmt.Sprintf("virtio-net-pci,netdev=default,mac=%s", macDefault.String()))
// overlay (multus) net details
if vmSpec.ExtraNetwork != nil && vmSpec.ExtraNetwork.Enable {
macOverlay, err := overlayNetwork(vmSpec.ExtraNetwork.Interface)
if err != nil {
return nil, fmt.Errorf("Failed to set up overlay network: %w", err)
}
qemuCmd = append(qemuCmd, "-netdev", fmt.Sprintf("tap,id=overlay,ifname=%s,script=no,downscript=no,vhost=on", overlayNetworkTapName))
qemuCmd = append(qemuCmd, "-device", fmt.Sprintf("virtio-net-pci,netdev=overlay,mac=%s", macOverlay.String()))
}
// kernel details
qemuCmd = append(qemuCmd, "-kernel", cfg.kernelPath)
var effectiveKernelCmdline string
if vmSpec.ExtraNetwork != nil && vmSpec.ExtraNetwork.Enable {
effectiveKernelCmdline = fmt.Sprintf("ip=%s:::%s:%s:eth1:off %s", vmStatus.ExtraNetIP, vmStatus.ExtraNetMask, vmStatus.PodName, baseKernelCmdline)
} else {
effectiveKernelCmdline = baseKernelCmdline
}
if cfg.appendKernelCmdline != "" {
effectiveKernelCmdline = fmt.Sprintf("%s %s", effectiveKernelCmdline, cfg.appendKernelCmdline)
}
qemuCmd = append(qemuCmd, "-append", effectiveKernelCmdline)
// should runner receive migration ?
if os.Getenv("RECEIVE_MIGRATION") == "true" {
qemuCmd = append(qemuCmd, "-incoming", fmt.Sprintf("tcp:0:%d", vmv1.MigrationPort))
}
return qemuCmd, nil
}
func runQEMU(
cfg *Config,
logger *zap.Logger,
vmSpec *vmv1.VirtualMachineSpec,
qemuCmd []string,
qemuCPUs QemuCPUs,
) error {
selfPodName, ok := os.LookupEnv("K8S_POD_NAME")
if !ok {
return fmt.Errorf("environment variable K8S_POD_NAME missing")
}
var cgroupPath string
if !cfg.skipCgroupManagement {
selfCgroupPath, err := getSelfCgroupPath(logger)
if err != nil {
return fmt.Errorf("Failed to get self cgroup path: %w", err)
}
// Sometimes we'll get just '/' as our cgroup path. If that's the case, we should reset it so
// that the cgroup '/neonvm-qemu-...' still works.
if selfCgroupPath == "/" {
selfCgroupPath = ""
}
// ... but also we should have some uniqueness just in case, so we're not sharing a root level
// cgroup if that *is* what's happening. This *should* only be relevant for local clusters.
//
// We don't want to just use the VM spec's .status.PodName because during migrations that will
// be equal to the source pod, not this one, which may be... somewhat confusing.
cgroupPath = fmt.Sprintf("%s/neonvm-qemu-%s", selfCgroupPath, selfPodName)
logger.Info("Determined QEMU cgroup path", zap.String("path", cgroupPath))
if err := setCgroupLimit(logger, qemuCPUs.use, cgroupPath); err != nil {
return fmt.Errorf("Failed to set cgroup limit: %w", err)
}
}
ctx, cancel := context.WithCancel(context.Background())
wg := sync.WaitGroup{}
wg.Add(1)
go terminateQemuOnSigterm(ctx, logger, &wg)
if !cfg.skipCgroupManagement {
wg.Add(1)
go listenForCPUChanges(ctx, logger, vmSpec.RunnerPort, cgroupPath, &wg)
}
wg.Add(1)
go forwardLogs(ctx, logger, &wg)
var bin string
var cmd []string
if !cfg.skipCgroupManagement {
bin = "cgexec"
cmd = append([]string{"-g", fmt.Sprintf("cpu:%s", cgroupPath), QEMU_BIN}, qemuCmd...)
} else {
bin = QEMU_BIN
cmd = qemuCmd
}
logger.Info(fmt.Sprintf("calling %s", bin), zap.Strings("args", cmd))
if err := execFg(bin, cmd...); err != nil {
logger.Error("QEMU exited with error", zap.Error(err))
} else {
logger.Info("QEMU exited without error")
}
cancel()
wg.Wait()
return nil
}
func handleCPUChange(logger *zap.Logger, w http.ResponseWriter, r *http.Request, cgroupPath string) {
if r.Method != "POST" {