forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
folder_update_prepper.go
1582 lines (1468 loc) · 49.6 KB
/
folder_update_prepper.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
// Copyright 2017 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"fmt"
"sync"
"github.com/keybase/client/go/kbfs/data"
"github.com/keybase/client/go/kbfs/idutil"
"github.com/keybase/client/go/kbfs/kbfsblock"
"github.com/keybase/client/go/kbfs/kbfssync"
"github.com/keybase/client/go/kbfs/libkey"
"github.com/keybase/client/go/kbfs/tlf"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
// folderUpdatePrepper is a helper struct for preparing blocks and MD
// updates before they get synced to the backend servers. It can be
// used for a single update or for a batch of updates (e.g. conflict
// resolution).
type folderUpdatePrepper struct {
config Config
folderBranch data.FolderBranch
blocks *folderBlockOps
log logger.Logger
vlog *libkb.VDebugLog
cacheLock sync.Mutex
cachedInfos map[data.BlockPointer]data.BlockInfo
}
func (fup *folderUpdatePrepper) id() tlf.ID {
return fup.folderBranch.Tlf
}
func (fup *folderUpdatePrepper) branch() data.BranchName {
return fup.folderBranch.Branch
}
func (fup *folderUpdatePrepper) nowUnixNano() int64 {
return fup.config.Clock().Now().UnixNano()
}
func (fup *folderUpdatePrepper) readyBlockMultiple(ctx context.Context,
kmd libkey.KeyMetadata, currBlock data.Block, chargedTo keybase1.UserOrTeamID,
bps blockPutState, bType keybase1.BlockType) (
info data.BlockInfo, plainSize int, err error) {
info, plainSize, readyBlockData, err :=
data.ReadyBlock(ctx, fup.config.BlockCache(), fup.config.BlockOps(),
kmd, currBlock, chargedTo, bType)
if err != nil {
return data.BlockInfo{}, 0, err
}
err = bps.AddNewBlock(
ctx, info.BlockPointer, currBlock, readyBlockData, nil)
if err != nil {
return data.BlockInfo{}, 0, err
}
return info, plainSize, nil
}
func (fup *folderUpdatePrepper) unembedBlockChanges(
ctx context.Context, bps blockPutState, md *RootMetadata,
changes *BlockChanges, chargedTo keybase1.UserOrTeamID) error {
buf, err := fup.config.Codec().Encode(changes)
if err != nil {
return err
}
// Treat the block change list as a file so we can reuse all the
// indirection code in fileData.
block := data.NewFileBlock().(*data.FileBlock)
id, err := fup.config.cryptoPure().MakeTemporaryBlockID()
if err != nil {
return err
}
ptr := data.BlockPointer{
ID: id,
KeyGen: md.LatestKeyGeneration(),
DataVer: fup.config.DataVersion(),
DirectType: data.DirectBlock,
Context: kbfsblock.MakeFirstContext(
chargedTo, keybase1.BlockType_MD),
}
file := data.Path{
FolderBranch: fup.folderBranch,
Path: []data.PathNode{{
BlockPointer: ptr,
Name: data.NewPathPartString(
fmt.Sprintf("<MD rev %d>", md.Revision()), nil),
},
}}
dirtyBcache := data.SimpleDirtyBlockCacheStandard()
// Simple dirty bcaches don't need to be shut down.
getter := func(ctx context.Context, _ libkey.KeyMetadata, ptr data.BlockPointer,
_ data.Path, _ data.BlockReqType) (*data.FileBlock, bool, error) {
block, err := dirtyBcache.Get(ctx, fup.id(), ptr, fup.branch())
if err != nil {
return nil, false, err
}
fblock, ok := block.(*data.FileBlock)
if !ok {
return nil, false, errors.Errorf(
"Block for %s is not a file block, block type: %T", ptr, block)
}
return fblock, true, nil
}
cacher := func(ctx context.Context, ptr data.BlockPointer, block data.Block) error {
return dirtyBcache.Put(ctx, fup.id(), ptr, fup.branch(), block)
}
// Start off the cache with the new block
err = cacher(ctx, ptr, block)
if err != nil {
return err
}
df := data.NewDirtyFile(file, dirtyBcache)
fd := data.NewFileData(
file, chargedTo, fup.config.BlockSplitter(), md.ReadOnly(), getter,
cacher, fup.log, fup.vlog)
// Write all the data.
_, _, _, _, _, err = fd.Write(ctx, buf, 0, block, data.DirEntry{}, df)
if err != nil {
return err
}
// There might be a new top block.
topBlock, err := dirtyBcache.Get(ctx, fup.id(), ptr, fup.branch())
if err != nil {
return err
}
block, ok := topBlock.(*data.FileBlock)
if !ok {
return errors.New("Top block change block no longer a file block")
}
// Ready all the child blocks.
infos, err := fd.Ready(ctx, fup.id(), fup.config.BlockCache(),
dirtyBcache, fup.config.BlockOps(), bps, block, df)
if err != nil {
return err
}
for info := range infos {
md.AddMDRefBytes(uint64(info.EncodedSize))
md.AddMDDiskUsage(uint64(info.EncodedSize))
}
fup.vlog.CLogf(ctx, libkb.VLog1, "%d unembedded child blocks", len(infos))
// Ready the top block.
info, _, err := fup.readyBlockMultiple(
ctx, md.ReadOnly(), block, chargedTo, bps, keybase1.BlockType_MD)
if err != nil {
return err
}
md.AddMDRefBytes(uint64(info.EncodedSize))
md.AddMDDiskUsage(uint64(info.EncodedSize))
md.data.cachedChanges = *changes
changes.Info = info
changes.Ops = nil
return nil
}
type isDirtyWithDBM struct {
dbm dirBlockMap
dirtyBcache data.DirtyBlockCache
}
func (idwl isDirtyWithDBM) IsDirty(
tlfID tlf.ID, ptr data.BlockPointer, branch data.BranchName) bool {
hasBlock, err := idwl.dbm.hasBlock(context.Background(), ptr)
if err != nil {
// TODO: do something with this error.
return false
}
if hasBlock {
return true
}
return idwl.dirtyBcache.IsDirty(tlfID, ptr, branch)
}
// prepUpdateForPath updates, and readies, the blocks along the path
// for the given write, up to the root of the tree or stopAt (if
// specified). When it updates the root of the tree, it also modifies
// the given head object with a new revision number and root block ID.
// It first checks the provided dbm for blocks that may have been
// modified by previous prepUpdateForPath calls or the FS calls
// themselves. It returns the updated path to the changed directory,
// the new or updated directory entry created as part of the call, and
// a summary of all the blocks that now must be put to the block
// server.
//
// This function is safe to use unlocked, but may modify MD to have
// the same revision number as another one. Callers that require
// serialized revision numbers must implement their own locking around
// their instance.
//
// entryType must not be Sym.
//
// TODO: deal with multiple nodes for indirect blocks
func (fup *folderUpdatePrepper) prepUpdateForPath(
ctx context.Context, lState *kbfssync.LockState,
chargedTo keybase1.UserOrTeamID, md *RootMetadata, newBlock data.Block,
newBlockPtr data.BlockPointer, dir data.Path, name data.PathPartString,
entryType data.EntryType, mtime bool, ctime bool, stopAt data.BlockPointer,
dbm dirBlockMap, bps blockPutState) (data.Path, data.DirEntry, error) {
// now ready each dblock and write the DirEntry for the next one
// in the path
currBlock := newBlock
var currDD *data.DirData
var currDDPtr data.BlockPointer
var cleanupFn func()
defer func() {
if cleanupFn != nil {
cleanupFn()
}
}()
if _, isDir := newBlock.(*data.DirBlock); isDir {
newPath := dir.ChildPath(
name, newBlockPtr, fup.blocks.nodeCache.ObfuscatorMaker()())
currDD, cleanupFn = fup.blocks.newDirDataWithDBM(
lState, newPath, chargedTo, md, dbm)
currDDPtr = newPath.TailPointer()
}
currName := name
newPath := data.Path{
FolderBranch: dir.FolderBranch,
Path: make([]data.PathNode, 0, len(dir.Path)),
}
var newDe data.DirEntry
doSetTime := true
now := fup.nowUnixNano()
var uid keybase1.UID
for len(newPath.Path) < len(dir.Path)+1 {
if currDD != nil {
// Ready any non-top blocks in the directory.
newInfos, err := currDD.Ready(
ctx, fup.id(), fup.config.BlockCache(),
isDirtyWithDBM{dbm, fup.config.DirtyBlockCache()},
fup.config.BlockOps(), bps, currBlock.(*data.DirBlock))
if err != nil {
return data.Path{}, data.DirEntry{}, err
}
for newInfo := range newInfos {
md.AddRefBlock(newInfo)
}
dirUnrefs := fup.blocks.getDirtyDirUnrefsLocked(
lState, currDDPtr)
for _, unref := range dirUnrefs {
md.AddUnrefBlock(unref)
}
cleanupFn()
cleanupFn = nil
}
info, plainSize, err := fup.readyBlockMultiple(
ctx, md.ReadOnly(), currBlock, chargedTo, bps,
fup.config.DefaultBlockType())
if err != nil {
return data.Path{}, data.DirEntry{}, err
}
if dblock, ok := currBlock.(*data.DirBlock); ok {
plainSize = dblock.TotalPlainSizeEstimate(
plainSize, fup.config.BlockSplitter())
}
// prepend to path and setup next one
newPath.Path = append([]data.PathNode{
{BlockPointer: info.BlockPointer, Name: currName}},
newPath.Path...)
// get the parent block
prevIdx := len(dir.Path) - len(newPath.Path)
var de data.DirEntry
var nextName data.PathPartString
nextDoSetTime := false
if prevIdx < 0 {
// root dir, update the MD instead
de = md.data.Dir
} else {
prevDir := data.Path{
FolderBranch: dir.FolderBranch,
Path: dir.Path[:prevIdx+1],
}
var dd *data.DirData
dd, cleanupFn = fup.blocks.newDirDataWithDBM(
lState, prevDir, chargedTo, md, dbm)
de, err = dd.Lookup(ctx, currName)
if _, noExists := errors.Cause(err).(idutil.NoSuchNameError); noExists {
// If this isn't the first time
// around, we have an error.
if len(newPath.Path) > 1 {
return data.Path{}, data.DirEntry{},
idutil.NoSuchNameError{Name: currName.String()}
}
// If this is a file, the size should be 0. (TODO:
// Ensure this.) If this is a directory, the size will
// be filled in below. The times will be filled in
// below as well, since we should only be creating a
// new directory entry when doSetTime is true.
de = data.DirEntry{
EntryInfo: data.EntryInfo{
Type: entryType,
Size: 0,
},
}
// If we're creating a new directory entry, the
// parent's times must be set as well.
nextDoSetTime = true
} else if err != nil {
return data.Path{}, data.DirEntry{}, err
}
prevDblock, err := dd.GetTopBlock(ctx, data.BlockWrite)
if err != nil {
return data.Path{}, data.DirEntry{}, err
}
currBlock = prevDblock
currDD = dd
currDDPtr = prevDir.TailPointer()
nextName = prevDir.TailName()
}
if de.Type == data.Dir {
de.Size = uint64(plainSize)
}
if prevIdx < 0 {
md.AddUpdate(md.data.Dir.BlockInfo, info)
err = bps.SaveOldPtr(ctx, md.data.Dir.BlockPointer)
if err != nil {
return data.Path{}, data.DirEntry{}, err
}
} else if prevDe, err := currDD.Lookup(ctx, currName); err == nil {
md.AddUpdate(prevDe.BlockInfo, info)
err = bps.SaveOldPtr(ctx, prevDe.BlockPointer)
if err != nil {
return data.Path{}, data.DirEntry{}, err
}
} else {
// this is a new block
md.AddRefBlock(info)
}
de.BlockInfo = info
de.PrevRevisions = de.PrevRevisions.AddRevision(
md.Revision(), md.data.LastGCRevision)
if doSetTime {
if mtime {
de.Mtime = now
}
if ctime {
de.Ctime = now
}
}
if fup.id().Type() == tlf.SingleTeam {
if uid.IsNil() {
session, err := fup.config.KBPKI().GetCurrentSession(ctx)
if err != nil {
return data.Path{}, data.DirEntry{}, err
}
uid = session.UID
}
de.TeamWriter = uid
}
if !newDe.IsInitialized() {
newDe = de
}
if prevIdx < 0 {
md.data.Dir = de
} else {
unrefs, err := currDD.SetEntry(ctx, currName, de)
if err != nil {
return data.Path{}, data.DirEntry{}, err
}
for _, unref := range unrefs {
md.AddUnrefBlock(unref)
}
// Fetch the current block again, since `setEntry` might
// not modify the original `currBlock`, but some
// re-assembled version if the disk cache is in use.
currBlock, err = dbm.getBlock(ctx, currDDPtr)
if err != nil {
return data.Path{}, data.DirEntry{}, err
}
}
currName = nextName
// Stop before we get to the common ancestor; it will be taken care of
// on the next sync call
if prevIdx >= 0 && dir.Path[prevIdx].BlockPointer == stopAt {
break
}
doSetTime = nextDoSetTime
}
return newPath, newDe, nil
}
// pathTreeNode represents a particular node in the part of the FS
// tree affected by a set of updates which needs to be sync'd.
type pathTreeNode struct {
ptr data.BlockPointer
parent *pathTreeNode
children map[string]*pathTreeNode
mergedPath data.Path
}
type prepFolderCopyBehavior int
const (
prepFolderCopyIndirectFileBlocks prepFolderCopyBehavior = 1
prepFolderDontCopyIndirectFileBlocks prepFolderCopyBehavior = 2
)
// prepTree, given a node in part of the FS tree that needs to be
// sync'd, either calls prepUpdateForPath on it if the node has no
// children of its own, or it calls prepTree recursively for all
// children. When calling itself recursively on its children, it
// instructs each child to sync only up to this node, except for the
// last child which may sync back to the given stopAt pointer. This
// ensures that the sync process will ready blocks that are complete
// (with all child changes applied) before readying any parent blocks.
// prepTree returns the merged blockPutState for itself and all of its
// children.
func (fup *folderUpdatePrepper) prepTree(
ctx context.Context, lState *kbfssync.LockState, unmergedChains *crChains,
newMD *RootMetadata, chargedTo keybase1.UserOrTeamID, node *pathTreeNode,
stopAt data.BlockPointer, dbm dirBlockMap, newFileBlocks fileBlockMap,
dirtyBcache data.DirtyBlockCacheSimple, bps blockPutState,
copyBehavior prepFolderCopyBehavior) error {
// If this has no children, then sync it, as far back as stopAt.
if len(node.children) == 0 {
// Look for the directory block or the new file block.
entryType := data.Dir
hasDirBlock, err := dbm.hasBlock(ctx, node.ptr)
if err != nil {
return err
}
// non-nil exactly when entryType != Dir.
var block data.Block
var fblock *data.FileBlock
if hasDirBlock {
dirBlock, err := dbm.getBlock(ctx, node.ptr)
if err != nil {
return err
}
block = dirBlock
} else {
// This must be a file, so look it up in the parent
if node.parent == nil {
return fmt.Errorf("No parent found for node %v while "+
"syncing path %v", node.ptr, node.mergedPath.Path)
}
var err error
fblock, err = newFileBlocks.GetTopBlock(
ctx, node.parent.ptr, node.mergedPath.TailName().Plaintext())
if err != nil {
return err
}
block = fblock
entryType = data.File // TODO: FIXME for Ex and Sym
}
// For an indirect file block, make sure a new
// reference is made for every child block.
if copyBehavior == prepFolderCopyIndirectFileBlocks &&
entryType != data.Dir && fblock.IsInd {
var infos []data.BlockInfo
var err error
// If journaling is enabled, new references aren't
// supported. We have to fetch each block and ready
// it. TODO: remove this when KBFS-1149 is fixed.
if TLFJournalEnabled(fup.config, fup.id()) {
infos, err = fup.blocks.UndupChildrenInCopy(
ctx, lState, newMD.ReadOnly(), node.mergedPath, bps,
dirtyBcache, fblock)
if err != nil {
return err
}
} else {
// Ready any mid-level internal children.
_, err = fup.blocks.ReadyNonLeafBlocksInCopy(
ctx, lState, newMD.ReadOnly(), node.mergedPath, bps,
dirtyBcache, fblock)
if err != nil {
return err
}
infos, err = fup.blocks.
GetIndirectFileBlockInfosWithTopBlock(
ctx, lState, newMD.ReadOnly(), node.mergedPath, fblock)
if err != nil {
return err
}
for _, info := range infos {
// The indirect blocks were already added to
// childBps, so only add the dedup'd leaf blocks.
if info.RefNonce != kbfsblock.ZeroRefNonce {
err = bps.AddNewBlock(
ctx, info.BlockPointer, nil, data.ReadyBlockData{}, nil)
if err != nil {
return err
}
}
}
}
for _, info := range infos {
newMD.AddRefBlock(info)
}
}
// Assume the mtime/ctime are already fixed up in the blocks
// in the dbm.
_, _, err = fup.prepUpdateForPath(
ctx, lState, chargedTo, newMD, block, node.ptr,
*node.mergedPath.ParentPath(), node.mergedPath.TailName(),
entryType, false, false, stopAt, dbm, bps)
if err != nil {
return err
}
return nil
}
// If there is more than one child, use this node as the stopAt
// since it is the branch point, except for the last child.
count := 0
for _, child := range node.children {
localStopAt := node.ptr
count++
if count == len(node.children) {
localStopAt = stopAt
}
err := fup.prepTree(
ctx, lState, unmergedChains, newMD, chargedTo, child, localStopAt,
dbm, newFileBlocks, dirtyBcache, bps, copyBehavior)
if err != nil {
return err
}
}
return nil
}
// updateResolutionUsageLockedCache figures out how many bytes are
// referenced and unreferenced in the merged branch by this
// resolution. Only needs to be called for non-squash resolutions.
// `fup.cacheLock` must be taken before calling.
func (fup *folderUpdatePrepper) updateResolutionUsageLockedCache(
ctx context.Context, lState *kbfssync.LockState, md *RootMetadata,
bps blockPutState, unmergedChains, mergedChains *crChains,
mostRecentMergedMD ImmutableRootMetadata,
refs, unrefs map[data.BlockPointer]bool) error {
md.SetRefBytes(0)
md.SetUnrefBytes(0)
md.SetMDRefBytes(0)
md.SetDiskUsage(mostRecentMergedMD.DiskUsage())
md.SetMDDiskUsage(mostRecentMergedMD.MDDiskUsage())
localBlocks := make(map[data.BlockPointer]data.Block)
for _, ptr := range bps.Ptrs() {
if block, err := bps.GetBlock(ctx, ptr); err == nil && block != nil {
localBlocks[ptr] = block
}
}
// Add bytes for every ref'd block.
refPtrsToFetch := make([]data.BlockPointer, 0, len(refs))
var refSum uint64
for ptr := range refs {
if block, ok := localBlocks[ptr]; ok {
refSum += uint64(block.GetEncodedSize())
} else {
refPtrsToFetch = append(refPtrsToFetch, ptr)
}
fup.vlog.CLogf(ctx, libkb.VLog1, "Ref'ing block %v", ptr)
}
// Look up the total sum of the ref blocks in parallel to get
// their sizes.
//
// TODO: If the blocks weren't already in the cache, this call
// won't cache them, so it's kind of wasting work. Furthermore,
// we might be able to get the encoded size from other sources as
// well (such as its directory entry or its indirect file block)
// if we happened to have come across it before.
refSumFetched, err := fup.blocks.GetCleanEncodedBlocksSizeSum(
ctx, lState, md.ReadOnly(), refPtrsToFetch, nil, fup.branch(), false)
if err != nil {
return err
}
refSum += refSumFetched
fup.vlog.CLogf(ctx, libkb.VLog1, "Ref'ing a total of %d bytes", refSum)
md.AddRefBytes(refSum)
md.AddDiskUsage(refSum)
unrefPtrsToFetch := make([]data.BlockPointer, 0, len(unrefs))
var unrefSum uint64
for ptr := range unrefs {
original, ok := unmergedChains.originals[ptr]
if !ok {
original = ptr
}
if original != ptr || unmergedChains.isCreated(original) {
// Only unref pointers that weren't created as part of the
// unmerged branch. Either they existed already or they
// were created as part of the merged branch.
continue
}
// Also make sure this wasn't already removed or overwritten
// on the merged branch.
original, ok = mergedChains.originals[ptr]
if !ok {
original = ptr
}
mergedChain, ok := mergedChains.byOriginal[original]
if (ok && original != mergedChain.mostRecent && original == ptr) ||
mergedChains.isDeleted(original) {
continue
}
if info, ok := fup.cachedInfos[ptr]; ok {
unrefSum += uint64(info.EncodedSize)
} else {
unrefPtrsToFetch = append(unrefPtrsToFetch, ptr)
}
}
// Look up the unref blocks in parallel to get their sizes. Since
// we don't know whether these are files or directories, just look
// them up generically. Ignore any recoverable errors for unrefs.
// Note that we can't combine these with the above ref fetches
// since they require a different MD. If the merged changes
// didn't change any blocks (in particular, the root block), we
// can assume all the blocks we are unreferencing were live;
// otherwise, we need to check with the server to make sure.
onlyCountIfLive := len(mergedChains.byOriginal) != 0
unrefSumFetched, err := fup.blocks.GetCleanEncodedBlocksSizeSum(
ctx, lState, mostRecentMergedMD, unrefPtrsToFetch, unrefs,
fup.branch(), onlyCountIfLive)
if err != nil {
return err
}
unrefSum += unrefSumFetched
// Subtract bytes for every unref'd block that wasn't created in
// the unmerged branch.
fup.vlog.CLogf(ctx, libkb.VLog1, "Unref'ing a total of %d bytes", unrefSum)
md.AddUnrefBytes(unrefSum)
md.SetDiskUsage(md.DiskUsage() - unrefSum)
return nil
}
// addUnrefToFinalResOp makes a resolutionOp at the end of opsList if
// one doesn't exist yet, and then adds the given pointer as an unref
// block to it.
func addUnrefToFinalResOp(ops opsList, ptr data.BlockPointer,
doNotUnref map[data.BlockPointer]bool) opsList {
// Make sure the block ID we want to unref isn't in the "do not
// unref" list -- it could mean that block has already been GC'd
// by the merged branch. We can't compare pointers directly
// because GC'd pointers contain no block context.
for noUnref := range doNotUnref {
if ptr.ID == noUnref.ID {
return ops
}
}
resOp, ok := ops[len(ops)-1].(*resolutionOp)
if !ok {
resOp = newResolutionOp()
ops = append(ops, resOp)
}
resOp.AddUncommittedUnrefBlock(ptr)
return ops
}
// updateResolutionUsageAndPointersLockedCache figures out how many
// bytes are referenced and unreferenced in the merged branch by this
// resolution (if needed), and adds referenced and unreferenced
// pointers to a final `resolutionOp` as necessary. It should be
// called before the block changes are unembedded in md. It returns
// the list of blocks that can be remove from the flushing queue, if
// any. `fup.cacheLock` must be taken before calling.
func (fup *folderUpdatePrepper) updateResolutionUsageAndPointersLockedCache(
ctx context.Context, lState *kbfssync.LockState, md *RootMetadata,
bps blockPutState, unmergedChains, mergedChains *crChains,
mostRecentUnmergedMD, mostRecentMergedMD ImmutableRootMetadata,
isLocalSquash bool) (
blocksToDelete []kbfsblock.ID, err error) {
// Track the refs and unrefs in a set, to ensure no duplicates
refs := make(map[data.BlockPointer]bool)
unrefs := make(map[data.BlockPointer]bool)
for _, op := range md.data.Changes.Ops {
// Iterate in reverse since we may be deleting references as we go.
for i := len(op.Refs()) - 1; i >= 0; i-- {
ptr := op.Refs()[i]
// Don't add usage if it's an unembedded block change
// pointer. Also, we shouldn't be referencing this
// anymore!
if unmergedChains.blockChangePointers[ptr] {
fup.vlog.CLogf(
ctx, libkb.VLog1, "Ignoring block change ptr %v", ptr)
op.DelRefBlock(ptr)
} else {
refs[ptr] = true
}
}
// Iterate in reverse since we may be deleting unrefs as we go.
for i := len(op.Unrefs()) - 1; i >= 0; i-- {
ptr := op.Unrefs()[i]
unrefs[ptr] = true
delete(refs, ptr)
if _, isCreateOp := op.(*createOp); isCreateOp {
// The only way a create op should have unref blocks
// is if it was created during conflict resolution.
// In that case, we should move the unref to a final
// resolution op, so it doesn't confuse future
// resolutions.
op.DelUnrefBlock(ptr)
md.data.Changes.Ops =
addUnrefToFinalResOp(
md.data.Changes.Ops, ptr, unmergedChains.doNotUnrefPointers)
}
}
for _, update := range op.allUpdates() {
if update.Unref != update.Ref {
unrefs[update.Unref] = true
delete(refs, update.Unref)
refs[update.Ref] = true
}
}
}
for _, resOp := range unmergedChains.resOps {
for _, ptr := range resOp.CommittedUnrefs() {
original, err := unmergedChains.originalFromMostRecentOrSame(ptr)
if err != nil {
return nil, err
}
if !unmergedChains.isCreated(original) {
fup.vlog.CLogf(
ctx, libkb.VLog1, "Unref'ing %v from old resOp", ptr)
unrefs[ptr] = true
}
}
}
// Unreference (and decrement the size) of any to-unref blocks
// that weren't created in the unmerged branch. (Example: non-top
// dir blocks that were changed during the CR process.)
for ptr := range unmergedChains.toUnrefPointers {
original, err := unmergedChains.originalFromMostRecentOrSame(ptr)
if err != nil {
return nil, err
}
if !unmergedChains.isCreated(original) {
unrefs[ptr] = true
}
}
if isLocalSquash {
// Collect any references made in previous resolution ops that
// are being squashed together. These must be re-referenced in
// the MD object to survive the squash.
resToRef := make(map[data.BlockPointer]bool)
for _, resOp := range unmergedChains.resOps {
for _, ptr := range resOp.Refs() {
if !unrefs[ptr] {
resToRef[ptr] = true
}
}
for _, ptr := range resOp.Unrefs() {
delete(resToRef, ptr)
}
for _, update := range resOp.allUpdates() {
delete(resToRef, update.Unref)
}
}
for ptr := range resToRef {
fup.vlog.CLogf(ctx, libkb.VLog1, "Ref'ing %v from old resOp", ptr)
refs[ptr] = true
md.data.Changes.Ops[0].AddRefBlock(ptr)
}
unmergedUsage := mostRecentUnmergedMD.DiskUsage()
mergedUsage := mostRecentMergedMD.DiskUsage()
// Local squashes can just use the bytes and usage from the
// latest unmerged MD, and we can avoid all the block fetching
// done by `updateResolutionUsage()`.
md.SetDiskUsage(unmergedUsage)
// TODO: it might be better to add up all the ref bytes, and
// all the unref bytes, from all unmerged MDs, instead of just
// calculating the difference between the usages. But that's
// not quite right either since it counts blocks that are
// ref'd and unref'd within the squash.
if md.DiskUsage() > mergedUsage {
md.SetRefBytes(md.DiskUsage() - mergedUsage)
md.SetUnrefBytes(0)
} else {
md.SetRefBytes(0)
md.SetUnrefBytes(mergedUsage - md.DiskUsage())
}
mergedMDUsage := mostRecentMergedMD.MDDiskUsage()
if md.MDDiskUsage() < mergedMDUsage {
return nil, fmt.Errorf("MD disk usage went down on unmerged "+
"branch: %d vs %d", md.MDDiskUsage(), mergedMDUsage)
}
// Additional MD disk usage will be determined entirely by the
// later `unembedBlockChanges()` call.
md.SetMDDiskUsage(mergedMDUsage)
md.SetMDRefBytes(0)
} else {
err = fup.updateResolutionUsageLockedCache(
ctx, lState, md, bps, unmergedChains, mergedChains,
mostRecentMergedMD, refs, unrefs)
if err != nil {
return nil, err
}
}
// Any blocks that were created on the unmerged branch and have
// been flushed, but didn't survive the resolution, should be
// marked as unreferenced in the resolution.
toUnref := make(map[data.BlockPointer]bool)
for ptr := range unmergedChains.originals {
if !refs[ptr] && !unrefs[ptr] {
toUnref[ptr] = true
}
}
for ptr := range unmergedChains.createdOriginals {
if !refs[ptr] && !unrefs[ptr] && unmergedChains.byOriginal[ptr] != nil {
toUnref[ptr] = true
} else if unmergedChains.blockChangePointers[ptr] {
toUnref[ptr] = true
}
}
for ptr := range unmergedChains.toUnrefPointers {
toUnref[ptr] = true
}
for _, resOp := range unmergedChains.resOps {
for _, ptr := range resOp.Refs() {
if !isLocalSquash && !refs[ptr] && !unrefs[ptr] {
toUnref[ptr] = true
}
}
for _, ptr := range resOp.Unrefs() {
if !refs[ptr] && !unrefs[ptr] {
toUnref[ptr] = true
}
}
}
deletedRefs := make(map[data.BlockPointer]bool)
deletedUnrefs := make(map[data.BlockPointer]bool)
for ptr := range toUnref {
if ptr == data.ZeroPtr || unmergedChains.doNotUnrefPointers[ptr] {
// A zero pointer can sneak in from the unrefs field of a
// syncOp following a failed syncOp, via
// `unmergedChains.toUnrefPointers` after a chain collapse.
continue
}
isUnflushed, err := fup.config.BlockServer().IsUnflushed(
ctx, fup.id(), ptr.ID)
if err != nil {
return nil, err
}
if isUnflushed {
blocksToDelete = append(blocksToDelete, ptr.ID)
deletedUnrefs[ptr] = true
// No need to unreference this since we haven't flushed it yet.
continue
}
deletedRefs[ptr] = true
// Put the unrefs in a new resOp after the final operation, to
// cancel out any stray refs in earlier ops.
fup.vlog.CLogf(ctx, libkb.VLog1, "Unreferencing dropped block %v", ptr)
md.data.Changes.Ops = addUnrefToFinalResOp(
md.data.Changes.Ops, ptr, unmergedChains.doNotUnrefPointers)
}
// Scrub all refs and unrefs of blocks that never made it to the
// server, for smaller updates and to make things easier on the
// StateChecker. We scrub the refs too because in some cases
// (e.g., on a copied conflict file), we add an unref without
// removing the original ref, and if we remove the unref, the ref
// must go too.
if len(deletedRefs) > 0 || len(deletedUnrefs) > 0 {
for _, op := range md.data.Changes.Ops {
var toDelRef []data.BlockPointer
for _, ref := range op.Refs() {
if deletedRefs[ref] || deletedUnrefs[ref] {
toDelRef = append(toDelRef, ref)
}
}
for _, ref := range toDelRef {
fup.vlog.CLogf(ctx, libkb.VLog1, "Scrubbing ref %v", ref)
op.DelRefBlock(ref)
}
var toDelUnref []data.BlockPointer
for _, unref := range op.Unrefs() {
if deletedUnrefs[unref] {
toDelUnref = append(toDelUnref, unref)
}
}
for _, unref := range toDelUnref {
fup.vlog.CLogf(ctx, libkb.VLog1, "Scrubbing unref %v", unref)
op.DelUnrefBlock(unref)
}
}
for _, resOp := range unmergedChains.resOps {
for _, unref := range resOp.Unrefs() {
if deletedUnrefs[unref] {
fup.vlog.CLogf(
ctx, libkb.VLog1, "Scrubbing resOp unref %v", unref)
resOp.DelUnrefBlock(unref)
}
}
}
}
fup.log.CDebugf(ctx, "New md byte usage: %d ref, %d unref, %d total usage "+
"(previously %d)", md.RefBytes(), md.UnrefBytes(), md.DiskUsage(),
mostRecentMergedMD.DiskUsage())
return blocksToDelete, nil
}
func (fup *folderUpdatePrepper) setChildrenNodes(
ctx context.Context, lState *kbfssync.LockState, kmd libkey.KeyMetadata,
p data.Path, indexInPath int, dbm dirBlockMap, nextNode *pathTreeNode,
currPath data.Path, names []string) {
dd, cleanupFn := fup.blocks.newDirDataWithDBM(
lState, currPath, keybase1.UserOrTeamID(""), kmd, dbm)
defer cleanupFn()
pnode := p.Path[indexInPath]
for _, namePlain := range names {
if _, ok := nextNode.children[namePlain]; ok {
continue
}
// Try to lookup the block pointer, but this might be
// for a new file.
var filePtr data.BlockPointer
name := data.NewPathPartString(namePlain, currPath.Obfuscator())
de, err := dd.Lookup(ctx, name)
switch errors.Cause(err).(type) {
case nil:
filePtr = de.BlockPointer
case idutil.NoSuchNameError:
default:
fup.log.CWarningf(ctx, "Couldn't look up child: %+v", err)
continue
}
fup.vlog.CLogf(
ctx, libkb.VLog1, "Creating child node for name %s for parent %v",
name, pnode.BlockPointer)
childPath := data.Path{
FolderBranch: p.FolderBranch,
Path: make([]data.PathNode, indexInPath+2),
}
copy(childPath.Path[0:indexInPath+1], p.Path[0:indexInPath+1])
childPath.Path[indexInPath+1] = data.PathNode{Name: name}
childNode := &pathTreeNode{
ptr: filePtr,
parent: nextNode,
children: make(map[string]*pathTreeNode),
mergedPath: childPath,
}
nextNode.children[namePlain] = childNode
}
}