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
|
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License 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 boot
import (
"fmt"
"math/rand"
"os"
"reflect"
"syscall"
"testing"
"time"
specs "github.com/opencontainers/runtime-spec/specs-go"
"golang.org/x/sys/unix"
"gvisor.dev/gvisor/pkg/control/server"
"gvisor.dev/gvisor/pkg/fd"
"gvisor.dev/gvisor/pkg/fspath"
"gvisor.dev/gvisor/pkg/log"
"gvisor.dev/gvisor/pkg/p9"
"gvisor.dev/gvisor/pkg/sentry/contexttest"
"gvisor.dev/gvisor/pkg/sentry/fs"
"gvisor.dev/gvisor/pkg/sentry/vfs"
"gvisor.dev/gvisor/pkg/sync"
"gvisor.dev/gvisor/pkg/unet"
"gvisor.dev/gvisor/runsc/config"
"gvisor.dev/gvisor/runsc/fsgofer"
)
func init() {
log.SetLevel(log.Debug)
rand.Seed(time.Now().UnixNano())
if err := fsgofer.OpenProcSelfFD(); err != nil {
panic(err)
}
config.RegisterFlags()
}
func testConfig() *config.Config {
conf, err := config.NewFromFlags()
if err != nil {
panic(err)
}
// Change test defaults.
conf.RootDir = "unused_root_dir"
conf.Network = config.NetworkNone
conf.DisableSeccomp = true
return conf
}
// testSpec returns a simple spec that can be used in tests.
func testSpec() *specs.Spec {
return &specs.Spec{
// The host filesystem root is the sandbox root.
Root: &specs.Root{
Path: "/",
Readonly: true,
},
Process: &specs.Process{
Args: []string{"/bin/true"},
},
}
}
// startGofer starts a new gofer routine serving 'root' path. It returns the
// sandbox side of the connection, and a function that when called will stop the
// gofer.
func startGofer(root string) (int, func(), error) {
fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC, 0)
if err != nil {
return 0, nil, err
}
sandboxEnd, goferEnd := fds[0], fds[1]
socket, err := unet.NewSocket(goferEnd)
if err != nil {
syscall.Close(sandboxEnd)
syscall.Close(goferEnd)
return 0, nil, fmt.Errorf("error creating server on FD %d: %v", goferEnd, err)
}
at, err := fsgofer.NewAttachPoint(root, fsgofer.Config{ROMount: true})
if err != nil {
return 0, nil, err
}
go func() {
s := p9.NewServer(at)
if err := s.Handle(socket); err != nil {
log.Infof("Gofer is stopping. FD: %d, err: %v\n", goferEnd, err)
}
}()
// Closing the gofer socket will stop the gofer and exit goroutine above.
cleanup := func() {
if err := socket.Close(); err != nil {
log.Warningf("Error closing gofer socket: %v", err)
}
}
return sandboxEnd, cleanup, nil
}
func createLoader(vfsEnabled bool, spec *specs.Spec) (*Loader, func(), error) {
fd, err := server.CreateSocket(ControlSocketAddr(fmt.Sprintf("%010d", rand.Int())[:10]))
if err != nil {
return nil, nil, err
}
conf := testConfig()
conf.VFS2 = vfsEnabled
sandEnd, cleanup, err := startGofer(spec.Root.Path)
if err != nil {
return nil, nil, err
}
// Loader takes ownership of stdio.
var stdio []int
for _, f := range []*os.File{os.Stdin, os.Stdout, os.Stderr} {
newFd, err := unix.Dup(int(f.Fd()))
if err != nil {
return nil, nil, err
}
stdio = append(stdio, newFd)
}
args := Args{
ID: "foo",
Spec: spec,
Conf: conf,
ControllerFD: fd,
GoferFDs: []int{sandEnd},
StdioFDs: stdio,
}
l, err := New(args)
if err != nil {
cleanup()
return nil, nil, err
}
return l, cleanup, nil
}
// TestRun runs a simple application in a sandbox and checks that it succeeds.
func TestRun(t *testing.T) {
doRun(t, false)
}
// TestRunVFS2 runs TestRun in VFSv2.
func TestRunVFS2(t *testing.T) {
doRun(t, true)
}
func doRun(t *testing.T, vfsEnabled bool) {
l, cleanup, err := createLoader(vfsEnabled, testSpec())
if err != nil {
t.Fatalf("error creating loader: %v", err)
}
defer l.Destroy()
defer cleanup()
// Start a goroutine to read the start chan result, otherwise Run will
// block forever.
var resultChanErr error
var wg sync.WaitGroup
wg.Add(1)
go func() {
resultChanErr = <-l.ctrl.manager.startResultChan
wg.Done()
}()
// Run the container.
if err := l.Run(); err != nil {
t.Errorf("error running container: %v", err)
}
// We should have not gotten an error on the startResultChan.
wg.Wait()
if resultChanErr != nil {
t.Errorf("error on startResultChan: %v", resultChanErr)
}
// Wait for the application to exit. It should succeed.
if status := l.WaitExit(); status.Code != 0 || status.Signo != 0 {
t.Errorf("application exited with status %+v, want 0", status)
}
}
// TestStartSignal tests that the controller Start message will cause
// WaitForStartSignal to return.
func TestStartSignal(t *testing.T) {
doStartSignal(t, false)
}
// TestStartSignalVFS2 does TestStartSignal with VFS2.
func TestStartSignalVFS2(t *testing.T) {
doStartSignal(t, true)
}
func doStartSignal(t *testing.T, vfsEnabled bool) {
l, cleanup, err := createLoader(vfsEnabled, testSpec())
if err != nil {
t.Fatalf("error creating loader: %v", err)
}
defer l.Destroy()
defer cleanup()
// We aren't going to wait on this application, so the control server
// needs to be shut down manually.
defer l.ctrl.srv.Stop()
// Start a goroutine that calls WaitForStartSignal and writes to a
// channel when it returns.
waitFinished := make(chan struct{})
go func() {
l.WaitForStartSignal()
// Pretend that Run() executed and returned no error.
l.ctrl.manager.startResultChan <- nil
waitFinished <- struct{}{}
}()
// Nothing has been written to the channel, so waitFinished should not
// return. Give it a little bit of time to make sure the goroutine has
// started.
select {
case <-waitFinished:
t.Errorf("WaitForStartSignal completed but it should not have")
case <-time.After(50 * time.Millisecond):
// OK.
}
// Trigger the control server StartRoot method.
cid := "foo"
if err := l.ctrl.manager.StartRoot(&cid, nil); err != nil {
t.Errorf("error calling StartRoot: %v", err)
}
// Now WaitForStartSignal should return (within a short amount of
// time).
select {
case <-waitFinished:
// OK.
case <-time.After(50 * time.Millisecond):
t.Errorf("WaitForStartSignal did not complete but it should have")
}
}
type CreateMountTestcase struct {
name string
// Spec that will be used to create the mount manager. Note
// that we can't mount procfs without a kernel, so each spec
// MUST contain something other than procfs mounted at /proc.
spec specs.Spec
// Paths that are expected to exist in the resulting fs.
expectedPaths []string
}
func createMountTestcases() []*CreateMountTestcase {
testCases := []*CreateMountTestcase{
&CreateMountTestcase{
// Only proc.
name: "only proc mount",
spec: specs.Spec{
Root: &specs.Root{
Path: os.TempDir(),
Readonly: true,
},
Mounts: []specs.Mount{
{
Destination: "/proc",
Type: "tmpfs",
},
},
},
// /proc, /dev, and /sys should always be mounted.
expectedPaths: []string{"/proc", "/dev", "/sys"},
},
{
// Mount at a deep path, with many components that do
// not exist in the root.
name: "deep mount path",
spec: specs.Spec{
Root: &specs.Root{
Path: os.TempDir(),
Readonly: true,
},
Mounts: []specs.Mount{
{
Destination: "/some/very/very/deep/path",
Type: "tmpfs",
},
{
Destination: "/proc",
Type: "tmpfs",
},
},
},
// /some/deep/path should be mounted, along with /proc,
// /dev, and /sys.
expectedPaths: []string{"/some/very/very/deep/path", "/proc", "/dev", "/sys"},
},
&CreateMountTestcase{
// Mounts are nested inside each other.
name: "nested mounts",
spec: specs.Spec{
Root: &specs.Root{
Path: os.TempDir(),
Readonly: true,
},
Mounts: []specs.Mount{
{
Destination: "/proc",
Type: "tmpfs",
},
{
Destination: "/foo",
Type: "tmpfs",
},
{
Destination: "/foo/qux",
Type: "tmpfs",
},
{
// File mounts with the same prefix.
Destination: "/foo/qux-quz",
Type: "tmpfs",
},
{
Destination: "/foo/bar",
Type: "tmpfs",
},
{
Destination: "/foo/bar/baz",
Type: "tmpfs",
},
{
// A deep path that is in foo but not the other mounts.
Destination: "/foo/some/very/very/deep/path",
Type: "tmpfs",
},
},
},
expectedPaths: []string{"/foo", "/foo/bar", "/foo/bar/baz", "/foo/qux",
"/foo/qux-quz", "/foo/some/very/very/deep/path", "/proc", "/dev", "/sys"},
},
&CreateMountTestcase{
name: "mount inside /dev",
spec: specs.Spec{
Root: &specs.Root{
Path: os.TempDir(),
Readonly: true,
},
Mounts: []specs.Mount{
{
Destination: "/proc",
Type: "tmpfs",
},
{
Destination: "/dev",
Type: "tmpfs",
},
{
// Mounted by runsc by default.
Destination: "/dev/fd",
Type: "tmpfs",
},
{
// Mount with the same prefix.
Destination: "/dev/fd-foo",
Type: "tmpfs",
},
{
// Unsupported fs type.
Destination: "/dev/mqueue",
Type: "mqueue",
},
{
Destination: "/dev/foo",
Type: "tmpfs",
},
{
Destination: "/dev/bar",
Type: "tmpfs",
},
},
},
expectedPaths: []string{"/proc", "/dev", "/dev/fd-foo", "/dev/foo", "/dev/bar", "/sys"},
},
}
vfsCase := &CreateMountTestcase{
name: "mounts inside mandatory mounts",
spec: specs.Spec{
Root: &specs.Root{
Path: os.TempDir(),
Readonly: true,
},
Mounts: []specs.Mount{
{
Destination: "/proc",
Type: "tmpfs",
},
{
Destination: "/sys/bar",
Type: "tmpfs",
},
{
Destination: "/tmp/baz",
Type: "tmpfs",
},
},
},
expectedPaths: []string{"/proc", "/sys", "/sys/bar", "/tmp", "/tmp/baz"},
}
return append(testCases, vfsCase)
}
// Test that MountNamespace can be created with various specs.
func TestCreateMountNamespace(t *testing.T) {
for _, tc := range createMountTestcases() {
t.Run(tc.name, func(t *testing.T) {
conf := testConfig()
ctx := contexttest.Context(t)
sandEnd, cleanup, err := startGofer(tc.spec.Root.Path)
if err != nil {
t.Fatalf("failed to create gofer: %v", err)
}
defer cleanup()
mntr := newContainerMounter(&tc.spec, []*fd.FD{fd.New(sandEnd)}, nil, &podMountHints{})
mns, err := mntr.createMountNamespace(ctx, conf)
if err != nil {
t.Fatalf("failed to create mount namespace: %v", err)
}
ctx = fs.WithRoot(ctx, mns.Root())
if err := mntr.mountSubmounts(ctx, conf, mns); err != nil {
t.Fatalf("failed to create mount namespace: %v", err)
}
root := mns.Root()
defer root.DecRef(ctx)
for _, p := range tc.expectedPaths {
maxTraversals := uint(0)
if d, err := mns.FindInode(ctx, root, root, p, &maxTraversals); err != nil {
t.Errorf("expected path %v to exist with spec %v, but got error %v", p, tc.spec, err)
} else {
d.DecRef(ctx)
}
}
})
}
}
// Test that MountNamespace can be created with various specs.
func TestCreateMountNamespaceVFS2(t *testing.T) {
for _, tc := range createMountTestcases() {
t.Run(tc.name, func(t *testing.T) {
spec := testSpec()
spec.Mounts = tc.spec.Mounts
spec.Root = tc.spec.Root
t.Logf("Using root: %q", spec.Root.Path)
l, loaderCleanup, err := createLoader(true /* VFS2 Enabled */, spec)
if err != nil {
t.Fatalf("failed to create loader: %v", err)
}
defer l.Destroy()
defer loaderCleanup()
mntr := newContainerMounter(l.root.spec, l.root.goferFDs, l.k, l.mountHints)
if err := mntr.processHints(l.root.conf, l.root.procArgs.Credentials); err != nil {
t.Fatalf("failed process hints: %v", err)
}
ctx := l.k.SupervisorContext()
mns, err := mntr.mountAll(l.root.conf, &l.root.procArgs)
if err != nil {
t.Fatalf("mountAll: %v", err)
}
root := mns.Root()
defer root.DecRef(ctx)
for _, p := range tc.expectedPaths {
target := &vfs.PathOperation{
Root: root,
Start: root,
Path: fspath.Parse(p),
}
if d, err := l.k.VFS().GetDentryAt(ctx, l.root.procArgs.Credentials, target, &vfs.GetDentryOptions{}); err != nil {
t.Errorf("expected path %v to exist with spec %v, but got error %v", p, tc.spec, err)
} else {
d.DecRef(ctx)
}
}
})
}
}
// TestRestoreEnvironment tests that the correct mounts are collected from the spec and config
// in order to build the environment for restoring.
func TestRestoreEnvironment(t *testing.T) {
testCases := []struct {
name string
spec *specs.Spec
ioFDs []int
errorExpected bool
expectedRenv fs.RestoreEnvironment
}{
{
name: "basic spec test",
spec: &specs.Spec{
Root: &specs.Root{
Path: os.TempDir(),
Readonly: true,
},
Mounts: []specs.Mount{
{
Destination: "/some/very/very/deep/path",
Type: "tmpfs",
},
{
Destination: "/proc",
Type: "tmpfs",
},
},
},
ioFDs: []int{0},
errorExpected: false,
expectedRenv: fs.RestoreEnvironment{
MountSources: map[string][]fs.MountArgs{
"9p": {
{
Dev: "9pfs-/",
Flags: fs.MountSourceFlags{ReadOnly: true},
DataString: "trans=fd,rfdno=0,wfdno=0,privateunixsocket=true",
},
},
"tmpfs": {
{
Dev: "none",
},
{
Dev: "none",
},
{
Dev: "none",
},
},
"devtmpfs": {
{
Dev: "none",
},
},
"devpts": {
{
Dev: "none",
},
},
"sysfs": {
{
Dev: "none",
},
},
},
},
},
{
name: "bind type test",
spec: &specs.Spec{
Root: &specs.Root{
Path: os.TempDir(),
Readonly: true,
},
Mounts: []specs.Mount{
{
Destination: "/dev/fd-foo",
Type: "bind",
},
},
},
ioFDs: []int{0, 1},
errorExpected: false,
expectedRenv: fs.RestoreEnvironment{
MountSources: map[string][]fs.MountArgs{
"9p": {
{
Dev: "9pfs-/",
Flags: fs.MountSourceFlags{ReadOnly: true},
DataString: "trans=fd,rfdno=0,wfdno=0,privateunixsocket=true",
},
{
Dev: "9pfs-/dev/fd-foo",
DataString: "trans=fd,rfdno=1,wfdno=1,privateunixsocket=true,cache=remote_revalidating",
},
},
"tmpfs": {
{
Dev: "none",
},
},
"devtmpfs": {
{
Dev: "none",
},
},
"devpts": {
{
Dev: "none",
},
},
"proc": {
{
Dev: "none",
},
},
"sysfs": {
{
Dev: "none",
},
},
},
},
},
{
name: "options test",
spec: &specs.Spec{
Root: &specs.Root{
Path: os.TempDir(),
Readonly: true,
},
Mounts: []specs.Mount{
{
Destination: "/dev/fd-foo",
Type: "tmpfs",
Options: []string{"uid=1022", "noatime"},
},
},
},
ioFDs: []int{0},
errorExpected: false,
expectedRenv: fs.RestoreEnvironment{
MountSources: map[string][]fs.MountArgs{
"9p": {
{
Dev: "9pfs-/",
Flags: fs.MountSourceFlags{ReadOnly: true},
DataString: "trans=fd,rfdno=0,wfdno=0,privateunixsocket=true",
},
},
"tmpfs": {
{
Dev: "none",
Flags: fs.MountSourceFlags{NoAtime: true},
DataString: "uid=1022",
},
{
Dev: "none",
},
},
"devtmpfs": {
{
Dev: "none",
},
},
"devpts": {
{
Dev: "none",
},
},
"proc": {
{
Dev: "none",
},
},
"sysfs": {
{
Dev: "none",
},
},
},
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
conf := testConfig()
var ioFDs []*fd.FD
for _, ioFD := range tc.ioFDs {
ioFDs = append(ioFDs, fd.New(ioFD))
}
mntr := newContainerMounter(tc.spec, ioFDs, nil, &podMountHints{})
actualRenv, err := mntr.createRestoreEnvironment(conf)
if !tc.errorExpected && err != nil {
t.Fatalf("could not create restore environment for test:%s", tc.name)
} else if tc.errorExpected {
if err == nil {
t.Errorf("expected an error, but no error occurred.")
}
} else {
if !reflect.DeepEqual(*actualRenv, tc.expectedRenv) {
t.Errorf("restore environments did not match for test:%s\ngot:%+v\nwant:%+v\n", tc.name, *actualRenv, tc.expectedRenv)
}
}
})
}
}
|