forked from firecracker-microvm/firecracker-containerd
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathservice.go
1795 lines (1496 loc) · 53.8 KB
/
service.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 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"net"
"os"
"runtime/debug"
"strconv"
"strings"
"sync"
"syscall"
"time"
// disable gosec check for math/rand. We just need a random starting
// place to start looking for CIDs; no need for cryptographically
// secure randomness
"math/rand" // #nosec
"github.com/containerd/containerd/api/types/task"
"github.com/containerd/containerd/cio"
"github.com/containerd/containerd/events/exchange"
"github.com/containerd/containerd/log"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/pkg/ttrpcutil"
"github.com/containerd/containerd/runtime/v2/shim"
taskAPI "github.com/containerd/containerd/runtime/v2/task"
"github.com/containerd/fifo"
"github.com/containerd/ttrpc"
"github.com/firecracker-microvm/firecracker-go-sdk"
"github.com/firecracker-microvm/firecracker-go-sdk/client/models"
"github.com/firecracker-microvm/firecracker-go-sdk/vsock"
"github.com/gofrs/uuid"
"github.com/gogo/protobuf/types"
"github.com/hashicorp/go-multierror"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/firecracker-microvm/firecracker-containerd/config"
"github.com/firecracker-microvm/firecracker-containerd/eventbridge"
"github.com/firecracker-microvm/firecracker-containerd/internal"
"github.com/firecracker-microvm/firecracker-containerd/internal/bundle"
"github.com/firecracker-microvm/firecracker-containerd/internal/vm"
"github.com/firecracker-microvm/firecracker-containerd/proto"
drivemount "github.com/firecracker-microvm/firecracker-containerd/proto/service/drivemount/ttrpc"
fccontrolTtrpc "github.com/firecracker-microvm/firecracker-containerd/proto/service/fccontrol/ttrpc"
ioproxy "github.com/firecracker-microvm/firecracker-containerd/proto/service/ioproxy/ttrpc"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
const (
defaultVsockPort = 10789
minVsockIOPort = uint32(11000)
// vmReadyTimeout is used to control the time all requests wait a Go channel (vmReady) before calling
// Firecracker's API server. The channel is closed once the VM starts.
vmReadyTimeout = 5 * time.Second
defaultCreateVMTimeout = 20 * time.Second
defaultStopVMTimeout = 5 * time.Second
defaultShutdownTimeout = 5 * time.Second
defaultVSockConnectTimeout = 5 * time.Second
// StartEventName is the topic published to when a VM starts
StartEventName = "/firecracker-vm/start"
// StopEventName is the topic published to when a VM stops
StopEventName = "/firecracker-vm/stop"
// taskExecID is a special exec ID that is pointing its task itself.
// While the constant is defined here, the convention is coming from containerd.
taskExecID = ""
)
var (
// type assertions
_ taskAPI.TaskService = &service{}
_ shim.Init = NewService
)
// implements shimapi
type service struct {
taskManager vm.TaskManager
eventExchange *exchange.Exchange
namespace string
logger *logrus.Entry
// Normally, it's ill-advised to store a context object in a struct. However,
// in this case there appears to be little choice. Containerd provides the
// context and cancel from their shim setup code to our NewService function.
// It is expected to live for the lifetime of the shim process and canceled
// when the shim is shutting down.
//
// The problem is that sometimes service methods, such as CreateVM, require
// a context scoped to the lifetime of the shim process but they are only provided
// a context scoped to the lifetime of the individual request, not the shimCtx.
//
// shimCtx should thus only be used by service methods that need to provide
// a context that will be canceled only when the shim is shutting down and
// cleanup should happen.
//
// This approach is also taken by containerd's current reference runc shim
// v2 implementation
shimCtx context.Context
shimCancel func()
vmID string
shimDir vm.Dir
config *config.Config
// vmReady is closed once CreateVM has been successfully called
vmReady chan struct{}
vmStartOnce sync.Once
agentClient taskAPI.TaskService
eventBridgeClient eventbridge.Getter
driveMountClient drivemount.DriveMounterService
ioProxyClient ioproxy.IOProxyService
jailer jailer
containerStubHandler *StubDriveHandler
driveMountStubs []MountableStubDrive
exitAfterAllTasksDeleted bool // exit the VM and shim when all tasks are deleted
blockDeviceTasks map[string]struct{}
cleanupErr error
cleanupOnce sync.Once
machine *firecracker.Machine
machineConfig *firecracker.Config
vsockIOPortCount uint32
vsockPortMu sync.Mutex
// fifos have stdio FIFOs containerd passed to the shim. The key is [taskID][execID].
fifos map[string]map[string]cio.Config
fifosMu sync.Mutex
}
func shimOpts(shimCtx context.Context) (*shim.Opts, error) {
opts, ok := shimCtx.Value(shim.OptsKey{}).(shim.Opts)
if !ok {
return nil, errors.New("failed to parse containerd shim opts from context")
}
return &opts, nil
}
// NewService creates new runtime shim.
func NewService(shimCtx context.Context, id string, remotePublisher shim.Publisher, shimCancel func()) (shim.Shim, error) {
cfg, err := config.LoadConfig("")
if err != nil {
return nil, err
}
opts, err := shimOpts(shimCtx)
if err != nil {
return nil, err
}
cfg.DebugHelper.ShimDebug = opts.Debug
namespace, ok := namespaces.Namespace(shimCtx)
if !ok {
namespace = namespaces.Default
}
var shimDir vm.Dir
vmID := os.Getenv(internal.VMIDEnvVarKey)
logger := log.G(shimCtx)
if vmID != "" {
logger = logger.WithField("vmID", vmID)
shimDir, err = vm.ShimDir(cfg.ShimBaseDir, namespace, vmID)
if err != nil {
return nil, fmt.Errorf("invalid shim directory: %s", err)
}
}
logrusLevel, ok := cfg.DebugHelper.GetFirecrackerContainerdLogLevel()
if ok {
logrus.SetLevel(logrusLevel)
logger.Logger.SetLevel(logrusLevel)
}
s := &service{
taskManager: vm.NewTaskManager(shimCtx, logger),
eventExchange: exchange.NewExchange(),
namespace: namespace,
logger: logger,
shimCtx: shimCtx,
shimCancel: shimCancel,
vmID: vmID,
shimDir: shimDir,
config: cfg,
vmReady: make(chan struct{}),
jailer: newNoopJailer(shimCtx, logger, shimDir),
blockDeviceTasks: make(map[string]struct{}),
fifos: make(map[string]map[string]cio.Config),
}
s.startEventForwarders(remotePublisher)
err = s.serveFCControl()
if err != nil {
err = fmt.Errorf("failed to start fccontrol server: %w", err)
s.logger.WithError(err).Error()
return nil, err
}
return s, nil
}
func (s *service) startEventForwarders(remotePublisher shim.Publisher) {
ns, ok := namespaces.Namespace(s.shimCtx)
if !ok {
s.logger.Error("failed to fetch the namespace from the context")
}
ctx := namespaces.WithNamespace(context.Background(), ns)
// Republish each event received on our exchange to the provided remote publisher.
// TODO ideally we would be forwarding events instead of re-publishing them, which would
// preserve the events' original timestamps and namespaces. However, as of this writing,
// the containerd v2 runtime model only provides a shim with a publisher, not a forwarder.
republishCh := eventbridge.Republish(ctx, s.eventExchange, remotePublisher)
go func() {
<-s.vmReady
// Once the VM is ready, also start forwarding events from it to our exchange
attachCh := eventbridge.Attach(ctx, s.eventBridgeClient, s.eventExchange)
err := <-attachCh
if err != nil && err != context.Canceled {
s.logger.WithError(err).Error("error while forwarding events from VM agent")
}
err = <-republishCh
if err != nil && err != context.Canceled {
s.logger.WithError(err).Error("error while republishing events")
}
remotePublisher.Close()
}()
}
// TODO we have to create separate listeners for the fccontrol service and shim service because
// containerd does not currently expose the shim server for us to register the fccontrol service with too.
// This is likely addressable through some relatively small upstream contributions; the following is a stop-gap
// solution until that time.
func (s *service) serveFCControl() error {
// If the fccontrol socket was configured, setup the fccontrol server
fcSocketFDEnvVal := os.Getenv(internal.FCSocketFDEnvKey)
if fcSocketFDEnvVal == "" {
// if there's no socket, we don't need to serve the API (this must be a shim start or shim delete call)
return nil
}
fcServer, err := ttrpc.NewServer(ttrpc.WithServerHandshaker(ttrpc.UnixSocketRequireSameUser()))
if err != nil {
return err
}
socketFD, err := strconv.Atoi(fcSocketFDEnvVal)
if err != nil {
err = fmt.Errorf("failed to parse fccontrol socket FD value: %w", err)
s.logger.WithError(err).Error()
return err
}
fccontrolTtrpc.RegisterFirecrackerService(fcServer, s)
fcListener, err := net.FileListener(os.NewFile(uintptr(socketFD), "fccontrol"))
if err != nil {
return err
}
go func() {
defer fcListener.Close()
err := fcServer.Serve(s.shimCtx, fcListener)
if err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
s.logger.WithError(err).Error("fccontrol ttrpc server error")
}
}()
return nil
}
func (s *service) StartShim(shimCtx context.Context, opts shim.StartOpts) (string, error) {
// In the shim start routine, we can assume that containerd provided a "log" FIFO in the current working dir.
// We have to use that instead of stdout/stderr because containerd reads the stdio pipes of shim start to get
// either the shim address or the error returned here.
logFifo, err := fifo.OpenFifo(shimCtx, "log", unix.O_WRONLY, 0200)
if err != nil {
return "", err
}
logrus.SetOutput(logFifo)
log := log.G(shimCtx).WithField("task_id", opts.ID)
log.Debug("StartShim")
// If we are running a shim start routine, we can safely assume our current working
// directory is the bundle directory
cwd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("failed to get current working directory: %w", err)
}
bundleDir := bundle.Dir(cwd)
// Since we're running a shim start routine, we need to determine the vmID for the incoming
// container. Start by looking at the container's OCI annotations
s.vmID, err = bundleDir.OCIConfig().VMID()
if err != nil {
return "", err
}
var exitAfterAllTasksDeleted bool
containerCount := 0
if s.vmID == "" {
// If here, no VMID has been provided by the client for this container, so auto-generate a new one.
// This results in a default behavior of running each container in its own VM if not otherwise
// specified by the client.
uuid, err := uuid.NewV4()
if err != nil {
return "", fmt.Errorf("failed to generate UUID for VMID: %w", err)
}
s.vmID = uuid.String()
// This request is handled by a short-lived shim process to find its control socket.
// A long-running shim process won't have the request. So, setting s.logger doesn't affect others.
log = log.WithField("vmID", s.vmID)
// If the client didn't specify a VMID, this is a single-task VM and should thus exit after this
// task is deleted
containerCount = 1
exitAfterAllTasksDeleted = true
}
client, err := ttrpcutil.NewClient(opts.TTRPCAddress)
if err != nil {
return "", err
}
ttrpcClient, err := client.Client()
if err != nil {
return "", err
}
fcControlClient := fccontrolTtrpc.NewFirecrackerClient(ttrpcClient)
_, err = fcControlClient.CreateVM(shimCtx, &proto.CreateVMRequest{
VMID: s.vmID,
ExitAfterAllTasksDeleted: exitAfterAllTasksDeleted,
ContainerCount: int32(containerCount),
})
if err != nil {
errStatus, ok := status.FromError(err)
// ignore AlreadyExists errors, that just means the shim is already up and running
if !ok || errStatus.Code() != codes.AlreadyExists {
return "", fmt.Errorf("unexpected error from CreateVM: %w", err)
}
}
// The shim cannot support traditional -version/-v flag because
// - shim.Run() will call flag.Parse(). So our main cannot call flag.Parse() before that.
// - -address is required and NewService() won't be called if the flag is missing.
// So we log the version informaion here instead
str := ""
if exitAfterAllTasksDeleted {
str = " The VM will be torn down after serving a single task."
}
log.WithField("vmID", s.vmID).Infof("successfully started shim (git commit: %s).%s", revision, str)
return shim.SocketAddress(shimCtx, opts.Address, s.vmID)
}
func logPanicAndDie(logger *logrus.Entry) {
if err := recover(); err != nil {
logger.WithError(err.(error)).Fatalf("panic: %s", string(debug.Stack()))
}
}
func (s *service) generateExtraData(jsonBytes []byte, options *types.Any) (*proto.ExtraData, error) {
var opts *types.Any
if options != nil {
// Copy values of existing options over
valCopy := make([]byte, len(options.Value))
copy(valCopy, options.Value)
opts = &types.Any{
TypeUrl: options.TypeUrl,
Value: valCopy,
}
}
return &proto.ExtraData{
JsonSpec: jsonBytes,
RuncOptions: opts,
StdinPort: s.nextVSockPort(),
StdoutPort: s.nextVSockPort(),
StderrPort: s.nextVSockPort(),
}, nil
}
// assumes caller has s.startVMMutex
func (s *service) nextVSockPort() uint32 {
s.vsockPortMu.Lock()
defer s.vsockPortMu.Unlock()
port := minVsockIOPort + s.vsockIOPortCount
if port == math.MaxUint32 {
// given we use 3 ports per container, there would need to
// be about 1431652098 containers spawned in this VM for
// this to actually happen in practice.
panic("overflow of vsock ports")
}
s.vsockIOPortCount++
return port
}
func (s *service) waitVMReady() error {
select {
case <-s.vmReady:
return nil
case <-time.After(vmReadyTimeout):
return status.Error(codes.DeadlineExceeded, "timed out waiting for VM start")
}
}
// CreateVM will attempt to create the VM as specified in the provided request, but only on the first request
// received. Any subsequent requests will be ignored and get an AlreadyExists error response.
func (s *service) CreateVM(requestCtx context.Context, request *proto.CreateVMRequest) (*proto.CreateVMResponse, error) {
defer logPanicAndDie(s.logger)
timeout := defaultCreateVMTimeout
if request.TimeoutSeconds > 0 {
timeout = time.Duration(request.TimeoutSeconds) * time.Second
}
ctxWithTimeout, cancel := context.WithTimeout(requestCtx, timeout)
defer cancel()
var (
err error
createRan bool
resp proto.CreateVMResponse
)
s.vmStartOnce.Do(func() {
err = s.createVM(ctxWithTimeout, request)
createRan = true
})
if !createRan {
return nil, status.Error(codes.AlreadyExists, "shim cannot create VM more than once")
}
// If we failed to create the VM, we have no point in existing anymore, so shutdown
if err != nil {
s.shimCancel()
s.logger.WithError(err).Error("failed to create VM")
if errors.Is(err, context.DeadlineExceeded) {
return nil, status.Errorf(codes.DeadlineExceeded, "VM %q didn't start within %s: %s", request.VMID, timeout, err)
}
return nil, fmt.Errorf("failed to create VM: %w", err)
}
// creating the VM succeeded, setup monitors and publish events to celebrate
err = s.publishVMStart()
if err != nil {
s.logger.WithError(err).Error("failed to publish start VM event")
}
go s.monitorVMExit()
// let all the other methods know that the VM is ready for tasks
close(s.vmReady)
resp.VMID = s.vmID
resp.MetricsFifoPath = s.machineConfig.MetricsFifo
resp.LogFifoPath = s.machineConfig.LogFifo
resp.SocketPath = s.shimDir.FirecrackerSockPath()
if c, ok := s.jailer.(cgroupPather); ok {
resp.CgroupPath = c.CgroupPath()
}
return &resp, nil
}
func (s *service) publishVMStart() error {
return s.eventExchange.Publish(s.shimCtx, StartEventName, &proto.VMStart{VMID: s.vmID})
}
func (s *service) publishVMStop() error {
return s.eventExchange.Publish(s.shimCtx, StopEventName, &proto.VMStop{VMID: s.vmID})
}
func (s *service) createVM(requestCtx context.Context, request *proto.CreateVMRequest) (err error) {
var vsockFd *os.File
defer func() {
if vsockFd != nil {
vsockFd.Close()
}
}()
namespace, ok := namespaces.Namespace(s.shimCtx)
if !ok {
namespace = namespaces.Default
}
dir, err := vm.ShimDir(s.config.ShimBaseDir, namespace, s.vmID)
if err != nil {
return err
}
s.logger.Info("creating new VM")
s.jailer, err = newJailer(s.shimCtx, s.logger, dir.RootPath(), s, request)
if err != nil {
return fmt.Errorf("failed to create jailer: %w", err)
}
defer func() {
// in the event of an error, we should stop the VM
if err != nil {
if e := s.jailer.Stop(true); e != nil {
s.logger.WithError(e).Debug("failed to stop firecracker")
}
}
}()
s.machineConfig, err = s.buildVMConfiguration(request)
if err != nil {
return fmt.Errorf("failed to build VM configuration: %w", err)
}
opts := []firecracker.Opt{}
if v, ok := s.config.DebugHelper.GetFirecrackerSDKLogLevel(); ok {
logger := log.G(s.shimCtx)
logger.Logger.SetLevel(v)
opts = append(opts, firecracker.WithLogger(logger))
}
relVSockPath, err := s.jailer.JailPath().FirecrackerVSockRelPath()
if err != nil {
return fmt.Errorf("failed to get relative path to firecracker vsock: %w", err)
}
jailedOpts, err := s.jailer.BuildJailedMachine(s.config, s.machineConfig, s.vmID)
if err != nil {
return fmt.Errorf("failed to build jailed machine options: %w", err)
}
if request.BalloonDevice == nil {
s.logger.Debug("No balloon device is setup")
} else {
// Creates a new balloon device if one does not already exist, otherwise updates it, before machine startup.
balloon, err := s.createBalloon(requestCtx, request)
if err != nil {
return fmt.Errorf("failed to create balloon device: %w", err)
}
balloonOpts, err := s.buildBalloonDeviceOpt(balloon)
if err != nil {
return fmt.Errorf("failed to create balloon device options: %w", err)
}
opts = append(opts, balloonOpts...)
}
opts = append(opts, jailedOpts...)
// In the event that a noop jailer is used, we will pass in the shim context
// and have the SDK construct a new machine using that context. Otherwise, a
// custom process runner will be provided via options which will stomp over
// the shim context that was provided here.
s.machine, err = firecracker.NewMachine(s.shimCtx, *s.machineConfig, opts...)
if err != nil {
return fmt.Errorf("failed to create new machine instance: %w", err)
}
if err = s.machine.Start(s.shimCtx); err != nil {
return fmt.Errorf("failed to start the VM: %w", err)
}
s.logger.Info("calling agent")
conn, err := vsock.DialContext(requestCtx, relVSockPath, defaultVsockPort, vsock.WithLogger(s.logger))
if err != nil {
return fmt.Errorf("failed to dial the VM over vsock: %w", err)
}
rpcClient := ttrpc.NewClient(conn, ttrpc.WithOnClose(func() { _ = conn.Close() }))
s.agentClient = taskAPI.NewTaskClient(rpcClient)
s.eventBridgeClient = eventbridge.NewGetterClient(rpcClient)
s.driveMountClient = drivemount.NewDriveMounterClient(rpcClient)
s.ioProxyClient = ioproxy.NewIOProxyClient(rpcClient)
s.exitAfterAllTasksDeleted = request.ExitAfterAllTasksDeleted
err = s.mountDrives(requestCtx)
if err != nil {
return err
}
s.logger.Info("successfully started the VM")
return nil
}
func (s *service) mountDrives(requestCtx context.Context) error {
for _, stubDrive := range s.driveMountStubs {
err := stubDrive.PatchAndMount(requestCtx, s.machine, s.driveMountClient)
if err != nil {
return fmt.Errorf("failed to patch drive mount stub: %w", err)
}
}
return nil
}
// StopVM will shutdown the VMM. Unlike Shutdown, this method is exposed to containerd clients.
// If the VM has not been created yet and the timeout is hit waiting for it to exist, an error will be returned
// but the shim will continue to shutdown. Similarly if we detect that the VM is in pause state, then
// we are unable to communicate to the in-VM agent. In this case, we do a forceful shutdown.
func (s *service) StopVM(requestCtx context.Context, request *proto.StopVMRequest) (_ *types.Empty, err error) {
defer logPanicAndDie(s.logger)
s.logger.WithFields(logrus.Fields{"timeout_seconds": request.TimeoutSeconds}).Debug("StopVM")
timeout := defaultStopVMTimeout
if request.TimeoutSeconds > 0 {
timeout = time.Duration(request.TimeoutSeconds) * time.Second
}
ctx, cancel := context.WithTimeout(requestCtx, timeout)
defer cancel()
if err = s.terminate(ctx); err != nil {
return nil, err
}
return &types.Empty{}, nil
}
// ResumeVM resumes a VM
func (s *service) ResumeVM(ctx context.Context, req *proto.ResumeVMRequest) (*types.Empty, error) {
defer logPanicAndDie(s.logger)
err := s.waitVMReady()
if err != nil {
s.logger.WithError(err).Error()
return nil, err
}
if err := s.machine.ResumeVM(ctx); err != nil {
s.logger.WithError(err).Error()
return nil, err
}
return &types.Empty{}, nil
}
// PauseVM pauses a VM
func (s *service) PauseVM(ctx context.Context, req *proto.PauseVMRequest) (*types.Empty, error) {
defer logPanicAndDie(s.logger)
err := s.waitVMReady()
if err != nil {
s.logger.WithError(err).Error()
return nil, err
}
if err := s.machine.PauseVM(ctx); err != nil {
s.logger.WithError(err).Error()
return nil, err
}
return &types.Empty{}, nil
}
// GetVMInfo returns metadata for the VM being managed by this shim. If the VM has not been created yet, this
// method will wait for up to a hardcoded timeout for it to exist, returning an error if the timeout is reached.
func (s *service) GetVMInfo(requestCtx context.Context, request *proto.GetVMInfoRequest) (*proto.GetVMInfoResponse, error) {
defer logPanicAndDie(s.logger)
err := s.waitVMReady()
if err != nil {
s.logger.WithError(err).Error()
return nil, err
}
cgroupPath := ""
if c, ok := s.jailer.(cgroupPather); ok {
cgroupPath = c.CgroupPath()
}
return &proto.GetVMInfoResponse{
VMID: s.vmID,
SocketPath: s.shimDir.FirecrackerSockPath(),
LogFifoPath: s.machineConfig.LogPath,
MetricsFifoPath: s.machineConfig.MetricsPath,
CgroupPath: cgroupPath,
VSockPath: s.shimDir.FirecrackerVSockPath(),
}, nil
}
// SetVMMetadata will update the VM being managed by this shim with the provided metadata. If the VM has not been created yet, this
// method will wait for up to a hardcoded timeout for it to exist, returning an error if the timeout is reached.
func (s *service) SetVMMetadata(requestCtx context.Context, request *proto.SetVMMetadataRequest) (*types.Empty, error) {
defer logPanicAndDie(s.logger)
err := s.waitVMReady()
if err != nil {
s.logger.WithError(err).Error()
return nil, err
}
s.logger.Info("setting VM metadata")
jayson := json.RawMessage(request.Metadata)
if err := s.machine.SetMetadata(requestCtx, jayson); err != nil {
err = fmt.Errorf("failed to set VM metadata: %w", err)
s.logger.WithError(err).Error()
return nil, err
}
return &types.Empty{}, nil
}
// UpdateVMMetadata updates the VM being managed by this shim with the provided metadata patch.
// If the vm has not been created yet, this method will wait for up to the hardcoded timeout for it
// to exist, returning an error if the timeout is reached.
func (s *service) UpdateVMMetadata(requestCtx context.Context, request *proto.UpdateVMMetadataRequest) (*types.Empty, error) {
defer logPanicAndDie(s.logger)
err := s.waitVMReady()
if err != nil {
s.logger.WithError(err).Error()
return nil, err
}
s.logger.Info("updating VM metadata")
jayson := json.RawMessage(request.Metadata)
if err := s.machine.UpdateMetadata(requestCtx, jayson); err != nil {
err = fmt.Errorf("failed to update VM metadata: %w", err)
s.logger.WithError(err).Error()
return nil, err
}
return &types.Empty{}, nil
}
// GetVMMetadata returns the metadata for the vm managed by this shim..
// If the vm has not been created yet, this method will wait for up to the hardcoded timeout for it
// to exist, returning an error if the timeout is reached.
func (s *service) GetVMMetadata(requestCtx context.Context, request *proto.GetVMMetadataRequest) (*proto.GetVMMetadataResponse, error) {
defer logPanicAndDie(s.logger)
err := s.waitVMReady()
if err != nil {
s.logger.WithError(err).Error()
return nil, err
}
s.logger.Info("Get VM metadata")
var metadata json.RawMessage
if err := s.machine.GetMetadata(requestCtx, &metadata); err != nil {
err = fmt.Errorf("failed to get VM metadata: %w", err)
s.logger.WithError(err).Error()
return nil, err
}
return &proto.GetVMMetadataResponse{Metadata: string(metadata)}, nil
}
func (s *service) createBalloon(requestCtx context.Context, request *proto.CreateVMRequest) (models.Balloon, error) {
amountMiB := request.BalloonDevice.AmountMib
deflateOnOom := request.BalloonDevice.DeflateOnOom
statsPollingIntervals := request.BalloonDevice.StatsPollingIntervals
balloonDevice := firecracker.NewBalloonDevice(amountMiB, deflateOnOom, firecracker.WithStatsPollingIntervals(statsPollingIntervals))
balloon := balloonDevice.Build()
if balloon.AmountMib == nil || balloon.DeflateOnOom == nil {
return balloon, fmt.Errorf("One of balloon properties is nil, please check %+v: ", balloon)
}
s.logger.Infof("Creating a balloon device: AmountMib=%d, DeflateOnOom=%t and statsPollingIntervals=%d ", *balloon.AmountMib, *balloon.DeflateOnOom, balloon.StatsPollingIntervals)
return balloon, nil
}
func (s *service) buildBalloonDeviceOpt(balloon models.Balloon) ([]firecracker.Opt, error) {
handler := firecracker.NewCreateBalloonHandler(*balloon.AmountMib, *balloon.DeflateOnOom, balloon.StatsPollingIntervals)
opt := []firecracker.Opt{
func(m *firecracker.Machine) {
m.Handlers.FcInit = m.Handlers.FcInit.AppendAfter(firecracker.CreateMachineHandlerName, handler)
},
}
return opt, nil
}
// GetBalloonConfig will get configuration for an existing balloon device, before or after machine startup
func (s *service) GetBalloonConfig(requestCtx context.Context, req *proto.GetBalloonConfigRequest) (*proto.GetBalloonConfigResponse, error) {
defer logPanicAndDie(s.logger)
err := s.waitVMReady()
if err != nil {
s.logger.WithError(err).Error()
return nil, err
}
s.logger.Info("Getting configuration for the balloon device")
balloon, err := s.machine.GetBalloonConfig(requestCtx)
if err != nil {
return nil, errors.New("Failed to get balloon configuration. Please check if you have successfully created a balloon device")
}
balloonConfig := &proto.FirecrackerBalloonDevice{
AmountMib: *balloon.AmountMib,
DeflateOnOom: *balloon.DeflateOnOom,
StatsPollingIntervals: balloon.StatsPollingIntervals,
}
return &proto.GetBalloonConfigResponse{BalloonConfig: balloonConfig}, err
}
// UpdateBalloon will update an existing balloon device, before or after machine startup
func (s *service) UpdateBalloon(requestCtx context.Context, req *proto.UpdateBalloonRequest) (*types.Empty, error) {
defer logPanicAndDie(s.logger)
err := s.waitVMReady()
if err != nil {
s.logger.WithError(err).Error()
return nil, err
}
s.logger.Infof("Updating balloon memory size, the new amount memory is %d MiB", req.AmountMib)
if err := s.machine.UpdateBalloon(requestCtx, req.AmountMib); err != nil {
err = fmt.Errorf("failed to update memory balloon: %w", err)
s.logger.WithError(err).Error()
return nil, err
}
return &types.Empty{}, nil
}
// GetBalloonStats will return the latest balloon device statistics, only if enabled pre-boot.
func (s *service) GetBalloonStats(requestCtx context.Context, req *proto.GetBalloonStatsRequest) (*proto.GetBalloonStatsResponse, error) {
defer logPanicAndDie(s.logger)
err := s.waitVMReady()
if err != nil {
s.logger.WithError(err).Error()
return nil, err
}
s.logger.Info("Getting statistics for the balloon device")
balloonStats, err := s.machine.GetBalloonStats(requestCtx)
if err != nil {
err = fmt.Errorf("failed to get balloon statistics: %w", err)
s.logger.WithError(err).Error()
return nil, err
}
if balloonStats.ActualMib == nil ||
balloonStats.ActualPages == nil ||
balloonStats.TargetMib == nil ||
balloonStats.TargetPages == nil {
return nil, fmt.Errorf("One of BalloonStats properties is nil, please check %+v: ", balloonStats)
}
resp := &proto.GetBalloonStatsResponse{
ActualMib: *balloonStats.ActualMib,
ActualPages: *balloonStats.ActualPages,
AvailableMemory: balloonStats.AvailableMemory,
DiskCaches: balloonStats.DiskCaches,
FreeMemory: balloonStats.FreeMemory,
HugetlbAllocations: balloonStats.HugetlbAllocations,
HugetlbFailures: balloonStats.HugetlbFailures,
MajorFaults: balloonStats.MajorFaults,
MinorFaults: balloonStats.MinorFaults,
SwapIn: balloonStats.SwapIn,
SwapOut: balloonStats.SwapOut,
TargetMib: *balloonStats.TargetMib,
TargetPages: *balloonStats.TargetPages,
TotalMemory: balloonStats.TotalMemory,
}
s.logger.Info("GetBalloonStatsResponse: ", resp)
return resp, nil
}
// UpdateBalloonStats will update an existing balloon device statistics interval, before or after machine startup.
func (s *service) UpdateBalloonStats(requestCtx context.Context, req *proto.UpdateBalloonStatsRequest) (*types.Empty, error) {
defer logPanicAndDie(s.logger)
err := s.waitVMReady()
if err != nil {
s.logger.WithError(err).Error()
return nil, err
}
s.logger.Info("updating balloon device statistics interval")
if err := s.machine.UpdateBalloonStats(requestCtx, req.StatsPollingIntervals); err != nil {
err = fmt.Errorf("failed to update balloon device statistics interval: %w", err)
s.logger.WithError(err).Error()
return nil, err
}
return &types.Empty{}, nil
}
func (s *service) buildVMConfiguration(req *proto.CreateVMRequest) (*firecracker.Config, error) {
for _, driveMount := range req.DriveMounts {
// Verify the request specified an absolute path for the source/dest of drives.
// Otherwise, users can implicitly rely on the CWD of this shim or agent.
if !strings.HasPrefix(driveMount.HostPath, "/") || !strings.HasPrefix(driveMount.VMPath, "/") {
return nil, fmt.Errorf("driveMount %s contains relative path", driveMount.String())
}
}
relSockPath, err := s.shimDir.FirecrackerSockRelPath()
if err != nil {
return nil, fmt.Errorf("failed to get relative path to firecracker api socket: %w", err)
}
relVSockPath, err := s.jailer.JailPath().FirecrackerVSockRelPath()
if err != nil {
return nil, fmt.Errorf("failed to get relative path to firecracker vsock: %w", err)
}
cfg := firecracker.Config{
SocketPath: relSockPath,
VsockDevices: []firecracker.VsockDevice{{
Path: relVSockPath,
ID: "agent_api",
}},
MachineCfg: machineConfigurationFromProto(s.config, req.MachineCfg),
LogLevel: s.config.DebugHelper.GetFirecrackerLogLevel(),
VMID: s.vmID,
}
flag, err := internal.SupportCPUTemplate()
if err != nil {
return nil, err
}
if !flag {
cfg.MachineCfg.CPUTemplate = ""
}
logPath := s.shimDir.FirecrackerLogFifoPath()
if req.LogFifoPath != "" {
logPath = req.LogFifoPath
}
err = syscall.Mkfifo(logPath, 0700)
if err != nil {
return nil, err
}
metricsPath := s.shimDir.FirecrackerMetricsFifoPath()
if req.MetricsFifoPath != "" {
metricsPath = req.MetricsFifoPath
}
err = syscall.Mkfifo(metricsPath, 0700)
if err != nil {
return nil, err
}
// The Config struct has LogFifo and MetricsFifo, but they will be deprecated since
// Firecracker doesn't have the corresponding fields anymore.
cfg.LogPath = logPath
cfg.MetricsPath = metricsPath
if req.JailerConfig != nil {
cfg.NetNS = req.JailerConfig.NetNS
}
s.logger.Debugf("using socket path: %s", cfg.SocketPath)
// Kernel configuration
if val := req.KernelArgs; val != "" {
cfg.KernelArgs = val
} else {
cfg.KernelArgs = s.config.KernelArgs
}
if val := req.KernelImagePath; val != "" {