-
Notifications
You must be signed in to change notification settings - Fork 239
/
spec.go
310 lines (281 loc) · 8.32 KB
/
spec.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
// +build linux
package hcsv2
import (
"context"
"fmt"
"path/filepath"
"strconv"
"strings"
"github.com/Microsoft/hcsshim/internal/log"
"github.com/opencontainers/runc/libcontainer/devices"
"github.com/opencontainers/runc/libcontainer/user"
oci "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
)
// getNetworkNamespaceID returns the `ToLower` of
// `spec.Windows.Network.NetworkNamespace` or `""`.
func getNetworkNamespaceID(spec *oci.Spec) string {
if spec.Windows != nil &&
spec.Windows.Network != nil {
return strings.ToLower(spec.Windows.Network.NetworkNamespace)
}
return ""
}
// isRootReadonly returns `true` if the spec specifies the rootfs is readonly.
func isRootReadonly(spec *oci.Spec) bool {
if spec.Root != nil {
return spec.Root.Readonly
}
return false
}
// isInMounts returns `true` if `target` matches a `Destination` in any of
// `mounts`.
func isInMounts(target string, mounts []oci.Mount) bool {
for _, m := range mounts {
if m.Destination == target {
return true
}
}
return false
}
// removeMount removes mount from the array if `target` matches `Destination`
func removeMount(target string, mounts []oci.Mount) []oci.Mount {
var result []oci.Mount
for _, m := range mounts {
if m.Destination == target {
continue
}
result = append(result, m)
}
return result
}
func setProcess(spec *oci.Spec) {
if spec.Process == nil {
spec.Process = &oci.Process{}
}
}
func setCoreRLimit(spec *oci.Spec, value string) error {
setProcess(spec)
vals := strings.Split(value, ";")
if len(vals) != 2 {
return errors.New("wrong number of values supplied for rlimit core")
}
soft, err := strconv.ParseUint(vals[0], 10, 64)
if err != nil {
return errors.Wrap(err, "failed to parse soft core rlimit")
}
hard, err := strconv.ParseUint(vals[1], 10, 64)
if err != nil {
return errors.Wrap(err, "failed to parse hard core rlimit")
}
spec.Process.Rlimits = append(spec.Process.Rlimits, oci.POSIXRlimit{
Type: "RLIMIT_CORE",
Soft: soft,
Hard: hard,
})
return nil
}
// setUserStr sets `spec.Process` to the valid `userstr` based on the OCI Image Spec
// v1.0.0 `userstr`.
//
// Valid values are: user, uid, user:group, uid:gid, uid:group, user:gid.
// If uid is provided instead of the username then that value is not checked against the
// /etc/passwd file to verify if the user with given uid actually exists.
func setUserStr(spec *oci.Spec, userstr string) error {
setProcess(spec)
parts := strings.Split(userstr, ":")
switch len(parts) {
case 1:
v, err := strconv.Atoi(parts[0])
if err != nil {
// evaluate username to uid/gid
return setUsername(spec, userstr)
}
return setUserID(spec, int(v))
case 2:
var (
username, groupname string
uid, gid int
)
v, err := strconv.Atoi(parts[0])
if err != nil {
username = parts[0]
} else {
uid = int(v)
}
v, err = strconv.Atoi(parts[1])
if err != nil {
groupname = parts[1]
} else {
gid = int(v)
}
if username != "" {
u, err := getUser(spec, func(u user.User) bool {
return u.Name == username
})
if err != nil {
return errors.Wrapf(err, "failed to find user by username: %s", username)
}
uid = u.Uid
}
if groupname != "" {
g, err := getGroup(spec, func(g user.Group) bool {
return g.Name == groupname
})
if err != nil {
return errors.Wrapf(err, "failed to find group by groupname: %s", groupname)
}
gid = g.Gid
}
spec.Process.User.UID, spec.Process.User.GID = uint32(uid), uint32(gid)
return nil
default:
return fmt.Errorf("invalid userstr: '%s'", userstr)
}
}
func setUsername(spec *oci.Spec, username string) error {
u, err := getUser(spec, func(u user.User) bool {
return u.Name == username
})
if err != nil {
return errors.Wrapf(err, "failed to find user by username: %s", username)
}
spec.Process.User.UID, spec.Process.User.GID = uint32(u.Uid), uint32(u.Gid)
return nil
}
func setUserID(spec *oci.Spec, uid int) error {
u, err := getUser(spec, func(u user.User) bool {
return u.Uid == uid
})
if err != nil {
spec.Process.User.UID, spec.Process.User.GID = uint32(uid), 0
return nil
}
spec.Process.User.UID, spec.Process.User.GID = uint32(u.Uid), uint32(u.Gid)
return nil
}
func getUser(spec *oci.Spec, filter func(user.User) bool) (user.User, error) {
users, err := user.ParsePasswdFileFilter(filepath.Join(spec.Root.Path, "/etc/passwd"), filter)
if err != nil {
return user.User{}, err
}
if len(users) != 1 {
return user.User{}, errors.Errorf("expected exactly 1 user matched '%d'", len(users))
}
return users[0], nil
}
func getGroup(spec *oci.Spec, filter func(user.Group) bool) (user.Group, error) {
groups, err := user.ParseGroupFileFilter(filepath.Join(spec.Root.Path, "/etc/group"), filter)
if err != nil {
return user.Group{}, err
}
if len(groups) != 1 {
return user.Group{}, errors.Errorf("expected exactly 1 group matched '%d'", len(groups))
}
return groups[0], nil
}
// applyAnnotationsToSpec modifies the spec based on additional information from annotations
func applyAnnotationsToSpec(ctx context.Context, spec *oci.Spec) error {
// Check if we need to override container's /dev/shm
if val, ok := spec.Annotations["io.microsoft.container.storage.shm.size-kb"]; ok {
sz, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return errors.Wrap(err, "/dev/shm size must be a valid integer")
}
if sz <= 0 {
return errors.Errorf("/dev/shm size must be a positive integer, got: %d", sz)
}
// Use the same options as in upstream https://github.com/containerd/containerd/blob/0def98e462706286e6eaeff4a90be22fda75e761/oci/mounts.go#L49
size := fmt.Sprintf("size=%dk", sz)
mt := oci.Mount{
Destination: "/dev/shm",
Type: "tmpfs",
Source: "shm",
Options: []string{"nosuid", "noexec", "nodev", "mode=1777", size},
}
spec.Mounts = removeMount("/dev/shm", spec.Mounts)
spec.Mounts = append(spec.Mounts, mt)
log.G(ctx).WithField("size", size).Debug("set custom /dev/shm size")
}
// Check if we need to do any capability/device mappings
if spec.Annotations["io.microsoft.virtualmachine.lcow.privileged"] == "true" {
log.G(ctx).Debug("'io.microsoft.virtualmachine.lcow.privileged' set for privileged container")
// Add all host devices
hostDevices, err := devices.HostDevices()
if err != nil {
return err
}
for _, hostDevice := range hostDevices {
addLinuxDeviceToSpec(ctx, hostDevice, spec, false)
}
// Set the cgroup access
spec.Linux.Resources.Devices = []oci.LinuxDeviceCgroup{
{
Allow: true,
Access: "rwm",
},
}
} else {
tempLinuxDevices := spec.Linux.Devices
spec.Linux.Devices = []oci.LinuxDevice{}
for _, ld := range tempLinuxDevices {
hostDevice, err := devices.DeviceFromPath(ld.Path, "rwm")
if err != nil {
return err
}
addLinuxDeviceToSpec(ctx, hostDevice, spec, true)
}
}
return nil
}
// Helper function to create an oci prestart hook to run ldconfig
func addLDConfigHook(ctx context.Context, spec *oci.Spec, args, env []string) error {
if spec.Hooks == nil {
spec.Hooks = &oci.Hooks{}
}
ldConfigHook := oci.Hook{
Path: "/sbin/ldconfig",
Args: args,
Env: env,
}
spec.Hooks.Prestart = append(spec.Hooks.Prestart, ldConfigHook)
return nil
}
func addLinuxDeviceToSpec(ctx context.Context, hostDevice *devices.Device, spec *oci.Spec, addCgroupDevice bool) {
rd := oci.LinuxDevice{
Path: hostDevice.Path,
Type: string(hostDevice.Type),
Major: hostDevice.Major,
Minor: hostDevice.Minor,
UID: &hostDevice.Uid,
GID: &hostDevice.Gid,
}
if hostDevice.Major == 0 && hostDevice.Minor == 0 {
// Invalid device, most likely a symbolic link, skip it.
return
}
found := false
for i, dev := range spec.Linux.Devices {
if dev.Path == rd.Path {
found = true
spec.Linux.Devices[i] = rd
break
}
if dev.Type == rd.Type && dev.Major == rd.Major && dev.Minor == rd.Minor {
log.G(ctx).Warnf("The same type '%s', major '%d' and minor '%d', should not be used for multiple devices.", dev.Type, dev.Major, dev.Minor)
}
}
if !found {
spec.Linux.Devices = append(spec.Linux.Devices, rd)
if addCgroupDevice {
deviceCgroup := oci.LinuxDeviceCgroup{
Allow: true,
Type: string(hostDevice.Type),
Major: &hostDevice.Major,
Minor: &hostDevice.Minor,
Access: string(hostDevice.Permissions),
}
spec.Linux.Resources.Devices = append(spec.Linux.Resources.Devices, deviceCgroup)
}
}
}