Debian Codegraph @

assemble.go

raw
1 package desync
2
3 import (
4 "context"
5 "fmt"
6 "golang.org/x/sync/errgroup"
7 "os"
8 "slices"
9 )
10
11 // InvalidSeedAction represents the action that we will take if a seed
12 // happens to be invalid. There are currently three options:
13 // - fail with an error
14 // - skip the invalid seed and try to continue
15 // - regenerate the invalid seed index
16 type InvalidSeedAction int
17
18 const (
19 InvalidSeedActionBailOut InvalidSeedAction = iota
20 InvalidSeedActionSkip
21 InvalidSeedActionRegenerate
22 )
23
24 type AssembleOptions struct {
25 N int
26 InvalidSeedAction InvalidSeedAction
27 }
28
29 // writeChunk tries to write a chunk by looking at the self seed, if it is already existing in the
30 // destination file or by taking it from the store. The in-place check runs first to avoid unnecessary
31 // writes. If the target already has the correct data, no write is performed. buf is scratch space
32 // for reading back the destination, reused across calls to avoid an allocation per chunk.
33 func writeChunk(c IndexChunk, ss *selfSeed, f *os.File, blocksize uint64, s Store, stats *ExtractStats, isBlank bool, buf []byte) error {
34 // If we operate on an existing file there's a good chance we already
35 // have the data written for this chunk. Let's read it from disk and
36 // compare to what is expected. This is checked first to avoid rewriting
37 // data that is already correct, even for chunks available in the selfSeed.
38 if !isBlank {
39 b := slices.Grow(buf[:0], int(c.Size))[:c.Size]
40 if _, err := f.ReadAt(b, int64(c.Start)); err != nil {
41 return err
42 }
43 sum := Digest.Sum(b)
44 if sum == c.ID {
45 // Record we kept this chunk in the file (when using in-place extract)
46 stats.incChunksInPlace()
47 return nil
48 }
49 }
50
51 // If we already took this chunk from the store we can reuse it by looking
52 // into the selfSeed.
53 if segment := ss.getChunk(c.ID); segment != nil {
54 copied, cloned, err := segment.WriteInto(f, c.Start, c.Size, blocksize, isBlank)
55 if err != nil {
56 return err
57 }
58 stats.addBytesCopied(copied)
59 stats.addBytesCloned(cloned)
60 return nil
61 }
62
63 // Record this chunk having been pulled from the store
64 stats.incChunksFromStore()
65 // Pull the (compressed) chunk from the store
66 chunk, err := s.GetChunk(c.ID)
67 if err != nil {
68 return err
69 }
70 b, err := chunk.Data()
71 if err != nil {
72 return err
73 }
74 // Might as well verify the chunk size while we're at it
75 if c.Size != uint64(len(b)) {
76 return fmt.Errorf("unexpected size for chunk %s", c.ID)
77 }
78 // Write the decompressed chunk into the file at the right position
79 if _, err = f.WriteAt(b, int64(c.Start)); err != nil {
80 return err
81 }
82 return nil
83 }
84
85 // AssembleFile re-assembles a file based on a list of index chunks. It runs n
86 // goroutines, creating one filehandle for the file "name" per goroutine
87 // and writes to the file simultaneously. If progress is provided, it'll be
88 // called when a chunk has been processed.
89 // If the input file exists and is not empty, the algorithm will first
90 // confirm if the data matches what is expected and only populate areas that
91 // differ from the expected content. This can be used to complete partly
92 // written files.
93 func AssembleFile(ctx context.Context, name string, idx Index, s Store, seeds []Seed, options AssembleOptions) (*ExtractStats, error) {
94 type Job struct {
95 segment IndexSegment
96 source SeedSegment
97 }
98 var (
99 attempt = 1
100 in = make(chan Job)
101 isBlank bool
102 isBlkDevice bool
103 pb ProgressBar
104 )
105 g, ctx := errgroup.WithContext(ctx)
106
107 // Initialize stats to be gathered during extraction
108 stats := &ExtractStats{
109 BytesTotal: idx.Length(),
110 ChunksTotal: len(idx.Chunks),
111 }
112
113 // Determine if the target exists and create it if not
114 info, err := os.Stat(name)
115 switch {
116 case os.IsNotExist(err): // File doesn't exist yet => create it
117 f, err := os.Create(name)
118 if err != nil {
119 return stats, err
120 }
121 f.Close()
122 isBlank = true
123 case err != nil: // Some other error => bail
124 return stats, err
125 case isDevice(info.Mode()): // Dealing with a block device
126 isBlkDevice = true
127 case info.Size() == 0: // Is a file that exists, but is empty => use optimizations for blank files
128 isBlank = true
129 }
130
131 // Truncate the output file to the full expected size. Not only does this
132 // confirm there's enough disk space, but it allows for an optimization
133 // when dealing with the Null Chunk. On Darwin, the file is physically
134 // pre-allocated as well since sparse files on APFS have shown to cause
135 // issues when written to concurrently.
136 if !isBlkDevice {
137 if err := preallocateFile(name, idx.Length()); err != nil {
138 return stats, err
139 }
140 }
141
142 // An index of a zero-length file has no chunks. The file has been created
143 // (and truncated) above, so there is nothing left to do.
144 if len(idx.Chunks) == 0 {
145 return stats, nil
146 }
147
148 // Determine the blocksize of the target file which is required for reflinking
149 blocksize := blocksizeOfFile(name)
150
151 // Prepend a nullchunk seed to the list of seeds to make sure we read that
152 // before any large null sections in other seed files
153 ns, err := newNullChunkSeed(name, blocksize, idx.Index.ChunkSizeMax)
154 if err != nil {
155 return stats, err
156 }
157 defer ns.close()
158 seeds = append([]Seed{ns}, seeds...)
159
160 // Start a self-seed which will become usable once chunks are written contiguously
161 // beginning at position 0. There is no need to add this to the seeds list because
162 // when we create a plan it will be empty.
163 ss, err := newSelfSeed(name, idx)
164 if err != nil {
165 return stats, err
166 }
167
168 // Record the total number of seeds and blocksize in the stats
169 stats.Seeds = len(seeds)
170 stats.Blocksize = blocksize
171
172 // Start the workers, each having its own filehandle to write concurrently
173 for i := 0; i < options.N; i++ {
174 f, err := os.OpenFile(name, os.O_RDWR, 0666)
175 if err != nil {
176 return stats, fmt.Errorf("unable to open file %s, %s", name, err)
177 }
178 defer f.Close()
179 g.Go(func() error {
180 // Scratch buffer for reading chunks back from the destination,
181 // reused for all chunks this worker processes. Grown on demand
182 // if the index reports no (or a too small) max chunk size.
183 buf := make([]byte, idx.Index.ChunkSizeMax)
184 for job := range in {
185 pb.Add(job.segment.lengthChunks())
186 if job.source != nil {
187 // If we have a seedSegment we expect 1 or more chunks between
188 // the start and the end of this segment.
189 stats.addChunksFromSeed(uint64(job.segment.lengthChunks()))
190 offset := job.segment.start()
191 length := job.segment.lengthBytes()
192 copied, cloned, err := job.source.WriteInto(f, offset, length, blocksize, isBlank)
193 if err != nil {
194 return err
195 }
196
197 // Null segments (identified by an empty filename, like in
198 // Plan.Validate) skip the read-back validation below: they write
199 // deterministic zeros with no external source that could change,
200 // and reading back and hashing large null sections is expensive.
201 if job.source.FileName() == "" {
202 stats.addBytesCopied(copied)
203 stats.addBytesCloned(cloned)
204 ss.add(job.segment)
205 continue
206 }
207
208 // Validate that the written chunks are exactly what we were expecting.
209 // Because the seed might point to a RW location, if the data changed
210 // while we were extracting an index, we might end up writing to the
211 // destination some unexpected values.
212 for _, c := range job.segment.chunks() {
213 buf = slices.Grow(buf[:0], int(c.Size))[:c.Size]
214 if _, err := f.ReadAt(buf, int64(c.Start)); err != nil {
215 return err
216 }
217 sum := Digest.Sum(buf)
218 if sum != c.ID {
219 if options.InvalidSeedAction == InvalidSeedActionRegenerate {
220 // Try harder before giving up and aborting
221 Log.WithField("ID", c.ID).Info("The seed may have changed during processing, trying to take the chunk from the self seed or the store")
222 if err := writeChunk(c, ss, f, blocksize, s, stats, isBlank, buf); err != nil {
223 return err
224 }
225 } else {
226 return fmt.Errorf("written data in %s doesn't match its expected hash value, seed may have changed during processing", name)
227 }
228 }
229 }
230
231 stats.addBytesCopied(copied)
232 stats.addBytesCloned(cloned)
233 // Record this segment's been written in the self-seed to make it
234 // available going forward
235 ss.add(job.segment)
236 continue
237 }
238
239 // If we don't have a seedSegment we expect an IndexSegment with just
240 // a single chunk, that we can take from either the selfSeed, from the
241 // destination file, or from the store.
242 if len(job.segment.chunks()) != 1 {
243 panic("Received an unexpected segment that doesn't contain just a single chunk")
244 }
245 c := job.segment.chunks()[0]
246
247 if err := writeChunk(c, ss, f, blocksize, s, stats, isBlank, buf); err != nil {
248 return err
249 }
250
251 // Record this chunk's been written in the self-seed.
252 // Even if we already confirmed that this chunk is present in the
253 // self-seed, we still need to record it as being written, otherwise
254 // the self-seed position pointer doesn't advance as we expect.
255 ss.add(job.segment)
256 }
257 return nil
258 })
259 }
260
261 // Let the sequencer break up the index into segments, create and validate a plan,
262 // feed the workers, and stop if there are any errors
263 seq := NewSeedSequencer(idx, seeds...)
264 plan := seq.Plan()
265 for {
266 validatingPrefix := fmt.Sprintf("Attempt %d: Validating ", attempt)
267 if err := plan.Validate(ctx, options.N, NewProgressBar(validatingPrefix)); err != nil {
268 // This plan has at least one invalid seed
269 switch options.InvalidSeedAction {
270 case InvalidSeedActionBailOut:
271 return stats, err
272 case InvalidSeedActionRegenerate:
273 Log.WithError(err).Info("Unable to use one of the chosen seeds, regenerating it")
274 if err := seq.RegenerateInvalidSeeds(ctx, options.N, attempt); err != nil {
275 return stats, err
276 }
277 case InvalidSeedActionSkip:
278 // Recreate the plan. This time the seed marked as invalid will be skipped
279 Log.WithError(err).Info("Unable to use one of the chosen seeds, skipping it")
280 default:
281 panic("Unhandled InvalidSeedAction")
282 }
283
284 attempt += 1
285 seq.Rewind()
286 plan = seq.Plan()
287 continue
288 }
289 // Found a valid plan
290 break
291 }
292
293 pb = NewProgressBar(fmt.Sprintf("Attempt %d: Assembling ", attempt))
294 pb.SetTotal(len(idx.Chunks))
295 pb.Start()
296 defer pb.Finish()
297
298 loop:
299 for _, segment := range plan {
300 select {
301 case <-ctx.Done():
302 break loop
303 case in <- Job{segment.indexSegment, segment.source}:
304 }
305 }
306 close(in)
307
308 return stats, g.Wait()
309 }