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
|
/*
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"
"encoding/gob"
"fmt"
"hash"
"io"
"io/fs"
"log"
"os"
"path"
"path/filepath"
"github.com/chmduquesne/rollinghash/rabinkarp64"
)
type FingerprintMap map[uint64]*ChunkId
type SketchMap map[uint64][]*ChunkId
type Repo struct {
path string
}
type File struct {
Path string
Size int64
}
func NewRepo(path string) *Repo {
os.MkdirAll(path, 0775)
return &Repo{path}
}
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)
os.Mkdir(newPath, 0775)
os.Mkdir(newChunkPath, 0775)
reader, writer := io.Pipe()
oldChunks := make(chan StoredChunk, 16)
files := listFiles(source)
go r.loadChunks(versions, oldChunks)
go concatFiles(files, writer)
fingerprints, _ := hashChunks(oldChunks)
chunks := r.matchStream(reader, fingerprints)
extractNewChunks(chunks)
// storeChunks(newChunkPath, newChunks)
// storeFiles(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 chunkStream(stream io.Reader, chunks chan<- []byte) {
var buff []byte
var prev, read = chunkSize, 0
var err error
for err != io.EOF {
if prev == chunkSize {
buff = make([]byte, 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 == chunkSize {
chunks <- buff
}
}
if prev != chunkSize {
chunks <- buff
}
close(chunks)
}
func storeFileList(dest string, files []File) {
err := writeFile(dest, files)
if err != nil {
log.Println(err)
}
}
func loadFileList(path string) []File {
var files []File
err := readFile(path, &files)
if err != nil {
log.Println(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++
}
}
func (r *Repo) loadChunks(versions []string, chunks chan<- StoredChunk) {
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 which are then returned.
func hashChunks(chunks <-chan StoredChunk) (FingerprintMap, SketchMap) {
fingerprints := make(FingerprintMap)
sketches := make(SketchMap)
hasher := hash.Hash64(rabinkarp64.New())
for c := range chunks {
hasher.Reset()
io.Copy(hasher, c.Reader())
h := hasher.Sum64()
fingerprints[h] = c.Id()
sketch, _ := SketchChunk(c, 32, 3, 4)
for _, s := range sketch {
sketches[s] = append(sketches[s], c.Id())
}
}
return fingerprints, sketches
}
func findSimilarChunks(chunks []Chunk, sketches SketchMap) {
for i, c := range chunks {
log.Println("New chunk:", i)
sketch, _ := SketchChunk(c, 32, 3, 4)
for _, s := range sketch {
chunkId, exists := sketches[s]
if exists {
log.Println("Found similar chunks: ", chunkId)
}
}
}
}
func readChunk(stream io.Reader) ([]byte, error) {
buff := make([]byte, chunkSize)
_, err := io.ReadFull(stream, buff)
return buff, err
}
func (r *Repo) matchStream(stream io.Reader, fingerprints FingerprintMap) []Chunk {
var b byte
var chunks []Chunk
bufStream := bufio.NewReaderSize(stream, chunkSize)
buff, err := readChunk(bufStream)
if err == io.EOF {
chunks = append(chunks, NewTempChunk(buff))
return chunks
}
hasher := rabinkarp64.New()
hasher.Write(buff)
buff = make([]byte, 0, chunkSize)
for err != io.EOF {
h := hasher.Sum64()
chunkId, exists := fingerprints[h]
if exists {
if len(buff) > 0 {
log.Printf("Add new partial chunk of size: %d\n", len(buff))
chunks = append(chunks, NewTempChunk(buff[:chunkSize]))
}
log.Printf("Add existing chunk: %d\n", chunkId)
chunks = append(chunks, NewChunkFile(r, chunkId))
buff = make([]byte, 0, chunkSize)
for i := 0; i < chunkSize && err == nil; i++ {
b, err = bufStream.ReadByte()
hasher.Roll(b)
}
continue
}
if len(buff) == chunkSize {
log.Println("Add new chunk")
chunks = append(chunks, NewTempChunk(buff))
buff = make([]byte, 0, chunkSize)
}
b, err = bufStream.ReadByte()
if err != io.EOF {
hasher.Roll(b)
buff = append(buff, b)
}
}
if len(buff) > 0 {
chunks = append(chunks, NewTempChunk(buff))
}
return chunks
}
// extractNewChunks extracts new chunks from an array of chunks and
// returns them in an array of consecutive new chunk's array
func extractNewChunks(chunks []Chunk) (ret [][]Chunk) {
var i int
ret = append(ret, nil)
for _, c := range chunks {
_, isTmp := c.(*TempChunk)
if !isTmp {
if len(ret[i]) != 0 {
i++
ret = append(ret, nil)
}
} else {
ret[i] = append(ret[i], c)
}
}
if len(ret[i]) == 0 {
ret = ret[:i]
}
return
}
func writeFile(filePath string, object interface{}) error {
file, err := os.Create(filePath)
if err == nil {
encoder := gob.NewEncoder(file)
encoder.Encode(object)
}
file.Close()
return err
}
func readFile(filePath string, object interface{}) error {
file, err := os.Open(filePath)
if err == nil {
decoder := gob.NewDecoder(file)
err = decoder.Decode(object)
}
file.Close()
return err
}
|