| 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 |
package layer |
| 24 |
|
| 25 |
import ( |
| 26 |
"bytes" |
| 27 |
"context" |
| 28 |
"fmt" |
| 29 |
"io" |
| 30 |
"os" |
| 31 |
"path/filepath" |
| 32 |
"sync" |
| 33 |
"time" |
| 34 |
|
| 35 |
"github.com/containerd/containerd/log" |
| 36 |
"github.com/containerd/containerd/reference" |
| 37 |
"github.com/containerd/stargz-snapshotter/cache" |
| 38 |
"github.com/containerd/stargz-snapshotter/estargz" |
| 39 |
"github.com/containerd/stargz-snapshotter/estargz/zstdchunked" |
| 40 |
"github.com/containerd/stargz-snapshotter/fs/config" |
| 41 |
commonmetrics "github.com/containerd/stargz-snapshotter/fs/metrics/common" |
| 42 |
"github.com/containerd/stargz-snapshotter/fs/reader" |
| 43 |
"github.com/containerd/stargz-snapshotter/fs/remote" |
| 44 |
"github.com/containerd/stargz-snapshotter/fs/source" |
| 45 |
"github.com/containerd/stargz-snapshotter/metadata" |
| 46 |
"github.com/containerd/stargz-snapshotter/task" |
| 47 |
"github.com/containerd/stargz-snapshotter/util/cacheutil" |
| 48 |
"github.com/containerd/stargz-snapshotter/util/namedmutex" |
| 49 |
fusefs "github.com/hanwen/go-fuse/v2/fs" |
| 50 |
digest "github.com/opencontainers/go-digest" |
| 51 |
ocispec "github.com/opencontainers/image-spec/specs-go/v1" |
| 52 |
"github.com/sirupsen/logrus" |
| 53 |
) |
| 54 |
|
| 55 |
const ( |
| 56 |
defaultResolveResultEntryTTLSec = 120 |
| 57 |
defaultMaxLRUCacheEntry = 10 |
| 58 |
defaultMaxCacheFds = 10 |
| 59 |
defaultPrefetchTimeoutSec = 10 |
| 60 |
memoryCacheType = "memory" |
| 61 |
) |
| 62 |
|
| 63 |
// Layer represents a layer. |
| 64 |
type Layer interface { |
| 65 |
// Info returns the information of this layer. |
| 66 |
Info() Info |
| 67 |
|
| 68 |
// RootNode returns the root node of this layer. |
| 69 |
RootNode(baseInode uint32) (fusefs.InodeEmbedder, error) |
| 70 |
|
| 71 |
// Check checks if the layer is still connectable. |
| 72 |
Check() error |
| 73 |
|
| 74 |
// Refresh refreshes the layer connection. |
| 75 |
Refresh(ctx context.Context, hosts source.RegistryHosts, refspec reference.Spec, desc ocispec.Descriptor) error |
| 76 |
|
| 77 |
// Verify verifies this layer using the passed TOC Digest. |
| 78 |
// Nop if Verify() or SkipVerify() was already called. |
| 79 |
Verify(tocDigest digest.Digest) (err error) |
| 80 |
|
| 81 |
// SkipVerify skips verification for this layer. |
| 82 |
// Nop if Verify() or SkipVerify() was already called. |
| 83 |
SkipVerify() |
| 84 |
|
| 85 |
// Prefetch prefetches the specified size. If the layer is eStargz and contains landmark files, |
| 86 |
// the range indicated by these files is respected. |
| 87 |
Prefetch(prefetchSize int64) error |
| 88 |
|
| 89 |
// ReadAt reads this layer. |
| 90 |
ReadAt([]byte, int64, ...remote.Option) (int, error) |
| 91 |
|
| 92 |
// WaitForPrefetchCompletion waits untils Prefetch completes. |
| 93 |
WaitForPrefetchCompletion() error |
| 94 |
|
| 95 |
// BackgroundFetch fetches the entire layer contents to the cache. |
| 96 |
// Fetching contents is done as a background task. |
| 97 |
BackgroundFetch() error |
| 98 |
|
| 99 |
// Done releases the reference to this layer. The resources related to this layer will be |
| 100 |
// discarded sooner or later. Queries after calling this function won't be serviced. |
| 101 |
Done() |
| 102 |
} |
| 103 |
|
| 104 |
// Info is the current status of a layer. |
| 105 |
type Info struct { |
| 106 |
Digest digest.Digest |
| 107 |
Size int64 // layer size in bytes |
| 108 |
FetchedSize int64 // layer fetched size in bytes |
| 109 |
PrefetchSize int64 // layer prefetch size in bytes |
| 110 |
ReadTime time.Time // last time the layer was read |
| 111 |
} |
| 112 |
|
| 113 |
// Resolver resolves the layer location and provieds the handler of that layer. |
| 114 |
type Resolver struct { |
| 115 |
rootDir string |
| 116 |
resolver *remote.Resolver |
| 117 |
prefetchTimeout time.Duration |
| 118 |
layerCache *cacheutil.TTLCache |
| 119 |
layerCacheMu sync.Mutex |
| 120 |
blobCache *cacheutil.TTLCache |
| 121 |
blobCacheMu sync.Mutex |
| 122 |
backgroundTaskManager *task.BackgroundTaskManager |
| 123 |
resolveLock *namedmutex.NamedMutex |
| 124 |
config config.Config |
| 125 |
metadataStore metadata.Store |
| 126 |
overlayOpaqueType OverlayOpaqueType |
| 127 |
additionalDecompressors func(context.Context, source.RegistryHosts, reference.Spec, ocispec.Descriptor) []metadata.Decompressor |
| 128 |
} |
| 129 |
|
| 130 |
// NewResolver returns a new layer resolver. |
| 131 |
func NewResolver(root string, backgroundTaskManager *task.BackgroundTaskManager, cfg config.Config, resolveHandlers map[string]remote.Handler, metadataStore metadata.Store, overlayOpaqueType OverlayOpaqueType, additionalDecompressors func(context.Context, source.RegistryHosts, reference.Spec, ocispec.Descriptor) []metadata.Decompressor) (*Resolver, error) { |
| 132 |
resolveResultEntryTTL := time.Duration(cfg.ResolveResultEntryTTLSec) * time.Second |
| 133 |
if resolveResultEntryTTL == 0 { |
| 134 |
resolveResultEntryTTL = defaultResolveResultEntryTTLSec * time.Second |
| 135 |
} |
| 136 |
prefetchTimeout := time.Duration(cfg.PrefetchTimeoutSec) * time.Second |
| 137 |
if prefetchTimeout == 0 { |
| 138 |
prefetchTimeout = defaultPrefetchTimeoutSec * time.Second |
| 139 |
} |
| 140 |
|
| 141 |
// layerCache caches resolved layers for future use. This is useful in a use-case where |
| 142 |
// the filesystem resolves and caches all layers in an image (not only queried one) in parallel, |
| 143 |
// before they are actually queried. |
| 144 |
layerCache := cacheutil.NewTTLCache(resolveResultEntryTTL) |
| 145 |
layerCache.OnEvicted = func(key string, value interface{}) { |
| 146 |
if err := value.(*layer).close(); err != nil { |
| 147 |
logrus.WithField("key", key).WithError(err).Warnf("failed to clean up layer") |
| 148 |
return |
| 149 |
} |
| 150 |
logrus.WithField("key", key).Debugf("cleaned up layer") |
| 151 |
} |
| 152 |
|
| 153 |
// blobCache caches resolved blobs for futural use. This is especially useful when a layer |
| 154 |
// isn't eStargz/stargz (the *layer object won't be created/cached in this case). |
| 155 |
blobCache := cacheutil.NewTTLCache(resolveResultEntryTTL) |
| 156 |
blobCache.OnEvicted = func(key string, value interface{}) { |
| 157 |
if err := value.(remote.Blob).Close(); err != nil { |
| 158 |
logrus.WithField("key", key).WithError(err).Warnf("failed to clean up blob") |
| 159 |
return |
| 160 |
} |
| 161 |
logrus.WithField("key", key).Debugf("cleaned up blob") |
| 162 |
} |
| 163 |
|
| 164 |
if err := os.MkdirAll(root, 0700); err != nil { |
| 165 |
return nil, err |
| 166 |
} |
| 167 |
|
| 168 |
return &Resolver{ |
| 169 |
rootDir: root, |
| 170 |
resolver: remote.NewResolver(cfg.BlobConfig, resolveHandlers), |
| 171 |
layerCache: layerCache, |
| 172 |
blobCache: blobCache, |
| 173 |
prefetchTimeout: prefetchTimeout, |
| 174 |
backgroundTaskManager: backgroundTaskManager, |
| 175 |
config: cfg, |
| 176 |
resolveLock: new(namedmutex.NamedMutex), |
| 177 |
metadataStore: metadataStore, |
| 178 |
overlayOpaqueType: overlayOpaqueType, |
| 179 |
additionalDecompressors: additionalDecompressors, |
| 180 |
}, nil |
| 181 |
} |
| 182 |
|
| 183 |
func newCache(root string, cacheType string, cfg config.Config) (cache.BlobCache, error) { |
| 184 |
if cacheType == memoryCacheType { |
| 185 |
return cache.NewMemoryCache(), nil |
| 186 |
} |
| 187 |
|
| 188 |
dcc := cfg.DirectoryCacheConfig |
| 189 |
maxDataEntry := dcc.MaxLRUCacheEntry |
| 190 |
if maxDataEntry == 0 { |
| 191 |
maxDataEntry = defaultMaxLRUCacheEntry |
| 192 |
} |
| 193 |
maxFdEntry := dcc.MaxCacheFds |
| 194 |
if maxFdEntry == 0 { |
| 195 |
maxFdEntry = defaultMaxCacheFds |
| 196 |
} |
| 197 |
|
| 198 |
bufPool := &sync.Pool{ |
| 199 |
New: func() interface{} { |
| 200 |
return new(bytes.Buffer) |
| 201 |
}, |
| 202 |
} |
| 203 |
dCache, fCache := cacheutil.NewLRUCache(maxDataEntry), cacheutil.NewLRUCache(maxFdEntry) |
| 204 |
dCache.OnEvicted = func(key string, value interface{}) { |
| 205 |
value.(*bytes.Buffer).Reset() |
| 206 |
bufPool.Put(value) |
| 207 |
} |
| 208 |
fCache.OnEvicted = func(key string, value interface{}) { |
| 209 |
value.(*os.File).Close() |
| 210 |
} |
| 211 |
// create a cache on an unique directory |
| 212 |
if err := os.MkdirAll(root, 0700); err != nil { |
| 213 |
return nil, err |
| 214 |
} |
| 215 |
cachePath, err := os.MkdirTemp(root, "") |
| 216 |
if err != nil { |
| 217 |
return nil, fmt.Errorf("failed to initialize directory cache: %w", err) |
| 218 |
} |
| 219 |
return cache.NewDirectoryCache( |
| 220 |
cachePath, |
| 221 |
cache.DirectoryCacheConfig{ |
| 222 |
SyncAdd: dcc.SyncAdd, |
| 223 |
DataCache: dCache, |
| 224 |
FdCache: fCache, |
| 225 |
BufPool: bufPool, |
| 226 |
Direct: dcc.Direct, |
| 227 |
}, |
| 228 |
) |
| 229 |
} |
| 230 |
|
| 231 |
// Resolve resolves a layer based on the passed layer blob information. |
| 232 |
func (r *Resolver) Resolve(ctx context.Context, hosts source.RegistryHosts, refspec reference.Spec, desc ocispec.Descriptor, esgzOpts ...metadata.Option) (_ Layer, retErr error) { |
| 233 |
name := refspec.String() + "/" + desc.Digest.String() |
| 234 |
|
| 235 |
// Wait if resolving this layer is already running. The result |
| 236 |
// can hopefully get from the cache. |
| 237 |
r.resolveLock.Lock(name) |
| 238 |
defer r.resolveLock.Unlock(name) |
| 239 |
|
| 240 |
ctx = log.WithLogger(ctx, log.G(ctx).WithField("src", name)) |
| 241 |
|
| 242 |
// First, try to retrieve this layer from the underlying cache. |
| 243 |
r.layerCacheMu.Lock() |
| 244 |
c, done, ok := r.layerCache.Get(name) |
| 245 |
r.layerCacheMu.Unlock() |
| 246 |
if ok { |
| 247 |
if l := c.(*layer); l.Check() == nil { |
| 248 |
log.G(ctx).Debugf("hit layer cache %q", name) |
| 249 |
return &layerRef{l, done}, nil |
| 250 |
} |
| 251 |
// Cached layer is invalid |
| 252 |
done() |
| 253 |
r.layerCacheMu.Lock() |
| 254 |
r.layerCache.Remove(name) |
| 255 |
r.layerCacheMu.Unlock() |
| 256 |
} |
| 257 |
|
| 258 |
log.G(ctx).Debugf("resolving") |
| 259 |
|
| 260 |
// Resolve the blob. |
| 261 |
blobR, err := r.resolveBlob(ctx, hosts, refspec, desc) |
| 262 |
if err != nil { |
| 263 |
return nil, fmt.Errorf("failed to resolve the blob: %w", err) |
| 264 |
} |
| 265 |
defer func() { |
| 266 |
if retErr != nil { |
| 267 |
blobR.done() |
| 268 |
} |
| 269 |
}() |
| 270 |
|
| 271 |
fsCache, err := newCache(filepath.Join(r.rootDir, "fscache"), r.config.FSCacheType, r.config) |
| 272 |
if err != nil { |
| 273 |
return nil, fmt.Errorf("failed to create fs cache: %w", err) |
| 274 |
} |
| 275 |
defer func() { |
| 276 |
if retErr != nil { |
| 277 |
fsCache.Close() |
| 278 |
} |
| 279 |
}() |
| 280 |
|
| 281 |
// Get a reader for stargz archive. |
| 282 |
// Each file's read operation is a prioritized task and all background tasks |
| 283 |
// will be stopped during the execution so this can avoid being disturbed for |
| 284 |
// NW traffic by background tasks. |
| 285 |
sr := io.NewSectionReader(readerAtFunc(func(p []byte, offset int64) (n int, err error) { |
| 286 |
r.backgroundTaskManager.DoPrioritizedTask() |
| 287 |
defer r.backgroundTaskManager.DonePrioritizedTask() |
| 288 |
return blobR.ReadAt(p, offset) |
| 289 |
}), 0, blobR.Size()) |
| 290 |
// define telemetry hooks to measure latency metrics inside estargz package |
| 291 |
telemetry := metadata.Telemetry{ |
| 292 |
GetFooterLatency: func(start time.Time) { |
| 293 |
commonmetrics.MeasureLatencyInMilliseconds(commonmetrics.StargzFooterGet, desc.Digest, start) |
| 294 |
}, |
| 295 |
GetTocLatency: func(start time.Time) { |
| 296 |
commonmetrics.MeasureLatencyInMilliseconds(commonmetrics.StargzTocGet, desc.Digest, start) |
| 297 |
}, |
| 298 |
DeserializeTocLatency: func(start time.Time) { |
| 299 |
commonmetrics.MeasureLatencyInMilliseconds(commonmetrics.DeserializeTocJSON, desc.Digest, start) |
| 300 |
}, |
| 301 |
} |
| 302 |
|
| 303 |
additionalDecompressors := []metadata.Decompressor{new(zstdchunked.Decompressor)} |
| 304 |
if r.additionalDecompressors != nil { |
| 305 |
additionalDecompressors = append(additionalDecompressors, r.additionalDecompressors(ctx, hosts, refspec, desc)...) |
| 306 |
} |
| 307 |
meta, err := r.metadataStore(sr, |
| 308 |
append(esgzOpts, metadata.WithTelemetry(&telemetry), metadata.WithDecompressors(additionalDecompressors...))...) |
| 309 |
if err != nil { |
| 310 |
return nil, err |
| 311 |
} |
| 312 |
vr, err := reader.NewReader(meta, fsCache, desc.Digest) |
| 313 |
if err != nil { |
| 314 |
return nil, fmt.Errorf("failed to read layer: %w", err) |
| 315 |
} |
| 316 |
|
| 317 |
// Combine layer information together and cache it. |
| 318 |
l := newLayer(r, desc, blobR, vr) |
| 319 |
r.layerCacheMu.Lock() |
| 320 |
cachedL, done2, added := r.layerCache.Add(name, l) |
| 321 |
r.layerCacheMu.Unlock() |
| 322 |
if !added { |
| 323 |
l.close() // layer already exists in the cache. discrad this. |
| 324 |
} |
| 325 |
|
| 326 |
log.G(ctx).Debugf("resolved") |
| 327 |
return &layerRef{cachedL.(*layer), done2}, nil |
| 328 |
} |
| 329 |
|
| 330 |
// resolveBlob resolves a blob based on the passed layer blob information. |
| 331 |
func (r *Resolver) resolveBlob(ctx context.Context, hosts source.RegistryHosts, refspec reference.Spec, desc ocispec.Descriptor) (_ *blobRef, retErr error) { |
| 332 |
name := refspec.String() + "/" + desc.Digest.String() |
| 333 |
|
| 334 |
// Try to retrieve the blob from the underlying cache. |
| 335 |
r.blobCacheMu.Lock() |
| 336 |
c, done, ok := r.blobCache.Get(name) |
| 337 |
r.blobCacheMu.Unlock() |
| 338 |
if ok { |
| 339 |
if blob := c.(remote.Blob); blob.Check() == nil { |
| 340 |
return &blobRef{blob, done}, nil |
| 341 |
} |
| 342 |
// invalid blob. discard this. |
| 343 |
done() |
| 344 |
r.blobCacheMu.Lock() |
| 345 |
r.blobCache.Remove(name) |
| 346 |
r.blobCacheMu.Unlock() |
| 347 |
} |
| 348 |
|
| 349 |
httpCache, err := newCache(filepath.Join(r.rootDir, "httpcache"), r.config.HTTPCacheType, r.config) |
| 350 |
if err != nil { |
| 351 |
return nil, fmt.Errorf("failed to create http cache: %w", err) |
| 352 |
} |
| 353 |
defer func() { |
| 354 |
if retErr != nil { |
| 355 |
httpCache.Close() |
| 356 |
} |
| 357 |
}() |
| 358 |
|
| 359 |
// Resolve the blob and cache the result. |
| 360 |
b, err := r.resolver.Resolve(ctx, hosts, refspec, desc, httpCache) |
| 361 |
if err != nil { |
| 362 |
return nil, fmt.Errorf("failed to resolve the source: %w", err) |
| 363 |
} |
| 364 |
r.blobCacheMu.Lock() |
| 365 |
cachedB, done, added := r.blobCache.Add(name, b) |
| 366 |
r.blobCacheMu.Unlock() |
| 367 |
if !added { |
| 368 |
b.Close() // blob already exists in the cache. discard this. |
| 369 |
} |
| 370 |
return &blobRef{cachedB.(remote.Blob), done}, nil |
| 371 |
} |
| 372 |
|
| 373 |
func newLayer( |
| 374 |
resolver *Resolver, |
| 375 |
desc ocispec.Descriptor, |
| 376 |
blob *blobRef, |
| 377 |
vr *reader.VerifiableReader, |
| 378 |
) *layer { |
| 379 |
return &layer{ |
| 380 |
resolver: resolver, |
| 381 |
desc: desc, |
| 382 |
blob: blob, |
| 383 |
verifiableReader: vr, |
| 384 |
prefetchWaiter: newWaiter(), |
| 385 |
} |
| 386 |
} |
| 387 |
|
| 388 |
type layer struct { |
| 389 |
resolver *Resolver |
| 390 |
desc ocispec.Descriptor |
| 391 |
blob *blobRef |
| 392 |
verifiableReader *reader.VerifiableReader |
| 393 |
prefetchWaiter *waiter |
| 394 |
|
| 395 |
prefetchSize int64 |
| 396 |
prefetchSizeMu sync.Mutex |
| 397 |
|
| 398 |
r reader.Reader |
| 399 |
|
| 400 |
closed bool |
| 401 |
closedMu sync.Mutex |
| 402 |
|
| 403 |
prefetchOnce sync.Once |
| 404 |
backgroundFetchOnce sync.Once |
| 405 |
} |
| 406 |
|
| 407 |
func (l *layer) Info() Info { |
| 408 |
var readTime time.Time |
| 409 |
if l.r != nil { |
| 410 |
readTime = l.r.LastOnDemandReadTime() |
| 411 |
} |
| 412 |
return Info{ |
| 413 |
Digest: l.desc.Digest, |
| 414 |
Size: l.blob.Size(), |
| 415 |
FetchedSize: l.blob.FetchedSize(), |
| 416 |
PrefetchSize: l.prefetchedSize(), |
| 417 |
ReadTime: readTime, |
| 418 |
} |
| 419 |
} |
| 420 |
|
| 421 |
func (l *layer) prefetchedSize() int64 { |
| 422 |
l.prefetchSizeMu.Lock() |
| 423 |
sz := l.prefetchSize |
| 424 |
l.prefetchSizeMu.Unlock() |
| 425 |
return sz |
| 426 |
} |
| 427 |
|
| 428 |
func (l *layer) Check() error { |
| 429 |
if l.isClosed() { |
| 430 |
return fmt.Errorf("layer is already closed") |
| 431 |
} |
| 432 |
return l.blob.Check() |
| 433 |
} |
| 434 |
|
| 435 |
func (l *layer) Refresh(ctx context.Context, hosts source.RegistryHosts, refspec reference.Spec, desc ocispec.Descriptor) error { |
| 436 |
if l.isClosed() { |
| 437 |
return fmt.Errorf("layer is already closed") |
| 438 |
} |
| 439 |
return l.blob.Refresh(ctx, hosts, refspec, desc) |
| 440 |
} |
| 441 |
|
| 442 |
func (l *layer) Verify(tocDigest digest.Digest) (err error) { |
| 443 |
if l.isClosed() { |
| 444 |
return fmt.Errorf("layer is already closed") |
| 445 |
} |
| 446 |
if l.r != nil { |
| 447 |
return nil |
| 448 |
} |
| 449 |
l.r, err = l.verifiableReader.VerifyTOC(tocDigest) |
| 450 |
return |
| 451 |
} |
| 452 |
|
| 453 |
func (l *layer) SkipVerify() { |
| 454 |
if l.r != nil { |
| 455 |
return |
| 456 |
} |
| 457 |
l.r = l.verifiableReader.SkipVerify() |
| 458 |
} |
| 459 |
|
| 460 |
func (l *layer) Prefetch(prefetchSize int64) (err error) { |
| 461 |
l.prefetchOnce.Do(func() { |
| 462 |
ctx := context.Background() |
| 463 |
l.resolver.backgroundTaskManager.DoPrioritizedTask() |
| 464 |
defer l.resolver.backgroundTaskManager.DonePrioritizedTask() |
| 465 |
err = l.prefetch(ctx, prefetchSize) |
| 466 |
if err != nil { |
| 467 |
log.G(ctx).WithError(err).Warnf("failed to prefetch layer=%v", l.desc.Digest) |
| 468 |
return |
| 469 |
} |
| 470 |
log.G(ctx).Debug("completed to prefetch") |
| 471 |
}) |
| 472 |
return |
| 473 |
} |
| 474 |
|
| 475 |
func (l *layer) prefetch(ctx context.Context, prefetchSize int64) error { |
| 476 |
defer l.prefetchWaiter.done() // Notify the completion |
| 477 |
// Measuring the total time to complete prefetch (use defer func() because l.Info().PrefetchSize is set later) |
| 478 |
start := time.Now() |
| 479 |
defer func() { |
| 480 |
commonmetrics.WriteLatencyWithBytesLogValue(ctx, l.desc.Digest, commonmetrics.PrefetchTotal, start, commonmetrics.PrefetchSize, l.prefetchedSize()) |
| 481 |
}() |
| 482 |
|
| 483 |
if l.isClosed() { |
| 484 |
return fmt.Errorf("layer is already closed") |
| 485 |
} |
| 486 |
rootID := l.verifiableReader.Metadata().RootID() |
| 487 |
if _, _, err := l.verifiableReader.Metadata().GetChild(rootID, estargz.NoPrefetchLandmark); err == nil { |
| 488 |
// do not prefetch this layer |
| 489 |
return nil |
| 490 |
} else if id, _, err := l.verifiableReader.Metadata().GetChild(rootID, estargz.PrefetchLandmark); err == nil { |
| 491 |
offset, err := l.verifiableReader.Metadata().GetOffset(id) |
| 492 |
if err != nil { |
| 493 |
return fmt.Errorf("failed to get offset of prefetch landmark: %w", err) |
| 494 |
} |
| 495 |
// override the prefetch size with optimized value |
| 496 |
prefetchSize = offset |
| 497 |
} else if prefetchSize > l.blob.Size() { |
| 498 |
// adjust prefetch size not to exceed the whole layer size |
| 499 |
prefetchSize = l.blob.Size() |
| 500 |
} |
| 501 |
|
| 502 |
// Fetch the target range |
| 503 |
downloadStart := time.Now() |
| 504 |
err := l.blob.Cache(0, prefetchSize) |
| 505 |
commonmetrics.WriteLatencyLogValue(ctx, l.desc.Digest, commonmetrics.PrefetchDownload, downloadStart) // time to download prefetch data |
| 506 |
|
| 507 |
if err != nil { |
| 508 |
return fmt.Errorf("failed to prefetch layer: %w", err) |
| 509 |
} |
| 510 |
|
| 511 |
// Set prefetch size for metrics after prefetch completed |
| 512 |
l.prefetchSizeMu.Lock() |
| 513 |
l.prefetchSize = prefetchSize |
| 514 |
l.prefetchSizeMu.Unlock() |
| 515 |
|
| 516 |
// Cache uncompressed contents of the prefetched range |
| 517 |
decompressStart := time.Now() |
| 518 |
err = l.verifiableReader.Cache(reader.WithFilter(func(offset int64) bool { |
| 519 |
return offset < prefetchSize // Cache only prefetch target |
| 520 |
})) |
| 521 |
commonmetrics.WriteLatencyLogValue(ctx, l.desc.Digest, commonmetrics.PrefetchDecompress, decompressStart) // time to decompress prefetch data |
| 522 |
if err != nil { |
| 523 |
return fmt.Errorf("failed to cache prefetched layer: %w", err) |
| 524 |
} |
| 525 |
|
| 526 |
return nil |
| 527 |
} |
| 528 |
|
| 529 |
func (l *layer) WaitForPrefetchCompletion() error { |
| 530 |
if l.isClosed() { |
| 531 |
return fmt.Errorf("layer is already closed") |
| 532 |
} |
| 533 |
return l.prefetchWaiter.wait(l.resolver.prefetchTimeout) |
| 534 |
} |
| 535 |
|
| 536 |
func (l *layer) BackgroundFetch() (err error) { |
| 537 |
l.backgroundFetchOnce.Do(func() { |
| 538 |
ctx := context.Background() |
| 539 |
err = l.backgroundFetch(ctx) |
| 540 |
if err != nil { |
| 541 |
log.G(ctx).WithError(err).Warnf("failed to fetch whole layer=%v", l.desc.Digest) |
| 542 |
return |
| 543 |
} |
| 544 |
log.G(ctx).Debug("completed to fetch all layer data in background") |
| 545 |
}) |
| 546 |
return |
| 547 |
} |
| 548 |
|
| 549 |
func (l *layer) backgroundFetch(ctx context.Context) error { |
| 550 |
defer commonmetrics.WriteLatencyLogValue(ctx, l.desc.Digest, commonmetrics.BackgroundFetchTotal, time.Now()) |
| 551 |
if l.isClosed() { |
| 552 |
return fmt.Errorf("layer is already closed") |
| 553 |
} |
| 554 |
br := io.NewSectionReader(readerAtFunc(func(p []byte, offset int64) (retN int, retErr error) { |
| 555 |
l.resolver.backgroundTaskManager.InvokeBackgroundTask(func(ctx context.Context) { |
| 556 |
// Measuring the time to download background fetch data (in milliseconds) |
| 557 |
defer commonmetrics.MeasureLatencyInMilliseconds(commonmetrics.BackgroundFetchDownload, l.Info().Digest, time.Now()) // time to download background fetch data |
| 558 |
retN, retErr = l.blob.ReadAt( |
| 559 |
p, |
| 560 |
offset, |
| 561 |
remote.WithContext(ctx), // Make cancellable |
| 562 |
remote.WithCacheOpts(cache.Direct()), // Do not pollute mem cache |
| 563 |
) |
| 564 |
}, 120*time.Second) |
| 565 |
return |
| 566 |
}), 0, l.blob.Size()) |
| 567 |
defer commonmetrics.WriteLatencyLogValue(ctx, l.desc.Digest, commonmetrics.BackgroundFetchDecompress, time.Now()) // time to decompress background fetch data (in milliseconds) |
| 568 |
return l.verifiableReader.Cache( |
| 569 |
reader.WithReader(br), // Read contents in background |
| 570 |
reader.WithCacheOpts(cache.Direct()), // Do not pollute mem cache |
| 571 |
) |
| 572 |
} |
| 573 |
|
| 574 |
func (l *layerRef) Done() { |
| 575 |
l.done() |
| 576 |
} |
| 577 |
|
| 578 |
func (l *layer) RootNode(baseInode uint32) (fusefs.InodeEmbedder, error) { |
| 579 |
if l.isClosed() { |
| 580 |
return nil, fmt.Errorf("layer is already closed") |
| 581 |
} |
| 582 |
if l.r == nil { |
| 583 |
return nil, fmt.Errorf("layer hasn't been verified yet") |
| 584 |
} |
| 585 |
return newNode(l.desc.Digest, l.r, l.blob, baseInode, l.resolver.overlayOpaqueType) |
| 586 |
} |
| 587 |
|
| 588 |
func (l *layer) ReadAt(p []byte, offset int64, opts ...remote.Option) (int, error) { |
| 589 |
return l.blob.ReadAt(p, offset, opts...) |
| 590 |
} |
| 591 |
|
| 592 |
func (l *layer) close() error { |
| 593 |
l.closedMu.Lock() |
| 594 |
defer l.closedMu.Unlock() |
| 595 |
if l.closed { |
| 596 |
return nil |
| 597 |
} |
| 598 |
l.closed = true |
| 599 |
defer l.blob.done() // Close reader first, then close the blob |
| 600 |
l.verifiableReader.Close() |
| 601 |
if l.r != nil { |
| 602 |
return l.r.Close() |
| 603 |
} |
| 604 |
return nil |
| 605 |
} |
| 606 |
|
| 607 |
func (l *layer) isClosed() bool { |
| 608 |
l.closedMu.Lock() |
| 609 |
closed := l.closed |
| 610 |
l.closedMu.Unlock() |
| 611 |
return closed |
| 612 |
} |
| 613 |
|
| 614 |
// blobRef is a reference to the blob in the cache. Calling `done` decreases the reference counter |
| 615 |
// of this blob in the underlying cache. When nobody refers to the blob in the cache, resources bound |
| 616 |
// to this blob will be discarded. |
| 617 |
type blobRef struct { |
| 618 |
remote.Blob |
| 619 |
done func() |
| 620 |
} |
| 621 |
|
| 622 |
// layerRef is a reference to the layer in the cache. Calling `Done` or `done` decreases the |
| 623 |
// reference counter of this blob in the underlying cache. When nobody refers to the layer in the |
| 624 |
// cache, resources bound to this layer will be discarded. |
| 625 |
type layerRef struct { |
| 626 |
*layer |
| 627 |
done func() |
| 628 |
} |
| 629 |
|
| 630 |
func newWaiter() *waiter { |
| 631 |
return &waiter{ |
| 632 |
completionCond: sync.NewCond(&sync.Mutex{}), |
| 633 |
} |
| 634 |
} |
| 635 |
|
| 636 |
type waiter struct { |
| 637 |
isDone bool |
| 638 |
isDoneMu sync.Mutex |
| 639 |
completionCond *sync.Cond |
| 640 |
} |
| 641 |
|
| 642 |
func (w *waiter) done() { |
| 643 |
w.isDoneMu.Lock() |
| 644 |
w.isDone = true |
| 645 |
w.isDoneMu.Unlock() |
| 646 |
w.completionCond.Broadcast() |
| 647 |
} |
| 648 |
|
| 649 |
func (w *waiter) wait(timeout time.Duration) error { |
| 650 |
wait := func() <-chan struct{} { |
| 651 |
ch := make(chan struct{}) |
| 652 |
go func() { |
| 653 |
w.isDoneMu.Lock() |
| 654 |
isDone := w.isDone |
| 655 |
w.isDoneMu.Unlock() |
| 656 |
|
| 657 |
w.completionCond.L.Lock() |
| 658 |
if !isDone { |
| 659 |
w.completionCond.Wait() |
| 660 |
} |
| 661 |
w.completionCond.L.Unlock() |
| 662 |
ch <- struct{}{} |
| 663 |
}() |
| 664 |
return ch |
| 665 |
} |
| 666 |
select { |
| 667 |
case <-time.After(timeout): |
| 668 |
w.isDoneMu.Lock() |
| 669 |
w.isDone = true |
| 670 |
w.isDoneMu.Unlock() |
| 671 |
w.completionCond.Broadcast() |
| 672 |
return fmt.Errorf("timeout(%v)", timeout) |
| 673 |
case <-wait(): |
| 674 |
return nil |
| 675 |
} |
| 676 |
} |
| 677 |
|
| 678 |
type readerAtFunc func([]byte, int64) (int, error) |
| 679 |
|
| 680 |
func (f readerAtFunc) ReadAt(p []byte, offset int64) (int, error) { return f(p, offset) } |