-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathfirecracker.go
More file actions
3531 lines (3120 loc) · 120 KB
/
firecracker.go
File metadata and controls
3531 lines (3120 loc) · 120 KB
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 firecracker
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"math"
"math/rand/v2"
"net"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"syscall"
"time"
_ "embed"
"github.com/armon/circbuf"
"github.com/bazelbuild/rules_go/go/runfiles"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/remote_execution/block_io"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/remote_execution/cgroup"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/remote_execution/commandutil"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/remote_execution/container"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/remote_execution/copy_on_write"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/remote_execution/snaploader"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/remote_execution/snaputil"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/remote_execution/uffd"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/remote_execution/vbd"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/remote_execution/vmexec_client"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/util/cpuset"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/util/ext4"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/util/oci"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/util/ociconv"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/util/vfs_server"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/util/vsock"
"github.com/buildbuddy-io/buildbuddy/server/environment"
"github.com/buildbuddy-io/buildbuddy/server/interfaces"
"github.com/buildbuddy-io/buildbuddy/server/metrics"
"github.com/buildbuddy-io/buildbuddy/server/remote_cache/digest"
"github.com/buildbuddy-io/buildbuddy/server/util/background"
"github.com/buildbuddy-io/buildbuddy/server/util/disk"
"github.com/buildbuddy-io/buildbuddy/server/util/error_util"
"github.com/buildbuddy-io/buildbuddy/server/util/flag"
"github.com/buildbuddy-io/buildbuddy/server/util/log"
"github.com/buildbuddy-io/buildbuddy/server/util/networking"
"github.com/buildbuddy-io/buildbuddy/server/util/platform"
"github.com/buildbuddy-io/buildbuddy/server/util/status"
"github.com/buildbuddy-io/buildbuddy/server/util/tracing"
"github.com/buildbuddy-io/buildbuddy/server/util/uuid"
"github.com/firecracker-microvm/firecracker-go-sdk/client/operations"
"github.com/klauspost/cpuid/v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel/attribute"
"golang.org/x/sync/errgroup"
"golang.org/x/sys/unix"
"google.golang.org/grpc"
vmsupport_bundle "github.com/buildbuddy-io/buildbuddy/enterprise/vmsupport"
fcpb "github.com/buildbuddy-io/buildbuddy/proto/firecracker"
repb "github.com/buildbuddy-io/buildbuddy/proto/remote_execution"
scpb "github.com/buildbuddy-io/buildbuddy/proto/scheduler"
vmxpb "github.com/buildbuddy-io/buildbuddy/proto/vmexec"
vmfspb "github.com/buildbuddy-io/buildbuddy/proto/vmvfs"
fcclient "github.com/firecracker-microvm/firecracker-go-sdk"
fcmodels "github.com/firecracker-microvm/firecracker-go-sdk/client/models"
hlpb "google.golang.org/grpc/health/grpc_health_v1"
tspb "google.golang.org/protobuf/types/known/timestamppb"
)
var (
firecrackerCgroupVersion = flag.String("executor.firecracker_cgroup_version", "", "Specifies the cgroup version for firecracker to use.")
debugStreamVMLogs = flag.Bool("executor.firecracker_debug_stream_vm_logs", false, "Stream firecracker VM logs to the terminal.")
debugTerminal = flag.Bool("executor.firecracker_debug_terminal", false, "Run an interactive terminal in the Firecracker VM connected to the executor's controlling terminal. For debugging only.")
dieOnFirecrackerFailure = flag.Bool("executor.die_on_firecracker_failure", false, "Makes the host executor process die if any command orchestrating or running Firecracker fails. Useful for capturing failures preemptively. WARNING: using this option MAY leave the host machine in an unhealthy state on Firecracker failure; some post-hoc cleanup may be necessary.")
workspaceDiskSlackSpaceMB = flag.Int64("executor.firecracker_workspace_disk_slack_space_mb", 2_000, "Extra space to allocate to firecracker workspace disks, in megabytes. ** Experimental **")
healthCheckInterval = flag.Duration("executor.firecracker_health_check_interval", 10*time.Second, "How often to run VM health checks while tasks are executing.")
healthCheckTimeout = flag.Duration("executor.firecracker_health_check_timeout", 30*time.Second, "Timeout for VM health check requests.")
overprovisionCPUs = flag.Int("executor.firecracker_overprovision_cpus", 3, "Number of CPUs to overprovision for VMs. This allows VMs to more effectively utilize CPU resources on the host machine. Set to -1 to allow all VMs to use max CPU.")
initOnAllocAndFree = flag.Bool("executor.firecracker_init_on_alloc_and_free", false, "Set init_on_alloc=1 and init_on_free=1 in firecracker vms")
netPoolSize = flag.Int("executor.firecracker_network_pool_size", 0, "Limit on the number of networks to be reused between VMs. Setting to 0 disables pooling. Setting to -1 uses the recommended default.")
firecrackerVMDockerMirrors = flag.Slice("executor.firecracker_vm_docker_mirrors", []string{}, "Registry mirror hosts (and ports) for public Docker images. Only used if InitDockerd is set to true.")
firecrackerVMDockerInsecureRegistries = flag.Slice("executor.firecracker_vm_docker_insecure_registries", []string{}, "Tell Docker to communicate over HTTP with these URLs. Only used if InitDockerd is set to true.")
enableLinux6_1 = flag.Bool("executor.firecracker_enable_linux_6_1", false, "Enable the 6.1 guest kernel for firecracker microVMs. x86_64 only.", flag.Internal)
dnsOverrides = flag.Slice("executor.firecracker_dns_overrides", []*networking.DNSOverride{}, "DNS entries to override in the guest.")
forceRemoteSnapshotting = flag.Bool("debug_force_remote_snapshots", false, "When remote snapshotting is enabled, force remote snapshotting even for tasks which otherwise wouldn't support it.")
disableWorkspaceSync = flag.Bool("debug_disable_firecracker_workspace_sync", false, "Do not sync the action workspace to the guest, instead using the existing workspace from the VM snapshot.")
debugDisableCgroup = flag.Bool("debug_disable_cgroup", false, "Disable firecracker cgroup setup.")
)
//go:embed guest_api_hash.sha256
var GuestAPIHash string
const (
// goinitVersion determines the version of the go init binary that this
// executor supports. This version needs to be bumped when making
// incompatible changes to the goinit binary. This includes but is not
// limited to:
//
// - Adding new platform prop based features that depend on goinit support,
// such as dockerd init options.
// - Adding new features to the vmexec.Exec service.
//
// We manually maintain this version instead of using a hash of the goinit
// binary because we expect the hash to be unstable, likely changing with
// each executor release.
//
// NOTE: this is part of the snapshot cache key, so bumping this version
// will make existing cached snapshots unusable.
GuestAPIVersion = "18"
// How long to wait when dialing the vmexec server inside the VM.
vSocketDialTimeout = 60 * time.Second
// How long to wait for the jailer directory to be created.
jailerDirectoryCreationTimeout = 1 * time.Second
// The firecracker socket path (will be relative to the chroot).
firecrackerSocketPath = "/run/fc.sock"
// The vSock path (also relative to the chroot).
firecrackerVSockPath = "/run/v.sock"
// UFFD socket path relative to the chroot.
uffdSockName = "uffd.sock"
// The names to use when creating snapshots (relative to chroot).
vmStateSnapshotName = "vmstate.snap"
fullMemSnapshotName = "full-mem.snap"
diffMemSnapshotName = "diff-mem.snap"
// Directory storing the memory file chunks.
memoryChunkDirName = snaputil.MemoryFileName
fullSnapshotType = "Full"
diffSnapshotType = "Diff"
mergeDiffSnapshotConcurrency = 4
// Firecracker writes changed blocks in 4Kb blocks.
mergeDiffSnapshotBlockSize = 4096
// Size of machine log tail to retain in memory so that we can parse logs for
// errors.
vmLogTailBufSize = 1024 * 12 // 12 KB
// File name of the VM logs in CommandResult.AuxiliaryLogs
vmLogTailFileName = "vm_log_tail.txt"
// Log prefix used by goinit when logging fatal errors.
fatalInitLogPrefix = "die: "
// VBD mount path suffix, which is appended to the drive ID.
// Example:
// "{chrootPath}/workspacefs.vbd/file"
vbdMountDirSuffix = ".vbd"
// Name of the empty file used as a placeholder for the workspace drive.
emptyFileName = "empty.bin"
// The workspacefs image name and drive ID.
workspaceFSName = "workspacefs.ext4"
workspaceDriveID = "workspacefs"
// The scratchfs image name and drive ID.
scratchFSName = "scratchfs.ext4"
scratchDriveID = "scratchfs"
// The rootfs image name and drive ID (merged containerfs + scratchfs).
rootFSName = "rootfs.ext4"
rootDriveID = "rootfs"
// minScratchDiskSizeBytes is the minimum size needed for the scratch disk.
// This is needed because the init binary needs some space to copy files around.
minScratchDiskSizeBytes = 64e6
// Chunk size to use when creating COW images from files.
cowChunkSizeInPages = 1000
// The containerfs drive ID.
containerFSName = "containerfs.ext4"
containerDriveID = "containerfs"
// The networking deets for host and vm interfaces.
// All VMs are configured with the same IP and tap device via boot args,
// but because they run inside of a network namespace, they do not
// conflict. More details here:
// https://github.com/firecracker-microvm/firecracker/blob/main/docs/snapshotting/network-for-clones.md
tapDeviceName = "vmtap0"
tapDeviceMac = "7a:a8:fa:dc:76:b7"
tapIP = "192.168.241.1"
tapAddr = tapIP + "/29"
vmIP = "192.168.241.2"
vmAddr = vmIP + "/29"
vmIface = "eth0"
// https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/networking_guide/sec-configuring_ip_networking_from_the_kernel_command_line
// ip<client-IP-number>:[<server-id>]:<gateway-IP-number>:<netmask>:<client-hostname>:<interface>:{dhcp|dhcp6|auto6|on|any|none|off}
machineIPBootArgs = "ip=" + vmIP + ":::255.255.255.48::" + vmIface + ":off"
// This is pretty arbitrary limit -- when vmIdx gets this big it will
// roll over to 0, causing new VMs to start re-using old local IPs. But
// net namespaces are deleted upon VM removal, so this should not cause
// any issue. If more than this many VMs were active on a single host at
// once -- it would cause an error.
maxVMSPerHost = 1000
// The path in the guest where VFS is mounted.
guestVFSMountDir = "/vfs"
// Timeout when mounting/unmounting the workspace within the guest.
mountTimeout = 1 * time.Minute
// How long to allow for the VM to be finalized (paused, outputs copied, etc.)
finalizationTimeout = 10 * time.Second
// Firecracker does not allow VMs over a certain size.
// See MAX_SUPPORTED_VCPUS in firecracker repo.
firecrackerMaxCPU = 32
// The max amount of time we'll wait for the balloon to expand to the target size.
maxUpdateBalloonDuration = 30 * time.Second
// Special file that actions can create in the workspace directory to
// invalidate the snapshot the action was run in. This can be written
// if the action detects that the snapshot was corrupted upon startup.
invalidateSnapshotMarkerFile = ".BUILDBUDDY_INVALIDATE_SNAPSHOT"
)
var (
vmIdx int
vmIdxMu sync.Mutex
fatalErrPattern = regexp.MustCompile(`\b` + fatalInitLogPrefix + `(.*)`)
slowInterruptWarningPattern = regexp.MustCompile(`hrtimer: interrupt took \d+ ns`)
)
// Derives the desired Firecracker NetworkMode from the provided network and
// init-dockerd platform properties enum.
func networkMode(network string, initDockerd bool) (fcpb.NetworkMode, error) {
if network == "external" || network == "" {
return fcpb.NetworkMode_NETWORK_MODE_EXTERNAL, nil
}
if network == "off" {
if initDockerd {
return fcpb.NetworkMode_NETWORK_MODE_LOCAL, nil
}
return fcpb.NetworkMode_NETWORK_MODE_OFF, nil
}
return fcpb.NetworkMode_NETWORK_MODE_UNSPECIFIED, status.InvalidArgumentErrorf("unsupported network option %q", network)
}
// networkingEnabled returns true if the VM has any networking capability.
func networkingEnabled(mode fcpb.NetworkMode) bool {
// UNSPECIFIED defaults to EXTERNAL for backward compatibility.
return mode != fcpb.NetworkMode_NETWORK_MODE_OFF
}
// externalNetworkingEnabled returns true if the VM can access external networks.
func externalNetworkingEnabled(mode fcpb.NetworkMode) bool {
// UNSPECIFIED defaults to EXTERNAL for backward compatibility.
return mode == fcpb.NetworkMode_NETWORK_MODE_UNSPECIFIED || mode == fcpb.NetworkMode_NETWORK_MODE_EXTERNAL
}
func init() {
// Configure firecracker request timeout (default: 500ms).
//
// We're increasing it from the default here since we do some remote reads
// during ResumeVM to handle page faults with UFFD.
os.Setenv("FIRECRACKER_GO_SDK_REQUEST_TIMEOUT_MILLISECONDS", fmt.Sprint(60_000))
}
func openFile(ctx context.Context, fsys fs.FS, fileName string) (io.ReadCloser, error) {
// If the file exists on the filesystem, use that.
if path, err := exec.LookPath(fileName); err == nil {
log.CtxDebugf(ctx, "Located %q at %s", fileName, path)
return os.Open(path)
}
// Otherwise try to find it in the provided fs
return fsys.Open(fileName)
}
// Returns the cgroup version available on this machine, which is returned from
//
// stat -fc %T /sys/fs/cgroup/
//
// and should be either 'cgroup2fs' (version 2) or 'tmpfs' (version 1)
//
// More info here: https://kubernetes.io/docs/concepts/architecture/cgroups/
// TODO(iain): preemptively get this in a provider a la Provider in podman.go.
func getCgroupVersion() (string, error) {
if *firecrackerCgroupVersion != "" {
return *firecrackerCgroupVersion, nil
}
b, err := exec.Command("stat", "-fc", "%T", "/sys/fs/cgroup/").Output()
if err != nil {
return "", status.UnavailableErrorf("Error determining system cgroup version: %v", err)
}
v := strings.TrimSpace(string(b))
if v == "cgroup2fs" {
return "2", nil
} else if v == "tmpfs" {
return "1", nil
} else {
return "", status.InternalErrorf("No cgroup version found (system reported %s)", v)
}
}
// putFileIntoDir finds "fileName" on the local filesystem, in runfiles, or
// in the bundle. It then puts that file into destdir (via hardlink or copying)
// and returns a path to the file in the new location. Files are written in
// a content-addressable-storage-based location, so when files are updated they
// will be put into new paths.
func putFileIntoDir(ctx context.Context, fsys fs.FS, fileName, destDir string, mode fs.FileMode) (string, error) {
f, err := openFile(ctx, fsys, fileName)
if err != nil {
return "", err
}
// If fileReader is still nil, the file was not found, so return an error.
if f == nil {
return "", status.NotFoundErrorf("File %q not found on fs, in runfiles or in bundle.", fileName)
}
defer f.Close()
// Compute the file hash to determine the new location where it should be written.
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
fileHash := hex.EncodeToString(h.Sum(nil))
fileHome := filepath.Join(destDir, "executor", fileHash)
if err := disk.EnsureDirectoryExists(fileHome); err != nil {
return "", err
}
casPath := filepath.Join(fileHome, filepath.Base(fileName))
if exists, err := disk.FileExists(ctx, casPath); err == nil && exists {
log.CtxDebugf(ctx, "Found existing %q in path: %q", fileName, casPath)
return casPath, nil
}
// Write the file to the new location if it does not exist there already.
f, err = openFile(ctx, fsys, fileName)
if err != nil {
return "", err
}
defer f.Close()
writer, err := disk.FileWriter(ctx, casPath)
if err != nil {
return "", err
}
if _, err := io.Copy(writer, f); err != nil {
return "", err
}
if err := writer.Commit(); err != nil {
return "", err
}
if err := writer.Close(); err != nil {
return "", err
}
log.CtxDebugf(ctx, "Put %q into new path: %q", fileName, casPath)
return casPath, nil
}
func getLogrusLogger() *logrus.Entry {
logrusLogger := logrus.New()
logrusLogger.SetLevel(logrus.ErrorLevel)
if *debugStreamVMLogs {
logrusLogger.SetLevel(logrus.TraceLevel)
}
return logrus.NewEntry(logrusLogger)
}
func checkIfFilesExist(targetDir string, files ...string) bool {
for _, f := range files {
fileName := filepath.Base(f)
newPath := filepath.Join(targetDir, fileName)
if _, err := os.Stat(newPath); err != nil {
return false
}
}
return true
}
// ExecutorConfig contains configuration that is computed once at executor
// startup and applies to all VMs created by the executor.
type ExecutorConfig struct {
JailerRoot string
CacheRoot string
InitrdImagePath string
GuestKernelImagePath string
FirecrackerBinaryPath string
JailerBinaryPath string
GuestKernelVersion string
HostKernelVersion string
FirecrackerVersion string
GuestAPIVersion string
GuestKernelImagePath6_1 string
GuestKernelVersion6_1 string
}
var (
// set by x_defs in BUILD file
initrdRunfilePath string
vmlinuxRunfilePath string
vmlinux6_1RunfilePath string
)
// GetExecutorConfig computes the ExecutorConfig for this executor instance.
//
// WARNING: The given buildRootDir will be used as the jailer root dir. Because
// of the limitation on the length of unix sock file paths (103), this directory
// path needs to be short. Specifically, a full sock path will look like:
// /tmp/firecracker/217d4de0-4b28-401b-891b-18e087718ad1/root/run/fc.sock
// everything after "/tmp" is 65 characters, so 38 are left for the jailerRoot.
func GetExecutorConfig(ctx context.Context, buildRootDir, cacheRootDir string) (*ExecutorConfig, error) {
bundle := vmsupport_bundle.Get()
initrdRunfileLocation, err := runfiles.Rlocation(initrdRunfilePath)
if err != nil {
return nil, fmt.Errorf("get initrd runfile path: %w", err)
}
initrdPath, err := putFileIntoDir(ctx, bundle, initrdRunfileLocation, buildRootDir, 0755)
if err != nil {
return nil, fmt.Errorf("put initrd into build root dir: %w", err)
}
var guestKernelPath6_1 string
var guestKernelDigest6_1 *repb.Digest
// TODO: build a 6.1 kernel for arm64, then remove this conditional.
if vmlinux6_1RunfilePath != "" {
vmlinuxRunfileLocation6_1, err := runfiles.Rlocation(vmlinux6_1RunfilePath)
if err != nil {
return nil, fmt.Errorf("get vmlinux 6.1 runfile path: %w", err)
}
p, err := putFileIntoDir(ctx, bundle, vmlinuxRunfileLocation6_1, buildRootDir, 0755)
if err != nil {
return nil, fmt.Errorf("put vmlinux 6.1 into build root dir: %w", err)
}
guestKernelPath6_1 = p
d, err := digest.ComputeForFile(guestKernelPath6_1, repb.DigestFunction_SHA256)
if err != nil {
return nil, fmt.Errorf("compute digest for vmlinux 6.1: %w", err)
}
guestKernelDigest6_1 = d
}
vmlinuxRunfileLocation5_15, err := runfiles.Rlocation(vmlinuxRunfilePath)
if err != nil {
return nil, fmt.Errorf("get vmlinux 5.15 runfile path: %w", err)
}
guestKernelPath5_15, err := putFileIntoDir(ctx, bundle, vmlinuxRunfileLocation5_15, buildRootDir, 0755)
if err != nil {
return nil, fmt.Errorf("put vmlinux 5.15 into build root dir: %w", err)
}
// TODO: when running as root, these should come from the bundle instead of
// $PATH, since we don't need to rely on the user having configured special
// perms on these binaries.
firecrackerPath, err := exec.LookPath("firecracker")
if err != nil {
return nil, fmt.Errorf("look up firecracker in PATH: %w", err)
}
jailerPath, err := exec.LookPath("jailer")
if err != nil {
return nil, fmt.Errorf("look up jailer in PATH: %w", err)
}
guestKernelDigest5_15, err := digest.ComputeForFile(guestKernelPath5_15, repb.DigestFunction_SHA256)
if err != nil {
return nil, fmt.Errorf("compute digest for vmlinux 5.15: %w", err)
}
firecrackerDigest, err := digest.ComputeForFile(firecrackerPath, repb.DigestFunction_SHA256)
if err != nil {
return nil, fmt.Errorf("compute digest for firecracker: %w", err)
}
hostKernelVersion, err := getHostKernelVersion()
if err != nil {
return nil, fmt.Errorf("get host kernel version: %w", err)
}
guestKernelImagePath := guestKernelPath5_15
guestKernelVersion := guestKernelDigest5_15.GetHash()
if *enableLinux6_1 {
guestKernelImagePath = guestKernelPath6_1
guestKernelVersion = guestKernelDigest6_1.GetHash()
}
return &ExecutorConfig{
// For now just use the build root dir as the jailer root dir, since
// these are guaranteed to be on the same FS.
JailerRoot: buildRootDir,
CacheRoot: cacheRootDir,
InitrdImagePath: initrdPath,
GuestKernelImagePath: guestKernelImagePath,
FirecrackerBinaryPath: firecrackerPath,
JailerBinaryPath: jailerPath,
GuestKernelVersion: guestKernelVersion,
HostKernelVersion: hostKernelVersion,
FirecrackerVersion: firecrackerDigest.GetHash(),
GuestAPIVersion: GuestAPIVersion,
GuestKernelImagePath6_1: guestKernelPath6_1,
GuestKernelVersion6_1: guestKernelDigest6_1.GetHash(),
}, nil
}
func getHostKernelVersion() (string, error) {
var uts unix.Utsname
if err := unix.Uname(&uts); err != nil {
return "", err
}
return unix.ByteSliceToString(uts.Release[:]), nil
}
type Provider struct {
env environment.Env
executorConfig *ExecutorConfig
networkPool *networking.VMNetworkPool
marshalledDNSOverrides string
}
func NewProvider(env environment.Env, buildRoot, cacheRoot string) (*Provider, error) {
executorConfig, err := GetExecutorConfig(env.GetServerContext(), buildRoot, cacheRoot)
if err != nil {
return nil, err
}
if err := ext4.EnsureDependencies(); err != nil {
return nil, status.WrapError(err, "verify ext4 tooling")
}
if _, err := os.Stat("/dev/kvm"); err != nil {
return nil, status.WrapError(err, "Firecracker isolation requires kvm")
}
// Enable masquerading on the host once on startup.
if err := networking.EnableMasquerading(env.GetServerContext()); err != nil {
return nil, status.WrapError(err, "enable masquerading")
}
var networkPool *networking.VMNetworkPool
if *netPoolSize != 0 {
networkPool = networking.NewVMNetworkPool(*netPoolSize)
env.GetHealthChecker().RegisterShutdownFunction(networkPool.Shutdown)
}
dns, err := parseDNSOverrides()
if err != nil {
return nil, err
}
return &Provider{
env: env,
executorConfig: executorConfig,
networkPool: networkPool,
marshalledDNSOverrides: dns,
}, nil
}
func (p *Provider) New(ctx context.Context, args *container.Init) (container.CommandContainer, error) {
var vmConfig *fcpb.VMConfiguration
sizeEstimate := args.Task.GetSchedulingMetadata().GetTaskSize()
numCPUs := int64(max(1.0, float64(sizeEstimate.GetEstimatedMilliCpu())/1000))
op := *overprovisionCPUs
if op == -1 {
numCPUs = int64(runtime.NumCPU())
} else {
numCPUs = min(numCPUs+int64(op), int64(runtime.NumCPU()))
}
if numCPUs > firecrackerMaxCPU {
numCPUs = firecrackerMaxCPU
}
networkMode, err := networkMode(args.Props.Network, args.Props.InitDockerd)
if err != nil {
return nil, err
}
vmConfig = &fcpb.VMConfiguration{
NumCpus: numCPUs,
MemSizeMb: int64(math.Max(1.0, float64(sizeEstimate.GetEstimatedMemoryBytes())/1e6)),
ScratchDiskSizeMb: int64(float64(sizeEstimate.GetEstimatedFreeDiskBytes()) / 1e6),
EnableLogging: platform.IsTrue(platform.FindEffectiveValue(args.Task.GetExecutionTask(), "debug-enable-vm-logs")),
NetworkMode: networkMode,
InitDockerd: args.Props.InitDockerd,
EnableDockerdTcp: args.Props.EnableDockerdTCP,
HostCpuid: getCPUID(),
EnableVfs: args.Props.EnableVFS,
}
vmConfig.BootArgs = getBootArgs(vmConfig)
opts := ContainerOpts{
VMConfiguration: vmConfig,
ContainerImage: args.Props.ContainerImage,
User: args.Props.DockerUser,
ActionWorkingDirectory: args.WorkDir,
CgroupParent: args.CgroupParent,
CgroupSettings: args.Task.GetSchedulingMetadata().GetCgroupSettings(),
BlockDevice: args.BlockDevice,
OverrideSnapshotKey: args.Props.OverrideSnapshotKey,
ExecutorConfig: p.executorConfig,
NetworkPool: p.networkPool,
MarshalledDNSOverrides: p.marshalledDNSOverrides,
UseOCIFetcher: args.Props.UseOCIFetcher,
}
c, err := NewContainer(ctx, p.env, args.Task.GetExecutionTask(), opts)
if err != nil {
return nil, err
}
return c, nil
}
// parseDNSOverrides validates the `dnsOverrides` flag and marshalls it to a string.
func parseDNSOverrides() (string, error) {
if len(*dnsOverrides) == 0 {
return "", nil
}
for _, o := range *dnsOverrides {
if o.HostnameToOverride == "" {
return "", status.InvalidArgumentErrorf("invalid empty dns override %+v", o)
}
// Ensure hostnames end with '.' so they are not resolved as relative names.
if !strings.HasSuffix(o.HostnameToOverride, ".") {
return "", status.InvalidArgumentErrorf("hostname_to_override %s should end with a '.'", o.HostnameToOverride)
}
}
marshalledOverrides, err := json.Marshal(*dnsOverrides)
if err != nil {
return "", status.WrapError(err, "marshall dns overrides")
}
return string(marshalledOverrides), nil
}
// FirecrackerContainer executes commands inside of a firecracker VM.
type FirecrackerContainer struct {
id string // a random GUID, unique per-run of firecracker
snapshotID string // a random GUID, unique per-run of firecracker
vmIdx int // the index of this vm on the host machine
loader *snaploader.FileCacheLoader
vmConfig *fcpb.VMConfiguration
containerImage string // the OCI container image. ex "alpine:latest"
actionWorkingDir string // the action directory with inputs / outputs
pulled bool // whether the container ext4 image has been pulled
user string // user to execute all commands as
rmOnce *sync.Once
rmErr error
networkPool *networking.VMNetworkPool
network *networking.VMNetwork
// Whether the VM was recycled.
recycled bool
// The following snapshot-related fields are initialized in NewContainer
// based on the incoming task. If there is a new task, you may want to call
// NewContainer again rather than directly unpausing a pre-existing container,
// to make sure these fields are updated and the best snapshot match is used
snapshotKeySet *fcpb.SnapshotKeySet
createFromSnapshot bool
supportsRemoteSnapshots bool
recyclingEnabled bool
// If set, the snapshot used to load the VM
snapshot *snaploader.Snapshot
// The current task assigned to the VM.
task *repb.ExecutionTask
// When the VM was initialized (i.e. created or unpaused) for the command
// it is currently executing
//
// This can be used to understand the total time it takes to execute a task,
// including VM startup time
currentTaskInitTime time.Time
executorConfig *ExecutorConfig
marshalledDNSOverrides string
// when VFS is enabled, this contains the layout for the next execution
fsLayout *container.FileSystemLayout
vfsServer *vfs_server.Server
scratchStore *copy_on_write.COWStore
scratchVBD *vbd.FS
rootStore *copy_on_write.COWStore
rootVBD *vbd.FS
uffdHandler *uffd.Handler
memoryStore *copy_on_write.COWStore
jailerRoot string // the root dir the jailer will work in
cgroupParent string // parent cgroup path (root-relative)
cgroupSettings *scpb.CgroupSettings // jailer cgroup settings
blockDevice *block_io.Device // block device for cgroup IO settings
machine *fcclient.Machine // the firecracker machine object.
vmLog *VMLog
env environment.Env
resolver *oci.Resolver
vmCtx context.Context
// cancelVmCtx cancels the Machine context, stopping the VMM if it hasn't
// already been stopped manually.
cancelVmCtx context.CancelCauseFunc
// releaseCPUs returns any CPUs that were leased for running the VM with.
releaseCPUs func()
vmExec struct {
conn *grpc.ClientConn
err error
}
useOCIFetcher bool
}
var _ container.VM = (*FirecrackerContainer)(nil)
func NewContainer(ctx context.Context, env environment.Env, task *repb.ExecutionTask, opts ContainerOpts) (*FirecrackerContainer, error) {
ctx, span := tracing.StartSpan(ctx)
defer span.End()
if opts.VMConfiguration == nil {
return nil, status.InvalidArgumentError("missing VMConfiguration")
}
if opts.VMConfiguration.InitDockerd && !networkingEnabled(opts.VMConfiguration.NetworkMode) {
return nil, status.FailedPreconditionError("InitDockerd set to true but NetworkMode set to OFF. Networking must be enabled to pass dockerd configuration over MMDS.")
}
vmLog, err := NewVMLog(vmLogTailBufSize)
if err != nil {
return nil, err
}
if opts.ExecutorConfig == nil {
return nil, status.InvalidArgumentError("missing opts.ExecutorConfig")
}
if len(opts.ExecutorConfig.JailerRoot) > 38 {
return nil, status.InvalidArgumentErrorf("build root dir %q length %d exceeds 38 character limit", opts.ExecutorConfig.JailerRoot, len(opts.ExecutorConfig.JailerRoot))
}
if err := disk.EnsureDirectoryExists(opts.ExecutorConfig.JailerRoot); err != nil {
return nil, err
}
loader, err := snaploader.New(env)
if err != nil {
return nil, err
}
resolver, err := oci.NewResolver(env)
if err != nil {
return nil, err
}
c := &FirecrackerContainer{
vmConfig: opts.VMConfiguration.CloneVT(),
executorConfig: opts.ExecutorConfig,
marshalledDNSOverrides: opts.MarshalledDNSOverrides,
jailerRoot: opts.ExecutorConfig.JailerRoot,
containerImage: opts.ContainerImage,
user: opts.User,
actionWorkingDir: opts.ActionWorkingDirectory,
cgroupParent: opts.CgroupParent,
networkPool: opts.NetworkPool,
cgroupSettings: &scpb.CgroupSettings{},
blockDevice: opts.BlockDevice,
env: env,
resolver: resolver,
task: task,
loader: loader,
vmLog: vmLog,
cancelVmCtx: func(err error) {},
useOCIFetcher: opts.UseOCIFetcher,
}
if opts.CgroupSettings != nil {
c.cgroupSettings = opts.CgroupSettings
}
c.vmConfig.GuestKernelVersion = c.executorConfig.GuestKernelVersion
if c.shouldUpgradeGuestKernel() {
c.vmConfig.GuestKernelVersion = c.executorConfig.GuestKernelVersion6_1
}
c.vmConfig.HostKernelVersion = c.executorConfig.HostKernelVersion
c.vmConfig.FirecrackerVersion = c.executorConfig.FirecrackerVersion
c.vmConfig.GuestApiVersion = c.executorConfig.GuestAPIVersion
if opts.ForceVMIdx != 0 {
c.vmIdx = opts.ForceVMIdx
}
c.supportsRemoteSnapshots = *snaputil.EnableRemoteSnapshotSharing && (platform.IsCICommand(task.GetCommand(), platform.GetProto(task.GetAction(), task.GetCommand())) || *forceRemoteSnapshotting)
if span.IsRecording() {
span.SetAttributes(attribute.Bool("supports_remote_snapshots", c.supportsRemoteSnapshots))
}
if opts.OverrideSnapshotKey == nil {
c.vmConfig.DebugMode = *debugTerminal
if err := c.newID(ctx); err != nil {
return nil, err
}
cd, err := digest.ComputeForMessage(c.vmConfig, repb.DigestFunction_SHA256)
if err != nil {
return nil, err
}
runnerID := c.id
if snaputil.IsChunkedSnapshotSharingEnabled() {
runnerID = ""
}
c.snapshotKeySet, err = loader.SnapshotKeySet(ctx, task, cd.GetHash(), runnerID)
if err != nil {
return nil, err
}
// If recycling is enabled and a snapshot exists, then when calling
// Create(), load the snapshot instead of creating a new VM.
recyclingEnabled := platform.IsRecyclingEnabled(task)
c.recyclingEnabled = recyclingEnabled
if recyclingEnabled && snaputil.IsChunkedSnapshotSharingEnabled() {
readPolicy, err := snapshotReadPolicy(task)
if err != nil {
return nil, err
}
snap, err := loader.GetSnapshot(ctx, c.snapshotKeySet, &snaploader.GetSnapshotOptions{
SupportsRemoteChunks: c.supportsRemoteSnapshots,
SupportsRemoteManifest: c.supportsRemoteSnapshots,
ReadPolicy: readPolicy,
})
c.createFromSnapshot = err == nil
label := ""
if err != nil {
label = metrics.MissStatusLabel
log.CtxInfof(ctx, "Failed to get VM snapshot for keyset %s: %s", snaploader.KeysetDebugString(ctx, c.env, c.SnapshotKeySet(), c.supportsRemoteSnapshots), err)
} else {
label = metrics.HitStatusLabel
log.CtxInfof(ctx, "Found snapshot %s", snaploader.SnapshotDebugString(ctx, c.env, snap))
}
metrics.RecycleRunnerRequests.With(prometheus.Labels{
metrics.RecycleRunnerRequestStatusLabel: label,
}).Inc()
}
} else {
if !snaputil.IsChunkedSnapshotSharingEnabled() {
return nil, status.InvalidArgumentError("chunked snapshot sharing must be enabled to provide an override snapshot key")
}
writeSnapshotID := uuid.New()
writeKey := opts.OverrideSnapshotKey.CloneVT()
writeKey.SnapshotId = writeSnapshotID
c.snapshotKeySet = &fcpb.SnapshotKeySet{BranchKey: opts.OverrideSnapshotKey, WriteKey: writeKey}
c.createFromSnapshot = true
c.recyclingEnabled = true
}
return c, nil
}
// MergeDiffSnapshot reads from diffSnapshotPath and writes all non-zero blocks
// into the baseSnapshotPath file or the baseSnapshotStore if non-nil.
func MergeDiffSnapshot(ctx context.Context, baseSnapshotPath string, baseSnapshotStore *copy_on_write.COWStore, diffSnapshotPath string, concurrency int, bufSize int) error {
ctx, span := tracing.StartSpan(ctx)
defer span.End()
metrics.SnapshotSaveWorkloadsExecuting.With(prometheus.Labels{
metrics.Stage: "merge_diff_snapshot",
}).Inc()
defer metrics.SnapshotSaveWorkloadsExecuting.With(prometheus.Labels{
metrics.Stage: "merge_diff_snapshot",
}).Dec()
var out io.WriterAt
var storeChunkSizeBytes int64
if baseSnapshotStore == nil {
f, err := os.OpenFile(baseSnapshotPath, os.O_WRONLY, 0644)
if err != nil {
return status.UnavailableErrorf("Could not open base snapshot file %q: %s", baseSnapshotPath, err)
}
defer f.Close()
out = f
} else {
out = baseSnapshotStore
storeChunkSizeBytes = baseSnapshotStore.ChunkSizeBytes()
}
in, err := os.Open(diffSnapshotPath)
if err != nil {
return status.UnavailableErrorf("Could not open diff snapshot file %q: %s", diffSnapshotPath, err)
}
defer in.Close()
inInfo, err := in.Stat()
if err != nil {
return status.UnavailableErrorf("Could not stat diff snapshot file %q: %s", diffSnapshotPath, err)
}
eg, ctx := errgroup.WithContext(ctx)
perThreadBytes := int64(math.Ceil(float64(inInfo.Size()) / float64(concurrency)))
perThreadBytes = alignToMultiple(perThreadBytes, int64(bufSize))
if baseSnapshotStore != nil {
// Ensure goroutines don't cross chunk boundaries and cause race conditions when writing
perThreadBytes = alignToMultiple(perThreadBytes, storeChunkSizeBytes)
}
for i := 0; i < concurrency; i++ {
i := i
offset := perThreadBytes * int64(i)
regionEnd := perThreadBytes * int64(i+1)
if regionEnd > inInfo.Size() {
regionEnd = inInfo.Size()
}
eg.Go(func() error {
gin, err := os.Open(diffSnapshotPath)
if err != nil {
return status.UnavailableErrorf("Could not open diff snapshot file %q: %s", diffSnapshotPath, err)
}
defer gin.Close()
buf := make([]byte, bufSize)
for {
select {
case <-ctx.Done():
return context.Cause(ctx)
default:
// continue with for loop
}
// 3 is the Linux constant for the SEEK_DATA option to lseek.
newOffset, err := syscall.Seek(int(gin.Fd()), offset, 3)
if err != nil {
// ENXIO is expected when the offset is within a hole at the end of
// the file.
if err == syscall.ENXIO {
if baseSnapshotStore != nil {
if err := baseSnapshotStore.UnmapChunk(offset); err != nil {
return err
}
}
break
}
return err
}
if baseSnapshotStore != nil {
ogChunkStartOffset := baseSnapshotStore.ChunkStartOffset(offset)
newChunkStartOffset := baseSnapshotStore.ChunkStartOffset(newOffset)
// If we've seeked to a new chunk, unmap the previous chunk to save memory
// usage on the executor
if newChunkStartOffset != ogChunkStartOffset {
if err := baseSnapshotStore.UnmapChunk(offset); err != nil {
return err
}
}
}
offset = newOffset
if offset >= regionEnd {
break
}
n, readErr := gin.ReadAt(buf, offset)
if readErr != nil && readErr != io.EOF {
return readErr
}
endOfDiffSnapshot := readErr == io.EOF
if _, err := out.WriteAt(buf[:n], offset); err != nil {
return err
}
if baseSnapshotStore != nil {
// If we've finished processing a chunk, unmap it to save memory
// usage on the executor
currentChunkStartOffset := baseSnapshotStore.ChunkStartOffset(offset)
newChunkStartOffset := baseSnapshotStore.ChunkStartOffset(offset + int64(n))
nextOffsetInNextChunk := newChunkStartOffset != currentChunkStartOffset
if nextOffsetInNextChunk || endOfDiffSnapshot {
if err := baseSnapshotStore.UnmapChunk(offset); err != nil {
return err
}
}
}
offset += int64(n)
if endOfDiffSnapshot {
break
}
}
return nil
})
}
return eg.Wait()
}
// alignToMultiple aligns the value n to a multiple of `multiple`
// It will round up if necessary
func alignToMultiple(n int64, multiple int64) int64 {
remainder := n % multiple