| 1 |
package desync |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"crypto" |
| 6 |
"fmt" |
| 7 |
"io" |
| 8 |
"os" |
| 9 |
"sync" |
| 10 |
"sync/atomic" |
| 11 |
) |
| 12 |
|
| 13 |
// IndexFromFile chunks a file in parallel and returns an index. It does not |
| 14 |
// store chunks! Each concurrent chunker starts filesize/n bytes apart and |
| 15 |
// splits independently. Each chunk worker tries to sync with its next |
| 16 |
// neighbor and if successful stops processing letting the next one continue. |
| 17 |
// The main routine reads and assembles a list of (confirmed) chunks from the |
| 18 |
// workers, starting with the first worker. |
| 19 |
// This algorithm wastes some CPU and I/O if the data doesn't contain chunk |
| 20 |
// boundaries, for example if the whole file contains nil bytes. If progress |
| 21 |
// is not nil, it'll be updated with the confirmed chunk position in the file. |
| 22 |
func IndexFromFile(ctx context.Context, |
| 23 |
name string, |
| 24 |
n int, |
| 25 |
min, avg, max uint64, |
| 26 |
pb ProgressBar, |
| 27 |
) (Index, ChunkingStats, error) { |
| 28 |
|
| 29 |
stats := ChunkingStats{} |
| 30 |
var wg sync.WaitGroup |
| 31 |
|
| 32 |
ctx, cancel := context.WithCancel(ctx) |
| 33 |
defer cancel() |
| 34 |
|
| 35 |
var digestFlag uint64 |
| 36 |
if Digest.Algorithm() == crypto.SHA512_256 { |
| 37 |
digestFlag = CaFormatSHA512256 |
| 38 |
} |
| 39 |
|
| 40 |
index := Index{ |
| 41 |
Index: FormatIndex{ |
| 42 |
FeatureFlags: CaFormatExcludeNoDump | digestFlag, |
| 43 |
ChunkSizeMin: min, |
| 44 |
ChunkSizeAvg: avg, |
| 45 |
ChunkSizeMax: max, |
| 46 |
}, |
| 47 |
} |
| 48 |
|
| 49 |
// If our input file has a catar header, copy its feature flags into the index |
| 50 |
f, err := os.Open(name) |
| 51 |
if err != nil { |
| 52 |
return index, stats, err |
| 53 |
} |
| 54 |
fDecoder := NewFormatDecoder(f) |
| 55 |
piece, err := fDecoder.Next() |
| 56 |
if err == nil { |
| 57 |
switch t := piece.(type) { |
| 58 |
case FormatEntry: |
| 59 |
index.Index.FeatureFlags |= t.FeatureFlags |
| 60 |
} |
| 61 |
} |
| 62 |
f.Close() |
| 63 |
|
| 64 |
size, err := GetFileSize(name) |
| 65 |
if err != nil { |
| 66 |
return index, stats, err |
| 67 |
} |
| 68 |
|
| 69 |
// Adjust n if it's a small file that doesn't have n*max bytes |
| 70 |
nn := size/max + 1 |
| 71 |
if nn < uint64(n) { |
| 72 |
n = int(nn) |
| 73 |
} |
| 74 |
span := size / uint64(n) // initial spacing between chunkers |
| 75 |
|
| 76 |
// Setup and start the progressbar if any |
| 77 |
pb.SetTotal(int(size)) |
| 78 |
pb.Start() |
| 79 |
defer pb.Finish() |
| 80 |
|
| 81 |
// Null chunks is produced when a large section of null bytes is chunked. There are no |
| 82 |
// split points in those sections so it's always of max chunk size. Used for optimizations |
| 83 |
// when chunking files with large empty sections. |
| 84 |
nullChunk := NewNullChunk(max) |
| 85 |
|
| 86 |
// Create/initialize the workers |
| 87 |
worker := make([]*pChunker, n) |
| 88 |
for i := 0; i < n; i++ { |
| 89 |
f, err := os.Open(name) // open one file per worker |
| 90 |
if err != nil { |
| 91 |
return index, stats, err |
| 92 |
} |
| 93 |
defer f.Close() |
| 94 |
start := span * uint64(i) // starting position for this chunker |
| 95 |
mChunks := (size-start)/min + 1 // max # of chunks this worker can produce |
| 96 |
s, err := f.Seek(int64(start), io.SeekStart) |
| 97 |
if err != nil { |
| 98 |
return index, stats, err |
| 99 |
} |
| 100 |
if uint64(s) != start { |
| 101 |
return index, stats, fmt.Errorf("requested seek to position %d, but got %d", start, s) |
| 102 |
} |
| 103 |
c, err := NewChunker(f, min, avg, max) |
| 104 |
if err != nil { |
| 105 |
return index, stats, err |
| 106 |
} |
| 107 |
p := &pChunker{ |
| 108 |
chunker: c, |
| 109 |
results: make(chan IndexChunk, mChunks), |
| 110 |
done: make(chan struct{}), |
| 111 |
offset: start, |
| 112 |
stats: &stats, |
| 113 |
nullChunk: nullChunk, |
| 114 |
} |
| 115 |
worker[i] = p |
| 116 |
} |
| 117 |
|
| 118 |
// Link the workers, each one gets a pointer to the next, the last one gets nil |
| 119 |
for i := 1; i < n; i++ { |
| 120 |
worker[i-1].next.Store(worker[i]) |
| 121 |
} |
| 122 |
|
| 123 |
// Start the workers |
| 124 |
for _, w := range worker { |
| 125 |
wg.Go(func() { w.start(ctx) }) |
| 126 |
defer w.stop() // panic/return safety net (idempotent via once) |
| 127 |
} |
| 128 |
|
| 129 |
// Go through the workers, starting with the first one, taking all chunks |
| 130 |
// from their bucket before moving on to the next. It's possible that a worker |
| 131 |
// reaches the end of the stream before the following worker does (eof=true), |
| 132 |
// don't advance to the next worker in that case. |
| 133 |
var chunkErr error |
| 134 |
for _, w := range worker { |
| 135 |
for chunk := range w.results { |
| 136 |
// Assemble the list of chunks in the index |
| 137 |
index.Chunks = append(index.Chunks, chunk) |
| 138 |
pb.Set(int(chunk.Start + chunk.Size)) |
| 139 |
stats.incAccepted() |
| 140 |
} |
| 141 |
// Done reading all chunks from this worker, check for any errors |
| 142 |
if w.err != nil { |
| 143 |
chunkErr = w.err |
| 144 |
break |
| 145 |
} |
| 146 |
// Stop if this worker reached the end of the stream (it's not necessarily |
| 147 |
// the last worker!) |
| 148 |
if w.eof { |
| 149 |
break |
| 150 |
} |
| 151 |
} |
| 152 |
|
| 153 |
// Stop every worker and wait for all goroutines to fully exit before |
| 154 |
// copying stats by value into the return. Otherwise the copy races the |
| 155 |
// workers' atomic stats updates and the count would be incomplete. |
| 156 |
cancel() |
| 157 |
for _, w := range worker { |
| 158 |
w.stop() |
| 159 |
} |
| 160 |
wg.Wait() |
| 161 |
|
| 162 |
return index, stats, chunkErr |
| 163 |
} |
| 164 |
|
| 165 |
// Parallel chunk worker - Splits a stream and stores start, size and ID in |
| 166 |
// a buffered channel to be sync'ed with surrounding chunkers. |
| 167 |
type pChunker struct { |
| 168 |
// "bucket" to store chunk results in until they are sync'ed with the previous |
| 169 |
// chunker and then recorded |
| 170 |
results chan IndexChunk |
| 171 |
|
| 172 |
// single-stream chunker used by this worker |
| 173 |
chunker Chunker |
| 174 |
|
| 175 |
// starting position in the stream for this worker, needed to calculate |
| 176 |
// the absolute position of every boundary that is returned |
| 177 |
offset uint64 |
| 178 |
|
| 179 |
once sync.Once |
| 180 |
done chan struct{} |
| 181 |
err error |
| 182 |
|
| 183 |
// next worker in the chain. Written by this worker when skipping dead |
| 184 |
// neighbors and read by the previous worker, which may happen concurrently |
| 185 |
// since the main routine can stop workers mid-iteration. |
| 186 |
next atomic.Pointer[pChunker] |
| 187 |
|
| 188 |
eof bool |
| 189 |
sync IndexChunk |
| 190 |
stats *ChunkingStats |
| 191 |
|
| 192 |
// Null chunk for optimizing chunking sparse files |
| 193 |
nullChunk *NullChunk |
| 194 |
} |
| 195 |
|
| 196 |
func (c *pChunker) start(ctx context.Context) { |
| 197 |
defer close(c.results) |
| 198 |
defer c.stop() |
| 199 |
for { |
| 200 |
select { |
| 201 |
case <-ctx.Done(): |
| 202 |
c.err = Interrupted{} |
| 203 |
return |
| 204 |
case <-c.done: |
| 205 |
return |
| 206 |
default: // We weren't asked to stop and weren't interrupted, carry on |
| 207 |
} |
| 208 |
start, b, err := c.chunker.Next() |
| 209 |
if err != nil { |
| 210 |
c.err = err |
| 211 |
return |
| 212 |
} |
| 213 |
c.stats.incProduced() |
| 214 |
start += c.offset |
| 215 |
if len(b) == 0 { |
| 216 |
// TODO: If this worker reached the end of the stream and it's not the |
| 217 |
// last one, we should probably stop all following workers. Meh, shouldn't |
| 218 |
// be happening for large files or save significant CPU for small ones. |
| 219 |
c.eof = true |
| 220 |
return |
| 221 |
} |
| 222 |
// Calculate the chunk ID |
| 223 |
id := Digest.Sum(b) |
| 224 |
|
| 225 |
// Store it in our bucket |
| 226 |
chunk := IndexChunk{Start: start, Size: uint64(len(b)), ID: id} |
| 227 |
c.results <- chunk |
| 228 |
|
| 229 |
// Check if the next worker already has this chunk, at which point we stop |
| 230 |
// here and let the next continue |
| 231 |
next := c.next.Load() |
| 232 |
if next != nil { |
| 233 |
inSync, zeroes := next.syncWith(chunk) |
| 234 |
if inSync { |
| 235 |
return |
| 236 |
} |
| 237 |
numNullChunks := int(int(zeroes) / len(c.nullChunk.Data)) |
| 238 |
if numNullChunks > 0 { |
| 239 |
if err := c.chunker.Advance(numNullChunks * len(c.nullChunk.Data)); err != nil { |
| 240 |
c.err = err |
| 241 |
return |
| 242 |
} |
| 243 |
nc := chunk |
| 244 |
for range numNullChunks { |
| 245 |
nc = IndexChunk{Start: nc.Start + nc.Size, Size: uint64(len(c.nullChunk.Data)), ID: c.nullChunk.ID} |
| 246 |
c.results <- nc |
| 247 |
zeroes -= uint64(len(c.nullChunk.Data)) |
| 248 |
} |
| 249 |
} |
| 250 |
} |
| 251 |
|
| 252 |
// If the next worker has stopped and has no more chunks in its bucket, |
| 253 |
// we want to skip that and try to sync with the one after |
| 254 |
if next != nil && !next.active() && len(next.results) == 0 { |
| 255 |
c.next.Store(next.next.Load()) |
| 256 |
} |
| 257 |
} |
| 258 |
} |
| 259 |
|
| 260 |
func (c *pChunker) stop() { |
| 261 |
c.once.Do(func() { close(c.done) }) |
| 262 |
} |
| 263 |
|
| 264 |
func (c *pChunker) active() bool { |
| 265 |
select { |
| 266 |
case <-c.done: |
| 267 |
return false |
| 268 |
default: |
| 269 |
return true |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
// Returns true if the given chunk lines up with one in the current bucket. Also returns |
| 274 |
// the number of zero bytes this chunker has found from 'chunk'. This helps the previous |
| 275 |
// chunker to skip chunking over those areas and put a null-chunks (always max size) in |
| 276 |
// place instead. |
| 277 |
func (c *pChunker) syncWith(chunk IndexChunk) (bool, uint64) { |
| 278 |
// Read from our bucket until we're past (or match) where the previous worker |
| 279 |
// currently is |
| 280 |
var prev IndexChunk |
| 281 |
for chunk.Start > c.sync.Start { |
| 282 |
prev = c.sync |
| 283 |
var ok bool |
| 284 |
select { |
| 285 |
case c.sync, ok = <-c.results: |
| 286 |
if !ok { |
| 287 |
return false, 0 |
| 288 |
} |
| 289 |
default: // Nothing in my bucket? Move on |
| 290 |
return false, 0 |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
// Did we find a match with the previous worker? If so, the previous worker |
| 295 |
// should stop and this one will keep going |
| 296 |
if chunk.Start == c.sync.Start && chunk.Size == c.sync.Size { |
| 297 |
return true, 0 |
| 298 |
} |
| 299 |
|
| 300 |
// The previous chunker didn't sync up with this one, but perhaps we're in a large area |
| 301 |
// of nulls (chunk split points are unlikely to line up). If so we can tell the previous |
| 302 |
// chunker how many nulls are coming so it doesn't need to do all the work again and can |
| 303 |
// skip ahead, producing null-chunks of max size. |
| 304 |
var n uint64 |
| 305 |
if c.sync.ID == c.nullChunk.ID && prev.ID == c.nullChunk.ID { |
| 306 |
// We know there're at least some null chunks in front of the previous chunker. Let's |
| 307 |
// see if there are more in our bucket so we can tell the previous chunker how far to |
| 308 |
// skip ahead. |
| 309 |
n = prev.Start + prev.Size - chunk.Start |
| 310 |
for { |
| 311 |
var ok bool |
| 312 |
select { |
| 313 |
case c.sync, ok = <-c.results: |
| 314 |
if !ok { |
| 315 |
return false, n |
| 316 |
} |
| 317 |
default: // Nothing more in my bucket? Move on |
| 318 |
return false, n |
| 319 |
} |
| 320 |
if c.sync.ID != c.nullChunk.ID { // Hit the end of the null chunks, stop here |
| 321 |
break |
| 322 |
} |
| 323 |
n += uint64(len(c.nullChunk.Data)) |
| 324 |
} |
| 325 |
} |
| 326 |
return false, n |
| 327 |
} |
| 328 |
|
| 329 |
// ChunkingStats is used to report statistics of a parallel chunking operation. |
| 330 |
type ChunkingStats struct { |
| 331 |
ChunksAccepted uint64 |
| 332 |
ChunksProduced uint64 |
| 333 |
} |
| 334 |
|
| 335 |
func (s *ChunkingStats) incAccepted() { |
| 336 |
atomic.AddUint64(&s.ChunksAccepted, 1) |
| 337 |
} |
| 338 |
|
| 339 |
func (s *ChunkingStats) incProduced() { |
| 340 |
atomic.AddUint64(&s.ChunksProduced, 1) |
| 341 |
} |