forked from pydio/cells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree-diff.go
478 lines (429 loc) · 14.2 KB
/
tree-diff.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
/*
* Copyright (c) 2019. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
package merger
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/gobwas/glob"
"go.uber.org/zap"
"github.com/pydio/cells/common/log"
"github.com/pydio/cells/common/proto/tree"
"github.com/pydio/cells/common/sync/model"
)
// Conflict represent a conflict between two nodes at the same path
type DiffConflict struct {
Type ConflictType
NodeLeft *tree.Node
NodeRight *tree.Node
}
// Diff represent basic differences between two sources
// It can be then transformed to Patch, depending on the sync being
// unidirectional (transform to Creates and Deletes) or bidirectional (transform only to Creates)
type TreeDiff struct {
left model.PathSyncSource
right model.PathSyncSource
missingLeft []*tree.Node
missingRight []*tree.Node
conflicts []*DiffConflict
ctx context.Context
cmd *model.Command
statusChan chan model.Status
doneChan chan interface{}
includeMetas []glob.Glob
}
// NewTreeDiff is a public access for instantiating a new TreeDiff
func NewTreeDiff(ctx context.Context, left model.PathSyncSource, right model.PathSyncSource) *TreeDiff {
return newTreeDiff(ctx, left, right)
}
// newTreeDiff instantiates a new TreeDiff - If left is a MetadataProvider and right a MetadataReceiver,
// it will setup metadata diff management
func newTreeDiff(ctx context.Context, left model.PathSyncSource, right model.PathSyncSource) *TreeDiff {
t := &TreeDiff{
ctx: ctx,
left: left,
right: right,
}
mp, leftOk := left.(model.MetadataProvider)
_, rightOk := right.(model.MetadataReceiver)
if leftOk && rightOk {
if globs, o := mp.ProvidesMetadataNamespaces(); o {
t.includeMetas = globs
}
}
return t
}
// Compute performs the actual diff between left and right
func (diff *TreeDiff) Compute(root string, lock chan bool, ignores ...glob.Glob) error {
defer func() {
diff.Done(true)
// Wait that monitor has finished its messaging before returning function
if lock != nil {
<-lock
}
}()
lTree := NewTree()
rTree := NewTree()
var errs []error
wg := &sync.WaitGroup{}
for _, k := range []string{"left", "right"} {
wg.Add(1)
go func(logId string) {
start := time.Now()
h := ""
uri := diff.left.GetEndpointInfo().URI
if k == "right" {
uri = diff.right.GetEndpointInfo().URI
}
defer func() {
s := model.NewProcessingStatus(fmt.Sprintf("[%s] Snapshot loaded in %v - Root Hash is %s", logId, time.Now().Sub(start), h)).SetEndpoint(uri)
diff.Status(s)
wg.Done()
}()
st := model.NewProcessingStatus(fmt.Sprintf("[%s] Loading snapshot", logId)).SetEndpoint(uri)
diff.Status(st)
var err error
if logId == "left" {
if lTree, err = TreeNodeFromSource(diff.left, root, ignores, diff.includeMetas, diff.statusChan); err == nil {
h = lTree.GetHash()
}
} else if logId == "right" {
if rTree, err = TreeNodeFromSource(diff.right, root, ignores, diff.includeMetas, diff.statusChan); err == nil {
h = rTree.GetHash()
}
}
if err != nil {
errs = append(errs, err)
}
}(k)
}
wg.Wait()
if len(errs) > 0 {
return errs[0]
}
diff.Status(model.NewProcessingStatus("Computing diff between snapshots"))
// fmt.Println(lTree.PrintTree())
// fmt.Println(rTree.PrintTree())
diff.mergeNodes(lTree, rTree)
log.Logger(diff.ctx).Info("Diff Stats", zap.Any("s", diff.Stats()))
diff.Status(model.NewProcessingStatus(fmt.Sprintf("Diff contents: missing left %v - missing right %v", len(diff.missingLeft), len(diff.missingRight))))
return nil
}
// ToUnidirectionalPatch transforms this diff to a patch
func (diff *TreeDiff) ToUnidirectionalPatch(direction model.DirectionType, patch Patch) (err error) {
_, rightOk := diff.right.(model.PathSyncTarget)
_, leftOk := diff.left.(model.PathSyncTarget)
if direction == model.DirectionRight && rightOk {
diff.toMissing(patch, diff.missingRight, true, false)
diff.toMissing(patch, diff.missingRight, false, false)
diff.toMissing(patch, diff.missingLeft, false, true)
diff.toMissingMeta(patch, diff.missingRight, false)
diff.toMissingMeta(patch, diff.missingLeft, true)
} else if direction == model.DirectionLeft && leftOk {
diff.toMissing(patch, diff.missingLeft, true, false)
diff.toMissing(patch, diff.missingLeft, false, false)
diff.toMissing(patch, diff.missingRight, false, true)
diff.toMissingMeta(patch, diff.missingLeft, false)
diff.toMissingMeta(patch, diff.missingRight, true)
} else {
return errors.New("error while extracting unidirectional patch. either left or right is not a sync target")
}
// Enqueue ConflictFileContent as DataOperation of type OpUpdateFile
for _, c := range diff.conflictsByType(ConflictFileContent) {
var n *tree.Node
if direction == model.DirectionRight {
n = c.NodeLeft
} else if direction == model.DirectionLeft {
n = c.NodeRight
} else {
n = MostRecentNode(c.NodeLeft, c.NodeRight)
}
patch.Enqueue(NewOperation(OpUpdateFile, model.NodeToEventInfo(diff.ctx, n.Path, n, model.EventCreate), n))
}
// Enqueue ConflictMetaChanged as DataOperation of type OpUpdateMeta
for _, c := range diff.conflictsByType(ConflictMetaChanged) {
var n *tree.Node
if direction == model.DirectionRight {
n = c.NodeLeft
} else {
n = c.NodeRight
}
patch.Enqueue(NewOperation(OpUpdateMeta, model.NodeToEventInfo(diff.ctx, n.Path, n, model.EventCreate), n))
}
log.Logger(diff.ctx).Info("Sending unidirectional patch", zap.Any("patch", patch.Stats()))
return
}
// ToBidirectionalPatch computes a bidirectional patch from this diff using the given targets
func (diff *TreeDiff) ToBidirectionalPatch(leftTarget model.PathSyncTarget, rightTarget model.PathSyncTarget, patch *BidirectionalPatch) (err error) {
var b *BidirectionalPatch
defer func() {
if b != nil {
patch.AppendBranch(diff.ctx, b)
}
}()
diff.solveConflicts(diff.ctx)
leftPatch, rightPatch := diff.leftAndRightPatches(leftTarget, rightTarget)
b, err = ComputeBidirectionalPatch(diff.ctx, leftPatch, rightPatch)
if err != nil {
return
}
// Re-enqueue Diff conflicts to Patch conflicts
for _, c := range diff.conflicts {
var leftOp, rightOp Operation
if c.NodeLeft.IsLeaf() {
leftOp = NewOperation(OpCreateFile, model.EventInfo{Path: c.NodeLeft.Path}, c.NodeLeft)
} else {
leftOp = NewOperation(OpCreateFolder, model.EventInfo{Path: c.NodeLeft.Path}, c.NodeLeft)
}
if c.NodeRight.IsLeaf() {
rightOp = NewOperation(OpCreateFile, model.EventInfo{Path: c.NodeRight.Path}, c.NodeRight)
} else {
rightOp = NewOperation(OpCreateFolder, model.EventInfo{Path: c.NodeRight.Path}, c.NodeRight)
}
b.Enqueue(NewConflictOperation(c.NodeLeft, c.Type, leftOp, rightOp))
}
if errs, ok := b.HasErrors(); ok {
err = fmt.Errorf("diff has conflicts %v", errs)
}
return
}
// leftAndRightPatches provides two patches from this diff, to be used as input for a BidirPatch computation
func (diff *TreeDiff) leftAndRightPatches(leftTarget model.PathSyncTarget, rightTarget model.PathSyncTarget) (leftPatch Patch, rightPatch Patch) {
leftPatch = NewPatch(leftTarget.(model.PathSyncSource), rightTarget, PatchOptions{MoveDetection: true})
if rightTarget != nil {
diff.toMissing(leftPatch, diff.missingRight, true, false)
diff.toMissing(leftPatch, diff.missingRight, false, false)
}
rightPatch = NewPatch(rightTarget.(model.PathSyncSource), leftTarget, PatchOptions{MoveDetection: true})
if leftTarget != nil {
diff.toMissing(rightPatch, diff.missingLeft, true, false)
diff.toMissing(rightPatch, diff.missingLeft, false, false)
}
return
}
// Status sends status to internal channel
func (diff *TreeDiff) Status(status model.Status) {
if diff.statusChan != nil {
diff.statusChan <- status
}
}
// SetupChannels registers status chan internally. Done chan is ignored
func (diff *TreeDiff) SetupChannels(status chan model.Status, done chan interface{}, cmd *model.Command) {
diff.statusChan = status
diff.doneChan = done
diff.cmd = cmd
}
func (diff *TreeDiff) Done(info interface{}) {
if diff.doneChan != nil {
diff.doneChan <- info
}
}
// String provides a string representation of this diff
func (diff *TreeDiff) String() string {
output := ""
if len(diff.missingLeft) > 0 {
output += "\n missingLeft : "
for _, node := range diff.missingLeft {
output += "\n " + node.Path
}
}
if len(diff.missingRight) > 0 {
output += "\n missingRight : "
for _, node := range diff.missingRight {
output += "\n " + node.Path
}
}
if len(diff.conflicts) > 0 {
output += "\n Diverging conflicts : "
for _, c := range diff.conflicts {
output += "\n " + c.NodeLeft.Path
}
}
return output
}
// Stats provides info about the diff internals
func (diff *TreeDiff) Stats() map[string]interface{} {
return map[string]interface{}{
"EndpointLeft": diff.left.GetEndpointInfo().URI,
"EndpointRight": diff.right.GetEndpointInfo().URI,
"missingLeft": len(diff.missingLeft),
"missingRight": len(diff.missingRight),
"conflicts": len(diff.conflicts),
}
}
// mergeNodes will recursively detect differences between two hash trees.
func (diff *TreeDiff) mergeNodes(left *TreeNode, right *TreeNode) {
if left.GetHash() == right.GetHash() {
return
}
if left.Type != right.Type {
// Node changed of type - Register conflict and keep browsing
diff.conflicts = append(diff.conflicts, &DiffConflict{
Type: ConflictNodeType,
NodeLeft: &left.Node,
NodeRight: &right.Node,
})
} else if !left.IsLeaf() && left.Uuid != right.Uuid {
// Folder has different UUID - Register conflict and keep browsing
diff.conflicts = append(diff.conflicts, &DiffConflict{
Type: ConflictFolderUUID,
NodeLeft: &left.Node,
NodeRight: &right.Node,
})
} else if left.IsLeaf() && left.Etag != right.Etag {
// Re-check that Etag differ - maybe the hash is composed of both eTag and metadata, and differ but NOT the Etag
// Files content differ - Register conflict
diff.conflicts = append(diff.conflicts, &DiffConflict{
Type: ConflictFileContent,
NodeLeft: &left.Node,
NodeRight: &right.Node,
})
// return // do not return here, there might be children (metadata pieces)
} else if left.Type == NodeType_METADATA {
// Meta differ - Register conflict and return (no children after that)
diff.conflicts = append(diff.conflicts, &DiffConflict{
Type: ConflictMetaChanged,
NodeLeft: &left.Node,
NodeRight: &right.Node,
})
return
}
cL := left.GetCursor()
cR := right.GetCursor()
a := cL.Next()
b := cR.Next()
for a != nil || b != nil {
if a != nil && b != nil {
switch strings.Compare(a.Label(), b.Label()) {
case 0:
diff.mergeNodes(a, b)
a = cL.Next()
b = cR.Next()
continue
case 1:
diff.missingLeft = b.Enqueue(diff.missingLeft)
b = cR.Next()
continue
case -1:
diff.missingRight = a.Enqueue(diff.missingRight)
a = cL.Next()
continue
}
} else if a == nil && b != nil {
diff.missingLeft = b.Enqueue(diff.missingLeft)
b = cR.Next()
continue
} else if b == nil && a != nil {
diff.missingRight = a.Enqueue(diff.missingRight)
a = cL.Next()
continue
}
}
}
// toMissing transforms Missing slices to BatchEvents
func (diff *TreeDiff) toMissing(patch Patch, in []*tree.Node, folders bool, removes bool) {
var eventType model.EventType
var batchEventType OperationType
if removes {
eventType = model.EventRemove
batchEventType = OpDelete
} else {
eventType = model.EventCreate
if folders {
batchEventType = OpCreateFolder
} else {
batchEventType = OpCreateFile
}
}
for _, n := range in {
if n.Type == NodeType_METADATA {
continue
}
if removes || !folders && n.IsLeaf() || folders && !n.IsLeaf() {
eventInfo := model.NodeToEventInfo(diff.ctx, n.Path, n, eventType)
patch.Enqueue(NewOperation(batchEventType, eventInfo, n))
}
}
}
// toMissingMeta is similar to toMissing but only handle Metadata nodes
func (diff *TreeDiff) toMissingMeta(patch Patch, in []*tree.Node, removes bool) {
var eventType model.EventType
var batchEventType OperationType
if removes {
eventType = model.EventRemove
batchEventType = OpDeleteMeta
} else {
eventType = model.EventCreate
batchEventType = OpCreateMeta
}
for _, n := range in {
if n.Type != NodeType_METADATA {
continue
}
patch.Enqueue(NewOperation(batchEventType, model.NodeToEventInfo(diff.ctx, n.Path, n, eventType), n))
}
}
// solveConflicts tries to fix existing conflicts and return remaining ones
func (diff *TreeDiff) solveConflicts(ctx context.Context) {
right := diff.right
left := diff.left
var remaining []*DiffConflict
// Try to refresh UUIDs on target
var refresher model.UuidFoldersRefresher
var canRefresh, refresherRight, refresherLeft bool
if refresher, canRefresh = right.(model.UuidFoldersRefresher); canRefresh {
refresherRight = true
} else if refresher, canRefresh = left.(model.UuidFoldersRefresher); canRefresh {
refresherLeft = true
}
for _, c := range diff.conflicts {
var solved bool
if c.Type == ConflictFolderUUID && canRefresh {
var srcUuid *tree.Node
if refresherRight {
srcUuid = c.NodeLeft
} else if refresherLeft {
srcUuid = c.NodeRight
}
if _, e := refresher.UpdateFolderUuid(ctx, srcUuid); e == nil {
solved = true
}
} else if c.Type == ConflictFileContent {
// What can we do?
}
if !solved {
remaining = append(remaining, c)
}
}
diff.conflicts = remaining
return
}
// conflictsByType filters a slice of conflicts for a given type
func (diff *TreeDiff) conflictsByType(conflictType ConflictType) (conflicts []*DiffConflict) {
for _, c := range diff.conflicts {
if c.Type == conflictType {
conflicts = append(conflicts, c)
}
}
return
}