This repository has been archived by the owner on Aug 15, 2020. It is now read-only.
/
archive.go
550 lines (517 loc) · 14.8 KB
/
archive.go
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
/* Copyright 2012 Marc-Antoine Ruel. 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 main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync/atomic"
"time"
"github.com/maruel/dumbcas/dumbcaslib"
"github.com/maruel/interrupt"
"github.com/maruel/subcommands"
)
var cmdArchive = &subcommands.Command{
UsageLine: "archive <.toArchive>",
ShortDesc: "archive files to a dumbcas archive",
LongDesc: "Archives files listed in <.toArchive> file to a directory in the DumbCas(tm) layout. Files listed may be in relative path or in absolute path and may contain environment variables.",
CommandRun: func() subcommands.CommandRun {
c := &archiveRun{}
c.Init()
c.Flags.StringVar(&c.comment, "comment", "", "Comment to embed in the file")
return c
},
}
type archiveRun struct {
CommonFlags
comment string
}
// For an item, tries to refresh its sha1 efficiently.
func updateFile(cache *dumbcaslib.EntryCache, item inputItem) (bool, error) {
now := time.Now().Unix()
size := item.Size()
timestamp := item.ModTime().Unix()
// If the file already exist, check for the timestamp and size to match.
if cache.Size == size && cache.Timestamp == timestamp {
cache.LastTested = now
return false, nil
}
digest, err := sha1File(item.fullPath)
if err != nil {
return false, err
}
cache.Sha1 = digest
cache.Size = size
cache.Timestamp = timestamp
cache.LastTested = now
return true, nil
}
// Reads a file with each line as an entry in the slice.
func readFileAsStrings(filepath string) ([]string, error) {
f, err := os.Open(filepath)
if err != nil {
return nil, fmt.Errorf("Failed to read %s: %s", filepath, err)
}
b := bufio.NewReader(f)
lines := []string{}
for {
line, err := b.ReadString('\n')
line = strings.TrimSpace(line)
if line != "" {
lines = append(lines, line)
}
if err == io.EOF {
err = nil
break
}
if err != nil {
err = fmt.Errorf("Failed to read %s: %s", filepath, err)
break
}
}
return lines, err
}
type syncInt int64
func (s *syncInt) Add(i int64) {
atomic.AddInt64((*int64)(s), i)
}
func (s *syncInt) Get() int64 {
return atomic.LoadInt64((*int64)(s))
}
func (s *syncInt) g() syncInt {
return syncInt(s.Get())
}
// Statistics are used with atomic functions. While not Go-idiomatic, it's much
// faster than using mutexes when calling i++ 100k times.
type statsValues struct {
errors syncInt
found syncInt // enumerateInputs()
totalSize syncInt
nbHashed syncInt // hashInputs()
bytesHashed syncInt
nbNotHashed syncInt
bytesNotHashed syncInt
nbArchived syncInt // archiveInputs()
bytesArchived syncInt
nbNotArchived syncInt
bytesNotArchived syncInt
}
// Stores statistic of the on-going process.
type stats struct {
statsValues
interrupted syncInt
out chan<- string
done chan<- bool
}
// Creates a copy of statsValues. Note that the copy *may* be inconsistent.
func (s *statsValues) Copy() *statsValues {
return &statsValues{
s.errors.g(),
s.found.g(),
s.totalSize.g(),
s.nbHashed.g(),
s.bytesHashed.g(),
s.nbNotHashed.g(),
s.bytesNotHashed.g(),
s.nbArchived.g(),
s.bytesArchived.g(),
s.nbNotArchived.g(),
s.bytesNotArchived.g(),
}
}
// equals compares two local copy of statsValues. Must *not* be used on a stats instance.
func (s *statsValues) equals(rhs *statsValues) bool {
return (s.errors.Get() == rhs.errors.Get() &&
s.found.Get() == rhs.found.Get() &&
s.totalSize.Get() == rhs.totalSize.Get() &&
s.nbHashed.Get() == rhs.nbHashed.Get() &&
s.bytesHashed.Get() == rhs.bytesHashed.Get() &&
s.nbNotHashed.Get() == rhs.nbNotHashed.Get() &&
s.bytesNotHashed.Get() == rhs.bytesNotHashed.Get() &&
s.nbArchived.Get() == rhs.nbArchived.Get() &&
s.bytesArchived.Get() == rhs.bytesArchived.Get() &&
s.nbNotArchived.Get() == rhs.nbNotArchived.Get() &&
s.bytesNotArchived.Get() == rhs.bytesNotArchived.Get())
}
type inputItem struct {
fullPath string
relPath string
os.FileInfo
}
// enumerateInputs reads the directories trees of each inputs and send each
// file into the output channel.
func (s *stats) enumerateInputs(inputs []string) <-chan inputItem {
// Throtttle after 128k entries.
c := make(chan inputItem, 128000)
go func() {
start := time.Now().UTC()
defer func() {
close(c)
s.done <- true
}()
// Do each entry serially. In theory there would be marginal gain by doing
// them concurrently if the inputs are on different drives but for the
// common use case where it's multiple directories on a single disk-based
// HD, it's going to be slower.
for _, input := range inputs {
stat, err := os.Stat(input)
if err != nil {
// Eat the error and continue archiving other items.
s.errors.Add(1)
s.out <- fmt.Sprintf("Failed to process %s: %s", input, err)
continue
}
if stat.IsDir() {
// Send the items back in the channel.
d := dumbcaslib.EnumerateTree(input)
cont := true
for cont {
select {
case <-interrupt.Channel:
// Early exit.
s.interrupted.Add(1)
return
case item, ok := <-d:
if !ok {
// Move on the next item.
cont = false
continue
}
if item.Error != nil {
// Eat the error and continue archiving other items.
s.errors.Add(1)
s.out <- fmt.Sprintf("Failed to process %s: %s", input, err)
} else if !item.IsDir() {
// Ignores directories. This tool is backing up content, not
// directories.
s.found.Add(1)
s.totalSize.Add(item.Size())
// TODO(maruel): Not necessarily true?
relPath := item.FullPath[len(input)+1:]
//s.out <- fmt.Sprintf("%s: %d", relPath, item.Size())
c <- inputItem{item.FullPath, relPath, item.FileInfo}
}
}
}
} else {
s.found.Add(1)
s.totalSize.Add(stat.Size())
relPath := filepath.Base(input)
c <- inputItem{input, relPath, stat}
}
}
end := time.Now().UTC()
s.out <- fmt.Sprintf("Done enumerating inputs: %s", end.Sub(start).String())
}()
return c
}
type itemToArchive struct {
fullPath string
relPath string
sha1 string
size int64
}
// Calculates each entry. Assumes inputs is cleaned paths.
func (s *stats) hashInputs(a DumbcasApplication, inputs <-chan inputItem) <-chan itemToArchive {
c := make(chan itemToArchive, 4096)
go func() {
// LoadCache must return a valid Cache instance even in case of failure.
cache, err := a.LoadCache()
if err != nil {
s.out <- fmt.Sprintf("Failed to load cache: %s\nWARNING: It will be unbearably slow!", err)
}
defer func() {
// Must save the cache *before* sending the 'done' signal.
close(c)
// TODO(maruel): Surface the error.
_ = cache.Close()
s.done <- true
}()
for {
select {
case <-interrupt.Channel:
// Early exit.
s.interrupted.Add(1)
return
case item, ok := <-inputs:
if !ok {
s.out <- fmt.Sprintf("Done hashing.")
return
}
if item.IsDir() {
panic("This can't happen; enumerateInputs() should eat all the directories.")
}
size := item.Size()
cachedItem := dumbcaslib.FindInCache(cache, item.fullPath)
if wasHashed, err := updateFile(cachedItem, item); err != nil {
// Eat the error and continue archiving other items.
s.errors.Add(1)
s.out <- fmt.Sprintf("Failed to process %s: %s", item.fullPath, err)
continue
} else if wasHashed {
//s.out <- fmt.Sprintf("Hashed: %s", item.relPath)
s.nbHashed.Add(1)
s.bytesHashed.Add(size)
} else {
s.nbNotHashed.Add(1)
s.bytesNotHashed.Add(size)
}
c <- itemToArchive{item.fullPath, item.relPath, cachedItem.Sha1, size}
}
}
}()
return c
}
// Archives one item in the CAS table.
func (s *stats) archiveItem(item itemToArchive, cas dumbcaslib.CasTable) {
f, err := os.Open(item.fullPath)
if err != nil {
s.errors.Add(1)
s.out <- fmt.Sprintf("Failed to archive %s: %s", item.fullPath, err)
return
}
defer func() {
_ = f.Close()
}()
err = cas.AddEntry(f, item.sha1)
if os.IsExist(err) {
s.nbNotArchived.Add(1)
s.bytesNotArchived.Add(item.size)
} else if err == nil {
s.nbArchived.Add(1)
s.bytesArchived.Add(item.size)
} else {
s.errors.Add(1)
s.out <- fmt.Sprintf("Failed to archive %s: %s", item.fullPath, err)
}
}
// Creates the Entry instance and the necessary Entry tree for |item|.
func makeEntry(root *dumbcaslib.Entry, item itemToArchive) {
for _, p := range strings.Split(item.relPath, string(filepath.Separator)) {
if root.Files == nil {
root.Files = make(map[string]*dumbcaslib.Entry)
}
if root.Files[p] == nil {
root.Files[p] = &dumbcaslib.Entry{}
}
root = root.Files[p]
}
root.Sha1 = item.sha1
root.Size = item.size
}
// Archives the items.
func (s *stats) archiveInputs(a DumbcasApplication, cas dumbcaslib.CasTable, items <-chan itemToArchive) <-chan string {
c := make(chan string)
go func() {
defer func() {
close(c)
s.done <- true
}()
entryRoot := &dumbcaslib.Entry{}
cont := true
for cont {
select {
case <-interrupt.Channel:
// Early exit.
s.interrupted.Add(1)
return
case item, ok := <-items:
if !ok {
cont = false
continue
}
//s.out <- fmt.Sprintf("Archiving: %s", item.relPath)
makeEntry(entryRoot, item)
s.archiveItem(item, cas)
}
}
// Serializes the entry file to archive it too.
data, err := json.Marshal(entryRoot)
if err != nil {
s.errors.Add(1)
s.out <- fmt.Sprintf("Failed to marshal entry file: %s", err)
} else {
entrySha1, err := dumbcaslib.AddBytes(cas, data)
if os.IsExist(err) {
s.nbNotArchived.Add(1)
s.bytesNotArchived.Add(int64(len(data)))
c <- entrySha1
} else if err == nil {
s.nbArchived.Add(1)
s.bytesArchived.Add(int64(len(data)))
c <- entrySha1
} else {
s.errors.Add(1)
s.out <- fmt.Sprintf("Failed to archive entry file: %s", err)
}
}
}()
return c
}
// Converts to absolute paths and evaluate environment variables.
func cleanupList(relDir string, inputs []string) {
for index, item := range inputs {
item = os.ExpandEnv(item)
item = strings.Replace(item, "/", string(filepath.Separator), 0)
if !filepath.IsAbs(item) {
item = filepath.Join(relDir, item)
}
inputs[index] = filepath.Clean(item)
}
}
func toMb(i int64) float64 {
return float64(i) / 1024. / 1024.
}
// Loads the list of inputs and starts the concurrent processes:
// - Enumerating the trees.
// - Updating the hash for each items in the cache.
// - Archiving items.
func (c *archiveRun) main(a DumbcasApplication, toArchiveArg string) error {
if err := c.Parse(a, true); err != nil {
return err
}
toArchive, err := filepath.Abs(toArchiveArg)
if err != nil {
return fmt.Errorf("Failed to process %s", toArchiveArg)
}
inputs, err := readFileAsStrings(toArchive)
if err != nil {
return err
}
// Make sure the file itself is archived too.
inputs = append(inputs, toArchive)
a.GetLog().Printf("Found %d entries to backup in %s", len(inputs), toArchive)
cleanupList(filepath.Dir(toArchive), inputs)
// Start the processes.
output := make(chan string)
done := make(chan bool, 3)
s := stats{out: output, done: done}
entry := s.archiveInputs(a, c.cas, s.hashInputs(a, s.enumerateInputs(inputs)))
headerWasPrinted := false
columns := []string{
"Found",
"Hashed",
"In cache",
"Archived",
"Skipped",
"Done",
}
for i := range columns {
columns[i] = fmt.Sprintf("%-19s", columns[i])
}
column := strings.TrimSpace(strings.Join(columns, ""))
errDone := errors.New("Dummy")
prevStats := s.Copy()
for err == nil {
select {
case line := <-output:
a.GetLog().Print(line)
case <-interrupt.Channel:
// Early exit. Note this as an error.
err = fmt.Errorf("Was interrupted.")
case item, ok := <-entry:
if !ok {
e := s.errors.Get()
if e != 0 {
err = fmt.Errorf("Got %d errors!", e)
} else if s.interrupted.Get() != 0 {
err = fmt.Errorf("Was interrupted.")
} else {
err = fmt.Errorf("Unexpected error.")
}
continue
}
if item != "" {
node := &dumbcaslib.Node{Entry: item, Comment: c.comment}
_, err = c.nodes.AddEntry(node, filepath.Base(toArchive))
err = errDone
} else {
e := s.errors.Get()
if e != 0 {
err = fmt.Errorf("Got %d errors!", e)
} else if s.interrupted.Get() != 0 {
err = fmt.Errorf("Was interrupted.")
} else {
err = fmt.Errorf("Unexpected error.")
}
}
case <-time.After(5 * time.Second):
nextStats := s.Copy()
if !prevStats.equals(nextStats) {
if !headerWasPrinted {
a.GetLog().Printf(column)
headerWasPrinted = true
}
prevStats = nextStats
fractionDone := float64(prevStats.bytesArchived.Get()+prevStats.bytesNotArchived.Get()) / float64(prevStats.totalSize.Get())
a.GetLog().Printf(
"%6d(%8.1fmb) %6d(%8.1fmb) %6d(%8.1fmb) %6d(%8.1fmb) %6d(%8.1fmb) %3.1f%% %d errors",
prevStats.found.Get(),
toMb(prevStats.totalSize.Get()),
prevStats.nbHashed.Get(),
toMb(prevStats.bytesHashed.Get()),
prevStats.nbNotHashed.Get(),
toMb(prevStats.bytesNotHashed.Get()),
prevStats.nbArchived.Get(),
toMb(prevStats.bytesArchived.Get()),
prevStats.nbNotArchived.Get(),
toMb(prevStats.bytesNotArchived.Get()),
100.*fractionDone,
prevStats.errors.Get())
}
}
}
if err == errDone {
err = nil
}
if interrupt.IsSet() {
fmt.Fprintf(a.GetOut(), "Was interrupted, waiting for processes to terminate.\n")
}
// Make sure all the worker threads are done. They may still be processing in
// case of interruption.
for i := 0; i < 3; i++ {
<-done
}
fmt.Fprintf(a.GetOut(), column+"\n")
fractionDone := float64(s.bytesArchived.Get()+s.bytesNotArchived.Get()) / float64(s.totalSize.Get())
fmt.Fprintf(
a.GetOut(),
"%7d(%7.1fmb) %7d(%7.1fmb) %7d(%7.1fmb) %7d(%7.1fmb) %7d(%7.1fmb) %3.1f%% %d errors\n",
s.found.Get(),
toMb(s.totalSize.Get()),
s.nbHashed.Get(),
toMb(s.bytesHashed.Get()),
s.nbNotHashed.Get(),
toMb(s.bytesNotHashed.Get()),
s.nbArchived.Get(),
toMb(s.bytesArchived.Get()),
s.nbNotArchived.Get(),
toMb(s.bytesNotArchived.Get()),
100.*fractionDone,
s.errors.Get())
return nil
}
func (c *archiveRun) Run(a subcommands.Application, args []string, _ subcommands.Env) int {
if len(args) != 1 {
fmt.Fprintf(a.GetErr(), "%s: Must only provide a .toArchive file.\n", a.GetName())
return 1
}
interrupt.HandleCtrlC()
d := a.(DumbcasApplication)
if err := c.main(d, args[0]); err != nil {
fmt.Fprintf(a.GetErr(), "%s: %s\n", a.GetName(), err)
return 1
}
return 0
}