Debian Codegraph @

fs/reader/reader.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 package reader
24
25 import (
26 "bufio"
27 "bytes"
28 "context"
29 "crypto/sha256"
30 "fmt"
31 "io"
32 "os"
33 "runtime"
34 "sync"
35 "time"
36
37 "github.com/containerd/stargz-snapshotter/cache"
38 "github.com/containerd/stargz-snapshotter/estargz"
39 commonmetrics "github.com/containerd/stargz-snapshotter/fs/metrics/common"
40 "github.com/containerd/stargz-snapshotter/metadata"
41 "github.com/hashicorp/go-multierror"
42 digest "github.com/opencontainers/go-digest"
43 "golang.org/x/sync/errgroup"
44 "golang.org/x/sync/semaphore"
45 )
46
47 const maxWalkDepth = 10000
48
49 type Reader interface {
50 OpenFile(id uint32) (io.ReaderAt, error)
51 Metadata() metadata.Reader
52 Close() error
53 LastOnDemandReadTime() time.Time
54 }
55
56 // VerifiableReader produces a Reader with a given verifier.
57 type VerifiableReader struct {
58 r *reader
59
60 lastVerifyErr error
61 lastVerifyErrMu sync.Mutex
62 prohibitVerifyFailure bool
63 prohibitVerifyFailureMu sync.RWMutex
64
65 closed bool
66 closedMu sync.Mutex
67
68 verifier func(uint32, string) (digest.Verifier, error)
69 }
70
71 func (vr *VerifiableReader) storeLastVerifyErr(err error) {
72 vr.lastVerifyErrMu.Lock()
73 vr.lastVerifyErr = err
74 vr.lastVerifyErrMu.Unlock()
75 }
76
77 func (vr *VerifiableReader) loadLastVerifyErr() error {
78 vr.lastVerifyErrMu.Lock()
79 err := vr.lastVerifyErr
80 vr.lastVerifyErrMu.Unlock()
81 return err
82 }
83
84 func (vr *VerifiableReader) SkipVerify() Reader {
85 return vr.r
86 }
87
88 func (vr *VerifiableReader) VerifyTOC(tocDigest digest.Digest) (Reader, error) {
89 if vr.isClosed() {
90 return nil, fmt.Errorf("reader is already closed")
91 }
92 vr.prohibitVerifyFailureMu.Lock()
93 vr.prohibitVerifyFailure = true
94 lastVerifyErr := vr.loadLastVerifyErr()
95 vr.prohibitVerifyFailureMu.Unlock()
96 if err := lastVerifyErr; err != nil {
97 return nil, fmt.Errorf("content error occurs during caching contents: %w", err)
98 }
99 if actual := vr.r.r.TOCDigest(); actual != tocDigest {
100 return nil, fmt.Errorf("invalid TOC JSON %q; want %q", actual, tocDigest)
101 }
102 vr.r.verify = true
103 return vr.r, nil
104 }
105
106 func (vr *VerifiableReader) Metadata() metadata.Reader {
107 // TODO: this shouldn't be called before verified
108 return vr.r.r
109 }
110
111 func (vr *VerifiableReader) Cache(opts ...CacheOption) (err error) {
112 if vr.isClosed() {
113 return fmt.Errorf("reader is already closed")
114 }
115
116 var cacheOpts cacheOptions
117 for _, o := range opts {
118 o(&cacheOpts)
119 }
120
121 gr := vr.r
122 r := gr.r
123 if cacheOpts.reader != nil {
124 r, err = r.Clone(cacheOpts.reader)
125 if err != nil {
126 return err
127 }
128 }
129 rootID := r.RootID()
130
131 filter := func(int64) bool {
132 return true
133 }
134 if cacheOpts.filter != nil {
135 filter = cacheOpts.filter
136 }
137
138 eg, egCtx := errgroup.WithContext(context.Background())
139 eg.Go(func() error {
140 return vr.cacheWithReader(egCtx,
141 0, eg, semaphore.NewWeighted(int64(runtime.GOMAXPROCS(0))),
142 rootID, r, filter, cacheOpts.cacheOpts...)
143 })
144 return eg.Wait()
145 }
146
147 func (vr *VerifiableReader) cacheWithReader(ctx context.Context, currentDepth int, eg *errgroup.Group, sem *semaphore.Weighted, dirID uint32, r metadata.Reader, filter func(int64) bool, opts ...cache.Option) (rErr error) {
148 if currentDepth > maxWalkDepth {
149 return fmt.Errorf("tree is too deep (depth:%d)", currentDepth)
150 }
151 rootID := r.RootID()
152 r.ForeachChild(dirID, func(name string, id uint32, mode os.FileMode) bool {
153 e, err := r.GetAttr(id)
154 if err != nil {
155 rErr = err
156 return false
157 }
158 if mode.IsDir() {
159 // Walk through all files on this stargz file.
160
161 // Ignore the entry of "./" (formated as "" by stargz lib) on root directory
162 // because this points to the root directory itself.
163 if dirID == rootID && name == "" {
164 return true
165 }
166
167 if err := vr.cacheWithReader(ctx, currentDepth+1, eg, sem, id, r, filter, opts...); err != nil {
168 rErr = err
169 return false
170 }
171 return true
172 } else if !mode.IsRegular() {
173 // Only cache regular files
174 return true
175 } else if dirID == rootID && name == estargz.TOCTarName {
176 // We don't need to cache TOC json file
177 return true
178 }
179
180 offset, err := r.GetOffset(id)
181 if err != nil {
182 rErr = err
183 return false
184 }
185 if !filter(offset) {
186 // This entry need to be filtered out
187 return true
188 }
189
190 fr, err := r.OpenFileWithPreReader(id, func(nid uint32, chunkOffset, chunkSize int64, chunkDigest string, r io.Reader) (retErr error) {
191 return vr.readAndCache(nid, r, chunkOffset, chunkSize, chunkDigest, opts...)
192 })
193 if err != nil {
194 rErr = err
195 return false
196 }
197
198 var nr int64
199 for nr < e.Size {
200 chunkOffset, chunkSize, chunkDigestStr, ok := fr.ChunkEntryForOffset(nr)
201 if !ok {
202 break
203 }
204 nr += chunkSize
205
206 if err := sem.Acquire(ctx, 1); err != nil {
207 rErr = err
208 return false
209 }
210
211 eg.Go(func() error {
212 defer sem.Release(1)
213 err := vr.readAndCache(id, io.NewSectionReader(fr, chunkOffset, chunkSize), chunkOffset, chunkSize, chunkDigestStr, opts...)
214 if err != nil {
215 return fmt.Errorf("failed to read %q (off:%d,size:%d): %w", name, chunkOffset, chunkSize, err)
216 }
217 return nil
218 })
219 }
220
221 return true
222 })
223
224 return
225 }
226
227 func (vr *VerifiableReader) readAndCache(id uint32, fr io.Reader, chunkOffset, chunkSize int64, chunkDigest string, opts ...cache.Option) (retErr error) {
228 gr := vr.r
229
230 if retErr != nil {
231 vr.storeLastVerifyErr(retErr)
232 }
233
234 // Check if it already exists in the cache
235 cacheID := genID(id, chunkOffset, chunkSize)
236 if r, err := gr.cache.Get(cacheID); err == nil {
237 r.Close()
238 return nil
239 }
240
241 // missed cache, needs to fetch and add it to the cache
242 br := bufio.NewReaderSize(fr, int(chunkSize))
243 if _, err := br.Peek(int(chunkSize)); err != nil {
244 return fmt.Errorf("cacheWithReader.peek: %v", err)
245 }
246 w, err := gr.cache.Add(cacheID, opts...)
247 if err != nil {
248 return err
249 }
250 defer w.Close()
251 v, err := vr.verifier(id, chunkDigest)
252 if err != nil {
253 vr.prohibitVerifyFailureMu.RLock()
254 if vr.prohibitVerifyFailure {
255 vr.prohibitVerifyFailureMu.RUnlock()
256 return fmt.Errorf("verifier not found: %w", err)
257 }
258 vr.storeLastVerifyErr(err)
259 vr.prohibitVerifyFailureMu.RUnlock()
260 }
261 tee := io.Discard
262 if v != nil {
263 tee = io.Writer(v) // verification is required
264 }
265 if _, err := io.CopyN(w, io.TeeReader(br, tee), chunkSize); err != nil {
266 w.Abort()
267 return fmt.Errorf("failed to cache file payload: %w", err)
268 }
269 if v != nil && !v.Verified() {
270 err := fmt.Errorf("invalid chunk")
271 vr.prohibitVerifyFailureMu.RLock()
272 if vr.prohibitVerifyFailure {
273 vr.prohibitVerifyFailureMu.RUnlock()
274 w.Abort()
275 return err
276 }
277 vr.storeLastVerifyErr(err)
278 vr.prohibitVerifyFailureMu.RUnlock()
279 }
280
281 return w.Commit()
282 }
283
284 func (vr *VerifiableReader) Close() error {
285 vr.closedMu.Lock()
286 defer vr.closedMu.Unlock()
287 if vr.closed {
288 return nil
289 }
290 vr.closed = true
291 return vr.r.Close()
292 }
293
294 func (vr *VerifiableReader) isClosed() bool {
295 vr.closedMu.Lock()
296 closed := vr.closed
297 vr.closedMu.Unlock()
298 return closed
299 }
300
301 // NewReader creates a Reader based on the given stargz blob and cache implementation.
302 // It returns VerifiableReader so the caller must provide a metadata.ChunkVerifier
303 // to use for verifying file or chunk contained in this stargz blob.
304 func NewReader(r metadata.Reader, cache cache.BlobCache, layerSha digest.Digest) (*VerifiableReader, error) {
305 vr := &reader{
306 r: r,
307 cache: cache,
308 bufPool: sync.Pool{
309 New: func() interface{} {
310 return new(bytes.Buffer)
311 },
312 },
313 layerSha: layerSha,
314 verifier: digestVerifier,
315 }
316 return &VerifiableReader{r: vr, verifier: digestVerifier}, nil
317 }
318
319 type reader struct {
320 r metadata.Reader
321 cache cache.BlobCache
322 bufPool sync.Pool
323
324 layerSha digest.Digest
325
326 lastReadTime time.Time
327 lastReadTimeMu sync.Mutex
328
329 closed bool
330 closedMu sync.Mutex
331
332 verify bool
333 verifier func(uint32, string) (digest.Verifier, error)
334 }
335
336 func (gr *reader) Metadata() metadata.Reader {
337 return gr.r
338 }
339
340 func (gr *reader) setLastReadTime(lastReadTime time.Time) {
341 gr.lastReadTimeMu.Lock()
342 gr.lastReadTime = lastReadTime
343 gr.lastReadTimeMu.Unlock()
344 }
345
346 func (gr *reader) LastOnDemandReadTime() time.Time {
347 gr.lastReadTimeMu.Lock()
348 t := gr.lastReadTime
349 gr.lastReadTimeMu.Unlock()
350 return t
351 }
352
353 func (gr *reader) OpenFile(id uint32) (io.ReaderAt, error) {
354 if gr.isClosed() {
355 return nil, fmt.Errorf("reader is already closed")
356 }
357 var fr metadata.File
358 fr, err := gr.r.OpenFileWithPreReader(id, func(nid uint32, chunkOffset, chunkSize int64, chunkDigest string, r io.Reader) error {
359 // Check if it already exists in the cache
360 cacheID := genID(nid, chunkOffset, chunkSize)
361 if r, err := gr.cache.Get(cacheID); err == nil {
362 r.Close()
363 return nil
364 }
365
366 // Read and cache
367 b := gr.bufPool.Get().(*bytes.Buffer)
368 b.Reset()
369 b.Grow(int(chunkSize))
370 ip := b.Bytes()[:chunkSize]
371 if _, err := io.ReadFull(r, ip); err != nil {
372 gr.putBuffer(b)
373 return err
374 }
375 err := gr.verifyAndCache(nid, ip, chunkDigest, cacheID)
376 gr.putBuffer(b)
377 return err
378 })
379 if err != nil {
380 return nil, fmt.Errorf("failed to open file %d: %w", id, err)
381 }
382 return &file{
383 id: id,
384 fr: fr,
385 gr: gr,
386 }, nil
387 }
388
389 func (gr *reader) Close() (retErr error) {
390 gr.closedMu.Lock()
391 defer gr.closedMu.Unlock()
392 if gr.closed {
393 return nil
394 }
395 gr.closed = true
396 if err := gr.cache.Close(); err != nil {
397 retErr = multierror.Append(retErr, err)
398 }
399 if err := gr.r.Close(); err != nil {
400 retErr = multierror.Append(retErr, err)
401 }
402 return
403 }
404
405 func (gr *reader) isClosed() bool {
406 gr.closedMu.Lock()
407 closed := gr.closed
408 gr.closedMu.Unlock()
409 return closed
410 }
411
412 func (gr *reader) putBuffer(b *bytes.Buffer) {
413 b.Reset()
414 gr.bufPool.Put(b)
415 }
416
417 type file struct {
418 id uint32
419 fr metadata.File
420 gr *reader
421 }
422
423 // ReadAt reads chunks from the stargz file with trying to fetch as many chunks
424 // as possible from the cache.
425 func (sf *file) ReadAt(p []byte, offset int64) (int, error) {
426 nr := 0
427 for nr < len(p) {
428 chunkOffset, chunkSize, chunkDigestStr, ok := sf.fr.ChunkEntryForOffset(offset + int64(nr))
429 if !ok {
430 break
431 }
432 var (
433 id = genID(sf.id, chunkOffset, chunkSize)
434 lowerDiscard = positive(offset - chunkOffset)
435 upperDiscard = positive(chunkOffset + chunkSize - (offset + int64(len(p))))
436 expectedSize = chunkSize - upperDiscard - lowerDiscard
437 )
438
439 // Check if the content exists in the cache
440 if r, err := sf.gr.cache.Get(id); err == nil {
441 n, err := r.ReadAt(p[nr:int64(nr)+expectedSize], lowerDiscard)
442 if (err == nil || err == io.EOF) && int64(n) == expectedSize {
443 nr += n
444 r.Close()
445 continue
446 }
447 r.Close()
448 }
449
450 // We missed cache. Take it from underlying reader.
451 // We read the whole chunk here and add it to the cache so that following
452 // reads against neighboring chunks can take the data without decmpression.
453 if lowerDiscard == 0 && upperDiscard == 0 {
454 // We can directly store the result to the given buffer
455 ip := p[nr : int64(nr)+chunkSize]
456 n, err := sf.fr.ReadAt(ip, chunkOffset)
457 if err != nil && err != io.EOF {
458 return 0, fmt.Errorf("failed to read data: %w", err)
459 }
460 if err := sf.gr.verifyAndCache(sf.id, ip, chunkDigestStr, id); err != nil {
461 return 0, err
462 }
463 nr += n
464 continue
465 }
466
467 // Use temporally buffer for aligning this chunk
468 b := sf.gr.bufPool.Get().(*bytes.Buffer)
469 b.Reset()
470 b.Grow(int(chunkSize))
471 ip := b.Bytes()[:chunkSize]
472 if _, err := sf.fr.ReadAt(ip, chunkOffset); err != nil && err != io.EOF {
473 sf.gr.putBuffer(b)
474 return 0, fmt.Errorf("failed to read data: %w", err)
475 }
476 if err := sf.gr.verifyAndCache(sf.id, ip, chunkDigestStr, id); err != nil {
477 sf.gr.putBuffer(b)
478 return 0, err
479 }
480 n := copy(p[nr:], ip[lowerDiscard:chunkSize-upperDiscard])
481 sf.gr.putBuffer(b)
482 if int64(n) != expectedSize {
483 return 0, fmt.Errorf("unexpected final data size %d; want %d", n, expectedSize)
484 }
485 nr += n
486 }
487
488 commonmetrics.AddBytesCount(commonmetrics.OnDemandBytesServed, sf.gr.layerSha, int64(nr)) // measure the number of on demand bytes served
489
490 return nr, nil
491 }
492
493 func (gr *reader) verifyAndCache(entryID uint32, ip []byte, chunkDigestStr string, cacheID string) error {
494 // We can end up doing on demand registry fetch when aligning the chunk
495 commonmetrics.IncOperationCount(commonmetrics.OnDemandRemoteRegistryFetchCount, gr.layerSha) // increment the number of on demand file fetches from remote registry
496 commonmetrics.AddBytesCount(commonmetrics.OnDemandBytesFetched, gr.layerSha, int64(len(ip))) // record total bytes fetched
497 gr.setLastReadTime(time.Now())
498
499 // Verify this chunk
500 if err := gr.verifyChunk(entryID, ip, chunkDigestStr); err != nil {
501 return fmt.Errorf("invalid chunk: %w", err)
502 }
503
504 // Cache this chunk
505 if w, err := gr.cache.Add(cacheID); err == nil {
506 if cn, err := w.Write(ip); err != nil || cn != len(ip) {
507 w.Abort()
508 } else {
509 w.Commit()
510 }
511 w.Close()
512 }
513
514 return nil
515 }
516
517 func (gr *reader) verifyChunk(id uint32, p []byte, chunkDigestStr string) error {
518 if !gr.verify {
519 return nil // verification is not required
520 }
521 v, err := gr.verifier(id, chunkDigestStr)
522 if err != nil {
523 return fmt.Errorf("invalid chunk: %w", err)
524 }
525 if _, err := v.Write(p); err != nil {
526 return fmt.Errorf("invalid chunk: failed to write to verifier: %w", err)
527 }
528 if !v.Verified() {
529 return fmt.Errorf("invalid chunk: not verified")
530 }
531
532 return nil
533 }
534
535 func genID(id uint32, offset, size int64) string {
536 sum := sha256.Sum256([]byte(fmt.Sprintf("%d-%d-%d", id, offset, size)))
537 return fmt.Sprintf("%x", sum)
538 }
539
540 func positive(n int64) int64 {
541 if n < 0 {
542 return 0
543 }
544 return n
545 }
546
547 type CacheOption func(*cacheOptions)
548
549 type cacheOptions struct {
550 cacheOpts []cache.Option
551 filter func(int64) bool
552 reader *io.SectionReader
553 }
554
555 func WithCacheOpts(cacheOpts ...cache.Option) CacheOption {
556 return func(opts *cacheOptions) {
557 opts.cacheOpts = cacheOpts
558 }
559 }
560
561 func WithFilter(filter func(int64) bool) CacheOption {
562 return func(opts *cacheOptions) {
563 opts.filter = filter
564 }
565 }
566
567 func WithReader(sr *io.SectionReader) CacheOption {
568 return func(opts *cacheOptions) {
569 opts.reader = sr
570 }
571 }
572
573 func digestVerifier(id uint32, chunkDigestStr string) (digest.Verifier, error) {
574 chunkDigest, err := digest.Parse(chunkDigestStr)
575 if err != nil {
576 return nil, fmt.Errorf("invalid chunk: no digest is recorded(len=%d): %w", len(chunkDigestStr), err)
577 }
578 return chunkDigest.Verifier(), nil
579 }