Debian Codegraph @

fs/remote/blob.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 remote
24
25 import (
26 "context"
27 "fmt"
28 "io"
29 "regexp"
30 "sort"
31 "strings"
32 "sync"
33 "time"
34
35 "github.com/containerd/containerd/reference"
36 "github.com/containerd/stargz-snapshotter/cache"
37 "github.com/containerd/stargz-snapshotter/fs/source"
38 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
39 "golang.org/x/sync/errgroup"
40 "golang.org/x/sync/singleflight"
41 )
42
43 var contentRangeRegexp = regexp.MustCompile(`bytes ([0-9]+)-([0-9]+)/([0-9]+|\\*)`)
44
45 type Blob interface {
46 Check() error
47 Size() int64
48 FetchedSize() int64
49 ReadAt(p []byte, offset int64, opts ...Option) (int, error)
50 Cache(offset int64, size int64, opts ...Option) error
51 Refresh(ctx context.Context, host source.RegistryHosts, refspec reference.Spec, desc ocispec.Descriptor) error
52 Close() error
53 }
54
55 type blob struct {
56 fetcher fetcher
57 fetcherMu sync.Mutex
58
59 size int64
60 chunkSize int64
61 prefetchChunkSize int64
62 cache cache.BlobCache
63 lastCheck time.Time
64 lastCheckMu sync.Mutex
65 checkInterval time.Duration
66 fetchTimeout time.Duration
67
68 fetchedRegionSet regionSet
69 fetchedRegionSetMu sync.Mutex
70 fetchedRegionGroup singleflight.Group
71 fetchedRegionCopyMu sync.Mutex
72
73 resolver *Resolver
74
75 closed bool
76 closedMu sync.Mutex
77 }
78
79 func makeBlob(fetcher fetcher, size int64, chunkSize int64, prefetchChunkSize int64,
80 blobCache cache.BlobCache, lastCheck time.Time, checkInterval time.Duration,
81 r *Resolver, fetchTimeout time.Duration) *blob {
82 return &blob{
83 fetcher: fetcher,
84 size: size,
85 chunkSize: chunkSize,
86 prefetchChunkSize: prefetchChunkSize,
87 cache: blobCache,
88 lastCheck: lastCheck,
89 checkInterval: checkInterval,
90 resolver: r,
91 fetchTimeout: fetchTimeout,
92 }
93 }
94
95 func (b *blob) Close() error {
96 b.closedMu.Lock()
97 defer b.closedMu.Unlock()
98 if b.closed {
99 return nil
100 }
101 b.closed = true
102 return b.cache.Close()
103 }
104
105 func (b *blob) isClosed() bool {
106 b.closedMu.Lock()
107 closed := b.closed
108 b.closedMu.Unlock()
109 return closed
110 }
111
112 func (b *blob) Refresh(ctx context.Context, hosts source.RegistryHosts, refspec reference.Spec, desc ocispec.Descriptor) error {
113 if b.isClosed() {
114 return fmt.Errorf("blob is already closed")
115 }
116
117 // refresh the fetcher
118 f, newSize, err := b.resolver.resolveFetcher(ctx, hosts, refspec, desc)
119 if err != nil {
120 return err
121 }
122 if newSize != b.size {
123 return fmt.Errorf("Invalid size of new blob %d; want %d", newSize, b.size)
124 }
125
126 // update the blob's fetcher with new one
127 b.fetcherMu.Lock()
128 b.fetcher = f
129 b.fetcherMu.Unlock()
130 b.lastCheckMu.Lock()
131 b.lastCheck = time.Now()
132 b.lastCheckMu.Unlock()
133
134 return nil
135 }
136
137 func (b *blob) Check() error {
138 if b.isClosed() {
139 return fmt.Errorf("blob is already closed")
140 }
141
142 now := time.Now()
143 b.lastCheckMu.Lock()
144 lastCheck := b.lastCheck
145 b.lastCheckMu.Unlock()
146 if now.Sub(lastCheck) < b.checkInterval {
147 // do nothing if not expired
148 return nil
149 }
150 b.fetcherMu.Lock()
151 fr := b.fetcher
152 b.fetcherMu.Unlock()
153 err := fr.check()
154 if err == nil {
155 // update lastCheck only if check succeeded.
156 // on failure, we should check this layer next time again.
157 b.lastCheckMu.Lock()
158 b.lastCheck = now
159 b.lastCheckMu.Unlock()
160 }
161
162 return err
163 }
164
165 func (b *blob) Size() int64 {
166 return b.size
167 }
168
169 func (b *blob) FetchedSize() int64 {
170 b.fetchedRegionSetMu.Lock()
171 sz := b.fetchedRegionSet.totalSize()
172 b.fetchedRegionSetMu.Unlock()
173 return sz
174 }
175
176 func makeSyncKey(allData map[region]io.Writer) string {
177 keys := make([]string, len(allData))
178 keysIndex := 0
179 for key := range allData {
180 keys[keysIndex] = fmt.Sprintf("[%d,%d]", key.b, key.e)
181 keysIndex++
182 }
183 sort.Strings(keys)
184 return strings.Join(keys, ",")
185 }
186
187 func (b *blob) cacheAt(offset int64, size int64, fr fetcher, cacheOpts *options) error {
188 fetchReg := region{floor(offset, b.chunkSize), ceil(offset+size-1, b.chunkSize) - 1}
189 discard := make(map[region]io.Writer)
190
191 err := b.walkChunks(fetchReg, func(reg region) error {
192 if r, err := b.cache.Get(fr.genID(reg), cacheOpts.cacheOpts...); err == nil {
193 return r.Close() // nop if the cache hits
194 }
195 discard[reg] = io.Discard
196 return nil
197 })
198 if err != nil {
199 return err
200 }
201
202 return b.fetchRange(discard, cacheOpts)
203 }
204
205 func (b *blob) Cache(offset int64, size int64, opts ...Option) error {
206 if b.isClosed() {
207 return fmt.Errorf("blob is already closed")
208 }
209
210 var cacheOpts options
211 for _, o := range opts {
212 o(&cacheOpts)
213 }
214
215 b.fetcherMu.Lock()
216 fr := b.fetcher
217 b.fetcherMu.Unlock()
218
219 if b.prefetchChunkSize <= b.chunkSize {
220 return b.cacheAt(offset, size, fr, &cacheOpts)
221 }
222
223 eg, _ := errgroup.WithContext(context.Background())
224
225 fetchSize := b.chunkSize * (b.prefetchChunkSize / b.chunkSize)
226
227 end := offset + size
228 for i := offset; i < end; i += fetchSize {
229 i, l := i, fetchSize
230 if i+l > end {
231 l = end - i
232 }
233 eg.Go(func() error {
234 return b.cacheAt(i, l, fr, &cacheOpts)
235 })
236 }
237
238 return eg.Wait()
239 }
240
241 // ReadAt reads remote chunks from specified offset for the buffer size.
242 // It tries to fetch as many chunks as possible from local cache.
243 // We can configure this function with options.
244 func (b *blob) ReadAt(p []byte, offset int64, opts ...Option) (int, error) {
245 if b.isClosed() {
246 return 0, fmt.Errorf("blob is already closed")
247 }
248
249 if len(p) == 0 || offset > b.size {
250 return 0, nil
251 }
252
253 // Make the buffer chunk aligned
254 allRegion := region{floor(offset, b.chunkSize), ceil(offset+int64(len(p))-1, b.chunkSize) - 1}
255 allData := make(map[region]io.Writer)
256
257 var readAtOpts options
258 for _, o := range opts {
259 o(&readAtOpts)
260 }
261
262 // Fetcher can be suddenly updated so we take and use the snapshot of it for
263 // consistency.
264 b.fetcherMu.Lock()
265 fr := b.fetcher
266 b.fetcherMu.Unlock()
267
268 b.walkChunks(allRegion, func(chunk region) error {
269 var (
270 base = positive(chunk.b - offset)
271 lowerUnread = positive(offset - chunk.b)
272 upperUnread = positive(chunk.e + 1 - (offset + int64(len(p))))
273 expectedSize = chunk.size() - upperUnread - lowerUnread
274 )
275
276 // Check if the content exists in the cache
277 r, err := b.cache.Get(fr.genID(chunk), readAtOpts.cacheOpts...)
278 if err == nil {
279 defer r.Close()
280 n, err := r.ReadAt(p[base:base+expectedSize], lowerUnread)
281 if (err == nil || err == io.EOF) && int64(n) == expectedSize {
282 return nil
283 }
284 }
285
286 // We missed cache. Take it from remote registry.
287 // We get the whole chunk here and add it to the cache so that following
288 // reads against neighboring chunks can take the data without making HTTP requests.
289 allData[chunk] = newBytesWriter(p[base:base+expectedSize], lowerUnread)
290 return nil
291 })
292
293 // Read required data
294 if err := b.fetchRange(allData, &readAtOpts); err != nil {
295 return 0, err
296 }
297
298 // Adjust the buffer size according to the blob size
299 if remain := b.size - offset; int64(len(p)) >= remain {
300 if remain < 0 {
301 remain = 0
302 }
303 p = p[:remain]
304 }
305
306 return len(p), nil
307 }
308
309 // fetchRegions fetches all specified chunks from remote blob and puts it in the local cache.
310 // It must be called from within fetchRange and need to ensure that it is inside the singleflight `Do` operation.
311 func (b *blob) fetchRegions(allData map[region]io.Writer, fetched map[region]bool, opts *options) error {
312 if len(allData) == 0 {
313 return nil
314 }
315
316 // Fetcher can be suddenly updated so we take and use the snapshot of it for
317 // consistency.
318 b.fetcherMu.Lock()
319 fr := b.fetcher
320 b.fetcherMu.Unlock()
321
322 // request missed regions
323 var req []region
324 for reg := range allData {
325 req = append(req, reg)
326 fetched[reg] = false
327 }
328
329 fetchCtx, cancel := context.WithTimeout(context.Background(), b.fetchTimeout)
330 defer cancel()
331 if opts.ctx != nil {
332 fetchCtx = opts.ctx
333 }
334 mr, err := fr.fetch(fetchCtx, req, true)
335
336 if err != nil {
337 return err
338 }
339 defer mr.Close()
340
341 // Update the check timer because we succeeded to access the blob
342 b.lastCheckMu.Lock()
343 b.lastCheck = time.Now()
344 b.lastCheckMu.Unlock()
345
346 // chunk and cache responsed data. Regions must be aligned by chunk size.
347 // TODO: Reorganize remoteData to make it be aligned by chunk size
348 for {
349 reg, p, err := mr.Next()
350 if err == io.EOF {
351 break
352 } else if err != nil {
353 return fmt.Errorf("failed to read multipart resp: %w", err)
354 }
355 if err := b.walkChunks(reg, func(chunk region) (retErr error) {
356 id := fr.genID(chunk)
357 cw, err := b.cache.Add(id, opts.cacheOpts...)
358 if err != nil {
359 return err
360 }
361 defer cw.Close()
362 w := io.Writer(cw)
363
364 // If this chunk is one of the targets, write the content to the
365 // passed reader too.
366 if _, ok := fetched[chunk]; ok {
367 w = io.MultiWriter(w, allData[chunk])
368 }
369
370 // Copy the target chunk
371 if _, err := io.CopyN(w, p, chunk.size()); err != nil {
372 cw.Abort()
373 return err
374 }
375
376 // Add the target chunk to the cache
377 if err := cw.Commit(); err != nil {
378 return err
379 }
380
381 b.fetchedRegionSetMu.Lock()
382 b.fetchedRegionSet.add(chunk)
383 b.fetchedRegionSetMu.Unlock()
384 fetched[chunk] = true
385 return nil
386 }); err != nil {
387 return fmt.Errorf("failed to get chunks: %w", err)
388 }
389 }
390
391 // Check all chunks are fetched
392 var unfetched []region
393 for c, b := range fetched {
394 if !b {
395 unfetched = append(unfetched, c)
396 }
397 }
398 if unfetched != nil {
399 return fmt.Errorf("failed to fetch region %v", unfetched)
400 }
401
402 return nil
403 }
404
405 // fetchRange fetches all specified chunks from local cache and remote blob.
406 func (b *blob) fetchRange(allData map[region]io.Writer, opts *options) error {
407 if len(allData) == 0 {
408 return nil
409 }
410
411 // We build a key based on regions we need to fetch and pass it to singleflightGroup.Do(...)
412 // to block simultaneous same requests. Once the request is finished and the data is ready,
413 // all blocked callers will be unblocked and that same data will be returned by all blocked callers.
414 key := makeSyncKey(allData)
415 fetched := make(map[region]bool)
416 _, err, shared := b.fetchedRegionGroup.Do(key, func() (interface{}, error) {
417 return nil, b.fetchRegions(allData, fetched, opts)
418 })
419
420 // When unblocked try to read from cache in case if there were no errors
421 // If we fail reading from cache, fetch from remote registry again
422 if err == nil && shared {
423 for reg := range allData {
424 if _, ok := fetched[reg]; ok {
425 continue
426 }
427 err = b.walkChunks(reg, func(chunk region) error {
428 b.fetcherMu.Lock()
429 fr := b.fetcher
430 b.fetcherMu.Unlock()
431
432 // Check if the content exists in the cache
433 // And if exists, read from cache
434 r, err := b.cache.Get(fr.genID(chunk), opts.cacheOpts...)
435 if err != nil {
436 return err
437 }
438 defer r.Close()
439 rr := io.NewSectionReader(r, 0, chunk.size())
440
441 // Copy the target chunk
442 b.fetchedRegionCopyMu.Lock()
443 defer b.fetchedRegionCopyMu.Unlock()
444 if _, err := io.CopyN(allData[chunk], rr, chunk.size()); err != nil {
445 return err
446 }
447 return nil
448 })
449 if err != nil {
450 break
451 }
452 }
453
454 // if we cannot read the data from cache, do fetch again
455 if err != nil {
456 return b.fetchRange(allData, opts)
457 }
458 }
459
460 return err
461 }
462
463 type walkFunc func(reg region) error
464
465 // walkChunks walks chunks from begin to end in order in the specified region.
466 // specified region must be aligned by chunk size.
467 func (b *blob) walkChunks(allRegion region, walkFn walkFunc) error {
468 if allRegion.b%b.chunkSize != 0 {
469 return fmt.Errorf("region (%d, %d) must be aligned by chunk size",
470 allRegion.b, allRegion.e)
471 }
472 for i := allRegion.b; i <= allRegion.e && i < b.size; i += b.chunkSize {
473 reg := region{i, i + b.chunkSize - 1}
474 if reg.e >= b.size {
475 reg.e = b.size - 1
476 }
477 if err := walkFn(reg); err != nil {
478 return err
479 }
480 }
481 return nil
482 }
483
484 func newBytesWriter(dest []byte, destOff int64) io.Writer {
485 return &bytesWriter{
486 dest: dest,
487 destOff: destOff,
488 current: 0,
489 }
490 }
491
492 type bytesWriter struct {
493 dest []byte
494 destOff int64
495 current int64
496 }
497
498 func (bw *bytesWriter) Write(p []byte) (int, error) {
499 defer func() { bw.current = bw.current + int64(len(p)) }()
500
501 var (
502 destBase = positive(bw.current - bw.destOff)
503 pBegin = positive(bw.destOff - bw.current)
504 pEnd = positive(bw.destOff + int64(len(bw.dest)) - bw.current)
505 )
506
507 if destBase > int64(len(bw.dest)) {
508 return len(p), nil
509 }
510 if pBegin >= int64(len(p)) {
511 return len(p), nil
512 }
513 if pEnd > int64(len(p)) {
514 pEnd = int64(len(p))
515 }
516
517 copy(bw.dest[destBase:], p[pBegin:pEnd])
518
519 return len(p), nil
520 }
521
522 func floor(n int64, unit int64) int64 {
523 return (n / unit) * unit
524 }
525
526 func ceil(n int64, unit int64) int64 {
527 return (n/unit + 1) * unit
528 }
529
530 func positive(n int64) int64 {
531 if n < 0 {
532 return 0
533 }
534 return n
535 }