-
Notifications
You must be signed in to change notification settings - Fork 833
/
task_executor.go
429 lines (387 loc) · 13.9 KB
/
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
// 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.
//go:generate mockgen -copyright_file ../../../LICENSE -package $GOPACKAGE -source $GOFILE -destination task_executor_mock.go
package replication
import (
"context"
"time"
commonpb "go.temporal.io/api/common/v1"
"go.temporal.io/api/serviceerror"
enumsspb "go.temporal.io/server/api/enums/v1"
"go.temporal.io/server/api/historyservice/v1"
replicationspb "go.temporal.io/server/api/replication/v1"
"go.temporal.io/server/common/headers"
"go.temporal.io/server/common/locks"
"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"
serviceerrors "go.temporal.io/server/common/serviceerror"
"go.temporal.io/server/common/xdc"
"go.temporal.io/server/service/history/deletemanager"
"go.temporal.io/server/service/history/shard"
wcache "go.temporal.io/server/service/history/workflow/cache"
)
type (
TaskExecutor interface {
Execute(ctx context.Context, replicationTask *replicationspb.ReplicationTask, forceApply bool) error
}
TaskExecutorParams struct {
RemoteCluster string // TODO: Remove this remote cluster from executor then it can use singleton.
Shard shard.Context
HistoryResender xdc.NDCHistoryResender
DeleteManager deletemanager.DeleteManager
WorkflowCache wcache.Cache
}
TaskExecutorProvider func(params TaskExecutorParams) TaskExecutor
taskExecutorImpl struct {
currentCluster string
remoteCluster string
shardContext shard.Context
namespaceRegistry namespace.Registry
nDCHistoryResender xdc.NDCHistoryResender
deleteManager deletemanager.DeleteManager
workflowCache wcache.Cache
metricsHandler metrics.Handler
logger log.Logger
}
)
// NewTaskExecutor creates a replication task executor
// The executor uses by 1) DLQ replication task handler 2) history replication task processor
func NewTaskExecutor(
remoteCluster string,
shardContext shard.Context,
nDCHistoryResender xdc.NDCHistoryResender,
deleteManager deletemanager.DeleteManager,
workflowCache wcache.Cache,
) TaskExecutor {
return &taskExecutorImpl{
currentCluster: shardContext.GetClusterMetadata().GetCurrentClusterName(),
remoteCluster: remoteCluster,
shardContext: shardContext,
namespaceRegistry: shardContext.GetNamespaceRegistry(),
nDCHistoryResender: nDCHistoryResender,
deleteManager: deleteManager,
workflowCache: workflowCache,
metricsHandler: shardContext.GetMetricsHandler(),
logger: shardContext.GetLogger(),
}
}
func (e *taskExecutorImpl) Execute(
ctx context.Context,
replicationTask *replicationspb.ReplicationTask,
forceApply bool,
) error {
var err error
switch replicationTask.GetTaskType() {
case enumsspb.REPLICATION_TASK_TYPE_SYNC_SHARD_STATUS_TASK:
// Shard status will be sent as part of the Replication message without kafka
case enumsspb.REPLICATION_TASK_TYPE_SYNC_ACTIVITY_TASK:
err = e.handleActivityTask(ctx, replicationTask, forceApply)
case enumsspb.REPLICATION_TASK_TYPE_HISTORY_METADATA_TASK:
// Without kafka we should not have size limits so we don't necessary need this in the new replication scheme.
case enumsspb.REPLICATION_TASK_TYPE_HISTORY_V2_TASK:
err = e.handleHistoryReplicationTask(ctx, replicationTask, forceApply)
case enumsspb.REPLICATION_TASK_TYPE_SYNC_WORKFLOW_STATE_TASK:
err = e.handleSyncWorkflowStateTask(ctx, replicationTask, forceApply)
default:
// NOTE: not handling SyncHSMTask in this deprecated code path, task will go to DLQ
e.logger.Error("Unknown replication task type.", tag.ReplicationTask(replicationTask))
err = ErrUnknownReplicationTask
}
return err
}
func (e *taskExecutorImpl) handleActivityTask(
ctx context.Context,
task *replicationspb.ReplicationTask,
forceApply bool,
) error {
attr := task.GetSyncActivityTaskAttributes()
doContinue, err := e.filterTask(namespace.ID(attr.GetNamespaceId()), forceApply)
if err != nil || !doContinue {
return err
}
startTime := time.Now().UTC()
defer func() {
metrics.ServiceLatency.With(e.metricsHandler).Record(
time.Since(startTime),
metrics.OperationTag(metrics.SyncActivityTaskScope),
)
}()
request := &historyservice.SyncActivityRequest{
NamespaceId: attr.NamespaceId,
WorkflowId: attr.WorkflowId,
RunId: attr.RunId,
Version: attr.Version,
ScheduledEventId: attr.ScheduledEventId,
ScheduledTime: attr.ScheduledTime,
StartedEventId: attr.StartedEventId,
StartedTime: attr.StartedTime,
LastHeartbeatTime: attr.LastHeartbeatTime,
Details: attr.Details,
Attempt: attr.Attempt,
LastFailure: attr.LastFailure,
LastWorkerIdentity: attr.LastWorkerIdentity,
LastStartedBuildId: attr.LastStartedBuildId,
LastStartedRedirectCounter: attr.LastStartedRedirectCounter,
VersionHistory: attr.GetVersionHistory(),
}
ctx, cancel := e.newTaskContext(ctx, attr.NamespaceId)
defer cancel()
// This might be extra cost if the workflow belongs to local shard.
// Add a wrapper of the history client to call history engine directly if it becomes an issue.
_, err = e.shardContext.GetHistoryClient().SyncActivity(ctx, request)
switch retryErr := err.(type) {
case nil:
return nil
case *serviceerrors.RetryReplication:
metrics.ClientRequests.With(e.metricsHandler).Record(
1,
metrics.OperationTag(metrics.HistoryRereplicationByActivityReplicationScope),
)
startTime := time.Now().UTC()
defer func() {
metrics.ClientLatency.With(e.metricsHandler).Record(
time.Since(startTime),
metrics.OperationTag(metrics.HistoryRereplicationByActivityReplicationScope),
)
}()
resendErr := e.nDCHistoryResender.SendSingleWorkflowHistory(
ctx,
e.remoteCluster,
namespace.ID(retryErr.NamespaceId),
retryErr.WorkflowId,
retryErr.RunId,
retryErr.StartEventId,
retryErr.StartEventVersion,
retryErr.EndEventId,
retryErr.EndEventVersion,
)
switch resendErr.(type) {
case *serviceerror.NotFound:
// workflow is not found in source cluster, cleanup workflow in target cluster
return e.cleanupWorkflowExecution(ctx, retryErr.NamespaceId, retryErr.WorkflowId, retryErr.RunId)
case nil:
// no-op
default:
e.logger.Error("error resend history for history event", tag.Error(resendErr))
return err
}
// This might be extra cost if the workflow belongs to local shard.
// Add a wrapper of the history client to call history engine directly if it becomes an issue.
_, err = e.shardContext.GetHistoryClient().SyncActivity(ctx, request)
return err
default:
return err
}
}
func (e *taskExecutorImpl) handleHistoryReplicationTask(
ctx context.Context,
task *replicationspb.ReplicationTask,
forceApply bool,
) error {
attr := task.GetHistoryTaskAttributes()
doContinue, err := e.filterTask(namespace.ID(attr.GetNamespaceId()), forceApply)
if err != nil || !doContinue {
return err
}
startTime := time.Now().UTC()
defer func() {
metrics.ServiceLatency.With(e.metricsHandler).Record(
time.Since(startTime),
metrics.OperationTag(metrics.HistoryReplicationTaskScope),
)
}()
request := &historyservice.ReplicateEventsV2Request{
NamespaceId: attr.NamespaceId,
WorkflowExecution: &commonpb.WorkflowExecution{
WorkflowId: attr.WorkflowId,
RunId: attr.RunId,
},
VersionHistoryItems: attr.VersionHistoryItems,
Events: attr.Events,
// new run events does not need version history since there is no prior events
NewRunEvents: attr.NewRunEvents,
NewRunId: attr.NewRunId,
}
ctx, cancel := e.newTaskContext(ctx, attr.NamespaceId)
defer cancel()
// This might be extra cost if the workflow belongs to local shard.
// Add a wrapper of the history client to call history engine directly if it becomes an issue.
_, err = e.shardContext.GetHistoryClient().ReplicateEventsV2(ctx, request)
switch retryErr := err.(type) {
case nil:
return nil
case *serviceerrors.RetryReplication:
metrics.ClientRequests.With(e.metricsHandler).Record(
1,
metrics.OperationTag(metrics.HistoryRereplicationByHistoryReplicationScope),
)
startTime := time.Now().UTC()
defer func() {
metrics.ClientLatency.With(e.metricsHandler).Record(
time.Since(startTime),
metrics.OperationTag(metrics.HistoryRereplicationByHistoryReplicationScope),
)
}()
resendErr := e.nDCHistoryResender.SendSingleWorkflowHistory(
ctx,
e.remoteCluster,
namespace.ID(retryErr.NamespaceId),
retryErr.WorkflowId,
retryErr.RunId,
retryErr.StartEventId,
retryErr.StartEventVersion,
retryErr.EndEventId,
retryErr.EndEventVersion,
)
switch resendErr.(type) {
case *serviceerror.NotFound:
// workflow is not found in source cluster, cleanup workflow in target cluster
return e.cleanupWorkflowExecution(ctx, retryErr.NamespaceId, retryErr.WorkflowId, retryErr.RunId)
case nil:
// no-op
default:
e.logger.Error("error resend history for history event", tag.Error(resendErr))
return err
}
// This might be extra cost if the workflow belongs to local shard.
// Add a wrapper of the history client to call history engine directly if it becomes an issue.
_, err = e.shardContext.GetHistoryClient().ReplicateEventsV2(ctx, request)
return err
default:
return err
}
}
func (e *taskExecutorImpl) handleSyncWorkflowStateTask(
ctx context.Context,
task *replicationspb.ReplicationTask,
forceApply bool,
) (retErr error) {
attr := task.GetSyncWorkflowStateTaskAttributes()
executionInfo := attr.GetWorkflowState().GetExecutionInfo()
namespaceID := namespace.ID(executionInfo.GetNamespaceId())
doContinue, err := e.filterTask(namespaceID, forceApply)
if err != nil || !doContinue {
return err
}
ctx, cancel := e.newTaskContext(ctx, executionInfo.NamespaceId)
defer cancel()
// This might be extra cost if the workflow belongs to local shard.
// Add a wrapper of the history client to call history engine directly if it becomes an issue.
request := &historyservice.ReplicateWorkflowStateRequest{
NamespaceId: namespaceID.String(),
WorkflowState: attr.GetWorkflowState(),
RemoteCluster: e.remoteCluster,
}
_, err = e.shardContext.GetHistoryClient().ReplicateWorkflowState(ctx, request)
switch retryErr := err.(type) {
case nil:
return nil
case *serviceerrors.RetryReplication:
resendErr := e.nDCHistoryResender.SendSingleWorkflowHistory(
ctx,
e.remoteCluster,
namespace.ID(retryErr.NamespaceId),
retryErr.WorkflowId,
retryErr.RunId,
retryErr.StartEventId,
retryErr.StartEventVersion,
retryErr.EndEventId,
retryErr.EndEventVersion,
)
switch resendErr.(type) {
case *serviceerror.NotFound:
// workflow is not found in source cluster, cleanup workflow in target cluster
return e.cleanupWorkflowExecution(ctx, retryErr.NamespaceId, retryErr.WorkflowId, retryErr.RunId)
case nil:
_, err = e.shardContext.GetHistoryClient().ReplicateWorkflowState(ctx, request)
return err
default:
e.logger.Error("error resend history for replicate workflow state", tag.Error(resendErr))
return err
}
default:
return err
}
}
func (e *taskExecutorImpl) filterTask(
namespaceID namespace.ID,
forceApply bool,
) (bool, error) {
if forceApply {
return true, nil
}
namespaceEntry, err := e.namespaceRegistry.GetNamespaceByID(namespaceID)
if err != nil {
if _, ok := err.(*serviceerror.NamespaceNotFound); ok {
// Drop the task
return false, nil
}
return false, err
}
shouldProcessTask := false
FilterLoop:
for _, targetCluster := range namespaceEntry.ClusterNames() {
if e.currentCluster == targetCluster {
shouldProcessTask = true
break FilterLoop
}
}
return shouldProcessTask, nil
}
func (e *taskExecutorImpl) cleanupWorkflowExecution(ctx context.Context, namespaceID string, workflowID string, runID string) (retErr error) {
nsID := namespace.ID(namespaceID)
ex := commonpb.WorkflowExecution{
WorkflowId: workflowID,
RunId: runID,
}
wfCtx, releaseFn, err := e.workflowCache.GetOrCreateWorkflowExecution(ctx, e.shardContext, nsID, &ex, locks.PriorityLow)
if err != nil {
return err
}
defer func() { releaseFn(retErr) }()
mutableState, err := wfCtx.LoadMutableState(ctx, e.shardContext)
if err != nil {
return err
}
return e.deleteManager.DeleteWorkflowExecution(
ctx,
nsID,
&ex,
wfCtx,
mutableState,
false,
nil, // stage is not stored during cleanup process.
)
}
func (e *taskExecutorImpl) newTaskContext(
parentCtx context.Context,
namespaceID string,
) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithTimeout(parentCtx, replicationTimeout)
namespace, _ := e.namespaceRegistry.GetNamespaceName(namespace.ID(namespaceID))
ctx = headers.SetCallerName(ctx, namespace.String())
return ctx, cancel
}