forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cr_chains.go
1521 lines (1400 loc) · 43.7 KB
/
cr_chains.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 2016 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"
"sort"
"time"
"github.com/keybase/client/go/kbfs/data"
"github.com/keybase/client/go/kbfs/idutil"
"github.com/keybase/client/go/kbfs/kbfscodec"
"github.com/keybase/client/go/kbfs/kbfscrypto"
"github.com/keybase/client/go/kbfs/kbfsmd"
"github.com/keybase/client/go/kbfs/libkey"
"github.com/keybase/client/go/kbfs/tlf"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
// crChain represents the set of operations that happened to a
// particular KBFS node (e.g., individual file or directory) over a
// given set of MD updates. It also tracks the starting and ending
// block pointers for the node.
type crChain struct {
ops []op
original, mostRecent data.BlockPointer
file bool
obfuscator data.Obfuscator
tlfID tlf.ID
}
// collapse finds complementary pairs of operations that cancel each
// other out, and remove the relevant operations from the chain.
// Examples include:
// * A create followed by a remove for the same name (delete both ops)
// * A create followed by a create (renamed == true) for the same name
// (delete the create op)
// * A remove that only unreferences blocks created within this branch
// This function returns the list of pointers that should be unreferenced
// as part of an eventual resolution of the corresponding branch.
func (cc *crChain) collapse(createdOriginals map[data.BlockPointer]bool,
originals map[data.BlockPointer]data.BlockPointer) (toUnrefs []data.BlockPointer) {
createsSeen := make(map[string]int)
indicesToRemove := make(map[int]bool)
var wr []WriteRange
lastSyncOp := -1
var syncRefs, syncUnrefs []data.BlockPointer
for i, op := range cc.ops {
switch realOp := op.(type) {
case *createOp:
if prevCreateIndex, ok :=
createsSeen[realOp.NewName]; realOp.renamed && ok {
// A rename has papered over the first create, so
// just drop it.
indicesToRemove[prevCreateIndex] = true
}
createsSeen[realOp.NewName] = i
case *rmOp:
if prevCreateIndex, ok := createsSeen[realOp.OldName]; ok {
delete(createsSeen, realOp.OldName)
// The rm cancels out the create, so remove it.
indicesToRemove[prevCreateIndex] = true
// Also remove the rmOp if it was part of a rename
// (i.e., it wasn't a "real" rm), or if it otherwise
// only unreferenced blocks that were created on this
// branch.
doRemove := true
for _, unref := range op.Unrefs() {
original, ok := originals[unref]
if !ok {
original = unref
}
if !createdOriginals[original] {
doRemove = false
break
}
}
if doRemove {
indicesToRemove[i] = true
toUnrefs = append(toUnrefs, op.Unrefs()...)
}
}
case *setAttrOp:
// TODO: Collapse opposite setex pairs
case *syncOp:
wr = realOp.collapseWriteRange(wr)
indicesToRemove[i] = true
lastSyncOp = i
// The last op will have its refs listed twice in the
// collapsed op, but that's harmless.
syncRefs = append(syncRefs, op.Refs()...)
// The last op will have its unrefs listed twice in the
// collapsed op, but that's harmless.
syncUnrefs = append(syncUnrefs, op.Unrefs()...)
default:
// ignore other op types
}
}
if len(indicesToRemove) > 0 {
ops := make([]op, 0, len(cc.ops)-len(indicesToRemove))
for i, op := range cc.ops {
if i == lastSyncOp {
so, ok := op.(*syncOp)
if !ok {
panic(fmt.Sprintf(
"Op %s at index %d should have been a syncOp", op, i))
}
so.Writes = wr
for _, ref := range syncRefs {
op.AddRefBlock(ref)
}
for _, unref := range syncUnrefs {
op.AddUnrefBlock(unref)
}
ops = append(ops, op)
} else if !indicesToRemove[i] {
ops = append(ops, op)
}
}
cc.ops = ops
}
return toUnrefs
}
func (cc *crChain) getCollapsedWriteRange() []WriteRange {
if !cc.isFile() {
return nil
}
var wr []WriteRange
for _, op := range cc.ops {
syncOp, ok := op.(*syncOp)
if !ok {
continue
}
wr = syncOp.collapseWriteRange(wr)
}
return wr
}
func writeRangesEquivalent(
wr1 []WriteRange, wr2 []WriteRange) bool {
// Both empty?
if len(wr1) == 0 && len(wr2) == 0 {
return true
}
// If both branches contain no writes, and their truncation
// points are the same, then there are no unmerged actions to
// take.
if len(wr1) == 1 && wr1[0].isTruncate() &&
len(wr2) == 1 && wr2[0].isTruncate() &&
wr1[0].Off == wr2[0].Off {
return true
}
// TODO: In the future we may be able to do smarter merging
// here if the write ranges don't overlap, though maybe only
// for certain file types?
return false
}
func (cc *crChain) removeSyncOps() {
var newOps []op
for _, op := range cc.ops {
if _, ok := op.(*syncOp); !ok {
newOps = append(newOps, op)
}
}
cc.ops = newOps
}
func (cc *crChain) getActionsToMerge(
ctx context.Context, renamer ConflictRenamer, mergedPath data.Path,
mergedChain *crChain) (crActionList, error) {
var actions crActionList
// If this is a file, determine whether the unmerged chain
// could actually have changed the file in some way that it
// hasn't already been changed. For example, if they both
// truncate the file to the same length, and there are no
// other writes, we can just drop the unmerged syncs.
if cc.isFile() && mergedChain != nil {
// The write ranges should already be collapsed into a single
// syncOp, these calls just find that one remaining syncOp.
myWriteRange := cc.getCollapsedWriteRange()
mergedWriteRange := mergedChain.getCollapsedWriteRange()
if writeRangesEquivalent(myWriteRange, mergedWriteRange) {
// drop all sync ops
cc.removeSyncOps()
}
}
// Check each op against all ops in the corresponding merged
// chain, looking for conflicts. If there is a conflict, return
// it as part of the action list. If there are no conflicts for
// that op, return the op's default actions.
for _, unmergedOp := range cc.ops {
conflict := false
if mergedChain != nil {
for _, mergedOp := range mergedChain.ops {
action, err :=
unmergedOp.checkConflict(
ctx, renamer, mergedOp, cc.isFile())
if err != nil {
return nil, err
}
if action != nil {
conflict = true
actions = append(actions, action)
}
}
}
// no conflicts!
if !conflict {
action := unmergedOp.getDefaultAction(mergedPath)
if action != nil {
actions = append(actions, action)
}
}
}
return actions, nil
}
func (cc *crChain) isFile() bool {
return cc.file
}
// identifyType figures out whether this chain represents a file or
// directory. It tries to figure it out based purely on operation
// state, but setAttr(mtime) can apply to either type; in that case,
// we need to fetch the block to figure out the type.
func (cc *crChain) identifyType(ctx context.Context, fbo *folderBlockOps,
kmd libkey.KeyMetadata, chains *crChains) error {
if len(cc.ops) == 0 {
return nil
}
// If any op is setAttr (ex or size) or sync, this is a file
// chain. If it only has a setAttr/mtime, we don't know what it
// is, so fall through and fetch the block unless we come across
// another op that can determine the type.
var parentDir data.BlockPointer
var lastSetAttr *setAttrOp
for _, op := range cc.ops {
switch realOp := op.(type) {
case *syncOp:
cc.file = true
return nil
case *setAttrOp:
if realOp.Attr != mtimeAttr {
cc.file = true
return nil
}
// We can't tell the file type from an mtimeAttr, so we
// may have to actually fetch the block to figure it out.
parentDir = realOp.Dir.Ref
lastSetAttr = realOp
default:
return nil
}
}
parentOriginal, ok := chains.originals[parentDir]
if !ok {
// If the parent dir was created as part of a squash/batch,
// there might not be any update for it, and so it might not
// appear in the `originals` map. In that case, we can use
// the original.
parentOriginal = parentDir
ok = chains.createdOriginals[parentDir]
}
if !ok {
if chains.isDeleted(parentDir) {
// If the parent's been deleted, it doesn't matter whether
// we find the type or not.
return nil
}
fbo.log.CDebugf(ctx,
"Can't find parent dir chain, unref=%s/ref=%s, for op %s (file=%s)",
lastSetAttr.Dir.Unref, lastSetAttr.Dir.Ref,
lastSetAttr, lastSetAttr.File)
// If the parent still can't be found, then barring bugs the
// whole directory was created and deleted within this update,
// so it should be treated as deleted.
chains.deletedOriginals[cc.original] = true
return nil
}
// We have to find the current parent directory block. If the
// file has been renamed, that might be different from parentDir
// above.
if newParent, _, ok := chains.renamedParentAndName(cc.original); ok {
parentOriginal = newParent
}
parentMostRecent, err := chains.mostRecentFromOriginalOrSame(parentOriginal)
if err != nil {
return err
}
// If we get down here, we have an ambiguity, and need to fetch
// the block to figure out the file type.
parentPath := data.Path{
FolderBranch: fbo.folderBranch,
Path: []data.PathNode{{
BlockPointer: parentMostRecent,
Name: data.PathPartString{},
}},
}
parentDD, cleanupFn := fbo.newDirDataWithDBM(
makeFBOLockState(), parentPath, keybase1.UserOrTeamID(""), kmd,
newDirBlockMapMemory())
defer cleanupFn()
entries, err := parentDD.GetEntries(ctx)
if err != nil {
return err
}
// We don't have the file name handy, so search for the pointer.
found := false
for _, entry := range entries {
if entry.BlockPointer != cc.mostRecent {
continue
}
switch entry.Type {
case data.Dir:
cc.file = false
case data.File:
cc.file = true
case data.Exec:
cc.file = true
default:
return errors.Errorf("Unexpected chain type: %s", entry.Type)
}
found = true
break
}
if !found {
// If the node can't be found, then the entry has been removed
// already, and there won't be any conflicts to resolve
// anyway. Mark it as deleted.
chains.deletedOriginals[cc.original] = true
// However, we still might be able to determine the type of
// the entry via the `rmOp` that actually deleted it. This
// could be important if the entry ends up being recreated due
// to a conflict with another branch (e.g. HOTPOT-719). So we
// still want to make an attempt to recover that entry type
// from the parent chain.
parentChain, ok := chains.byOriginal[parentOriginal]
if ok {
for _, op := range parentChain.ops {
rop, ok := op.(*rmOp)
if !ok {
continue
}
unrefs := rop.Unrefs()
if len(unrefs) > 0 && unrefs[0] == cc.mostRecent {
cc.file = rop.RemovedType == data.File ||
rop.RemovedType == data.Exec
break
}
}
}
}
return nil
}
func (cc *crChain) remove(ctx context.Context, log logger.Logger,
revision kbfsmd.Revision) bool {
anyRemoved := false
var newOps []op
for i, currOp := range cc.ops {
info := currOp.getWriterInfo()
if info.revision == revision {
log.CDebugf(ctx, "Removing op %s from chain with mostRecent=%v",
currOp, cc.mostRecent)
if !anyRemoved {
newOps = make([]op, i, len(cc.ops)-1)
// Copy everything we've iterated over so far.
copy(newOps[:i], cc.ops[:i])
anyRemoved = true
}
} else if anyRemoved {
newOps = append(newOps, currOp)
}
}
if anyRemoved {
cc.ops = newOps
}
return anyRemoved
}
func (cc *crChain) hasSyncOp() bool {
for _, op := range cc.ops {
if _, ok := op.(*syncOp); ok {
return true
}
}
return false
}
func (cc *crChain) hasSetAttrOp() bool {
for _, op := range cc.ops {
if _, ok := op.(*setAttrOp); ok {
return true
}
}
return false
}
func (cc *crChain) ensurePath(op op, ptr data.BlockPointer) {
if op.getFinalPath().IsValid() {
return
}
// Use the same obfuscator for both the node's name and it's
// children, because it's too complicated to try to get the real
// parent obfuscator from the chain.
op.setFinalPath(data.Path{
FolderBranch: data.FolderBranch{
Tlf: cc.tlfID,
Branch: data.MasterBranch,
},
Path: []data.PathNode{{
BlockPointer: ptr,
Name: data.NewPathPartString("", cc.obfuscator),
}},
ChildObfuscator: cc.obfuscator,
})
}
type renameInfo struct {
originalOldParent data.BlockPointer
oldName string
originalNewParent data.BlockPointer
newName string
}
func (ri renameInfo) String() string {
return fmt.Sprintf(
"renameInfo{originalOldParent: %s, oldName: %s, originalNewParent: %s, newName: %s}",
ri.originalOldParent, ri.oldName,
ri.originalNewParent, ri.newName)
}
// crChains contains a crChain for every KBFS node affected by the
// operations over a given set of MD updates. The chains are indexed
// by both the starting (original) and ending (most recent) pointers.
// It also keeps track of which chain points to the root of the folder.
type crChains struct {
byOriginal map[data.BlockPointer]*crChain
byMostRecent map[data.BlockPointer]*crChain
originalRoot data.BlockPointer
// The original blockpointers for nodes that have been
// unreferenced or initially referenced during this chain.
deletedOriginals map[data.BlockPointer]bool
createdOriginals map[data.BlockPointer]bool
// A map from original blockpointer to the full rename operation
// of the node (from the original location of the node to the
// final locations).
renamedOriginals map[data.BlockPointer]renameInfo
// Separately track pointers for unembedded block changes.
blockChangePointers map[data.BlockPointer]bool
// Pointers that should be explicitly cleaned up in the resolution.
toUnrefPointers map[data.BlockPointer]bool
// Pointers that should explicitly *not* be cleaned up in the
// resolution.
doNotUnrefPointers map[data.BlockPointer]bool
// Also keep the info for the most recent chain MD used to
// build these chains.
mostRecentChainMDInfo KeyMetadataWithRootDirEntry
// We need to be able to track ANY BlockPointer, at any point in
// the chain, back to its original.
originals map[data.BlockPointer]data.BlockPointer
// All the resolution ops from the branch, in order.
resOps []*resolutionOp
// Make per-chain obfuscators.
makeObfuscator func() data.Obfuscator
}
func (ccs *crChains) addOp(ptr data.BlockPointer, op op) error {
currChain, ok := ccs.byMostRecent[ptr]
if !ok {
return errors.Errorf("Could not find chain for most recent ptr %v", ptr)
}
// Make sure this op has a valid path with an obfuscator.
currChain.ensurePath(op, ptr)
currChain.ops = append(currChain.ops, op)
return nil
}
// addNoopChain adds a new chain with no ops to the chains struct, if
// that pointer isn't involved in any chains yet.
func (ccs *crChains) addNoopChain(ptr data.BlockPointer) {
if _, ok := ccs.byMostRecent[ptr]; ok {
return
}
if _, ok := ccs.byOriginal[ptr]; ok {
return
}
if _, ok := ccs.originals[ptr]; ok {
return
}
chain := &crChain{
original: ptr,
mostRecent: ptr,
obfuscator: ccs.makeObfuscator(),
tlfID: ccs.mostRecentChainMDInfo.TlfID(),
}
ccs.byOriginal[ptr] = chain
ccs.byMostRecent[ptr] = chain
}
func (ccs *crChains) makeChainForOp(op op) error {
// Ignore gc ops -- their unref semantics differ from the other
// ops. Note that this only matters for old gcOps: new gcOps
// only unref the block ID, and not the whole pointer, so they
// wouldn't confuse chain creation.
if _, isGCOp := op.(*GCOp); isGCOp {
return nil
}
// First set the pointers for all updates, and track what's been
// created and destroyed.
for _, update := range op.allUpdates() {
chain, ok := ccs.byMostRecent[update.Unref]
if !ok {
// No matching chain means it's time to start a new chain
chain = &crChain{
original: update.Unref,
obfuscator: ccs.makeObfuscator(),
tlfID: ccs.mostRecentChainMDInfo.TlfID(),
}
ccs.byOriginal[update.Unref] = chain
}
if chain.mostRecent.IsInitialized() {
// delete the old most recent pointer, it's no longer needed
delete(ccs.byMostRecent, chain.mostRecent)
}
chain.mostRecent = update.Ref
ccs.byMostRecent[update.Ref] = chain
if chain.original != update.Ref {
// Always be able to track this one back to its original.
ccs.originals[update.Ref] = chain.original
}
}
for _, ptr := range op.Refs() {
ccs.createdOriginals[ptr] = true
}
for _, ptr := range op.Unrefs() {
// Look up the original pointer corresponding to this most
// recent one.
original, ok := ccs.originals[ptr]
if !ok {
original = ptr
}
// If it has already been updated to something else, we should
// just ignore this unref. See KBFS-3258.
if chain, ok := ccs.byOriginal[original]; ok {
if ptr != chain.mostRecent {
continue
}
}
ccs.deletedOriginals[original] = true
}
// then set the op depending on the actual op type
switch realOp := op.(type) {
default:
panic(fmt.Sprintf("Unrecognized operation: %v", op))
case *createOp:
err := ccs.addOp(realOp.Dir.Ref, op)
if err != nil {
return err
}
case *rmOp:
err := ccs.addOp(realOp.Dir.Ref, op)
if err != nil {
return err
}
if len(op.Unrefs()) == 0 {
// This might be an rmOp of a file that was created and
// removed within a single batch. If it's been renamed,
// we should also mark it as deleted to avoid confusing
// the CR code.
chain, ok := ccs.byMostRecent[realOp.Dir.Ref]
if !ok {
return errors.Errorf("No chain for rmOp dir %v", realOp.Dir.Ref)
}
for original, ri := range ccs.renamedOriginals {
if ri.originalNewParent == chain.original &&
ri.newName == realOp.OldName {
ccs.deletedOriginals[original] = true
break
}
}
}
case *renameOp:
// split rename op into two separate operations, one for
// remove and one for create
ro, err := newRmOp(
realOp.OldName, realOp.OldDir.Unref, realOp.RenamedType)
if err != nil {
return err
}
ro.setWriterInfo(realOp.getWriterInfo())
ro.setLocalTimestamp(realOp.getLocalTimestamp())
// realOp.OldDir.Ref may be zero if this is a
// post-resolution chain, so set ro.Dir.Ref manually.
ro.Dir.Ref = realOp.OldDir.Ref
err = ccs.addOp(realOp.OldDir.Ref, ro)
if err != nil {
return err
}
ndu := realOp.NewDir.Unref
ndr := realOp.NewDir.Ref
if realOp.NewDir == (blockUpdate{}) {
// this is a rename within the same directory
ndu = realOp.OldDir.Unref
ndr = realOp.OldDir.Ref
}
if len(realOp.Unrefs()) > 0 {
// Something was overwritten; make an explicit rm for it
// so we can check for conflicts.
roOverwrite, err := newRmOp(
realOp.NewName, ndu, data.File)
if err != nil {
return err
}
roOverwrite.setWriterInfo(realOp.getWriterInfo())
err = roOverwrite.Dir.setRef(ndr)
if err != nil {
return err
}
err = ccs.addOp(ndr, roOverwrite)
if err != nil {
return err
}
// Transfer any unrefs over.
for _, ptr := range realOp.Unrefs() {
roOverwrite.AddUnrefBlock(ptr)
}
}
co, err := newCreateOp(realOp.NewName, ndu, realOp.RenamedType)
if err != nil {
return err
}
co.setWriterInfo(realOp.getWriterInfo())
co.setLocalTimestamp(realOp.getLocalTimestamp())
co.renamed = true
// ndr may be zero if this is a post-resolution chain,
// so set co.Dir.Ref manually.
co.Dir.Ref = ndr
err = ccs.addOp(ndr, co)
if err != nil {
return err
}
// also keep track of the new parent for the renamed node
if realOp.Renamed.IsInitialized() {
newParentChain, ok := ccs.byMostRecent[ndr]
if !ok {
return errors.Errorf("While renaming, couldn't find the chain "+
"for the new parent %v", ndr)
}
oldParentChain, ok := ccs.byMostRecent[realOp.OldDir.Ref]
if !ok {
return errors.Errorf("While renaming, couldn't find the chain "+
"for the old parent %v", ndr)
}
renamedOriginal := realOp.Renamed
if renamedChain, ok := ccs.byMostRecent[realOp.Renamed]; ok {
renamedOriginal = renamedChain.original
}
// Use the previous old info if there is one already,
// in case this node has been renamed multiple times.
ri, ok := ccs.renamedOriginals[renamedOriginal]
if !ok {
// Otherwise make a new one.
ri = renameInfo{
originalOldParent: oldParentChain.original,
oldName: realOp.OldName,
}
}
ri.originalNewParent = newParentChain.original
ri.newName = realOp.NewName
ccs.renamedOriginals[renamedOriginal] = ri
// Remember what you create, in case we need to merge
// directories after a rename.
co.AddRefBlock(renamedOriginal)
}
case *syncOp:
err := ccs.addOp(realOp.File.Ref, op)
if err != nil {
return err
}
case *setAttrOp:
// Because the attributes apply to the file, which doesn't
// actually have an updated pointer, we may need to create a
// new chain.
_, ok := ccs.byMostRecent[realOp.File]
if !ok {
// pointer didn't change, so most recent is the same:
chain := &crChain{
original: realOp.File,
mostRecent: realOp.File,
obfuscator: ccs.makeObfuscator(),
tlfID: ccs.mostRecentChainMDInfo.TlfID(),
}
ccs.byOriginal[realOp.File] = chain
ccs.byMostRecent[realOp.File] = chain
}
err := ccs.addOp(realOp.File, op)
if err != nil {
return err
}
case *resolutionOp:
ccs.resOps = append(ccs.resOps, realOp)
case *rekeyOp:
// ignore rekey op
case *GCOp:
// ignore gc op
}
return nil
}
func (ccs *crChains) makeChainForNewOpWithUpdate(
targetPtr data.BlockPointer, newOp op, update *blockUpdate) error {
oldUpdate := *update
// so that most recent == original
var err error
*update, err = makeBlockUpdate(targetPtr, update.Unref)
if err != nil {
return err
}
defer func() {
// reset the update to its original state before returning.
*update = oldUpdate
}()
err = ccs.makeChainForOp(newOp)
if err != nil {
return err
}
return nil
}
// makeChainForNewOp makes a new chain for an op that does not yet
// have its pointers initialized. It does so by setting Unref and Ref
// to be the same for the duration of this function, and calling the
// usual makeChainForOp method. This function is not goroutine-safe
// with respect to newOp. Also note that rename ops will not be split
// into two ops; they will be placed only in the new directory chain.
func (ccs *crChains) makeChainForNewOp(targetPtr data.BlockPointer, newOp op) error {
switch realOp := newOp.(type) {
case *createOp:
return ccs.makeChainForNewOpWithUpdate(targetPtr, newOp, &realOp.Dir)
case *rmOp:
return ccs.makeChainForNewOpWithUpdate(targetPtr, newOp, &realOp.Dir)
case *renameOp:
// In this case, we don't want to split the rename chain, so
// just make up a new operation and later overwrite it with
// the rename op.
co, err := newCreateOp(realOp.NewName, realOp.NewDir.Unref, data.File)
if err != nil {
return err
}
err = ccs.makeChainForNewOpWithUpdate(targetPtr, co, &co.Dir)
if err != nil {
return err
}
chain, ok := ccs.byMostRecent[targetPtr]
if !ok {
return errors.Errorf("Couldn't find chain for %v after making it",
targetPtr)
}
if len(chain.ops) != 1 {
return errors.Errorf("Chain of unexpected length for %v after "+
"making it", targetPtr)
}
chain.ops[0] = realOp
return nil
case *setAttrOp:
return ccs.makeChainForNewOpWithUpdate(targetPtr, newOp, &realOp.Dir)
case *syncOp:
return ccs.makeChainForNewOpWithUpdate(targetPtr, newOp, &realOp.File)
default:
return errors.Errorf("Couldn't make chain with unknown operation %s",
newOp)
}
}
func (ccs *crChains) mostRecentFromOriginal(original data.BlockPointer) (
data.BlockPointer, error) {
chain, ok := ccs.byOriginal[original]
if !ok {
return data.BlockPointer{}, errors.WithStack(NoChainFoundError{original})
}
return chain.mostRecent, nil
}
func (ccs *crChains) mostRecentFromOriginalOrSame(original data.BlockPointer) (
data.BlockPointer, error) {
ptr, err := ccs.mostRecentFromOriginal(original)
if err == nil {
// A satisfactory chain was found.
return ptr, nil
} else if _, ok := errors.Cause(err).(NoChainFoundError); !ok {
// An unexpected error!
return data.BlockPointer{}, err
}
return original, nil
}
func (ccs *crChains) originalFromMostRecent(mostRecent data.BlockPointer) (
data.BlockPointer, error) {
chain, ok := ccs.byMostRecent[mostRecent]
if !ok {
return data.BlockPointer{}, errors.WithStack(NoChainFoundError{mostRecent})
}
return chain.original, nil
}
func (ccs *crChains) originalFromMostRecentOrSame(mostRecent data.BlockPointer) (
data.BlockPointer, error) {
ptr, err := ccs.originalFromMostRecent(mostRecent)
if err == nil {
// A satisfactory chain was found.
return ptr, nil
} else if _, ok := errors.Cause(err).(NoChainFoundError); !ok {
// An unexpected error!
return data.BlockPointer{}, err
}
return mostRecent, nil
}
func (ccs *crChains) isCreated(original data.BlockPointer) bool {
return ccs.createdOriginals[original]
}
func (ccs *crChains) isDeleted(original data.BlockPointer) bool {
return ccs.deletedOriginals[original]
}
func (ccs *crChains) renamedParentAndName(original data.BlockPointer) (
data.BlockPointer, string, bool) {
info, ok := ccs.renamedOriginals[original]
if !ok {
return data.BlockPointer{}, "", false
}
return info.originalNewParent, info.newName, true
}
func newCRChainsEmpty(makeObfuscator func() data.Obfuscator) *crChains {
return &crChains{
byOriginal: make(map[data.BlockPointer]*crChain),
byMostRecent: make(map[data.BlockPointer]*crChain),
deletedOriginals: make(map[data.BlockPointer]bool),
createdOriginals: make(map[data.BlockPointer]bool),
renamedOriginals: make(map[data.BlockPointer]renameInfo),
blockChangePointers: make(map[data.BlockPointer]bool),
toUnrefPointers: make(map[data.BlockPointer]bool),
doNotUnrefPointers: make(map[data.BlockPointer]bool),
originals: make(map[data.BlockPointer]data.BlockPointer),
makeObfuscator: makeObfuscator,
}
}
func (ccs *crChains) addOps(codec kbfscodec.Codec,
privateMD PrivateMetadata, winfo writerInfo,
localTimestamp time.Time) error {
// Copy the ops since CR will change them.
var oldOps opsList
if privateMD.Changes.Info.BlockPointer.IsInitialized() {
// In some cases (e.g., journaling) we might not have been
// able to re-embed the block changes. So use the cached
// version directly.
oldOps = privateMD.cachedChanges.Ops
} else {
oldOps = privateMD.Changes.Ops
}
ops := make(opsList, len(oldOps))
err := kbfscodec.Update(codec, &ops, oldOps)
if err != nil {
return err
}
for i, op := range ops {
op.setFinalPath(oldOps[i].getFinalPath())
op.setWriterInfo(winfo)
op.setLocalTimestamp(localTimestamp)
err := ccs.makeChainForOp(op)
if err != nil {
return err
}
}
return nil
}
// chainMetadata is the interface for metadata objects that can be
// used in building crChains. It is implemented by
// ImmutableRootMetadata, but is also mostly implemented by
// RootMetadata (just need LastModifyingWriterVerifyingKey
// LocalTimestamp).
type chainMetadata interface {
KeyMetadataWithRootDirEntry
IsWriterMetadataCopiedSet() bool
LastModifyingWriter() keybase1.UID
LastModifyingWriterVerifyingKey() kbfscrypto.VerifyingKey
Revision() kbfsmd.Revision
Data() *PrivateMetadata
LocalTimestamp() time.Time
}
// newCRChains builds a new crChains object from the given list of
// chainMetadatas, which must be non-empty.
func newCRChains(
ctx context.Context, codec kbfscodec.Codec, osg idutil.OfflineStatusGetter,
chainMDs []chainMetadata, fbo *folderBlockOps, identifyTypes bool) (
ccs *crChains, err error) {
if fbo != nil {
ccs = newCRChainsEmpty(fbo.obfuscatorMaker())
} else {
ccs = newCRChainsEmpty(func() data.Obfuscator { return nil })
}
mostRecentMD := chainMDs[len(chainMDs)-1]
ccs.mostRecentChainMDInfo = mostRecentMD
// For each MD update, turn each update in each op into map
// entries and create chains for the BlockPointers that are
// affected directly by the operation.
for _, chainMD := range chainMDs {
// No new operations in these.
if chainMD.IsWriterMetadataCopiedSet() {
continue
}
offline := keybase1.OfflineAvailability_NONE
if osg != nil {
offline = osg.OfflineAvailabilityForID(chainMD.TlfID())
}
winfo := newWriterInfo(
chainMD.LastModifyingWriter(),
chainMD.LastModifyingWriterVerifyingKey(),
chainMD.Revision(), offline)
if err != nil {
return nil, err
}
chainData := *chainMD.Data()
err = ccs.addOps(codec, chainData, winfo, chainMD.LocalTimestamp())
if ptr := chainData.cachedChanges.Info.BlockPointer; ptr != data.ZeroPtr {
ccs.blockChangePointers[ptr] = true
// Any child block change pointers?
infos, err := fbo.GetIndirectFileBlockInfos(
ctx, makeFBOLockState(), chainMD,
data.Path{
FolderBranch: fbo.folderBranch,
Path: []data.PathNode{{
BlockPointer: ptr,
Name: data.NewPathPartString(
fmt.Sprintf("<MD rev %d>", chainMD.Revision()),