/
transfer_queue_active_task_executor.go
1592 lines (1444 loc) · 53.9 KB
/
transfer_queue_active_task_executor.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
// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// 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.
package history
import (
"context"
"fmt"
"github.com/pborman/uuid"
commonpb "go.temporal.io/api/common/v1"
enumspb "go.temporal.io/api/enums/v1"
historypb "go.temporal.io/api/history/v1"
"go.temporal.io/api/serviceerror"
taskqueuepb "go.temporal.io/api/taskqueue/v1"
workflowpb "go.temporal.io/api/workflow/v1"
"go.temporal.io/api/workflowservice/v1"
clockspb "go.temporal.io/server/api/clock/v1"
"go.temporal.io/server/api/historyservice/v1"
persistencespb "go.temporal.io/server/api/persistence/v1"
workflowspb "go.temporal.io/server/api/workflow/v1"
"go.temporal.io/server/common"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
"go.temporal.io/server/common/metrics"
"go.temporal.io/server/common/namespace"
"go.temporal.io/server/common/persistence"
"go.temporal.io/server/common/persistence/versionhistory"
"go.temporal.io/server/common/persistence/visibility/manager"
"go.temporal.io/server/common/primitives/timestamp"
"go.temporal.io/server/common/resource"
"go.temporal.io/server/common/rpc"
"go.temporal.io/server/common/sdk"
serviceerrors "go.temporal.io/server/common/serviceerror"
"go.temporal.io/server/common/worker_versioning"
"go.temporal.io/server/service/history/configs"
"go.temporal.io/server/service/history/consts"
"go.temporal.io/server/service/history/ndc"
"go.temporal.io/server/service/history/queues"
"go.temporal.io/server/service/history/shard"
"go.temporal.io/server/service/history/tasks"
"go.temporal.io/server/service/history/vclock"
"go.temporal.io/server/service/history/workflow"
wcache "go.temporal.io/server/service/history/workflow/cache"
"go.temporal.io/server/service/worker/parentclosepolicy"
)
type (
transferQueueActiveTaskExecutor struct {
*transferQueueTaskExecutorBase
workflowResetter ndc.WorkflowResetter
parentClosePolicyClient parentclosepolicy.Client
}
)
func newTransferQueueActiveTaskExecutor(
shard shard.Context,
workflowCache wcache.Cache,
sdkClientFactory sdk.ClientFactory,
logger log.Logger,
metricProvider metrics.Handler,
config *configs.Config,
historyRawClient resource.HistoryRawClient,
matchingRawClient resource.MatchingRawClient,
visibilityManager manager.VisibilityManager,
) queues.Executor {
return &transferQueueActiveTaskExecutor{
transferQueueTaskExecutorBase: newTransferQueueTaskExecutorBase(
shard,
workflowCache,
logger,
metricProvider,
historyRawClient,
matchingRawClient,
visibilityManager,
),
workflowResetter: ndc.NewWorkflowResetter(
shard,
workflowCache,
logger,
),
parentClosePolicyClient: parentclosepolicy.NewClient(
shard.GetMetricsHandler(),
shard.GetLogger(),
sdkClientFactory,
config.NumParentClosePolicySystemWorkflows(),
),
}
}
func (t *transferQueueActiveTaskExecutor) Execute(
ctx context.Context,
executable queues.Executable,
) queues.ExecuteResponse {
task := executable.GetTask()
taskType := queues.GetActiveTransferTaskTypeTagValue(task)
namespaceTag, replicationState := getNamespaceTagAndReplicationStateByID(
t.shardContext.GetNamespaceRegistry(),
task.GetNamespaceID(),
)
metricsTags := []metrics.Tag{
namespaceTag,
metrics.TaskTypeTag(taskType),
metrics.OperationTag(taskType), // for backward compatibility
}
if replicationState == enumspb.REPLICATION_STATE_HANDOVER {
// TODO: exclude task types here if we believe it's safe & necessary to execute
// them during namespace handover.
// TODO: move this logic to queues.Executable when metrics tag doesn't need to
// be returned from task executor
return queues.ExecuteResponse{
ExecutionMetricTags: metricsTags,
ExecutedAsActive: true,
ExecutionErr: consts.ErrNamespaceHandover,
}
}
var err error
switch task := task.(type) {
case *tasks.ActivityTask:
err = t.processActivityTask(ctx, task)
case *tasks.WorkflowTask:
err = t.processWorkflowTask(ctx, task)
case *tasks.CloseExecutionTask:
err = t.processCloseExecution(ctx, task)
case *tasks.CancelExecutionTask:
err = t.processCancelExecution(ctx, task)
case *tasks.SignalExecutionTask:
err = t.processSignalExecution(ctx, task)
case *tasks.StartChildExecutionTask:
err = t.processStartChildExecution(ctx, task)
case *tasks.ResetWorkflowTask:
err = t.processResetWorkflow(ctx, task)
case *tasks.DeleteExecutionTask:
err = t.processDeleteExecutionTask(ctx, task)
default:
err = errUnknownTransferTask
}
return queues.ExecuteResponse{
ExecutionMetricTags: metricsTags,
ExecutedAsActive: true,
ExecutionErr: err,
}
}
func (t *transferQueueActiveTaskExecutor) processDeleteExecutionTask(ctx context.Context,
task *tasks.DeleteExecutionTask) error {
return t.transferQueueTaskExecutorBase.processDeleteExecutionTask(ctx, task,
t.config.TransferProcessorEnsureCloseBeforeDelete())
}
func (t *transferQueueActiveTaskExecutor) processActivityTask(
ctx context.Context,
task *tasks.ActivityTask,
) (retError error) {
ctx, cancel := context.WithTimeout(ctx, taskTimeout)
defer cancel()
weContext, release, err := getWorkflowExecutionContextForTask(ctx, t.shardContext, t.cache, task)
if err != nil {
return err
}
defer func() { release(retError) }()
mutableState, err := loadMutableStateForTransferTask(ctx, t.shardContext, weContext, task, t.metricHandler, t.logger)
if err != nil {
return err
}
if mutableState == nil {
release(nil) // release(nil) so that the mutable state is not unloaded from cache
return consts.ErrWorkflowExecutionNotFound
}
ai, ok := mutableState.GetActivityInfo(task.ScheduledEventID)
if !ok {
release(nil) // release(nil) so that the mutable state is not unloaded from cache
return consts.ErrActivityTaskNotFound
}
err = CheckTaskVersion(t.shardContext, t.logger, mutableState.GetNamespaceEntry(), ai.Version, task.Version, task)
if err != nil {
return err
}
if !mutableState.IsWorkflowExecutionRunning() {
release(nil) // release(nil) so that the mutable state is not unloaded from cache
return consts.ErrWorkflowCompleted
}
timeout := timestamp.DurationValue(ai.ScheduleToStartTimeout)
directive := worker_versioning.MakeDirectiveForActivityTask(mutableState.GetWorkerVersionStamp(), ai.UseCompatibleVersion)
// NOTE: do not access anything related mutable state after this lock release
// release the context lock since we no longer need mutable state and
// the rest of logic is making RPC call, which takes time.
release(nil)
return t.pushActivity(ctx, task, timeout, directive)
}
func (t *transferQueueActiveTaskExecutor) processWorkflowTask(
ctx context.Context,
transferTask *tasks.WorkflowTask,
) (retError error) {
ctx, cancel := context.WithTimeout(ctx, taskTimeout)
defer cancel()
weContext, release, err := getWorkflowExecutionContextForTask(ctx, t.shardContext, t.cache, transferTask)
if err != nil {
return err
}
defer func() { release(retError) }()
mutableState, err := loadMutableStateForTransferTask(ctx, t.shardContext, weContext, transferTask, t.metricHandler, t.logger)
if err != nil {
return err
}
if mutableState == nil || !mutableState.IsWorkflowExecutionRunning() {
return nil
}
workflowTask := mutableState.GetWorkflowTaskByID(transferTask.ScheduledEventID)
if workflowTask == nil {
return nil
}
err = CheckTaskVersion(t.shardContext, t.logger, mutableState.GetNamespaceEntry(), workflowTask.Version, transferTask.Version, transferTask)
if err != nil {
return err
}
// Task queue from transfer task (not current one from mutable state) must be used here.
// If current task queue becomes sticky since this transfer task was created,
// it can't be used here, because timeout timer was not created for it,
// because it used to be non-sticky when this transfer task was created .
taskQueue, scheduleToStartTimeout := mutableState.TaskQueueScheduleToStartTimeout(transferTask.TaskQueue)
normalTaskQueueName := mutableState.GetExecutionInfo().TaskQueue
directive := worker_versioning.MakeDirectiveForWorkflowTask(
mutableState.GetWorkerVersionStamp(),
mutableState.GetLastWorkflowTaskStartedEventID(),
)
// NOTE: Do not access mutableState after this lock is released.
// It is important to release the workflow lock here, because pushWorkflowTask will call matching,
// which will call history back (with RecordWorkflowTaskStarted), and it will try to get workflow lock again.
release(nil)
err = t.pushWorkflowTask(ctx, transferTask, taskQueue, scheduleToStartTimeout.AsDuration(), directive)
if _, ok := err.(*serviceerrors.StickyWorkerUnavailable); ok {
// sticky worker is unavailable, switch to original normal task queue
taskQueue = &taskqueuepb.TaskQueue{
// do not use task.TaskQueue which is sticky, use original normal task queue from mutable state
Name: normalTaskQueueName,
Kind: enumspb.TASK_QUEUE_KIND_NORMAL,
}
// Continue to use sticky schedule_to_start timeout as TTL for the matching task. Because the schedule_to_start
// timeout timer task is already created which will timeout this task if no worker pick it up in 5s anyway.
// There is no need to reset sticky, because if this task is picked by new worker, the new worker will reset
// the sticky queue to a new one. However, if worker is completely down, that schedule_to_start timeout task
// will re-create a new non-sticky task and reset sticky.
err = t.pushWorkflowTask(ctx, transferTask, taskQueue, scheduleToStartTimeout.AsDuration(), directive)
}
return err
}
func (t *transferQueueActiveTaskExecutor) processCloseExecution(
ctx context.Context,
task *tasks.CloseExecutionTask,
) (retError error) {
ctx, cancel := context.WithTimeout(ctx, taskTimeout)
defer cancel()
weContext, release, err := getWorkflowExecutionContextForTask(ctx, t.shardContext, t.cache, task)
if err != nil {
return err
}
defer func() { release(retError) }()
mutableState, err := loadMutableStateForTransferTask(ctx, t.shardContext, weContext, task, t.metricHandler, t.logger)
if err != nil {
return err
}
if mutableState == nil || mutableState.IsWorkflowExecutionRunning() {
return nil
}
// DeleteAfterClose is set to true when this close execution task was generated as part of delete open workflow execution procedure.
// Delete workflow execution is started by user API call and should be done regardless of current workflow version.
if !task.DeleteAfterClose {
lastWriteVersion, err := mutableState.GetLastWriteVersion()
if err != nil {
return err
}
err = CheckTaskVersion(t.shardContext, t.logger, mutableState.GetNamespaceEntry(), lastWriteVersion, task.Version, task)
if err != nil {
return err
}
}
workflowExecution := commonpb.WorkflowExecution{
WorkflowId: task.GetWorkflowID(),
RunId: task.GetRunID(),
}
executionInfo := mutableState.GetExecutionInfo()
var completionEvent *historypb.HistoryEvent // needed to report close event to parent workflow
replyToParentWorkflow := mutableState.HasParentExecution() && executionInfo.NewExecutionRunId == ""
if replyToParentWorkflow {
// only load close event if needed.
completionEvent, err = mutableState.GetCompletionEvent(ctx)
if err != nil {
return err
}
replyToParentWorkflow = replyToParentWorkflow && !ndc.IsTerminatedByResetter(completionEvent)
}
parentNamespaceID := executionInfo.ParentNamespaceId
parentWorkflowID := executionInfo.ParentWorkflowId
parentRunID := executionInfo.ParentRunId
parentInitiatedID := executionInfo.ParentInitiatedId
parentInitiatedVersion := executionInfo.ParentInitiatedVersion
var parentClock *clockspb.VectorClock
if executionInfo.ParentClock != nil {
parentClock = vclock.NewVectorClock(
executionInfo.ParentClock.ClusterId,
executionInfo.ParentClock.ShardId,
executionInfo.ParentClock.Clock,
)
}
namespaceName := mutableState.GetNamespaceEntry().Name()
children := copyChildWorkflowInfos(mutableState.GetPendingChildExecutionInfos())
// NOTE: do not access anything related mutable state after this lock release.
// Release lock immediately since mutable state is not needed
// and the rest of logic is RPC calls, which can take time.
release(nil)
// Communicate the result to parent execution if this is Child Workflow execution
if replyToParentWorkflow {
_, err := t.historyRawClient.RecordChildExecutionCompleted(ctx, &historyservice.RecordChildExecutionCompletedRequest{
NamespaceId: parentNamespaceID,
ParentExecution: &commonpb.WorkflowExecution{
WorkflowId: parentWorkflowID,
RunId: parentRunID,
},
ParentInitiatedId: parentInitiatedID,
ParentInitiatedVersion: parentInitiatedVersion,
ChildExecution: &workflowExecution,
Clock: parentClock,
CompletionEvent: completionEvent,
})
switch err.(type) {
case nil:
// noop
case *serviceerror.NotFound, *serviceerror.NamespaceNotFound:
// parent gone, noop
default:
return err
}
}
err = t.processParentClosePolicy(
ctx,
namespaceName.String(),
&workflowExecution,
children,
)
if err != nil {
// This is some retryable error, not NotFound or NamespaceNotFound.
return err
}
if task.DeleteAfterClose {
err = t.deleteExecution(
ctx,
task,
// Visibility is not updated (to avoid race condition for visibility tasks) and workflow execution is
// still open there.
true,
false,
&task.DeleteProcessStage,
)
}
return err
}
func (t *transferQueueActiveTaskExecutor) processCancelExecution(
ctx context.Context,
task *tasks.CancelExecutionTask,
) (retError error) {
ctx, cancel := context.WithTimeout(ctx, taskTimeout)
defer cancel()
weContext, release, err := getWorkflowExecutionContextForTask(ctx, t.shardContext, t.cache, task)
if err != nil {
return err
}
defer func() { release(retError) }()
mutableState, err := loadMutableStateForTransferTask(ctx, t.shardContext, weContext, task, t.metricHandler, t.logger)
if err != nil {
return err
}
if mutableState == nil || !mutableState.IsWorkflowExecutionRunning() {
return nil
}
requestCancelInfo, ok := mutableState.GetRequestCancelInfo(task.InitiatedEventID)
if !ok {
return nil
}
err = CheckTaskVersion(t.shardContext, t.logger, mutableState.GetNamespaceEntry(), requestCancelInfo.Version, task.Version, task)
if err != nil {
return err
}
initiatedEvent, err := mutableState.GetRequesteCancelExternalInitiatedEvent(ctx, task.InitiatedEventID)
if err != nil {
return err
}
attributes := initiatedEvent.GetRequestCancelExternalWorkflowExecutionInitiatedEventAttributes()
targetNamespaceEntry, err := t.registry.GetNamespaceByID(namespace.ID(task.TargetNamespaceID))
if err != nil {
if _, isNotFound := err.(*serviceerror.NamespaceNotFound); !isNotFound {
return err
}
// It is possible that target namespace got deleted. Record failure.
t.logger.Debug("Target namespace is not found.", tag.WorkflowNamespaceID(task.TargetNamespaceID))
err = t.requestCancelExternalExecutionFailed(
ctx,
task,
weContext,
namespace.Name(task.TargetNamespaceID), // Use ID as namespace name because namespace is already deleted and name is used only for history.
namespace.ID(task.TargetNamespaceID),
task.TargetWorkflowID,
task.TargetRunID,
enumspb.CANCEL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_NAMESPACE_NOT_FOUND)
return err
}
targetNamespaceName := targetNamespaceEntry.Name()
// handle workflow cancel itself
if task.NamespaceID == task.TargetNamespaceID && task.WorkflowID == task.TargetWorkflowID {
// it does not matter if the run ID is a mismatch
err = t.requestCancelExternalExecutionFailed(
ctx,
task,
weContext,
targetNamespaceName,
namespace.ID(task.TargetNamespaceID),
task.TargetWorkflowID,
task.TargetRunID,
enumspb.CANCEL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_EXTERNAL_WORKFLOW_EXECUTION_NOT_FOUND)
return err
}
if err = t.requestCancelExternalExecution(
ctx,
task,
targetNamespaceName,
requestCancelInfo,
attributes,
); err != nil {
t.logger.Debug(fmt.Sprintf("Failed to cancel external workflow execution. Error: %v", err))
// Check to see if the error is non-transient, in which case add RequestCancelFailed
// event and complete transfer task by returning nil error.
if common.IsServiceTransientError(err) || common.IsContextDeadlineExceededErr(err) {
// for retryable error just return
return err
}
var failedCause enumspb.CancelExternalWorkflowExecutionFailedCause
switch err.(type) {
case *serviceerror.NotFound:
failedCause = enumspb.CANCEL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_EXTERNAL_WORKFLOW_EXECUTION_NOT_FOUND
case *serviceerror.NamespaceNotFound:
failedCause = enumspb.CANCEL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_NAMESPACE_NOT_FOUND
default:
t.logger.Error("Unexpected error type returned from RequestCancelWorkflowExecution API call.", tag.ErrorType(err), tag.Error(err))
return err
}
return t.requestCancelExternalExecutionFailed(
ctx,
task,
weContext,
targetNamespaceName,
namespace.ID(task.TargetNamespaceID),
task.TargetWorkflowID,
task.TargetRunID,
failedCause,
)
}
// Record ExternalWorkflowExecutionCancelRequested in source execution
return t.requestCancelExternalExecutionCompleted(
ctx,
task,
weContext,
targetNamespaceName,
namespace.ID(task.TargetNamespaceID),
task.TargetWorkflowID,
task.TargetRunID,
)
}
func (t *transferQueueActiveTaskExecutor) processSignalExecution(
ctx context.Context,
task *tasks.SignalExecutionTask,
) (retError error) {
ctx, cancel := context.WithTimeout(ctx, taskTimeout)
defer cancel()
weContext, release, err := getWorkflowExecutionContextForTask(ctx, t.shardContext, t.cache, task)
if err != nil {
return err
}
defer func() { release(retError) }()
mutableState, err := loadMutableStateForTransferTask(ctx, t.shardContext, weContext, task, t.metricHandler, t.logger)
if err != nil {
return err
}
if mutableState == nil {
release(nil) // release(nil) so that the mutable state is not unloaded from cache
return consts.ErrWorkflowExecutionNotFound
}
signalInfo, ok := mutableState.GetSignalInfo(task.InitiatedEventID)
if !ok {
// TODO: here we should also RemoveSignalMutableState from target workflow
// Otherwise, target SignalRequestID still can leak if shard restart after signalExternalExecutionCompleted
// To do that, probably need to add the SignalRequestID in transfer task.
return nil
}
err = CheckTaskVersion(t.shardContext, t.logger, mutableState.GetNamespaceEntry(), signalInfo.Version, task.Version, task)
if err != nil {
return err
}
if !mutableState.IsWorkflowExecutionRunning() {
release(nil) // release(nil) so that the mutable state is not unloaded from cache
return consts.ErrWorkflowCompleted
}
initiatedEvent, err := mutableState.GetSignalExternalInitiatedEvent(ctx, task.InitiatedEventID)
if err != nil {
return err
}
attributes := initiatedEvent.GetSignalExternalWorkflowExecutionInitiatedEventAttributes()
targetNamespaceEntry, err := t.registry.GetNamespaceByID(namespace.ID(task.TargetNamespaceID))
if err != nil {
if _, isNotFound := err.(*serviceerror.NamespaceNotFound); !isNotFound {
return err
}
// It is possible that target namespace got deleted. Record failure.
t.logger.Debug("Target namespace is not found.", tag.WorkflowNamespaceID(task.TargetNamespaceID))
return t.signalExternalExecutionFailed(
ctx,
task,
weContext,
namespace.Name(task.TargetNamespaceID), // Use ID as namespace name because namespace is already deleted and name is used only for history.
namespace.ID(task.TargetNamespaceID),
task.TargetWorkflowID,
task.TargetRunID,
attributes.Control,
enumspb.SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_NAMESPACE_NOT_FOUND,
)
}
targetNamespaceName := targetNamespaceEntry.Name()
// handle workflow signal itself
if task.NamespaceID == task.TargetNamespaceID && task.WorkflowID == task.TargetWorkflowID {
// it does not matter if the run ID is a mismatch
return t.signalExternalExecutionFailed(
ctx,
task,
weContext,
targetNamespaceName,
namespace.ID(task.TargetNamespaceID),
task.TargetWorkflowID,
task.TargetRunID,
attributes.Control,
enumspb.SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_EXTERNAL_WORKFLOW_EXECUTION_NOT_FOUND,
)
}
if err = t.signalExternalExecution(
ctx,
task,
targetNamespaceName,
signalInfo,
attributes,
); err != nil {
t.logger.Debug("Failed to signal external workflow execution", tag.Error(err))
// Check to see if the error is non-transient, in which case add SignalFailed
// event and complete transfer task by returning nil error.
if common.IsServiceTransientError(err) || common.IsContextDeadlineExceededErr(err) {
// for retryable error just return
return err
}
var failedCause enumspb.SignalExternalWorkflowExecutionFailedCause
switch err.(type) {
case *serviceerror.NotFound:
failedCause = enumspb.SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_EXTERNAL_WORKFLOW_EXECUTION_NOT_FOUND
case *serviceerror.NamespaceNotFound:
failedCause = enumspb.SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_NAMESPACE_NOT_FOUND
case *serviceerror.InvalidArgument:
failedCause = enumspb.SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_SIGNAL_COUNT_LIMIT_EXCEEDED
default:
t.logger.Error("Unexpected error type returned from SignalWorkflowExecution API call.", tag.ErrorType(err), tag.Error(err))
return err
}
return t.signalExternalExecutionFailed(
ctx,
task,
weContext,
targetNamespaceName,
namespace.ID(task.TargetNamespaceID),
task.TargetWorkflowID,
task.TargetRunID,
attributes.Control,
failedCause,
)
}
err = t.signalExternalExecutionCompleted(
ctx,
task,
weContext,
targetNamespaceName,
namespace.ID(task.TargetNamespaceID),
task.TargetWorkflowID,
task.TargetRunID,
attributes.Control,
)
if err != nil {
return err
}
signalRequestID := signalInfo.GetRequestId()
// release the weContext lock since we no longer need mutable state and
// the rest of logic is making RPC call, which takes time.
release(retError)
// remove signalRequestedID from target workflow, after Signal detail is removed from source workflow
_, err = t.historyRawClient.RemoveSignalMutableState(ctx, &historyservice.RemoveSignalMutableStateRequest{
NamespaceId: task.TargetNamespaceID,
WorkflowExecution: &commonpb.WorkflowExecution{
WorkflowId: task.TargetWorkflowID,
RunId: task.TargetRunID,
},
RequestId: signalRequestID,
})
return err
}
func (t *transferQueueActiveTaskExecutor) processStartChildExecution(
ctx context.Context,
task *tasks.StartChildExecutionTask,
) (retError error) {
ctx, cancel := context.WithTimeout(ctx, taskTimeout)
defer cancel()
weContext, release, err := getWorkflowExecutionContextForTask(ctx, t.shardContext, t.cache, task)
if err != nil {
return err
}
defer func() { release(retError) }()
mutableState, err := loadMutableStateForTransferTask(ctx, t.shardContext, weContext, task, t.metricHandler, t.logger)
if err != nil {
return err
}
if mutableState == nil {
release(nil) // release(nil) so that the mutable state is not unloaded from cache
return consts.ErrWorkflowExecutionNotFound
}
childInfo, ok := mutableState.GetChildExecutionInfo(task.InitiatedEventID)
if !ok {
release(nil) // release(nil) so that the mutable state is not unloaded from cache
return consts.ErrChildExecutionNotFound
}
err = CheckTaskVersion(t.shardContext, t.logger, mutableState.GetNamespaceEntry(), childInfo.Version, task.Version, task)
if err != nil {
return err
}
// workflow running or not, child started or not, parent close policy is abandon or not
// 8 cases in total
workflowRunning := mutableState.IsWorkflowExecutionRunning()
childStarted := childInfo.StartedEventId != common.EmptyEventID
if !workflowRunning && (!childStarted || childInfo.ParentClosePolicy != enumspb.PARENT_CLOSE_POLICY_ABANDON) {
// three cases here:
// case 1: workflow not running, child started, parent close policy is not abandon
// case 2: workflow not running, child not started, parent close policy is not abandon
// case 3: workflow not running, child not started, parent close policy is abandon
//
// NOTE: ideally for case 3, we should continue to start child. However, with current start child
// and standby start child verification logic, we can't do that because:
// 1. Once workflow is closed, we can't update mutable state or record child started event.
// If the RPC call for scheduling first workflow task times out but the call actually succeeds on child workflow.
// Then the child workflow can run, complete and another unrelated workflow can reuse this workflowID.
// Now when the start child task retries, we can't rely on requestID to dedupe the start child call. (We can use runID instead of requestID to dedupe)
// 2. No update to mutable state and child started event means we are not able to replicate the information
// to the standby cluster, so standby start child logic won't be able to verify the child has started.
// To resolve the issue above, we need to
// 1. Start child workflow and schedule the first workflow task in one transaction. Use runID to perform deduplication
// 2. Standby start child logic need to verify if child workflow actually started instead of relying on the information
// in parent mutable state.
return nil
}
// ChildExecution already started, just create WorkflowTask and complete transfer task
// If parent already closed, since child workflow started event already written to history,
// still schedule the workflowTask if the parent close policy is Abandon.
// If parent close policy cancel or terminate, parent close policy will be applied in another
// transfer task.
// case 4, 5: workflow started, child started, parent close policy is or is not abandon
// case 6: workflow closed, child started, parent close policy is abandon
if childStarted {
childExecution := &commonpb.WorkflowExecution{
WorkflowId: childInfo.StartedWorkflowId,
RunId: childInfo.StartedRunId,
}
childClock := childInfo.Clock
// NOTE: do not access anything related mutable state after this lock release
// release the context lock since we no longer need mutable state and
// the rest of logic is making RPC call, which takes time.
release(nil)
parentClock, err := t.shardContext.NewVectorClock()
if err != nil {
return err
}
return t.createFirstWorkflowTask(ctx, task.TargetNamespaceID, childExecution, parentClock, childClock)
}
// remaining 2 cases:
// case 7, 8: workflow running, child not started, parent close policy is or is not abandon
initiatedEvent, err := mutableState.GetChildExecutionInitiatedEvent(ctx, task.InitiatedEventID)
if err != nil {
return err
}
attributes := initiatedEvent.GetStartChildWorkflowExecutionInitiatedEventAttributes()
var parentNamespaceName namespace.Name
if namespaceEntry, err := t.registry.GetNamespaceByID(namespace.ID(task.NamespaceID)); err != nil {
if _, isNotFound := err.(*serviceerror.NamespaceNotFound); !isNotFound {
return err
}
// It is possible that the parent namespace got deleted. Use namespaceID instead as this is only needed for the history event.
parentNamespaceName = namespace.Name(task.NamespaceID)
} else {
parentNamespaceName = namespaceEntry.Name()
}
var targetNamespaceName namespace.Name
if namespaceEntry, err := t.registry.GetNamespaceByID(namespace.ID(task.TargetNamespaceID)); err != nil {
if _, isNotFound := err.(*serviceerror.NamespaceNotFound); !isNotFound {
return err
}
// It is possible that target namespace got deleted. Record failure.
t.logger.Debug("Target namespace is not found.", tag.WorkflowNamespaceID(task.TargetNamespaceID))
err = t.recordStartChildExecutionFailed(
ctx,
task,
weContext,
attributes,
enumspb.START_CHILD_WORKFLOW_EXECUTION_FAILED_CAUSE_NAMESPACE_NOT_FOUND,
)
return err
} else {
targetNamespaceName = namespaceEntry.Name()
}
// copy version stamp from parent to child if:
// - command says to use compatible version
// - parent is using versioning
var sourceVersionStamp *commonpb.WorkerVersionStamp
if attributes.UseCompatibleVersion {
sourceVersionStamp = worker_versioning.StampIfUsingVersioning(mutableState.GetWorkerVersionStamp())
}
childRunID, childClock, err := t.startWorkflow(
ctx,
task,
parentNamespaceName,
targetNamespaceName,
childInfo.CreateRequestId,
attributes,
sourceVersionStamp,
)
if err != nil {
t.logger.Debug("Failed to start child workflow execution", tag.Error(err))
if common.IsServiceTransientError(err) || common.IsContextDeadlineExceededErr(err) {
// for retryable error just return
return err
}
var failedCause enumspb.StartChildWorkflowExecutionFailedCause
switch err.(type) {
case *serviceerror.WorkflowExecutionAlreadyStarted:
failedCause = enumspb.START_CHILD_WORKFLOW_EXECUTION_FAILED_CAUSE_WORKFLOW_ALREADY_EXISTS
case *serviceerror.NamespaceNotFound:
failedCause = enumspb.START_CHILD_WORKFLOW_EXECUTION_FAILED_CAUSE_NAMESPACE_NOT_FOUND
default:
t.logger.Error("Unexpected error type returned from StartWorkflowExecution API call for child workflow.", tag.ErrorType(err), tag.Error(err))
return err
}
return t.recordStartChildExecutionFailed(
ctx,
task,
weContext,
attributes,
failedCause,
)
}
t.logger.Debug("Child Execution started successfully",
tag.WorkflowID(attributes.WorkflowId), tag.WorkflowRunID(childRunID))
// Child execution is successfully started, record ChildExecutionStartedEvent in parent execution
err = t.recordChildExecutionStarted(ctx, task, weContext, attributes, childRunID, childClock)
if err != nil {
return err
}
// NOTE: do not access anything related mutable state after this lock is released.
// Release the context lock since we no longer need mutable state and
// the rest of logic is making RPC call, which takes time.
release(nil)
parentClock, err := t.shardContext.NewVectorClock()
if err != nil {
return err
}
return t.createFirstWorkflowTask(ctx, task.TargetNamespaceID, &commonpb.WorkflowExecution{
WorkflowId: task.TargetWorkflowID,
RunId: childRunID,
}, parentClock, childClock)
}
func (t *transferQueueActiveTaskExecutor) processResetWorkflow(
ctx context.Context,
task *tasks.ResetWorkflowTask,
) (retError error) {
ctx, cancel := context.WithTimeout(ctx, taskTimeout)
defer cancel()
currentContext, currentRelease, err := getWorkflowExecutionContextForTask(ctx, t.shardContext, t.cache, task)
if err != nil {
return err
}
defer func() { currentRelease(retError) }()
currentMutableState, err := loadMutableStateForTransferTask(ctx, t.shardContext, currentContext, task, t.metricHandler, t.logger)
if err != nil {
return err
}
if currentMutableState == nil {
return nil
}
logger := log.With(
t.logger,
tag.WorkflowNamespaceID(task.NamespaceID),
tag.WorkflowID(task.WorkflowID),
tag.WorkflowRunID(task.RunID),
)
if !currentMutableState.IsWorkflowExecutionRunning() {
// it means this this might not be current anymore, we need to check
var resp *persistence.GetCurrentExecutionResponse
resp, err = t.shardContext.GetCurrentExecution(ctx, &persistence.GetCurrentExecutionRequest{
ShardID: t.shardContext.GetShardID(),
NamespaceID: task.NamespaceID,
WorkflowID: task.WorkflowID,
})
if err != nil {
return err
}
if resp.RunID != task.RunID {
logger.Warn("Auto-Reset is skipped, because current run is stale.")
return nil
}
}
// TODO: current reset doesn't allow childWFs, in the future we will release this restriction
if len(currentMutableState.GetPendingChildExecutionInfos()) > 0 {
logger.Warn("Auto-Reset is skipped, because current run has pending child executions.")
return nil
}
currentStartVersion, err := currentMutableState.GetStartVersion()
if err != nil {
return err
}
err = CheckTaskVersion(t.shardContext, t.logger, currentMutableState.GetNamespaceEntry(), currentStartVersion, task.Version, task)
if err != nil {
return err
}
executionInfo := currentMutableState.GetExecutionInfo()
executionState := currentMutableState.GetExecutionState()
namespaceEntry, err := t.registry.GetNamespaceByID(namespace.ID(executionInfo.NamespaceId))
if err != nil {
return err
}
logger = log.With(logger, tag.WorkflowNamespace(namespaceEntry.Name().String()))
reason, resetPoint := workflow.FindAutoResetPoint(t.shardContext.GetTimeSource(), namespaceEntry.VerifyBinaryChecksum, executionInfo.AutoResetPoints)
if resetPoint == nil {
logger.Warn("Auto-Reset is skipped, because reset point is not found.")
return nil
}
logger = log.With(
logger,
tag.WorkflowResetBaseRunID(resetPoint.GetRunId()),
tag.WorkflowBinaryChecksum(resetPoint.GetBinaryChecksum()),
tag.WorkflowEventID(resetPoint.GetFirstWorkflowTaskCompletedId()),
)
var baseContext workflow.Context
var baseMutableState workflow.MutableState
var baseRelease wcache.ReleaseCacheFunc
if resetPoint.GetRunId() == executionState.RunId {
baseContext = currentContext
baseMutableState = currentMutableState
baseRelease = currentRelease
} else {
baseContext, baseRelease, err = getWorkflowExecutionContext(
ctx,
t.shardContext,
t.cache,
namespace.ID(task.NamespaceID),
&commonpb.WorkflowExecution{
WorkflowId: task.WorkflowID,
RunId: resetPoint.GetRunId(),
},
)
if err != nil {
return err
}
defer func() { baseRelease(retError) }()
baseMutableState, err = loadMutableStateForTransferTask(ctx, t.shardContext, baseContext, task, t.metricHandler, t.logger)
if err != nil {
return err
}
if baseMutableState == nil {
return nil
}
}
// NOTE: reset need to go through history which may take a longer time,
// so it's using its own timeout
return t.resetWorkflow(
ctx,
task,
reason,
resetPoint,
baseMutableState,
currentContext,
currentMutableState,
logger,
)
}
func (t *transferQueueActiveTaskExecutor) recordChildExecutionStarted(
ctx context.Context,