/
history_replicator.go
737 lines (665 loc) · 19.6 KB
/
history_replicator.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
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package ndc
import (
ctx "context"
"time"
"github.com/pborman/uuid"
"github.com/uber/cadence/common"
"github.com/uber/cadence/common/cache"
"github.com/uber/cadence/common/cluster"
"github.com/uber/cadence/common/errors"
"github.com/uber/cadence/common/log"
"github.com/uber/cadence/common/log/tag"
"github.com/uber/cadence/common/metrics"
"github.com/uber/cadence/common/persistence"
"github.com/uber/cadence/common/types"
"github.com/uber/cadence/service/history/execution"
"github.com/uber/cadence/service/history/shard"
)
const (
mutableStateMissingMessage = "Resend events due to missing mutable state"
)
type (
// HistoryReplicator handles history replication task
HistoryReplicator interface {
ApplyEvents(
ctx ctx.Context,
request *types.ReplicateEventsV2Request,
) error
}
historyReplicatorImpl struct {
shard shard.Context
clusterMetadata cluster.Metadata
historyV2Manager persistence.HistoryManager
historySerializer persistence.PayloadSerializer
metricsClient metrics.Client
domainCache cache.DomainCache
executionCache *execution.Cache
eventsReapplier EventsReapplier
transactionManager transactionManager
logger log.Logger
newBranchManager branchManagerProvider
newConflictResolver conflictResolverProvider
newWorkflowResetter workflowResetterProvider
newStateBuilder stateBuilderProvider
newMutableState mutableStateProvider
}
stateBuilderProvider func(
mutableState execution.MutableState,
logger log.Logger) execution.StateBuilder
mutableStateProvider func(
domainEntry *cache.DomainCacheEntry,
logger log.Logger,
) execution.MutableState
branchManagerProvider func(
context execution.Context,
mutableState execution.MutableState,
logger log.Logger,
) branchManager
conflictResolverProvider func(
context execution.Context,
mutableState execution.MutableState,
logger log.Logger,
) conflictResolver
workflowResetterProvider func(
domainID string,
workflowID string,
baseRunID string,
newContext execution.Context,
newRunID string,
logger log.Logger,
) WorkflowResetter
)
var _ HistoryReplicator = (*historyReplicatorImpl)(nil)
var errPanic = errors.NewInternalFailureError("encounter panic")
// NewHistoryReplicator creates history replicator
func NewHistoryReplicator(
shard shard.Context,
executionCache *execution.Cache,
eventsReapplier EventsReapplier,
logger log.Logger,
) HistoryReplicator {
transactionManager := newTransactionManager(shard, executionCache, eventsReapplier, logger)
replicator := &historyReplicatorImpl{
shard: shard,
clusterMetadata: shard.GetService().GetClusterMetadata(),
historyV2Manager: shard.GetHistoryManager(),
historySerializer: persistence.NewPayloadSerializer(),
metricsClient: shard.GetMetricsClient(),
domainCache: shard.GetDomainCache(),
executionCache: executionCache,
transactionManager: transactionManager,
eventsReapplier: eventsReapplier,
logger: logger.WithTags(tag.ComponentHistoryReplicator),
newBranchManager: func(
context execution.Context,
mutableState execution.MutableState,
logger log.Logger,
) branchManager {
return newBranchManager(shard, context, mutableState, logger)
},
newConflictResolver: func(
context execution.Context,
mutableState execution.MutableState,
logger log.Logger,
) conflictResolver {
return newConflictResolver(shard, context, mutableState, logger)
},
newWorkflowResetter: func(
domainID string,
workflowID string,
baseRunID string,
newContext execution.Context,
newRunID string,
logger log.Logger,
) WorkflowResetter {
return NewWorkflowResetter(shard, transactionManager, domainID, workflowID, baseRunID, newContext, newRunID, logger)
},
newStateBuilder: func(
state execution.MutableState,
logger log.Logger,
) execution.StateBuilder {
return execution.NewStateBuilder(
shard,
logger,
state,
func(mutableState execution.MutableState) execution.MutableStateTaskGenerator {
return execution.NewMutableStateTaskGenerator(shard.GetClusterMetadata(), shard.GetDomainCache(), logger, mutableState)
},
)
},
newMutableState: func(
domainEntry *cache.DomainCacheEntry,
logger log.Logger,
) execution.MutableState {
return execution.NewMutableStateBuilderWithVersionHistories(
shard,
logger,
domainEntry,
)
},
}
return replicator
}
func (r *historyReplicatorImpl) ApplyEvents(
ctx ctx.Context,
request *types.ReplicateEventsV2Request,
) (retError error) {
startTime := time.Now()
task, err := newReplicationTask(
r.clusterMetadata,
r.historySerializer,
startTime,
r.logger,
request,
)
if err != nil {
return err
}
return r.applyEvents(ctx, task)
}
func (r *historyReplicatorImpl) applyEvents(
ctx ctx.Context,
task replicationTask,
) (retError error) {
context, releaseFn, err := r.executionCache.GetOrCreateWorkflowExecution(
ctx,
task.getDomainID(),
*task.getExecution(),
)
if err != nil {
// for get workflow execution context, with valid run id
// err will not be of type EntityNotExistsError
return err
}
defer func() {
if rec := recover(); rec != nil {
releaseFn(errPanic)
panic(rec)
} else {
releaseFn(retError)
}
}()
switch task.getFirstEvent().GetEventType() {
case types.EventTypeWorkflowExecutionStarted:
return r.applyStartEvents(ctx, context, releaseFn, task)
default:
// apply events, other than simple start workflow execution
// the continue as new + start workflow execution combination will also be processed here
var mutableState execution.MutableState
var err error
domainName, err := r.domainCache.GetDomainName(context.GetDomainID())
if err != nil {
return err
}
if r.shard.GetConfig().ReplicationEventsFromCurrentCluster(domainName) {
// this branch is used when replicating events (generated from current cluster)from remote cluster to current cluster.
// this could happen when the events are lost in current cluster and plan to recover them from remote cluster.
mutableState, err = context.LoadWorkflowExecutionForReplication(ctx, task.getVersion())
} else {
mutableState, err = context.LoadWorkflowExecution(ctx)
}
switch err.(type) {
case nil:
// Sanity check to make only 3DC mutable state here
if mutableState.GetVersionHistories() == nil {
return execution.ErrMissingVersionHistories
}
doContinue, branchIndex, err := r.applyNonStartEventsPrepareBranch(ctx, context, mutableState, task)
if err != nil {
return err
} else if !doContinue {
r.metricsClient.IncCounter(metrics.ReplicateHistoryEventsScope, metrics.DuplicateReplicationEventsCounter)
return nil
}
mutableState, isRebuilt, err := r.applyNonStartEventsPrepareMutableState(ctx, context, mutableState, branchIndex, task)
if err != nil {
return err
}
if mutableState.GetVersionHistories().GetCurrentVersionHistoryIndex() == branchIndex {
return r.applyNonStartEventsToCurrentBranch(ctx, context, mutableState, isRebuilt, releaseFn, task)
}
return r.applyNonStartEventsToNoneCurrentBranch(ctx, context, mutableState, branchIndex, releaseFn, task)
case *types.EntityNotExistsError:
// mutable state not created, check if is workflow reset
mutableState, err := r.applyNonStartEventsMissingMutableState(ctx, context, task)
if err != nil {
return err
}
return r.applyNonStartEventsResetWorkflow(ctx, context, mutableState, task)
default:
// unable to get mutable state, return err so we can retry the task later
return err
}
}
}
func (r *historyReplicatorImpl) applyStartEvents(
ctx ctx.Context,
context execution.Context,
releaseFn execution.ReleaseFunc,
task replicationTask,
) (retError error) {
domainEntry, err := r.domainCache.GetDomainByID(task.getDomainID())
if err != nil {
return err
}
requestID := uuid.New() // requestID used for start workflow execution request. This is not on the history event.
mutableState := r.newMutableState(domainEntry, task.getLogger())
stateBuilder := r.newStateBuilder(mutableState, task.getLogger())
// use state builder for workflow mutable state mutation
_, err = stateBuilder.ApplyEvents(
task.getDomainID(),
requestID,
*task.getExecution(),
task.getEvents(),
task.getNewEvents(),
)
if err != nil {
task.getLogger().Error(
"nDCHistoryReplicator unable to apply events when applyStartEvents",
tag.Error(err),
)
return err
}
err = r.transactionManager.createWorkflow(
ctx,
task.getEventTime(),
execution.NewWorkflow(
ctx,
r.domainCache,
r.clusterMetadata,
context,
mutableState,
releaseFn,
),
)
if err != nil {
task.getLogger().Error(
"nDCHistoryReplicator unable to create workflow when applyStartEvents",
tag.Error(err),
)
} else {
r.notify(task.getSourceCluster(), task.getEventTime())
}
return err
}
func (r *historyReplicatorImpl) applyNonStartEventsPrepareBranch(
ctx ctx.Context,
context execution.Context,
mutableState execution.MutableState,
task replicationTask,
) (bool, int, error) {
incomingVersionHistory := task.getVersionHistory()
branchManager := r.newBranchManager(context, mutableState, task.getLogger())
doContinue, versionHistoryIndex, err := branchManager.prepareVersionHistory(
ctx,
incomingVersionHistory,
task.getFirstEvent().GetEventID(),
task.getFirstEvent().GetVersion(),
)
switch err.(type) {
case nil:
return doContinue, versionHistoryIndex, nil
case *types.RetryTaskV2Error:
// replication message can arrive out of order
// do not log
return false, 0, err
default:
task.getLogger().Error(
"nDCHistoryReplicator unable to prepare version history when applyNonStartEventsPrepareBranch",
tag.Error(err),
)
return false, 0, err
}
}
func (r *historyReplicatorImpl) applyNonStartEventsPrepareMutableState(
ctx ctx.Context,
context execution.Context,
mutableState execution.MutableState,
branchIndex int,
task replicationTask,
) (execution.MutableState, bool, error) {
incomingVersion := task.getVersion()
conflictResolver := r.newConflictResolver(context, mutableState, task.getLogger())
mutableState, isRebuilt, err := conflictResolver.prepareMutableState(
ctx,
branchIndex,
incomingVersion,
)
if err != nil {
task.getLogger().Error(
"nDCHistoryReplicator unable to prepare mutable state when applyNonStartEventsPrepareMutableState",
tag.Error(err),
)
}
return mutableState, isRebuilt, err
}
func (r *historyReplicatorImpl) applyNonStartEventsToCurrentBranch(
ctx ctx.Context,
context execution.Context,
mutableState execution.MutableState,
isRebuilt bool,
releaseFn execution.ReleaseFunc,
task replicationTask,
) error {
requestID := uuid.New() // requestID used for start workflow execution request. This is not on the history event.
stateBuilder := r.newStateBuilder(mutableState, task.getLogger())
newMutableState, err := stateBuilder.ApplyEvents(
task.getDomainID(),
requestID,
*task.getExecution(),
task.getEvents(),
task.getNewEvents(),
)
if err != nil {
task.getLogger().Error(
"nDCHistoryReplicator unable to apply events when applyNonStartEventsToCurrentBranch",
tag.Error(err),
)
return err
}
targetWorkflow := execution.NewWorkflow(
ctx,
r.domainCache,
r.clusterMetadata,
context,
mutableState,
releaseFn,
)
var newWorkflow execution.Workflow
if newMutableState != nil {
newExecutionInfo := newMutableState.GetExecutionInfo()
newContext := execution.NewContext(
newExecutionInfo.DomainID,
types.WorkflowExecution{
WorkflowID: newExecutionInfo.WorkflowID,
RunID: newExecutionInfo.RunID,
},
r.shard,
r.shard.GetExecutionManager(),
r.logger,
)
newWorkflow = execution.NewWorkflow(
ctx,
r.domainCache,
r.clusterMetadata,
newContext,
newMutableState,
execution.NoopReleaseFn,
)
}
err = r.transactionManager.updateWorkflow(
ctx,
task.getEventTime(),
isRebuilt,
targetWorkflow,
newWorkflow,
)
if err != nil {
task.getLogger().Error(
"nDCHistoryReplicator unable to update workflow when applyNonStartEventsToCurrentBranch",
tag.Error(err),
)
} else {
r.notify(task.getSourceCluster(), task.getEventTime())
}
return err
}
func (r *historyReplicatorImpl) applyNonStartEventsToNoneCurrentBranch(
ctx ctx.Context,
context execution.Context,
mutableState execution.MutableState,
branchIndex int,
releaseFn execution.ReleaseFunc,
task replicationTask,
) error {
if len(task.getNewEvents()) != 0 {
return r.applyNonStartEventsToNoneCurrentBranchWithContinueAsNew(
ctx,
context,
releaseFn,
task,
)
}
return r.applyNonStartEventsToNoneCurrentBranchWithoutContinueAsNew(
ctx,
context,
mutableState,
branchIndex,
releaseFn,
task,
)
}
func (r *historyReplicatorImpl) applyNonStartEventsToNoneCurrentBranchWithoutContinueAsNew(
ctx ctx.Context,
context execution.Context,
mutableState execution.MutableState,
branchIndex int,
releaseFn execution.ReleaseFunc,
task replicationTask,
) error {
versionHistoryItem := persistence.NewVersionHistoryItem(
task.getLastEvent().GetEventID(),
task.getLastEvent().GetVersion(),
)
versionHistories := mutableState.GetVersionHistories()
if versionHistories == nil {
return execution.ErrMissingVersionHistories
}
versionHistory, err := versionHistories.GetVersionHistory(branchIndex)
if err != nil {
return err
}
if err = versionHistory.AddOrUpdateItem(versionHistoryItem); err != nil {
return err
}
err = r.transactionManager.backfillWorkflow(
ctx,
task.getEventTime(),
execution.NewWorkflow(
ctx,
r.domainCache,
r.clusterMetadata,
context,
mutableState,
releaseFn,
),
&persistence.WorkflowEvents{
DomainID: task.getDomainID(),
WorkflowID: task.getExecution().GetWorkflowID(),
RunID: task.getExecution().GetRunID(),
BranchToken: versionHistory.GetBranchToken(),
Events: task.getEvents(),
},
)
if err != nil {
task.getLogger().Error(
"nDCHistoryReplicator unable to backfill workflow when applyNonStartEventsToNoneCurrentBranch",
tag.Error(err),
)
return err
}
return nil
}
func (r *historyReplicatorImpl) applyNonStartEventsToNoneCurrentBranchWithContinueAsNew(
ctx ctx.Context,
context execution.Context,
releaseFn execution.ReleaseFunc,
task replicationTask,
) error {
// workflow backfill to non current branch with continue as new
// first, release target workflow lock & create the new workflow as zombie
// NOTE: need to release target workflow due to target workflow
// can potentially be the current workflow causing deadlock
// 1. clear all in memory changes & release target workflow lock
// 2. apply new workflow first
// 3. apply target workflow
// step 1
context.Clear()
releaseFn(nil)
// step 2
startTime := time.Now()
task, newTask, err := task.splitTask(startTime)
if err != nil {
return err
}
if err := r.applyEvents(ctx, newTask); err != nil {
newTask.getLogger().Error(
"nDCHistoryReplicator unable to create new workflow when applyNonStartEventsToNoneCurrentBranchWithContinueAsNew",
tag.Error(err),
)
return err
}
// step 3
if err := r.applyEvents(ctx, task); err != nil {
newTask.getLogger().Error(
"nDCHistoryReplicator unable to create target workflow when applyNonStartEventsToNoneCurrentBranchWithContinueAsNew",
tag.Error(err),
)
return err
}
return nil
}
func (r *historyReplicatorImpl) applyNonStartEventsMissingMutableState(
ctx ctx.Context,
newContext execution.Context,
task replicationTask,
) (execution.MutableState, error) {
// for non reset workflow execution replication task, just do re-replication
if !task.isWorkflowReset() {
firstEvent := task.getFirstEvent()
return nil, newNDCRetryTaskErrorWithHint(
mutableStateMissingMessage,
task.getDomainID(),
task.getWorkflowID(),
task.getRunID(),
nil,
nil,
common.Int64Ptr(firstEvent.GetEventID()),
common.Int64Ptr(firstEvent.GetVersion()),
)
}
decisionTaskEvent := task.getFirstEvent()
baseEventID := decisionTaskEvent.GetEventID() - 1
baseRunID, newRunID, baseEventVersion := task.getWorkflowResetMetadata()
workflowResetter := r.newWorkflowResetter(
task.getDomainID(),
task.getWorkflowID(),
baseRunID,
newContext,
newRunID,
task.getLogger(),
)
resetMutableState, err := workflowResetter.ResetWorkflow(
ctx,
task.getEventTime(),
baseEventID,
baseEventVersion,
task.getFirstEvent().GetEventID(),
task.getVersion(),
)
if err != nil {
task.getLogger().Error(
"nDCHistoryReplicator unable to reset workflow when applyNonStartEventsMissingMutableState",
tag.Error(err),
)
return nil, err
}
return resetMutableState, nil
}
func (r *historyReplicatorImpl) applyNonStartEventsResetWorkflow(
ctx ctx.Context,
context execution.Context,
mutableState execution.MutableState,
task replicationTask,
) error {
requestID := uuid.New() // requestID used for start workflow execution request. This is not on the history event.
stateBuilder := r.newStateBuilder(mutableState, task.getLogger())
_, err := stateBuilder.ApplyEvents(
task.getDomainID(),
requestID,
*task.getExecution(),
task.getEvents(),
task.getNewEvents(),
)
if err != nil {
task.getLogger().Error(
"nDCHistoryReplicator unable to apply events when applyNonStartEventsResetWorkflow",
tag.Error(err),
)
return err
}
targetWorkflow := execution.NewWorkflow(
ctx,
r.domainCache,
r.clusterMetadata,
context,
mutableState,
execution.NoopReleaseFn,
)
err = r.transactionManager.createWorkflow(
ctx,
task.getEventTime(),
targetWorkflow,
)
if err != nil {
task.getLogger().Error(
"nDCHistoryReplicator unable to create workflow when applyNonStartEventsResetWorkflow",
tag.Error(err),
)
} else {
r.notify(task.getSourceCluster(), task.getEventTime())
}
return err
}
func (r *historyReplicatorImpl) notify(
clusterName string,
now time.Time,
) {
if clusterName == r.clusterMetadata.GetCurrentClusterName() {
// this is a valid use case for testing, but not for production
r.logger.Warn("nDCHistoryReplicator applying events generated by current cluster")
return
}
now = now.Add(-r.shard.GetConfig().StandbyClusterDelay())
r.shard.SetCurrentTime(clusterName, now)
}
func newNDCRetryTaskErrorWithHint(
message string,
domainID string,
workflowID string,
runID string,
startEventID *int64,
startEventVersion *int64,
endEventID *int64,
endEventVersion *int64,
) error {
return &types.RetryTaskV2Error{
Message: message,
DomainID: domainID,
WorkflowID: workflowID,
RunID: runID,
StartEventID: startEventID,
StartEventVersion: startEventVersion,
EndEventID: endEventID,
EndEventVersion: endEventVersion,
}
}