aboutsummaryrefslogtreecommitdiffhomepage
path: root/hst/fsbind.go
blob: e95eb7b7d54eec53aaf3dd29236290a715d0b1bc (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
92
93
94
95
96
97
98
99
100
101
102
package hst

import (
	"encoding/gob"
	"strings"

	"hakurei.app/container"
)

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

// FilesystemBind is the [FilesystemConfig.Type] name of a bind mount point.
const FilesystemBind = "bind"

// FSBind represents a host to container bind mount.
type FSBind struct {
	// mount point in container, same as src if empty
	Dst *container.Absolute `json:"dst,omitempty"`
	// host filesystem path to make available to the container
	Src *container.Absolute `json:"src"`
	// do not mount filesystem read-only
	Write bool `json:"write,omitempty"`
	// do not disable device files, implies Write
	Device bool `json:"dev,omitempty"`
	// skip this mount point if the host path does not exist
	Optional bool `json:"optional,omitempty"`
}

func (b *FSBind) Type() string { return FilesystemBind }

func (b *FSBind) Target() *container.Absolute {
	if b == nil || b.Src == nil {
		return nil
	}
	if b.Dst == nil {
		return b.Src
	}
	return b.Dst
}

func (b *FSBind) Host() []*container.Absolute {
	if b == nil || b.Src == nil {
		return nil
	}
	return []*container.Absolute{b.Src}
}

func (b *FSBind) Apply(ops *container.Ops) {
	if b == nil || b.Src == nil {
		return
	}

	dst := b.Dst
	if dst == nil {
		dst = b.Src
	}
	var flags int
	if b.Write {
		flags |= container.BindWritable
	}
	if b.Device {
		flags |= container.BindDevice | container.BindWritable
	}
	if b.Optional {
		flags |= container.BindOptional
	}
	ops.Bind(b.Src, dst, flags)
}

func (b *FSBind) String() string {
	g := 4
	if b == nil || b.Src == nil {
		return "<invalid>"
	}

	g += len(b.Src.String())
	if b.Dst != nil {
		g += len(b.Dst.String())
	}

	expr := new(strings.Builder)
	expr.Grow(g)

	if b.Device {
		expr.WriteString("d")
	} else if b.Write {
		expr.WriteString("w")
	}

	if !b.Optional {
		expr.WriteString("*")
	} else {
		expr.WriteString("+")
	}

	expr.WriteString(b.Src.String())
	if b.Dst != nil {
		expr.WriteString(":" + b.Dst.String())
	}

	return expr.String()
}