-
Notifications
You must be signed in to change notification settings - Fork 787
/
resetter.go
686 lines (620 loc) · 17.3 KB
/
resetter.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
// Copyright (c) 2020 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.
//go:generate mockgen -package $GOPACKAGE -source $GOFILE -destination resetter_mock.go
package reset
import (
"context"
"github.com/uber/cadence/common"
"github.com/uber/cadence/common/cache"
"github.com/uber/cadence/common/cluster"
"github.com/uber/cadence/common/collection"
"github.com/uber/cadence/common/definition"
"github.com/uber/cadence/common/log"
"github.com/uber/cadence/common/persistence"
persistenceutils "github.com/uber/cadence/common/persistence/persistence-utils"
"github.com/uber/cadence/common/types"
"github.com/uber/cadence/service/history/execution"
"github.com/uber/cadence/service/history/shard"
)
type (
// WorkflowResetter is the new NDC compatible workflow reset component
WorkflowResetter interface {
ResetWorkflow(
ctx context.Context,
domainID string,
workflowID string,
baseRunID string,
baseBranchToken []byte,
baseRebuildLastEventID int64,
baseRebuildLastEventVersion int64,
baseNextEventID int64,
resetRunID string,
resetRequestID string,
currentWorkflow execution.Workflow,
resetReason string,
additionalReapplyEvents []*types.HistoryEvent,
skipSignalReapply bool,
) error
}
workflowResetterImpl struct {
shard shard.Context
domainCache cache.DomainCache
clusterMetadata cluster.Metadata
historyV2Mgr persistence.HistoryManager
executionCache execution.Cache
newStateRebuilder nDCStateRebuilderProvider
logger log.Logger
}
nDCStateRebuilderProvider func() execution.StateRebuilder
)
var _ WorkflowResetter = (*workflowResetterImpl)(nil)
// NewWorkflowResetter creates a workflow resetter
func NewWorkflowResetter(
shard shard.Context,
executionCache execution.Cache,
logger log.Logger,
) WorkflowResetter {
return &workflowResetterImpl{
shard: shard,
domainCache: shard.GetDomainCache(),
clusterMetadata: shard.GetClusterMetadata(),
historyV2Mgr: shard.GetHistoryManager(),
executionCache: executionCache,
newStateRebuilder: func() execution.StateRebuilder {
return execution.NewStateRebuilder(shard, logger)
},
logger: logger,
}
}
func (r *workflowResetterImpl) ResetWorkflow(
ctx context.Context,
domainID string,
workflowID string,
baseRunID string,
baseBranchToken []byte,
baseRebuildLastEventID int64,
baseRebuildLastEventVersion int64,
baseNextEventID int64,
resetRunID string,
resetRequestID string,
currentWorkflow execution.Workflow,
resetReason string,
additionalReapplyEvents []*types.HistoryEvent,
skipSignalReapply bool,
) (retError error) {
domainEntry, err := r.domainCache.GetDomainByID(domainID)
if err != nil {
return err
}
resetWorkflowVersion := domainEntry.GetFailoverVersion()
currentMutableState := currentWorkflow.GetMutableState()
currentWorkflowTerminated := false
if currentMutableState.IsWorkflowExecutionRunning() {
if err := r.terminateWorkflow(
currentMutableState,
resetReason,
); err != nil {
return err
}
resetWorkflowVersion = currentMutableState.GetCurrentVersion()
currentWorkflowTerminated = true
}
resetWorkflow, err := r.prepareResetWorkflow(
ctx,
domainID,
workflowID,
baseRunID,
baseBranchToken,
baseRebuildLastEventID,
baseRebuildLastEventVersion,
baseNextEventID,
resetRunID,
resetRequestID,
resetWorkflowVersion,
resetReason,
additionalReapplyEvents,
skipSignalReapply,
)
if err != nil {
return err
}
defer resetWorkflow.GetReleaseFn()(retError)
return r.persistToDB(
ctx,
currentWorkflowTerminated,
currentWorkflow,
resetWorkflow,
)
}
func (r *workflowResetterImpl) prepareResetWorkflow(
ctx context.Context,
domainID string,
workflowID string,
baseRunID string,
baseBranchToken []byte,
baseRebuildLastEventID int64,
baseRebuildLastEventVersion int64,
baseNextEventID int64,
resetRunID string,
resetRequestID string,
resetWorkflowVersion int64,
resetReason string,
additionalReapplyEvents []*types.HistoryEvent,
skipSignalReapply bool,
) (execution.Workflow, error) {
resetWorkflow, err := r.replayResetWorkflow(
ctx,
domainID,
workflowID,
baseRunID,
baseBranchToken,
baseRebuildLastEventID,
baseRebuildLastEventVersion,
resetRunID,
resetRequestID,
)
if err != nil {
return nil, err
}
resetMutableState := resetWorkflow.GetMutableState()
baseLastEventVersion := resetMutableState.GetCurrentVersion()
if baseLastEventVersion > resetWorkflowVersion {
return nil, &types.InternalServiceError{
Message: "workflowResetter encounter version mismatch.",
}
}
if err := resetMutableState.UpdateCurrentVersion(
resetWorkflowVersion,
false,
); err != nil {
return nil, err
}
resetMutableState, err = r.closePendingDecisionTask(
resetMutableState,
baseRunID,
resetRunID,
baseLastEventVersion,
resetReason,
resetRequestID,
)
if err != nil {
return nil, err
}
if err := r.failInflightActivity(resetMutableState, resetReason); err != nil {
return nil, err
}
// TODO right now only signals are eligible for reapply, so we can directly skip the whole reapply process
// for the sake of performance. In the future, if there are other events that need to be reapplied, remove this check
// For example, we may want to re-apply activity/timer results for https://github.com/uber/cadence/issues/2934
if !skipSignalReapply {
if err := r.reapplyResetAndContinueAsNewWorkflowEvents(
ctx,
resetMutableState,
domainID,
workflowID,
baseRunID,
baseBranchToken,
baseRebuildLastEventID+1,
baseNextEventID,
); err != nil {
return nil, err
}
}
// NOTE: this is reapplying events that are passing into the API that we shouldn't skip
if err := r.reapplyEvents(resetMutableState, additionalReapplyEvents); err != nil {
return nil, err
}
if err := execution.ScheduleDecision(resetMutableState); err != nil {
return nil, err
}
return resetWorkflow, nil
}
func (r *workflowResetterImpl) persistToDB(
ctx context.Context,
currentWorkflowTerminated bool,
currentWorkflow execution.Workflow,
resetWorkflow execution.Workflow,
) error {
if currentWorkflowTerminated {
return currentWorkflow.GetContext().UpdateWorkflowExecutionWithNewAsActive(
ctx,
r.shard.GetTimeSource().Now(),
resetWorkflow.GetContext(),
resetWorkflow.GetMutableState(),
)
}
currentMutableState := currentWorkflow.GetMutableState()
currentRunID := currentMutableState.GetExecutionInfo().RunID
currentLastWriteVersion, err := currentMutableState.GetLastWriteVersion()
if err != nil {
return err
}
now := r.shard.GetTimeSource().Now()
resetWorkflowSnapshot, resetWorkflowEventsSeq, err := resetWorkflow.GetMutableState().CloseTransactionAsSnapshot(
now,
execution.TransactionPolicyActive,
)
if err != nil {
return err
}
if len(resetWorkflowEventsSeq) != 1 {
return &types.InternalServiceError{
Message: "there should be EXACTLY one batch of events for reset",
}
}
// reset workflow with decision task failed or timed out
resetWorkflowHistory, err := resetWorkflow.GetContext().PersistNonStartWorkflowBatchEvents(ctx, resetWorkflowEventsSeq[0])
if err != nil {
return err
}
return resetWorkflow.GetContext().CreateWorkflowExecution(
ctx,
resetWorkflowSnapshot,
resetWorkflowHistory,
persistence.CreateWorkflowModeContinueAsNew,
currentRunID,
currentLastWriteVersion,
persistence.CreateWorkflowRequestModeNew,
)
}
func (r *workflowResetterImpl) replayResetWorkflow(
ctx context.Context,
domainID string,
workflowID string,
baseRunID string,
baseBranchToken []byte,
baseRebuildLastEventID int64,
baseRebuildLastEventVersion int64,
resetRunID string,
resetRequestID string,
) (execution.Workflow, error) {
resetBranchToken, err := r.forkAndGenerateBranchToken(
ctx,
domainID,
workflowID,
baseBranchToken,
baseRebuildLastEventID+1,
resetRunID,
)
if err != nil {
return nil, err
}
resetContext := execution.NewContext(
domainID,
types.WorkflowExecution{
WorkflowID: workflowID,
RunID: resetRunID,
},
r.shard,
r.shard.GetExecutionManager(),
r.logger,
)
resetMutableState, resetHistorySize, err := r.newStateRebuilder().Rebuild(
ctx,
r.shard.GetTimeSource().Now(),
definition.NewWorkflowIdentifier(
domainID,
workflowID,
baseRunID,
),
baseBranchToken,
baseRebuildLastEventID,
baseRebuildLastEventVersion,
definition.NewWorkflowIdentifier(
domainID,
workflowID,
resetRunID,
),
resetBranchToken,
resetRequestID,
)
if err != nil {
return nil, err
}
resetContext.SetHistorySize(resetHistorySize)
return execution.NewWorkflow(
ctx,
r.clusterMetadata,
resetContext,
resetMutableState,
execution.NoopReleaseFn,
), nil
}
func (r *workflowResetterImpl) failInflightActivity(
mutableState execution.MutableState,
terminateReason string,
) error {
for _, ai := range mutableState.GetPendingActivityInfos() {
switch ai.StartedID {
case common.EmptyEventID:
// activity not started, noop
case common.TransientEventID:
// activity is started (with retry policy)
// should not encounter this case when rebuilding mutable state
return &types.InternalServiceError{
Message: "workflowResetter encounter transient activity",
}
default:
if _, err := mutableState.AddActivityTaskFailedEvent(
ai.ScheduleID,
ai.StartedID,
&types.RespondActivityTaskFailedRequest{
Reason: common.StringPtr(terminateReason),
Details: ai.Details,
Identity: ai.StartedIdentity,
},
); err != nil {
return err
}
}
}
return nil
}
func (r *workflowResetterImpl) forkAndGenerateBranchToken(
ctx context.Context,
domainID string,
workflowID string,
forkBranchToken []byte,
forkNodeID int64,
resetRunID string,
) ([]byte, error) {
// fork a new history branch
shardID := r.shard.GetShardID()
domainName, err := r.domainCache.GetDomainName(domainID)
if err != nil {
return nil, err
}
resp, err := r.historyV2Mgr.ForkHistoryBranch(ctx, &persistence.ForkHistoryBranchRequest{
ForkBranchToken: forkBranchToken,
ForkNodeID: forkNodeID,
Info: persistence.BuildHistoryGarbageCleanupInfo(domainID, workflowID, resetRunID),
ShardID: common.IntPtr(shardID),
DomainName: domainName,
})
if err != nil {
return nil, err
}
return resp.NewBranchToken, nil
}
func (r *workflowResetterImpl) terminateWorkflow(
mutableState execution.MutableState,
terminateReason string,
) error {
eventBatchFirstEventID := mutableState.GetNextEventID()
return execution.TerminateWorkflow(
mutableState,
eventBatchFirstEventID,
terminateReason,
nil,
execution.IdentityHistoryService,
)
}
func (r *workflowResetterImpl) reapplyResetAndContinueAsNewWorkflowEvents(
ctx context.Context,
resetMutableState execution.MutableState,
domainID string,
workflowID string,
baseRunID string,
baseBranchToken []byte,
baseRebuildNextEventID int64,
baseNextEventID int64,
) error {
// TODO change this logic to fetching all workflow [baseWorkflow, currentWorkflow]
// from visibility for better coverage of events eligible for re-application.
var nextRunID string
var err error
// first special handling the remaining events for base workflow
if nextRunID, err = r.reapplyWorkflowEvents(
ctx,
resetMutableState,
baseRebuildNextEventID,
baseNextEventID,
baseBranchToken,
); err != nil {
return err
}
getNextEventIDBranchToken := func(runID string) (nextEventID int64, branchToken []byte, retError error) {
context, release, err := r.executionCache.GetOrCreateWorkflowExecution(
ctx,
domainID,
types.WorkflowExecution{
WorkflowID: workflowID,
RunID: runID,
},
)
if err != nil {
return 0, nil, err
}
defer func() { release(retError) }()
mutableState, err := context.LoadWorkflowExecution(ctx)
if err != nil {
// no matter what error happen, we need to retry
return 0, nil, err
}
nextEventID = mutableState.GetNextEventID()
branchToken, err = mutableState.GetCurrentBranchToken()
if err != nil {
return 0, nil, err
}
return nextEventID, branchToken, nil
}
// second for remaining continue as new workflow, reapply eligible events
for len(nextRunID) != 0 {
nextWorkflowNextEventID, nextWorkflowBranchToken, err := getNextEventIDBranchToken(nextRunID)
if err != nil {
return err
}
if nextRunID, err = r.reapplyWorkflowEvents(
ctx,
resetMutableState,
common.FirstEventID,
nextWorkflowNextEventID,
nextWorkflowBranchToken,
); err != nil {
return err
}
}
return nil
}
func (r *workflowResetterImpl) reapplyWorkflowEvents(
ctx context.Context,
mutableState execution.MutableState,
firstEventID int64,
nextEventID int64,
branchToken []byte,
) (string, error) {
// TODO change this logic to fetching all workflow [baseWorkflow, currentWorkflow]
// from visibility for better coverage of events eligible for re-application.
// after the above change, this API do not have to return the continue as new run ID
if firstEventID == nextEventID {
// This means the workflow reset to a pending decision task
// and the decision task is the latest event in the workflow.
return "", nil
}
domainID := mutableState.GetExecutionInfo().DomainID
iter := collection.NewPagingIterator(r.getPaginationFn(
ctx,
firstEventID,
nextEventID,
branchToken,
domainID,
))
var nextRunID string
var lastEvents []*types.HistoryEvent
for iter.HasNext() {
batch, err := iter.Next()
if err != nil {
return "", err
}
lastEvents = batch.(*types.History).Events
if err := r.reapplyEvents(mutableState, lastEvents); err != nil {
return "", err
}
}
if len(lastEvents) > 0 {
lastEvent := lastEvents[len(lastEvents)-1]
if lastEvent.GetEventType() == types.EventTypeWorkflowExecutionContinuedAsNew {
nextRunID = lastEvent.GetWorkflowExecutionContinuedAsNewEventAttributes().GetNewExecutionRunID()
}
}
return nextRunID, nil
}
func (r *workflowResetterImpl) reapplyEvents(
mutableState execution.MutableState,
events []*types.HistoryEvent,
) error {
for _, event := range events {
switch event.GetEventType() {
case types.EventTypeWorkflowExecutionSignaled:
attr := event.GetWorkflowExecutionSignaledEventAttributes()
if _, err := mutableState.AddWorkflowExecutionSignaled(
attr.GetSignalName(),
attr.GetInput(),
attr.GetIdentity(),
"", // Do not set requestID for requests reapplied, because they have already been applied previously
); err != nil {
return err
}
default:
// events other than signal will be ignored
}
}
return nil
}
func (r *workflowResetterImpl) getPaginationFn(
ctx context.Context,
firstEventID int64,
nextEventID int64,
branchToken []byte,
domainID string,
) collection.PaginationFn {
return func(paginationToken []byte) ([]interface{}, []byte, error) {
_, historyBatches, token, _, err := persistenceutils.PaginateHistory(
ctx,
r.historyV2Mgr,
true,
branchToken,
firstEventID,
nextEventID,
paginationToken,
execution.NDCDefaultPageSize,
common.IntPtr(r.shard.GetShardID()),
domainID,
r.domainCache,
)
if err != nil {
return nil, nil, err
}
var paginateItems []interface{}
for _, history := range historyBatches {
paginateItems = append(paginateItems, history)
}
return paginateItems, token, nil
}
}
func (r *workflowResetterImpl) closePendingDecisionTask(
resetMutableState execution.MutableState,
baseRunID string,
resetRunID string,
baseLastEventVersion int64,
resetReason string,
resetRequestID string,
) (execution.MutableState, error) {
if len(resetMutableState.GetPendingChildExecutionInfos()) > 0 {
return nil, &types.BadRequestError{
Message: "Can not reset workflow with pending child workflows",
}
}
if decision, ok := resetMutableState.GetInFlightDecision(); ok {
// reset workflow has decision task start
_, err := resetMutableState.AddDecisionTaskFailedEvent(
decision.ScheduleID,
decision.StartedID,
types.DecisionTaskFailedCauseResetWorkflow,
nil,
execution.IdentityHistoryService,
resetReason,
"",
baseRunID,
resetRunID,
baseLastEventVersion,
resetRequestID,
)
if err != nil {
return nil, err
}
} else if decision, ok := resetMutableState.GetPendingDecision(); ok {
if ok {
// reset workflow has decision task schedule
_, err := resetMutableState.AddDecisionTaskResetTimeoutEvent(
decision.ScheduleID,
baseRunID,
resetRunID,
baseLastEventVersion,
resetReason,
resetRequestID,
)
if err != nil {
return nil, err
}
}
}
return resetMutableState, nil
}