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
|
// 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"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"syscall"
// Include filesystem types that OCI spec might mount.
_ "gvisor.dev/gvisor/pkg/sentry/fs/dev"
"gvisor.dev/gvisor/pkg/sentry/fs/gofer"
_ "gvisor.dev/gvisor/pkg/sentry/fs/host"
_ "gvisor.dev/gvisor/pkg/sentry/fs/proc"
"gvisor.dev/gvisor/pkg/sentry/fs/ramfs"
_ "gvisor.dev/gvisor/pkg/sentry/fs/sys"
_ "gvisor.dev/gvisor/pkg/sentry/fs/tmpfs"
_ "gvisor.dev/gvisor/pkg/sentry/fs/tty"
specs "github.com/opencontainers/runtime-spec/specs-go"
"gvisor.dev/gvisor/pkg/log"
"gvisor.dev/gvisor/pkg/sentry/context"
"gvisor.dev/gvisor/pkg/sentry/fs"
"gvisor.dev/gvisor/pkg/sentry/kernel"
"gvisor.dev/gvisor/pkg/syserror"
"gvisor.dev/gvisor/runsc/specutils"
)
const (
// Filesystem name for 9p gofer mounts.
rootFsName = "9p"
// Device name for root mount.
rootDevice = "9pfs-/"
// MountPrefix is the annotation prefix for mount hints.
MountPrefix = "gvisor.dev/spec/mount"
// Filesystems that runsc supports.
bind = "bind"
devpts = "devpts"
devtmpfs = "devtmpfs"
proc = "proc"
sysfs = "sysfs"
tmpfs = "tmpfs"
nonefs = "none"
)
func addOverlay(ctx context.Context, conf *Config, lower *fs.Inode, name string, lowerFlags fs.MountSourceFlags) (*fs.Inode, error) {
// Upper layer uses the same flags as lower, but it must be read-write.
upperFlags := lowerFlags
upperFlags.ReadOnly = false
tmpFS := mustFindFilesystem("tmpfs")
if !fs.IsDir(lower.StableAttr) {
// Create overlay on top of mount file, e.g. /etc/hostname.
msrc := fs.NewCachingMountSource(ctx, tmpFS, upperFlags)
return fs.NewOverlayRootFile(ctx, msrc, lower, upperFlags)
}
// Create overlay on top of mount dir.
upper, err := tmpFS.Mount(ctx, name+"-upper", upperFlags, "", nil)
if err != nil {
return nil, fmt.Errorf("creating tmpfs overlay: %v", err)
}
// Replicate permissions and owner from lower to upper mount point.
attr, err := lower.UnstableAttr(ctx)
if err != nil {
return nil, fmt.Errorf("reading attributes from lower mount point: %v", err)
}
if !upper.InodeOperations.SetPermissions(ctx, upper, attr.Perms) {
return nil, fmt.Errorf("error setting permission to upper mount point")
}
if err := upper.InodeOperations.SetOwner(ctx, upper, attr.Owner); err != nil {
return nil, fmt.Errorf("setting owner to upper mount point: %v", err)
}
return fs.NewOverlayRoot(ctx, upper, lower, upperFlags)
}
// compileMounts returns the supported mounts from the mount spec, adding any
// mandatory mounts that are required by the OCI specification.
func compileMounts(spec *specs.Spec) []specs.Mount {
// Keep track of whether proc and sys were mounted.
var procMounted, sysMounted bool
var mounts []specs.Mount
// Always mount /dev.
mounts = append(mounts, specs.Mount{
Type: devtmpfs,
Destination: "/dev",
})
mounts = append(mounts, specs.Mount{
Type: devpts,
Destination: "/dev/pts",
})
// Mount all submounts from the spec.
for _, m := range spec.Mounts {
if !specutils.IsSupportedDevMount(m) {
log.Warningf("ignoring dev mount at %q", m.Destination)
continue
}
mounts = append(mounts, m)
switch filepath.Clean(m.Destination) {
case "/proc":
procMounted = true
case "/sys":
sysMounted = true
}
}
// Mount proc and sys even if the user did not ask for it, as the spec
// says we SHOULD.
var mandatoryMounts []specs.Mount
if !procMounted {
mandatoryMounts = append(mandatoryMounts, specs.Mount{
Type: proc,
Destination: "/proc",
})
}
if !sysMounted {
mandatoryMounts = append(mandatoryMounts, specs.Mount{
Type: sysfs,
Destination: "/sys",
})
}
// The mandatory mounts should be ordered right after the root, in case
// there are submounts of these mandatory mounts already in the spec.
mounts = append(mounts[:0], append(mandatoryMounts, mounts[0:]...)...)
return mounts
}
// p9MountOptions creates a slice of options for a p9 mount.
func p9MountOptions(fd int, fa FileAccessType) []string {
opts := []string{
"trans=fd",
"rfdno=" + strconv.Itoa(fd),
"wfdno=" + strconv.Itoa(fd),
"privateunixsocket=true",
}
if fa == FileAccessShared {
opts = append(opts, "cache=remote_revalidating")
}
return opts
}
// parseAndFilterOptions parses a MountOptions slice and filters by the allowed
// keys.
func parseAndFilterOptions(opts []string, allowedKeys ...string) ([]string, error) {
var out []string
for _, o := range opts {
kv := strings.Split(o, "=")
switch len(kv) {
case 1:
if specutils.ContainsStr(allowedKeys, o) {
out = append(out, o)
continue
}
log.Warningf("ignoring unsupported key %q", kv)
case 2:
if specutils.ContainsStr(allowedKeys, kv[0]) {
out = append(out, o)
continue
}
log.Warningf("ignoring unsupported key %q", kv[0])
default:
return nil, fmt.Errorf("invalid option %q", o)
}
}
return out, nil
}
// mountDevice returns a device string based on the fs type and target
// of the mount.
func mountDevice(m specs.Mount) string {
if m.Type == bind {
// Make a device string that includes the target, which is consistent across
// S/R and uniquely identifies the connection.
return "9pfs-" + m.Destination
}
// All other fs types use device "none".
return "none"
}
func mountFlags(opts []string) fs.MountSourceFlags {
mf := fs.MountSourceFlags{}
for _, o := range opts {
switch o {
case "rw":
mf.ReadOnly = false
case "ro":
mf.ReadOnly = true
case "noatime":
mf.NoAtime = true
case "noexec":
mf.NoExec = true
default:
log.Warningf("ignoring unknown mount option %q", o)
}
}
return mf
}
func mustFindFilesystem(name string) fs.Filesystem {
fs, ok := fs.FindFilesystem(name)
if !ok {
panic(fmt.Sprintf("could not find filesystem %q", name))
}
return fs
}
// addSubmountOverlay overlays the inode over a ramfs tree containing the given
// paths.
func addSubmountOverlay(ctx context.Context, inode *fs.Inode, submounts []string) (*fs.Inode, error) {
// Construct a ramfs tree of mount points. The contents never
// change, so this can be fully caching. There's no real
// filesystem backing this tree, so we set the filesystem to
// nil.
msrc := fs.NewCachingMountSource(ctx, nil, fs.MountSourceFlags{})
mountTree, err := ramfs.MakeDirectoryTree(ctx, msrc, submounts)
if err != nil {
return nil, fmt.Errorf("creating mount tree: %v", err)
}
overlayInode, err := fs.NewOverlayRoot(ctx, inode, mountTree, fs.MountSourceFlags{})
if err != nil {
return nil, fmt.Errorf("adding mount overlay: %v", err)
}
return overlayInode, err
}
// subtargets takes a set of Mounts and returns only the targets that are
// children of the given root. The returned paths are relative to the root.
func subtargets(root string, mnts []specs.Mount) []string {
var targets []string
for _, mnt := range mnts {
if relPath, isSubpath := fs.IsSubpath(mnt.Destination, root); isSubpath {
targets = append(targets, relPath)
}
}
return targets
}
// setExecutablePath sets the procArgs.Filename by searching the PATH for an
// executable matching the procArgs.Argv[0].
func setExecutablePath(ctx context.Context, procArgs *kernel.CreateProcessArgs) error {
paths := fs.GetPath(procArgs.Envv)
exe := procArgs.Argv[0]
f, err := procArgs.MountNamespace.ResolveExecutablePath(ctx, procArgs.WorkingDirectory, exe, paths)
if err != nil {
return fmt.Errorf("searching for executable %q, cwd: %q, $PATH=%q: %v", exe, procArgs.WorkingDirectory, strings.Join(paths, ":"), err)
}
procArgs.Filename = f
return nil
}
func adjustDirentCache(k *kernel.Kernel) error {
var hl syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &hl); err != nil {
return fmt.Errorf("getting RLIMIT_NOFILE: %v", err)
}
if int64(hl.Cur) != syscall.RLIM_INFINITY {
newSize := hl.Cur / 2
if newSize < gofer.DefaultDirentCacheSize {
log.Infof("Setting gofer dirent cache size to %d", newSize)
gofer.DefaultDirentCacheSize = newSize
k.DirentCacheLimiter = fs.NewDirentCacheLimiter(newSize)
}
}
return nil
}
type fdDispenser struct {
fds []int
}
func (f *fdDispenser) remove() int {
if f.empty() {
panic("fdDispenser out of fds")
}
rv := f.fds[0]
f.fds = f.fds[1:]
return rv
}
func (f *fdDispenser) empty() bool {
return len(f.fds) == 0
}
type shareType int
const (
invalid shareType = iota
// container shareType indicates that the mount is used by a single container.
container
// pod shareType indicates that the mount is used by more than one container
// inside the pod.
pod
// shared shareType indicates that the mount can also be shared with a process
// outside the pod, e.g. NFS.
shared
)
func parseShare(val string) (shareType, error) {
switch val {
case "container":
return container, nil
case "pod":
return pod, nil
case "shared":
return shared, nil
default:
return 0, fmt.Errorf("invalid share value %q", val)
}
}
func (s shareType) String() string {
switch s {
case invalid:
return "invalid"
case container:
return "container"
case pod:
return "pod"
case shared:
return "shared"
default:
return fmt.Sprintf("invalid share value %d", s)
}
}
// mountHint represents extra information about mounts that are provided via
// annotations. They can override mount type, and provide sharing information
// so that mounts can be correctly shared inside the pod.
type mountHint struct {
name string
share shareType
mount specs.Mount
// root is the inode where the volume is mounted. For mounts with 'pod' share
// the volume is mounted once and then bind mounted inside the containers.
root *fs.Inode
}
func (m *mountHint) setField(key, val string) error {
switch key {
case "source":
if len(val) == 0 {
return fmt.Errorf("source cannot be empty")
}
m.mount.Source = val
case "type":
return m.setType(val)
case "share":
share, err := parseShare(val)
if err != nil {
return err
}
m.share = share
case "options":
return m.setOptions(val)
default:
return fmt.Errorf("invalid mount annotation: %s=%s", key, val)
}
return nil
}
func (m *mountHint) setType(val string) error {
switch val {
case "tmpfs", "bind":
m.mount.Type = val
default:
return fmt.Errorf("invalid type %q", val)
}
return nil
}
func (m *mountHint) setOptions(val string) error {
opts := strings.Split(val, ",")
if err := specutils.ValidateMountOptions(opts); err != nil {
return err
}
// Sort options so it can be compared with container mount options later on.
sort.Strings(opts)
m.mount.Options = opts
return nil
}
func (m *mountHint) isSupported() bool {
return m.mount.Type == tmpfs && m.share == pod
}
// podMountHints contains a collection of mountHints for the pod.
type podMountHints struct {
mounts map[string]*mountHint
}
func newPodMountHints(spec *specs.Spec) (*podMountHints, error) {
mnts := make(map[string]*mountHint)
for k, v := range spec.Annotations {
// Look for 'gvisor.dev/spec/mount' annotations and parse them.
if strings.HasPrefix(k, MountPrefix) {
parts := strings.Split(k, "/")
if len(parts) != 5 {
return nil, fmt.Errorf("invalid mount annotation: %s=%s", k, v)
}
name := parts[3]
if len(name) == 0 || path.Clean(name) != name {
return nil, fmt.Errorf("invalid mount name: %s", name)
}
mnt := mnts[name]
if mnt == nil {
mnt = &mountHint{name: name}
mnts[name] = mnt
}
if err := mnt.setField(parts[4], v); err != nil {
return nil, err
}
}
}
// Validate all hints after done parsing.
for name, m := range mnts {
log.Infof("Mount annotation found, name: %s, source: %q, type: %s, share: %v", name, m.mount.Source, m.mount.Type, m.share)
if m.share == invalid {
return nil, fmt.Errorf("share field for %q has not been set", m.name)
}
if len(m.mount.Source) == 0 {
return nil, fmt.Errorf("source field for %q has not been set", m.name)
}
if len(m.mount.Type) == 0 {
return nil, fmt.Errorf("type field for %q has not been set", m.name)
}
// Check for duplicate mount sources.
for name2, m2 := range mnts {
if name != name2 && m.mount.Source == m2.mount.Source {
return nil, fmt.Errorf("mounts %q and %q have the same mount source %q", m.name, m2.name, m.mount.Source)
}
}
}
return &podMountHints{mounts: mnts}, nil
}
func (p *podMountHints) findMount(mount specs.Mount) *mountHint {
for _, m := range p.mounts {
if m.mount.Source == mount.Source {
return m
}
}
return nil
}
type containerMounter struct {
root *specs.Root
// mounts is the set of submounts for the container. It's a copy from the spec
// that may be freely modified without affecting the original spec.
mounts []specs.Mount
// fds is the list of FDs to be dispensed for mounts that require it.
fds fdDispenser
k *kernel.Kernel
hints *podMountHints
}
func newContainerMounter(spec *specs.Spec, goferFDs []int, k *kernel.Kernel, hints *podMountHints) *containerMounter {
return &containerMounter{
root: spec.Root,
mounts: compileMounts(spec),
fds: fdDispenser{fds: goferFDs},
k: k,
hints: hints,
}
}
// setupChildContainer is used to set up the file system for non-root containers
// and amend the procArgs accordingly. This is the main entry point for this
// rest of functions in this file. procArgs are passed by reference and the
// FDMap field is modified. It dups stdioFDs.
func (c *containerMounter) setupChildContainer(conf *Config, procArgs *kernel.CreateProcessArgs) error {
// Setup a child container.
log.Infof("Creating new process in child container.")
// Create a new root inode and mount namespace for the container.
rootCtx := c.k.SupervisorContext()
rootInode, err := c.createRootMount(rootCtx, conf)
if err != nil {
return fmt.Errorf("creating filesystem for container: %v", err)
}
mns, err := fs.NewMountNamespace(rootCtx, rootInode)
if err != nil {
return fmt.Errorf("creating new mount namespace for container: %v", err)
}
procArgs.MountNamespace = mns
root := mns.Root()
defer root.DecRef()
// Mount all submounts.
if err := c.mountSubmounts(rootCtx, conf, mns, root); err != nil {
return err
}
return c.checkDispenser()
}
func (c *containerMounter) checkDispenser() error {
if !c.fds.empty() {
return fmt.Errorf("not all gofer FDs were consumed, remaining: %v", c.fds)
}
return nil
}
// setupRootContainer creates a mount namespace containing the root filesystem
// and all mounts. 'rootCtx' is used to walk directories to find mount points.
// The 'setMountNS' callback is called after the mount namespace is created and
// will get a reference on that namespace. The callback must ensure that the
// rootCtx has the provided mount namespace.
func (c *containerMounter) setupRootContainer(userCtx context.Context, rootCtx context.Context, conf *Config, setMountNS func(*fs.MountNamespace)) error {
for _, hint := range c.hints.mounts {
log.Infof("Mounting master of shared mount %q from %q type %q", hint.name, hint.mount.Source, hint.mount.Type)
inode, err := c.mountSharedMaster(rootCtx, conf, hint)
if err != nil {
return fmt.Errorf("mounting shared master %q: %v", hint.name, err)
}
hint.root = inode
}
rootInode, err := c.createRootMount(rootCtx, conf)
if err != nil {
return fmt.Errorf("creating root mount: %v", err)
}
mns, err := fs.NewMountNamespace(userCtx, rootInode)
if err != nil {
return fmt.Errorf("creating root mount namespace: %v", err)
}
setMountNS(mns)
root := mns.Root()
defer root.DecRef()
if err := c.mountSubmounts(rootCtx, conf, mns, root); err != nil {
return fmt.Errorf("mounting submounts: %v", err)
}
return c.checkDispenser()
}
// mountSharedMaster mounts the master of a volume that is shared among
// containers in a pod. It returns the root mount's inode.
func (c *containerMounter) mountSharedMaster(ctx context.Context, conf *Config, hint *mountHint) (*fs.Inode, error) {
// Map mount type to filesystem name, and parse out the options that we are
// capable of dealing with.
fsName, opts, useOverlay, err := c.getMountNameAndOptions(conf, hint.mount)
if err != nil {
return nil, err
}
if len(fsName) == 0 {
return nil, fmt.Errorf("mount type not supported %q", hint.mount.Type)
}
// Mount with revalidate because it's shared among containers.
opts = append(opts, "cache=revalidate")
// All filesystem names should have been mapped to something we know.
filesystem := mustFindFilesystem(fsName)
mf := mountFlags(hint.mount.Options)
if useOverlay {
// All writes go to upper, be paranoid and make lower readonly.
mf.ReadOnly = true
}
inode, err := filesystem.Mount(ctx, mountDevice(hint.mount), mf, strings.Join(opts, ","), nil)
if err != nil {
return nil, fmt.Errorf("creating mount %q: %v", hint.name, err)
}
if useOverlay {
log.Debugf("Adding overlay on top of shared mount %q", hint.name)
inode, err = addOverlay(ctx, conf, inode, hint.mount.Type, mf)
if err != nil {
return nil, err
}
}
return inode, nil
}
// createRootMount creates the root filesystem.
func (c *containerMounter) createRootMount(ctx context.Context, conf *Config) (*fs.Inode, error) {
// First construct the filesystem from the spec.Root.
mf := fs.MountSourceFlags{ReadOnly: c.root.Readonly || conf.Overlay}
fd := c.fds.remove()
log.Infof("Mounting root over 9P, ioFD: %d", fd)
p9FS := mustFindFilesystem("9p")
opts := p9MountOptions(fd, conf.FileAccess)
rootInode, err := p9FS.Mount(ctx, rootDevice, mf, strings.Join(opts, ","), nil)
if err != nil {
return nil, fmt.Errorf("creating root mount point: %v", err)
}
// We need to overlay the root on top of a ramfs with stub directories
// for submount paths. "/dev" "/sys" "/proc" and "/tmp" are always
// mounted even if they are not in the spec.
submounts := append(subtargets("/", c.mounts), "/dev", "/sys", "/proc", "/tmp")
rootInode, err = addSubmountOverlay(ctx, rootInode, submounts)
if err != nil {
return nil, fmt.Errorf("adding submount overlay: %v", err)
}
if conf.Overlay && !c.root.Readonly {
log.Debugf("Adding overlay on top of root mount")
// Overlay a tmpfs filesystem on top of the root.
rootInode, err = addOverlay(ctx, conf, rootInode, "root-overlay-upper", mf)
if err != nil {
return nil, err
}
}
log.Infof("Mounted %q to %q type root", c.root.Path, "/")
return rootInode, nil
}
// getMountNameAndOptions retrieves the fsName, opts, and useOverlay values
// used for mounts.
func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (string, []string, bool, error) {
var (
fsName string
opts []string
useOverlay bool
err error
)
switch m.Type {
case devpts, devtmpfs, proc, sysfs:
fsName = m.Type
case nonefs:
fsName = sysfs
case tmpfs:
fsName = m.Type
// tmpfs has some extra supported options that we must pass through.
opts, err = parseAndFilterOptions(m.Options, "mode", "uid", "gid")
case bind:
fd := c.fds.remove()
fsName = "9p"
// Non-root bind mounts are always shared.
opts = p9MountOptions(fd, FileAccessShared)
// If configured, add overlay to all writable mounts.
useOverlay = conf.Overlay && !mountFlags(m.Options).ReadOnly
default:
// TODO(nlacasse): Support all the mount types and make this a fatal error.
// Most applications will "just work" without them, so this is a warning
// for now.
log.Warningf("ignoring unknown filesystem type %q", m.Type)
}
return fsName, opts, useOverlay, err
}
func (c *containerMounter) mountSubmounts(ctx context.Context, conf *Config, mns *fs.MountNamespace, root *fs.Dirent) error {
for _, m := range c.mounts {
if hint := c.hints.findMount(m); hint != nil && hint.isSupported() {
if err := c.mountSharedSubmount(ctx, mns, root, m, hint); err != nil {
return fmt.Errorf("mount shared mount %q to %q: %v", hint.name, m.Destination, err)
}
} else {
if err := c.mountSubmount(ctx, conf, mns, root, m); err != nil {
return fmt.Errorf("mount submount %q: %v", m.Destination, err)
}
}
}
if err := c.mountTmp(ctx, conf, mns, root); err != nil {
return fmt.Errorf("mount submount %q: %v", "tmp", err)
}
return nil
}
// mountSubmount mounts volumes inside the container's root. Because mounts may
// be readonly, a lower ramfs overlay is added to create the mount point dir.
// Another overlay is added with tmpfs on top if Config.Overlay is true.
// 'm.Destination' must be an absolute path with '..' and symlinks resolved.
func (c *containerMounter) mountSubmount(ctx context.Context, conf *Config, mns *fs.MountNamespace, root *fs.Dirent, m specs.Mount) error {
// Map mount type to filesystem name, and parse out the options that we are
// capable of dealing with.
fsName, opts, useOverlay, err := c.getMountNameAndOptions(conf, m)
if err != nil {
return err
}
if fsName == "" {
// Filesystem is not supported (e.g. cgroup), just skip it.
return nil
}
// All filesystem names should have been mapped to something we know.
filesystem := mustFindFilesystem(fsName)
mf := mountFlags(m.Options)
if useOverlay {
// All writes go to upper, be paranoid and make lower readonly.
mf.ReadOnly = true
}
inode, err := filesystem.Mount(ctx, mountDevice(m), mf, strings.Join(opts, ","), nil)
if err != nil {
return fmt.Errorf("creating mount with source %q: %v", m.Source, err)
}
// If there are submounts, we need to overlay the mount on top of a ramfs
// with stub directories for submount paths.
submounts := subtargets(m.Destination, c.mounts)
if len(submounts) > 0 {
log.Infof("Adding submount overlay over %q", m.Destination)
inode, err = addSubmountOverlay(ctx, inode, submounts)
if err != nil {
return fmt.Errorf("adding submount overlay: %v", err)
}
}
if useOverlay {
log.Debugf("Adding overlay on top of mount %q", m.Destination)
inode, err = addOverlay(ctx, conf, inode, m.Type, mf)
if err != nil {
return err
}
}
maxTraversals := uint(0)
dirent, err := mns.FindInode(ctx, root, root, m.Destination, &maxTraversals)
if err != nil {
return fmt.Errorf("can't find mount destination %q: %v", m.Destination, err)
}
defer dirent.DecRef()
if err := mns.Mount(ctx, dirent, inode); err != nil {
return fmt.Errorf("mount %q error: %v", m.Destination, err)
}
log.Infof("Mounted %q to %q type %s", m.Source, m.Destination, m.Type)
return nil
}
// mountSharedSubmount binds mount to a previously mounted volume that is shared
// among containers in the same pod.
func (c *containerMounter) mountSharedSubmount(ctx context.Context, mns *fs.MountNamespace, root *fs.Dirent, mount specs.Mount, source *mountHint) error {
// For now enforce that all options are the same. Once bind mount is properly
// supported, then we should ensure the master is less restrictive than the
// container, e.g. master can be 'rw' while container mounts as 'ro'.
if len(mount.Options) != len(source.mount.Options) {
return fmt.Errorf("mount options in annotations differ from container mount, annotation: %s, mount: %s", source.mount.Options, mount.Options)
}
sort.Strings(mount.Options)
for i, opt := range mount.Options {
if opt != source.mount.Options[i] {
return fmt.Errorf("mount options in annotations differ from container mount, annotation: %s, mount: %s", source.mount.Options, mount.Options)
}
}
maxTraversals := uint(0)
target, err := mns.FindInode(ctx, root, root, mount.Destination, &maxTraversals)
if err != nil {
return fmt.Errorf("can't find mount destination %q: %v", mount.Destination, err)
}
defer target.DecRef()
// Take a ref on the inode that is about to be (re)-mounted.
source.root.IncRef()
if err := mns.Mount(ctx, target, source.root); err != nil {
source.root.DecRef()
return fmt.Errorf("bind mount %q error: %v", mount.Destination, err)
}
log.Infof("Mounted %q type shared bind to %q", mount.Destination, source.name)
return nil
}
// addRestoreMount adds a mount to the MountSources map used for restoring a
// checkpointed container.
func (c *containerMounter) addRestoreMount(conf *Config, renv *fs.RestoreEnvironment, m specs.Mount) error {
fsName, opts, useOverlay, err := c.getMountNameAndOptions(conf, m)
if err != nil {
return err
}
if fsName == "" {
// Filesystem is not supported (e.g. cgroup), just skip it.
return nil
}
newMount := fs.MountArgs{
Dev: mountDevice(m),
Flags: mountFlags(m.Options),
DataString: strings.Join(opts, ","),
}
if useOverlay {
newMount.Flags.ReadOnly = true
}
renv.MountSources[fsName] = append(renv.MountSources[fsName], newMount)
log.Infof("Added mount at %q: %+v", fsName, newMount)
return nil
}
// createRestoreEnvironment builds a fs.RestoreEnvironment called renv by adding
// the mounts to the environment.
func (c *containerMounter) createRestoreEnvironment(conf *Config) (*fs.RestoreEnvironment, error) {
renv := &fs.RestoreEnvironment{
MountSources: make(map[string][]fs.MountArgs),
}
// Add root mount.
fd := c.fds.remove()
opts := p9MountOptions(fd, conf.FileAccess)
mf := fs.MountSourceFlags{}
if c.root.Readonly || conf.Overlay {
mf.ReadOnly = true
}
rootMount := fs.MountArgs{
Dev: rootDevice,
Flags: mf,
DataString: strings.Join(opts, ","),
}
renv.MountSources[rootFsName] = append(renv.MountSources[rootFsName], rootMount)
// Add submounts.
var tmpMounted bool
for _, m := range c.mounts {
if err := c.addRestoreMount(conf, renv, m); err != nil {
return nil, err
}
if filepath.Clean(m.Destination) == "/tmp" {
tmpMounted = true
}
}
// TODO(b/67958150): handle '/tmp' properly (see mountTmp()).
if !tmpMounted {
tmpMount := specs.Mount{
Type: tmpfs,
Destination: "/tmp",
}
if err := c.addRestoreMount(conf, renv, tmpMount); err != nil {
return nil, err
}
}
return renv, nil
}
// mountTmp mounts an internal tmpfs at '/tmp' if it's safe to do so.
// Technically we don't have to mount tmpfs at /tmp, as we could just rely on
// the host /tmp, but this is a nice optimization, and fixes some apps that call
// mknod in /tmp. It's unsafe to mount tmpfs if:
// 1. /tmp is mounted explicitly: we should not override user's wish
// 2. /tmp is not empty: mounting tmpfs would hide existing files in /tmp
//
// Note that when there are submounts inside of '/tmp', directories for the
// mount points must be present, making '/tmp' not empty anymore.
func (c *containerMounter) mountTmp(ctx context.Context, conf *Config, mns *fs.MountNamespace, root *fs.Dirent) error {
for _, m := range c.mounts {
if filepath.Clean(m.Destination) == "/tmp" {
log.Debugf("Explict %q mount found, skipping internal tmpfs, mount: %+v", "/tmp", m)
return nil
}
}
maxTraversals := uint(0)
tmp, err := mns.FindInode(ctx, root, root, "tmp", &maxTraversals)
switch err {
case nil:
// Found '/tmp' in filesystem, check if it's empty.
defer tmp.DecRef()
f, err := tmp.Inode.GetFile(ctx, tmp, fs.FileFlags{Read: true, Directory: true})
if err != nil {
return err
}
defer f.DecRef()
serializer := &fs.CollectEntriesSerializer{}
if err := f.Readdir(ctx, serializer); err != nil {
return err
}
// If more than "." and ".." is found, skip internal tmpfs to prevent hiding
// existing files.
if len(serializer.Order) > 2 {
log.Infof("Skipping internal tmpfs on top %q, because it's not empty", "/tmp")
return nil
}
log.Infof("Mounting internal tmpfs on top of empty %q", "/tmp")
fallthrough
case syserror.ENOENT:
// No '/tmp' found (or fallthrough from above). Safe to mount internal
// tmpfs.
tmpMount := specs.Mount{
Type: tmpfs,
Destination: "/tmp",
// Sticky bit is added to prevent accidental deletion of files from
// another user. This is normally done for /tmp.
Options: []string{"mode=1777"},
}
return c.mountSubmount(ctx, conf, mns, root, tmpMount)
default:
return err
}
}
|