-
Notifications
You must be signed in to change notification settings - Fork 127
/
machine_test.go
2441 lines (2055 loc) · 66.1 KB
/
machine_test.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 firecracker
import (
"bytes"
"context"
"errors"
"flag"
"fmt"
"io"
"net"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/vishvananda/netns"
"github.com/containerd/fifo"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/ssh"
models "github.com/firecracker-microvm/firecracker-go-sdk/client/models"
ops "github.com/firecracker-microvm/firecracker-go-sdk/client/operations"
"github.com/firecracker-microvm/firecracker-go-sdk/fctesting"
"github.com/firecracker-microvm/firecracker-go-sdk/internal"
)
const (
firecrackerBinaryPath = "firecracker"
firecrackerBinaryOverrideEnv = "FC_TEST_BIN"
defaultJailerBinary = "jailer"
jailerBinaryOverrideEnv = "FC_TEST_JAILER_BIN"
defaultTuntapName = "fc-test-tap0"
tuntapOverrideEnv = "FC_TEST_TAP"
testDataPathEnv = "FC_TEST_DATA_PATH"
sudoUID = "SUDO_UID"
sudoGID = "SUDO_GID"
)
var (
skipTuntap bool
testDataPath = envOrDefault(testDataPathEnv, "./testdata")
testDataLogPath = filepath.Join(testDataPath, "logs")
testDataBin = filepath.Join(testDataPath, "bin")
testRootfs = filepath.Join(testDataPath, "root-drive.img")
testRootfsWithSSH = filepath.Join(testDataPath, "root-drive-with-ssh.img")
testSSHKey = filepath.Join(testDataPath, "root-drive-ssh-key")
testBalloonMemory = int64(10)
testBalloonNewMemory = int64(6)
testBalloonDeflateOnOom = true
testStatsPollingIntervals = int64(1)
testNewStatsPollingIntervals = int64(6)
)
func envOrDefault(k, empty string) string {
value := os.Getenv(k)
if value == "" {
return empty
}
return value
}
// Replace filesystem-unsafe characters (such as /) which are often seen in Go's test names
var fsSafeTestName = strings.NewReplacer("/", "_")
func makeSocketPath(tb testing.TB) (string, func()) {
tb.Helper()
dir, err := os.MkdirTemp("", fsSafeTestName.Replace(tb.Name()))
require.NoError(tb, err)
return filepath.Join(dir, "fc.sock"), func() { os.RemoveAll(dir) }
}
func init() {
flag.BoolVar(&skipTuntap, "test.skip-tuntap", false, "Disables tests that require a tuntap device")
if err := os.MkdirAll(testDataLogPath, 0777); err != nil {
panic(err)
}
}
// Ensure that we can create a new machine
func TestNewMachine(t *testing.T) {
m, err := NewMachine(
context.Background(),
Config{
DisableValidation: true,
MachineCfg: models.MachineConfiguration{
VcpuCount: Int64(1),
MemSizeMib: Int64(100),
Smt: Bool(false),
},
},
WithLogger(fctesting.NewLogEntry(t)))
if err != nil {
t.Fatalf("failed to create new machine: %v", err)
}
m.Handlers.Validation = m.Handlers.Validation.Clear()
if m == nil {
t.Errorf("NewMachine did not create a Machine")
}
}
func TestJailerMicroVMExecution(t *testing.T) {
fctesting.RequiresKVM(t)
fctesting.RequiresRoot(t)
logPath := filepath.Join(testDataLogPath, "TestJailerMicroVMExecution")
err := os.MkdirAll(logPath, 0777)
require.NoError(t, err, "unable to create %s path", logPath)
jailerUID := 123
jailerGID := 100
if v := os.Getenv(sudoUID); v != "" {
if jailerUID, err = strconv.Atoi(v); err != nil {
t.Fatalf("Failed to parse %q", sudoUID)
}
}
if v := os.Getenv(sudoGID); v != "" {
if jailerGID, err = strconv.Atoi(v); err != nil {
t.Fatalf("Failed to parse %q", sudoGID)
}
}
// uses temp directory due to testdata's path being too long which causes a
// SUN_LEN error.
tmpDir, err := os.MkdirTemp(os.TempDir(), "jailer-test")
if err != nil {
t.Fatalf("Failed to create temporary directory: %v", err)
}
vmlinuxPath := filepath.Join(tmpDir, "vmlinux")
if err := copyFile(filepath.Join(testDataPath, "vmlinux"), vmlinuxPath, jailerUID, jailerGID); err != nil {
t.Fatalf("Failed to copy the vmlinux file: %v", err)
}
rootdrivePath := filepath.Join(tmpDir, "root-drive.img")
if err := copyFile(testRootfs, rootdrivePath, jailerUID, jailerGID); err != nil {
t.Fatalf("Failed to copy the root drive file: %v", err)
}
var nCpus int64 = 2
var memSz int64 = 256
// short names and directory to prevent SUN_LEN error
id := "b"
jailerTestPath := tmpDir
os.MkdirAll(jailerTestPath, 0777)
socketPath := "TestJailerMicroVMExecution.socket"
logFifo := filepath.Join(tmpDir, "firecracker.log")
metricsFifo := filepath.Join(tmpDir, "firecracker-metrics")
capturedLog := filepath.Join(tmpDir, "writer.fifo")
fw, err := os.OpenFile(capturedLog, os.O_CREATE|os.O_RDWR, 0600)
require.NoError(t, err, "failed to open fifo writer file")
defer func() {
fw.Close()
exec.Command("cp", capturedLog, logPath).Run()
os.Remove(capturedLog)
os.Remove(filepath.Join(jailerTestPath, "firecracker", socketPath))
os.Remove(logFifo)
os.Remove(metricsFifo)
os.RemoveAll(tmpDir)
}()
logFd, err := os.OpenFile(
filepath.Join(logPath, "TestJailerMicroVMExecution.log"),
os.O_CREATE|os.O_RDWR,
0666)
require.NoError(t, err, "failed to create log file")
defer logFd.Close()
cfg := Config{
SocketPath: socketPath,
LogFifo: logFifo,
MetricsFifo: metricsFifo,
LogLevel: "Debug",
KernelImagePath: vmlinuxPath,
MachineCfg: models.MachineConfiguration{
VcpuCount: Int64(nCpus),
MemSizeMib: Int64(memSz),
Smt: Bool(false),
},
Drives: []models.Drive{
{
DriveID: String("1"),
IsRootDevice: Bool(true),
IsReadOnly: Bool(false),
PathOnHost: String(rootdrivePath),
},
},
JailerCfg: &JailerConfig{
JailerBinary: getJailerBinaryPath(),
GID: Int(jailerGID),
UID: Int(jailerUID),
NumaNode: Int(0),
ID: id,
ChrootBaseDir: jailerTestPath,
ExecFile: getFirecrackerBinaryPath(),
ChrootStrategy: NewNaiveChrootStrategy(vmlinuxPath),
Stdout: logFd,
Stderr: logFd,
CgroupVersion: "2",
},
FifoLogWriter: fw,
}
if _, err := os.Stat(vmlinuxPath); err != nil {
t.Fatalf("Cannot find vmlinux file: %s\n"+
`Verify that you have a vmlinux file at "%s" or set the `+
"`%s` environment variable to the correct location.",
err, vmlinuxPath, testDataPathEnv)
}
kernelImageInfo := syscall.Stat_t{}
if err := syscall.Stat(cfg.KernelImagePath, &kernelImageInfo); err != nil {
t.Fatalf("Failed to stat kernel image: %v", err)
}
if kernelImageInfo.Uid != uint32(jailerUID) || kernelImageInfo.Gid != uint32(jailerGID) {
t.Fatalf("Kernel image does not have the proper UID or GID.\n"+
"To fix this simply run:\n"+
"sudo chown %d:%d %s",
jailerUID, jailerGID, cfg.KernelImagePath)
}
for _, drive := range cfg.Drives {
driveImageInfo := syscall.Stat_t{}
drivePath := StringValue(drive.PathOnHost)
if err := syscall.Stat(drivePath, &driveImageInfo); err != nil {
t.Fatalf("Failed to stat kernel image: %v", err)
}
if driveImageInfo.Uid != uint32(jailerUID) || kernelImageInfo.Gid != uint32(jailerGID) {
t.Fatalf("Drive does not have the proper UID or GID.\n"+
"To fix this simply run:\n"+
"sudo chown %d:%d %s",
jailerUID, jailerGID, drivePath)
}
}
ctx := context.Background()
m, err := NewMachine(ctx, cfg, WithLogger(fctesting.NewLogEntry(t)))
if err != nil {
t.Fatalf("failed to create new machine: %v", err)
}
vmmCtx, vmmCancel := context.WithTimeout(ctx, 30*time.Second)
defer vmmCancel()
if err := m.Start(vmmCtx); err != nil {
t.Errorf("Failed to start VMM: %v", err)
}
m.StopVMM()
info, err := os.Stat(capturedLog)
assert.NoError(t, err, "failed to stat captured log file")
assert.NotEqual(t, 0, info.Size())
}
func TestMicroVMExecution(t *testing.T) {
fctesting.RequiresKVM(t)
var nCpus int64 = 2
var memSz int64 = 256
dir, err := os.MkdirTemp("", t.Name())
require.NoError(t, err)
defer os.RemoveAll(dir)
socketPath := filepath.Join(dir, "TestMicroVMExecution.sock")
logFifo := filepath.Join(dir, "firecracker.log")
metricsFifo := filepath.Join(dir, "firecracker-metrics")
capturedLog := filepath.Join(dir, "writer.fifo")
fw, err := os.OpenFile(capturedLog, os.O_CREATE|os.O_RDWR, 0600)
require.NoError(t, err, "failed to open fifo writer file")
defer fw.Close()
vmlinuxPath := getVmlinuxPath(t)
networkIfaces := []NetworkInterface{{
StaticConfiguration: &StaticNetworkConfiguration{
MacAddress: "01-23-45-67-89-AB-CD-EF",
HostDevName: "tap0",
},
}}
cfg := Config{
SocketPath: socketPath,
LogFifo: logFifo,
MetricsFifo: metricsFifo,
LogLevel: "Debug",
MachineCfg: models.MachineConfiguration{
VcpuCount: Int64(nCpus),
MemSizeMib: Int64(memSz),
Smt: Bool(false),
},
DisableValidation: true,
NetworkInterfaces: networkIfaces,
FifoLogWriter: fw,
}
ctx := context.Background()
cmd := VMCommandBuilder{}.
WithSocketPath(socketPath).
WithBin(getFirecrackerBinaryPath()).
Build(ctx)
m, err := NewMachine(ctx, cfg, WithProcessRunner(cmd), WithLogger(fctesting.NewLogEntry(t)))
if err != nil {
t.Fatalf("failed to create new machine: %v", err)
}
m.Handlers.Validation = m.Handlers.Validation.Clear()
vmmCtx, vmmCancel := context.WithTimeout(ctx, 30*time.Second)
defer vmmCancel()
exitchannel := make(chan error)
go func() {
err := m.startVMM(vmmCtx)
if err != nil {
exitchannel <- err
close(exitchannel)
return
}
defer m.StopVMM()
exitchannel <- m.Wait(vmmCtx)
close(exitchannel)
}()
deadlineCtx, deadlineCancel := context.WithTimeout(vmmCtx, 250*time.Millisecond)
defer deadlineCancel()
if err := waitForAliveVMM(deadlineCtx, m.client); err != nil {
t.Fatal(err)
}
t.Run("TestCreateMachine", func(t *testing.T) { testCreateMachine(ctx, t, m) })
t.Run("TestGetFirecrackerVersion", func(t *testing.T) { testGetFirecrackerVersion(ctx, t, m) })
t.Run("TestMachineConfigApplication", func(t *testing.T) { testMachineConfigApplication(ctx, t, m, cfg) })
t.Run("TestCreateBootSource", func(t *testing.T) { testCreateBootSource(ctx, t, m, vmlinuxPath) })
t.Run("TestCreateNetworkInterface", func(t *testing.T) { testCreateNetworkInterfaceByID(ctx, t, m) })
t.Run("TestAttachRootDrive", func(t *testing.T) { testAttachRootDrive(ctx, t, m) })
t.Run("TestAttachSecondaryDrive", func(t *testing.T) { testAttachSecondaryDrive(ctx, t, m) })
t.Run("TestAttachVsock", func(t *testing.T) { testAttachVsock(ctx, t, m) })
t.Run("SetMetadata", func(t *testing.T) { testSetMetadata(ctx, t, m) })
t.Run("UpdateMetadata", func(t *testing.T) { testUpdateMetadata(ctx, t, m) })
t.Run("GetMetadata", func(t *testing.T) { testGetMetadata(ctx, t, m) }) // Should be after testSetMetadata and testUpdateMetadata
t.Run("TestCreateBalloon", func(t *testing.T) { testCreateBalloon(ctx, t, m) }) // should be before the microVM is started(only pre-boot)
t.Run("TestStartInstance", func(t *testing.T) { testStartInstance(ctx, t, m) })
t.Run("TestGetInstanceInfo", func(t *testing.T) { testGetInstanceInfo(ctx, t, m) })
t.Run("TestGetBalloonConfig", func(t *testing.T) { testGetBalloonConfig(ctx, t, m) }) // should be after testCreateBalloon
t.Run("TestGetBalloonStats", func(t *testing.T) { testGetBalloonStats(ctx, t, m) })
// Let the VMM start and stabilize...
timer := time.NewTimer(5 * time.Second)
select {
case <-timer.C:
t.Run("TestUpdateGuestDrive", func(t *testing.T) { testUpdateGuestDrive(ctx, t, m) })
t.Run("TestUpdateGuestNetworkInterface", func(t *testing.T) { testUpdateGuestNetworkInterface(ctx, t, m) })
t.Run("TestUpdateBalloon", func(t *testing.T) { testUpdateBalloon(ctx, t, m) })
t.Run("TestUpdateBalloonStats", func(t *testing.T) { testUpdateBalloonStats(ctx, t, m) })
t.Run("TestShutdown", func(t *testing.T) { testShutdown(ctx, t, m) })
case <-exitchannel:
// if we've already exited, there's no use waiting for the timer
}
// unconditionally stop the VM here. TestShutdown may have triggered a shutdown, but if it
// didn't for some reason, we still need to terminate it:
m.StopVMM()
m.Wait(vmmCtx)
info, err := os.Stat(capturedLog)
assert.NoError(t, err, "failed to stat captured log file")
assert.NotEqual(t, 0, info.Size())
}
func TestStartVMM(t *testing.T) {
fctesting.RequiresKVM(t)
socketPath, cleanup := makeSocketPath(t)
defer cleanup()
cfg := Config{
SocketPath: socketPath,
}
ctx := context.Background()
cmd := VMCommandBuilder{}.
WithSocketPath(cfg.SocketPath).
WithBin(getFirecrackerBinaryPath()).
Build(ctx)
m, err := NewMachine(ctx, cfg, WithProcessRunner(cmd), WithLogger(fctesting.NewLogEntry(t)))
if err != nil {
t.Fatalf("failed to create new machine: %v", err)
}
m.Handlers.Validation = m.Handlers.Validation.Clear()
timeout, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
defer cancel()
err = m.startVMM(timeout)
if err != nil {
t.Fatalf("startVMM failed: %s", err)
}
defer m.StopVMM()
select {
case <-timeout.Done():
if timeout.Err() == context.DeadlineExceeded {
t.Log("firecracker ran for 250ms")
} else {
t.Errorf("startVMM returned %s", m.Wait(ctx))
}
}
// Make sure exitCh close
_, closed := <-m.exitCh
assert.False(t, closed)
}
func TestLogAndMetrics(t *testing.T) {
if skipLogAndMetricsTest() {
t.Skip()
}
fctesting.RequiresKVM(t)
tests := []struct {
logLevel string
quiet bool
}{
{logLevel: "", quiet: false},
{logLevel: "Info", quiet: false},
{logLevel: "Error", quiet: true},
}
for _, test := range tests {
t.Run(test.logLevel, func(t *testing.T) {
out := testLogAndMetrics(t, test.logLevel)
if test.quiet {
// Non-released versions have version strings like
// "v0.26-wip-145-g6cbffe0d".
assert.Regexp(t, `^Running Firecracker v\d+\.\d+[\.-]`, out)
return
}
// By default, Firecracker's log level is Warn.
logLevel := "WARN"
if test.logLevel != "" {
logLevel = strings.ToUpper(test.logLevel)
}
assert.Contains(t, out, ":"+logLevel+"]")
})
}
}
func skipLogAndMetricsTest() bool {
// Firecracker logging behavior has changed after
// https://github.com/firecracker-microvm/firecracker/pull/4047
// This includes default log level being changed from WARN to INFO
// TODO: Update this test once firecracker version is upgraded to >v1.5.0
version, err := getFirecrackerVersion()
if err != nil {
return true
}
// match version 1.4.x
pattern := `^1\.4\.\d+$`
match, _ := regexp.MatchString(pattern, version)
return !match
}
func testLogAndMetrics(t *testing.T, logLevel string) string {
const vmID = "UserSuppliedVMID"
dir, err := os.MkdirTemp("", strings.Replace(t.Name(), "/", "_", -1))
require.NoError(t, err)
defer os.RemoveAll(dir)
socketPath := filepath.Join(dir, "fc.sock")
cfg := Config{
VMID: vmID,
SocketPath: socketPath,
DisableValidation: true,
KernelImagePath: getVmlinuxPath(t),
MachineCfg: models.MachineConfiguration{
VcpuCount: Int64(1),
MemSizeMib: Int64(64),
Smt: Bool(false),
},
MetricsPath: filepath.Join(dir, "fc-metrics.out"),
LogPath: filepath.Join(dir, "fc.log"),
LogLevel: logLevel,
}
ctx := context.Background()
cmd := configureBuilder(VMCommandBuilder{}.WithBin(getFirecrackerBinaryPath()), cfg).Build(ctx)
m, err := NewMachine(ctx, cfg, WithProcessRunner(cmd), WithLogger(fctesting.NewLogEntry(t)))
require.NoError(t, err)
timeout, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
defer cancel()
err = m.Start(timeout)
require.NoError(t, err)
defer m.StopVMM()
select {
case <-timeout.Done():
if timeout.Err() == context.DeadlineExceeded {
t.Log("firecracker ran for 250ms")
t.Run("TestStopVMM", func(t *testing.T) { testStopVMM(ctx, t, m) })
} else {
t.Errorf("startVMM returned %s", m.Wait(ctx))
}
}
metrics, err := os.Stat(cfg.MetricsPath)
require.NoError(t, err)
assert.NotEqual(t, 0, metrics.Size())
log, err := os.Stat(cfg.LogPath)
require.NoError(t, err)
assert.NotEqual(t, 0, log.Size())
content, err := os.ReadFile(cfg.LogPath)
require.NoError(t, err)
return string(content)
}
func TestStartVMMOnce(t *testing.T) {
fctesting.RequiresKVM(t)
socketPath, cleanup := makeSocketPath(t)
defer cleanup()
cfg := Config{
SocketPath: socketPath,
DisableValidation: true,
KernelImagePath: getVmlinuxPath(t),
MachineCfg: models.MachineConfiguration{
VcpuCount: Int64(1),
MemSizeMib: Int64(64),
Smt: Bool(false),
},
}
if cpu_temp, err := internal.SupportCPUTemplate(); cpu_temp && err == nil {
cfg.MachineCfg.CPUTemplate = models.CPUTemplate(models.CPUTemplateT2)
}
ctx := context.Background()
cmd := VMCommandBuilder{}.
WithSocketPath(cfg.SocketPath).
WithBin(getFirecrackerBinaryPath()).
Build(ctx)
m, err := NewMachine(ctx, cfg, WithProcessRunner(cmd), WithLogger(fctesting.NewLogEntry(t)))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
timeout, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
defer cancel()
err = m.Start(timeout)
if err != nil {
t.Fatalf("startVMM failed: %s", err)
}
defer m.StopVMM()
err = m.Start(timeout)
assert.Error(t, err, "should return an error when Start is called multiple times")
assert.Equal(t, ErrAlreadyStarted, err, "should be ErrAlreadyStarted")
select {
case <-timeout.Done():
if timeout.Err() == context.DeadlineExceeded {
t.Log("firecracker ran for 250ms")
t.Run("TestStopVMM", func(t *testing.T) { testStopVMM(ctx, t, m) })
} else {
t.Errorf("startVMM returned %s", m.Wait(ctx))
}
}
}
func getFirecrackerBinaryPath() string {
if val := os.Getenv(firecrackerBinaryOverrideEnv); val != "" {
return val
}
return filepath.Join(testDataPath, firecrackerBinaryPath)
}
func getJailerBinaryPath() string {
if val := os.Getenv(jailerBinaryOverrideEnv); val != "" {
return val
}
return filepath.Join(testDataPath, defaultJailerBinary)
}
func getVmlinuxPath(t *testing.T) string {
t.Helper()
vmlinuxPath := filepath.Join(testDataPath, "./vmlinux")
if _, err := os.Stat(vmlinuxPath); err != nil {
t.Fatalf("Cannot find vmlinux file: %s\n"+
`Verify that you have a vmlinux file at "%s" or set the `+
"`%s` environment variable to the correct location.",
err, vmlinuxPath, testDataPathEnv)
}
return vmlinuxPath
}
func testCreateMachine(ctx context.Context, t *testing.T, m *Machine) {
err := m.createMachine(ctx)
if err != nil {
t.Errorf("createMachine said %s", err)
} else {
t.Log("firecracker created a machine")
}
}
func parseVersionFromStdout(stdout []byte) (string, error) {
pattern := regexp.MustCompile(`Firecracker v(?P<version>[0-9]+\.[0-9]+\.[0-9]+-?.*)`)
groupNames := pattern.SubexpNames()
matches := pattern.FindStringSubmatch(string(stdout))
for i, name := range groupNames {
if name == "version" {
return matches[i], nil
}
}
return "", fmt.Errorf("Unable to parse firecracker version from stdout (Output: %s)",
stdout)
}
func getFirecrackerVersion() (string, error) {
cmd := exec.Command(getFirecrackerBinaryPath(), "--version")
stdout, err := cmd.Output()
if err != nil {
return "", err
}
return parseVersionFromStdout(stdout)
}
func testGetFirecrackerVersion(ctx context.Context, t *testing.T, m *Machine) {
version, err := m.GetFirecrackerVersion(ctx)
if err != nil {
t.Errorf("GetFirecrackerVersion: %v", err)
}
expectedVersion, err := getFirecrackerVersion()
if err != nil {
t.Errorf("GetFirecrackerVersion: %v", err)
}
assert.Equalf(t, expectedVersion, version,
"GetFirecrackerVersion: Expected version %v, got version %v",
expectedVersion, version)
}
func testMachineConfigApplication(ctx context.Context, t *testing.T, m *Machine, expectedValues Config) {
assert.Equal(t, expectedValues.MachineCfg.VcpuCount,
m.machineConfig.VcpuCount, "CPU count should be equal")
assert.Equal(t, expectedValues.MachineCfg.MemSizeMib, m.machineConfig.MemSizeMib, "memory...")
}
func testCreateBootSource(ctx context.Context, t *testing.T, m *Machine, vmlinuxPath string) {
// panic=0: This option disables reboot-on-panic behavior for the kernel. We
// use this option as we might run the tests without a real root
// filesystem available to the guest.
// Kernel command-line options can be found in the kernel source tree at
// Documentation/admin-guide/kernel-parameters.txt.
err := m.createBootSource(ctx, vmlinuxPath, "", "ro console=ttyS0 noapic reboot=k panic=0 pci=off nomodules")
if err != nil {
t.Errorf("failed to create boot source: %s", err)
}
}
func testUpdateGuestDrive(ctx context.Context, t *testing.T, m *Machine) {
path := filepath.Join(testDataPath, "drive-3.img")
if err := m.UpdateGuestDrive(ctx, "2", path); err != nil {
t.Errorf("unexpected error on swapping guest drive: %v", err)
}
}
func testUpdateGuestNetworkInterface(ctx context.Context, t *testing.T, m *Machine) {
rateLimitSet := RateLimiterSet{
InRateLimiter: NewRateLimiter(
TokenBucketBuilder{}.WithBucketSize(10).WithRefillDuration(10).Build(),
TokenBucketBuilder{}.WithBucketSize(10).WithRefillDuration(10).Build(),
),
}
if err := m.UpdateGuestNetworkInterfaceRateLimit(ctx, "1", rateLimitSet); err != nil {
t.Fatalf("Failed to update the network interface %v", err)
}
}
func testCreateNetworkInterfaceByID(ctx context.Context, t *testing.T, m *Machine) {
if skipTuntap {
t.Skip("Skipping: tuntap tests explicitly disabled")
}
hostDevName := getTapName()
iface := NetworkInterface{
StaticConfiguration: &StaticNetworkConfiguration{
MacAddress: "02:00:00:01:02:03",
HostDevName: hostDevName,
},
}
err := m.createNetworkInterface(ctx, iface, 1)
if err != nil {
t.Errorf(`createNetworkInterface: %s
Do you have a tuntap device named %s?
Create one with `+"`sudo ip tuntap add %s mode tap user $UID`", err, hostDevName, hostDevName)
}
}
func getTapName() string {
if val := os.Getenv(tuntapOverrideEnv); val != "" {
return val
}
return defaultTuntapName
}
func testAttachRootDrive(ctx context.Context, t *testing.T, m *Machine) {
drive := models.Drive{
DriveID: String("0"),
IsRootDevice: Bool(true),
IsReadOnly: Bool(true),
PathOnHost: String(testRootfs),
}
err := m.attachDrives(ctx, drive)
if err != nil {
t.Errorf("attaching root drive failed: %s", err)
}
}
func testAttachSecondaryDrive(ctx context.Context, t *testing.T, m *Machine) {
drive := models.Drive{
DriveID: String("2"),
IsRootDevice: Bool(false),
IsReadOnly: Bool(true),
PathOnHost: String(filepath.Join(testDataPath, "drive-2.img")),
}
err := m.attachDrive(ctx, drive)
if err != nil {
t.Errorf("attaching secondary drive failed: %s", err)
}
}
func testAttachVsock(ctx context.Context, t *testing.T, m *Machine) {
timestamp := strconv.Itoa(int(time.Now().UnixNano()))
dev := VsockDevice{
ID: "1",
CID: 3,
Path: timestamp + ".vsock",
}
err := m.addVsock(ctx, dev)
if err != nil {
if badRequest, ok := err.(*ops.PutGuestVsockBadRequest); ok &&
strings.HasPrefix(badRequest.Payload.FaultMessage, "Invalid request method and/or path") {
t.Errorf(`attaching vsock failed: %s
Does your Firecracker binary have vsock support?
Build one with vsock support by running `+"`cargo build --release --features vsock` from within the Firecracker repository.",
badRequest.Payload.FaultMessage)
} else {
t.Errorf("attaching vsock failed: %s", err)
}
}
}
func testStartInstance(ctx context.Context, t *testing.T, m *Machine) {
err := m.startInstance(ctx)
if err != nil {
if syncErr, ok := err.(*ops.CreateSyncActionDefault); ok &&
strings.HasPrefix(syncErr.Payload.FaultMessage, "Cannot create vsock device") {
t.Errorf(`startInstance: %s
Do you have permission to interact with /dev/vhost-vsock?
Grant yourself permission with `+"`sudo setfacl -m u:${USER}:rw /dev/vhost-vsock`", syncErr.Payload.FaultMessage)
} else {
t.Errorf("startInstance failed: %s", err)
}
}
}
func testStopVMM(ctx context.Context, t *testing.T, m *Machine) {
err := m.StopVMM()
if err != nil {
t.Errorf("StopVMM failed: %s", err)
}
}
func TestStopVMMCleanup(t *testing.T) {
fctesting.RequiresKVM(t)
fctesting.RequiresRoot(t)
socketPath, cleanup := makeSocketPath(t)
defer cleanup()
dir, err := os.MkdirTemp("", t.Name())
require.NoError(t, err)
defer os.RemoveAll(dir)
cniConfDir := filepath.Join(dir, "cni.conf")
err = os.MkdirAll(cniConfDir, 0777)
require.NoError(t, err)
cniBinPath := []string{testDataBin}
const networkName = "fcnet"
const ifName = "veth0"
networkMask := "/24"
subnet := "10.168.0.0" + networkMask
cniConfPath := fmt.Sprintf("%s/%s.conflist", cniConfDir, networkName)
err = writeCNIConfWithHostLocalSubnet(cniConfPath, networkName, subnet)
require.NoError(t, err)
defer os.Remove(cniConfPath)
networkInterface := NetworkInterface{
CNIConfiguration: &CNIConfiguration{
NetworkName: networkName,
IfName: ifName,
ConfDir: cniConfDir,
BinPath: cniBinPath,
VMIfName: "eth0",
},
}
cfg := Config{
SocketPath: socketPath,
DisableValidation: true,
KernelImagePath: getVmlinuxPath(t),
NetworkInterfaces: []NetworkInterface{networkInterface},
MachineCfg: models.MachineConfiguration{
VcpuCount: Int64(1),
MemSizeMib: Int64(64),
Smt: Bool(false),
},
}
ctx := context.Background()
cmd := VMCommandBuilder{}.
WithSocketPath(cfg.SocketPath).
WithBin(getFirecrackerBinaryPath()).
Build(ctx)
m, err := NewMachine(ctx, cfg, WithProcessRunner(cmd), WithLogger(fctesting.NewLogEntry(t)))
require.NoError(t, err)
err = m.Start(ctx)
require.NoError(t, err)
err = m.stopVMM()
require.NoError(t, err)
_, err = netns.GetFromName(m.Cfg.VMID)
require.Error(t, err)
}
func testShutdown(ctx context.Context, t *testing.T, m *Machine) {
err := m.Shutdown(ctx)
if err != nil {
t.Errorf("machine.Shutdown() failed: %s", err)
}
}
func TestWaitForSocket(t *testing.T) {
okClient := fctesting.MockClient{}
errClient := fctesting.MockClient{
GetMachineConfigurationFn: func(params *ops.GetMachineConfigurationParams) (*ops.GetMachineConfigurationOK, error) {
return nil, errors.New("http error")
},
}
// testWaitForSocket has three conditions that need testing:
// 1. The expected file is created within the deadline and
// socket HTTP request succeeded
// 2. The expected file is not created within the deadline
// 3. The process responsible for creating the file exits
// (indicated by an error published to exitchan)
filename, cleanup := makeSocketPath(t)
defer cleanup()
errchan := make(chan error)
m := Machine{
Cfg: Config{SocketPath: filename},
logger: fctesting.NewLogEntry(t),
}
go func() {
time.Sleep(50 * time.Millisecond)
_, err := os.Create(filename)
if err != nil {
t.Errorf("Unable to create test file %s: %s", filename, err)
return
}
}()
// Socket file created, HTTP request succeeded
m.client = NewClient(filename, fctesting.NewLogEntry(t), true, WithOpsClient(&okClient))
if err := m.waitForSocket(500*time.Millisecond, errchan); err != nil {
t.Errorf("waitForSocket returned unexpected error %s", err)
}
// Socket file exists, HTTP request failed
m.client = NewClient(filename, fctesting.NewLogEntry(t), true, WithOpsClient(&errClient))
if err := m.waitForSocket(500*time.Millisecond, errchan); err != context.DeadlineExceeded {
t.Error("waitforSocket did not return an expected timeout error")
}
cleanup()
// No socket file
if err := m.waitForSocket(100*time.Millisecond, errchan); err != context.DeadlineExceeded {
t.Error("waitforSocket did not return an expected timeout error")
}
chanErr := errors.New("this is an expected error")
go func() {
time.Sleep(50 * time.Millisecond)
errchan <- chanErr
}()
// Unexpected process exit
if err := m.waitForSocket(100*time.Millisecond, errchan); err != chanErr {
t.Error("waitForSocket did not properly detect program exit")
}
}
func TestMicroVMExecutionWithMmdsV2(t *testing.T) {
fctesting.RequiresKVM(t)
var nCpus int64 = 2
var memSz int64 = 256
dir, err := os.MkdirTemp("", t.Name())
require.NoError(t, err)
defer os.RemoveAll(dir)
socketPath := filepath.Join(dir, "TestMicroVMExecution.sock")
logFifo := filepath.Join(dir, "firecracker.log")
metricsFifo := filepath.Join(dir, "firecracker-metrics")
capturedLog := filepath.Join(dir, "writer.fifo")
fw, err := os.OpenFile(capturedLog, os.O_CREATE|os.O_RDWR, 0600)
require.NoError(t, err, "failed to open fifo writer file")
defer fw.Close()
vmlinuxPath := getVmlinuxPath(t)
networkIfaces := []NetworkInterface{{
StaticConfiguration: &StaticNetworkConfiguration{
MacAddress: "01-23-45-67-89-AB-CD-EF",
HostDevName: "tap0",
},
}}
cfg := Config{
SocketPath: socketPath,
LogFifo: logFifo,
MetricsFifo: metricsFifo,
LogLevel: "Debug",
MachineCfg: models.MachineConfiguration{
VcpuCount: Int64(nCpus),
MemSizeMib: Int64(memSz),
Smt: Bool(false),
},
DisableValidation: true,
NetworkInterfaces: networkIfaces,
FifoLogWriter: fw,
MmdsVersion: MMDSv2,
}
ctx := context.Background()
cmd := VMCommandBuilder{}.
WithSocketPath(socketPath).
WithBin(getFirecrackerBinaryPath()).
Build(ctx)