-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathclone.go
More file actions
413 lines (334 loc) · 9.35 KB
/
clone.go
File metadata and controls
413 lines (334 loc) · 9.35 KB
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
/*
* Copyright 2016 Frank Wessels <fwessels@xs4all.nl>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package s3git
import (
"encoding/hex"
"fmt"
"github.com/s3git/s3git-go/internal/backend"
"github.com/s3git/s3git-go/internal/cas"
"github.com/s3git/s3git-go/internal/config"
"github.com/s3git/s3git-go/internal/core"
"github.com/s3git/s3git-go/internal/kv"
"io/ioutil"
"os"
"path"
"sort"
"sync"
)
type treeInput struct {
hash string
client backend.Backend
}
type treeOutput struct {
added []string
}
type cloneOptions struct {
leafSize uint32
maxRepoSize uint64
accessKey string
secretKey string
endpoint string
progressDownloading func(maxTicks int64)
progressProcessing func(maxTicks int64)
}
func CloneOptionSetLeafSize(leafSize uint32) func(optns *cloneOptions) {
return func(optns *cloneOptions) {
optns.leafSize = leafSize
}
}
func CloneOptionSetMaxRepoSize(maxRepoSize uint64) func(optns *cloneOptions) {
return func(optns *cloneOptions) {
optns.maxRepoSize = maxRepoSize
}
}
func CloneOptionSetAccessKey(accessKey string) func(optns *cloneOptions) {
return func(optns *cloneOptions) {
optns.accessKey = accessKey
}
}
func CloneOptionSetSecretKey(secretKey string) func(optns *cloneOptions) {
return func(optns *cloneOptions) {
optns.secretKey = secretKey
}
}
func CloneOptionSetEndpoint(endpoint string) func(optns *cloneOptions) {
return func(optns *cloneOptions) {
optns.endpoint = endpoint
}
}
func CloneOptionSetDownloadProgress(progressDownloading func(maxTicks int64)) func(optns *cloneOptions) {
return func(optns *cloneOptions) {
optns.progressDownloading = progressDownloading
}
}
func CloneOptionSetProcessingProgress(progressProcessing func(maxTicks int64)) func(optns *cloneOptions) {
return func(optns *cloneOptions) {
optns.progressProcessing = progressProcessing
}
}
type CloneOptions func(*cloneOptions)
// Clone a remote repository
func Clone(url, path string, options ...CloneOptions) (*Repository, error) {
optns := &cloneOptions{}
for _, op := range options {
op(optns)
}
err := config.SaveConfigFromUrl(url, path, optns.accessKey, optns.secretKey, optns.endpoint, optns.leafSize, optns.maxRepoSize)
if err != nil {
return nil, err
}
repo, err := OpenRepository(path)
if err != nil {
return nil, err
}
client, err := backend.GetDefaultClient()
if err != nil {
return nil, err
}
progressDummy := func(total int64) {}
// Plug in dummy progress calls if unset
if optns.progressDownloading == nil {
optns.progressDownloading = progressDummy
}
if optns.progressProcessing == nil {
optns.progressProcessing = progressDummy
}
err = clone(client, optns.progressDownloading, optns.progressProcessing)
if err != nil {
return nil, err
}
return repo, nil
}
func treeDownloader(trees <-chan treeInput, results chan<- treeOutput, errs chan<- error) {
for t := range trees {
// Pull down tree object
cas.PullBlobDownToLocalDisk(t.hash, kv.TREE, t.client)
to, err := core.GetTreeObject(t.hash)
if err != nil {
errs <- fmt.Errorf("core.GetTreeObject", err)
return
}
results <- treeOutput{added: to.S3gitAdded}
// Delete the chunks for the tree object since we are unlikely the need it again
err = cas.DeleteLeavesForBlob(t.hash)
if err != nil {
errs <- fmt.Errorf("DeleteChunksForBlob error: ", err)
return
}
}
}
func clone(client backend.Backend, progressDownloading, progressProcessing func(maxTicks int64)) error {
// Get map of prefixes already in store
prefixesInBackend, err := listPrefixes(client)
if err != nil {
return err
}
if len(prefixesInBackend) == 0 {
return nil
}
var wg sync.WaitGroup
trees := make(chan treeInput)
results := make(chan treeOutput)
// TODO: Handle error(s) read from error channel
errs := make(chan error)
// Start multiple downloaders in parallel
for i := 0; i <= 16; i++ {
wg.Add(1)
go func() {
defer wg.Done()
treeDownloader(trees, results, errs)
}()
}
// Push trees onto input channel
go func() {
progressDownloading(int64(len(prefixesInBackend)))
for prefix, _ := range prefixesInBackend {
// TODO: Make resistant to crashes/interrupts, e.g. first save blobs, then trees, then commits, and finally prefix objects
cas.PullBlobDownToLocalDisk(prefix, kv.PREFIX, client)
po, err := core.GetPrefixObject(prefix)
if err != nil {
errs <- fmt.Errorf("core.GetCommitObject error: ", err)
return
}
// Now pull down commit object
cas.PullBlobDownToLocalDisk(po.S3gitFollowMe, kv.COMMIT, client)
co, err := core.GetCommitObject(po.S3gitFollowMe)
if err != nil {
errs <- fmt.Errorf("core.GetCommitObject error: ", err)
return
}
// Mark warm and cold parents as parents
err = co.MarkWarmAndColdParents()
if err != nil {
errs <- fmt.Errorf("co.MarkWarmAndColdParents error: ", err)
return
}
if co.S3gitTree != "" {
trees <- treeInput{hash: co.S3gitTree, client: client}
}
if co.S3gitSnapshot != "" {
err = cacheKeysInKV([]string{co.S3gitSnapshot}, kv.SNAPSHOT)
if err != nil {
return
}
}
progressDownloading(int64(len(prefixesInBackend)))
}
// Close input channel
close(trees)
}()
// Wait for workers to complete
go func() {
wg.Wait()
close(results) // Close output channel
}()
for r := range results {
// Cache root hash for all added blobs in this commit ...
err := cacheKeyForBlobsToLocalDiskFirst(r.added)
if err != nil {
return err
}
}
// As last step first stop the keys and import sorted list into KV
if err := sortAndImportKeys(progressProcessing); err != nil {
return err
}
return nil
}
// Name for temp files storing blob hashes
func hiddenKeyFilename(index int) string {
return fmt.Sprintf("%s/.keys-0x%02x.dat", path.Join(config.Config.BasePath, config.S3GIT_DIR), index)
}
func appendBytes(slice []byte, data []byte) []byte {
m := len(slice)
n := m + len(data)
if n > cap(slice) { // if necessary, reallocate
// allocate double what's needed, for future growth.
newSlice := make([]byte, (n+1)*2)
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0:n]
copy(slice[m:n], data)
return slice
}
func cacheKeyForBlobsToLocalDiskFirst(added []string) error {
keyArray := make([][]byte, 256)
for index, _ := range keyArray {
keyArray[index] = make([]byte, 0, treeBatchSize*cas.KeySize)
}
count := 0
for _, add := range added {
key, _ := hex.DecodeString(add)
index := uint(key[0])
keyArray[index] = appendBytes(keyArray[index], key[:])
count++
}
// First create (empty) files if they do not already exist
for i := 0; i < 0x100; i++ {
filename := hiddenKeyFilename(i)
if _, err := os.Stat(filename); os.IsNotExist(err) {
f, err := os.OpenFile(filename, os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return err
}
f.Close()
}
}
// Append new keys to file
for i := 0; i < 0x100; i++ {
filename := hiddenKeyFilename(i)
f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0666)
if err != nil {
return err
}
if _, err = f.Write(keyArray[i]); err != nil {
return err
}
f.Close()
}
return nil
}
type sortKeys [][]byte
func (s sortKeys) Less(i, j int) bool {
for index := 0; index < cas.KeySize; index++ {
if s[i][index] < s[j][index] {
return true
} else if s[i][index] > s[j][index] {
return false
}
}
return false
}
func (s sortKeys) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sortKeys) Len() int {
return len(s)
}
func sortKeysFunc(s [][]byte) [][]byte {
sort.Sort(sortKeys(s))
return s
}
func sortAndImportKeys(progressProcessing func(maxTicks int64)) error {
keyFiles := []string{}
// Find out number of keys in use
for keyNr := 0; keyNr < 0x100; keyNr++ {
keyfilename := hiddenKeyFilename(keyNr)
if stat, err := os.Stat(keyfilename); err == nil {
if stat.Size() > 0 {
keyFiles = append(keyFiles, keyfilename)
} else {
// File is empty, nothing to process, so remove file already
os.Remove(keyfilename)
}
}
}
progressProcessing(int64(len(keyFiles)))
for _, keyfilename := range keyFiles {
w1, _ := ioutil.ReadFile(keyfilename)
array := make([][]byte, len(w1)/cas.KeySize)
for i := 0; i < len(array); i++ {
array[i] = w1[cas.KeySize*i : cas.KeySize*(i+1)]
}
w2 := sortKeysFunc(array)
// Create arrays to be able to batch the operation
keys := make([][]byte, 0, treeBatchSize)
values := make([][]byte, 0, treeBatchSize)
for i := 0; i < len(w2); i++ {
keys = append(keys, w2[i])
values = append(values, nil)
if len(keys) == cap(keys) {
err := kv.AddMultiToLevel1(keys, values, kv.BLOB)
if err != nil {
return err
}
keys = keys[:0]
values = values[:0]
}
}
if len(keys) > 0 {
err := kv.AddMultiToLevel1(keys, values, kv.BLOB)
if err != nil {
return err
}
}
// We are done, remove the file
os.Remove(keyfilename)
progressProcessing(int64(len(keyFiles)))
}
return nil
}