-
Notifications
You must be signed in to change notification settings - Fork 769
/
transfer_task_executor_base.go
420 lines (381 loc) · 13.2 KB
/
transfer_task_executor_base.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
// 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 task
import (
"context"
"time"
"github.com/uber/cadence/client/matching"
"github.com/uber/cadence/common"
"github.com/uber/cadence/common/backoff"
"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/service"
"github.com/uber/cadence/common/types"
"github.com/uber/cadence/service/history/config"
"github.com/uber/cadence/service/history/execution"
"github.com/uber/cadence/service/history/shard"
"github.com/uber/cadence/service/worker/archiver"
)
const (
taskDefaultTimeout = 3 * time.Second
taskGetExecutionContextTimeout = 500 * time.Millisecond
taskRPCCallTimeout = 2 * time.Second
secondsInDay = int32(24 * time.Hour / time.Second)
defaultDomainName = "defaultDomainName"
)
type (
transferTaskExecutorBase struct {
shard shard.Context
archiverClient archiver.Client
executionCache *execution.Cache
logger log.Logger
metricsClient metrics.Client
matchingClient matching.Client
visibilityMgr persistence.VisibilityManager
config *config.Config
throttleRetry *backoff.ThrottleRetry
}
)
func newTransferTaskExecutorBase(
shard shard.Context,
archiverClient archiver.Client,
executionCache *execution.Cache,
logger log.Logger,
config *config.Config,
) *transferTaskExecutorBase {
return &transferTaskExecutorBase{
shard: shard,
archiverClient: archiverClient,
executionCache: executionCache,
logger: logger,
metricsClient: shard.GetMetricsClient(),
matchingClient: shard.GetService().GetMatchingClient(),
visibilityMgr: shard.GetService().GetVisibilityManager(),
config: config,
throttleRetry: backoff.NewThrottleRetry(
backoff.WithRetryPolicy(taskRetryPolicy),
backoff.WithRetryableError(common.IsServiceTransientError),
),
}
}
func (t *transferTaskExecutorBase) pushActivity(
ctx context.Context,
task *persistence.TransferTaskInfo,
activityScheduleToStartTimeout int32,
partitionConfig map[string]string,
) error {
ctx, cancel := context.WithTimeout(ctx, taskRPCCallTimeout)
defer cancel()
if task.TaskType != persistence.TransferTaskTypeActivityTask {
t.logger.Fatal("Cannot process non activity task", tag.TaskType(task.GetTaskType()))
}
return t.matchingClient.AddActivityTask(ctx, &types.AddActivityTaskRequest{
DomainUUID: task.TargetDomainID,
SourceDomainUUID: task.DomainID,
Execution: &types.WorkflowExecution{
WorkflowID: task.WorkflowID,
RunID: task.RunID,
},
TaskList: &types.TaskList{Name: task.TaskList},
ScheduleID: task.ScheduleID,
ScheduleToStartTimeoutSeconds: common.Int32Ptr(activityScheduleToStartTimeout),
PartitionConfig: partitionConfig,
})
}
func (t *transferTaskExecutorBase) pushDecision(
ctx context.Context,
task *persistence.TransferTaskInfo,
tasklist *types.TaskList,
decisionScheduleToStartTimeout int32,
partitionConfig map[string]string,
) error {
ctx, cancel := context.WithTimeout(ctx, taskRPCCallTimeout)
defer cancel()
if task.TaskType != persistence.TransferTaskTypeDecisionTask {
t.logger.Fatal("Cannot process non decision task", tag.TaskType(task.GetTaskType()))
}
return t.matchingClient.AddDecisionTask(ctx, &types.AddDecisionTaskRequest{
DomainUUID: task.DomainID,
Execution: &types.WorkflowExecution{
WorkflowID: task.WorkflowID,
RunID: task.RunID,
},
TaskList: tasklist,
ScheduleID: task.ScheduleID,
ScheduleToStartTimeoutSeconds: common.Int32Ptr(decisionScheduleToStartTimeout),
PartitionConfig: partitionConfig,
})
}
func (t *transferTaskExecutorBase) recordWorkflowStarted(
ctx context.Context,
domainID string,
workflowID string,
runID string,
workflowTypeName string,
startTimeUnixNano int64,
executionTimeUnixNano int64,
workflowTimeout int32,
taskID int64,
taskList string,
isCron bool,
numClusters int16,
visibilityMemo *types.Memo,
updateTimeUnixNano int64,
searchAttributes map[string][]byte,
) error {
domain := defaultDomainName
if domainEntry, err := t.shard.GetDomainCache().GetDomainByID(domainID); err != nil {
if _, ok := err.(*types.EntityNotExistsError); !ok {
return err
}
} else {
domain = domainEntry.GetInfo().Name
// if sampled for longer retention is enabled, only record those sampled events
if domainEntry.IsSampledForLongerRetentionEnabled(workflowID) &&
!domainEntry.IsSampledForLongerRetention(workflowID) {
return nil
}
}
request := &persistence.RecordWorkflowExecutionStartedRequest{
DomainUUID: domainID,
Domain: domain,
Execution: types.WorkflowExecution{
WorkflowID: workflowID,
RunID: runID,
},
WorkflowTypeName: workflowTypeName,
StartTimestamp: startTimeUnixNano,
ExecutionTimestamp: executionTimeUnixNano,
WorkflowTimeout: int64(workflowTimeout),
TaskID: taskID,
Memo: visibilityMemo,
TaskList: taskList,
IsCron: isCron,
NumClusters: numClusters,
UpdateTimestamp: updateTimeUnixNano,
SearchAttributes: searchAttributes,
ShardID: int16(t.shard.GetShardID()),
}
if t.config.EnableRecordWorkflowExecutionUninitialized(domain) {
uninitializedRequest := &persistence.RecordWorkflowExecutionUninitializedRequest{
DomainUUID: domainID,
Domain: domain,
Execution: types.WorkflowExecution{
WorkflowID: workflowID,
RunID: runID,
},
WorkflowTypeName: workflowTypeName,
UpdateTimestamp: updateTimeUnixNano,
ShardID: int64(t.shard.GetShardID()),
}
if err := t.visibilityMgr.RecordWorkflowExecutionUninitialized(ctx, uninitializedRequest); err != nil {
t.logger.Error("Failed to record uninitialized workflow execution", tag.Error(err))
}
}
return t.visibilityMgr.RecordWorkflowExecutionStarted(ctx, request)
}
func (t *transferTaskExecutorBase) upsertWorkflowExecution(
ctx context.Context,
domainID string,
workflowID string,
runID string,
workflowTypeName string,
startTimeUnixNano int64,
executionTimeUnixNano int64,
workflowTimeout int32,
taskID int64,
taskList string,
visibilityMemo *types.Memo,
isCron bool,
numClusters int16,
updateTimeUnixNano int64,
searchAttributes map[string][]byte,
) error {
domain, err := t.shard.GetDomainCache().GetDomainName(domainID)
if err != nil {
if _, ok := err.(*types.EntityNotExistsError); !ok {
return err
}
domain = defaultDomainName
}
request := &persistence.UpsertWorkflowExecutionRequest{
DomainUUID: domainID,
Domain: domain,
Execution: types.WorkflowExecution{
WorkflowID: workflowID,
RunID: runID,
},
WorkflowTypeName: workflowTypeName,
StartTimestamp: startTimeUnixNano,
ExecutionTimestamp: executionTimeUnixNano,
WorkflowTimeout: int64(workflowTimeout),
TaskID: taskID,
Memo: visibilityMemo,
TaskList: taskList,
IsCron: isCron,
NumClusters: numClusters,
SearchAttributes: searchAttributes,
UpdateTimestamp: updateTimeUnixNano,
ShardID: int64(t.shard.GetShardID()),
}
return t.visibilityMgr.UpsertWorkflowExecution(ctx, request)
}
func (t *transferTaskExecutorBase) recordWorkflowClosed(
ctx context.Context,
domainID string,
workflowID string,
runID string,
workflowTypeName string,
startTimeUnixNano int64,
executionTimeUnixNano int64,
endTimeUnixNano int64,
closeStatus types.WorkflowExecutionCloseStatus,
historyLength int64,
taskID int64,
visibilityMemo *types.Memo,
taskList string,
isCron bool,
numClusters int16,
updateTimeUnixNano int64,
searchAttributes map[string][]byte,
) error {
// Record closing in visibility store
retentionSeconds := int64(0)
domain := defaultDomainName
recordWorkflowClose := true
archiveVisibility := false
domainEntry, err := t.shard.GetDomainCache().GetDomainByID(domainID)
if err != nil && !isWorkflowNotExistError(err) {
return err
}
if err == nil {
// retention in domain config is in days, convert to seconds
retentionSeconds = int64(domainEntry.GetRetentionDays(workflowID)) * int64(secondsInDay)
domain = domainEntry.GetInfo().Name
// if sampled for longer retention is enabled, only record those sampled events
if domainEntry.IsSampledForLongerRetentionEnabled(workflowID) &&
!domainEntry.IsSampledForLongerRetention(workflowID) {
recordWorkflowClose = false
}
clusterConfiguredForVisibilityArchival := t.shard.GetService().GetArchivalMetadata().GetVisibilityConfig().ClusterConfiguredForArchival()
domainConfiguredForVisibilityArchival := domainEntry.GetConfig().VisibilityArchivalStatus == types.ArchivalStatusEnabled
archiveVisibility = clusterConfiguredForVisibilityArchival && domainConfiguredForVisibilityArchival
}
if recordWorkflowClose {
if err := t.visibilityMgr.RecordWorkflowExecutionClosed(ctx, &persistence.RecordWorkflowExecutionClosedRequest{
DomainUUID: domainID,
Domain: domain,
Execution: types.WorkflowExecution{
WorkflowID: workflowID,
RunID: runID,
},
WorkflowTypeName: workflowTypeName,
StartTimestamp: startTimeUnixNano,
ExecutionTimestamp: executionTimeUnixNano,
CloseTimestamp: endTimeUnixNano,
Status: closeStatus,
HistoryLength: historyLength,
RetentionSeconds: retentionSeconds,
TaskID: taskID,
Memo: visibilityMemo,
TaskList: taskList,
SearchAttributes: searchAttributes,
IsCron: isCron,
UpdateTimestamp: updateTimeUnixNano,
NumClusters: numClusters,
ShardID: int16(t.shard.GetShardID()),
}); err != nil {
return err
}
}
if archiveVisibility {
archiveCtx, cancel := context.WithTimeout(ctx, t.config.TransferProcessorVisibilityArchivalTimeLimit())
defer cancel()
_, err := t.archiverClient.Archive(archiveCtx, &archiver.ClientRequest{
ArchiveRequest: &archiver.ArchiveRequest{
DomainID: domainID,
DomainName: domain,
WorkflowID: workflowID,
RunID: runID,
WorkflowTypeName: workflowTypeName,
StartTimestamp: startTimeUnixNano,
ExecutionTimestamp: executionTimeUnixNano,
CloseTimestamp: endTimeUnixNano,
CloseStatus: closeStatus,
HistoryLength: historyLength,
Memo: visibilityMemo,
SearchAttributes: searchAttributes,
VisibilityURI: domainEntry.GetConfig().VisibilityArchivalURI,
URI: domainEntry.GetConfig().HistoryArchivalURI,
Targets: []archiver.ArchivalTarget{archiver.ArchiveTargetVisibility},
},
CallerService: service.History,
AttemptArchiveInline: true, // archive visibility inline by default
})
return err
}
return nil
}
// Argument startEvent is to save additional call of msBuilder.GetStartEvent
func getWorkflowExecutionTimestamp(
msBuilder execution.MutableState,
startEvent *types.HistoryEvent,
) time.Time {
// Use value 0 to represent workflows that don't need backoff. Since ES doesn't support
// comparison between two field, we need a value to differentiate them from cron workflows
// or later runs of a workflow that needs retry.
executionTimestamp := time.Unix(0, 0)
if startEvent == nil {
return executionTimestamp
}
if backoffSeconds := startEvent.WorkflowExecutionStartedEventAttributes.GetFirstDecisionTaskBackoffSeconds(); backoffSeconds != 0 {
startTimestamp := time.Unix(0, startEvent.GetTimestamp())
executionTimestamp = startTimestamp.Add(time.Duration(backoffSeconds) * time.Second)
}
return executionTimestamp
}
func getWorkflowMemo(
memo map[string][]byte,
) *types.Memo {
if memo == nil {
return nil
}
return &types.Memo{Fields: memo}
}
func copySearchAttributes(
input map[string][]byte,
) map[string][]byte {
if input == nil {
return nil
}
result := make(map[string][]byte)
for k, v := range input {
val := make([]byte, len(v))
copy(val, v)
result[k] = val
}
return result
}
func isWorkflowNotExistError(err error) bool {
_, ok := err.(*types.EntityNotExistsError)
return ok
}