1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
|
/*
Manage a deduplicated versionned backups repository.
Sample repository:
```
repo/
├── 00000/
│ ├── chunks/
│ │ ├── 000000000000000
│ │ ├── 000000000000001
│ │ ├── 000000000000002
│ │ ├── 000000000000003
│ ├── files
│ └── recipe
└── 00001/
├── chunks/
│ ├── 000000000000000
│ ├── 000000000000001
├── files
└── recipe
```
*/
package main
import (
"bufio"
"bytes"
"encoding/gob"
"fmt"
"hash"
"io"
"io/fs"
"log"
"os"
"path"
"path/filepath"
"reflect"
"github.com/chmduquesne/rollinghash/rabinkarp64"
)
type FingerprintMap map[uint64]*ChunkId
type SketchMap map[uint64][]*ChunkId
type Repo struct {
path string
chunkSize int
sketchWSize int
sketchSfCount int
sketchFCount int
pol rabinkarp64.Pol
differ Differ
patcher Patcher
fingerprints FingerprintMap
sketches SketchMap
}
type File struct {
Path string
Size int64
}
func NewRepo(path string) *Repo {
err := os.MkdirAll(path, 0775)
// if err != nil {
// log.Panicln(err)
// }
var seed int64 = 1
p, err := rabinkarp64.RandomPolynomial(seed)
if err != nil {
log.Panicln(err)
}
return &Repo{
path: path,
chunkSize: 8 << 10,
sketchWSize: 32,
sketchSfCount: 3,
sketchFCount: 4,
pol: p,
differ: &Bsdiff{},
patcher: &Bsdiff{},
fingerprints: make(FingerprintMap),
sketches: make(SketchMap),
}
}
func (r *Repo) Differ() Differ {
return r.differ
}
func (r *Repo) Patcher() Patcher {
return r.patcher
}
func (r *Repo) Commit(source string) {
versions := r.loadVersions()
newVersion := len(versions)
newPath := path.Join(r.path, fmt.Sprintf(versionFmt, newVersion))
newChunkPath := path.Join(newPath, chunksName)
newFilesPath := path.Join(newPath, filesName)
newRecipePath := path.Join(newPath, recipeName)
os.Mkdir(newPath, 0775)
os.Mkdir(newChunkPath, 0775)
reader, writer := io.Pipe()
oldChunks := make(chan IdentifiedChunk, 16)
files := listFiles(source)
go r.loadChunks(versions, oldChunks)
go concatFiles(files, writer)
r.hashChunks(oldChunks)
recipe := r.matchStream(reader, newVersion)
storeRecipe(newRecipePath, recipe)
storeFileList(newFilesPath, files)
fmt.Println(files)
}
func (r *Repo) loadVersions() []string {
var versions []string
files, err := os.ReadDir(r.path)
if err != nil {
log.Fatalln(err)
}
for _, f := range files {
if !f.IsDir() {
continue
}
versions = append(versions, path.Join(r.path, f.Name()))
}
return versions
}
func listFiles(path string) []File {
var files []File
err := filepath.Walk(path,
func(p string, i fs.FileInfo, err error) error {
if err != nil {
log.Println(err)
return err
}
if i.IsDir() {
return nil
}
files = append(files, File{p, i.Size()})
return nil
})
if err != nil {
log.Println(err)
}
return files
}
func concatFiles(files []File, stream io.WriteCloser) {
for _, f := range files {
file, err := os.Open(f.Path)
if err != nil {
log.Printf("Error reading file '%s': %s\n", f.Path, err)
continue
}
io.Copy(stream, file)
}
stream.Close()
}
func (r *Repo) chunkMinLen() int {
return SuperFeatureSize(r.chunkSize, r.sketchSfCount, r.sketchFCount)
}
func (r *Repo) chunkStream(stream io.Reader, chunks chan<- []byte) {
var buff []byte
var prev, read = r.chunkSize, 0
var err error
for err != io.EOF {
if prev == r.chunkSize {
buff = make([]byte, r.chunkSize)
prev, err = stream.Read(buff)
} else {
read, err = stream.Read(buff[prev:])
prev += read
}
if err != nil && err != io.EOF {
log.Println(err)
}
if prev == r.chunkSize {
chunks <- buff
}
}
if prev != r.chunkSize {
chunks <- buff[:prev]
}
close(chunks)
}
func storeFileList(dest string, files []File) {
file, err := os.Create(dest)
if err == nil {
encoder := gob.NewEncoder(file)
err = encoder.Encode(files)
}
if err != nil {
log.Panicln(err)
}
if err = file.Close(); err != nil {
log.Panicln(err)
}
}
func loadFileList(path string) []File {
var files []File
file, err := os.Open(path)
if err == nil {
decoder := gob.NewDecoder(file)
err = decoder.Decode(&files)
}
if err != nil {
log.Panicln(err)
}
if err = file.Close(); err != nil {
log.Panicln(err)
}
return files
}
func storeChunks(dest string, chunks <-chan []byte) {
i := 0
for c := range chunks {
path := path.Join(dest, fmt.Sprintf(chunkIdFmt, i))
err := os.WriteFile(path, c, 0664)
if err != nil {
log.Println(err)
}
i++
}
}
// TODO: use atoi for chunkid
func (r *Repo) loadChunks(versions []string, chunks chan<- IdentifiedChunk) {
for i, v := range versions {
p := path.Join(v, chunksName)
entries, err := os.ReadDir(p)
if err != nil {
log.Printf("Error reading version '%05d' in '%s' chunks: %s", i, v, err)
}
for j, e := range entries {
if e.IsDir() {
continue
}
f := path.Join(p, e.Name())
buff, err := os.ReadFile(f)
if err != nil {
log.Printf("Error reading chunk '%s': %s", f, err.Error())
}
c := NewLoadedChunk(
&ChunkId{
Ver: i,
Idx: uint64(j),
},
buff,
)
chunks <- c
}
}
close(chunks)
}
// hashChunks calculates the hashes for a channel of chunks.
//
// For each chunk, both a fingerprint (hash over the full content) and a sketch
// (resemblance hash based on maximal values of regions) are calculated and
// stored in an hashmap.
func (r *Repo) hashChunks(chunks <-chan IdentifiedChunk) {
hasher := rabinkarp64.NewFromPol(r.pol)
for c := range chunks {
r.hashAndStoreChunk(c, hasher)
}
}
func (r *Repo) hashAndStoreChunk(chunk IdentifiedChunk, hasher hash.Hash64) {
hasher.Reset()
io.Copy(hasher, chunk.Reader())
fingerprint := hasher.Sum64()
sketch, _ := SketchChunk(chunk, r.pol, r.chunkSize, r.sketchWSize, r.sketchSfCount, r.sketchFCount)
r.storeChunkId(chunk.GetId(), fingerprint, sketch)
}
func (r *Repo) storeChunkId(id *ChunkId, fingerprint uint64, sketch []uint64) {
r.fingerprints[fingerprint] = id
for _, s := range sketch {
prev := r.sketches[s]
if contains(prev, id) {
continue
}
r.sketches[s] = append(prev, id)
}
}
func contains(s []*ChunkId, id *ChunkId) bool {
for _, v := range s {
if v == id {
return true
}
}
return false
}
func (r *Repo) findSimilarChunk(chunk Chunk) (*ChunkId, bool) {
var similarChunks = make(map[ChunkId]int)
var max int
var similarChunk *ChunkId
sketch, _ := SketchChunk(chunk, r.pol, r.chunkSize, r.sketchWSize, r.sketchSfCount, r.sketchFCount)
for _, s := range sketch {
chunkIds, exists := r.sketches[s]
if !exists {
continue
}
for _, id := range chunkIds {
count := similarChunks[*id]
count += 1
log.Printf("Found %d %d time(s)", id, count)
if count > max {
similarChunk = id
}
similarChunks[*id] = count
}
}
return similarChunk, similarChunk != nil
}
func (r *Repo) tryDeltaEncodeChunk(temp BufferedChunk) (Chunk, bool) {
id, found := r.findSimilarChunk(temp)
if found {
var buff bytes.Buffer
if err := r.differ.Diff(id.Reader(r), temp.Reader(), &buff); err != nil {
log.Println("Error trying delta encode chunk:", temp, "with source:", id, ":", err)
} else {
return &DeltaChunk{
repo: r,
Source: id,
Patch: buff.Bytes(),
Size: temp.Len(),
}, true
}
}
return temp, false
}
// encodeTempChunk first tries to delta-encode the given chunk before attributing
// it an Id and saving it into the fingerprints and sketches maps.
func (r *Repo) encodeTempChunk(temp BufferedChunk, version int, last *uint64) (chunk Chunk, isDelta bool) {
chunk, isDelta = r.tryDeltaEncodeChunk(temp)
if isDelta {
log.Println("Add new delta chunk")
return
}
if chunk.Len() == r.chunkSize {
id := &ChunkId{Ver: version, Idx: *last}
*last++
ic := NewLoadedChunk(id, temp.Bytes())
hasher := rabinkarp64.NewFromPol(r.pol)
r.hashAndStoreChunk(ic, hasher)
ic.Store(r.path)
log.Println("Add new chunk", id)
return ic, false
}
log.Println("Add new partial chunk of size:", chunk.Len())
return
}
// encodeTempChunks encodes the current temporary chunks based on the value of the previous one.
// Temporary chunks can be partial. If the current chunk is smaller than the size of a
// super-feature and there exists a previous chunk, then both are merged before attempting
// to delta-encode them.
func (r *Repo) encodeTempChunks(prev BufferedChunk, curr BufferedChunk, version int, last *uint64) []Chunk {
if reflect.ValueOf(prev).IsNil() {
c, _ := r.encodeTempChunk(curr, version, last)
return []Chunk{c}
} else if curr.Len() < r.chunkMinLen() {
c, success := r.encodeTempChunk(NewTempChunk(append(prev.Bytes(), curr.Bytes()...)), version, last)
if success {
return []Chunk{c}
} else {
return []Chunk{prev, curr}
}
} else {
prevD, _ := r.encodeTempChunk(prev, version, last)
currD, _ := r.encodeTempChunk(curr, version, last)
return []Chunk{prevD, currD}
}
}
func (r *Repo) matchStream(stream io.Reader, version int) []Chunk {
var b byte
var chunks []Chunk
var prev *TempChunk
var last uint64
var err error
bufStream := bufio.NewReaderSize(stream, r.chunkSize*2)
buff := make([]byte, r.chunkSize, r.chunkSize*2)
if n, err := io.ReadFull(stream, buff); n < r.chunkSize {
if err == io.EOF {
chunks = append(chunks, NewTempChunk(buff[:n]))
return chunks
} else {
log.Panicf("Error Read only %d bytes with error '%s'\n", n, err)
}
}
hasher := rabinkarp64.NewFromPol(r.pol)
hasher.Write(buff)
for err != io.EOF {
h := hasher.Sum64()
chunkId, exists := r.fingerprints[h]
if exists {
if len(buff) > r.chunkSize && len(buff) < r.chunkSize*2 {
size := len(buff) - r.chunkSize
temp := NewTempChunk(buff[:size])
chunks = append(chunks, r.encodeTempChunks(prev, temp, version, &last)...)
prev = nil
} else if prev != nil {
c, _ := r.encodeTempChunk(prev, version, &last)
chunks = append(chunks, c)
prev = nil
}
log.Printf("Add existing chunk: %d\n", chunkId)
chunks = append(chunks, NewStoredChunk(r, chunkId))
buff = make([]byte, 0, r.chunkSize*2)
for i := 0; i < r.chunkSize && err == nil; i++ {
b, err = bufStream.ReadByte()
if err != io.EOF {
hasher.Roll(b)
buff = append(buff, b)
}
}
continue
}
if len(buff) == r.chunkSize*2 {
if prev != nil {
chunk, _ := r.encodeTempChunk(prev, version, &last)
chunks = append(chunks, chunk)
}
prev = NewTempChunk(buff[:r.chunkSize])
tmp := buff[r.chunkSize:]
buff = make([]byte, r.chunkSize, r.chunkSize*2)
copy(buff, tmp)
}
b, err = bufStream.ReadByte()
if err != io.EOF {
hasher.Roll(b)
buff = append(buff, b)
}
}
if len(buff) > 0 {
var temp *TempChunk
if len(buff) > r.chunkSize {
prev = NewTempChunk(buff[:r.chunkSize])
temp = NewTempChunk(buff[r.chunkSize:])
} else {
temp = NewTempChunk(buff)
}
chunks = append(chunks, r.encodeTempChunks(prev, temp, version, &last)...)
}
return chunks
}
func storeRecipe(dest string, recipe []Chunk) {
gob.Register(&LoadedChunk{})
gob.Register(&StoredChunk{})
gob.Register(&TempChunk{})
gob.Register(&DeltaChunk{})
file, err := os.Create(dest)
if err == nil {
encoder := gob.NewEncoder(file)
for _, c := range recipe {
if err = encoder.Encode(&c); err != nil {
log.Panicln(err)
}
}
}
if err != nil {
log.Panicln(err)
}
if err = file.Close(); err != nil {
log.Panicln(err)
}
}
func loadRecipe(path string) []Chunk {
var recipe []Chunk
gob.Register(&LoadedChunk{})
gob.Register(&StoredChunk{})
gob.Register(&TempChunk{})
gob.Register(&DeltaChunk{})
file, err := os.Open(path)
if err == nil {
decoder := gob.NewDecoder(file)
for i := 0; err == nil; i++ {
var c Chunk
if err = decoder.Decode(&c); err == nil {
recipe = append(recipe, c)
}
}
}
if err != nil && err != io.EOF {
log.Panicln(err)
}
if err = file.Close(); err != nil {
log.Panicln(err)
}
return recipe
}
// mergeTempChunks joins temporary partial chunks from an array of chunks if possible.
// If a chunk is smaller than the size required to calculate a super-feature,
// it is then appended to the previous consecutive temporary chunk if it exists.
func (r *Repo) mergeTempChunks(chunks []Chunk) (ret []Chunk) {
var prev *TempChunk
var curr *TempChunk
for _, c := range chunks {
tmp, isTmp := c.(*TempChunk)
if !isTmp {
if prev != nil && curr.Len() <= SuperFeatureSize(r.chunkSize, r.sketchSfCount, r.sketchFCount) {
prev.AppendFrom(curr.Reader())
} else if curr != nil {
ret = append(ret, curr)
}
ret = append(ret, c)
curr = nil
prev = nil
} else {
prev = curr
curr = tmp
if prev != nil {
ret = append(ret, prev)
}
}
}
if curr != nil {
ret = append(ret, curr)
}
return
}
func extractTempChunks(chunks []Chunk) (ret []*TempChunk) {
for _, c := range chunks {
tmp, isTmp := c.(*TempChunk)
if isTmp {
ret = append(ret, tmp)
}
}
return
}
func extractDeltaChunks(chunks []Chunk) (ret []*DeltaChunk) {
for _, c := range chunks {
tmp, isDelta := c.(*DeltaChunk)
if isDelta {
ret = append(ret, tmp)
}
}
return
}
|