| 1 |
package desync |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"fmt" |
| 6 |
"io" |
| 7 |
"os" |
| 8 |
"slices" |
| 9 |
"sync" |
| 10 |
) |
| 11 |
|
| 12 |
// FileSeed is used to copy or clone blocks from an existing index+blob during |
| 13 |
// file extraction. |
| 14 |
type FileSeed struct { |
| 15 |
srcFile string |
| 16 |
index Index |
| 17 |
pos map[ChunkID][]int |
| 18 |
canReflink bool |
| 19 |
isInvalid bool |
| 20 |
mu sync.RWMutex |
| 21 |
} |
| 22 |
|
| 23 |
// NewIndexSeed initializes a new seed that uses an existing index and its blob |
| 24 |
func NewIndexSeed(dstFile string, srcFile string, index Index) (*FileSeed, error) { |
| 25 |
s := FileSeed{ |
| 26 |
srcFile: srcFile, |
| 27 |
pos: make(map[ChunkID][]int), |
| 28 |
index: index, |
| 29 |
canReflink: CanClone(dstFile, srcFile), |
| 30 |
isInvalid: false, |
| 31 |
} |
| 32 |
for i, c := range s.index.Chunks { |
| 33 |
s.pos[c.ID] = append(s.pos[c.ID], i) |
| 34 |
} |
| 35 |
return &s, nil |
| 36 |
} |
| 37 |
|
| 38 |
// LongestMatchWith returns the longest sequence of chunks anywhere in Source |
| 39 |
// that match `chunks` starting at chunks[0], limiting the maximum number of chunks |
| 40 |
// if reflinks are not supported. If there is no match, it returns a length of zero |
| 41 |
// and a nil SeedSegment. |
| 42 |
func (s *FileSeed) LongestMatchWith(chunks []IndexChunk) (int, SeedSegment) { |
| 43 |
s.mu.RLock() |
| 44 |
isInvalid := s.isInvalid |
| 45 |
s.mu.RUnlock() |
| 46 |
|
| 47 |
// isInvalid can be concurrently read or written. Use a mutex to avoid a race |
| 48 |
if len(chunks) == 0 || len(s.index.Chunks) == 0 || isInvalid { |
| 49 |
return 0, nil |
| 50 |
} |
| 51 |
pos, ok := s.pos[chunks[0].ID] |
| 52 |
if !ok { |
| 53 |
return 0, nil |
| 54 |
} |
| 55 |
// From every position of chunks[0] in the source, find a slice of |
| 56 |
// matching chunks. Then return the longest of those slices. |
| 57 |
var ( |
| 58 |
match []IndexChunk |
| 59 |
max int |
| 60 |
limit int |
| 61 |
) |
| 62 |
if !s.canReflink { |
| 63 |
// Limit the maximum number of chunks, in a single sequence, to avoid |
| 64 |
// having jobs that are too unbalanced. |
| 65 |
// However, if reflinks are supported, we don't limit it to make it faster and |
| 66 |
// take less space. |
| 67 |
limit = 100 |
| 68 |
} |
| 69 |
for _, p := range pos { |
| 70 |
m := s.maxMatchFrom(chunks, p, limit) |
| 71 |
if len(m) > max { |
| 72 |
match = m |
| 73 |
max = len(m) |
| 74 |
} |
| 75 |
if limit != 0 && limit == max { |
| 76 |
break |
| 77 |
} |
| 78 |
} |
| 79 |
return max, newFileSeedSegment(s.srcFile, match, s.canReflink) |
| 80 |
} |
| 81 |
|
| 82 |
func (s *FileSeed) RegenerateIndex(ctx context.Context, n int, attempt int, seedNumber int) error { |
| 83 |
chunkingPrefix := fmt.Sprintf("Attempt %d: Chunking Seed %d ", attempt, seedNumber) |
| 84 |
index, _, err := IndexFromFile(ctx, s.srcFile, n, s.index.Index.ChunkSizeMin, s.index.Index.ChunkSizeAvg, |
| 85 |
s.index.Index.ChunkSizeMax, NewProgressBar(chunkingPrefix)) |
| 86 |
if err != nil { |
| 87 |
return err |
| 88 |
} |
| 89 |
|
| 90 |
s.index = index |
| 91 |
s.SetInvalid(false) |
| 92 |
s.pos = make(map[ChunkID][]int, len(s.index.Chunks)) |
| 93 |
for i, c := range s.index.Chunks { |
| 94 |
s.pos[c.ID] = append(s.pos[c.ID], i) |
| 95 |
} |
| 96 |
|
| 97 |
return nil |
| 98 |
} |
| 99 |
|
| 100 |
func (s *FileSeed) SetInvalid(value bool) { |
| 101 |
s.mu.Lock() |
| 102 |
defer s.mu.Unlock() |
| 103 |
s.isInvalid = value |
| 104 |
} |
| 105 |
|
| 106 |
func (s *FileSeed) IsInvalid() bool { |
| 107 |
s.mu.Lock() |
| 108 |
defer s.mu.Unlock() |
| 109 |
return s.isInvalid |
| 110 |
} |
| 111 |
|
| 112 |
// Returns a slice of chunks from the seed. Compares chunks from position 0 |
| 113 |
// with seed chunks starting at p. A "limit" value of zero means that there is no limit. |
| 114 |
func (s *FileSeed) maxMatchFrom(chunks []IndexChunk, p int, limit int) []IndexChunk { |
| 115 |
if len(chunks) == 0 { |
| 116 |
return nil |
| 117 |
} |
| 118 |
var ( |
| 119 |
sp int |
| 120 |
dp = p |
| 121 |
) |
| 122 |
for { |
| 123 |
if limit != 0 && sp == limit { |
| 124 |
break |
| 125 |
} |
| 126 |
if dp >= len(s.index.Chunks) || sp >= len(chunks) { |
| 127 |
break |
| 128 |
} |
| 129 |
if chunks[sp].ID != s.index.Chunks[dp].ID { |
| 130 |
break |
| 131 |
} |
| 132 |
dp++ |
| 133 |
sp++ |
| 134 |
} |
| 135 |
return s.index.Chunks[p:dp] |
| 136 |
} |
| 137 |
|
| 138 |
type fileSeedSegment struct { |
| 139 |
file string |
| 140 |
chunks []IndexChunk |
| 141 |
canReflink bool |
| 142 |
} |
| 143 |
|
| 144 |
func newFileSeedSegment(file string, chunks []IndexChunk, canReflink bool) *fileSeedSegment { |
| 145 |
return &fileSeedSegment{ |
| 146 |
canReflink: canReflink, |
| 147 |
file: file, |
| 148 |
chunks: chunks, |
| 149 |
} |
| 150 |
} |
| 151 |
|
| 152 |
func (s *fileSeedSegment) FileName() string { |
| 153 |
return s.file |
| 154 |
} |
| 155 |
|
| 156 |
func (s *fileSeedSegment) Size() uint64 { |
| 157 |
if len(s.chunks) == 0 { |
| 158 |
return 0 |
| 159 |
} |
| 160 |
last := s.chunks[len(s.chunks)-1] |
| 161 |
return last.Start + last.Size - s.chunks[0].Start |
| 162 |
} |
| 163 |
|
| 164 |
func (s *fileSeedSegment) WriteInto(dst *os.File, offset, length, blocksize uint64, isBlank bool) (uint64, uint64, error) { |
| 165 |
if length != s.Size() { |
| 166 |
return 0, 0, fmt.Errorf("unable to copy %d bytes from %s to %s : wrong size", length, s.file, dst.Name()) |
| 167 |
} |
| 168 |
src, err := os.Open(s.file) |
| 169 |
if err != nil { |
| 170 |
return 0, 0, err |
| 171 |
} |
| 172 |
defer src.Close() |
| 173 |
|
| 174 |
// Do a straight copy if reflinks are not supported or blocks aren't aligned |
| 175 |
if !s.canReflink || s.chunks[0].Start%blocksize != offset%blocksize { |
| 176 |
return s.copy(dst, src, s.chunks[0].Start, length, offset) |
| 177 |
} |
| 178 |
return s.clone(dst, src, s.chunks[0].Start, length, offset, blocksize) |
| 179 |
} |
| 180 |
|
| 181 |
// Validate compares all chunks in this slice of the seed index to the underlying data |
| 182 |
// and fails if they don't match. |
| 183 |
func (s *fileSeedSegment) Validate(file *os.File) error { |
| 184 |
var buf []byte |
| 185 |
for _, c := range s.chunks { |
| 186 |
buf = slices.Grow(buf[:0], int(c.Size))[:c.Size] |
| 187 |
if _, err := file.ReadAt(buf, int64(c.Start)); err != nil { |
| 188 |
return err |
| 189 |
} |
| 190 |
sum := Digest.Sum(buf) |
| 191 |
if sum != c.ID { |
| 192 |
return fmt.Errorf("seed index for %s doesn't match its data", s.file) |
| 193 |
} |
| 194 |
} |
| 195 |
return nil |
| 196 |
} |
| 197 |
|
| 198 |
// Performs a plain copy of everything in the seed to the target, not cloning |
| 199 |
// of blocks. |
| 200 |
func (s *fileSeedSegment) copy(dst, src *os.File, srcOffset, length, dstOffset uint64) (uint64, uint64, error) { |
| 201 |
if _, err := dst.Seek(int64(dstOffset), io.SeekStart); err != nil { |
| 202 |
return 0, 0, err |
| 203 |
} |
| 204 |
if _, err := src.Seek(int64(srcOffset), io.SeekStart); err != nil { |
| 205 |
return 0, 0, err |
| 206 |
} |
| 207 |
|
| 208 |
// Copy using a fixed buffer. Using io.Copy() with a LimitReader will make it |
| 209 |
// create a buffer matching N of the LimitReader which can be too large |
| 210 |
copied, err := io.CopyBuffer(dst, io.LimitReader(src, int64(length)), make([]byte, 64*1024)) |
| 211 |
return uint64(copied), 0, err |
| 212 |
} |
| 213 |
|
| 214 |
// Reflink the overlapping blocks in the two ranges and copy the bit before and |
| 215 |
// after the blocks. |
| 216 |
func (s *fileSeedSegment) clone(dst, src *os.File, srcOffset, srcLength, dstOffset, blocksize uint64) (uint64, uint64, error) { |
| 217 |
if srcOffset%blocksize != dstOffset%blocksize { |
| 218 |
return 0, 0, fmt.Errorf("reflink ranges not aligned between %s and %s", src.Name(), dst.Name()) |
| 219 |
} |
| 220 |
|
| 221 |
srcAlignStart := (srcOffset/blocksize + 1) * blocksize |
| 222 |
srcAlignEnd := (srcOffset + srcLength) / blocksize * blocksize |
| 223 |
|
| 224 |
// If the range is too small to contain a full aligned block, there is |
| 225 |
// nothing that can be cloned. Copy the whole range instead. This also |
| 226 |
// guards against srcAlignEnd-srcAlignStart underflowing, and against |
| 227 |
// calling CloneRange with a zero length, which FICLONERANGE interprets |
| 228 |
// as "clone to the end of the source file". Filesystems with large |
| 229 |
// blocks, like ZFS with the default 128k recordsize, hit this case |
| 230 |
// frequently. |
| 231 |
if srcAlignEnd <= srcAlignStart { |
| 232 |
return s.copy(dst, src, srcOffset, srcLength, dstOffset) |
| 233 |
} |
| 234 |
|
| 235 |
dstAlignStart := (dstOffset/blocksize + 1) * blocksize |
| 236 |
alignLength := srcAlignEnd - srcAlignStart |
| 237 |
dstAlignEnd := dstAlignStart + alignLength |
| 238 |
|
| 239 |
// fill the area before the first aligned block |
| 240 |
var copied uint64 |
| 241 |
c1, _, err := s.copy(dst, src, srcOffset, srcAlignStart-srcOffset, dstOffset) |
| 242 |
if err != nil { |
| 243 |
return c1, 0, err |
| 244 |
} |
| 245 |
copied += c1 |
| 246 |
// fill the area after the last aligned block |
| 247 |
c2, _, err := s.copy(dst, src, srcAlignEnd, srcOffset+srcLength-srcAlignEnd, dstAlignEnd) |
| 248 |
if err != nil { |
| 249 |
return copied + c2, 0, err |
| 250 |
} |
| 251 |
copied += c2 |
| 252 |
// close the aligned blocks |
| 253 |
if err := cloneRange(dst, src, srcAlignStart, alignLength, dstAlignStart); err != nil { |
| 254 |
// Not every filesystem that passes the CanClone probe can clone every |
| 255 |
// range. ZFS for example requires alignment to its record size and |
| 256 |
// refuses to clone data that hasn't been committed to disk yet. Fall |
| 257 |
// back to copying the blocks. |
| 258 |
c3, _, err := s.copy(dst, src, srcAlignStart, alignLength, dstAlignStart) |
| 259 |
return copied + c3, 0, err |
| 260 |
} |
| 261 |
return copied, alignLength, nil |
| 262 |
} |