-
Notifications
You must be signed in to change notification settings - Fork 758
/
executable.go
452 lines (375 loc) · 13.6 KB
/
executable.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
// 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 executable_mock.go
package queues
import (
"context"
"sync"
"time"
"go.temporal.io/api/serviceerror"
"go.temporal.io/server/common"
"go.temporal.io/server/common/backoff"
"go.temporal.io/server/common/clock"
"go.temporal.io/server/common/dynamicconfig"
"go.temporal.io/server/common/headers"
"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"
ctasks "go.temporal.io/server/common/tasks"
"go.temporal.io/server/common/util"
"go.temporal.io/server/service/history/consts"
"go.temporal.io/server/service/history/shard"
"go.temporal.io/server/service/history/tasks"
)
type (
Executable interface {
ctasks.Task
tasks.Task
Attempt() int
GetTask() tasks.Task
GetPriority() ctasks.Priority
GetScheduledTime() time.Time
SetScheduledTime(time.Time)
}
Executor interface {
// TODO: remove isActive return value after deprecating
// active/standby queue processing logic
Execute(context.Context, Executable) (tags []metrics.Tag, isActive bool, err error)
}
// TaskFilter determines if the given task should be executed
// TODO: remove after merging active/standby queue processor
// task should always be executed as active or verified as standby
TaskFilter func(task tasks.Task) bool
)
var (
// schedulerRetryPolicy is the retry policy for retrying the executable
// in one submission to scheduler, the goroutine for processing this executable
// is held during the retry
schedulerRetryPolicy = common.CreateTaskProcessingRetryPolicy()
// reschedulePolicy is the policy for determine reschedule backoff duration
// across multiple submissions to scheduler
reschedulePolicy = common.CreateTaskReschedulePolicy()
taskNotReadyReschedulePolicy = common.CreateTaskNotReadyReschedulePolicy()
)
const (
// resubmitMaxAttempts is the max number of attempts we may skip rescheduler when a task is Nacked.
// check the comment in shouldResubmitOnNack() for more details
resubmitMaxAttempts = 10
)
type (
executableImpl struct {
tasks.Task
sync.Mutex
state ctasks.State
priority ctasks.Priority // priority for the current attempt
lowestPriority ctasks.Priority // priority for emitting metrics across multiple attempts
attempt int
executor Executor
scheduler Scheduler
rescheduler Rescheduler
priorityAssigner PriorityAssigner
timeSource clock.TimeSource
namespaceRegistry namespace.Registry
readerID int32
loadTime time.Time
scheduledTime time.Time
userLatency time.Duration
lastActiveness bool
logger log.Logger
metricsHandler metrics.MetricsHandler
taggedMetricsHandler metrics.MetricsHandler
criticalRetryAttempt dynamicconfig.IntPropertyFn
namespaceCacheRefreshInterval dynamicconfig.DurationPropertyFn
filter TaskFilter
shouldProcess bool
}
)
// TODO: Remove filter, queueType, and namespaceCacheRefreshInterval
// parameters after deprecating old queue processing logic.
// CriticalRetryAttempt probably should also be removed as it's only
// used for emiting logs and metrics when # of attempts is high, and
// doesn't have to be a dynamic config.
func NewExecutable(
readerID int32,
task tasks.Task,
filter TaskFilter,
executor Executor,
scheduler Scheduler,
rescheduler Rescheduler,
priorityAssigner PriorityAssigner,
timeSource clock.TimeSource,
namespaceRegistry namespace.Registry,
logger log.Logger,
metricsHandler metrics.MetricsHandler,
criticalRetryAttempt dynamicconfig.IntPropertyFn,
namespaceCacheRefreshInterval dynamicconfig.DurationPropertyFn,
) Executable {
executable := &executableImpl{
Task: task,
state: ctasks.TaskStatePending,
attempt: 1,
executor: executor,
scheduler: scheduler,
rescheduler: rescheduler,
priorityAssigner: priorityAssigner,
timeSource: timeSource,
namespaceRegistry: namespaceRegistry,
readerID: readerID,
loadTime: util.MaxTime(timeSource.Now(), task.GetKey().FireTime),
logger: log.NewLazyLogger(
logger,
func() []tag.Tag {
return tasks.Tags(task)
},
),
metricsHandler: metricsHandler,
criticalRetryAttempt: criticalRetryAttempt,
filter: filter,
namespaceCacheRefreshInterval: namespaceCacheRefreshInterval,
}
executable.updatePriority()
return executable
}
func (e *executableImpl) Execute() error {
if e.State() == ctasks.TaskStateCancelled {
return nil
}
// this filter should also contain the logic for overriding
// results from task allocator (force executing some standby task types)
e.shouldProcess = true
if e.filter != nil {
if e.shouldProcess = e.filter(e.Task); !e.shouldProcess {
return nil
}
}
ctx := metrics.AddMetricsContext(context.Background())
namespace, _ := e.namespaceRegistry.GetNamespaceName(namespace.ID(e.GetNamespaceID()))
ctx = headers.SetCallerInfo(ctx, headers.NewBackgroundCallerInfo(namespace.String()))
startTime := e.timeSource.Now()
metricsTags, isActive, err := e.executor.Execute(ctx, e)
e.taggedMetricsHandler = e.metricsHandler.WithTags(metricsTags...)
if isActive != e.lastActiveness {
// namespace did a failover, reset task attempt
e.Lock()
e.attempt = 0
e.Unlock()
}
e.lastActiveness = isActive
var userLatency time.Duration
if duration, ok := metrics.ContextCounterGet(ctx, metrics.HistoryWorkflowExecutionCacheLatency); ok {
userLatency = time.Duration(duration)
}
e.userLatency += userLatency
e.taggedMetricsHandler.Timer(TaskProcessingLatency).Record(time.Since(startTime))
e.taggedMetricsHandler.Timer(TaskNoUserProcessingLatency).Record(time.Since(startTime) - userLatency)
priorityTaggedProvider := e.taggedMetricsHandler.WithTags(metrics.TaskPriorityTag(e.priority.String()))
priorityTaggedProvider.Counter(TaskRequests).Record(1)
priorityTaggedProvider.Timer(TaskScheduleLatency).Record(e.scheduledTime.Sub(startTime))
return err
}
func (e *executableImpl) HandleErr(err error) (retErr error) {
defer func() {
if retErr != nil {
e.Lock()
defer e.Unlock()
e.attempt++
if e.attempt > e.criticalRetryAttempt() {
e.metricsHandler.Histogram(TaskAttempt, metrics.Dimensionless).Record(int64(e.attempt))
e.logger.Error("Critical error processing task, retrying.", tag.Error(err), tag.OperationCritical)
}
}
}()
if err == nil {
return nil
}
if _, isNotFound := err.(*serviceerror.NotFound); isNotFound {
return nil
}
// This means that namespace is deleted, and it is safe to drop the task (=ignore the error).
if _, isNotFound := err.(*serviceerror.NamespaceNotFound); isNotFound {
return nil
}
if err == consts.ErrTaskRetry {
e.metricsHandler.Counter(TaskStandbyRetryCounter).Record(1)
return err
}
if err == consts.ErrWorkflowBusy {
e.metricsHandler.Counter(TaskWorkflowBusyCounter).Record(1)
return err
}
if err == consts.ErrTaskDiscarded {
e.metricsHandler.Counter(TaskDiscarded).Record(1)
return nil
}
// this is a transient error
// TODO remove this error check special case
// since the new task life cycle will not give up until task processed / verified
if _, ok := err.(*serviceerror.NamespaceNotActive); ok {
if e.timeSource.Now().Sub(e.loadTime) > 2*e.namespaceCacheRefreshInterval() {
e.metricsHandler.Counter(TaskNotActiveCounter).Record(1)
return nil
}
return err
}
e.metricsHandler.Counter(TaskFailures).Record(1)
e.logger.Error("Fail to process task", tag.Error(err), tag.LifeCycleProcessingFailed)
return err
}
func (e *executableImpl) IsRetryableError(err error) bool {
// this determines if the executable should be retried when hold the worker goroutine
if e.State() == ctasks.TaskStateCancelled {
return false
}
if shard.IsShardOwnershipLostError(err) {
return false
}
// don't retry immediately for resource exhausted which may incur more load
// context deadline exceed may also suggested downstream is overloaded, so don't retry immediately
if common.IsResourceExhausted(err) || common.IsContextDeadlineExceededErr(err) {
return false
}
// ErrTaskRetry means mutable state is not ready for standby task processing
// there's no point for retrying the task immediately which will hold the worker corouinte
// TODO: change ErrTaskRetry to a better name
return err != consts.ErrTaskRetry && err != consts.ErrWorkflowBusy
}
func (e *executableImpl) RetryPolicy() backoff.RetryPolicy {
// this is the retry policy for one submission
// not for calculating the backoff after the task is nacked
return schedulerRetryPolicy
}
func (e *executableImpl) Cancel() {
e.Lock()
defer e.Unlock()
if e.state == ctasks.TaskStatePending {
e.state = ctasks.TaskStateCancelled
}
}
func (e *executableImpl) Ack() {
e.Lock()
defer e.Unlock()
if e.state == ctasks.TaskStateCancelled {
return
}
e.state = ctasks.TaskStateAcked
if e.shouldProcess {
e.taggedMetricsHandler.Timer(TaskLoadLatency).Record(
e.loadTime.Sub(e.GetVisibilityTime()),
metrics.QueueReaderIDTag(e.readerID),
)
e.taggedMetricsHandler.Histogram(TaskAttempt, metrics.Dimensionless).Record(int64(e.attempt))
priorityTaggedProvider := e.taggedMetricsHandler.WithTags(metrics.TaskPriorityTag(e.lowestPriority.String()))
priorityTaggedProvider.Timer(TaskLatency).Record(time.Since(e.loadTime))
priorityTaggedProvider.Timer(TaskUserLatency).Record(e.userLatency)
priorityTaggedProvider.Timer(TaskNoUserLatency).Record(time.Since(e.loadTime) - e.userLatency)
readerIDTaggedProvider := priorityTaggedProvider.WithTags(metrics.QueueReaderIDTag(e.readerID))
readerIDTaggedProvider.Timer(TaskQueueLatency).Record(time.Since(e.GetVisibilityTime()))
readerIDTaggedProvider.Timer(TaskNoUserQueueLatency).Record(time.Since(e.GetVisibilityTime()) - e.userLatency)
}
}
func (e *executableImpl) Nack(err error) {
if e.State() == ctasks.TaskStateCancelled {
return
}
e.updatePriority()
submitted := false
if e.shouldResubmitOnNack(e.Attempt(), err) {
// we do not need to know if there any error during submission
// as long as it's not submitted, the execuable should be add
// to the rescheduler
e.SetScheduledTime(e.timeSource.Now())
submitted = e.scheduler.TrySubmit(e)
}
if !submitted {
e.rescheduler.Add(e, e.rescheduleTime(err, e.Attempt()))
}
}
func (e *executableImpl) Reschedule() {
if e.State() == ctasks.TaskStateCancelled {
return
}
e.updatePriority()
e.rescheduler.Add(e, e.rescheduleTime(nil, e.Attempt()))
}
func (e *executableImpl) State() ctasks.State {
e.Lock()
defer e.Unlock()
return e.state
}
func (e *executableImpl) GetPriority() ctasks.Priority {
e.Lock()
defer e.Unlock()
return e.priority
}
func (e *executableImpl) Attempt() int {
e.Lock()
defer e.Unlock()
return e.attempt
}
func (e *executableImpl) GetTask() tasks.Task {
return e.Task
}
func (e *executableImpl) GetScheduledTime() time.Time {
return e.scheduledTime
}
func (e *executableImpl) SetScheduledTime(t time.Time) {
e.scheduledTime = t
}
func (e *executableImpl) shouldResubmitOnNack(attempt int, err error) bool {
// this is an optimization for skipping rescheduler and retry the task sooner.
// this is useful for errors like workflow busy, which doesn't have to wait for
// the longer rescheduling backoff.
if e.Attempt() > resubmitMaxAttempts {
return false
}
if shard.IsShardOwnershipLostError(err) {
return false
}
return err != consts.ErrTaskRetry
}
func (e *executableImpl) rescheduleTime(
err error,
attempt int,
) time.Time {
// elapsedTime (the first parameter in ComputeNextDelay) is not relevant here
// since reschedule policy has no expiration interval.
if err == consts.ErrTaskRetry {
// using a different reschedule policy to slow down retry
// as the error means mutable state is not ready to handle the task,
// need to wait for replication.
e.timeSource.Now().Add(taskNotReadyReschedulePolicy.ComputeNextDelay(0, attempt))
}
return e.timeSource.Now().Add(reschedulePolicy.ComputeNextDelay(0, attempt))
}
func (e *executableImpl) updatePriority() {
// do NOT invoke Assign while holding the lock
newPriority := e.priorityAssigner.Assign(e)
e.Lock()
defer e.Unlock()
e.priority = newPriority
if e.priority > e.lowestPriority {
e.lowestPriority = e.priority
}
}