Debian Codegraph @

fs/layer/testutil.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 layer
24
25 import (
26 "bytes"
27 "compress/gzip"
28 "context"
29 "crypto/sha256"
30 "encoding/json"
31 "fmt"
32 "io"
33 "math/rand"
34 "net/http"
35 "os"
36 "path"
37 "path/filepath"
38 "strings"
39 "syscall"
40 "testing"
41 "time"
42
43 "github.com/containerd/containerd/reference"
44 "github.com/containerd/stargz-snapshotter/cache"
45 "github.com/containerd/stargz-snapshotter/estargz"
46 "github.com/containerd/stargz-snapshotter/fs/reader"
47 "github.com/containerd/stargz-snapshotter/fs/remote"
48 "github.com/containerd/stargz-snapshotter/fs/source"
49 "github.com/containerd/stargz-snapshotter/metadata"
50 "github.com/containerd/stargz-snapshotter/task"
51 tutil "github.com/containerd/stargz-snapshotter/util/testutil"
52 fusefs "github.com/hanwen/go-fuse/v2/fs"
53 "github.com/hanwen/go-fuse/v2/fuse"
54 "github.com/klauspost/compress/zstd"
55 digest "github.com/opencontainers/go-digest"
56 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
57 "golang.org/x/sys/unix"
58 )
59
60 const (
61 sampleChunkSize = 3
62 sampleData1 = "0123456789"
63 sampleData2 = "abcdefghij"
64 )
65
66 var srcCompressions = map[string]tutil.CompressionFactory{
67 "zstd-fastest": tutil.ZstdCompressionWithLevel(zstd.SpeedFastest),
68 "gzip-bestspeed": tutil.GzipCompressionWithLevel(gzip.BestSpeed),
69 "externaltoc-gzip-bestspeed": tutil.ExternalTOCGzipCompressionWithLevel(gzip.BestSpeed),
70 }
71
72 func TestSuiteLayer(t *testing.T, store metadata.Store) {
73 testPrefetch(t, store)
74 testNodeRead(t, store)
75 testNodes(t, store)
76 }
77
78 var testStateLayerDigest = digest.FromString("dummy")
79
80 func testPrefetch(t *testing.T, factory metadata.Store) {
81 data64KB := string(tutil.RandomBytes(t, 64000))
82 defaultPrefetchSize := int64(10000)
83 landmarkPosition := func(t *testing.T, l *layer) int64 {
84 if l.r == nil {
85 t.Fatalf("layer hasn't been verified yet")
86 }
87 if id, _, err := l.r.Metadata().GetChild(l.r.Metadata().RootID(), estargz.PrefetchLandmark); err == nil {
88 offset, err := l.r.Metadata().GetOffset(id)
89 if err != nil {
90 t.Fatalf("failed to get offset of prefetch landmark")
91 }
92 return offset
93 }
94 return defaultPrefetchSize
95 }
96 tests := []struct {
97 name string
98 chunkSize int // default is "sampleChunkSize"
99 minChunkSize int
100 in []tutil.TarEntry
101 wantNum int // number of chunks wanted in the cache
102 wants []string // filenames to compare
103 prefetchSize func(*testing.T, *layer) int64
104 prioritizedFiles []string
105 }{
106 {
107 name: "no_prefetch",
108 in: []tutil.TarEntry{
109 tutil.File("foo.txt", sampleData1),
110 },
111 wantNum: 0,
112 prioritizedFiles: nil,
113 },
114 {
115 name: "prefetch",
116 in: []tutil.TarEntry{
117 tutil.File("foo.txt", sampleData1),
118 tutil.File("bar.txt", sampleData2),
119 },
120 wantNum: chunkNum(sampleData1),
121 wants: []string{"foo.txt"},
122 prefetchSize: landmarkPosition,
123 prioritizedFiles: []string{"foo.txt"},
124 },
125 {
126 name: "with_dir",
127 in: []tutil.TarEntry{
128 tutil.Dir("foo/"),
129 tutil.File("foo/bar.txt", sampleData1),
130 tutil.Dir("buz/"),
131 tutil.File("buz/buzbuz.txt", sampleData2),
132 },
133 wantNum: chunkNum(sampleData1),
134 wants: []string{"foo/bar.txt"},
135 prefetchSize: landmarkPosition,
136 prioritizedFiles: []string{"foo/", "foo/bar.txt"},
137 },
138 {
139 name: "several_files_in_chunk",
140 minChunkSize: 8000,
141 chunkSize: 1000000000, // do not chunk
142 in: []tutil.TarEntry{
143 tutil.Dir("foo/"),
144 tutil.File("foo/foo1", data64KB),
145 tutil.File("foo2", "bb"),
146 tutil.File("foo22", "ccc"),
147 tutil.Dir("bar/"),
148 tutil.File("bar/bar.txt", "aaa"),
149 tutil.File("foo3", data64KB),
150 },
151 // NOTE: we assume that the compressed "data64KB" is still larger than 8KB
152 // landmark+dir+foo1, foo2+foo22+dir+bar.txt+foo3, TOC, footer
153 wantNum: 5, // foo1 + foo2 + foo22 + bar.txt + foo3
154 wants: []string{"foo/foo1", "foo2", "foo22", "bar/bar.txt", "foo3"},
155 prefetchSize: landmarkPosition,
156 prioritizedFiles: []string{"foo/", "foo/foo1", "foo2", "foo22", "bar/", "bar/bar.txt", "foo3"},
157 },
158 {
159 name: "several_files_in_chunk_chunked",
160 minChunkSize: 8000,
161 chunkSize: 32000,
162 in: []tutil.TarEntry{
163 tutil.Dir("foo/"),
164 tutil.File("foo/foo1", data64KB),
165 tutil.File("foo2", "bb"),
166 tutil.Dir("bar/"),
167 tutil.File("foo3", data64KB),
168 },
169 // NOTE: we assume that the compressed chunk of "data64KB" is still larger than 8KB
170 // landmark+dir+foo1(1), foo1(2), foo2, dir+foo3(1), foo3(2), TOC, footer
171 wantNum: 3, // foo1(2) + foo2 (foo3(1) shouldn't be in a separated stream)
172 wants: []string{"foo/foo1", "foo2"},
173 prefetchSize: landmarkPosition,
174 prioritizedFiles: []string{"foo/", "foo/foo1", "foo2"},
175 },
176 }
177
178 for _, tt := range tests {
179 for srcCompressionName, srcCompression := range srcCompressions {
180 cl := srcCompression()
181 t.Run("testPrefetch-"+tt.name+"-"+srcCompressionName, func(t *testing.T) {
182 chunkSize := sampleChunkSize
183 if tt.chunkSize > 0 {
184 chunkSize = tt.chunkSize
185 }
186 minChunkSize := 0
187 if tt.minChunkSize > 0 {
188 minChunkSize = tt.minChunkSize
189 }
190 sr, dgst, err := tutil.BuildEStargz(tt.in,
191 tutil.WithEStargzOptions(
192 estargz.WithChunkSize(chunkSize),
193 estargz.WithMinChunkSize(minChunkSize),
194 estargz.WithPrioritizedFiles(tt.prioritizedFiles),
195 estargz.WithCompression(cl),
196 ))
197 if err != nil {
198 t.Fatalf("failed to build eStargz: %v", err)
199 }
200 blob := newBlob(t, sr)
201 mcache := cache.NewMemoryCache()
202 mr, err := factory(sr, metadata.WithDecompressors(cl))
203 if err != nil {
204 t.Fatalf("failed to create metadata reader: %v", err)
205 }
206 defer mr.Close()
207 vr, err := reader.NewReader(mr, mcache, digest.FromString(""))
208 if err != nil {
209 t.Fatalf("failed to create reader: %v", err)
210 }
211 l := newLayer(
212 &Resolver{
213 prefetchTimeout: time.Second,
214 backgroundTaskManager: task.NewBackgroundTaskManager(10, 5*time.Second),
215 },
216 ocispec.Descriptor{Digest: testStateLayerDigest},
217 &blobRef{blob, func() {}},
218 vr,
219 )
220 if err := l.Verify(dgst); err != nil {
221 t.Errorf("failed to verify reader: %v", err)
222 return
223 }
224 prefetchSize := int64(0)
225 if tt.prefetchSize != nil {
226 prefetchSize = tt.prefetchSize(t, l)
227 }
228 if err := l.Prefetch(defaultPrefetchSize); err != nil {
229 t.Errorf("failed to prefetch: %v", err)
230 return
231 }
232 if blob.calledPrefetchOffset != 0 {
233 t.Errorf("invalid prefetch offset %d; want %d",
234 blob.calledPrefetchOffset, 0)
235 }
236 if blob.calledPrefetchSize != prefetchSize {
237 t.Errorf("invalid prefetch size %d; want %d",
238 blob.calledPrefetchSize, prefetchSize)
239 }
240 if cLen := len(mcache.(*cache.MemoryCache).Membuf); tt.wantNum != cLen {
241 t.Errorf("number of chunks in the cache %d; want %d: %v", cLen, tt.wantNum, err)
242 return
243 }
244
245 lr := l.r
246 if lr == nil {
247 t.Fatalf("failed to get reader from layer: %v", err)
248 }
249 for _, file := range tt.wants {
250 id, err := lookup(lr.Metadata(), file)
251 if err != nil {
252 t.Fatalf("failed to lookup %q: %v", file, err)
253 }
254 e, err := lr.Metadata().GetAttr(id)
255 if err != nil {
256 t.Fatalf("failed to get attr of %q: %v", file, err)
257 }
258 wantFile, err := lr.OpenFile(id)
259 if err != nil {
260 t.Fatalf("failed to open file %q", file)
261 }
262 blob.readCalled = false
263 if _, err := io.Copy(io.Discard, io.NewSectionReader(wantFile, 0, e.Size)); err != nil {
264 t.Fatalf("failed to read file %q", file)
265 }
266 if blob.readCalled {
267 t.Errorf("chunks of file %q aren't cached", file)
268 return
269 }
270 }
271 })
272 }
273 }
274 }
275
276 func lookup(r metadata.Reader, name string) (uint32, error) {
277 name = strings.TrimPrefix(path.Clean("/"+name), "/")
278 if name == "" {
279 return r.RootID(), nil
280 }
281 dir, base := filepath.Split(name)
282 pid, err := lookup(r, dir)
283 if err != nil {
284 return 0, err
285 }
286 id, _, err := r.GetChild(pid, base)
287 return id, err
288 }
289
290 func chunkNum(data string) int {
291 return (len(data)-1)/sampleChunkSize + 1
292 }
293
294 type region struct {
295 begin int64
296 end int64 // inclusive
297 }
298
299 func isDup(a, b region) bool {
300 if a.begin < b.begin {
301 return a.end >= b.begin
302 }
303 // b.begin <= a.begin
304 return b.end >= a.begin
305 }
306
307 func newBlob(t *testing.T, sr *io.SectionReader) *sampleBlob {
308 return &sampleBlob{
309 t: t,
310 r: sr,
311 }
312 }
313
314 type sampleBlob struct {
315 t *testing.T
316
317 r *io.SectionReader
318 readCalled bool
319 calledPrefetchOffset int64
320 calledPrefetchSize int64
321 calledRegions []region // sorted
322 }
323
324 func (sb *sampleBlob) Authn(tr http.RoundTripper) (http.RoundTripper, error) { return nil, nil }
325 func (sb *sampleBlob) Check() error { return nil }
326 func (sb *sampleBlob) Size() int64 { return sb.r.Size() }
327 func (sb *sampleBlob) FetchedSize() int64 { return 0 }
328 func (sb *sampleBlob) ReadAt(p []byte, offset int64, opts ...remote.Option) (int, error) {
329 if len(p) > 0 {
330 target := region{offset, offset + int64(len(p)) - 1}
331 if len(sb.calledRegions) == 0 {
332 sb.calledRegions = []region{target}
333 } else {
334 pos := 0
335 found := false
336 for i, r := range sb.calledRegions {
337 if target.begin < r.begin {
338 pos = i
339 found = true
340 break
341 }
342 }
343 if !found {
344 pos = len(sb.calledRegions)
345 }
346 if pos > 0 {
347 b := sb.calledRegions[pos-1]
348 if isDup(b, target) {
349 sb.t.Fatalf("reading on the previous region is duplicated: %+v and %+v", b, target)
350 }
351 }
352 if pos+1 < len(sb.calledRegions) {
353 a := sb.calledRegions[pos+1]
354 if isDup(a, target) {
355 sb.t.Fatalf("reading on the next region is duplicated: %+v and %+v", a, target)
356 }
357 }
358 sb.calledRegions = append(sb.calledRegions[:pos], append([]region{target}, sb.calledRegions[pos:]...)...)
359 }
360 }
361
362 sb.readCalled = true
363 return sb.r.ReadAt(p, offset)
364 }
365 func (sb *sampleBlob) Cache(offset int64, size int64, option ...remote.Option) error {
366 sb.calledPrefetchOffset = offset
367 sb.calledPrefetchSize = size
368 return nil
369 }
370 func (sb *sampleBlob) Refresh(ctx context.Context, hosts source.RegistryHosts, refspec reference.Spec, desc ocispec.Descriptor) error {
371 return nil
372 }
373 func (sb *sampleBlob) Close() error { return nil }
374
375 const (
376 sampleMiddleOffset = sampleChunkSize / 2
377 lastChunkOffset1 = sampleChunkSize * (int64(len(sampleData1)) / sampleChunkSize)
378 )
379
380 func testNodeRead(t *testing.T, factory metadata.Store) {
381 sizeCond := map[string]int64{
382 "single_chunk": sampleChunkSize - sampleMiddleOffset,
383 "multi_chunks": sampleChunkSize + sampleMiddleOffset,
384 }
385 innerOffsetCond := map[string]int64{
386 "at_top": 0,
387 "at_middle": sampleMiddleOffset,
388 }
389 baseOffsetCond := map[string]int64{
390 "of_1st_chunk": sampleChunkSize * 0,
391 "of_2nd_chunk": sampleChunkSize * 1,
392 "of_last_chunk": lastChunkOffset1,
393 }
394 fileSizeCond := map[string]int64{
395 "in_1_chunk_file": sampleChunkSize * 1,
396 "in_2_chunks_file": sampleChunkSize * 2,
397 "in_max_size_file": int64(len(sampleData1)),
398 }
399 for sn, size := range sizeCond {
400 for in, innero := range innerOffsetCond {
401 for bo, baseo := range baseOffsetCond {
402 for fn, filesize := range fileSizeCond {
403 for _, srcCompression := range srcCompressions {
404 cl := srcCompression()
405 t.Run(fmt.Sprintf("reading_%s_%s_%s_%s", sn, in, bo, fn), func(t *testing.T) {
406 if filesize > int64(len(sampleData1)) {
407 t.Fatal("sample file size is larger than sample data")
408 }
409
410 wantN := size
411 offset := baseo + innero
412 if remain := filesize - offset; remain < wantN {
413 if wantN = remain; wantN < 0 {
414 wantN = 0
415 }
416 }
417
418 // use constant string value as a data source.
419 want := strings.NewReader(sampleData1)
420
421 // data we want to get.
422 wantData := make([]byte, wantN)
423 _, err := want.ReadAt(wantData, offset)
424 if err != nil && err != io.EOF {
425 t.Fatalf("want.ReadAt (offset=%d,size=%d): %v", offset, wantN, err)
426 }
427
428 // data we get from the file node.
429 f, closeFn := makeNodeReader(t, []byte(sampleData1)[:filesize], sampleChunkSize, factory, cl)
430 defer closeFn()
431 tmpbuf := make([]byte, size) // fuse library can request bigger than remain
432 rr, errno := f.Read(context.Background(), tmpbuf, offset)
433 if errno != 0 {
434 t.Errorf("failed to read off=%d, size=%d, filesize=%d: %v", offset, size, filesize, err)
435 return
436 }
437 if rsize := rr.Size(); int64(rsize) != wantN {
438 t.Errorf("read size: %d; want: %d; passed %d", rsize, wantN, size)
439 return
440 }
441 tmpbuf = make([]byte, len(tmpbuf))
442 respData, fs := rr.Bytes(tmpbuf)
443 if fs != fuse.OK {
444 t.Errorf("failed to read result data for off=%d, size=%d, filesize=%d: %v", offset, size, filesize, err)
445 }
446
447 if !bytes.Equal(wantData, respData) {
448 t.Errorf("off=%d, filesize=%d; read data{size=%d,data=%q}; want (size=%d,data=%q)",
449 offset, filesize, len(respData), string(respData), wantN, string(wantData))
450 return
451 }
452 })
453 }
454 }
455 }
456 }
457 }
458 }
459
460 func makeNodeReader(t *testing.T, contents []byte, chunkSize int, factory metadata.Store, cl tutil.Compression) (_ *file, closeFn func() error) {
461 testName := "test"
462 sr, tocDgst, err := tutil.BuildEStargz(
463 []tutil.TarEntry{tutil.File(testName, string(contents))},
464 tutil.WithEStargzOptions(estargz.WithChunkSize(chunkSize), estargz.WithCompression(cl)),
465 )
466 if err != nil {
467 t.Fatalf("failed to build sample eStargz: %v", err)
468 }
469 r, err := factory(sr, metadata.WithDecompressors(cl))
470 if err != nil {
471 t.Fatalf("failed to create reader: %v", err)
472 }
473 rootNode := getRootNode(t, r, OverlayOpaqueAll, tocDgst, cache.NewMemoryCache())
474 var eo fuse.EntryOut
475 inode, errno := rootNode.Lookup(context.Background(), testName, &eo)
476 if errno != 0 {
477 r.Close()
478 t.Fatalf("failed to lookup test node; errno: %v", errno)
479 }
480 f, _, errno := inode.Operations().(fusefs.NodeOpener).Open(context.Background(), 0)
481 if errno != 0 {
482 r.Close()
483 t.Fatalf("failed to open test file; errno: %v", errno)
484 }
485 return f.(*file), r.Close
486 }
487
488 func testNodes(t *testing.T, factory metadata.Store) {
489 for _, o := range []OverlayOpaqueType{OverlayOpaqueAll, OverlayOpaqueTrusted, OverlayOpaqueUser} {
490 testNodesWithOpaque(t, factory, o)
491 }
492 }
493
494 func testNodesWithOpaque(t *testing.T, factory metadata.Store, opaque OverlayOpaqueType) {
495 data64KB := string(tutil.RandomBytes(t, 64000))
496 hasOpaque := func(entry string) check {
497 return func(t *testing.T, root *node, cc cache.BlobCache, cr *calledReaderAt) {
498 for _, k := range opaqueXattrs[opaque] {
499 hasNodeXattrs(entry, k, opaqueXattrValue)(t, root, cc, cr)
500 }
501 }
502 }
503 tests := []struct {
504 name string
505 chunkSize int
506 minChunkSize int
507 in []tutil.TarEntry
508 want []check
509 }{
510 {
511 name: "1_whiteout_with_sibling",
512 in: []tutil.TarEntry{
513 tutil.Dir("foo/"),
514 tutil.File("foo/bar.txt", ""),
515 tutil.File("foo/.wh.foo.txt", ""),
516 },
517 want: []check{
518 hasValidWhiteout("foo/foo.txt"),
519 fileNotExist("foo/.wh.foo.txt"),
520 },
521 },
522 {
523 name: "1_whiteout_with_duplicated_name",
524 in: []tutil.TarEntry{
525 tutil.Dir("foo/"),
526 tutil.File("foo/bar.txt", "test"),
527 tutil.File("foo/.wh.bar.txt", ""),
528 },
529 want: []check{
530 hasFileDigest("foo/bar.txt", digestFor("test")),
531 fileNotExist("foo/.wh.bar.txt"),
532 },
533 },
534 {
535 name: "1_opaque",
536 in: []tutil.TarEntry{
537 tutil.Dir("foo/"),
538 tutil.File("foo/.wh..wh..opq", ""),
539 },
540 want: []check{
541 hasOpaque("foo/"),
542 fileNotExist("foo/.wh..wh..opq"),
543 },
544 },
545 {
546 name: "1_opaque_with_sibling",
547 in: []tutil.TarEntry{
548 tutil.Dir("foo/"),
549 tutil.File("foo/.wh..wh..opq", ""),
550 tutil.File("foo/bar.txt", "test"),
551 },
552 want: []check{
553 hasOpaque("foo/"),
554 hasFileDigest("foo/bar.txt", digestFor("test")),
555 fileNotExist("foo/.wh..wh..opq"),
556 },
557 },
558 {
559 name: "1_opaque_with_xattr",
560 in: []tutil.TarEntry{
561 tutil.Dir("foo/", tutil.WithDirXattrs(map[string]string{"foo": "bar"})),
562 tutil.File("foo/.wh..wh..opq", ""),
563 },
564 want: []check{
565 hasOpaque("foo/"),
566 hasNodeXattrs("foo/", "foo", "bar"),
567 fileNotExist("foo/.wh..wh..opq"),
568 },
569 },
570 {
571 name: "prefetch_landmark",
572 in: []tutil.TarEntry{
573 tutil.File(estargz.PrefetchLandmark, "test"),
574 tutil.Dir("foo/"),
575 tutil.File(fmt.Sprintf("foo/%s", estargz.PrefetchLandmark), "test"),
576 },
577 want: []check{
578 fileNotExist(estargz.PrefetchLandmark),
579 hasFileDigest(fmt.Sprintf("foo/%s", estargz.PrefetchLandmark), digestFor("test")),
580 },
581 },
582 {
583 name: "no_prefetch_landmark",
584 in: []tutil.TarEntry{
585 tutil.File(estargz.NoPrefetchLandmark, "test"),
586 tutil.Dir("foo/"),
587 tutil.File(fmt.Sprintf("foo/%s", estargz.NoPrefetchLandmark), "test"),
588 },
589 want: []check{
590 fileNotExist(estargz.NoPrefetchLandmark),
591 hasFileDigest(fmt.Sprintf("foo/%s", estargz.NoPrefetchLandmark), digestFor("test")),
592 },
593 },
594 {
595 name: "state_file",
596 in: []tutil.TarEntry{
597 tutil.File("test", "test"),
598 },
599 want: []check{
600 hasFileDigest("test", digestFor("test")),
601 hasStateFile(t, testStateLayerDigest.String()+".json"),
602 },
603 },
604 {
605 name: "file_suid",
606 in: []tutil.TarEntry{
607 tutil.File("test", "test", tutil.WithFileMode(0644|os.ModeSetuid)),
608 },
609 want: []check{
610 hasExtraMode("test", os.ModeSetuid),
611 },
612 },
613 {
614 name: "dir_sgid",
615 in: []tutil.TarEntry{
616 tutil.Dir("test/", tutil.WithDirMode(0755|os.ModeSetgid)),
617 },
618 want: []check{
619 hasExtraMode("test/", os.ModeSetgid),
620 },
621 },
622 {
623 name: "file_sticky",
624 in: []tutil.TarEntry{
625 tutil.File("test", "test", tutil.WithFileMode(0644|os.ModeSticky)),
626 },
627 want: []check{
628 hasExtraMode("test", os.ModeSticky),
629 },
630 },
631 {
632 name: "symlink_size",
633 in: []tutil.TarEntry{
634 tutil.Symlink("test", "target"),
635 },
636 want: []check{
637 hasSize("test", len("target")),
638 },
639 },
640 {
641 name: "several_files_in_chunk",
642 minChunkSize: 8000,
643 in: []tutil.TarEntry{
644 tutil.Dir("foo/"),
645 tutil.File("foo/foo1", data64KB),
646 tutil.File("foo2", "bb"),
647 tutil.File("foo22", "ccc"),
648 tutil.Dir("bar/"),
649 tutil.File("bar/bar.txt", "aaa"),
650 tutil.File("foo3", data64KB),
651 },
652 // NOTE: we assume that the compressed "data64KB" is still larger than 8KB
653 // landmark+dir+foo1, foo2+foo22+dir+bar.txt+foo3, TOC, footer
654 want: []check{
655 hasFileContentsWithPreCached("foo22", 0, "ccc", chunkInfo{"foo2", "bb", 0, 2}, chunkInfo{"bar/bar.txt", "aaa", 0, 3}, chunkInfo{"foo3", data64KB, 0, 64000}),
656 hasFileContentsOffset("foo2", 0, "bb", true),
657 hasFileContentsOffset("bar/bar.txt", 0, "aaa", true),
658 hasFileContentsOffset("bar/bar.txt", 1, "aa", true),
659 hasFileContentsOffset("bar/bar.txt", 2, "a", true),
660 hasFileContentsOffset("foo3", 0, data64KB, true),
661 hasFileContentsOffset("foo22", 0, "ccc", true),
662 hasFileContentsOffset("foo/foo1", 0, data64KB, false),
663 hasFileContentsOffset("foo/foo1", 0, data64KB, true),
664 hasFileContentsOffset("foo/foo1", 1, data64KB[1:], true),
665 hasFileContentsOffset("foo/foo1", 2, data64KB[2:], true),
666 hasFileContentsOffset("foo/foo1", 3, data64KB[3:], true),
667 },
668 },
669 {
670 name: "several_files_in_chunk_chunked",
671 minChunkSize: 8000,
672 chunkSize: 32000,
673 in: []tutil.TarEntry{
674 tutil.Dir("foo/"),
675 tutil.File("foo/foo1", data64KB),
676 tutil.File("foo2", "bb"),
677 tutil.Dir("bar/"),
678 tutil.File("foo3", data64KB),
679 },
680 // NOTE: we assume that the compressed chunk of "data64KB" is still larger than 8KB
681 // landmark+dir+foo1(1), foo1(2), foo2+dir+foo3(1), foo3(2), TOC, footer
682 want: []check{
683 hasFileContentsWithPreCached("foo2", 0, "bb", chunkInfo{"foo3", data64KB[:32000], 0, 32000}),
684 hasFileContentsOffset("foo2", 0, "bb", true),
685 hasFileContentsOffset("foo2", 1, "b", true),
686 hasFileContentsOffset("foo3", 0, data64KB[:len(data64KB)/2], true),
687 hasFileContentsOffset("foo3", 1, data64KB[1:len(data64KB)/2], true),
688 hasFileContentsOffset("foo3", 2, data64KB[2:len(data64KB)/2], true),
689 hasFileContentsOffset("foo3", int64(len(data64KB)/2), data64KB[len(data64KB)/2:], false),
690 hasFileContentsOffset("foo3", int64(len(data64KB)-1), data64KB[len(data64KB)-1:], true),
691 hasFileContentsOffset("foo/foo1", 0, data64KB, false),
692 hasFileContentsOffset("foo/foo1", 1, data64KB[1:], true),
693 hasFileContentsOffset("foo/foo1", 2, data64KB[2:], true),
694 hasFileContentsOffset("foo/foo1", int64(len(data64KB)/2), data64KB[len(data64KB)/2:], true),
695 hasFileContentsOffset("foo/foo1", int64(len(data64KB)-1), data64KB[len(data64KB)-1:], true),
696 },
697 },
698 }
699
700 for _, tt := range tests {
701 for _, srcCompression := range srcCompressions {
702 cl := srcCompression()
703 t.Run(tt.name, func(t *testing.T) {
704 opts := []tutil.BuildEStargzOption{
705 tutil.WithEStargzOptions(estargz.WithCompression(cl)),
706 }
707 if tt.chunkSize > 0 {
708 opts = append(opts, tutil.WithEStargzOptions(estargz.WithChunkSize(tt.chunkSize)))
709 }
710 if tt.minChunkSize > 0 {
711 opts = append(opts, tutil.WithEStargzOptions(estargz.WithMinChunkSize(tt.minChunkSize)))
712 }
713 sgz, tocDgst, err := tutil.BuildEStargz(tt.in, opts...)
714 if err != nil {
715 t.Fatalf("failed to build sample eStargz: %v", err)
716 }
717
718 testR := &calledReaderAt{sgz, nil}
719 r, err := factory(io.NewSectionReader(testR, 0, sgz.Size()), metadata.WithDecompressors(cl))
720 if err != nil {
721 t.Fatalf("failed to create reader: %v", err)
722 }
723 defer r.Close()
724 mcache := cache.NewMemoryCache()
725 rootNode := getRootNode(t, r, opaque, tocDgst, mcache)
726 for _, want := range tt.want {
727 want(t, rootNode, mcache, testR)
728 }
729 })
730 }
731 }
732 }
733
734 func getRootNode(t *testing.T, r metadata.Reader, opaque OverlayOpaqueType, tocDgst digest.Digest, cc cache.BlobCache) *node {
735 vr, err := reader.NewReader(r, cc, digest.FromString(""))
736 if err != nil {
737 t.Fatalf("failed to create reader: %v", err)
738 }
739 rr, err := vr.VerifyTOC(tocDgst)
740 if err != nil {
741 t.Fatalf("failed to verify reader: %v", err)
742 }
743 rootNode, err := newNode(testStateLayerDigest, rr, &testBlobState{10, 5}, 100, opaque)
744 if err != nil {
745 t.Fatalf("failed to get root node: %v", err)
746 }
747 fusefs.NewNodeFS(rootNode, &fusefs.Options{}) // initializes root node
748 return rootNode.(*node)
749 }
750
751 type testBlobState struct {
752 size int64
753 fetchedSize int64
754 }
755
756 func (tb *testBlobState) Check() error { return nil }
757 func (tb *testBlobState) Size() int64 { return tb.size }
758 func (tb *testBlobState) FetchedSize() int64 { return tb.fetchedSize }
759 func (tb *testBlobState) ReadAt(p []byte, offset int64, opts ...remote.Option) (int, error) {
760 return 0, nil
761 }
762 func (tb *testBlobState) Cache(offset int64, size int64, opts ...remote.Option) error { return nil }
763 func (tb *testBlobState) Refresh(ctx context.Context, host source.RegistryHosts, refspec reference.Spec, desc ocispec.Descriptor) error {
764 return nil
765 }
766 func (tb *testBlobState) Close() error { return nil }
767
768 type check func(*testing.T, *node, cache.BlobCache, *calledReaderAt)
769
770 func fileNotExist(file string) check {
771 return func(t *testing.T, root *node, cc cache.BlobCache, cr *calledReaderAt) {
772 if _, _, err := getDirentAndNode(t, root, file); err == nil {
773 t.Errorf("Node %q exists", file)
774 }
775 }
776 }
777
778 func hasFileDigest(filename string, digest string) check {
779 return func(t *testing.T, root *node, cc cache.BlobCache, cr *calledReaderAt) {
780 _, n, err := getDirentAndNode(t, root, filename)
781 if err != nil {
782 t.Fatalf("failed to get node %q: %v", filename, err)
783 }
784 ni := n.Operations().(*node)
785 attr, err := ni.fs.r.Metadata().GetAttr(ni.id)
786 if err != nil {
787 t.Fatalf("failed to get attr %q(%d): %v", filename, ni.id, err)
788 }
789 fh, _, errno := ni.Open(context.Background(), 0)
790 if errno != 0 {
791 t.Fatalf("failed to open node %q: %v", filename, errno)
792 }
793 rr, errno := fh.(*file).Read(context.Background(), make([]byte, attr.Size), 0)
794 if errno != 0 {
795 t.Fatalf("failed to read node %q: %v", filename, errno)
796 }
797 res, status := rr.Bytes(make([]byte, attr.Size))
798 if status != fuse.OK {
799 t.Fatalf("failed to get read result of node %q: %v", filename, status)
800 }
801 if ndgst := digestFor(string(res)); ndgst != digest {
802 t.Fatalf("Digest(%q) = %q, want %q", filename, ndgst, digest)
803 }
804 }
805 }
806
807 func hasSize(name string, size int) check {
808 return func(t *testing.T, root *node, cc cache.BlobCache, cr *calledReaderAt) {
809 _, n, err := getDirentAndNode(t, root, name)
810 if err != nil {
811 t.Fatalf("failed to get node %q: %v", name, err)
812 }
813 var ao fuse.AttrOut
814 if errno := n.Operations().(fusefs.NodeGetattrer).Getattr(context.Background(), nil, &ao); errno != 0 {
815 t.Fatalf("failed to get attributes of node %q: %v", name, errno)
816 }
817 if ao.Attr.Size != uint64(size) {
818 t.Fatalf("got size = %d, want %d", ao.Attr.Size, size)
819 }
820 }
821 }
822
823 func hasExtraMode(name string, mode os.FileMode) check {
824 return func(t *testing.T, root *node, cc cache.BlobCache, cr *calledReaderAt) {
825 _, n, err := getDirentAndNode(t, root, name)
826 if err != nil {
827 t.Fatalf("failed to get node %q: %v", name, err)
828 }
829 var ao fuse.AttrOut
830 if errno := n.Operations().(fusefs.NodeGetattrer).Getattr(context.Background(), nil, &ao); errno != 0 {
831 t.Fatalf("failed to get attributes of node %q: %v", name, errno)
832 }
833 a := ao.Attr
834 gotMode := a.Mode & (syscall.S_ISUID | syscall.S_ISGID | syscall.S_ISVTX)
835 wantMode := extraModeToTarMode(mode)
836 if gotMode != uint32(wantMode) {
837 t.Fatalf("got mode = %b, want %b", gotMode, wantMode)
838 }
839 }
840 }
841
842 func hasValidWhiteout(name string) check {
843 return func(t *testing.T, root *node, cc cache.BlobCache, cr *calledReaderAt) {
844 ent, n, err := getDirentAndNode(t, root, name)
845 if err != nil {
846 t.Fatalf("failed to get node %q: %v", name, err)
847 }
848 var ao fuse.AttrOut
849 if errno := n.Operations().(fusefs.NodeGetattrer).Getattr(context.Background(), nil, &ao); errno != 0 {
850 t.Fatalf("failed to get attributes of file %q: %v", name, errno)
851 }
852 a := ao.Attr
853 if a.Ino != ent.Ino {
854 t.Errorf("inconsistent inodes %d(Node) != %d(Dirent)", a.Ino, ent.Ino)
855 return
856 }
857
858 // validate the direntry
859 if ent.Mode != syscall.S_IFCHR {
860 t.Errorf("whiteout entry %q isn't a char device", name)
861 return
862 }
863
864 // validate the node
865 if a.Mode != syscall.S_IFCHR {
866 t.Errorf("whiteout %q has an invalid mode %o; want %o",
867 name, a.Mode, syscall.S_IFCHR)
868 return
869 }
870 if a.Rdev != uint32(unix.Mkdev(0, 0)) {
871 t.Errorf("whiteout %q has invalid device numbers (%d, %d); want (0, 0)",
872 name, unix.Major(uint64(a.Rdev)), unix.Minor(uint64(a.Rdev)))
873 return
874 }
875 }
876 }
877
878 func hasNodeXattrs(entry, name, value string) check {
879 return func(t *testing.T, root *node, cc cache.BlobCache, cr *calledReaderAt) {
880 _, n, err := getDirentAndNode(t, root, entry)
881 if err != nil {
882 t.Fatalf("failed to get node %q: %v", entry, err)
883 }
884
885 // check xattr exists in the xattrs list.
886 buf := make([]byte, 1000)
887 nb, errno := n.Operations().(fusefs.NodeListxattrer).Listxattr(context.Background(), buf)
888 if errno != 0 {
889 t.Fatalf("failed to get xattrs list of node %q: %v", entry, err)
890 }
891 attrs := strings.Split(string(buf[:nb]), "\x00")
892 var found bool
893 for _, x := range attrs {
894 if x == name {
895 found = true
896 }
897 }
898 if !found {
899 t.Errorf("node %q doesn't have an opaque xattr %q", entry, value)
900 return
901 }
902
903 // check the xattr has valid value.
904 v := make([]byte, len(value))
905 nv, errno := n.Operations().(fusefs.NodeGetxattrer).Getxattr(context.Background(), name, v)
906 if errno != 0 {
907 t.Fatalf("failed to get xattr %q of node %q: %v", name, entry, err)
908 }
909 if int(nv) != len(value) {
910 t.Fatalf("invalid xattr size for file %q, value %q got %d; want %d",
911 name, value, nv, len(value))
912 }
913 if string(v) != value {
914 t.Errorf("node %q has an invalid xattr %q; want %q", entry, v, value)
915 return
916 }
917 }
918 }
919
920 func hasEntry(t *testing.T, name string, ents fusefs.DirStream) (fuse.DirEntry, bool) {
921 for ents.HasNext() {
922 de, errno := ents.Next()
923 if errno != 0 {
924 t.Fatalf("faield to read entries for %q", name)
925 }
926 if de.Name == name {
927 return de, true
928 }
929 }
930 return fuse.DirEntry{}, false
931 }
932
933 func hasStateFile(t *testing.T, id string) check {
934 return func(t *testing.T, root *node, cc cache.BlobCache, cr *calledReaderAt) {
935
936 // Check the state dir is hidden on OpenDir for "/"
937 ents, errno := root.Readdir(context.Background())
938 if errno != 0 {
939 t.Errorf("failed to open root directory: %v", errno)
940 return
941 }
942 if _, ok := hasEntry(t, stateDirName, ents); ok {
943 t.Errorf("state direntry %q should not be listed", stateDirName)
944 return
945 }
946
947 // Check existence of state dir
948 var eo fuse.EntryOut
949 sti, errno := root.Lookup(context.Background(), stateDirName, &eo)
950 if errno != 0 {
951 t.Errorf("failed to lookup directory %q: %v", stateDirName, errno)
952 return
953 }
954 st, ok := sti.Operations().(*state)
955 if !ok {
956 t.Errorf("directory %q isn't a state node", stateDirName)
957 return
958 }
959
960 // Check existence of state file
961 ents, errno = st.Readdir(context.Background())
962 if errno != 0 {
963 t.Errorf("failed to open directory %q: %v", stateDirName, errno)
964 return
965 }
966 if _, ok := hasEntry(t, id, ents); !ok {
967 t.Errorf("direntry %q not found in %q", id, stateDirName)
968 return
969 }
970 inode, errno := st.Lookup(context.Background(), id, &eo)
971 if errno != 0 {
972 t.Errorf("failed to lookup node %q in %q: %v", id, stateDirName, errno)
973 return
974 }
975 n, ok := inode.Operations().(*statFile)
976 if !ok {
977 t.Errorf("entry %q isn't a normal node", id)
978 return
979 }
980
981 // wanted data
982 rand.Seed(time.Now().UnixNano())
983 wantErr := fmt.Errorf("test-%d", rand.Int63())
984
985 // report the data
986 root.fs.s.report(wantErr)
987
988 // obtain file size (check later)
989 var ao fuse.AttrOut
990 errno = n.Operations().(fusefs.NodeGetattrer).Getattr(context.Background(), nil, &ao)
991 if errno != 0 {
992 t.Errorf("failed to get attr of state file: %v", errno)
993 return
994 }
995 attr := ao.Attr
996
997 // get data via state file
998 tmp := make([]byte, 4096)
999 res, errno := n.Read(context.Background(), nil, tmp, 0)
1000 if errno != 0 {
1001 t.Errorf("failed to read state file: %v", errno)
1002 return
1003 }
1004 gotState, status := res.Bytes(nil)
1005 if status != fuse.OK {
1006 t.Errorf("failed to get result bytes of state file: %v", errno)
1007 return
1008 }
1009 if attr.Size != uint64(len(string(gotState))) {
1010 t.Errorf("size %d; want %d", attr.Size, len(string(gotState)))
1011 return
1012 }
1013
1014 var j statJSON
1015 if err := json.Unmarshal(gotState, &j); err != nil {
1016 t.Errorf("failed to unmarshal %q: %v", string(gotState), err)
1017 return
1018 }
1019 if wantErr.Error() != j.Error {
1020 t.Errorf("expected error %q, got %q", wantErr.Error(), j.Error)
1021 return
1022 }
1023 }
1024 }
1025
1026 // getDirentAndNode gets dirent and node at the specified path at once and makes
1027 // sure that the both of them exist.
1028 func getDirentAndNode(t *testing.T, root *node, path string) (ent fuse.DirEntry, n *fusefs.Inode, err error) {
1029 dir, base := filepath.Split(filepath.Clean(path))
1030
1031 // get the target's parent directory.
1032 var eo fuse.EntryOut
1033 d := root
1034 for _, name := range strings.Split(dir, "/") {
1035 if len(name) == 0 {
1036 continue
1037 }
1038 di, errno := d.Lookup(context.Background(), name, &eo)
1039 if errno != 0 {
1040 err = fmt.Errorf("failed to lookup directory %q: %v", name, errno)
1041 return
1042 }
1043 var ok bool
1044 if d, ok = di.Operations().(*node); !ok {
1045 err = fmt.Errorf("directory %q isn't a normal node", name)
1046 return
1047 }
1048
1049 }
1050
1051 // get the target's direntry.
1052 ents, errno := d.Readdir(context.Background())
1053 if errno != 0 {
1054 err = fmt.Errorf("failed to open directory %q: %v", path, errno)
1055 }
1056 ent, ok := hasEntry(t, base, ents)
1057 if !ok {
1058 err = fmt.Errorf("direntry %q not found in the parent directory of %q", base, path)
1059 }
1060
1061 // get the target's node.
1062 n, errno = d.Lookup(context.Background(), base, &eo)
1063 if errno != 0 {
1064 err = fmt.Errorf("failed to lookup node %q: %v", path, errno)
1065 }
1066
1067 return
1068 }
1069
1070 func digestFor(content string) string {
1071 sum := sha256.Sum256([]byte(content))
1072 return fmt.Sprintf("sha256:%x", sum)
1073 }
1074
1075 // suid, guid, sticky bits for archive/tar
1076 // https://github.com/golang/go/blob/release-branch.go1.13/src/archive/tar/common.go#L607-L609
1077 const (
1078 cISUID = 04000 // Set uid
1079 cISGID = 02000 // Set gid
1080 cISVTX = 01000 // Save text (sticky bit)
1081 )
1082
1083 func extraModeToTarMode(fm os.FileMode) (tm int64) {
1084 if fm&os.ModeSetuid != 0 {
1085 tm |= cISUID
1086 }
1087 if fm&os.ModeSetgid != 0 {
1088 tm |= cISGID
1089 }
1090 if fm&os.ModeSticky != 0 {
1091 tm |= cISVTX
1092 }
1093 return
1094 }
1095
1096 type chunkInfo struct {
1097 name string
1098 data string
1099 chunkOffset int64
1100 chunkSize int64
1101 }
1102
1103 func hasFileContentsWithPreCached(name string, off int64, contents string, extra ...chunkInfo) check {
1104 return func(t *testing.T, root *node, cc cache.BlobCache, cr *calledReaderAt) {
1105 buf := readFile(t, root, name, int64(len(contents)), off)
1106 if len(buf) != len(contents) {
1107 t.Fatalf("failed to read contents %q (off:%d, want:%q) got %q", name, off, longBytesView([]byte(contents)), longBytesView(buf))
1108 }
1109 if string(buf) != contents {
1110 t.Fatalf("unexpected content of %q: %q want %q", name, longBytesView(buf), longBytesView([]byte(contents)))
1111 }
1112 for _, e := range extra {
1113 cr.called = nil // reset test
1114 data := readFile(t, root, e.name, e.chunkSize, e.chunkOffset)
1115 if string(data) != e.data {
1116 t.Fatalf("unexpected contents of %q (%+v): %q; wanted %q", e.name, e, longBytesView(data), longBytesView([]byte(e.data)))
1117 }
1118 if len(cr.called) != 0 {
1119 t.Fatalf("unexpected read on %q: offsets: %v", e.name, cr.called)
1120 }
1121 }
1122 }
1123 }
1124
1125 func hasFileContentsOffset(name string, off int64, contents string, fromCache bool) check {
1126 return func(t *testing.T, root *node, cc cache.BlobCache, cr *calledReaderAt) {
1127 cr.called = nil // reset test
1128 buf := readFile(t, root, name, int64(len(contents)), off)
1129 if len(buf) != len(contents) {
1130 t.Fatalf("failed to read contents %q (off:%d, want:%q) got %q", name, off, longBytesView([]byte(contents)), longBytesView(buf))
1131 }
1132 if string(buf) != contents {
1133 t.Fatalf("unexpected content of %q: %q want %q", name, longBytesView(buf), longBytesView([]byte(contents)))
1134 }
1135 t.Logf("reader calls for %q: offsets: %+v", name, cr.called)
1136 if fromCache {
1137 if len(cr.called) != 0 {
1138 t.Fatalf("unexpected read on %q: offsets: %v", name, cr.called)
1139 }
1140 } else {
1141 if len(cr.called) == 0 {
1142 t.Fatalf("no call happened to reader for %q", name)
1143 }
1144 }
1145 }
1146 }
1147
1148 func readFile(t *testing.T, root *node, filename string, size, off int64) []byte {
1149 _, n, err := getDirentAndNode(t, root, filename)
1150 if err != nil {
1151 t.Fatalf("failed to get node %q: %v", filename, err)
1152 }
1153 ni := n.Operations().(*node)
1154 fh, _, errno := ni.Open(context.Background(), 0)
1155 if errno != 0 {
1156 t.Fatalf("failed to open node %q: %v", filename, errno)
1157 }
1158 rr, errno := fh.(*file).Read(context.Background(), make([]byte, size), off)
1159 if errno != 0 {
1160 t.Fatalf("failed to read node %q: %v", filename, errno)
1161 }
1162 buf, status := rr.Bytes(make([]byte, size))
1163 if status != fuse.OK {
1164 t.Fatalf("failed to get read result of node %q: %v", filename, status)
1165 }
1166 return buf
1167 }
1168
1169 type calledReaderAt struct {
1170 io.ReaderAt
1171 called []int64
1172 }
1173
1174 func (r *calledReaderAt) ReadAt(p []byte, off int64) (int, error) {
1175 r.called = append(r.called, off)
1176 return r.ReaderAt.ReadAt(p, off)
1177 }
1178
1179 // longBytesView is an alias of []byte suitable for printing a long data as an omitted string to avoid long data being printed.
1180 type longBytesView []byte
1181
1182 func (b longBytesView) String() string {
1183 if len(b) < 100 {
1184 return string(b)
1185 }
1186 return string(b[:50]) + "...(omit)..." + string(b[len(b)-50:])
1187 }