| 1 |
package desync |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"fmt" |
| 6 |
"os" |
| 7 |
|
| 8 |
"golang.org/x/sync/errgroup" |
| 9 |
) |
| 10 |
|
| 11 |
// VerifyIndex re-calculates the checksums of a blob comparing it to a given index. |
| 12 |
// Fails if the index does not match the blob. |
| 13 |
func VerifyIndex(ctx context.Context, name string, idx Index, n int, pb ProgressBar) error { |
| 14 |
in := make(chan []IndexChunk) |
| 15 |
g, ctx := errgroup.WithContext(ctx) |
| 16 |
|
| 17 |
// Setup and start the progressbar if any |
| 18 |
pb.SetTotal(len(idx.Chunks)) |
| 19 |
pb.Start() |
| 20 |
defer pb.Finish() |
| 21 |
|
| 22 |
stat, err := os.Stat(name) |
| 23 |
if err != nil { |
| 24 |
return err |
| 25 |
} |
| 26 |
if !isDevice(stat.Mode()) && stat.Size() != int64(idx.Length()) { |
| 27 |
return fmt.Errorf("index size (%d) does not match file size (%d)", idx.Length(), stat.Size()) |
| 28 |
} |
| 29 |
|
| 30 |
// Start the workers, each having its own filehandle to read concurrently |
| 31 |
for range n { |
| 32 |
f, err := os.Open(name) |
| 33 |
if err != nil { |
| 34 |
return fmt.Errorf("unable to open file %s, %s", name, err) |
| 35 |
} |
| 36 |
defer f.Close() |
| 37 |
g.Go(func() error { |
| 38 |
for c := range in { |
| 39 |
// Reuse the fileSeedSegment structure, this is really just a seed segment after all |
| 40 |
segment := newFileSeedSegment(name, c, false) |
| 41 |
if err := segment.Validate(f); err != nil { |
| 42 |
return err |
| 43 |
} |
| 44 |
|
| 45 |
// Update progress bar, if any |
| 46 |
pb.Add(len(c)) |
| 47 |
} |
| 48 |
return nil |
| 49 |
}) |
| 50 |
} |
| 51 |
|
| 52 |
chunksNum := len(idx.Chunks) |
| 53 |
|
| 54 |
// Number of chunks that will be evaluated in a single Goroutine. |
| 55 |
// This helps to reduce the required number of context switch. |
| 56 |
// In theory, we could just divide the total number of chunks by the number |
| 57 |
// of workers, but instead we reduce that by 10 times to avoid the situation |
| 58 |
// where we end up waiting a single worker that was slower to complete (e.g. |
| 59 |
// if its chunks were not in cache while the others were). |
| 60 |
batch := chunksNum / (n * 10) |
| 61 |
|
| 62 |
// Feed the workers, stop if there are any errors |
| 63 |
loop: |
| 64 |
for i := 0; i < chunksNum; i = i + batch + 1 { |
| 65 |
last := i + batch |
| 66 |
if last >= chunksNum { |
| 67 |
// We reached the end of the array |
| 68 |
last = chunksNum - 1 |
| 69 |
} |
| 70 |
select { |
| 71 |
case <-ctx.Done(): |
| 72 |
break loop |
| 73 |
case in <- idx.Chunks[i : last+1]: |
| 74 |
} |
| 75 |
} |
| 76 |
close(in) |
| 77 |
|
| 78 |
return g.Wait() |
| 79 |
} |