forked from firecracker-microvm/firecracker-containerd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice_integ_test.go
2530 lines (2118 loc) · 82.2 KB
/
service_integ_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 main
import (
"bufio"
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/containerd/containerd"
"github.com/containerd/containerd/api/events"
"github.com/containerd/containerd/cio"
"github.com/containerd/containerd/containers"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/oci"
"github.com/containerd/containerd/runtime"
"github.com/containerd/go-runc"
"github.com/containerd/typeurl"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/shirou/gopsutil/process"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
"github.com/firecracker-microvm/firecracker-containerd/config"
_ "github.com/firecracker-microvm/firecracker-containerd/firecracker-control"
"github.com/firecracker-microvm/firecracker-containerd/internal"
"github.com/firecracker-microvm/firecracker-containerd/internal/vm"
"github.com/firecracker-microvm/firecracker-containerd/proto"
fccontrol "github.com/firecracker-microvm/firecracker-containerd/proto/service/fccontrol/ttrpc"
"github.com/firecracker-microvm/firecracker-containerd/runtime/firecrackeroci"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
defaultNamespace = namespaces.Default
firecrackerRuntime = "aws.firecracker"
shimProcessName = "containerd-shim-aws-firecracker"
firecrackerProcessName = "firecracker"
defaultVMNetDevName = "eth0"
numberOfVmsEnvName = "NUMBER_OF_VMS"
defaultNumberOfVms = 5
tapPrefixEnvName = "TAP_PREFIX"
defaultBalloonMemory = int64(66)
defaultStatsPollingIntervals = int64(1)
containerdSockPathEnvVar = "CONTAINERD_SOCKET"
)
var (
findShim = findProcWithName(shimProcessName)
findFirecracker = findProcWithName(firecrackerProcessName)
containerdSockPath = "/run/firecracker-containerd/containerd.sock"
)
func init() {
if v := os.Getenv(containerdSockPathEnvVar); v != "" {
containerdSockPath = v
}
}
// Images are presumed by the isolated tests to have already been pulled
// into the content store. This will just unpack the layers into an
// image with the provided snapshotter.
func unpackImage(ctx context.Context, client *containerd.Client, snapshotterName string, imageRef string) (containerd.Image, error) {
img, err := client.GetImage(ctx, imageRef)
if err != nil {
return nil, errors.Wrap(err, "failed to get image")
}
err = img.Unpack(ctx, snapshotterName)
if err != nil {
return nil, errors.Wrap(err, "failed to unpack image")
}
return img, nil
}
func alpineImage(ctx context.Context, client *containerd.Client, snapshotterName string) (containerd.Image, error) {
return unpackImage(ctx, client, snapshotterName, "docker.io/library/alpine:3.10.1")
}
func iperf3Image(ctx context.Context, client *containerd.Client, snapshotterName string) (containerd.Image, error) {
return unpackImage(ctx, client, snapshotterName, "docker.io/mlabbe/iperf3:3.6-r0")
}
func TestShimExitsUponContainerDelete_Isolated(t *testing.T) {
prepareIntegTest(t)
ctx := namespaces.WithNamespace(context.Background(), defaultNamespace)
client, err := containerd.New(containerdSockPath)
require.NoError(t, err, "unable to create client to containerd service at %s, is containerd running?", containerdSockPath)
defer client.Close()
image, err := alpineImage(ctx, client, defaultSnapshotterName)
require.NoError(t, err, "failed to get alpine image")
testTimeout := 60 * time.Second
testCtx, testCancel := context.WithTimeout(ctx, testTimeout)
defer testCancel()
containerName := fmt.Sprintf("%s-%d", t.Name(), time.Now().UnixNano())
snapshotName := fmt.Sprintf("%s-snapshot", containerName)
container, err := client.NewContainer(testCtx,
containerName,
containerd.WithRuntime(firecrackerRuntime, nil),
containerd.WithSnapshotter(defaultSnapshotterName),
containerd.WithNewSnapshot(snapshotName, image),
containerd.WithNewSpec(
oci.WithProcessArgs("sleep", fmt.Sprintf("%d", testTimeout/time.Second)),
oci.WithDefaultPathEnv,
),
)
require.NoError(t, err, "failed to create container %s", containerName)
_, err = client.NewContainer(testCtx,
fmt.Sprintf("should-fail-%s-%d", t.Name(), time.Now().UnixNano()),
containerd.WithRuntime(firecrackerRuntime, nil),
containerd.WithSnapshotter(defaultSnapshotterName),
containerd.WithNewSnapshot(snapshotName, image),
containerd.WithNewSpec(
oci.WithProcessArgs("sleep", fmt.Sprintf("%d", testTimeout/time.Second)),
oci.WithDefaultPathEnv,
),
)
require.Error(t, err, "should not be able to create additional container when no drives are available")
task, err := container.NewTask(testCtx, cio.NewCreator(cio.WithStdio))
require.NoError(t, err, "failed to create task for container %s", containerName)
exitEventCh, exitEventErrCh := client.Subscribe(testCtx, fmt.Sprintf(`topic=="%s"`, runtime.TaskExitEventTopic))
err = task.Start(testCtx)
require.NoError(t, err, "failed to start task for container %s", containerName)
shimProcesses, err := internal.WaitForProcessToExist(testCtx, time.Second, findShim)
require.NoError(t, err, "failed waiting for expected shim process %q to come up", shimProcessName)
require.Len(t, shimProcesses, 1, "expected only one shim process to exist")
shimProcess := shimProcesses[0]
err = task.Kill(testCtx, syscall.SIGKILL)
require.NoError(t, err, "failed to SIGKILL containerd task %s", containerName)
_, err = task.Delete(testCtx)
require.NoError(t, err, "failed to Delete containerd task %s", containerName)
select {
case envelope := <-exitEventCh:
unmarshaledEvent, err := typeurl.UnmarshalAny(envelope.Event)
require.NoError(t, err, "failed to unmarshal event")
switch event := unmarshaledEvent.(type) {
case *events.TaskExit:
require.Equal(t, container.ID(), event.ContainerID, "received exit event from expected container %s", container.ID())
default:
require.Fail(t, "unexpected event type", "received unexpected non-exit event type on topic: %s", envelope.Topic)
}
err = internal.WaitForPidToExit(testCtx, time.Second, shimProcess.Pid)
require.NoError(t, err, "failed waiting for shim process \"%s\" to exit", shimProcessName)
cfg, err := config.LoadConfig("")
require.NoError(t, err, "failed to load config")
varRunFCContents, err := ioutil.ReadDir(cfg.ShimBaseDir)
require.NoError(t, err, `failed to list directory "%s"`, cfg.ShimBaseDir)
require.Len(t, varRunFCContents, 0, "expect %s to be empty", cfg.ShimBaseDir)
case err = <-exitEventErrCh:
require.Fail(t, "unexpected error", "unexpectedly received on task exit error channel: %s", err.Error())
case <-testCtx.Done():
require.Fail(t, "context canceled", "context canceled while waiting for container \"%s\" exit: %s", containerName, testCtx.Err())
}
}
// vmIDtoMacAddr converts a provided VMID to a unique Mac Address. This is a convenient way of providing the VMID to clients within
// the VM without the extra complication of alternative approaches like MMDS.
func vmIDtoMacAddr(vmID uint) string {
var addrParts []string
// mac addresses have 6 hex components separate by ":", i.e. "11:22:33:44:55:66"
numMacAddrComponents := uint(6)
for n := uint(0); n < numMacAddrComponents; n++ {
// To isolate the value of the nth component, right bit shift the vmID by 8*n (there are 8 bits per component) and
// mask out any upper bits leftover (bitwise AND with 255)
addrComponent := (vmID >> (8 * n)) & 255
// format the component as a two-digit hex string
addrParts = append(addrParts, fmt.Sprintf("%02x", addrComponent))
}
return strings.Join(addrParts, ":")
}
func ipCommand(ctx context.Context, args ...string) error {
out, err := exec.CommandContext(ctx, "ip", args...).CombinedOutput()
if err != nil {
s := strings.Trim(string(out), "\n")
return fmt.Errorf("failed to execute ip %s: %s: %w", strings.Join(args, " "), s, err)
}
return nil
}
func deleteTapDevice(ctx context.Context, tapName string) error {
if err := ipCommand(ctx, "link", "delete", tapName); err != nil {
return err
}
return ipCommand(ctx, "tuntap", "del", tapName, "mode", "tap")
}
func createTapDevice(ctx context.Context, tapName string) error {
if err := ipCommand(ctx, "tuntap", "add", tapName, "mode", "tap"); err != nil {
return err
}
return ipCommand(ctx, "link", "set", tapName, "up")
}
func TestMultipleVMs_Isolated(t *testing.T) {
prepareIntegTest(t)
// This test starts multiple VMs and some may hit firecracker-containerd's
// default timeout. So overriding the timeout to wait longer.
// One hour should be enough to start a VM, regardless of the load of
// the underlying host.
const createVMTimeout = time.Hour
netns, err := ns.GetCurrentNS()
require.NoError(t, err, "failed to get a namespace")
// numberOfVmsEnvName = NUMBER_OF_VMS ENV and is configurable from buildkite
numberOfVms := defaultNumberOfVms
if str := os.Getenv(numberOfVmsEnvName); str != "" {
numberOfVms, err = strconv.Atoi(str)
require.NoError(t, err, "failed to get NUMBER_OF_VMS env")
}
t.Logf("TestMultipleVMs_Isolated: will run %d vm's", numberOfVms)
tapPrefix := os.Getenv(tapPrefixEnvName)
cases := []struct {
MaxContainers int32
JailerConfig *proto.JailerConfig
}{
{
MaxContainers: 5,
},
{
MaxContainers: 3,
JailerConfig: &proto.JailerConfig{
UID: 300000,
GID: 300000,
NetNS: netns.Path(),
},
},
{
MaxContainers: 3,
JailerConfig: &proto.JailerConfig{
UID: 300000,
GID: 300000,
NetNS: netns.Path(),
CgroupPath: "/mycgroup",
},
},
}
testCtx := namespaces.WithNamespace(context.Background(), defaultNamespace)
client, err := containerd.New(containerdSockPath, containerd.WithDefaultRuntime(firecrackerRuntime))
require.NoError(t, err, "unable to create client to containerd service at %s, is containerd running?", containerdSockPath)
defer client.Close()
image, err := alpineImage(testCtx, client, defaultSnapshotterName)
require.NoError(t, err, "failed to get alpine image")
cfg, err := config.LoadConfig("")
require.NoError(t, err, "failed to load config")
// This test spawns separate VMs in parallel and ensures containers are spawned within each expected VM. It asserts each
// container ends up in the right VM by assigning each VM a network device with a unique mac address and having each container
// print the mac address it sees inside its VM.
vmEg, vmEgCtx := errgroup.WithContext(testCtx)
for i := 0; i < numberOfVms; i++ {
caseTypeNumber := i % len(cases)
vmID := i
c := cases[caseTypeNumber]
f := func(ctx context.Context) error {
containerCount := c.MaxContainers
jailerConfig := c.JailerConfig
tapName := fmt.Sprintf("%stap%d", tapPrefix, vmID)
err := createTapDevice(ctx, tapName)
if err != nil {
return err
}
defer deleteTapDevice(ctx, tapName)
rootfsPath := cfg.RootDrive
vmIDStr := strconv.Itoa(vmID)
req := &proto.CreateVMRequest{
VMID: vmIDStr,
RootDrive: &proto.FirecrackerRootDrive{
HostPath: rootfsPath,
},
NetworkInterfaces: []*proto.FirecrackerNetworkInterface{
{
AllowMMDS: true,
StaticConfig: &proto.StaticNetworkConfiguration{
HostDevName: tapName,
MacAddress: vmIDtoMacAddr(uint(vmID)),
},
},
},
ContainerCount: containerCount,
JailerConfig: jailerConfig,
TimeoutSeconds: uint32(createVMTimeout / time.Second),
// In tests, our in-VM agent has Go's race detector,
// which makes the agent resource-hoggy than its production build
// So the default VM size (128MB) is too small.
MachineCfg: &proto.FirecrackerMachineConfiguration{MemSizeMib: 1024},
}
fcClient, err := newFCControlClient(containerdSockPath)
if err != nil {
return err
}
resp, createVMErr := fcClient.CreateVM(ctx, req)
if createVMErr != nil {
matches, err := findProcess(ctx, findFirecracker)
if err != nil {
return fmt.Errorf(
"failed to create a VM and couldn't find Firecracker due to %s: %w",
createVMErr, err,
)
}
return fmt.Errorf(
"failed to create a VM while there are %d Firecracker processes: %w",
len(matches),
createVMErr,
)
}
containerEg, containerCtx := errgroup.WithContext(vmEgCtx)
for containerID := 0; containerID < int(containerCount); containerID++ {
containerID := containerID
containerEg.Go(func() error {
return testMultipleExecs(
containerCtx,
vmID,
containerID,
client, image,
jailerConfig,
resp.CgroupPath,
)
})
}
// verify duplicate CreateVM call fails with right error
_, err = fcClient.CreateVM(ctx, &proto.CreateVMRequest{VMID: strconv.Itoa(vmID)})
if err == nil {
return fmt.Errorf("creating the same VM must return an error")
}
// verify GetVMInfo returns expected data
vmInfoResp, err := fcClient.GetVMInfo(ctx, &proto.GetVMInfoRequest{VMID: strconv.Itoa(vmID)})
if err != nil {
return err
}
if vmInfoResp.VMID != strconv.Itoa(vmID) {
return fmt.Errorf("%q must be %q", vmInfoResp.VMID, strconv.Itoa(vmID))
}
nspVMid := defaultNamespace + "#" + strconv.Itoa(vmID)
cfg, err := config.LoadConfig("")
if err != nil {
return err
}
if vmInfoResp.SocketPath != filepath.Join(cfg.ShimBaseDir, nspVMid, "firecracker.sock") ||
vmInfoResp.VSockPath != filepath.Join(cfg.ShimBaseDir, nspVMid, "firecracker.vsock") ||
vmInfoResp.LogFifoPath != filepath.Join(cfg.ShimBaseDir, nspVMid, "fc-logs.fifo") ||
vmInfoResp.MetricsFifoPath != filepath.Join(cfg.ShimBaseDir, nspVMid, "fc-metrics.fifo") ||
resp.CgroupPath != vmInfoResp.CgroupPath {
return fmt.Errorf("unexpected result from GetVMInfo: %+v", vmInfoResp)
}
// just verify that updating the metadata doesn't return an error, a separate test case is needed
// to very the MMDS update propagates to the container correctly
_, err = fcClient.SetVMMetadata(ctx, &proto.SetVMMetadataRequest{
VMID: strconv.Itoa(vmID),
Metadata: "{}",
})
if err != nil {
return err
}
err = containerEg.Wait()
if err != nil {
return fmt.Errorf("unexpected error from the containers in VM %d: %w", vmID, err)
}
_, err = fcClient.StopVM(ctx, &proto.StopVMRequest{VMID: strconv.Itoa(vmID), TimeoutSeconds: 5})
if err != nil {
return err
}
return nil
}
vmEg.Go(func() error {
err := f(vmEgCtx)
if err != nil {
return fmt.Errorf("unexpected errors from VM %d: %w", vmID, err)
}
return nil
})
}
err = vmEg.Wait()
require.NoError(t, err)
}
func testMultipleExecs(
ctx context.Context,
vmID int,
containerID int,
client *containerd.Client,
image containerd.Image,
jailerConfig *proto.JailerConfig,
cgroupPath string,
) error {
vmIDStr := strconv.Itoa(vmID)
testTimeout := 600 * time.Second
containerName := fmt.Sprintf("container-%d-%d", vmID, containerID)
snapshotName := fmt.Sprintf("snapshot-%d-%d", vmID, containerID)
processArgs := oci.WithProcessArgs("/bin/sh", "-c", strings.Join([]string{
fmt.Sprintf("/bin/cat /sys/class/net/%s/address", defaultVMNetDevName),
"/usr/bin/readlink /proc/self/ns/mnt",
fmt.Sprintf("/bin/sleep %d", testTimeout/time.Second),
}, " && "))
// spawn a container that just prints the VM's eth0 mac address (which we have set uniquely per VM)
newContainer, err := client.NewContainer(ctx,
containerName,
containerd.WithSnapshotter(defaultSnapshotterName),
containerd.WithNewSnapshot(snapshotName, image),
containerd.WithNewSpec(
processArgs,
oci.WithHostNamespace(specs.NetworkNamespace),
firecrackeroci.WithVMID(vmIDStr),
),
)
if err != nil {
return err
}
defer newContainer.Delete(ctx)
var taskStdout bytes.Buffer
var taskStderr bytes.Buffer
newTask, err := newContainer.NewTask(ctx,
cio.NewCreator(cio.WithStreams(nil, &taskStdout, &taskStderr)))
if err != nil {
return err
}
taskExitCh, err := newTask.Wait(ctx)
if err != nil {
return err
}
err = newTask.Start(ctx)
if err != nil {
return err
}
// Create a few execs for the task, including one with the same ID as the taskID (to provide
// regression coverage for a bug related to using the same task and exec ID).
//
// Save each of their stdout buffers, which will later be compared to ensure they each have
// the same output.
//
// The output of the exec is the mount namespace in which it found itself executing. This
// will be compared with the mount namespace the task is executing to ensure they are the same.
// This is a rudimentary way of asserting that each exec was created in the expected task.
execIDs := []string{fmt.Sprintf("exec-%d-%d", vmID, containerID), containerName}
execStdouts := make(chan string, len(execIDs))
var eg, _ = errgroup.WithContext(ctx)
for _, execID := range execIDs {
execID := execID
eg.Go(func() error {
ns, err := getMountNamespace(ctx, client, containerName, newTask, execID)
if err != nil {
return err
}
execStdouts <- ns
return nil
})
}
err = eg.Wait()
if err != nil {
return fmt.Errorf("unexpected error from the execs in container %d: %w", containerID, err)
}
close(execStdouts)
if jailerConfig != nil {
dir, err := vm.ShimDir(shimBaseDir(), "default", vmIDStr)
if err != nil {
return err
}
jailer := &runcJailer{
Config: runcJailerConfig{
OCIBundlePath: dir.RootPath(),
},
vmID: vmIDStr,
}
_, err = os.Stat(jailer.RootPath())
if err != nil {
return err
}
_, err = os.Stat(filepath.Join("/sys/fs/cgroup/cpu", cgroupPath))
if err != nil {
return err
}
ok, err := regexp.Match(".+/"+vmIDStr, []byte(cgroupPath))
if err != nil {
return err
}
if !ok {
return fmt.Errorf("%q doesn't match %q", cgroupPath, vmIDStr)
}
}
// Verify each exec had the same stdout and use that value as the mount namespace that will be compared
// against that of the task below.
var execMntNS string
for execStdout := range execStdouts {
if execMntNS == "" {
// This is the first iteration of loop; we do a check that execStdout is not "" via require.NotEmptyf
// in the execID loop above.
execMntNS = execStdout
}
if execStdout != execMntNS {
return fmt.Errorf("%q must be %q", execStdout, execMntNS)
}
}
// Now kill the task and verify it was in the right VM and has the same mnt namespace as its execs
err = newTask.Kill(ctx, syscall.SIGKILL)
if err != nil {
return err
}
select {
case <-taskExitCh:
_, err = newTask.Delete(ctx)
if err != nil {
return err
}
// if there was anything on stderr, print it to assist debugging
stderrOutput := taskStderr.String()
if len(stderrOutput) != 0 {
fmt.Printf("stderr output from task %q: %q", containerName, stderrOutput)
}
stdout := taskStdout.String()
expected := fmt.Sprintf("%s\n%s\n", vmIDtoMacAddr(uint(vmID)), execMntNS)
if stdout != expected {
return fmt.Errorf("%q must be %q", stdout, expected)
}
case <-ctx.Done():
return ctx.Err()
}
return nil
}
func getMountNamespace(ctx context.Context, client *containerd.Client, containerName string, newTask containerd.Task, execID string) (string, error) {
var execStdout bytes.Buffer
var execStderr bytes.Buffer
newExec, err := newTask.Exec(ctx, execID, &specs.Process{
Args: []string{"/usr/bin/readlink", "/proc/self/ns/mnt"},
Cwd: "/",
}, cio.NewCreator(cio.WithStreams(nil, &execStdout, &execStderr)))
if err != nil {
return "", err
}
execExitCh, err := newExec.Wait(ctx)
if err != nil {
return "", err
}
err = newExec.Start(ctx)
if err != nil {
return "", err
}
select {
case exitStatus := <-execExitCh:
_, err = newExec.Delete(ctx)
if err != nil {
return "", err
}
// if there was anything on stderr, print it to assist debugging
stderrOutput := execStderr.String()
if len(stderrOutput) != 0 {
fmt.Printf("stderr output from exec %q: %q", execID, stderrOutput)
}
mntNS := strings.TrimSpace(execStdout.String())
code := exitStatus.ExitCode()
if code != 0 {
return "", fmt.Errorf("exit code %d != 0, stdout=%q stderr=%q", code, execStdout.String(), stderrOutput)
}
return mntNS, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func TestLongUnixSocketPath_Isolated(t *testing.T) {
prepareIntegTest(t)
cfg, err := config.LoadConfig("")
require.NoError(t, err, "failed to load config")
// Verify that if the absolute path of the Firecracker unix sockets are longer
// than the max length enforced by the kernel (UNIX_PATH_MAX, usually 108), we
// don't fail (due to the internal implementation using relative paths).
// We do this by using the max VMID len (64 chars), which in combination with the
// default location we store state results in a path like
// "/run/firecracker-containerd/<namespace>/<vmID>" (with len 112).
const maxUnixSockLen = 108
namespace := strings.Repeat("n", 20)
vmID := strings.Repeat("v", 64)
ctx := namespaces.WithNamespace(context.Background(), namespace)
fcClient, err := newFCControlClient(containerdSockPath)
require.NoError(t, err, "failed to create fccontrol client")
subtests := []struct {
name string
request proto.CreateVMRequest
}{
{
name: "Without Jailer",
request: proto.CreateVMRequest{
VMID: vmID,
NetworkInterfaces: []*proto.FirecrackerNetworkInterface{},
},
},
{
name: "With Jailer",
request: proto.CreateVMRequest{
VMID: vmID,
NetworkInterfaces: []*proto.FirecrackerNetworkInterface{},
JailerConfig: &proto.JailerConfig{
UID: 30000,
GID: 30000,
},
},
},
}
for _, subtest := range subtests {
request := subtest.request
vmID := request.VMID
t.Run(subtest.name, func(t *testing.T) {
_, err = fcClient.CreateVM(ctx, &request)
require.NoError(t, err, "failed to create VM")
// double-check that the sockets are at the expected path and that their absolute
// length exceeds 108 bytes
shimDir, err := vm.ShimDir(cfg.ShimBaseDir, namespace, vmID)
require.NoError(t, err, "failed to get shim dir")
if request.JailerConfig == nil {
_, err = os.Stat(shimDir.FirecrackerSockPath())
require.NoError(t, err, "failed to stat firecracker socket path")
if len(shimDir.FirecrackerSockPath()) <= maxUnixSockLen {
assert.Failf(t, "firecracker sock absolute path %q is not greater than max unix socket path length", shimDir.FirecrackerSockPath())
}
_, err = os.Stat(shimDir.FirecrackerVSockPath())
require.NoError(t, err, "failed to stat firecracker vsock path")
if len(shimDir.FirecrackerVSockPath()) <= maxUnixSockLen {
assert.Failf(t, "firecracker vsock absolute path %q is not greater than max unix socket path length", shimDir.FirecrackerVSockPath())
}
}
_, err = fcClient.StopVM(ctx, &proto.StopVMRequest{VMID: vmID})
require.NoError(t, err)
matches, err := findProcess(ctx, findShim)
require.NoError(t, err)
require.Empty(t, matches)
matches, err = findProcess(ctx, findFirecracker)
require.NoError(t, err)
require.Empty(t, matches)
})
}
}
func allowDeviceAccess(_ context.Context, _ oci.Client, _ *containers.Container, s *oci.Spec) error {
// By default, all devices accesses are forbidden.
s.Linux.Resources.Devices = append(
s.Linux.Resources.Devices,
specs.LinuxDeviceCgroup{Allow: true, Access: "r"},
)
// Exposes the host kernel's /dev as /dev.
// By default, runc creates own /dev with a minimal set of pseudo devices such as /dev/null.
s.Mounts = append(s.Mounts, specs.Mount{
Type: "bind",
Options: []string{"bind"},
Destination: "/dev",
Source: "/dev",
})
return nil
}
func TestStubBlockDevices_Isolated(t *testing.T) {
prepareIntegTest(t)
const vmID = 0
ctx := namespaces.WithNamespace(context.Background(), "default")
client, err := containerd.New(containerdSockPath, containerd.WithDefaultRuntime(firecrackerRuntime))
require.NoError(t, err, "unable to create client to containerd service at %s, is containerd running?", containerdSockPath)
defer client.Close()
image, err := alpineImage(ctx, client, defaultSnapshotterName)
require.NoError(t, err, "failed to get alpine image")
tapName := fmt.Sprintf("tap%d", vmID)
err = createTapDevice(ctx, tapName)
require.NoError(t, err, "failed to create tap device for vm %d", vmID)
containerName := fmt.Sprintf("%s-%d", t.Name(), time.Now().UnixNano())
snapshotName := fmt.Sprintf("%s-snapshot", containerName)
fcClient, err := newFCControlClient(containerdSockPath)
require.NoError(t, err, "failed to create fccontrol client")
_, err = fcClient.CreateVM(ctx, &proto.CreateVMRequest{
VMID: strconv.Itoa(vmID),
NetworkInterfaces: []*proto.FirecrackerNetworkInterface{
{
AllowMMDS: true,
StaticConfig: &proto.StaticNetworkConfiguration{
HostDevName: tapName,
MacAddress: vmIDtoMacAddr(uint(vmID)),
},
},
},
ContainerCount: 5,
})
require.NoError(t, err, "failed to create VM")
newContainer, err := client.NewContainer(ctx,
containerName,
containerd.WithSnapshotter(defaultSnapshotterName),
containerd.WithNewSnapshot(snapshotName, image),
containerd.WithNewSpec(
firecrackeroci.WithVMID(strconv.Itoa(vmID)),
oci.WithProcessArgs("/bin/sh", "/var/firecracker-containerd-test/scripts/lsblk.sh"),
oci.WithMounts([]specs.Mount{
// Exposes test scripts from the host kernel
{
Type: "bind",
Options: []string{"bind"},
Destination: "/var/firecracker-containerd-test/scripts",
Source: "/var/firecracker-containerd-test/scripts",
},
}),
allowDeviceAccess,
),
)
require.NoError(t, err, "failed to create container %s", containerName)
var stdout bytes.Buffer
var stderr bytes.Buffer
newTask, err := newContainer.NewTask(ctx,
cio.NewCreator(cio.WithStreams(nil, &stdout, &stderr)))
require.NoError(t, err, "failed to create task for container %s", containerName)
exitCh, err := newTask.Wait(ctx)
require.NoError(t, err, "failed to wait on task for container %s", containerName)
err = newTask.Start(ctx)
require.NoError(t, err, "failed to start task for container %s", containerName)
const containerID = 0
select {
case exitStatus := <-exitCh:
_, err = newTask.Delete(ctx)
require.NoError(t, err)
// if there was anything on stderr, print it to assist debugging
stderrOutput := stderr.String()
if len(stderrOutput) != 0 {
fmt.Printf("stderr output from vm %d, container %d: %s", vmID, containerID, stderrOutput)
}
const expectedOutput = `
vdb 254:16 0 1073741824B 0 | 0 0 0 0 0 0 0 0
vdc 254:32 0 512B 0 | 214 244 216 245 215 177 177 177
vdd 254:48 0 512B 0 | 214 244 216 245 215 177 177 177
vde 254:64 0 512B 0 | 214 244 216 245 215 177 177 177
vdf 254:80 0 512B 0 | 214 244 216 245 215 177 177 177`
parts := strings.Split(stdout.String(), "vdb")
require.Equal(t, strings.TrimSpace(expectedOutput), strings.TrimSpace("vdb"+parts[1]))
require.NoError(t, exitStatus.Error(), "failed to retrieve exitStatus")
require.Equal(t, uint32(0), exitStatus.ExitCode())
case <-ctx.Done():
require.Fail(t, "context cancelled",
"context cancelled while waiting for container %s to exit, err: %v", containerName, ctx.Err())
}
}
func startAndWaitTask(ctx context.Context, t *testing.T, c containerd.Container) string {
var stdout bytes.Buffer
var stderr bytes.Buffer
task, err := c.NewTask(ctx, cio.NewCreator(cio.WithStreams(nil, &stdout, &stderr)))
require.NoError(t, err, "failed to create task for container %s", c.ID())
exitCh, err := task.Wait(ctx)
require.NoError(t, err, "failed to wait on task for container %s", c.ID())
err = task.Start(ctx)
require.NoError(t, err, "failed to start task for container %s", c.ID())
defer func() {
require.NoError(t, err, "failed to delete task for container %s", c.ID())
}()
select {
case exitStatus := <-exitCh:
assert.NoError(t, exitStatus.Error(), "failed to retrieve exitStatus")
assert.Equal(t, uint32(0), exitStatus.ExitCode())
status, err := task.Delete(ctx)
assert.NoErrorf(t, err, "failed to delete task %q after exit", c.ID())
if status != nil {
assert.NoError(t, status.Error())
}
assert.Equal(t, "", stderr.String())
case <-ctx.Done():
require.Fail(t, "context cancelled",
"context cancelled while waiting for container %s to exit, err: %v", c.ID(), ctx.Err())
}
return stdout.String()
}
func testCreateContainerWithSameName(t *testing.T, vmID string) {
ctx := namespaces.WithNamespace(context.Background(), "default")
// Explicitly specify Container Count = 2 to workaround #230
if len(vmID) != 0 {
fcClient, err := newFCControlClient(containerdSockPath)
require.NoError(t, err, "failed to create fccontrol client")
_, err = fcClient.CreateVM(ctx, &proto.CreateVMRequest{
VMID: vmID,
ContainerCount: 2,
})
require.NoError(t, err)
}
withNewSpec := containerd.WithNewSpec(oci.WithProcessArgs("echo", "hello"), firecrackeroci.WithVMID(vmID), oci.WithDefaultPathEnv)
client, err := containerd.New(containerdSockPath, containerd.WithDefaultRuntime(firecrackerRuntime))
require.NoError(t, err, "unable to create client to containerd service at %s, is containerd running?", containerdSockPath)
defer client.Close()
image, err := alpineImage(ctx, client, defaultSnapshotterName)
require.NoError(t, err, "failed to get alpine image")
containerName := fmt.Sprintf("%s-%d", t.Name(), time.Now().UnixNano())
snapshotName := fmt.Sprintf("%s-snapshot", containerName)
containerPath := fmt.Sprintf("/run/containerd/io.containerd.runtime.v2.task/default/%s", containerName)
c1, err := client.NewContainer(ctx,
containerName,
containerd.WithSnapshotter(defaultSnapshotterName),
containerd.WithNewSnapshot(snapshotName, image),
withNewSpec,
)
require.NoError(t, err, "failed to create container %s", containerName)
require.Equal(t, "hello\n", startAndWaitTask(ctx, t, c1))
// All resources regarding the container will be deleted
err = c1.Delete(ctx, containerd.WithSnapshotCleanup)
require.NoError(t, err, "failed to delete container %s", containerName)
_, err = os.Stat(containerPath)
require.True(t, os.IsNotExist(err))
cfg, err := config.LoadConfig("")
require.NoError(t, err, "failed to load config")
if len(vmID) != 0 {
shimPath := fmt.Sprintf("%s/default#%s/%s/%s", cfg.ShimBaseDir, vmID, vmID, containerName)
_, err = os.Stat(shimPath)
require.True(t, os.IsNotExist(err))
}
// So, we can launch a new container with the same name
c2, err := client.NewContainer(ctx,
containerName,
containerd.WithSnapshotter(defaultSnapshotterName),
containerd.WithNewSnapshot(snapshotName, image),
withNewSpec,
)
require.NoError(t, err, "failed to create container %s", containerName)
require.Equal(t, "hello\n", startAndWaitTask(ctx, t, c2))
err = c2.Delete(ctx, containerd.WithSnapshotCleanup)
require.NoError(t, err, "failed to delete container %s", containerName)
_, err = os.Stat(containerPath)
require.True(t, os.IsNotExist(err))
if len(vmID) != 0 {
shimPath := fmt.Sprintf("%s/default#%s/%s/%s", cfg.ShimBaseDir, vmID, vmID, containerName)
_, err = os.Stat(shimPath)
require.True(t, os.IsNotExist(err))
}
}
func TestCreateContainerWithSameName_Isolated(t *testing.T) {
prepareIntegTest(t)
testCreateContainerWithSameName(t, "")
vmID := fmt.Sprintf("same-vm-%d", time.Now().UnixNano())
testCreateContainerWithSameName(t, vmID)
}
func TestStubDriveReserveAndReleaseByContainers_Isolated(t *testing.T) {
prepareIntegTest(t)
assert := assert.New(t)
ctx := namespaces.WithNamespace(context.Background(), "default")
client, err := containerd.New(containerdSockPath, containerd.WithDefaultRuntime(firecrackerRuntime))
require.NoError(t, err, "unable to create client to containerd service at %s, is containerd running?", containerdSockPath)