Debian Codegraph @

assemble_test.go

raw
1 package desync
2
3 import (
4 "context"
5 "crypto/md5"
6 "crypto/rand"
7 "fmt"
8 "os"
9 "path/filepath"
10 "testing"
11
12 "github.com/stretchr/testify/require"
13 )
14
15 func TestExtract(t *testing.T) {
16 // Make a test file that's guaranteed to have duplicate chunks.
17 b, err := os.ReadFile("testdata/chunker.input")
18 if err != nil {
19 t.Fatal(err)
20 }
21 for range 4 { // Replicate it a few times to make sure we get dupes
22 b = append(b, b...)
23 }
24 b = append(b, make([]byte, 2*ChunkSizeMaxDefault)...) // want to have at least one null-chunk in the input
25 tmp := t.TempDir()
26 in := filepath.Join(tmp, "in")
27 require.NoError(t, os.WriteFile(in, b, 0644))
28
29 // Record the checksum of the input file, used to compare to the output later
30 inSum := md5.Sum(b)
31
32 // Chunk the file to get an index
33 index, _, err := IndexFromFile(
34 context.Background(),
35 in,
36 10,
37 ChunkSizeMinDefault, ChunkSizeAvgDefault, ChunkSizeMaxDefault,
38 NewProgressBar(""),
39 )
40 if err != nil {
41 t.Fatal(err)
42 }
43
44 // Chop up the input file into a (temporary) local store
45 store := t.TempDir()
46
47 s, err := NewLocalStore(store, StoreOptions{})
48 if err != nil {
49 t.Fatal(err)
50 }
51 if err := ChopFile(context.Background(), in, index.Chunks, s, 10, NewProgressBar("")); err != nil {
52 t.Fatal(err)
53 }
54
55 // Make a blank store - used to test a case where no chunk *should* be requested
56 blankstore := t.TempDir()
57 bs, err := NewLocalStore(blankstore, StoreOptions{})
58 if err != nil {
59 t.Fatal(err)
60 }
61
62 // Prepare output files for each test - first a non-existing one
63 out1 := filepath.Join(tmp, "out1")
64
65 // This one is a complete file matching what we expect at the end
66 out2 := filepath.Join(tmp, "out2")
67 require.NoError(t, os.WriteFile(out2, b, 0644))
68
69 // Incomplete or damaged file that has most but not all data
70 b[0] ^= 0xff // flip some bits
71 b[len(b)-1] ^= 0xff
72 b = append(b, 0) // make it longer
73 out3 := filepath.Join(tmp, "out3")
74 require.NoError(t, os.WriteFile(out3, b, 0644))
75
76 // At this point we have the data needed for the test setup
77 // in - Temp file that represents the original input file
78 // inSub - MD5 of the input file
79 // index - Index file for the input file
80 // s - Local store containing the chunks needed to rebuild the input file
81 // bs - A blank local store, all GetChunk fail on it
82 // out1 - Just a non-existing file that gets assembled
83 // out2 - The output file already fully complete, no GetChunk should be needed
84 // out3 - Partial/damaged file with most, but not all data correct
85 // seedIndex + seedFile - Seed file to help assemble the input
86 tests := map[string]struct {
87 outfile string
88 store Store
89 seed []Seed
90 }{
91 "extract to new file": {outfile: out1, store: s},
92 "extract to complete file": {outfile: out2, store: bs},
93 "extract to incomplete file": {outfile: out3, store: s},
94 }
95
96 for name, test := range tests {
97 t.Run(name, func(t *testing.T) {
98 if _, err := AssembleFile(context.Background(), test.outfile, index, test.store, nil,
99 AssembleOptions{10, InvalidSeedActionBailOut},
100 ); err != nil {
101 t.Fatal(err)
102 }
103 b, err := os.ReadFile(test.outfile)
104 if err != nil {
105 t.Fatal(err)
106 }
107 outSum := md5.Sum(b)
108 if inSum != outSum {
109 t.Fatal("checksum of extracted file doesn't match expected")
110 }
111 })
112 }
113 }
114
115 func TestSeed(t *testing.T) {
116 // Prepare different types of data slices that'll be used to assemble target
117 // and seed files with varying amount of duplication
118 data1, err := os.ReadFile("testdata/chunker.input")
119 if err != nil {
120 t.Fatal(err)
121 }
122 null := make([]byte, 4*ChunkSizeMaxDefault)
123 rand1 := make([]byte, 4*ChunkSizeMaxDefault)
124 rand.Read(rand1)
125 rand2 := make([]byte, 4*ChunkSizeMaxDefault)
126 rand.Read(rand2)
127
128 // Setup a temporary store
129 store := t.TempDir()
130
131 s, err := NewLocalStore(store, StoreOptions{})
132 if err != nil {
133 t.Fatal(err)
134 }
135
136 // Define tests with files with different content, by building files out
137 // of sets of byte slices to create duplication or not between the target and
138 // its seeds
139 tests := map[string]struct {
140 target [][]byte
141 seeds [][][]byte
142 }{
143 "extract without seed": {
144 target: [][]byte{rand1, rand2},
145 seeds: nil},
146 "extract all null file": {
147 target: [][]byte{null, null, null, null, null},
148 seeds: nil},
149 "extract repetitive file": {
150 target: [][]byte{data1, data1, data1, data1, data1},
151 seeds: nil},
152 "extract with single file seed": {
153 target: [][]byte{data1, null, null, rand1, null},
154 seeds: [][][]byte{
155 {data1, null, rand2, rand2, data1},
156 },
157 },
158 "extract with multiple file seeds": {
159 target: [][]byte{null, null, rand1, null, data1},
160 seeds: [][][]byte{
161 {rand2, null, rand2, rand2, data1},
162 {data1, null, rand2, rand2, data1},
163 {rand2},
164 },
165 },
166 "extract with identical file seed": {
167 target: [][]byte{data1, null, rand1, null, data1},
168 seeds: [][][]byte{
169 {data1, null, rand1, null, data1},
170 },
171 },
172 }
173
174 for name, test := range tests {
175 t.Run(name, func(t *testing.T) {
176 // Build the destination file so we can chunk it
177 tmp := t.TempDir()
178 dst := filepath.Join(tmp, "dst")
179 dstBytes := join(test.target...)
180 require.NoError(t, os.WriteFile(dst, dstBytes, 0644))
181
182 // Record the checksum of the target file, used to compare to the output later
183 dstSum := md5.Sum(dstBytes)
184
185 // Chunk the file to get an index
186 dstIndex, _, err := IndexFromFile(
187 context.Background(),
188 dst,
189 10,
190 ChunkSizeMinDefault, ChunkSizeAvgDefault, ChunkSizeMaxDefault,
191 NewProgressBar(""),
192 )
193 if err != nil {
194 t.Fatal(err)
195 }
196
197 // Chop up the input file into the store
198 if err := ChopFile(context.Background(), dst, dstIndex.Chunks, s, 10, NewProgressBar("")); err != nil {
199 t.Fatal(err)
200 }
201
202 // Build the seed files and indexes then populate the array of seeds
203 var seeds []Seed
204 for i, f := range test.seeds {
205 seedFile := filepath.Join(tmp, fmt.Sprintf("seed%d", i))
206 require.NoError(t, os.WriteFile(seedFile, join(f...), 0644))
207 seedIndex, _, err := IndexFromFile(
208 context.Background(),
209 seedFile,
210 10,
211 ChunkSizeMinDefault, ChunkSizeAvgDefault, ChunkSizeMaxDefault,
212 NewProgressBar(""),
213 )
214 if err != nil {
215 t.Fatal(err)
216 }
217 seed, err := NewIndexSeed(dst, seedFile, seedIndex)
218 if err != nil {
219 t.Fatal(err)
220 }
221 seeds = append(seeds, seed)
222 }
223
224 if _, err := AssembleFile(context.Background(), dst, dstIndex, s, seeds,
225 AssembleOptions{10, InvalidSeedActionBailOut},
226 ); err != nil {
227 t.Fatal(err)
228 }
229 b, err := os.ReadFile(dst)
230 if err != nil {
231 t.Fatal(err)
232 }
233 outSum := md5.Sum(b)
234 if dstSum != outSum {
235 t.Fatal("checksum of extracted file doesn't match expected")
236 }
237 })
238 }
239
240 }
241
242 // TestSelfSeedInPlace is the same as TestSelfSeed but the target file is
243 // pre-populated with the correct content before extraction. Every chunk must
244 // be kept in-place and the self-seed must not cause any re-writes.
245 func TestSelfSeedInPlace(t *testing.T) {
246 // Setup a temporary store
247 store := t.TempDir()
248
249 s, err := NewLocalStore(store, StoreOptions{})
250 if err != nil {
251 t.Fatal(err)
252 }
253
254 // Build a number of fake chunks that can then be used in the test in any order
255 type rawChunk struct {
256 id ChunkID
257 data []byte
258 }
259 size := 1024
260 numChunks := 10
261 chunks := make([]rawChunk, numChunks)
262
263 for i := range numChunks {
264 b := make([]byte, size)
265 rand.Read(b)
266 chunk := NewChunk(b)
267 if err = s.StoreChunk(chunk); err != nil {
268 t.Fatal(err)
269 }
270 chunks[i] = rawChunk{chunk.ID(), b}
271 }
272
273 // The target is pre-written with the correct content,
274 // so every chunk should be detected as in-place.
275 tests := map[string]struct {
276 index []int
277 }{
278 "single chunk": {
279 index: []int{0},
280 },
281 "repeating single chunk": {
282 index: []int{0, 0, 0, 0, 0},
283 },
284 "repeating chunk sequence": {
285 index: []int{0, 1, 2, 0, 1, 2, 2},
286 },
287 "repeating chunk sequence mid file": {
288 index: []int{1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3},
289 },
290 "repeating chunk sequence reversed": {
291 index: []int{0, 1, 2, 2, 1, 0},
292 },
293 "non-repeating chunks": {
294 index: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
295 },
296 }
297
298 for name, test := range tests {
299 t.Run(name, func(t *testing.T) {
300 // Build an index from the target chunks
301 var idx Index
302 var b []byte
303 for i, p := range test.index {
304 chunk := IndexChunk{
305 ID: chunks[p].id,
306 Start: uint64(i * size),
307 Size: uint64(size),
308 }
309 b = append(b, chunks[p].data...)
310 idx.Chunks = append(idx.Chunks, chunk)
311 }
312
313 // Calculate the expected checksum
314 sum := md5.Sum(b)
315
316 // Build a temp target file pre-populated with the correct content
317 dst := filepath.Join(t.TempDir(), "dst")
318 require.NoError(t, os.WriteFile(dst, b, 0644))
319
320 // Extract the file
321 stats, err := AssembleFile(context.Background(), dst, idx, s, nil,
322 AssembleOptions{1, InvalidSeedActionBailOut},
323 )
324 if err != nil {
325 t.Fatal(err)
326 }
327
328 // Compare the checksums to that of the input data
329 b, err = os.ReadFile(dst)
330 if err != nil {
331 t.Fatal(err)
332 }
333 outSum := md5.Sum(b)
334 if sum != outSum {
335 t.Fatal("checksum of extracted file doesn't match expected")
336 }
337
338 // All chunks must be in-place. The in-place check in writeChunk
339 // runs before the self-seed lookup, so repeated chunks are not
340 // re-written from the self-seed.
341 if stats.ChunksInPlace != uint64(len(test.index)) {
342 t.Fatalf("expected all %d chunks in-place, got %d", len(test.index), stats.ChunksInPlace)
343 }
344 })
345 }
346
347 }
348
349 // Null segments skip the destination read-back after writing since they have
350 // no external source that could change during extraction. Assemble a null-heavy
351 // file over an existing file full of non-zero data to confirm the null sections
352 // are still written out correctly.
353 func TestExtractNullsOverExistingFile(t *testing.T) {
354 data := make([]byte, 4*ChunkSizeMaxDefault)
355 rand.Read(data)
356 null := make([]byte, 4*ChunkSizeMaxDefault)
357 b := join(null, data, null)
358
359 tmp := t.TempDir()
360 in := filepath.Join(tmp, "in")
361 require.NoError(t, os.WriteFile(in, b, 0644))
362 inSum := md5.Sum(b)
363
364 index, _, err := IndexFromFile(
365 context.Background(),
366 in,
367 10,
368 ChunkSizeMinDefault, ChunkSizeAvgDefault, ChunkSizeMaxDefault,
369 NewProgressBar(""),
370 )
371 require.NoError(t, err)
372
373 s, err := NewLocalStore(t.TempDir(), StoreOptions{})
374 require.NoError(t, err)
375 require.NoError(t, ChopFile(context.Background(), in, index.Chunks, s, 10, NewProgressBar("")))
376
377 // Pre-populate the output file with non-zero data so the null sections
378 // actually have to be written, not just skipped over in a blank file
379 garbage := make([]byte, len(b))
380 rand.Read(garbage)
381 out := filepath.Join(tmp, "out")
382 require.NoError(t, os.WriteFile(out, garbage, 0644))
383
384 _, err = AssembleFile(context.Background(), out, index, s, nil,
385 AssembleOptions{10, InvalidSeedActionBailOut})
386 require.NoError(t, err)
387
388 got, err := os.ReadFile(out)
389 require.NoError(t, err)
390 require.Equal(t, inSum, md5.Sum(got))
391 }
392
393 func join(slices ...[]byte) []byte {
394 var out []byte
395 for _, b := range slices {
396 out = append(out, b...)
397 }
398 return out
399 }
400
401 func readCaibxFile(t *testing.T, indexLocation string) (idx Index) {
402 is, err := NewLocalIndexStore(filepath.Dir(indexLocation))
403 require.NoError(t, err)
404 defer is.Close()
405 indexName := filepath.Base(indexLocation)
406 idx, err = is.GetIndex(indexName)
407 require.NoError(t, err)
408 return idx
409 }
410
411 // An index of a zero-length file has no chunks. Extracting it should produce
412 // an empty output file rather than panic.
413 func TestExtractEmptyIndex(t *testing.T) {
414 out := filepath.Join(t.TempDir(), "out")
415
416 // Write some data into the output file to confirm it gets truncated
417 require.NoError(t, os.WriteFile(out, []byte("old content"), 0644))
418
419 index := Index{
420 Index: FormatIndex{
421 FeatureFlags: CaFormatSHA512256,
422 ChunkSizeMin: ChunkSizeMinDefault,
423 ChunkSizeAvg: ChunkSizeAvgDefault,
424 ChunkSizeMax: ChunkSizeMaxDefault,
425 },
426 }
427 store, err := NewLocalStore(t.TempDir(), StoreOptions{})
428 require.NoError(t, err)
429
430 _, err = AssembleFile(context.Background(), out, index, store, nil,
431 AssembleOptions{10, InvalidSeedActionBailOut})
432 require.NoError(t, err)
433
434 b, err := os.ReadFile(out)
435 require.NoError(t, err)
436 require.Empty(t, b)
437 }
438
439 func TestExtractWithNonStaticSeeds(t *testing.T) {
440 n := 10
441 outDir := t.TempDir()
442 out := filepath.Join(outDir, "out")
443
444 // Test a seed that is initially valid, but becomes corrupted halfway through
445 // the extraction operation
446 MockValidate = true
447
448 store, err := NewLocalStore("testdata/blob2.store", StoreOptions{})
449 require.NoError(t, err)
450 defer store.Close()
451
452 index := readCaibxFile(t, "testdata/blob2.caibx")
453
454 var seeds []Seed
455 srcIndex := readCaibxFile(t, "testdata/blob2_corrupted.caibx")
456 seed, err := NewIndexSeed(out, "testdata/blob2_corrupted", srcIndex)
457 require.NoError(t, err)
458 seeds = append(seeds, seed)
459
460 // Test that the MockValidate works as expected
461 seq := NewSeedSequencer(index, seeds...)
462 plan := seq.Plan()
463 err = plan.Validate(context.Background(), n, NullProgressBar{})
464 require.NoError(t, err)
465
466 options := AssembleOptions{n, InvalidSeedActionRegenerate}
467 _, err = AssembleFile(context.Background(), out, index, store, seeds, options)
468 require.NoError(t, err)
469
470 //Test the output
471 err = VerifyIndex(context.Background(), out, index, n, NullProgressBar{})
472 require.NoError(t, err)
473 }