forked from kata-containers/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fc.go
1214 lines (1000 loc) · 32.4 KB
/
fc.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
// Copyright (c) 2018 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
package virtcontainers
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/containerd/fifo"
httptransport "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
kataclient "github.com/hfyeh/agent/protocols/client"
persistapi "github.com/hfyeh/runtime/virtcontainers/persist/api"
"github.com/hfyeh/runtime/virtcontainers/pkg/firecracker/client"
models "github.com/hfyeh/runtime/virtcontainers/pkg/firecracker/client/models"
ops "github.com/hfyeh/runtime/virtcontainers/pkg/firecracker/client/operations"
"github.com/opencontainers/selinux/go-selinux/label"
opentracing "github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/blang/semver"
"github.com/containerd/console"
"github.com/hfyeh/runtime/virtcontainers/device/config"
"github.com/hfyeh/runtime/virtcontainers/types"
"github.com/hfyeh/runtime/virtcontainers/utils"
)
type vmmState uint8
const (
notReady vmmState = iota
cfReady
vmReady
)
const (
//fcTimeout is the maximum amount of time in seconds to wait for the VMM to respond
fcTimeout = 10
fcSocket = "firecracker.socket"
//Name of the files within jailer root
//Having predefined names helps with cleanup
fcKernel = "vmlinux"
fcRootfs = "rootfs"
fcStopSandboxTimeout = 15
// This indicates the number of block devices that can be attached to the
// firecracker guest VM.
// We attach a pool of placeholder drives before the guest has started, and then
// patch the replace placeholder drives with drives with actual contents.
fcDiskPoolSize = 8
defaultHybridVSocketName = "kata.hvsock"
// This is the first usable vsock context ID. All the vsocks can use the same
// ID, since it's only used in the guest.
defaultGuestVSockCID = int64(0x3)
// This is related to firecracker logging scheme
fcLogFifo = "logs.fifo"
fcMetricsFifo = "metrics.fifo"
defaultFcConfig = "fcConfig.json"
// storagePathSuffix mirrors persist/fs/fs.go:storagePathSuffix
storagePathSuffix = "vc"
)
// Specify the minimum version of firecracker supported
var fcMinSupportedVersion = semver.MustParse("0.21.1")
var fcKernelParams = append(commonVirtioblkKernelRootParams, []Param{
// The boot source is the first partition of the first block device added
{"pci", "off"},
{"reboot", "k"},
{"panic", "1"},
{"iommu", "off"},
{"net.ifnames", "0"},
{"random.trust_cpu", "on"},
// Firecracker doesn't support ACPI
// Fix kernel error "ACPI BIOS Error (bug)"
{"acpi", "off"},
}...)
func (s vmmState) String() string {
switch s {
case notReady:
return "FC not ready"
case cfReady:
return "FC configure ready"
case vmReady:
return "FC VM ready"
}
return ""
}
// FirecrackerInfo contains information related to the hypervisor that we
// want to store on disk
type FirecrackerInfo struct {
PID int
Version string
}
type firecrackerState struct {
sync.RWMutex
state vmmState
}
func (s *firecrackerState) set(state vmmState) {
s.Lock()
defer s.Unlock()
s.state = state
}
// firecracker is an Hypervisor interface implementation for the firecracker VMM.
type firecracker struct {
id string //Unique ID per pod. Normally maps to the sandbox id
vmPath string //All jailed VM assets need to be under this
chrootBaseDir string //chroot base for the jailer
jailerRoot string
socketPath string
netNSPath string
uid string //UID and GID to be used for the VMM
gid string
info FirecrackerInfo
firecrackerd *exec.Cmd //Tracks the firecracker process itself
connection *client.Firecracker //Tracks the current active connection
ctx context.Context
config HypervisorConfig
pendingDevices []firecrackerDevice // Devices to be added before the FC VM ready
state firecrackerState
jailed bool //Set to true if jailer is enabled
stateful bool //Set to true if running with shimv2
fcConfigPath string
fcConfig *types.FcConfig // Parameters configured before VM starts
}
type firecrackerDevice struct {
dev interface{}
devType deviceType
}
// Logger returns a logrus logger appropriate for logging firecracker messages
func (fc *firecracker) Logger() *logrus.Entry {
return virtLog.WithField("subsystem", "firecracker")
}
func (fc *firecracker) trace(name string) (opentracing.Span, context.Context) {
if fc.ctx == nil {
fc.Logger().WithField("type", "bug").Error("trace called before context set")
fc.ctx = context.Background()
}
span, ctx := opentracing.StartSpanFromContext(fc.ctx, name)
span.SetTag("subsystem", "hypervisor")
span.SetTag("type", "firecracker")
return span, ctx
}
//At some cases, when sandbox id is too long, it will incur error of overlong
//firecracker API unix socket(fc.socketPath).
//In Linux, sun_path could maximumly contains 108 bytes in size.
//(http://man7.org/linux/man-pages/man7/unix.7.html)
func (fc *firecracker) truncateID(id string) string {
if len(id) > 32 {
//truncate the id to only leave the size of UUID(128bit).
return id[:32]
}
return id
}
// For firecracker this call only sets the internal structure up.
// The sandbox will be created and started through startSandbox().
func (fc *firecracker) createSandbox(ctx context.Context, id string, networkNS NetworkNamespace, hypervisorConfig *HypervisorConfig, stateful bool) error {
fc.ctx = ctx
span, _ := fc.trace("createSandbox")
defer span.Finish()
//TODO: check validity of the hypervisor config provided
//https://github.com/hfyeh/runtime/issues/1065
fc.id = fc.truncateID(id)
fc.state.set(notReady)
fc.config = *hypervisorConfig
fc.stateful = stateful
// When running with jailer all resources need to be under
// a specific location and that location needs to have
// exec permission (i.e. should not be mounted noexec, e.g. /run, /var/run)
// Also unix domain socket names have a hard limit
// #define UNIX_PATH_MAX 108
// Keep it short and live within the jailer expected paths
// <chroot_base>/<exec_file_name>/<id>/
// Also jailer based on the id implicitly sets up cgroups under
// <cgroups_base>/<exec_file_name>/<id>/
hypervisorName := filepath.Base(hypervisorConfig.HypervisorPath)
//fs.RunStoragePath cannot be used as we need exec perms
fc.chrootBaseDir = filepath.Join("/run", storagePathSuffix)
fc.vmPath = filepath.Join(fc.chrootBaseDir, hypervisorName, fc.id)
fc.jailerRoot = filepath.Join(fc.vmPath, "root") // auto created by jailer
// Firecracker and jailer automatically creates default API socket under /run
// with the name of "firecracker.socket"
fc.socketPath = filepath.Join(fc.jailerRoot, "run", fcSocket)
// So we need to repopulate this at startSandbox where it is valid
fc.netNSPath = networkNS.NetNsPath
// Till we create lower privileged kata user run as root
// https://github.com/hfyeh/runtime/issues/1869
fc.uid = "0"
fc.gid = "0"
fc.fcConfig = &types.FcConfig{}
fc.fcConfigPath = filepath.Join(fc.vmPath, defaultFcConfig)
return nil
}
func (fc *firecracker) newFireClient() *client.Firecracker {
span, _ := fc.trace("newFireClient")
defer span.Finish()
httpClient := client.NewHTTPClient(strfmt.NewFormats())
socketTransport := &http.Transport{
DialContext: func(ctx context.Context, network, path string) (net.Conn, error) {
addr, err := net.ResolveUnixAddr("unix", fc.socketPath)
if err != nil {
return nil, err
}
return net.DialUnix("unix", nil, addr)
},
}
transport := httptransport.New(client.DefaultHost, client.DefaultBasePath, client.DefaultSchemes)
transport.SetLogger(fc.Logger())
transport.SetDebug(fc.Logger().Logger.Level == logrus.DebugLevel)
transport.Transport = socketTransport
httpClient.SetTransport(transport)
return httpClient
}
func (fc *firecracker) vmRunning() bool {
resp, err := fc.client().Operations.DescribeInstance(nil)
if err != nil {
fc.Logger().WithError(err).Error("getting vm status failed")
return false
}
// Be explicit
switch *resp.Payload.State {
case models.InstanceInfoStateStarting:
// Unsure what we should do here
fc.Logger().WithField("unexpected-state", models.InstanceInfoStateStarting).Debug("vmRunning")
return false
case models.InstanceInfoStateRunning:
return true
case models.InstanceInfoStateUninitialized:
return false
default:
return false
}
}
func (fc *firecracker) getVersionNumber() (string, error) {
args := []string{"--version"}
checkCMD := exec.Command(fc.config.HypervisorPath, args...)
data, err := checkCMD.Output()
if err != nil {
return "", fmt.Errorf("Running checking FC version command failed: %v", err)
}
var version string
fields := strings.Split(string(data), " ")
if len(fields) > 1 {
// The output format of `Firecracker --verion` is as follows
// Firecracker v0.21.1
version = strings.TrimPrefix(strings.TrimSpace(fields[1]), "v")
return version, nil
}
return "", errors.New("getting FC version failed, the output is malformed")
}
func (fc *firecracker) checkVersion(version string) error {
v, err := semver.Make(version)
if err != nil {
return fmt.Errorf("Malformed firecracker version: %v", err)
}
if v.LT(fcMinSupportedVersion) {
return fmt.Errorf("version %v is not supported. Minimum supported version of firecracker is %v", v.String(), fcMinSupportedVersion.String())
}
return nil
}
// waitVMMRunning will wait for timeout seconds for the VMM to be up and running.
func (fc *firecracker) waitVMMRunning(timeout int) error {
span, _ := fc.trace("wait VMM to be running")
defer span.Finish()
if timeout < 0 {
return fmt.Errorf("Invalid timeout %ds", timeout)
}
timeStart := time.Now()
for {
if fc.vmRunning() {
return nil
}
if int(time.Since(timeStart).Seconds()) > timeout {
return fmt.Errorf("Failed to connect to firecrackerinstance (timeout %ds)", timeout)
}
time.Sleep(time.Duration(10) * time.Millisecond)
}
}
func (fc *firecracker) fcInit(timeout int) error {
span, _ := fc.trace("fcInit")
defer span.Finish()
var err error
//FC version set and check
if fc.info.Version, err = fc.getVersionNumber(); err != nil {
return err
}
if err := fc.checkVersion(fc.info.Version); err != nil {
return err
}
var cmd *exec.Cmd
var args []string
if fc.fcConfigPath, err = fc.fcJailResource(fc.fcConfigPath, defaultFcConfig); err != nil {
return err
}
if !fc.config.Debug && fc.stateful {
args = append(args, "--daemonize")
}
//https://github.com/firecracker-microvm/firecracker/blob/master/docs/jailer.md#jailer-usage
//--seccomp-level specifies whether seccomp filters should be installed and how restrictive they should be. Possible values are:
//0 : disabled.
//1 : basic filtering. This prohibits syscalls not whitelisted by Firecracker.
//2 (default): advanced filtering. This adds further checks on some of the parameters of the allowed syscalls.
if fc.jailed {
jailedArgs := []string{
"--id", fc.id,
"--node", "0", //FIXME: Comprehend NUMA topology or explicit ignore
"--exec-file", fc.config.HypervisorPath,
"--uid", "0", //https://github.com/hfyeh/runtime/issues/1869
"--gid", "0",
"--chroot-base-dir", fc.chrootBaseDir,
}
args = append(args, jailedArgs...)
if fc.netNSPath != "" {
args = append(args, "--netns", fc.netNSPath)
}
args = append(args, "--", "--config-file", fc.fcConfigPath)
cmd = exec.Command(fc.config.JailerPath, args...)
} else {
args = append(args,
"--api-sock", fc.socketPath,
"--config-file", fc.fcConfigPath)
cmd = exec.Command(fc.config.HypervisorPath, args...)
}
if fc.config.Debug && fc.stateful {
stdin, err := fc.watchConsole()
if err != nil {
return err
}
cmd.Stderr = stdin
cmd.Stdout = stdin
}
fc.Logger().WithField("hypervisor args", args).Debug()
fc.Logger().WithField("hypervisor cmd", cmd).Debug()
fc.Logger().Info("Starting VM")
if err := cmd.Start(); err != nil {
fc.Logger().WithField("Error starting firecracker", err).Debug()
return err
}
fc.info.PID = cmd.Process.Pid
fc.firecrackerd = cmd
fc.connection = fc.newFireClient()
if err := fc.waitVMMRunning(timeout); err != nil {
fc.Logger().WithField("fcInit failed:", err).Debug()
return err
}
return nil
}
func (fc *firecracker) fcEnd() (err error) {
span, _ := fc.trace("fcEnd")
defer span.Finish()
fc.Logger().Info("Stopping firecracker VM")
defer func() {
if err != nil {
fc.Logger().Info("fcEnd failed")
} else {
fc.Logger().Info("Firecracker VM stopped")
}
}()
pid := fc.info.PID
// Send a SIGTERM to the VM process to try to stop it properly
if err = syscall.Kill(pid, syscall.SIGTERM); err != nil {
if err == syscall.ESRCH {
return nil
}
return err
}
// Wait for the VM process to terminate
tInit := time.Now()
for {
if err = syscall.Kill(pid, syscall.Signal(0)); err != nil {
return nil
}
if time.Since(tInit).Seconds() >= fcStopSandboxTimeout {
fc.Logger().Warnf("VM still running after waiting %ds", fcStopSandboxTimeout)
break
}
// Let's avoid to run a too busy loop
time.Sleep(time.Duration(50) * time.Millisecond)
}
// Let's try with a hammer now, a SIGKILL should get rid of the
// VM process.
return syscall.Kill(pid, syscall.SIGKILL)
}
func (fc *firecracker) client() *client.Firecracker {
span, _ := fc.trace("client")
defer span.Finish()
if fc.connection == nil {
fc.connection = fc.newFireClient()
}
return fc.connection
}
func (fc *firecracker) createJailedDrive(name string) (string, error) {
// Don't bind mount the resource, just create a raw file
// that can be bind-mounted later
r := filepath.Join(fc.jailerRoot, name)
f, err := os.Create(r)
if err != nil {
return "", err
}
f.Close()
if fc.jailed {
// use path relative to the jail
r = filepath.Join("/", name)
}
return r, nil
}
// when running with jailer, firecracker binary will firstly be copied into fc.jailerRoot,
// and then being executed there. Therefore we need to ensure fc.JailerRoot has exec permissions.
func (fc *firecracker) fcRemountJailerRootWithExec() error {
if err := bindMount(context.Background(), fc.jailerRoot, fc.jailerRoot, false, "shared"); err != nil {
fc.Logger().WithField("JailerRoot", fc.jailerRoot).Errorf("bindMount failed: %v", err)
return err
}
// /run is normally mounted with rw, nosuid(MS_NOSUID), relatime(MS_RELATIME), noexec(MS_NOEXEC).
// we re-mount jailerRoot to deliberately leave out MS_NOEXEC.
if err := remount(context.Background(), syscall.MS_NOSUID|syscall.MS_RELATIME, fc.jailerRoot); err != nil {
fc.Logger().WithField("JailerRoot", fc.jailerRoot).Errorf("Re-mount failed: %v", err)
return err
}
return nil
}
func (fc *firecracker) fcJailResource(src, dst string) (string, error) {
if src == "" || dst == "" {
return "", fmt.Errorf("fcJailResource: invalid jail locations: src:%v, dst:%v",
src, dst)
}
jailedLocation := filepath.Join(fc.jailerRoot, dst)
if err := bindMount(context.Background(), src, jailedLocation, false, "slave"); err != nil {
fc.Logger().WithField("bindMount failed", err).Error()
return "", err
}
if !fc.jailed {
return jailedLocation, nil
}
// This is the path within the jailed root
absPath := filepath.Join("/", dst)
return absPath, nil
}
func (fc *firecracker) fcSetBootSource(path, params string) error {
span, _ := fc.trace("fcSetBootSource")
defer span.Finish()
fc.Logger().WithFields(logrus.Fields{"kernel-path": path,
"kernel-params": params}).Debug("fcSetBootSource")
kernelPath, err := fc.fcJailResource(path, fcKernel)
if err != nil {
return err
}
src := &models.BootSource{
KernelImagePath: &kernelPath,
BootArgs: params,
}
fc.fcConfig.BootSource = src
return nil
}
func (fc *firecracker) fcSetVMRootfs(path string) error {
span, _ := fc.trace("fcSetVMRootfs")
defer span.Finish()
jailedRootfs, err := fc.fcJailResource(path, fcRootfs)
if err != nil {
return err
}
driveID := "rootfs"
isReadOnly := true
//Add it as a regular block device
//This allows us to use a partitoned root block device
isRootDevice := false
// This is the path within the jailed root
drive := &models.Drive{
DriveID: &driveID,
IsReadOnly: &isReadOnly,
IsRootDevice: &isRootDevice,
PathOnHost: &jailedRootfs,
}
fc.fcConfig.Drives = append(fc.fcConfig.Drives, drive)
return nil
}
func (fc *firecracker) fcSetVMBaseConfig(mem int64, vcpus int64, htEnabled bool) {
span, _ := fc.trace("fcSetVMBaseConfig")
defer span.Finish()
fc.Logger().WithFields(logrus.Fields{"mem": mem,
"vcpus": vcpus,
"htEnabled": htEnabled}).Debug("fcSetVMBaseConfig")
cfg := &models.MachineConfiguration{
HtEnabled: &htEnabled,
MemSizeMib: &mem,
VcpuCount: &vcpus,
}
fc.fcConfig.MachineConfig = cfg
}
func (fc *firecracker) fcSetLogger() error {
span, _ := fc.trace("fcSetLogger")
defer span.Finish()
fcLogLevel := "Error"
if fc.config.Debug {
fcLogLevel = "Debug"
}
// listen to log fifo file and transfer error info
jailedLogFifo, err := fc.fcListenToFifo(fcLogFifo)
if err != nil {
return fmt.Errorf("Failed setting log: %s", err)
}
// listen to metrics file and transfer error info
jailedMetricsFifo, err := fc.fcListenToFifo(fcMetricsFifo)
if err != nil {
return fmt.Errorf("Failed setting log: %s", err)
}
fc.fcConfig.Logger = &models.Logger{
Level: &fcLogLevel,
LogFifo: &jailedLogFifo,
MetricsFifo: &jailedMetricsFifo,
}
return err
}
func (fc *firecracker) fcListenToFifo(fifoName string) (string, error) {
fcFifoPath := filepath.Join(fc.vmPath, fifoName)
fcFifo, err := fifo.OpenFifo(context.Background(), fcFifoPath, syscall.O_CREAT|syscall.O_RDONLY|syscall.O_NONBLOCK, 0)
if err != nil {
return "", fmt.Errorf("Failed to open/create fifo file %s", err)
}
jailedFifoPath, err := fc.fcJailResource(fcFifoPath, fifoName)
if err != nil {
return "", err
}
go func() {
scanner := bufio.NewScanner(fcFifo)
for scanner.Scan() {
fc.Logger().WithFields(logrus.Fields{
"fifoName": fifoName,
"contents": scanner.Text()}).Error("firecracker failed")
}
if err := scanner.Err(); err != nil {
fc.Logger().WithError(err).Errorf("Failed reading firecracker fifo file")
}
if err := fcFifo.Close(); err != nil {
fc.Logger().WithError(err).Errorf("Failed closing firecracker fifo file")
}
}()
return jailedFifoPath, nil
}
func (fc *firecracker) fcInitConfiguration() error {
// Firecracker API socket(firecracker.socket) is automatically created
// under /run dir.
err := os.MkdirAll(filepath.Join(fc.jailerRoot, "run"), DirMode)
if err != nil {
return err
}
defer func() {
if err != nil {
if err := os.RemoveAll(fc.vmPath); err != nil {
fc.Logger().WithError(err).Error("Fail to clean up vm directory")
}
}
}()
if fc.config.JailerPath != "" {
fc.jailed = true
if err := fc.fcRemountJailerRootWithExec(); err != nil {
return err
}
}
fc.fcSetVMBaseConfig(int64(fc.config.MemorySize),
int64(fc.config.NumVCPUs), false)
kernelPath, err := fc.config.KernelAssetPath()
if err != nil {
return err
}
if fc.config.Debug && fc.stateful {
fcKernelParams = append(fcKernelParams, Param{"console", "ttyS0"})
} else {
fcKernelParams = append(fcKernelParams, []Param{
{"8250.nr_uarts", "0"},
// Tell agent where to send the logs
{"agent.log_vport", fmt.Sprintf("%d", vSockLogsPort)},
}...)
}
kernelParams := append(fc.config.KernelParams, fcKernelParams...)
strParams := SerializeParams(kernelParams, "=")
formattedParams := strings.Join(strParams, " ")
if err := fc.fcSetBootSource(kernelPath, formattedParams); err != nil {
return err
}
image, err := fc.config.InitrdAssetPath()
if err != nil {
return err
}
if image == "" {
image, err = fc.config.ImageAssetPath()
if err != nil {
return err
}
}
if err := fc.fcSetVMRootfs(image); err != nil {
return err
}
if err := fc.createDiskPool(); err != nil {
return err
}
if err := fc.fcSetLogger(); err != nil {
return err
}
fc.state.set(cfReady)
for _, d := range fc.pendingDevices {
if err := fc.addDevice(d.dev, d.devType); err != nil {
return err
}
}
return nil
}
// startSandbox will start the hypervisor for the given sandbox.
// In the context of firecracker, this will start the hypervisor,
// for configuration, but not yet start the actual virtual machine
func (fc *firecracker) startSandbox(timeout int) error {
span, _ := fc.trace("startSandbox")
defer span.Finish()
if err := fc.fcInitConfiguration(); err != nil {
return err
}
data, errJSON := json.MarshalIndent(fc.fcConfig, "", "\t")
if errJSON != nil {
return errJSON
}
if err := ioutil.WriteFile(fc.fcConfigPath, data, 0640); err != nil {
return err
}
var err error
defer func() {
if err != nil {
fc.fcEnd()
}
}()
// This needs to be done as late as possible, since all processes that
// are executed by kata-runtime after this call, run with the SELinux
// label. If these processes require privileged, we do not want to run
// them under confinement.
if err := label.SetProcessLabel(fc.config.SELinuxProcessLabel); err != nil {
return err
}
defer label.SetProcessLabel("")
err = fc.fcInit(fcTimeout)
if err != nil {
return err
}
// make sure 'others' don't have access to this socket
err = os.Chmod(filepath.Join(fc.jailerRoot, defaultHybridVSocketName), 0640)
if err != nil {
return fmt.Errorf("Could not change socket permissions: %v", err)
}
fc.state.set(vmReady)
return nil
}
func fcDriveIndexToID(i int) string {
return "drive_" + strconv.Itoa(i)
}
func (fc *firecracker) createDiskPool() error {
span, _ := fc.trace("createDiskPool")
defer span.Finish()
for i := 0; i < fcDiskPoolSize; i++ {
driveID := fcDriveIndexToID(i)
isReadOnly := false
isRootDevice := false
// Create a temporary file as a placeholder backend for the drive
jailedDrive, err := fc.createJailedDrive(driveID)
if err != nil {
return err
}
drive := &models.Drive{
DriveID: &driveID,
IsReadOnly: &isReadOnly,
IsRootDevice: &isRootDevice,
PathOnHost: &jailedDrive,
}
fc.fcConfig.Drives = append(fc.fcConfig.Drives, drive)
}
return nil
}
func (fc *firecracker) umountResource(jailedPath string) {
hostPath := filepath.Join(fc.jailerRoot, jailedPath)
fc.Logger().WithField("resource", hostPath).Debug("Unmounting resource")
err := syscall.Unmount(hostPath, syscall.MNT_DETACH)
if err != nil {
fc.Logger().WithError(err).Error("Failed to umount resource")
}
}
// cleanup all jail artifacts
func (fc *firecracker) cleanupJail() {
span, _ := fc.trace("cleanupJail")
defer span.Finish()
fc.umountResource(fcKernel)
fc.umountResource(fcRootfs)
fc.umountResource(fcLogFifo)
fc.umountResource(fcMetricsFifo)
fc.umountResource(defaultFcConfig)
// if running with jailer, we also need to umount fc.jailerRoot
if fc.config.JailerPath != "" {
if err := syscall.Unmount(fc.jailerRoot, syscall.MNT_DETACH); err != nil {
fc.Logger().WithField("JailerRoot", fc.jailerRoot).WithError(err).Error("Failed to umount")
}
}
fc.Logger().WithField("cleaningJail", fc.vmPath).Info()
if err := os.RemoveAll(fc.vmPath); err != nil {
fc.Logger().WithField("cleanupJail failed", err).Error()
}
}
// stopSandbox will stop the Sandbox's VM.
func (fc *firecracker) stopSandbox() (err error) {
span, _ := fc.trace("stopSandbox")
defer span.Finish()
return fc.fcEnd()
}
func (fc *firecracker) pauseSandbox() error {
return nil
}
func (fc *firecracker) saveSandbox() error {
return nil
}
func (fc *firecracker) resumeSandbox() error {
return nil
}
func (fc *firecracker) fcAddVsock(hvs types.HybridVSock) {
span, _ := fc.trace("fcAddVsock")
defer span.Finish()
udsPath := hvs.UdsPath
if fc.jailed {
udsPath = filepath.Join("/", defaultHybridVSocketName)
}
vsockID := "root"
ctxID := defaultGuestVSockCID
vsock := &models.Vsock{
GuestCid: &ctxID,
UdsPath: &udsPath,
VsockID: &vsockID,
}
fc.fcConfig.Vsock = vsock
}
func (fc *firecracker) fcAddNetDevice(endpoint Endpoint) {
span, _ := fc.trace("fcAddNetDevice")
defer span.Finish()
ifaceID := endpoint.Name()
ifaceCfg := &models.NetworkInterface{
AllowMmdsRequests: false,
GuestMac: endpoint.HardwareAddr(),
IfaceID: &ifaceID,
HostDevName: &endpoint.NetworkPair().TapInterface.TAPIface.Name,
}
fc.fcConfig.NetworkInterfaces = append(fc.fcConfig.NetworkInterfaces, ifaceCfg)
}
func (fc *firecracker) fcAddBlockDrive(drive config.BlockDrive) error {
span, _ := fc.trace("fcAddBlockDrive")
defer span.Finish()
driveID := drive.ID
isReadOnly := false
isRootDevice := false
jailedDrive, err := fc.fcJailResource(drive.File, driveID)
if err != nil {
fc.Logger().WithField("fcAddBlockDrive failed", err).Error()
return err
}
driveFc := &models.Drive{
DriveID: &driveID,
IsReadOnly: &isReadOnly,
IsRootDevice: &isRootDevice,
PathOnHost: &jailedDrive,
}
fc.fcConfig.Drives = append(fc.fcConfig.Drives, driveFc)
return nil
}
// Firecracker supports replacing the host drive used once the VM has booted up
func (fc *firecracker) fcUpdateBlockDrive(path, id string) error {
span, _ := fc.trace("fcUpdateBlockDrive")
defer span.Finish()
// Use the global block index as an index into the pool of the devices
// created for firecracker.
driveParams := ops.NewPatchGuestDriveByIDParams()
driveParams.SetDriveID(id)
driveFc := &models.PartialDrive{
DriveID: &id,
PathOnHost: &path, //This is the only property that can be modified
}
driveParams.SetBody(driveFc)
if _, err := fc.client().Operations.PatchGuestDriveByID(driveParams); err != nil {
return err
}
return nil
}
// addDevice will add extra devices to firecracker. Limited to configure before the
// virtual machine starts. Devices include drivers and network interfaces only.
func (fc *firecracker) addDevice(devInfo interface{}, devType deviceType) error {
span, _ := fc.trace("addDevice")
defer span.Finish()
fc.state.RLock()
defer fc.state.RUnlock()
if fc.state.state == notReady {
dev := firecrackerDevice{
dev: devInfo,
devType: devType,
}
fc.Logger().Info("FC not ready, queueing device")
fc.pendingDevices = append(fc.pendingDevices, dev)
return nil
}
var err error
switch v := devInfo.(type) {
case Endpoint:
fc.Logger().WithField("device-type-endpoint", devInfo).Info("Adding device")
fc.fcAddNetDevice(v)
case config.BlockDrive:
fc.Logger().WithField("device-type-blockdrive", devInfo).Info("Adding device")
err = fc.fcAddBlockDrive(v)
case types.HybridVSock:
fc.Logger().WithField("device-type-hybrid-vsock", devInfo).Info("Adding device")
fc.fcAddVsock(v)
default:
fc.Logger().WithField("unknown-device-type", devInfo).Error("Adding device")