-
Notifications
You must be signed in to change notification settings - Fork 647
/
Copy pathrun_mount.go
362 lines (320 loc) · 11 KB
/
run_mount.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
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
/*
Copyright The containerd 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 container
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
"github.com/containerd/containerd"
"github.com/containerd/containerd/containers"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/leases"
"github.com/containerd/containerd/mount"
"github.com/containerd/containerd/oci"
"github.com/containerd/containerd/pkg/userns"
"github.com/containerd/continuity/fs"
"github.com/containerd/log"
"github.com/containerd/nerdctl/v2/pkg/api/types"
"github.com/containerd/nerdctl/v2/pkg/idgen"
"github.com/containerd/nerdctl/v2/pkg/imgutil"
"github.com/containerd/nerdctl/v2/pkg/inspecttypes/dockercompat"
"github.com/containerd/nerdctl/v2/pkg/labels"
"github.com/containerd/nerdctl/v2/pkg/mountutil"
"github.com/containerd/nerdctl/v2/pkg/mountutil/volumestore"
"github.com/containerd/nerdctl/v2/pkg/strutil"
securejoin "github.com/cyphar/filepath-securejoin"
"github.com/opencontainers/image-spec/identity"
"github.com/opencontainers/runtime-spec/specs-go"
)
// copy from https://github.com/containerd/containerd/blob/v1.6.0-rc.1/pkg/cri/opts/spec_linux.go#L129-L151
func withMounts(mounts []specs.Mount) oci.SpecOpts {
return func(ctx context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {
// Copy all mounts from default mounts, except for
// - mounts overridden by supplied mount;
// - all mounts under /dev if a supplied /dev is present.
mountSet := make(map[string]struct{})
for _, m := range mounts {
mountSet[filepath.Clean(m.Destination)] = struct{}{}
}
defaultMounts := s.Mounts
s.Mounts = nil
for _, m := range defaultMounts {
dst := filepath.Clean(m.Destination)
if _, ok := mountSet[dst]; ok {
// filter out mount overridden by a supplied mount
continue
}
if _, mountDev := mountSet["/dev"]; mountDev && strings.HasPrefix(dst, "/dev/") {
// filter out everything under /dev if /dev is a supplied mount
continue
}
s.Mounts = append(s.Mounts, m)
}
s.Mounts = append(s.Mounts, mounts...)
sort.Slice(s.Mounts, func(i, j int) bool {
// Consistent with the less function in Docker.
// https://github.com/moby/moby/blob/0db417451313474133c5ed62bbf95e2d3c92444d/daemon/volumes.go#L34
return strings.Count(filepath.Clean(s.Mounts[i].Destination), string(os.PathSeparator)) < strings.Count(filepath.Clean(s.Mounts[j].Destination), string(os.PathSeparator))
})
return nil
}
}
// parseMountFlags parses --volume, --mount and --tmpfs.
func parseMountFlags(volStore volumestore.VolumeStore, options types.ContainerCreateOptions) ([]*mountutil.Processed, error) {
var parsed []*mountutil.Processed //nolint:prealloc
for _, v := range strutil.DedupeStrSlice(options.Volume) {
// createDir=true for -v option to allow creation of directory on host if not found.
x, err := mountutil.ProcessFlagV(v, volStore, true)
if err != nil {
return nil, err
}
parsed = append(parsed, x)
}
for _, v := range strutil.DedupeStrSlice(options.Tmpfs) {
x, err := mountutil.ProcessFlagTmpfs(v)
if err != nil {
return nil, err
}
parsed = append(parsed, x)
}
for _, v := range strutil.DedupeStrSlice(options.Mount) {
x, err := mountutil.ProcessFlagMount(v, volStore)
if err != nil {
return nil, err
}
parsed = append(parsed, x)
}
return parsed, nil
}
// generateMountOpts generates volume-related mount opts.
// Other mounts such as procfs mount are not handled here.
func generateMountOpts(ctx context.Context, client *containerd.Client, ensuredImage *imgutil.EnsuredImage,
volStore volumestore.VolumeStore, options types.ContainerCreateOptions) ([]oci.SpecOpts, []string, []*mountutil.Processed, error) {
//nolint:golint,prealloc
var (
opts []oci.SpecOpts
anonVolumes []string
userMounts []specs.Mount
mountPoints []*mountutil.Processed
)
mounted := make(map[string]struct{})
var imageVolumes map[string]struct{}
var tempDir string
if ensuredImage != nil {
imageVolumes = ensuredImage.ImageConfig.Volumes
if err := ensuredImage.Image.Unpack(ctx, options.GOptions.Snapshotter); err != nil {
return nil, nil, nil, fmt.Errorf("error unpacking image: %w", err)
}
diffIDs, err := ensuredImage.Image.RootFS(ctx)
if err != nil {
return nil, nil, nil, err
}
chainID := identity.ChainID(diffIDs).String()
s := client.SnapshotService(options.GOptions.Snapshotter)
tempDir, err = os.MkdirTemp("", "initialC")
if err != nil {
return nil, nil, nil, err
}
// We use Remove here instead of RemoveAll.
// The RemoveAll will delete the temp dir and all children it contains.
// When the Unmount fails, RemoveAll will incorrectly delete data from the mounted dir
defer os.Remove(tempDir)
// Add a lease of 1 hour to the view so that it is not garbage collected
// Note(gsamfira): should we make this shorter?
ctx, done, err := client.WithLease(ctx, leases.WithRandomID(), leases.WithExpiration(1*time.Hour))
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to create lease: %w", err)
}
defer done(ctx)
var mounts []mount.Mount
mounts, err = s.View(ctx, tempDir, chainID)
if err != nil {
return nil, nil, nil, err
}
// windows has additional steps for mounting see
// https://github.com/containerd/containerd/commit/791e175c79930a34cfbb2048fbcaa8493fd2c86b
unmounter := func(mountPath string) {
if uerr := mount.Unmount(mountPath, 0); uerr != nil {
log.G(ctx).Debugf("Failed to unmount snapshot %q", tempDir)
if err == nil {
err = uerr
}
}
}
if runtime.GOOS == "linux" {
defer unmounter(tempDir)
for _, m := range mounts {
m := m
if m.Type == "bind" && userns.RunningInUserNS() {
// For https://github.com/containerd/nerdctl/issues/2056
unpriv, err := mountutil.UnprivilegedMountFlags(m.Source)
if err != nil {
return nil, nil, nil, err
}
m.Options = strutil.DedupeStrSlice(append(m.Options, unpriv...))
}
if err := m.Mount(tempDir); err != nil {
if rmErr := s.Remove(ctx, tempDir); rmErr != nil && !errdefs.IsNotFound(rmErr) {
return nil, nil, nil, rmErr
}
return nil, nil, nil, fmt.Errorf("failed to mount %+v on %q: %w", m, tempDir, err)
}
}
} else {
defer unmounter(tempDir)
if err := mount.All(mounts, tempDir); err != nil {
if err := s.Remove(ctx, tempDir); err != nil && !errdefs.IsNotFound(err) {
return nil, nil, nil, err
}
return nil, nil, nil, err
}
}
}
if parsed, err := parseMountFlags(volStore, options); err != nil {
return nil, nil, nil, err
} else if len(parsed) > 0 {
ociMounts := make([]specs.Mount, len(parsed))
for i, x := range parsed {
ociMounts[i] = x.Mount
mounted[filepath.Clean(x.Mount.Destination)] = struct{}{}
target, err := securejoin.SecureJoin(tempDir, x.Mount.Destination)
if err != nil {
return nil, nil, nil, err
}
// Copying content in AnonymousVolume and namedVolume
if x.Type == "volume" {
if err := copyExistingContents(target, x.Mount.Source); err != nil {
return nil, nil, nil, err
}
}
if x.AnonymousVolume != "" {
anonVolumes = append(anonVolumes, x.AnonymousVolume)
}
opts = append(opts, x.Opts...)
}
userMounts = append(userMounts, ociMounts...)
// add parsed user specified bind-mounts/volume/tmpfs to mountPoints
mountPoints = append(mountPoints, parsed...)
}
// imageVolumes are defined in Dockerfile "VOLUME" instruction
for imgVolRaw := range imageVolumes {
imgVol := filepath.Clean(imgVolRaw)
switch imgVol {
case "/", "/dev", "/sys", "proc":
return nil, nil, nil, fmt.Errorf("invalid VOLUME: %q", imgVolRaw)
}
if _, ok := mounted[imgVol]; ok {
continue
}
anonVolName := idgen.GenerateID()
log.G(ctx).Debugf("creating anonymous volume %q, for \"VOLUME %s\"",
anonVolName, imgVolRaw)
anonVol, err := volStore.Create(anonVolName, []string{})
if err != nil {
return nil, nil, nil, err
}
target, err := securejoin.SecureJoin(tempDir, imgVol)
if err != nil {
return nil, nil, nil, err
}
//copying up initial contents of the mount point directory
if err := copyExistingContents(target, anonVol.Mountpoint); err != nil {
return nil, nil, nil, err
}
m := specs.Mount{
Type: "none",
Source: anonVol.Mountpoint,
Destination: imgVol,
Options: []string{"rbind"},
}
userMounts = append(userMounts, m)
anonVolumes = append(anonVolumes, anonVolName)
mountPoint := &mountutil.Processed{
Type: "volume",
AnonymousVolume: anonVolName,
Mount: m,
}
mountPoints = append(mountPoints, mountPoint)
}
opts = append(opts, withMounts(userMounts))
containers, err := client.Containers(ctx)
if err != nil {
return nil, nil, nil, err
}
vfSet := strutil.SliceToSet(options.VolumesFrom)
var vfMountPoints []dockercompat.MountPoint
var vfAnonVolumes []string
for _, c := range containers {
ls, err := c.Labels(ctx)
if err != nil {
// Containerd note: there is no guarantee that the containers we got from the list still exist at this point
// If that is the case, just ignore and move on
if errors.Is(err, errdefs.ErrNotFound) {
log.G(ctx).Debugf("container %q is gone - ignoring", c.ID())
continue
}
return nil, nil, nil, err
}
_, idMatch := vfSet[c.ID()]
nameMatch := false
if name, found := ls[labels.Name]; found {
_, nameMatch = vfSet[name]
}
if idMatch || nameMatch {
if av, found := ls[labels.AnonymousVolumes]; found {
err = json.Unmarshal([]byte(av), &vfAnonVolumes)
if err != nil {
return nil, nil, nil, err
}
}
if m, found := ls[labels.Mounts]; found {
err = json.Unmarshal([]byte(m), &vfMountPoints)
if err != nil {
return nil, nil, nil, err
}
}
ps := processeds(vfMountPoints)
s, err := c.Spec(ctx)
if err != nil {
return nil, nil, nil, err
}
opts = append(opts, withMounts(s.Mounts))
anonVolumes = append(anonVolumes, vfAnonVolumes...)
mountPoints = append(mountPoints, ps...)
}
}
return opts, anonVolumes, mountPoints, nil
}
// copyExistingContents copies from the source to the destination and
// ensures the ownership is appropriately set.
func copyExistingContents(source, destination string) error {
if _, err := os.Stat(source); os.IsNotExist(err) {
return nil
}
dstList, err := os.ReadDir(destination)
if err != nil {
return err
}
if len(dstList) != 0 {
log.L.Debugf("volume at %q is not initially empty, skipping copying", destination)
return nil
}
return fs.CopyDir(destination, source)
}