Debian Codegraph @

fs/fs.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 /*
18 Copyright 2019 The Go Authors. All rights reserved.
19 Use of this source code is governed by a BSD-style
20 license that can be found in the NOTICE.md file.
21 */
22
23 //
24 // Example implementation of FileSystem.
25 //
26 // This implementation uses stargz by CRFS(https://github.com/google/crfs) as
27 // image format, which has following feature:
28 // - We can use docker registry as a backend store (means w/o additional layer
29 // stores).
30 // - The stargz-formatted image is still docker-compatible (means normal
31 // runtimes can still use the formatted image).
32 //
33 // Currently, we reimplemented CRFS-like filesystem for ease of integration.
34 // But in the near future, we intend to integrate it with CRFS.
35 //
36
37 package fs
38
39 import (
40 "context"
41 "fmt"
42 "os/exec"
43 "strconv"
44 "sync"
45 "time"
46
47 "github.com/containerd/containerd/log"
48 "github.com/containerd/containerd/reference"
49 "github.com/containerd/containerd/remotes/docker"
50 "github.com/containerd/stargz-snapshotter/estargz"
51 "github.com/containerd/stargz-snapshotter/fs/config"
52 "github.com/containerd/stargz-snapshotter/fs/layer"
53 commonmetrics "github.com/containerd/stargz-snapshotter/fs/metrics/common"
54 layermetrics "github.com/containerd/stargz-snapshotter/fs/metrics/layer"
55 "github.com/containerd/stargz-snapshotter/fs/remote"
56 "github.com/containerd/stargz-snapshotter/fs/source"
57 "github.com/containerd/stargz-snapshotter/metadata"
58 memorymetadata "github.com/containerd/stargz-snapshotter/metadata/memory"
59 "github.com/containerd/stargz-snapshotter/snapshot"
60 "github.com/containerd/stargz-snapshotter/task"
61 metrics "github.com/docker/go-metrics"
62 fusefs "github.com/hanwen/go-fuse/v2/fs"
63 "github.com/hanwen/go-fuse/v2/fuse"
64 digest "github.com/opencontainers/go-digest"
65 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
66 "github.com/sirupsen/logrus"
67 "golang.org/x/sys/unix"
68 )
69
70 const (
71 defaultFuseTimeout = time.Second
72 defaultMaxConcurrency = 2
73 )
74
75 var fusermountBin = []string{"fusermount", "fusermount3"}
76
77 type Option func(*options)
78
79 type options struct {
80 getSources source.GetSources
81 resolveHandlers map[string]remote.Handler
82 metadataStore metadata.Store
83 metricsLogLevel *logrus.Level
84 overlayOpaqueType layer.OverlayOpaqueType
85 additionalDecompressors func(context.Context, source.RegistryHosts, reference.Spec, ocispec.Descriptor) []metadata.Decompressor
86 }
87
88 func WithGetSources(s source.GetSources) Option {
89 return func(opts *options) {
90 opts.getSources = s
91 }
92 }
93
94 func WithResolveHandler(name string, handler remote.Handler) Option {
95 return func(opts *options) {
96 if opts.resolveHandlers == nil {
97 opts.resolveHandlers = make(map[string]remote.Handler)
98 }
99 opts.resolveHandlers[name] = handler
100 }
101 }
102
103 func WithMetadataStore(metadataStore metadata.Store) Option {
104 return func(opts *options) {
105 opts.metadataStore = metadataStore
106 }
107 }
108
109 func WithMetricsLogLevel(logLevel logrus.Level) Option {
110 return func(opts *options) {
111 opts.metricsLogLevel = &logLevel
112 }
113 }
114
115 func WithOverlayOpaqueType(overlayOpaqueType layer.OverlayOpaqueType) Option {
116 return func(opts *options) {
117 opts.overlayOpaqueType = overlayOpaqueType
118 }
119 }
120
121 func WithAdditionalDecompressors(d func(context.Context, source.RegistryHosts, reference.Spec, ocispec.Descriptor) []metadata.Decompressor) Option {
122 return func(opts *options) {
123 opts.additionalDecompressors = d
124 }
125 }
126
127 func NewFilesystem(root string, cfg config.Config, opts ...Option) (_ snapshot.FileSystem, err error) {
128 var fsOpts options
129 for _, o := range opts {
130 o(&fsOpts)
131 }
132 maxConcurrency := cfg.MaxConcurrency
133 if maxConcurrency == 0 {
134 maxConcurrency = defaultMaxConcurrency
135 }
136
137 attrTimeout := time.Duration(cfg.FuseConfig.AttrTimeout) * time.Second
138 if attrTimeout == 0 {
139 attrTimeout = defaultFuseTimeout
140 }
141
142 entryTimeout := time.Duration(cfg.FuseConfig.EntryTimeout) * time.Second
143 if entryTimeout == 0 {
144 entryTimeout = defaultFuseTimeout
145 }
146
147 metadataStore := fsOpts.metadataStore
148 if metadataStore == nil {
149 metadataStore = memorymetadata.NewReader
150 }
151
152 getSources := fsOpts.getSources
153 if getSources == nil {
154 getSources = source.FromDefaultLabels(func(refspec reference.Spec) (hosts []docker.RegistryHost, _ error) {
155 return docker.ConfigureDefaultRegistries(docker.WithPlainHTTP(docker.MatchLocalhost))(refspec.Hostname())
156 })
157 }
158 tm := task.NewBackgroundTaskManager(maxConcurrency, 5*time.Second)
159 r, err := layer.NewResolver(root, tm, cfg, fsOpts.resolveHandlers, metadataStore, fsOpts.overlayOpaqueType, fsOpts.additionalDecompressors)
160 if err != nil {
161 return nil, fmt.Errorf("failed to setup resolver: %w", err)
162 }
163
164 var ns *metrics.Namespace
165 if !cfg.NoPrometheus {
166 ns = metrics.NewNamespace("stargz", "fs", nil)
167 logLevel := logrus.DebugLevel
168 if fsOpts.metricsLogLevel != nil {
169 logLevel = *fsOpts.metricsLogLevel
170 }
171 commonmetrics.Register(logLevel) // Register common metrics. This will happen only once.
172 }
173 c := layermetrics.NewLayerMetrics(ns)
174 if ns != nil {
175 metrics.Register(ns) // Register layer metrics.
176 }
177
178 return &filesystem{
179 resolver: r,
180 getSources: getSources,
181 prefetchSize: cfg.PrefetchSize,
182 noprefetch: cfg.NoPrefetch,
183 noBackgroundFetch: cfg.NoBackgroundFetch,
184 debug: cfg.Debug,
185 layer: make(map[string]layer.Layer),
186 backgroundTaskManager: tm,
187 allowNoVerification: cfg.AllowNoVerification,
188 disableVerification: cfg.DisableVerification,
189 metricsController: c,
190 attrTimeout: attrTimeout,
191 entryTimeout: entryTimeout,
192 }, nil
193 }
194
195 type filesystem struct {
196 resolver *layer.Resolver
197 prefetchSize int64
198 noprefetch bool
199 noBackgroundFetch bool
200 debug bool
201 layer map[string]layer.Layer
202 layerMu sync.Mutex
203 backgroundTaskManager *task.BackgroundTaskManager
204 allowNoVerification bool
205 disableVerification bool
206 getSources source.GetSources
207 metricsController *layermetrics.Controller
208 attrTimeout time.Duration
209 entryTimeout time.Duration
210 }
211
212 func (fs *filesystem) Mount(ctx context.Context, mountpoint string, labels map[string]string) (retErr error) {
213 // Setting the start time to measure the Mount operation duration.
214 start := time.Now()
215
216 // This is a prioritized task and all background tasks will be stopped
217 // execution so this can avoid being disturbed for NW traffic by background
218 // tasks.
219 fs.backgroundTaskManager.DoPrioritizedTask()
220 defer fs.backgroundTaskManager.DonePrioritizedTask()
221 ctx = log.WithLogger(ctx, log.G(ctx).WithField("mountpoint", mountpoint))
222
223 // Get source information of this layer.
224 src, err := fs.getSources(labels)
225 if err != nil {
226 return err
227 } else if len(src) == 0 {
228 return fmt.Errorf("source must be passed")
229 }
230
231 defaultPrefetchSize := fs.prefetchSize
232 if psStr, ok := labels[config.TargetPrefetchSizeLabel]; ok {
233 if ps, err := strconv.ParseInt(psStr, 10, 64); err == nil {
234 defaultPrefetchSize = ps
235 }
236 }
237
238 // Resolve the target layer
239 var (
240 resultChan = make(chan layer.Layer)
241 errChan = make(chan error)
242 )
243 go func() {
244 rErr := fmt.Errorf("failed to resolve target")
245 for _, s := range src {
246 l, err := fs.resolver.Resolve(ctx, s.Hosts, s.Name, s.Target)
247 if err == nil {
248 resultChan <- l
249 fs.prefetch(ctx, l, defaultPrefetchSize, start)
250 return
251 }
252 rErr = fmt.Errorf("failed to resolve layer %q from %q: %v: %w", s.Target.Digest, s.Name, err, rErr)
253 }
254 errChan <- rErr
255 }()
256
257 // Also resolve and cache other layers in parallel
258 preResolve := src[0] // TODO: should we pre-resolve blobs in other sources as well?
259 for _, desc := range neighboringLayers(preResolve.Manifest, preResolve.Target) {
260 desc := desc
261 go func() {
262 // Avoids to get canceled by client.
263 ctx := log.WithLogger(context.Background(), log.G(ctx).WithField("mountpoint", mountpoint))
264 l, err := fs.resolver.Resolve(ctx, preResolve.Hosts, preResolve.Name, desc)
265 if err != nil {
266 log.G(ctx).WithError(err).Debug("failed to pre-resolve")
267 return
268 }
269 fs.prefetch(ctx, l, defaultPrefetchSize, start)
270
271 // Release this layer because this isn't target and we don't use it anymore here.
272 // However, this will remain on the resolver cache until eviction.
273 l.Done()
274 }()
275 }
276
277 // Wait for resolving completion
278 var l layer.Layer
279 select {
280 case l = <-resultChan:
281 case err := <-errChan:
282 log.G(ctx).WithError(err).Debug("failed to resolve layer")
283 return fmt.Errorf("failed to resolve layer: %w", err)
284 case <-time.After(30 * time.Second):
285 log.G(ctx).Debug("failed to resolve layer (timeout)")
286 return fmt.Errorf("failed to resolve layer (timeout)")
287 }
288 defer func() {
289 if retErr != nil {
290 l.Done() // don't use this layer.
291 }
292 }()
293
294 // Verify layer's content
295 if fs.disableVerification {
296 // Skip if verification is disabled completely
297 l.SkipVerify()
298 log.G(ctx).Infof("Verification forcefully skipped")
299 } else if tocDigest, ok := labels[estargz.TOCJSONDigestAnnotation]; ok {
300 // Verify this layer using the TOC JSON digest passed through label.
301 dgst, err := digest.Parse(tocDigest)
302 if err != nil {
303 log.G(ctx).WithError(err).Debugf("failed to parse passed TOC digest %q", dgst)
304 return fmt.Errorf("invalid TOC digest: %v: %w", tocDigest, err)
305 }
306 if err := l.Verify(dgst); err != nil {
307 log.G(ctx).WithError(err).Debugf("invalid layer")
308 return fmt.Errorf("invalid stargz layer: %w", err)
309 }
310 log.G(ctx).Debugf("verified")
311 } else if _, ok := labels[config.TargetSkipVerifyLabel]; ok && fs.allowNoVerification {
312 // If unverified layer is allowed, use it with warning.
313 // This mode is for legacy stargz archives which don't contain digests
314 // necessary for layer verification.
315 l.SkipVerify()
316 log.G(ctx).Warningf("No verification is held for layer")
317 } else {
318 // Verification must be done. Don't mount this layer.
319 return fmt.Errorf("digest of TOC JSON must be passed")
320 }
321 node, err := l.RootNode(0)
322 if err != nil {
323 log.G(ctx).WithError(err).Warnf("Failed to get root node")
324 return fmt.Errorf("failed to get root node: %w", err)
325 }
326
327 // Measuring duration of Mount operation for resolved layer.
328 digest := l.Info().Digest // get layer sha
329 defer commonmetrics.MeasureLatencyInMilliseconds(commonmetrics.Mount, digest, start)
330
331 // Register the mountpoint layer
332 fs.layerMu.Lock()
333 fs.layer[mountpoint] = l
334 fs.layerMu.Unlock()
335 fs.metricsController.Add(mountpoint, l)
336
337 // mount the node to the specified mountpoint
338 // TODO: bind mount the state directory as a read-only fs on snapshotter's side
339 rawFS := fusefs.NewNodeFS(node, &fusefs.Options{
340 AttrTimeout: &fs.attrTimeout,
341 EntryTimeout: &fs.entryTimeout,
342 NullPermissions: true,
343 })
344 mountOpts := &fuse.MountOptions{
345 AllowOther: true, // allow users other than root&mounter to access fs
346 FsName: "stargz", // name this filesystem as "stargz"
347 Debug: fs.debug,
348 }
349 if isFusermountBinExist() {
350 log.G(ctx).Infof("fusermount detected")
351 mountOpts.Options = []string{"suid"} // option for fusermount; allow setuid inside container
352 } else {
353 log.G(ctx).WithError(err).Infof("%s not installed; trying direct mount", fusermountBin)
354 mountOpts.DirectMount = true
355 }
356 server, err := fuse.NewServer(rawFS, mountpoint, mountOpts)
357 if err != nil {
358 log.G(ctx).WithError(err).Debug("failed to make filesystem server")
359 return err
360 }
361
362 go server.Serve()
363 return server.WaitMount()
364 }
365
366 func (fs *filesystem) Check(ctx context.Context, mountpoint string, labels map[string]string) error {
367 // This is a prioritized task and all background tasks will be stopped
368 // execution so this can avoid being disturbed for NW traffic by background
369 // tasks.
370 fs.backgroundTaskManager.DoPrioritizedTask()
371 defer fs.backgroundTaskManager.DonePrioritizedTask()
372
373 defer commonmetrics.MeasureLatencyInMilliseconds(commonmetrics.PrefetchesCompleted, digest.FromString(""), time.Now()) // measuring the time the container launch is blocked on prefetch to complete
374
375 ctx = log.WithLogger(ctx, log.G(ctx).WithField("mountpoint", mountpoint))
376
377 fs.layerMu.Lock()
378 l := fs.layer[mountpoint]
379 fs.layerMu.Unlock()
380 if l == nil {
381 log.G(ctx).Debug("layer not registered")
382 return fmt.Errorf("layer not registered")
383 }
384
385 // Check the blob connectivity and try to refresh the connection on failure
386 if err := fs.check(ctx, l, labels); err != nil {
387 log.G(ctx).WithError(err).Warn("check failed")
388 return err
389 }
390
391 // Wait for prefetch compeletion
392 if !fs.noprefetch {
393 if err := l.WaitForPrefetchCompletion(); err != nil {
394 log.G(ctx).WithError(err).Warn("failed to sync with prefetch completion")
395 }
396 }
397
398 return nil
399 }
400
401 func (fs *filesystem) check(ctx context.Context, l layer.Layer, labels map[string]string) error {
402 err := l.Check()
403 if err == nil {
404 return nil
405 }
406 log.G(ctx).WithError(err).Warn("failed to connect to blob")
407
408 // Check failed. Try to refresh the connection with fresh source information
409 src, err := fs.getSources(labels)
410 if err != nil {
411 return err
412 }
413 var (
414 retrynum = 1
415 rErr = fmt.Errorf("failed to refresh connection")
416 )
417 for retry := 0; retry < retrynum; retry++ {
418 log.G(ctx).Warnf("refreshing(%d)...", retry)
419 for _, s := range src {
420 err := l.Refresh(ctx, s.Hosts, s.Name, s.Target)
421 if err == nil {
422 log.G(ctx).Debug("Successfully refreshed connection")
423 return nil
424 }
425 log.G(ctx).WithError(err).Warnf("failed to refresh the layer %q from %q", s.Target.Digest, s.Name)
426 rErr = fmt.Errorf("failed(layer:%q, ref:%q): %v: %w", s.Target.Digest, s.Name, err, rErr)
427 }
428 }
429
430 return rErr
431 }
432
433 func (fs *filesystem) Unmount(ctx context.Context, mountpoint string) error {
434 if mountpoint == "" {
435 return fmt.Errorf("mount point must be specified")
436 }
437 fs.layerMu.Lock()
438 l, ok := fs.layer[mountpoint]
439 if !ok {
440 fs.layerMu.Unlock()
441 return fmt.Errorf("specified path %q isn't a mountpoint", mountpoint)
442 }
443 delete(fs.layer, mountpoint) // unregisters the corresponding layer
444 l.Done()
445 fs.layerMu.Unlock()
446 fs.metricsController.Remove(mountpoint)
447
448 if err := unmount(mountpoint, 0); err != nil {
449 if err != unix.EBUSY {
450 return err
451 }
452 // Try force unmount
453 log.G(ctx).WithError(err).Debugf("trying force unmount %q", mountpoint)
454 if err := unmount(mountpoint, unix.MNT_FORCE); err != nil {
455 return err
456 }
457 }
458
459 return nil
460 }
461
462 func unmount(target string, flags int) error {
463 for {
464 if err := unix.Unmount(target, flags); err != unix.EINTR {
465 return err
466 }
467 }
468 }
469
470 func (fs *filesystem) prefetch(ctx context.Context, l layer.Layer, defaultPrefetchSize int64, start time.Time) {
471 // Prefetch a layer. The first Check() for this layer waits for the prefetch completion.
472 if !fs.noprefetch {
473 go l.Prefetch(defaultPrefetchSize)
474 }
475
476 // Fetch whole layer aggressively in background.
477 if !fs.noBackgroundFetch {
478 go func() {
479 if err := l.BackgroundFetch(); err == nil {
480 // write log record for the latency between mount start and last on demand fetch
481 commonmetrics.LogLatencyForLastOnDemandFetch(ctx, l.Info().Digest, start, l.Info().ReadTime)
482 }
483 }()
484 }
485 }
486
487 // neighboringLayers returns layer descriptors except the `target` layer in the specified manifest.
488 func neighboringLayers(manifest ocispec.Manifest, target ocispec.Descriptor) (descs []ocispec.Descriptor) {
489 for _, desc := range manifest.Layers {
490 if desc.Digest.String() != target.Digest.String() {
491 descs = append(descs, desc)
492 }
493 }
494 return
495 }
496
497 func isFusermountBinExist() bool {
498 for _, b := range fusermountBin {
499 if _, err := exec.LookPath(b); err == nil {
500 return true
501 }
502 }
503 return false
504 }