-
Notifications
You must be signed in to change notification settings - Fork 64
/
v1alpha1.go
604 lines (496 loc) · 17.7 KB
/
v1alpha1.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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2022, Unikraft GmbH and The KraftKit Authors.
// Licensed under the BSD-3-Clause License (the "License").
// You may not use this file except in compliance with the License.
package firecracker
import (
"context"
"fmt"
"io/fs"
"os"
"path/filepath"
"time"
zip "api.zip"
"github.com/acorn-io/baaah/pkg/merr"
firecracker "github.com/firecracker-microvm/firecracker-go-sdk"
"github.com/firecracker-microvm/firecracker-go-sdk/client/models"
"github.com/fsnotify/fsnotify"
goprocess "github.com/shirou/gopsutil/v3/process"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/uuid"
machinev1alpha1 "kraftkit.sh/api/machine/v1alpha1"
"kraftkit.sh/config"
"kraftkit.sh/exec"
"kraftkit.sh/internal/logtail"
"kraftkit.sh/internal/run"
"kraftkit.sh/log"
"kraftkit.sh/machine/network/macaddr"
"kraftkit.sh/unikraft/export/v0/posixenviron"
"kraftkit.sh/unikraft/export/v0/ukargparse"
"kraftkit.sh/unikraft/export/v0/uknetdev"
"kraftkit.sh/unikraft/export/v0/vfscore"
)
const (
FirecrackerBin = "firecracker"
DefaultClientTimout = time.Second * 5
FirecrackerMemoryScale = 1024 * 1024
)
// machineV1alpha1Service ...
type machineV1alpha1Service struct {
timeout time.Duration
debug bool
}
// NewMachineV1alpha1Service implements mdriver.NewDriverConstructor
func NewMachineV1alpha1Service(ctx context.Context, opts ...any) (machinev1alpha1.MachineService, error) {
service := machineV1alpha1Service{}
for _, opt := range opts {
qopt, ok := opt.(MachineServiceV1alpha1Option)
if !ok {
panic("cannot apply non-MachineServiceV1alpha1Option type methods")
}
if err := qopt(&service); err != nil {
return nil, err
}
}
if service.timeout == 0 {
service.timeout = DefaultClientTimout
}
return &service, nil
}
// Create implements kraftkit.sh/api/machine/v1alpha1.MachineService.Create
func (service *machineV1alpha1Service) Create(ctx context.Context, machine *machinev1alpha1.Machine) (*machinev1alpha1.Machine, error) {
// Start with fail-safe checks for unsupported specification declarations.
if len(machine.Spec.Ports) > 0 {
return machine, fmt.Errorf("kraftkit does not yet support port forwarding to firecracker (contributions welcome): please use a network instead")
}
if machine.Status.KernelPath == "" {
return machine, fmt.Errorf("cannot create firecracker instance without kernel")
}
if machine.Spec.Emulation {
return machine, fmt.Errorf("cannot create firecracker instance with emulation")
}
if machine.ObjectMeta.UID == "" {
machine.ObjectMeta.UID = uuid.NewUUID()
}
machine.Status.State = machinev1alpha1.MachineStateUnknown
if len(machine.Status.StateDir) == 0 {
machine.Status.StateDir = filepath.Join(config.G[config.KraftKit](ctx).RuntimeDir, string(machine.ObjectMeta.UID))
}
if err := os.MkdirAll(machine.Status.StateDir, fs.ModeSetgid|0o775); err != nil {
return machine, err
}
// Set and create the log file for this machine
if len(machine.Status.LogFile) == 0 {
machine.Status.LogFile = filepath.Join(machine.Status.StateDir, "machine.log")
}
var fstab []string
for _, vol := range machine.Spec.Volumes {
switch vol.Spec.Driver {
case "initrd":
fstab = append(fstab, vfscore.NewFstabEntry(
"initrd0",
vol.Spec.Destination,
"extract",
"",
"",
"",
).String())
default:
return machine, fmt.Errorf("unsupported Firecracker volume driver: %v", vol.Spec.Driver)
}
}
if machine.Spec.Resources.Requests.Memory().Value() == 0 {
quantity, err := resource.ParseQuantity("64Mi")
if err != nil {
machine.Status.State = machinev1alpha1.MachineStateFailed
return machine, err
}
machine.Spec.Resources.Requests[corev1.ResourceMemory] = quantity
}
if machine.Spec.Resources.Requests.Cpu().Value() == 0 {
quantity, err := resource.ParseQuantity("1")
if err != nil {
machine.Status.State = machinev1alpha1.MachineStateFailed
return machine, err
}
machine.Spec.Resources.Requests[corev1.ResourceCPU] = quantity
}
fcLogFile := filepath.Join(machine.Status.StateDir, "firecracker.log")
fi, err := os.Create(fcLogFile)
if err != nil {
return machine, err
}
fi.Close()
fccfg := FirecrackerConfig{
SocketPath: filepath.Join(machine.Status.StateDir, "firecracker.sock"),
LogPath: fcLogFile,
Memory: machine.Spec.Resources.Requests.Memory().String(),
}
defer func() {
if err != nil {
machine.Status.State = machinev1alpha1.MachineStateFailed
}
}()
// If you fork and replace the stdout file descriptor with an fd of a log file
// and then execv firecracker, you don't have to care about collecting the
// logs
logFile, err := os.Create(machine.Status.LogFile)
if err != nil {
return machine, err
}
defer logFile.Close()
machine.Status.PlatformConfig = &fccfg
e, err := exec.NewExecutable(FirecrackerBin, ExecConfig{
Id: string(machine.UID),
ApiSock: fccfg.SocketPath,
})
if err != nil {
return machine, fmt.Errorf("could not prepare firecracker executable: %v", err)
}
process, err := exec.NewProcessFromExecutable(e,
exec.WithStdout(logFile),
exec.WithDetach(true),
)
if err != nil {
return machine, fmt.Errorf("could not prepare firecracker process: %v", err)
}
machine.CreationTimestamp = metav1.NewTime(time.Now())
// Pre-emptively prepare inotify on the state directory so we can wait until
// the socket file has been created. This is an indicator that firecracker
// process has initialized into a running state.
watcher, err := fsnotify.NewWatcher()
if err != nil {
return machine, err
}
defer watcher.Close()
if err := watcher.Add(machine.Status.StateDir); err != nil {
return machine, err
}
// Start and also wait for the process to be released, this ensures the
// program is actively being executed.
if err := process.Start(ctx); err != nil {
return machine, fmt.Errorf("could not start and wait for firecracker process: %v", err)
}
// Wait for the socket file to be created
watch:
for {
select {
case event, ok := <-watcher.Events:
if !ok {
continue
}
if event.Name == fccfg.SocketPath {
break watch
}
case <-ctx.Done():
err = ctx.Err()
break watch
}
}
pid, err := process.Pid()
if err != nil {
return machine, fmt.Errorf("could not get firecracker pid: %v", err)
}
client := firecracker.NewClient(fccfg.SocketPath, logrus.NewEntry(log.G(ctx)), false)
kernelArgs, err := ukargparse.Parse(machine.Spec.KernelArgs...)
if err != nil {
return machine, err
}
if len(fstab) > 0 {
kernelArgs = append(kernelArgs,
vfscore.ParamVfsFstab.WithValue(fstab),
)
}
var environ []string
for k, v := range machine.Spec.Env {
environ = append(environ, fmt.Sprintf("%s=%s", k, v))
}
if len(environ) > 0 {
kernelArgs = append(kernelArgs,
posixenviron.ParamEnvVars.WithValue(environ),
)
}
if len(machine.Spec.Networks) > 0 {
// Start MAC addresses iteratively. Each interface will have the last
// hexdecimal byte increase by 1 starting at 1, allowing for easy-to-spot
// interface IDs from the MAC address. The return value below returns `:00`
// as the last byte.
startMac, err := macaddr.GenerateMacAddress(true)
if err != nil {
return machine, err
}
i := 0 // host network ID.
// Iterate over each interface of each network interface associated with
// this machine and attach it as a device.
for _, network := range machine.Spec.Networks {
for _, iface := range network.Interfaces {
mac := iface.Spec.MacAddress
if mac == "" {
// Increase the MAC address value by 1 such that we are able to
// identify interface IDs.
startMac = macaddr.IncrementMacAddress(startMac)
mac = startMac.String()
}
if _, err := client.PutGuestNetworkInterfaceByID(ctx, network.IfName, &models.NetworkInterface{
GuestMac: mac,
HostDevName: &iface.Spec.IfName,
IfaceID: &network.IfName,
}); err != nil {
return machine, err
}
kernelArgs = append(kernelArgs,
uknetdev.NewParamIp().WithValue(uknetdev.NetdevIp{
CIDR: iface.Spec.CIDR,
Gateway: iface.Spec.Gateway,
DNS0: iface.Spec.DNS0,
DNS1: iface.Spec.DNS1,
Hostname: iface.Spec.Hostname,
Domain: iface.Spec.Domain,
}),
)
// Increment the host network ID for additional interfaces.
i++
}
}
}
// TODO(nderjung): This is standard "Unikraft" positional argument syntax
// (kernel args and application arguments separated with "--"). The resulting
// string should be standardized through a central function.
args := []string{filepath.Base(machine.Status.KernelPath)}
args = append(args, kernelArgs.Strings()...)
if len(args) > 0 {
args = append(args, "--")
}
args = append(args, machine.Spec.ApplicationArgs...)
// Set the machine's resource configuration.
if _, err := client.PutMachineConfiguration(ctx, &models.MachineConfiguration{
VcpuCount: firecracker.Int64(machine.Spec.Resources.Requests.Cpu().Value()),
MemSizeMib: firecracker.Int64(machine.Spec.Resources.Requests.Memory().Value() / FirecrackerMemoryScale),
}); err != nil {
return machine, err
}
// Set the boot source configuration.
if _, err := client.PutGuestBootSource(ctx, &models.BootSource{
KernelImagePath: &machine.Status.KernelPath,
InitrdPath: machine.Status.InitrdPath,
BootArgs: run.BootArgsPrepare(args...),
}); err != nil {
return machine, err
}
// Set the logger information.
if service.debug {
if _, err := client.PutLogger(ctx, &models.Logger{
Level: firecracker.String("Debug"),
LogPath: firecracker.String(filepath.Join(machine.Status.StateDir, "firecracker.log")),
ShowLevel: firecracker.Bool(true),
ShowLogOrigin: firecracker.Bool(true),
}); err != nil {
return machine, err
}
}
machine.Status.Pid = int32(pid)
machine.Status.State = machinev1alpha1.MachineStateCreated
return machine, nil
}
func getFirecrackerConfigFromPlatformConfig(platformConfig interface{}) (*FirecrackerConfig, error) {
fccfgptr, ok := platformConfig.(*FirecrackerConfig)
if ok {
return fccfgptr, nil
}
fccfg, ok := platformConfig.(FirecrackerConfig)
if ok {
return &fccfg, nil
}
return nil, fmt.Errorf("could not cast firecracker platform config from store")
}
// Update implements kraftkit.sh/api/machine/v1alpha1.MachineService
func (service *machineV1alpha1Service) Update(ctx context.Context, machine *machinev1alpha1.Machine) (*machinev1alpha1.Machine, error) {
panic("not implemented: kraftkit.sh/machine/firecracker.machineV1alpha1Service.Update")
}
// Watch implements kraftkit.sh/api/machine/v1alpha1.MachineService
func (service *machineV1alpha1Service) Watch(ctx context.Context, machine *machinev1alpha1.Machine) (chan *machinev1alpha1.Machine, chan error, error) {
events := make(chan *machinev1alpha1.Machine)
errs := make(chan error)
go service.watch(ctx, machine, &events, &errs)
return events, errs, nil
}
func (service *machineV1alpha1Service) watch(ctx context.Context, machine *machinev1alpha1.Machine, events *chan *machinev1alpha1.Machine, errs *chan error) {
for {
select {
case <-ctx.Done():
log.G(ctx).Info("context cancelled (watch)")
*errs <- ctx.Err()
return
default:
process, err := os.FindProcess(int(machine.Status.Pid))
if err != nil {
return
}
state, err := process.Wait()
if err != nil {
*errs <- err
return
}
if state.Exited() {
machine.Status.State = machinev1alpha1.MachineStateExited
machine.Status.ExitCode = state.ExitCode()
}
*events <- machine
}
}
}
// Start implements kraftkit.sh/api/machine/v1alpha1.MachineService
func (service *machineV1alpha1Service) Start(ctx context.Context, machine *machinev1alpha1.Machine) (*machinev1alpha1.Machine, error) {
fccfg, err := getFirecrackerConfigFromPlatformConfig(machine.Status.PlatformConfig)
if err != nil {
return machine, err
}
client := firecracker.NewClient(fccfg.SocketPath, logrus.NewEntry(log.G(ctx)), false)
action := models.InstanceActionInfoActionTypeInstanceStart
info := models.InstanceActionInfo{
ActionType: &action,
}
if _, err := client.CreateSyncAction(ctx, &info); err != nil {
return machine, err
}
machine.Status.State = machinev1alpha1.MachineStateRunning
machine.Status.StartedAt = time.Now()
return machine, nil
}
// Pause implements kraftkit.sh/api/machine/v1alpha1.MachineService
func (service *machineV1alpha1Service) Pause(ctx context.Context, machine *machinev1alpha1.Machine) (*machinev1alpha1.Machine, error) {
panic("not implemented: kraftkit.sh/machine/firecracker.machineV1alpha1Service.Pause")
}
// Logs implements kraftkit.sh/api/machine/v1alpha1.MachineService
func (service *machineV1alpha1Service) Logs(ctx context.Context, machine *machinev1alpha1.Machine) (chan string, chan error, error) {
return logtail.NewLogTail(ctx, machine.Status.LogFile)
}
// Get implements kraftkit.sh/api/machine/v1alpha1/MachineService.Get
func (service *machineV1alpha1Service) Get(ctx context.Context, machine *machinev1alpha1.Machine) (*machinev1alpha1.Machine, error) {
state := machinev1alpha1.MachineStateUnknown
savedState := machine.Status.State
fccfg, err := getFirecrackerConfigFromPlatformConfig(machine.Status.PlatformConfig)
if err != nil {
return machine, err
}
// Set the cpu and memory resources
// TODO(craciunouc): This is a temporary solution until we have proper
// un/marshalling of the resources (and all structures).
machine.Spec.Resources.Requests[corev1.ResourceCPU] = resource.MustParse("1")
// Backwards compatibility with older runs
memory := "0Mi"
if fccfg.Memory != "" {
memory = fccfg.Memory
}
machine.Spec.Resources.Requests[corev1.ResourceMemory] = resource.MustParse(memory)
// Check if the process is alive, which ultimately indicates to us whether we
// able to speak to the exposed QMP socket
activeProcess := false
if process, err := goprocess.NewProcess(machine.Status.Pid); err == nil {
activeProcess, err = process.IsRunning()
if err != nil {
state = machinev1alpha1.MachineStateExited
}
}
exitedAt := machine.Status.ExitedAt
exitCode := machine.Status.ExitCode
defer func() {
if exitCode >= 0 && machine.Status.ExitedAt.IsZero() {
exitedAt = time.Now()
}
// Update the machine config with the latest values if they are different from
// what we have on record
if machine.Status.ExitedAt != exitedAt || machine.Status.ExitCode != exitCode {
machine.Status.ExitedAt = exitedAt
machine.Status.ExitCode = exitCode
}
// Set the start time to now if it was not previously set
if machine.Status.StartedAt.IsZero() && state == machinev1alpha1.MachineStateRunning {
machine.Status.StartedAt = time.Now()
}
// Finally, save the state if it is different from the what we have on
// record
if state != savedState {
machine.Status.State = state
}
}()
if !activeProcess {
state = machinev1alpha1.MachineStateExited
if savedState == machinev1alpha1.MachineStateRunning {
exitCode = 1
}
return machine, nil
}
client := firecracker.NewClient(fccfg.SocketPath, logrus.NewEntry(log.G(ctx)), false)
// Grab the actual state of the machine by querying the API socket
ctx, cancel := context.WithTimeout(ctx, service.timeout)
info, err := client.GetInstanceInfo(ctx)
if err != nil {
cancel()
// We cannot amend the status at this point, even if the process is
// alive, since it is not an indicator of the state of the VM, only of the
// VMM. So we return what we already know via LookupMachineConfig.
return machine, fmt.Errorf("could not query machine status via API socket: %v", err)
}
cancel()
// Map the Firecracker state to supported machine states
switch *info.Payload.State {
case models.InstanceInfoStateNotStarted:
state = machinev1alpha1.MachineStateCreated
exitCode = -1
case models.InstanceInfoStateRunning:
state = machinev1alpha1.MachineStateRunning
exitCode = -1
case models.InstanceInfoStatePaused:
state = machinev1alpha1.MachineStatePaused
exitCode = -1
}
machine.Status.PlatformConfig = fccfg
return machine, nil
}
// List implements kraftkit.sh/api/machine/v1alpha1.MachineService.List
func (service *machineV1alpha1Service) List(ctx context.Context, machines *machinev1alpha1.MachineList) (*machinev1alpha1.MachineList, error) {
cached := machines.Items
machines.Items = []zip.Object[machinev1alpha1.MachineSpec, machinev1alpha1.MachineStatus]{}
// Iterate through each machine and grab the latest status
for _, machine := range cached {
machine, err := service.Get(ctx, &machine)
if err != nil {
machines.Items = cached
return machines, err
}
machines.Items = append(machines.Items, *machine)
}
return machines, nil
}
// Stop implements kraftkit.sh/api/machine/v1alpha1.MachineService.Stop
func (service *machineV1alpha1Service) Stop(ctx context.Context, machine *machinev1alpha1.Machine) (*machinev1alpha1.Machine, error) {
if machine.Status.State == machinev1alpha1.MachineStateExited {
return machine, nil
}
process, err := goprocess.NewProcess(machine.Status.Pid)
if err != nil {
return machine, err
}
if err := process.Terminate(); err != nil {
return machine, err
}
machine.Status.State = machinev1alpha1.MachineStateExited
machine.Status.ExitedAt = time.Now()
return machine, nil
}
// Delete implements kraftkit.sh/api/machine/v1alpha1.MachineService.Delete
func (service *machineV1alpha1Service) Delete(ctx context.Context, machine *machinev1alpha1.Machine) (*machinev1alpha1.Machine, error) {
fccfg, err := getFirecrackerConfigFromPlatformConfig(machine.Status.PlatformConfig)
if err != nil {
return machine, err
}
var errs merr.Errors
errs = append(errs, os.Remove(machine.Status.LogFile))
errs = append(errs, os.Remove(fccfg.LogPath))
errs = append(errs, os.RemoveAll(machine.Status.StateDir))
return nil, errs.Err()
}