| 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 |
"bytes" |
| 27 |
"compress/gzip" |
| 28 |
"fmt" |
| 29 |
"io" |
| 30 |
"os" |
| 31 |
"path" |
| 32 |
"path/filepath" |
| 33 |
"strings" |
| 34 |
"sync" |
| 35 |
"testing" |
| 36 |
"time" |
| 37 |
|
| 38 |
"github.com/containerd/stargz-snapshotter/cache" |
| 39 |
"github.com/containerd/stargz-snapshotter/estargz" |
| 40 |
"github.com/containerd/stargz-snapshotter/metadata" |
| 41 |
"github.com/containerd/stargz-snapshotter/util/testutil" |
| 42 |
tutil "github.com/containerd/stargz-snapshotter/util/testutil" |
| 43 |
"github.com/klauspost/compress/zstd" |
| 44 |
digest "github.com/opencontainers/go-digest" |
| 45 |
"golang.org/x/sync/errgroup" |
| 46 |
) |
| 47 |
|
| 48 |
type region struct{ b, e int64 } |
| 49 |
|
| 50 |
const ( |
| 51 |
sampleChunkSize = 3 |
| 52 |
sampleMiddleOffset = sampleChunkSize / 2 |
| 53 |
sampleData1 = "0123456789" |
| 54 |
lastChunkOffset1 = sampleChunkSize * (int64(len(sampleData1)) / sampleChunkSize) |
| 55 |
) |
| 56 |
|
| 57 |
var srcCompressions = map[string]tutil.CompressionFactory{ |
| 58 |
"zstd-fastest": tutil.ZstdCompressionWithLevel(zstd.SpeedFastest), |
| 59 |
"gzip-bestspeed": tutil.GzipCompressionWithLevel(gzip.BestSpeed), |
| 60 |
"externaltoc-gzip-bestspeed": tutil.ExternalTOCGzipCompressionWithLevel(gzip.BestSpeed), |
| 61 |
} |
| 62 |
|
| 63 |
func TestSuiteReader(t *testing.T, store metadata.Store) { |
| 64 |
testFileReadAt(t, store) |
| 65 |
testCacheVerify(t, store) |
| 66 |
testFailReader(t, store) |
| 67 |
testPreReader(t, store) |
| 68 |
} |
| 69 |
|
| 70 |
func testFileReadAt(t *testing.T, factory metadata.Store) { |
| 71 |
sizeCond := map[string]int64{ |
| 72 |
"single_chunk": sampleChunkSize - sampleMiddleOffset, |
| 73 |
"multi_chunks": sampleChunkSize + sampleMiddleOffset, |
| 74 |
} |
| 75 |
innerOffsetCond := map[string]int64{ |
| 76 |
"at_top": 0, |
| 77 |
"at_middle": sampleMiddleOffset, |
| 78 |
} |
| 79 |
baseOffsetCond := map[string]int64{ |
| 80 |
"of_1st_chunk": sampleChunkSize * 0, |
| 81 |
"of_2nd_chunk": sampleChunkSize * 1, |
| 82 |
"of_last_chunk": lastChunkOffset1, |
| 83 |
} |
| 84 |
fileSizeCond := map[string]int64{ |
| 85 |
"in_1_chunk_file": sampleChunkSize * 1, |
| 86 |
"in_2_chunks_file": sampleChunkSize * 2, |
| 87 |
"in_max_size_file": int64(len(sampleData1)), |
| 88 |
} |
| 89 |
cacheCond := map[string][]region{ |
| 90 |
"with_clean_cache": nil, |
| 91 |
"with_edge_filled_cache": { |
| 92 |
region{0, sampleChunkSize - 1}, |
| 93 |
region{lastChunkOffset1, int64(len(sampleData1)) - 1}, |
| 94 |
}, |
| 95 |
"with_sparse_cache": { |
| 96 |
region{0, sampleChunkSize - 1}, |
| 97 |
region{2 * sampleChunkSize, 3*sampleChunkSize - 1}, |
| 98 |
}, |
| 99 |
} |
| 100 |
for sn, size := range sizeCond { |
| 101 |
for in, innero := range innerOffsetCond { |
| 102 |
for bo, baseo := range baseOffsetCond { |
| 103 |
for fn, filesize := range fileSizeCond { |
| 104 |
for cc, cacheExcept := range cacheCond { |
| 105 |
for srcCompressionName, srcCompression := range srcCompressions { |
| 106 |
srcCompression := srcCompression() |
| 107 |
t.Run(fmt.Sprintf("reading_%s_%s_%s_%s_%s_%s", sn, in, bo, fn, cc, srcCompressionName), func(t *testing.T) { |
| 108 |
if filesize > int64(len(sampleData1)) { |
| 109 |
t.Fatal("sample file size is larger than sample data") |
| 110 |
} |
| 111 |
|
| 112 |
wantN := size |
| 113 |
offset := baseo + innero |
| 114 |
if remain := filesize - offset; remain < wantN { |
| 115 |
if wantN = remain; wantN < 0 { |
| 116 |
wantN = 0 |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
// use constant string value as a data source. |
| 121 |
want := strings.NewReader(sampleData1) |
| 122 |
|
| 123 |
// data we want to get. |
| 124 |
wantData := make([]byte, wantN) |
| 125 |
_, err := want.ReadAt(wantData, offset) |
| 126 |
if err != nil && err != io.EOF { |
| 127 |
t.Fatalf("want.ReadAt (offset=%d,size=%d): %v", offset, wantN, err) |
| 128 |
} |
| 129 |
|
| 130 |
// data we get through a file. |
| 131 |
f, closeFn := makeFile(t, []byte(sampleData1)[:filesize], sampleChunkSize, factory, srcCompression) |
| 132 |
defer closeFn() |
| 133 |
f.fr = newExceptFile(t, f.fr, cacheExcept...) |
| 134 |
for _, reg := range cacheExcept { |
| 135 |
id := genID(f.id, reg.b, reg.e-reg.b+1) |
| 136 |
w, err := f.gr.cache.Add(id) |
| 137 |
if err != nil { |
| 138 |
w.Close() |
| 139 |
t.Fatalf("failed to add cache %v: %v", id, err) |
| 140 |
} |
| 141 |
if _, err := w.Write([]byte(sampleData1[reg.b : reg.e+1])); err != nil { |
| 142 |
w.Close() |
| 143 |
t.Fatalf("failed to write cache %v: %v", id, err) |
| 144 |
} |
| 145 |
if err := w.Commit(); err != nil { |
| 146 |
w.Close() |
| 147 |
t.Fatalf("failed to commit cache %v: %v", id, err) |
| 148 |
} |
| 149 |
w.Close() |
| 150 |
} |
| 151 |
respData := make([]byte, size) |
| 152 |
n, err := f.ReadAt(respData, offset) |
| 153 |
if err != nil { |
| 154 |
t.Errorf("failed to read off=%d, size=%d, filesize=%d: %v", offset, size, filesize, err) |
| 155 |
return |
| 156 |
} |
| 157 |
respData = respData[:n] |
| 158 |
|
| 159 |
if !bytes.Equal(wantData, respData) { |
| 160 |
t.Errorf("off=%d, filesize=%d; read data{size=%d,data=%q}; want (size=%d,data=%q)", |
| 161 |
offset, filesize, len(respData), string(respData), wantN, string(wantData)) |
| 162 |
return |
| 163 |
} |
| 164 |
|
| 165 |
// check cache has valid contents. |
| 166 |
cn := 0 |
| 167 |
nr := 0 |
| 168 |
for int64(nr) < wantN { |
| 169 |
chunkOffset, chunkSize, _, ok := f.fr.ChunkEntryForOffset(offset + int64(nr)) |
| 170 |
if !ok { |
| 171 |
break |
| 172 |
} |
| 173 |
data := make([]byte, chunkSize) |
| 174 |
id := genID(f.id, chunkOffset, chunkSize) |
| 175 |
r, err := f.gr.cache.Get(id) |
| 176 |
if err != nil { |
| 177 |
t.Errorf("missed cache of offset=%d, size=%d: %v(got size=%d)", chunkOffset, chunkSize, err, n) |
| 178 |
return |
| 179 |
} |
| 180 |
defer r.Close() |
| 181 |
if n, err := r.ReadAt(data, 0); (err != nil && err != io.EOF) || n != int(chunkSize) { |
| 182 |
t.Errorf("failed to read cache of offset=%d, size=%d: %v(got size=%d)", chunkOffset, chunkSize, err, n) |
| 183 |
return |
| 184 |
} |
| 185 |
nr += n |
| 186 |
cn++ |
| 187 |
} |
| 188 |
}) |
| 189 |
} |
| 190 |
} |
| 191 |
} |
| 192 |
} |
| 193 |
} |
| 194 |
} |
| 195 |
} |
| 196 |
|
| 197 |
func newExceptFile(t *testing.T, fr metadata.File, except ...region) metadata.File { |
| 198 |
er := exceptFile{fr: fr, t: t} |
| 199 |
er.except = map[region]bool{} |
| 200 |
for _, reg := range except { |
| 201 |
er.except[reg] = true |
| 202 |
} |
| 203 |
return &er |
| 204 |
} |
| 205 |
|
| 206 |
type exceptFile struct { |
| 207 |
fr metadata.File |
| 208 |
except map[region]bool |
| 209 |
t *testing.T |
| 210 |
} |
| 211 |
|
| 212 |
func (er *exceptFile) ReadAt(p []byte, offset int64) (int, error) { |
| 213 |
if er.except[region{offset, offset + int64(len(p)) - 1}] { |
| 214 |
er.t.Fatalf("Requested prohibited region of chunk: (%d, %d)", offset, offset+int64(len(p))-1) |
| 215 |
} |
| 216 |
return er.fr.ReadAt(p, offset) |
| 217 |
} |
| 218 |
|
| 219 |
func (er *exceptFile) ChunkEntryForOffset(offset int64) (off int64, size int64, dgst string, ok bool) { |
| 220 |
return er.fr.ChunkEntryForOffset(offset) |
| 221 |
} |
| 222 |
|
| 223 |
func makeFile(t *testing.T, contents []byte, chunkSize int, factory metadata.Store, comp tutil.Compression) (*file, func() error) { |
| 224 |
testName := "test" |
| 225 |
sr, dgst, err := testutil.BuildEStargz([]testutil.TarEntry{ |
| 226 |
testutil.File(testName, string(contents)), |
| 227 |
}, testutil.WithEStargzOptions(estargz.WithChunkSize(chunkSize), estargz.WithCompression(comp))) |
| 228 |
if err != nil { |
| 229 |
t.Fatalf("failed to build sample estargz") |
| 230 |
} |
| 231 |
mr, err := factory(sr, metadata.WithDecompressors(comp)) |
| 232 |
if err != nil { |
| 233 |
t.Fatalf("failed to create reader: %v", err) |
| 234 |
} |
| 235 |
vr, err := NewReader(mr, cache.NewMemoryCache(), digest.FromString("")) |
| 236 |
if err != nil { |
| 237 |
mr.Close() |
| 238 |
t.Fatalf("failed to make new reader: %v", err) |
| 239 |
} |
| 240 |
r, err := vr.VerifyTOC(dgst) |
| 241 |
if err != nil { |
| 242 |
vr.Close() |
| 243 |
t.Fatalf("failed to verify TOC: %v", err) |
| 244 |
} |
| 245 |
tid, _, err := r.Metadata().GetChild(r.Metadata().RootID(), testName) |
| 246 |
if err != nil { |
| 247 |
vr.Close() |
| 248 |
t.Fatalf("failed to get %q: %v", testName, err) |
| 249 |
} |
| 250 |
ra, err := r.OpenFile(tid) |
| 251 |
if err != nil { |
| 252 |
vr.Close() |
| 253 |
t.Fatalf("Failed to open testing file: %v", err) |
| 254 |
} |
| 255 |
f, ok := ra.(*file) |
| 256 |
if !ok { |
| 257 |
vr.Close() |
| 258 |
t.Fatalf("invalid type of file %q", tid) |
| 259 |
} |
| 260 |
return f, vr.Close |
| 261 |
} |
| 262 |
|
| 263 |
func testCacheVerify(t *testing.T, factory metadata.Store) { |
| 264 |
for _, skipVerify := range [2]bool{true, false} { |
| 265 |
for _, invalidChunkBeforeVerify := range [2]bool{true, false} { |
| 266 |
for _, invalidChunkAfterVerify := range [2]bool{true, false} { |
| 267 |
for srcCompressionName, srcCompression := range srcCompressions { |
| 268 |
srcCompression := srcCompression() |
| 269 |
name := fmt.Sprintf("test_cache_verify_%v_%v_%v_%v", |
| 270 |
skipVerify, invalidChunkBeforeVerify, invalidChunkAfterVerify, srcCompressionName) |
| 271 |
t.Run(name, func(t *testing.T) { |
| 272 |
sr, tocDgst, err := testutil.BuildEStargz([]testutil.TarEntry{ |
| 273 |
testutil.File("a", sampleData1+"a"), |
| 274 |
testutil.File("b", sampleData1+"b"), |
| 275 |
}, testutil.WithEStargzOptions(estargz.WithChunkSize(sampleChunkSize), estargz.WithCompression(srcCompression))) |
| 276 |
if err != nil { |
| 277 |
t.Fatalf("failed to build sample estargz") |
| 278 |
} |
| 279 |
|
| 280 |
// Determine the expected behaviour |
| 281 |
var wantVerifyFail, wantCacheFail, wantCacheFail2 bool |
| 282 |
if skipVerify { |
| 283 |
// always no error if verification is disabled |
| 284 |
wantVerifyFail, wantCacheFail, wantCacheFail2 = false, false, false |
| 285 |
} else if invalidChunkBeforeVerify { |
| 286 |
// errors occurred before verifying TOC must be reported via VerifyTOC() |
| 287 |
wantVerifyFail = true |
| 288 |
} else if invalidChunkAfterVerify { |
| 289 |
// errors occurred after verifying TOC must be reported via Cache() |
| 290 |
wantVerifyFail, wantCacheFail, wantCacheFail2 = false, true, true |
| 291 |
} else { |
| 292 |
// otherwise no verification error |
| 293 |
wantVerifyFail, wantCacheFail, wantCacheFail2 = false, false, false |
| 294 |
} |
| 295 |
|
| 296 |
// Prepare reader |
| 297 |
verifier := &failIDVerifier{} |
| 298 |
mr, err := factory(sr, metadata.WithDecompressors(srcCompression)) |
| 299 |
if err != nil { |
| 300 |
t.Fatalf("failed to prepare reader %v", err) |
| 301 |
} |
| 302 |
defer mr.Close() |
| 303 |
vr, err := NewReader(mr, cache.NewMemoryCache(), digest.FromString("")) |
| 304 |
if err != nil { |
| 305 |
t.Fatalf("failed to make new reader: %v", err) |
| 306 |
} |
| 307 |
if verifier != nil { |
| 308 |
vr.verifier = verifier.verifier |
| 309 |
vr.r.verifier = verifier.verifier |
| 310 |
} |
| 311 |
|
| 312 |
off2id, id2path, err := prepareMap(vr.Metadata(), vr.Metadata().RootID(), "") |
| 313 |
if err != nil || off2id == nil || id2path == nil { |
| 314 |
t.Fatalf("failed to prepare offset map %v, off2id = %+v, id2path = %+v", err, off2id, id2path) |
| 315 |
} |
| 316 |
|
| 317 |
// Perform Cache() before verification |
| 318 |
// 1. Either of "a" or "b" is read and verified |
| 319 |
// 2. VerifyTOC/SkipVerify is called |
| 320 |
// 3. Another entry ("a" or "b") is called |
| 321 |
verifyDone := make(chan struct{}) |
| 322 |
var firstEntryCalled bool |
| 323 |
var eg errgroup.Group |
| 324 |
var mu sync.Mutex |
| 325 |
eg.Go(func() error { |
| 326 |
return vr.Cache(WithFilter(func(off int64) bool { |
| 327 |
id, ok := off2id[off] |
| 328 |
if !ok { |
| 329 |
t.Fatalf("no ID is assigned to offset %d", off) |
| 330 |
} |
| 331 |
name, ok := id2path[id] |
| 332 |
if !ok { |
| 333 |
t.Fatalf("no name is assigned to id %d", id) |
| 334 |
} |
| 335 |
if name == "a" || name == "b" { |
| 336 |
mu.Lock() |
| 337 |
if !firstEntryCalled { |
| 338 |
firstEntryCalled = true |
| 339 |
if invalidChunkBeforeVerify { |
| 340 |
verifier.registerFails([]uint32{id}) |
| 341 |
} |
| 342 |
mu.Unlock() |
| 343 |
return true |
| 344 |
} |
| 345 |
mu.Unlock() |
| 346 |
<-verifyDone |
| 347 |
if invalidChunkAfterVerify { |
| 348 |
verifier.registerFails([]uint32{id}) |
| 349 |
} |
| 350 |
return true |
| 351 |
} |
| 352 |
return false |
| 353 |
})) |
| 354 |
}) |
| 355 |
if invalidChunkBeforeVerify { |
| 356 |
// wait for encountering the error of the first chunk read |
| 357 |
start := time.Now() |
| 358 |
for { |
| 359 |
if err := vr.loadLastVerifyErr(); err != nil { |
| 360 |
break |
| 361 |
} |
| 362 |
if time.Since(start) > time.Second { |
| 363 |
t.Fatalf("timeout(1s): failed to wait for read error is registered") |
| 364 |
} |
| 365 |
time.Sleep(10 * time.Millisecond) |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
// Perform verification |
| 370 |
if skipVerify { |
| 371 |
vr.SkipVerify() |
| 372 |
} else { |
| 373 |
_, err = vr.VerifyTOC(tocDgst) |
| 374 |
} |
| 375 |
if checkErr := checkError(wantVerifyFail, err); checkErr != nil { |
| 376 |
t.Errorf("verify: %v", checkErr) |
| 377 |
return |
| 378 |
} |
| 379 |
if err != nil { |
| 380 |
return |
| 381 |
} |
| 382 |
close(verifyDone) |
| 383 |
|
| 384 |
// Check the result of Cache() |
| 385 |
if checkErr := checkError(wantCacheFail, eg.Wait()); checkErr != nil { |
| 386 |
t.Errorf("cache: %v", checkErr) |
| 387 |
return |
| 388 |
} |
| 389 |
|
| 390 |
// Call Cache() again and check the result |
| 391 |
if checkErr := checkError(wantCacheFail2, vr.Cache()); checkErr != nil { |
| 392 |
t.Errorf("cache(2): %v", checkErr) |
| 393 |
return |
| 394 |
} |
| 395 |
}) |
| 396 |
} |
| 397 |
} |
| 398 |
} |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
type failIDVerifier struct { |
| 403 |
fails []uint32 |
| 404 |
failsMu sync.Mutex |
| 405 |
} |
| 406 |
|
| 407 |
func (f *failIDVerifier) registerFails(fails []uint32) { |
| 408 |
f.failsMu.Lock() |
| 409 |
defer f.failsMu.Unlock() |
| 410 |
f.fails = fails |
| 411 |
|
| 412 |
} |
| 413 |
|
| 414 |
func (f *failIDVerifier) verifier(id uint32, chunkDigest string) (digest.Verifier, error) { |
| 415 |
f.failsMu.Lock() |
| 416 |
defer f.failsMu.Unlock() |
| 417 |
success := true |
| 418 |
for _, n := range f.fails { |
| 419 |
if n == id { |
| 420 |
success = false |
| 421 |
break |
| 422 |
} |
| 423 |
} |
| 424 |
return &testVerifier{success}, nil |
| 425 |
} |
| 426 |
|
| 427 |
type testVerifier struct { |
| 428 |
success bool |
| 429 |
} |
| 430 |
|
| 431 |
func (bv *testVerifier) Write(p []byte) (n int, err error) { |
| 432 |
return len(p), nil |
| 433 |
} |
| 434 |
|
| 435 |
func (bv *testVerifier) Verified() bool { |
| 436 |
return bv.success |
| 437 |
} |
| 438 |
|
| 439 |
func checkError(wantFail bool, err error) error { |
| 440 |
if wantFail && err == nil { |
| 441 |
return fmt.Errorf("wanted to fail but succeeded") |
| 442 |
} else if !wantFail && err != nil { |
| 443 |
return fmt.Errorf("wanted to succeed verification but failed: %w", err) |
| 444 |
} |
| 445 |
return nil |
| 446 |
} |
| 447 |
|
| 448 |
func prepareMap(mr metadata.Reader, id uint32, p string) (off2id map[int64]uint32, id2path map[uint32]string, _ error) { |
| 449 |
attr, err := mr.GetAttr(id) |
| 450 |
if err != nil { |
| 451 |
return nil, nil, err |
| 452 |
} |
| 453 |
id2path = map[uint32]string{id: p} |
| 454 |
off2id = make(map[int64]uint32) |
| 455 |
if attr.Mode.IsRegular() { |
| 456 |
off, err := mr.GetOffset(id) |
| 457 |
if err != nil { |
| 458 |
return nil, nil, err |
| 459 |
} |
| 460 |
off2id[off] = id |
| 461 |
} |
| 462 |
var retErr error |
| 463 |
mr.ForeachChild(id, func(name string, id uint32, mode os.FileMode) bool { |
| 464 |
o2i, i2p, err := prepareMap(mr, id, path.Join(p, name)) |
| 465 |
if err != nil { |
| 466 |
retErr = err |
| 467 |
return false |
| 468 |
} |
| 469 |
for k, v := range o2i { |
| 470 |
off2id[k] = v |
| 471 |
} |
| 472 |
for k, v := range i2p { |
| 473 |
id2path[k] = v |
| 474 |
} |
| 475 |
return true |
| 476 |
}) |
| 477 |
if retErr != nil { |
| 478 |
return nil, nil, retErr |
| 479 |
} |
| 480 |
return off2id, id2path, nil |
| 481 |
} |
| 482 |
|
| 483 |
func testFailReader(t *testing.T, factory metadata.Store) { |
| 484 |
testFileName := "test" |
| 485 |
for srcCompressionName, srcCompression := range srcCompressions { |
| 486 |
srcCompression := srcCompression() |
| 487 |
t.Run(fmt.Sprintf("%v", srcCompressionName), func(t *testing.T) { |
| 488 |
for _, rs := range []bool{true, false} { |
| 489 |
for _, vs := range []bool{true, false} { |
| 490 |
stargzFile, tocDigest, err := testutil.BuildEStargz([]testutil.TarEntry{ |
| 491 |
testutil.File(testFileName, sampleData1), |
| 492 |
}, testutil.WithEStargzOptions(estargz.WithChunkSize(sampleChunkSize), estargz.WithCompression(srcCompression))) |
| 493 |
if err != nil { |
| 494 |
t.Fatalf("failed to build sample estargz") |
| 495 |
} |
| 496 |
|
| 497 |
br := &breakReaderAt{ |
| 498 |
ReaderAt: stargzFile, |
| 499 |
success: true, |
| 500 |
} |
| 501 |
bev := &testChunkVerifier{true} |
| 502 |
mcache := cache.NewMemoryCache() |
| 503 |
mr, err := factory(io.NewSectionReader(br, 0, stargzFile.Size()), metadata.WithDecompressors(srcCompression)) |
| 504 |
if err != nil { |
| 505 |
t.Fatalf("failed to prepare metadata reader") |
| 506 |
} |
| 507 |
defer mr.Close() |
| 508 |
vr, err := NewReader(mr, mcache, digest.FromString("")) |
| 509 |
if err != nil { |
| 510 |
t.Fatalf("failed to make new reader: %v", err) |
| 511 |
} |
| 512 |
defer vr.Close() |
| 513 |
vr.verifier = bev.verifier |
| 514 |
vr.r.verifier = bev.verifier |
| 515 |
gr, err := vr.VerifyTOC(tocDigest) |
| 516 |
if err != nil { |
| 517 |
t.Fatalf("failed to verify TOC: %v", err) |
| 518 |
} |
| 519 |
|
| 520 |
notexist := uint32(0) |
| 521 |
found := false |
| 522 |
for i := uint32(0); i < 1000000; i++ { |
| 523 |
if _, err := gr.Metadata().GetAttr(i); err != nil { |
| 524 |
notexist, found = i, true |
| 525 |
break |
| 526 |
} |
| 527 |
} |
| 528 |
if !found { |
| 529 |
t.Fatalf("free ID not found") |
| 530 |
} |
| 531 |
|
| 532 |
// tests for opening non-existing file |
| 533 |
_, err = gr.OpenFile(notexist) |
| 534 |
if err == nil { |
| 535 |
t.Errorf("succeeded to open file but wanted to fail") |
| 536 |
return |
| 537 |
} |
| 538 |
|
| 539 |
// tests failure behaviour of a file read |
| 540 |
tid, _, err := gr.Metadata().GetChild(gr.Metadata().RootID(), testFileName) |
| 541 |
if err != nil { |
| 542 |
t.Errorf("failed to get %q: %v", testFileName, err) |
| 543 |
return |
| 544 |
} |
| 545 |
fr, err := gr.OpenFile(tid) |
| 546 |
if err != nil { |
| 547 |
t.Errorf("failed to open file but wanted to succeed: %v", err) |
| 548 |
return |
| 549 |
} |
| 550 |
|
| 551 |
mcache.(*cache.MemoryCache).Membuf = map[string]*bytes.Buffer{} |
| 552 |
br.success = rs |
| 553 |
bev.success = vs |
| 554 |
|
| 555 |
// tests for reading file |
| 556 |
p := make([]byte, len(sampleData1)) |
| 557 |
n, err := fr.ReadAt(p, 0) |
| 558 |
if rs && vs { |
| 559 |
if err != nil || n != len(sampleData1) || !bytes.Equal([]byte(sampleData1), p) { |
| 560 |
t.Errorf("failed to read data but wanted to succeed: %v", err) |
| 561 |
return |
| 562 |
} |
| 563 |
} else { |
| 564 |
if err == nil { |
| 565 |
t.Errorf("succeeded to read data but wanted to fail (reader:%v,verify:%v)", rs, vs) |
| 566 |
return |
| 567 |
} |
| 568 |
} |
| 569 |
} |
| 570 |
} |
| 571 |
}) |
| 572 |
} |
| 573 |
} |
| 574 |
|
| 575 |
type breakReaderAt struct { |
| 576 |
io.ReaderAt |
| 577 |
success bool |
| 578 |
} |
| 579 |
|
| 580 |
func (br *breakReaderAt) ReadAt(p []byte, off int64) (int, error) { |
| 581 |
if br.success { |
| 582 |
return br.ReaderAt.ReadAt(p, off) |
| 583 |
} |
| 584 |
return 0, fmt.Errorf("failed") |
| 585 |
} |
| 586 |
|
| 587 |
type testChunkVerifier struct { |
| 588 |
success bool |
| 589 |
} |
| 590 |
|
| 591 |
func (bev *testChunkVerifier) verifier(id uint32, chunkDigest string) (digest.Verifier, error) { |
| 592 |
return &testVerifier{bev.success}, nil |
| 593 |
} |
| 594 |
|
| 595 |
func testPreReader(t *testing.T, factory metadata.Store) { |
| 596 |
data64KB := string(tutil.RandomBytes(t, 64000)) |
| 597 |
tests := []struct { |
| 598 |
name string |
| 599 |
chunkSize int |
| 600 |
minChunkSize int |
| 601 |
in []tutil.TarEntry |
| 602 |
want []check |
| 603 |
}{ |
| 604 |
{ |
| 605 |
name: "several_files_in_chunk", |
| 606 |
minChunkSize: 8000, |
| 607 |
in: []tutil.TarEntry{ |
| 608 |
tutil.Dir("foo/"), |
| 609 |
tutil.File("foo/foo1", data64KB), |
| 610 |
tutil.File("foo2", "bb"), |
| 611 |
tutil.File("foo22", "ccc"), |
| 612 |
tutil.Dir("bar/"), |
| 613 |
tutil.File("bar/bar.txt", "aaa"), |
| 614 |
tutil.File("foo3", data64KB), |
| 615 |
}, |
| 616 |
// NOTE: we assume that the compressed "data64KB" is still larger than 8KB |
| 617 |
// landmark+dir+foo1, foo2+foo22+dir+bar.txt+foo3, TOC, footer |
| 618 |
want: []check{ |
| 619 |
hasFileContentsWithPreCached("foo22", 0, "ccc", chunkInfo{"foo2", "bb", 0, 2}, chunkInfo{"bar/bar.txt", "aaa", 0, 3}, chunkInfo{"foo3", data64KB, 0, 64000}), |
| 620 |
hasFileContentsOffset("foo2", 0, "bb", true), |
| 621 |
hasFileContentsOffset("bar/bar.txt", 0, "aaa", true), |
| 622 |
hasFileContentsOffset("bar/bar.txt", 1, "aa", true), |
| 623 |
hasFileContentsOffset("bar/bar.txt", 2, "a", true), |
| 624 |
hasFileContentsOffset("foo3", 0, data64KB, true), |
| 625 |
hasFileContentsOffset("foo22", 0, "ccc", true), |
| 626 |
hasFileContentsOffset("foo/foo1", 0, data64KB, false), |
| 627 |
hasFileContentsOffset("foo/foo1", 0, data64KB, true), |
| 628 |
hasFileContentsOffset("foo/foo1", 1, data64KB[1:], true), |
| 629 |
hasFileContentsOffset("foo/foo1", 2, data64KB[2:], true), |
| 630 |
hasFileContentsOffset("foo/foo1", 3, data64KB[3:], true), |
| 631 |
}, |
| 632 |
}, |
| 633 |
{ |
| 634 |
name: "several_files_in_chunk_chunked", |
| 635 |
minChunkSize: 8000, |
| 636 |
chunkSize: 32000, |
| 637 |
in: []tutil.TarEntry{ |
| 638 |
tutil.Dir("foo/"), |
| 639 |
tutil.File("foo/foo1", data64KB), |
| 640 |
tutil.File("foo2", "bb"), |
| 641 |
tutil.Dir("bar/"), |
| 642 |
tutil.File("foo3", data64KB), |
| 643 |
}, |
| 644 |
// NOTE: we assume that the compressed chunk of "data64KB" is still larger than 8KB |
| 645 |
// landmark+dir+foo1(1), foo1(2), foo2+dir+foo3(1), foo3(2), TOC, footer |
| 646 |
want: []check{ |
| 647 |
hasFileContentsWithPreCached("foo2", 0, "bb", chunkInfo{"foo3", data64KB[:32000], 0, 32000}), |
| 648 |
hasFileContentsOffset("foo2", 0, "bb", true), |
| 649 |
hasFileContentsOffset("foo2", 1, "b", true), |
| 650 |
hasFileContentsOffset("foo3", 0, data64KB[:len(data64KB)/2], true), |
| 651 |
hasFileContentsOffset("foo3", 1, data64KB[1:len(data64KB)/2], true), |
| 652 |
hasFileContentsOffset("foo3", 2, data64KB[2:len(data64KB)/2], true), |
| 653 |
hasFileContentsOffset("foo3", int64(len(data64KB)/2), data64KB[len(data64KB)/2:], false), |
| 654 |
hasFileContentsOffset("foo3", int64(len(data64KB)-1), data64KB[len(data64KB)-1:], true), |
| 655 |
hasFileContentsOffset("foo/foo1", 0, data64KB, false), |
| 656 |
hasFileContentsOffset("foo/foo1", 1, data64KB[1:], true), |
| 657 |
hasFileContentsOffset("foo/foo1", 2, data64KB[2:], true), |
| 658 |
hasFileContentsOffset("foo/foo1", int64(len(data64KB)/2), data64KB[len(data64KB)/2:], true), |
| 659 |
hasFileContentsOffset("foo/foo1", int64(len(data64KB)-1), data64KB[len(data64KB)-1:], true), |
| 660 |
}, |
| 661 |
}, |
| 662 |
} |
| 663 |
for _, tt := range tests { |
| 664 |
for srcCompresionName, srcCompression := range srcCompressions { |
| 665 |
srcCompression := srcCompression() |
| 666 |
t.Run(tt.name+"-"+srcCompresionName, func(t *testing.T) { |
| 667 |
opts := []tutil.BuildEStargzOption{ |
| 668 |
tutil.WithEStargzOptions(estargz.WithCompression(srcCompression)), |
| 669 |
} |
| 670 |
if tt.chunkSize > 0 { |
| 671 |
opts = append(opts, tutil.WithEStargzOptions(estargz.WithChunkSize(tt.chunkSize))) |
| 672 |
} |
| 673 |
if tt.minChunkSize > 0 { |
| 674 |
t.Logf("minChunkSize = %d", tt.minChunkSize) |
| 675 |
opts = append(opts, tutil.WithEStargzOptions(estargz.WithMinChunkSize(tt.minChunkSize))) |
| 676 |
} |
| 677 |
esgz, tocDgst, err := tutil.BuildEStargz(tt.in, opts...) |
| 678 |
if err != nil { |
| 679 |
t.Fatalf("failed to build sample eStargz: %v", err) |
| 680 |
} |
| 681 |
testR := &calledReaderAt{esgz, nil} |
| 682 |
mr, err := factory(io.NewSectionReader(testR, 0, esgz.Size()), metadata.WithDecompressors(srcCompression)) |
| 683 |
if err != nil { |
| 684 |
t.Fatalf("failed to create new reader: %v", err) |
| 685 |
} |
| 686 |
defer mr.Close() |
| 687 |
memcache := cache.NewMemoryCache() |
| 688 |
vr, err := NewReader(mr, memcache, digest.FromString("")) |
| 689 |
if err != nil { |
| 690 |
t.Fatalf("failed to make new reader: %v", err) |
| 691 |
} |
| 692 |
rr, err := vr.VerifyTOC(tocDgst) |
| 693 |
if err != nil { |
| 694 |
t.Fatalf("failed to verify TOC: %v", err) |
| 695 |
} |
| 696 |
r := rr.(*reader) |
| 697 |
for _, want := range tt.want { |
| 698 |
want(t, r, testR) |
| 699 |
} |
| 700 |
}) |
| 701 |
} |
| 702 |
} |
| 703 |
} |
| 704 |
|
| 705 |
type check func(*testing.T, *reader, *calledReaderAt) |
| 706 |
|
| 707 |
type chunkInfo struct { |
| 708 |
name string |
| 709 |
data string |
| 710 |
chunkOffset int64 |
| 711 |
chunkSize int64 |
| 712 |
} |
| 713 |
|
| 714 |
func hasFileContentsOffset(name string, off int64, contents string, fromCache bool) check { |
| 715 |
return func(t *testing.T, r *reader, cr *calledReaderAt) { |
| 716 |
tid, err := lookup(r, name) |
| 717 |
if err != nil { |
| 718 |
t.Fatalf("failed to lookup %q", name) |
| 719 |
} |
| 720 |
ra, err := r.OpenFile(tid) |
| 721 |
if err != nil { |
| 722 |
t.Fatalf("Failed to open testing file: %v", err) |
| 723 |
} |
| 724 |
cr.called = nil // reset test |
| 725 |
buf := make([]byte, len(contents)) |
| 726 |
n, err := ra.ReadAt(buf, off) |
| 727 |
if err != nil { |
| 728 |
t.Fatalf("failed to readat %q: %v", name, err) |
| 729 |
} |
| 730 |
if n != len(contents) { |
| 731 |
t.Fatalf("failed to read contents %q (off:%d, want:%q) got %q", name, off, longBytesView([]byte(contents)), longBytesView(buf)) |
| 732 |
} |
| 733 |
if string(buf) != contents { |
| 734 |
t.Fatalf("unexpected content of %q: %q want %q", name, longBytesView(buf), longBytesView([]byte(contents))) |
| 735 |
} |
| 736 |
t.Logf("reader calls for %q: offsets: %+v", name, cr.called) |
| 737 |
if fromCache { |
| 738 |
if len(cr.called) != 0 { |
| 739 |
t.Fatalf("unexpected read on %q: offsets: %v", name, cr.called) |
| 740 |
} |
| 741 |
} else { |
| 742 |
if len(cr.called) == 0 { |
| 743 |
t.Fatalf("no call happened to reader for %q", name) |
| 744 |
} |
| 745 |
} |
| 746 |
} |
| 747 |
} |
| 748 |
|
| 749 |
func hasFileContentsWithPreCached(name string, off int64, contents string, extra ...chunkInfo) check { |
| 750 |
return func(t *testing.T, r *reader, cr *calledReaderAt) { |
| 751 |
tid, err := lookup(r, name) |
| 752 |
if err != nil { |
| 753 |
t.Fatalf("failed to lookup %q", name) |
| 754 |
} |
| 755 |
ra, err := r.OpenFile(tid) |
| 756 |
if err != nil { |
| 757 |
t.Fatalf("Failed to open testing file: %v", err) |
| 758 |
} |
| 759 |
buf := make([]byte, len(contents)) |
| 760 |
n, err := ra.ReadAt(buf, off) |
| 761 |
if err != nil { |
| 762 |
t.Fatalf("failed to readat %q: %v", name, err) |
| 763 |
} |
| 764 |
if n != len(contents) { |
| 765 |
t.Fatalf("failed to read contents %q (off:%d, want:%q) got %q", name, off, longBytesView([]byte(contents)), longBytesView(buf)) |
| 766 |
} |
| 767 |
if string(buf) != contents { |
| 768 |
t.Fatalf("unexpected content of %q: %q want %q", name, longBytesView(buf), longBytesView([]byte(contents))) |
| 769 |
} |
| 770 |
for _, e := range extra { |
| 771 |
eid, err := lookup(r, e.name) |
| 772 |
if err != nil { |
| 773 |
t.Fatalf("failed to lookup %q", e.name) |
| 774 |
} |
| 775 |
cacheID := genID(eid, e.chunkOffset, e.chunkSize) |
| 776 |
er, err := r.cache.Get(cacheID) |
| 777 |
if err != nil { |
| 778 |
t.Fatalf("failed to get cache %q: %+v", cacheID, e) |
| 779 |
} |
| 780 |
data, err := io.ReadAll(io.NewSectionReader(er, 0, e.chunkSize)) |
| 781 |
er.Close() |
| 782 |
if err != nil { |
| 783 |
t.Fatalf("failed to read cache %q: %+v", cacheID, e) |
| 784 |
} |
| 785 |
if string(data) != e.data { |
| 786 |
t.Fatalf("unexpected contents of cache %q (%+v): %q; wanted %q", cacheID, e, longBytesView(data), longBytesView([]byte(e.data))) |
| 787 |
} |
| 788 |
} |
| 789 |
} |
| 790 |
} |
| 791 |
|
| 792 |
func lookup(r *reader, name string) (uint32, error) { |
| 793 |
name = strings.TrimPrefix(path.Clean("/"+name), "/") |
| 794 |
if name == "" { |
| 795 |
return r.Metadata().RootID(), nil |
| 796 |
} |
| 797 |
dir, base := filepath.Split(name) |
| 798 |
pid, err := lookup(r, dir) |
| 799 |
if err != nil { |
| 800 |
return 0, err |
| 801 |
} |
| 802 |
id, _, err := r.Metadata().GetChild(pid, base) |
| 803 |
return id, err |
| 804 |
} |
| 805 |
|
| 806 |
type calledReaderAt struct { |
| 807 |
io.ReaderAt |
| 808 |
called []int64 |
| 809 |
} |
| 810 |
|
| 811 |
func (r *calledReaderAt) ReadAt(p []byte, off int64) (int, error) { |
| 812 |
r.called = append(r.called, off) |
| 813 |
return r.ReaderAt.ReadAt(p, off) |
| 814 |
} |
| 815 |
|
| 816 |
// longBytesView is an alias of []byte suitable for printing a long data as an omitted string to avoid long data being printed. |
| 817 |
type longBytesView []byte |
| 818 |
|
| 819 |
func (b longBytesView) String() string { |
| 820 |
if len(b) < 100 { |
| 821 |
return string(b) |
| 822 |
} |
| 823 |
return string(b[:50]) + "...(omit)..." + string(b[len(b)-50:]) |
| 824 |
} |