aboutsummaryrefslogtreecommitdiffhomepage
path: root/container/autoroot.go
blob: b6375b8c2609d154a186c92d7e9bc7f6c0e28de1 (plain)
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
package container

import (
	"encoding/gob"
	"fmt"
	"os"
	"path"
	. "syscall"
)

func init() { gob.Register(new(AutoRootOp)) }

// Root appends an [Op] that expands a directory into a toplevel bind mount mirror on container root.
// This is not a generic setup op. It is implemented here to reduce ipc overhead.
func (f *Ops) Root(host, prefix string, flags int) *Ops {
	*f = append(*f, &AutoRootOp{host, prefix, flags, nil})
	return f
}

type AutoRootOp struct {
	Host, Prefix string
	// passed through to bindMount
	Flags int

	// obtained during early;
	// these wrap the underlying Op because BindMountOp is relatively complex,
	// so duplicating that code would be unwise
	resolved []Op
}

func (r *AutoRootOp) early(params *Params) error {
	if !path.IsAbs(r.Host) {
		return msg.WrapErr(EBADE, fmt.Sprintf("path %q is not absolute", r.Host))
	}

	if d, err := os.ReadDir(r.Host); err != nil {
		return wrapErrSelf(err)
	} else {
		r.resolved = make([]Op, 0, len(d))
		for _, ent := range d {
			name := ent.Name()
			if IsAutoRootBindable(name) {
				op := &BindMountOp{
					Source: path.Join(r.Host, name),
					Target: "/" + name,
					Flags:  r.Flags,
				}
				if err = op.early(params); err != nil {
					return err
				}
				r.resolved = append(r.resolved, op)
			}
		}
		return nil
	}
}

func (r *AutoRootOp) apply(params *Params) error {
	for _, op := range r.resolved {
		msg.Verbosef("%s %s", op.prefix(), op)
		if err := op.apply(params); err != nil {
			return err
		}
	}
	return nil
}

func (r *AutoRootOp) Is(op Op) bool {
	vr, ok := op.(*AutoRootOp)
	return ok && ((r == nil && vr == nil) || (r != nil && vr != nil &&
		r.Host == vr.Host && r.Prefix == vr.Prefix && r.Flags == vr.Flags))
}
func (*AutoRootOp) prefix() string { return "setting up" }
func (r *AutoRootOp) String() string {
	return fmt.Sprintf("auto root %q prefix %s flags %#x", r.Host, r.Prefix, r.Flags)
}

// IsAutoRootBindable returns whether a dir entry name is selected for AutoRoot.
func IsAutoRootBindable(name string) bool {
	switch name {
	case "proc":
	case "dev":
	case "tmp":
	case "mnt":
	case "etc":

	default:
		return true
	}
	return false
}