-
Notifications
You must be signed in to change notification settings - Fork 1
/
tree.go
1356 lines (988 loc) · 28.7 KB
/
tree.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
/*
* Rufs - Remote Union File System
*
* Copyright 2017 Matthias Ladkau. All rights reserved.
*
* This Source Code Form is subject to the terms of the MIT
* License, If a copy of the MIT License was not distributed with this
* file, You can obtain one at https://opensource.org/licenses/MIT.
*/
package rufs
import (
"bytes"
"crypto/tls"
"encoding/gob"
"encoding/json"
"fmt"
"io"
"os"
"path"
"regexp"
"sort"
"strings"
"sync"
"time"
"unicode/utf8"
"devt.de/krotik/common/bitutil"
"devt.de/krotik/common/fileutil"
"devt.de/krotik/common/stringutil"
"devt.de/krotik/rufs/config"
"devt.de/krotik/rufs/node"
)
/*
Tree models a Rufs client which combines several branches.
*/
type Tree struct {
client *node.Client // RPC client
treeLock *sync.RWMutex // Lock for maps
root *treeItem // Tree root item
branches []map[string]string // Added working branches
branchesAll []map[string]string // All added branches also not working
mapping []map[string]interface{} // Mappings from working branches
mappingAll []map[string]interface{} // All used mappings
}
/*
NewTree creates a new tree.
*/
func NewTree(cfg map[string]interface{}, cert *tls.Certificate) (*Tree, error) {
var err error
var t *Tree
// Make sure the given config is ok
if err = config.CheckTreeConfig(cfg); err == nil {
// Create RPC client
c := node.NewClient(fileutil.ConfStr(cfg, config.TreeSecret), cert)
// Create the tree
t = &Tree{c, &sync.RWMutex{}, &treeItem{make(map[string]*treeItem),
[]string{}, []bool{}}, []map[string]string{},
[]map[string]string{}, []map[string]interface{}{},
[]map[string]interface{}{}}
}
return t, err
}
/*
Config returns the current tree configuration as a JSON string.
*/
func (t *Tree) Config() string {
t.treeLock.RLock()
defer t.treeLock.RUnlock()
out, _ := json.MarshalIndent(map[string]interface{}{
"branches": t.branches,
"tree": t.mapping,
}, "", " ")
return string(out)
}
/*
SetMapping adds a given tree mapping configuration in a JSON string.
*/
func (t *Tree) SetMapping(config string) error {
var err error
var conf map[string][]map[string]interface{}
// Unmarshal the config
if err = json.Unmarshal([]byte(config), &conf); err == nil {
// Reset the whole tree
t.Reset(true)
if branches, ok := conf["branches"]; ok {
for _, b := range branches {
t.AddBranch(b["branch"].(string), b["rpc"].(string), b["fingerprint"].(string))
}
}
if mounts, ok := conf["tree"]; ok {
for _, m := range mounts {
t.AddMapping(m["path"].(string), m["branch"].(string), m["writeable"].(bool))
}
}
}
return err
}
/*
KnownBranches returns a map of all known branches (active or not reachable).
Caution: This map contains also the map of active branches with their fingerprints
it should only be used for read operations.
*/
func (t *Tree) KnownBranches() map[string]map[string]string {
ret := make(map[string]map[string]string)
t.treeLock.RLock()
t.treeLock.RUnlock()
for _, b := range t.branchesAll {
ret[b["branch"]] = b
}
return ret
}
/*
ActiveBranches returns a list of all known active branches and their fingerprints.
*/
func (t *Tree) ActiveBranches() ([]string, []string) {
return t.client.Peers()
}
/*
NotReachableBranches returns a map of all known branches which couldn't be
reached. The map contains the name and the definition of the branch.
*/
func (t *Tree) NotReachableBranches() map[string]map[string]string {
ret := make(map[string]map[string]string)
t.treeLock.RLock()
t.treeLock.RUnlock()
activeBranches := make(map[string]map[string]string)
for _, b := range t.branches {
activeBranches[b["branch"]] = b
}
for _, b := range t.branchesAll {
name := b["branch"]
if _, ok := activeBranches[name]; !ok {
ret[name] = b
}
}
return ret
}
/*
PingBranch sends a ping to a remote branch and returns its fingerprint or an error.
*/
func (t *Tree) PingBranch(node string, rpc string) (string, error) {
_, fp, err := t.client.SendPing(node, rpc)
return fp, err
}
/*
Reset either resets only all mounts or if the branches flag is specified
also all known branches.
*/
func (t *Tree) Reset(branches bool) {
if branches {
peers, _ := t.client.Peers()
for _, p := range peers {
t.client.RemovePeer(p)
}
t.branches = []map[string]string{}
t.branchesAll = []map[string]string{}
}
t.treeLock.Lock()
defer t.treeLock.Unlock()
t.mapping = []map[string]interface{}{}
t.mappingAll = []map[string]interface{}{}
t.root = &treeItem{make(map[string]*treeItem), []string{}, []bool{}}
}
/*
Refresh refreshes all known branches and mappings. Only reachable branches will
be mapped into the tree.
*/
func (t *Tree) Refresh() {
addBranches := make(map[string]map[string]string)
delBranches := make(map[string]map[string]string)
nrBranches := t.NotReachableBranches()
// Check all known branches and decide if they should be added or removed
t.treeLock.RLock()
for _, data := range t.branchesAll {
branchName := data["branch"]
branchRPC := data["rpc"]
_, knownAsNotWorking := nrBranches[branchName]
// Ping the branch
_, _, err := t.client.SendPing(branchName, branchRPC)
if err == nil && knownAsNotWorking {
// Success branch can now be reached
addBranches[branchName] = data
} else if err != nil && !knownAsNotWorking {
// Failure branch can no longer be reached
delBranches[branchName] = data
}
}
t.treeLock.RUnlock()
// Now lock the tree and add/remove branches
t.treeLock.Lock()
for i, b := range t.branches {
branchName := b["branch"]
if _, ok := delBranches[branchName]; ok {
t.client.RemovePeer(branchName)
t.branches = append(t.branches[:i], t.branches[i+1:]...)
}
}
for _, b := range addBranches {
branchName := b["branch"]
branchRPC := b["rpc"]
branchFingerprint := b["fingerprint"]
t.client.RegisterPeer(branchName, branchRPC, branchFingerprint)
t.branches = append(t.branches, b)
}
// Rebuild all mappings
mappings := t.mappingAll
t.mapping = []map[string]interface{}{}
t.mappingAll = []map[string]interface{}{}
t.root = &treeItem{make(map[string]*treeItem), []string{}, []bool{}}
t.treeLock.Unlock()
for _, m := range mappings {
t.AddMapping(fmt.Sprint(m["path"]), fmt.Sprint(m["branch"]), m["writeable"].(bool))
}
}
/*
AddBranch adds a branch to the tree.
*/
func (t *Tree) AddBranch(branchName string, branchRPC string, branchFingerprint string) error {
branchMap := map[string]string{
"branch": branchName,
"rpc": branchRPC,
"fingerprint": branchFingerprint,
}
t.branchesAll = append(t.branchesAll, branchMap)
// First ping the branch and see if we get a response
_, fp, err := t.client.SendPing(branchName, branchRPC)
// Only add the branch as active if we've seen it
if err == nil {
if branchFingerprint != "" && branchFingerprint != fp {
err = fmt.Errorf("Remote branch has an unexpected fingerprint\nPresented fingerprint: %s\nExpected fingerprint : %s", branchFingerprint, fp)
} else {
t.treeLock.Lock()
defer t.treeLock.Unlock()
if err = t.client.RegisterPeer(branchName, branchRPC, fp); err == nil {
// Once we know and accepted the fingerprint we change it
//
// Remote branches will never change their fingerprint
// during a single network session
branchMap["fingerprint"] = fp
t.branches = append(t.branches, branchMap) // Store the added branch
}
}
}
return err
}
/*
AddMapping adds a mapping from tree path to a branch.
*/
func (t *Tree) AddMapping(dir, branchName string, writable bool) error {
t.treeLock.Lock()
defer t.treeLock.Unlock()
err := node.ErrUnknownTarget
mappingMap := map[string]interface{}{
"path": dir,
"branch": branchName,
"writeable": writable,
}
t.mappingAll = append(t.mappingAll, mappingMap)
peers, _ := t.client.Peers()
for _, p := range peers {
if p == branchName {
// Split the given path and add the mapping
t.root.addMapping(createMappingPath(dir), branchName, writable)
t.mapping = append(t.mapping, mappingMap)
err = nil
}
}
return err
}
/*
String returns a string representation of this tree.
*/
func (t *Tree) String() string {
if t.treeLock != nil {
t.treeLock.RLock()
defer t.treeLock.RUnlock()
}
var buf bytes.Buffer
buf.WriteString("/: ")
if t != nil && t.root != nil {
t.root.String(1, &buf)
}
return buf.String()
}
// Client API
// ==========
/*
Dir returns file listings matching a given pattern of one or more directories.
The contents of the given path is returned. Optionally, also the contents of
all subdirectories can be returned if the recursive flag is set. The return
values is a list of traversed directories and their corresponding contents.
*/
func (t *Tree) Dir(dir string, pattern string, recursive bool, checksums bool) ([]string, [][]os.FileInfo, error) {
var err error
var dirs []string
var fis [][]os.FileInfo
// Compile pattern
re, err := regexp.Compile(pattern)
if err != nil {
return nil, nil, err
}
t.treeLock.RLock()
defer t.treeLock.RUnlock()
// Stip off trailing slashes to normalize the input
if strings.HasSuffix(dir, "/") {
dir = dir[:len(dir)-1]
}
treeVisitor := func(item *treeItem, treePath string, branchPath []string, branches []string, writable []bool) {
for _, b := range branches {
var res []byte
if err == nil {
res, err = t.client.SendData(b, map[string]string{
ParamAction: OpDir,
ParamPath: path.Join(branchPath...),
ParamPattern: fmt.Sprint(pattern),
ParamRecursive: fmt.Sprint(recursive),
ParamChecksums: fmt.Sprint(checksums),
}, nil)
if err == nil {
var dest []interface{}
// Unpack the result
if err = gob.NewDecoder(bytes.NewBuffer(res)).Decode(&dest); err == nil {
bdirs := dest[0].([]string)
bfis := dest[1].([][]os.FileInfo)
// Construct the actual tree path for the returned directories
for i, d := range bdirs {
bdirs[i] = path.Join(treePath, d)
// Merge these results into the overall results
found := false
for j, dir := range dirs {
// Check if a directory from the result is already
// in the overall result
if dir == bdirs[i] {
found = true
// Create a map of existing names to avoid duplicates
existing := make(map[string]bool)
for _, fi := range fis[j] {
existing[fi.Name()] = true
}
// Only add new files to the overall result
for _, fi := range bfis[i] {
if _, ok := existing[fi.Name()]; !ok {
fis[j] = append(fis[j], fi)
}
}
}
}
if !found {
// Just append if the directory is not in the
// overall results yet
dirs = append(dirs, bdirs[i])
fis = append(fis, bfis[i])
}
}
}
}
}
}
}
t.root.findPathBranches("/", createMappingPath(dir), recursive, treeVisitor)
// Add pseudo directories for mapping components which have no corresponding
// real directories
dirsMap := make(map[string]int)
for i, d := range dirs {
dirsMap[d] = i
}
t.root.findPathBranches("/", createMappingPath(dir), recursive,
func(item *treeItem, treePath string, branchPath []string, branches []string, writable []bool) {
if !strings.HasPrefix(treePath, dir) {
return
}
idx, ok := dirsMap[treePath]
if !ok {
// Create the entry if it does not exist
dirs = append(dirs, treePath)
idx = len(dirs) - 1
dirsMap[treePath] = idx
fis = append(fis, []os.FileInfo{})
}
// Add pseudo dirs if a physical directory is not present
for n := range item.children {
found := false
for _, fi := range fis[idx] {
if fi.Name() == n {
found = true
break
}
}
if found {
continue
}
if re.MatchString(n) {
// Append if it matches the pattern
fis[idx] = append(fis[idx], &FileInfo{
FiName: n,
FiSize: 0,
FiMode: os.FileMode(os.ModeDir | 0777),
FiModTime: time.Time{},
})
}
}
})
return dirs, fis, err
}
/*
Stat returns information about a given item. Use this function to find out
if a given path is a file or directory.
*/
func (t *Tree) Stat(item string) (os.FileInfo, error) {
dir, file := path.Split(item)
_, fis, err := t.Dir(dir, file, false, true)
if len(fis) == 1 {
for _, fi := range fis[0] {
if fi.Name() == file {
return fi, err
}
}
}
if err == nil {
err = &node.Error{
Type: node.ErrRemoteAction,
Detail: os.ErrNotExist.Error(),
IsNotExist: true,
}
}
return nil, err
}
/*
Copy is a general purpose copy function which creates files and directories.
Destination must be a directory. A non-existing destination
directory will be created.
*/
func (t *Tree) Copy(src []string, dst string,
updFunc func(file string, writtenBytes, totalBytes, currentFile, totalFiles int64)) error {
var err error
var relPaths []string
files := make(map[string]os.FileInfo) // Make sure any file is only copied once
paths := make(map[string]string)
// Add files to be copied to items
for _, s := range src {
var fi os.FileInfo
fi, err = t.Stat(s)
if fi, err = t.Stat(s); fi != nil {
if fi.IsDir() {
// Find all files inside directories
if dirs, fis, err := t.Dir(s, "", true, false); err == nil {
for i, d := range dirs {
for _, fi2 := range fis[i] {
if !fi2.IsDir() {
// Calculate the relative path by removing
// source path from the absolute path
relPath := path.Join(d, fi2.Name())[len(s):]
relPath = path.Join("/"+fi.Name(), relPath)
relPaths = append(relPaths, relPath)
files[relPath] = fi2
paths[relPath] = path.Join(d, fi2.Name())
}
}
}
}
} else {
// Single files are just added - these files will always
// be at the root of the destination
relPath := "/" + fi.Name()
relPaths = append(relPaths, relPath)
files[relPath] = fi
paths[relPath] = s
}
}
if err != nil {
err = fmt.Errorf("Cannot stat %v: %v", s, err.Error())
break
}
}
if err == nil {
var allFiles, cnt int64
// Copy all found files
allFiles = int64(len(files))
for _, k := range relPaths {
var totalSize, totalTransferred int64
cnt++
fi := files[k]
totalSize = fi.Size()
srcFile := paths[k]
err = t.CopyFile(srcFile, path.Join(dst, k), func(b int) {
if b >= 0 {
totalTransferred += int64(b)
updFunc(k, totalTransferred, totalSize, cnt, allFiles)
} else {
updFunc(k, int64(b), totalSize, cnt, allFiles)
}
})
if err != nil {
err = fmt.Errorf("Cannot copy %v to %v: %v", srcFile, dst, err.Error())
break
}
}
}
return err
}
/*
Sync operations
*/
const (
SyncCreateDirectory = "Create directory"
SyncCopyFile = "Copy file"
SyncRemoveDirectory = "Remove directory"
SyncRemoveFile = "Remove file"
)
/*
Sync a given destination with a given source directory. After this command has
finished the dstDir will have the same files and directories as the srcDir.
*/
func (t *Tree) Sync(srcDir string, dstDir string, recursive bool,
updFunc func(op, srcFile, dstFile string, writtenBytes, totalBytes, currentFile, totalFiles int64)) error {
var currentFile, totalFiles int64
t.treeLock.RLock()
defer t.treeLock.RUnlock()
// doSync syncs a given src directory
doSync := func(dir string, finfos []os.FileInfo) error {
sdir := path.Join(srcDir, dir)
ddir := path.Join(dstDir, dir)
// Query the corresponding destination to see what is there
_, dstFis, err := t.Dir(ddir, "", false, true)
if err == nil {
fileMap := make(map[string]string) // Map to quickly lookup destination files
dirMap := make(map[string]bool) // Map to quickly lookup destination directories
if len(dstFis) > 0 {
for _, fi := range dstFis[0] {
if fi.IsDir() {
dirMap[fi.Name()] = true
} else {
fileMap[fi.Name()] = fi.(*FileInfo).Checksum()
}
}
}
// Go through the given source file infos and see what needs to be copied
for _, fi := range finfos {
currentFile++
// Check if we have a directory or a file
if fi.IsDir() {
if _, ok := dirMap[fi.Name()]; !ok {
// Create all directories which aren't there
if updFunc != nil {
updFunc(SyncCreateDirectory, "", path.Join(ddir, fi.Name()), 0, 0, currentFile, totalFiles)
}
_, err = t.ItemOp(ddir, map[string]string{
ItemOpAction: ItemOpActMkDir,
ItemOpName: fi.Name(),
})
}
// Remove existing directories from the map so we can
// use the map to remove directories which shouldn't
// be there
delete(dirMap, fi.Name())
} else {
fsum, ok := fileMap[fi.Name()]
if !ok || fsum != fi.(*FileInfo).Checksum() {
var u func(b int)
s := path.Join(sdir, fi.Name())
d := path.Join(ddir, fi.Name())
// Copy the file if it does not exist or the checksum
// is not matching
if updFunc != nil {
var totalTransferred, totalSize int64
totalSize = fi.Size()
u = func(b int) {
if b >= 0 {
totalTransferred += int64(b)
updFunc(SyncCopyFile, s, d, totalTransferred, totalSize, currentFile, totalFiles)
} else {
updFunc(SyncCopyFile, s, d, int64(b), totalSize, currentFile, totalFiles)
}
}
}
if err = t.CopyFile(s, d, u); err != nil && updFunc != nil {
// Note at which point the error message was produced
updFunc(SyncCopyFile, s, d, 0, fi.Size(), currentFile, totalFiles)
}
}
// Remove existing files from the map so we can
// use the map to remove files which shouldn't
// be there
delete(fileMap, fi.Name())
}
if err != nil {
break
}
}
if err == nil {
// Remove files and directories which are in the destination but
// not in the source
for d := range dirMap {
if err == nil {
if updFunc != nil {
p := path.Join(ddir, d)
updFunc(SyncRemoveDirectory, "", p, 0, 0, currentFile, totalFiles)
}
_, err = t.ItemOp(ddir, map[string]string{
ItemOpAction: ItemOpActDelete,
ItemOpName: d,
})
}
}
for f := range fileMap {
if err == nil {
if updFunc != nil {
p := path.Join(ddir, f)
updFunc(SyncRemoveFile, "", p, 0, 0, currentFile, totalFiles)
}
_, err = t.ItemOp(ddir, map[string]string{
ItemOpAction: ItemOpActDelete,
ItemOpName: f,
})
}
}
}
}
return err
}
// We only query the source once otherwise we might end up in an
// endless loop if for example the dstDir is a subdirectory of srcDir
srcDirs, srcFis, err := t.Dir(srcDir, "", recursive, true)
if err == nil {
for _, fis := range srcFis {
totalFiles += int64(len(fis))
}
for i, dir := range srcDirs {
if err = doSync(relPath(dir, srcDir), srcFis[i]); err != nil {
break
}
}
}
return err
}
/*
CopyFile copies a given file using a simple io.Pipe.
*/
func (t *Tree) CopyFile(srcPath, dstPath string, updFunc func(writtenBytes int)) error {
var pw io.WriteCloser
var err, rerr error
t.treeLock.RLock()
defer t.treeLock.RUnlock()
// Use a pipe to stream the contents of the source file to the destination file
pr, pw := io.Pipe()
if updFunc != nil {
// Wrap the writer of the pipe
pw = &statusUpdatingWriter{pw, updFunc}
}
// Make sure the src exists
if _, rerr = t.ReadFile(srcPath, []byte{}, 0); rerr == nil {
// Read the source in a go routine
go func() {
rerr = t.ReadFileToBuffer(srcPath, pw)
pw.Close()
}()
// Write the destination file - this will return once the
// writer is closed
err = t.WriteFileFromBuffer(dstPath, pr)
}
if rerr != nil {
// Check if we got an empty file
if IsEOF(rerr) {
_, err = t.WriteFile(dstPath, nil, 0)
updFunc(0) // Report the creation of the empty file
rerr = nil
} else {
// Read errors are reported before write errors
err = rerr
}
}
pr.Close()
return err
}
/*
ReadFileToBuffer reads a complete file into a given buffer which implements
io.Writer.
*/
func (t *Tree) ReadFileToBuffer(spath string, buf io.Writer) error {
var n int
var err error
var offset int64
readBuf := make([]byte, DefaultReadBufferSize)
for err == nil {
n, err = t.ReadFile(spath, readBuf, offset)
if err == nil {
_, err = buf.Write(readBuf[:n])
offset += int64(n)
} else if IsEOF(err) {
// We reached the end of the file
err = nil
break
}
}
return err
}
/*
ReadFile reads up to len(p) bytes into p from the given offset. It
returns the number of bytes read (0 <= n <= len(p)) and any error
encountered.
*/
func (t *Tree) ReadFile(spath string, p []byte, offset int64) (int, error) {
var err error
var n int
var success bool
t.treeLock.RLock()
defer t.treeLock.RUnlock()
err = &node.Error{
Type: node.ErrRemoteAction,
Detail: os.ErrNotExist.Error(),
IsNotExist: true,
}
dir, file := path.Split(spath)
t.root.findPathBranches(dir, createMappingPath(dir), false,
func(item *treeItem, treePath string, branchPath []string, branches []string, writable []bool) {
for _, b := range branches {
if !success { // Only try other branches if we didn't have a success before
var res []byte
rpath := path.Join(branchPath...)
rpath = path.Join(rpath, file)
if res, err = t.client.SendData(b, map[string]string{
ParamAction: OpRead,
ParamPath: rpath,
ParamOffset: fmt.Sprint(offset),
ParamSize: fmt.Sprint(len(p)),
}, nil); err == nil {
var dest []interface{}
// Unpack the result
if err = gob.NewDecoder(bytes.NewBuffer(res)).Decode(&dest); err == nil {