forked from sahib/brig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fs.go
1729 lines (1404 loc) · 39.1 KB
/
fs.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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package catfs
import (
"archive/tar"
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"path"
"sort"
"strconv"
"strings"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/sahib/config"
capnp "zombiezen.com/go/capnproto2"
e "github.com/pkg/errors"
c "github.com/sahib/brig/catfs/core"
"github.com/sahib/brig/catfs/db"
ie "github.com/sahib/brig/catfs/errors"
"github.com/sahib/brig/catfs/mio"
"github.com/sahib/brig/catfs/mio/compress"
n "github.com/sahib/brig/catfs/nodes"
"github.com/sahib/brig/catfs/vcs"
"github.com/sahib/brig/util"
h "github.com/sahib/brig/util/hashlib"
)
// FS (short for Filesystem) is the central API entry for everything related to
// paths. It exposes a POSIX-like interface where path are mapped to the
// actual underlying hashes and the associated metadata.
//
// Additionally it supports version control commands like MakeCommit(),
// Checkout() etc. The API is file-centric, i.e. directories are created on
// the fly for some operations like Stage(). Empty directories can be created
// via Mkdir() though.
type FS struct {
mu sync.Mutex
// underlying key/value store
kv db.Database
// linker (holds all nodes together)
lkr *c.Linker
// garbage collector for dead metadata links
gc *c.GarbageCollector
// channel to schedule gc runs and quit the gc loop
gcControl chan bool
// channel to schedule auto commits and quit the loop
autoCommitControl chan bool
// Actual storage backend (e.g. ipfs or memory)
bk FsBackend
// internal config
cfg *config.Config
// cache for the isPinned operation
pinner *Pinner
// wether this fs is read only and cannot be changed.
// It can be change by applying patches though.
readOnly bool
}
// ErrReadOnly is returned when a file system was created in read only mode
// and a modifying operation was called on it.
var ErrReadOnly = errors.New("fs is read only")
// StatInfo describes the metadata of a single node.
// The concept is comparable to the POSIX stat() call.
type StatInfo struct {
// Path is the full path to the file
Path string
// TreeHash is the hash of the node in the DAG
TreeHash h.Hash
// ContentHash is the actual hash of the content
// (used to test for content equality)
ContentHash h.Hash
// BackendHash is the hash under which the file is reachable
// in the backend.
BackendHash h.Hash
// User is the name of the user that modified this node last.
User string
// Size in bytes
Size uint64
// Inode is a unique number specific to this node
Inode uint64
// Depth is the hierarchy level inside of this node (root has 0)
Depth int
// ModTime is the last modification timestamp
ModTime time.Time
// IsDir tells you if this node is a dir
IsDir bool
// IsPinned tells you if this node is pinned (either implicit or explicit)
IsPinned bool
// IsExplicit is true when the user pinned this node on purpose
IsExplicit bool
}
// DiffPair is a pair of nodes.
// It is returned by MakeDiff(), where the source
// is a node on the remote side and the dst node is
// a node on our side.
type DiffPair struct {
Src StatInfo
Dst StatInfo
}
// Diff is a list of things that changed between to commits
type Diff struct {
// Added is a list of nodes that were added newly
Added []StatInfo
// Removed is a list of nodes that were removed
Removed []StatInfo
// Ignored is a list of nodes that were not considered
Ignored []StatInfo
// Missing is a list of nodes that the remoe side is missing
Missing []StatInfo
// Moved is a list of nodes that changed path
Moved []DiffPair
// Merged is a list of nodes that can be merged automatically
Merged []DiffPair
// Conflict is a list of nodes that cannot be merged automatically
Conflict []DiffPair
}
// Commit gives information about a single commit.
type Commit struct {
// Hash is the id of this commit
Hash h.Hash
// Msg describes the committed contents
Msg string
// Tags is a user defined list of tags
// (tags like HEAD, CURR and INIT are assigned dynamically as exception)
Tags []string
// Date is the time when the commit was made
Date time.Time
}
// Change describes a single change to a node between two versions
type Change struct {
// Path is the node that was changed
Path string
// IsPinned tells you if the content is pinned at this stage
IsPinned bool
// IsExplicty tells you if the content is pinned explicitly.
IsExplicit bool
// Change describes what was changed
Change string
// MovedTo indicates that the node at this Path was moved to
// another location and that there is no node at this location now.
MovedTo string
// WasPreviouslyAt is filled when the node was moved
// and was previously at another location.
WasPreviouslyAt string
// Head is the commit after the change
Head *Commit
// Next is the commit before the change
Next *Commit
}
// ExplicitPin is a pair of path and commit id.
type ExplicitPin struct {
Path string
Commit string
}
/////////////////////
// UTILITY HELPERS //
/////////////////////
func (fs *FS) nodeToStat(nd n.Node) *StatInfo {
isPinned, isExplicit, err := fs.pinner.IsNodePinned(nd)
if err != nil {
log.Warningf("stat: failed to acquire pin state: %v", err)
}
return &StatInfo{
Path: nd.Path(),
User: nd.User(),
ModTime: nd.ModTime(),
IsDir: nd.Type() == n.NodeTypeDirectory,
Inode: nd.Inode(),
Size: nd.Size(),
Depth: n.Depth(nd),
IsPinned: isPinned,
IsExplicit: isExplicit,
ContentHash: nd.ContentHash().Clone(),
BackendHash: nd.BackendHash().Clone(),
TreeHash: nd.TreeHash().Clone(),
}
}
func lookupFileOrDir(lkr *c.Linker, path string) (n.ModNode, error) {
nd, err := lkr.LookupNode(path)
if err != nil {
return nil, err
}
if nd == nil || nd.Type() == n.NodeTypeGhost {
return nil, ie.NoSuchFile(path)
}
modNd, ok := nd.(n.ModNode)
if !ok {
return nil, ie.ErrBadNode
}
return modNd, nil
}
func (fs *FS) handleGcEvent(nd n.Node) bool {
if nd.Type() != n.NodeTypeFile {
return true
}
file, ok := nd.(*n.File)
if !ok {
return true
}
content := file.BackendHash()
log.Infof("unpinning gc'd node %v", content.B58String())
// This node will not be reachable anymore by brig.
// Make sure it is also unpinned to save space.
if err := fs.pinner.Unpin(file.Inode(), file.BackendHash(), true); err != nil {
log.Warningf("unpinning attempt failed: %v", err)
}
// Still return true, no need to stop the GC
return true
}
///////////////////////////////
// ACTUAL API IMPLEMENTATION //
///////////////////////////////
func (fs *FS) doGcRun() {
fs.mu.Lock()
defer fs.mu.Unlock()
owner, err := fs.lkr.Owner()
if err != nil {
log.Warningf("gc: failed to get owner: %v", err)
return
}
log.Debugf("filesystem GC (for %s): running", owner)
if err := fs.gc.Run(true); err != nil {
log.Warnf("failed to run GC: %v", err)
}
}
// NewFilesystem creates a new CATFS filesystem.
// This filesystem stores all its data in a Merkle DAG and is fully versioned.
func NewFilesystem(backend FsBackend, dbPath string, owner string, readOnly bool, fsCfg *config.Config) (*FS, error) {
kv, err := db.NewBadgerDatabase(dbPath)
if err != nil {
return nil, err
}
lkr := c.NewLinker(kv)
if err := lkr.SetOwner(owner); err != nil {
return nil, err
}
pinCache, err := NewPinner(lkr, backend)
if err != nil {
return nil, err
}
// NOTE: We do not need to validate fsCfg here.
// This is already done on the side of our config module.
// (we just need to convert a few keys to the vcs.SyncOptions enum later).
fs := &FS{
kv: kv,
lkr: lkr,
bk: backend,
cfg: fsCfg,
readOnly: readOnly,
gcControl: make(chan bool),
autoCommitControl: make(chan bool),
pinner: pinCache,
}
// Start the garbage collection background task.
// It will run locked every few seconds and removes unreachable
// objects from the staging area.
fs.gc = c.NewGarbageCollector(lkr, kv, fs.handleGcEvent)
go fs.gcLoop()
go fs.autoCommitLoop()
return fs, nil
}
func (fs *FS) gcLoop() {
gcTicker := time.NewTicker(120 * time.Second)
defer gcTicker.Stop()
for {
select {
case state := <-fs.gcControl:
if state {
fs.doGcRun()
} else {
// Quit the gc loop:
log.Debugf("Quitting the GC loop")
return
}
case <-gcTicker.C:
fs.doGcRun()
}
}
}
func (fs *FS) autoCommitLoop() {
lastCheck := time.Now()
checkTicker := time.NewTicker(1 * time.Second)
defer checkTicker.Stop()
for {
select {
case <-fs.autoCommitControl:
log.Debugf("quitting the auto commit loop")
return
case <-checkTicker.C:
isEnabled := fs.cfg.Bool("autocommit.enabled")
if !isEnabled {
continue
}
if time.Since(lastCheck) >= fs.cfg.Duration("autocommit.interval") {
lastCheck = time.Now()
msg := fmt.Sprintf("auto commit at »%s«", time.Now().Format(time.RFC822))
if err := fs.MakeCommit(msg); err != nil && err != ie.ErrNoChange {
log.Warningf("failed to create auto commit: %v", err)
}
}
}
}
}
// Close will clean up internal storage.
func (fs *FS) Close() error {
go func() {
fs.gcControl <- false
}()
go func() {
fs.autoCommitControl <- false
}()
if err := fs.pinner.Close(); err != nil {
log.Warnf("Failed to close pin cache: %v", err)
}
return fs.kv.Close()
}
// Export will export a serialized version of the filesystem to `w`.
func (fs *FS) Export(w io.Writer) error {
fs.mu.Lock()
defer fs.mu.Unlock()
return fs.kv.Export(w)
}
// Import will read a previously FS dump from `r`.
func (fs *FS) Import(r io.Reader) error {
fs.mu.Lock()
defer fs.mu.Unlock()
if err := fs.kv.Import(r); err != nil {
return err
}
// disk (probably) changed, delete memcache:
fs.lkr.MemIndexClear()
return nil
}
/////////////////////
// CORE OPERATIONS //
/////////////////////
// Move will move the file or directory at `src` to `dst`.
// If it does not exist, an error will be returned.
func (fs *FS) Move(src, dst string) error {
fs.mu.Lock()
defer fs.mu.Unlock()
if fs.readOnly {
return ErrReadOnly
}
srcNd, err := lookupFileOrDir(fs.lkr, src)
if err != nil {
return err
}
return c.Move(fs.lkr, srcNd, dst)
}
// Copy will copy the file or directory at `src` to `dst`.
// If it does not exist, an error will be returned.
func (fs *FS) Copy(src, dst string) error {
fs.mu.Lock()
defer fs.mu.Unlock()
if fs.readOnly {
return ErrReadOnly
}
srcNd, err := lookupFileOrDir(fs.lkr, src)
if err != nil {
return err
}
_, err = c.Copy(fs.lkr, srcNd, dst)
return err
}
// Mkdir creates a new empty directory at `dir`, possibly creating
// all intermediate parents if `createParents` is set.
func (fs *FS) Mkdir(dir string, createParents bool) error {
fs.mu.Lock()
defer fs.mu.Unlock()
if fs.readOnly {
return ErrReadOnly
}
// "brig mkdir ." somehow is able to overwrite everything:
dir = strings.TrimLeft(path.Clean(dir), ".")
_, err := c.Mkdir(fs.lkr, dir, createParents)
return err
}
// Remove removes the file or directory at `path`.
func (fs *FS) Remove(path string) error {
fs.mu.Lock()
defer fs.mu.Unlock()
if fs.readOnly {
return ErrReadOnly
}
nd, err := lookupFileOrDir(fs.lkr, path)
if err != nil {
return err
}
_, _, err = c.Remove(fs.lkr, nd, true, true)
return err
}
// Stat delivers detailed information about the node at `path`.
func (fs *FS) Stat(path string) (*StatInfo, error) {
fs.mu.Lock()
defer fs.mu.Unlock()
nd, err := fs.lkr.LookupNode(path)
if err != nil {
return nil, err
}
if nd.Type() == n.NodeTypeGhost {
return nil, ie.NoSuchFile(path)
}
return fs.nodeToStat(nd), nil
}
// List returns stat info for each node below (and including) root.
// Nodes deeper than maxDepth will not be shown. If maxDepth is a
// negative number, all nodes will be shown.
func (fs *FS) List(root string, maxDepth int) ([]*StatInfo, error) {
fs.mu.Lock()
defer fs.mu.Unlock()
// NOTE: This method is highly inefficient:
// - iterates over all nodes even if maxDepth is >= 0
//
// Fix whenever it proves to be a problem.
// I don't want to engineer something now until I know what's needed.
rootNd, err := fs.lkr.LookupNode(root)
if err != nil {
return nil, err
}
if rootNd.Type() == n.NodeTypeGhost {
return nil, ie.NoSuchFile(root)
}
// Start counting max depth relative to the root:
if maxDepth >= 0 {
maxDepth += n.Depth(rootNd)
}
result := []*StatInfo{}
err = n.Walk(fs.lkr, rootNd, false, func(child n.Node) error {
if maxDepth < 0 || n.Depth(child) <= maxDepth {
if maxDepth >= 0 && child.Path() == root {
return nil
}
// Ghost nodes should not be visible to the outside.
if child.Type() == n.NodeTypeGhost {
return nil
}
result = append(result, fs.nodeToStat(child))
}
return nil
})
sort.Slice(result, func(i, j int) bool {
iDepth := result[i].Depth
jDepth := result[j].Depth
if iDepth == jDepth {
return result[i].Path < result[j].Path
}
return iDepth < jDepth
})
if err != nil {
return nil, err
}
return result, nil
}
////////////////////////
// PINNING OPERATIONS //
////////////////////////
// preCache makes the backend fetch the data already from the network,
// even though it might not be needed yet.
func (fs *FS) preCache(path string) error {
stream, err := fs.Cat(path)
if err != nil {
return err
}
_, err = io.Copy(ioutil.Discard, stream)
return err
}
func (fs *FS) preCacheInBackground(path string) {
if !fs.cfg.Bool("pre_cache.enabled") {
return
}
go func() {
if err := fs.preCache(path); err != nil {
log.Debugf("failed to pre-cache `%s`: %v", path, err)
}
}()
}
// Pin will pin the file or directory at `path` explicitly.
func (fs *FS) Pin(path string) error {
fs.mu.Lock()
defer fs.mu.Unlock()
nd, err := lookupFileOrDir(fs.lkr, path)
if err != nil {
return err
}
if err := fs.pinner.PinNode(nd, true); err != nil {
return err
}
// Make sure the data is available:
// (this is some sort of `cat path > /dev/null`)
fs.preCacheInBackground(path)
return nil
}
// Unpin will unpin the file or directory at `path` explicitly.
func (fs *FS) Unpin(path string) error {
fs.mu.Lock()
defer fs.mu.Unlock()
nd, err := lookupFileOrDir(fs.lkr, path)
if err != nil {
return err
}
return fs.pinner.UnpinNode(nd, true)
}
// ListExplicitPins returns all pathes that are pinned explicitly.
func (fs *FS) ListExplicitPins(prefix, fromRef, toRef string) ([]ExplicitPin, error) {
fs.mu.Lock()
defer fs.mu.Unlock()
var from, to *n.Commit
var err error
if fromRef != "" {
from, err = parseRev(fs.lkr, fromRef)
if err != nil {
return nil, e.Wrapf(err, "parse from ref")
}
}
if toRef != "" {
to, err = parseRev(fs.lkr, toRef)
if err != nil {
return nil, e.Wrapf(err, "parse to ref")
}
}
results := []ExplicitPin{}
err = fs.lkr.IterAll(from, to, func(nd n.ModNode, cmt *n.Commit) error {
if nd.Type() != n.NodeTypeFile {
return nil
}
if !strings.HasPrefix(nd.Path(), prefix) {
return nil
}
_, isExplicit, err := fs.pinner.IsPinned(nd.Inode(), nd.BackendHash())
if err != nil {
return err
}
// isExplicit implies isPinned.
if isExplicit {
results = append(results, ExplicitPin{
Path: nd.Path(),
Commit: cmt.TreeHash().B58String(),
})
}
return nil
})
if err != nil {
return nil, err
}
return results, nil
}
// ClearExplicitPins clears all pins in the commit range referenced
// by `fromRef` and `toRef`. The cleared files have to start with `prefix`.
func (fs *FS) ClearExplicitPins(prefix, fromRef, toRef string) (int, error) {
fs.mu.Lock()
defer fs.mu.Unlock()
return fs.setExplicitPins(false, prefix, fromRef, toRef)
}
// SetExplicitPin pins all pins in the commit range referenced by `fromRef` and
// `toRef` explicitly. The files have to start with `prefix`.
func (fs *FS) SetExplicitPin(prefix, fromRef, toRef string) (int, error) {
fs.mu.Lock()
defer fs.mu.Unlock()
return fs.setExplicitPins(true, prefix, fromRef, toRef)
}
func (fs *FS) setExplicitPins(doPin bool, prefix, fromRef, toRef string) (int, error) {
var err error
var from, to *n.Commit
if fromRef != "" {
from, err = parseRev(fs.lkr, fromRef)
if err != nil {
return 0, e.Wrapf(err, "parse from ref")
}
}
if toRef != "" {
to, err = parseRev(fs.lkr, toRef)
if err != nil {
return 0, e.Wrapf(err, "parse to ref")
}
}
processed := 0
return processed, fs.lkr.IterAll(from, to, func(nd n.ModNode, cmt *n.Commit) error {
if nd.Type() != n.NodeTypeFile {
return nil
}
if !strings.HasPrefix(nd.Path(), prefix) {
return nil
}
if doPin {
err = fs.pinner.PinNode(nd, true)
} else {
err = fs.pinner.UnpinNode(nd, true)
}
if err != nil {
return err
}
processed++
return nil
})
}
// IsPinned returns true for files and directories that are pinned.
// A directory only counts as pinned if all files and directories
// in it are also pinned.
func (fs *FS) IsPinned(path string) (bool, bool, error) {
fs.mu.Lock()
defer fs.mu.Unlock()
nd, err := lookupFileOrDir(fs.lkr, path)
if err != nil {
return false, false, err
}
return fs.pinner.IsNodePinned(nd)
}
////////////////////////
// STAGING OPERATIONS //
////////////////////////
func prefixSlash(s string) string {
if !strings.HasPrefix(s, "/") {
return "/" + s
}
return s
}
// Touch creates an empty file at `path` if it does not exist yet.
// If it exists, it's mod time is being updated to the current time.
func (fs *FS) Touch(path string) error {
fs.mu.Lock()
if fs.readOnly {
fs.mu.Unlock()
return ErrReadOnly
}
nd, err := fs.lkr.LookupNode(path)
if err != nil && !ie.IsNoSuchFileError(err) {
fs.mu.Unlock()
return err
}
if nd != nil {
modNd, ok := nd.(n.ModNode)
if !ok {
// Probably a ghost node.
fs.mu.Unlock()
return nil
}
modNd.SetModTime(time.Now())
fs.mu.Unlock()
return nil
}
// We may not call Stage() with a lock.
fs.mu.Unlock()
// Notthing there, stage an empty file.
return fs.Stage(prefixSlash(path), bytes.NewReader([]byte{}))
}
// Truncate cuts of the output of the file at `path` to `size`.
// `size` should be between 0 and the size of the file,
// all other values will be ignored.
//
// Note that this is not implemented as an actual IO operation.
// It is possible to go back to a bigger size until the actual
// content was changed via Stage().
func (fs *FS) Truncate(path string, size uint64) error {
fs.mu.Lock()
defer fs.mu.Unlock()
if fs.readOnly {
return ErrReadOnly
}
nd, err := fs.lkr.LookupModNode(path)
if err != nil {
return err
}
if nd.Type() != n.NodeTypeFile {
return fmt.Errorf("`%s` is not a file", path)
}
nd.SetSize(size)
return fs.lkr.StageNode(nd)
}
func (fs *FS) computePreconditions(path string, rs io.ReadSeeker) (h.Hash, uint64, compress.AlgorithmType, error) {
// Save a little header of the things we read,
// but avoid reading it twice.
headerBuf, pr, err := util.PeekHeader(rs, 4*1024)
if err != nil {
return nil, 0, compress.AlgoNone, err
}
hashWriter := h.NewHashWriter()
hashReader := io.TeeReader(pr, hashWriter)
sizeAcc := &util.SizeAccumulator{}
sizeReader := io.TeeReader(hashReader, sizeAcc)
if _, err := io.Copy(ioutil.Discard, sizeReader); err != nil {
return nil, 0, compress.AlgoNone, err
}
// Go back to the beginning of the file:
if _, err := rs.Seek(0, io.SeekStart); err != nil {
return nil, 0, compress.AlgoNone, err
}
algo, err := compress.GuessAlgorithm(path, headerBuf)
if err != nil {
// Use the default algorithm set in the config:
algo, err = compress.AlgoFromString(fs.cfg.String("compress.default_algo"))
if err != nil {
return nil, 0, compress.AlgoNone, err
}
log.Warningf("failed to guess suitable zip algo for %s: %v", path, err)
}
if algo != compress.AlgoNone {
log.Debugf("Using '%s' compression for file %s", algo, path)
}
contentHash := hashWriter.Finalize()
size := sizeAcc.Size()
return contentHash, size, algo, nil
}
func deriveKeyFromContent(content h.Hash, size uint64) []byte {
salt := make([]byte, 8)
binary.LittleEndian.PutUint64(salt, size)
return util.DeriveKey(content, salt, 32)
}
func (fs *FS) renewPins(oldFile, newFile *n.File) error {
pinExplicit := false
if oldFile != nil {
oldBackendHash := oldFile.BackendHash()
if oldBackendHash.Equal(newFile.BackendHash()) {
// Nothing changed, nothing to do...
return nil
}
_, isExplicit, err := fs.pinner.IsNodePinned(oldFile)
if err != nil {
return err
}
// If the old file was pinned explicitly, we should also pin
// the new file explicitly to carry over that info.
pinExplicit = isExplicit
if !isExplicit {
if err := fs.pinner.UnpinNode(oldFile, pinExplicit); err != nil {
return err
}
}
}
return fs.pinner.PinNode(newFile, pinExplicit)
}
// Stage reads all data from `r` and stores as content of the node at `path`.
// If `path` already exists, it will be updated.
func (fs *FS) Stage(path string, r io.ReadSeeker) error {
fs.mu.Lock()
if fs.readOnly {
return ErrReadOnly
}
path = prefixSlash(path)
// See if we already have such a file.
// If not we gonna need to generate new key for it
// based on the content hash.
var oldFile *n.File
oldNode, err := fs.lkr.LookupNode(path)
// Check that we're handling the right kind of node.
// We should be able to add on-top of ghosts, but directorie
// are pointless as input.
if err == nil {
switch oldNode.Type() {
case n.NodeTypeDirectory:
fs.mu.Unlock()
return fmt.Errorf("Cannot stage over directory: %v", path)
case n.NodeTypeGhost:
// Act like there was no such node:
err = ie.NoSuchFile(path)
case n.NodeTypeFile:
var ok bool
oldFile, ok = oldNode.(*n.File)
if !ok {
fs.mu.Unlock()
return ie.ErrBadNode
}
}
}
if err != nil && !ie.IsNoSuchFileError(err) {
fs.mu.Unlock()
return err
}
// Copy self, so we do not need to fear race conditions below.
var oldFileCopy *n.File
if oldFile != nil {
oldFileCopy = oldFile.Copy(oldFile.Inode()).(*n.File)
}
// Unlock the fs lock while adding the stream to the backend.
// This is not required for the data integrity of the fs.
fs.mu.Unlock()
contentHash, size, compressAlgo, err := fs.computePreconditions(path, r)
if err != nil {
return err
}
var key []byte
if oldFileCopy == nil {
// only create a new key for new files.
// The key depends on the content hash and the size.
key = deriveKeyFromContent(contentHash, size)
} else {
if contentHash.Equal(oldFileCopy.ContentHash()) {
log.Infof("content of %s did not change; not modifying", path)
return nil
}
// Next generations of the same file get the same key.
key = oldFileCopy.Key()
}
stream, err := mio.NewInStream(r, key, compressAlgo)
if err != nil {
return err
}
backendHash, err := fs.bk.Add(stream)
if err != nil {
return err
}
// Lock it again for the metadata staging:
fs.mu.Lock()
defer fs.mu.Unlock()
newFile, err := c.Stage(fs.lkr, path, contentHash, backendHash, size, key)
if err != nil {
return err