-
Notifications
You must be signed in to change notification settings - Fork 833
/
task.go
292 lines (267 loc) · 9.5 KB
/
task.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
// 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 executions
import (
"context"
"time"
commonpb "go.temporal.io/api/common/v1"
"go.temporal.io/api/serviceerror"
"go.temporal.io/server/api/adminservice/v1"
"go.temporal.io/server/api/historyservice/v1"
persistencespb "go.temporal.io/server/api/persistence/v1"
"go.temporal.io/server/common/backoff"
"go.temporal.io/server/common/collection"
"go.temporal.io/server/common/dynamicconfig"
"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/quotas"
"go.temporal.io/server/service/worker/scanner/executor"
)
const (
executionsPageSize = 100
taskStartupDelayRatio = 100 * time.Millisecond
taskStartupDelayRandomizationRatio = 1.0
)
type (
// task is a runnable task that adheres to the executor.Task interface
// for the scavenger, each of this task processes a single workflow mutableState
task struct {
shardID int32
executionManager persistence.ExecutionManager
registry namespace.Registry
historyClient historyservice.HistoryServiceClient
adminClient adminservice.AdminServiceClient
metricsHandler metrics.MetricsHandler
logger log.Logger
scavenger *Scavenger
ctx context.Context
rateLimiter quotas.RateLimiter
executionDataDurationBuffer dynamicconfig.DurationPropertyFn
paginationToken []byte
}
)
// newTask returns a new instance of an executable task which will process a single mutableState
func newTask(
ctx context.Context,
shardID int32,
executionManager persistence.ExecutionManager,
registry namespace.Registry,
historyClient historyservice.HistoryServiceClient,
adminClient adminservice.AdminServiceClient,
metricsHandler metrics.MetricsHandler,
logger log.Logger,
scavenger *Scavenger,
rateLimiter quotas.RateLimiter,
executionDataDurationBuffer dynamicconfig.DurationPropertyFn,
) executor.Task {
return &task{
shardID: shardID,
executionManager: executionManager,
registry: registry,
historyClient: historyClient,
adminClient: adminClient,
metricsHandler: metricsHandler.WithTags(metrics.OperationTag(metrics.ExecutionsScavengerScope)),
logger: logger,
scavenger: scavenger,
ctx: ctx,
rateLimiter: rateLimiter,
executionDataDurationBuffer: executionDataDurationBuffer,
}
}
// Run runs the task
func (t *task) Run() executor.TaskStatus {
time.Sleep(backoff.JitDuration(
taskStartupDelayRatio*time.Duration(t.scavenger.numHistoryShards),
taskStartupDelayRandomizationRatio,
))
iter := collection.NewPagingIteratorWithToken(t.getPaginationFn(), t.paginationToken)
var retryTask bool
for iter.HasNext() {
_ = t.rateLimiter.Wait(t.ctx)
record, err := iter.Next()
if err != nil {
t.metricsHandler.Counter(metrics.ScavengerValidationSkipsCount.GetMetricName()).Record(1)
// continue validation process and retry after all workflow records has been iterated.
t.logger.Error("unable to paginate concrete execution", tag.ShardID(t.shardID), tag.Error(err))
retryTask = true
}
mutableState := &MutableState{WorkflowMutableState: record}
results := t.validate(mutableState)
printValidationResult(
mutableState,
results,
t.metricsHandler,
t.logger,
)
err = t.handleFailures(mutableState, results)
if err != nil {
// continue validation process and retry after all workflow records has been iterated.
executionInfo := mutableState.GetExecutionInfo()
t.metricsHandler.Counter(metrics.ScavengerValidationSkipsCount.GetMetricName()).Record(1)
t.logger.Error("unable to process failure result",
tag.ShardID(t.shardID),
tag.Error(err),
tag.WorkflowNamespaceID(executionInfo.GetNamespaceId()),
tag.WorkflowID(executionInfo.GetWorkflowId()),
tag.WorkflowRunID(mutableState.GetExecutionState().GetRunId()))
retryTask = true
}
}
if retryTask {
return executor.TaskStatusDefer
}
return executor.TaskStatusDone
}
func (t *task) validate(
mutableState *MutableState,
) []MutableStateValidationResult {
var results []MutableStateValidationResult
t.logger.Debug("validating mutable state",
tag.ShardID(t.shardID),
tag.WorkflowNamespaceID(mutableState.GetExecutionInfo().GetNamespaceId()),
tag.WorkflowID(mutableState.GetExecutionInfo().GetWorkflowId()),
tag.WorkflowRunID(mutableState.GetExecutionState().GetRunId()),
)
if validationResults, err := NewMutableStateValidator(
t.registry,
t.executionDataDurationBuffer,
).Validate(
t.ctx,
mutableState,
); err != nil {
t.logger.Error("unable to validate mutable state ID",
tag.ShardID(t.shardID),
tag.WorkflowNamespaceID(mutableState.GetExecutionInfo().GetNamespaceId()),
tag.WorkflowID(mutableState.GetExecutionInfo().GetWorkflowId()),
tag.WorkflowRunID(mutableState.GetExecutionState().GetRunId()),
tag.Error(err),
)
} else {
results = append(results, validationResults...)
}
// Fail fast if the mutable is corrupted, no need to validate history.
if len(results) > 0 {
return results
}
if validationResults, err := NewHistoryEventIDValidator(
t.shardID,
t.executionManager,
).Validate(t.ctx, mutableState); err != nil {
t.logger.Error("unable to validate history event ID being contiguous",
tag.ShardID(t.shardID),
tag.WorkflowNamespaceID(mutableState.GetExecutionInfo().GetNamespaceId()),
tag.WorkflowID(mutableState.GetExecutionInfo().GetWorkflowId()),
tag.WorkflowRunID(mutableState.GetExecutionState().GetRunId()),
tag.Error(err),
)
} else {
results = append(results, validationResults...)
}
return results
}
func (t *task) getPaginationFn() collection.PaginationFn[*persistencespb.WorkflowMutableState] {
return func(paginationToken []byte) ([]*persistencespb.WorkflowMutableState, []byte, error) {
req := &persistence.ListConcreteExecutionsRequest{
ShardID: t.shardID,
PageSize: executionsPageSize,
PageToken: paginationToken,
}
resp, err := t.executionManager.ListConcreteExecutions(t.ctx, req)
if err != nil {
return nil, nil, err
}
paginateItems := resp.States
t.paginationToken = resp.PageToken
return paginateItems, resp.PageToken, nil
}
}
func (t *task) handleFailures(
mutableState *MutableState,
results []MutableStateValidationResult,
) error {
for _, failure := range results {
switch failure.failureType {
case mutableStateRetentionFailureType:
executionInfo := mutableState.GetExecutionInfo()
runID := mutableState.GetExecutionState().GetRunId()
ns, err := t.registry.GetNamespaceByID(namespace.ID(executionInfo.GetNamespaceId()))
switch err.(type) {
case *serviceerror.NotFound,
*serviceerror.NamespaceNotFound:
t.logger.Error("Garbage data in DB after namespace is deleted", tag.WorkflowNamespaceID(executionInfo.GetNamespaceId()))
// We cannot do much in this case. It just ignores this error.
return nil
case nil:
// continue to delete
default:
return err
}
_, err = t.adminClient.DeleteWorkflowExecution(t.ctx, &adminservice.DeleteWorkflowExecutionRequest{
Namespace: ns.Name().String(),
Execution: &commonpb.WorkflowExecution{
WorkflowId: executionInfo.GetWorkflowId(),
RunId: runID,
},
})
switch err.(type) {
case *serviceerror.NotFound,
*serviceerror.NamespaceNotFound:
return nil
case nil:
continue
default:
return err
}
default:
// no-op
continue
}
}
return nil
}
func printValidationResult(
mutableState *MutableState,
results []MutableStateValidationResult,
metricsHandler metrics.MetricsHandler,
logger log.Logger,
) {
metricsHandler.Counter(metrics.ScavengerValidationRequestsCount.GetMetricName()).Record(1)
if len(results) == 0 {
return
}
metricsHandler.Counter(metrics.ScavengerValidationFailuresCount.GetMetricName()).Record(1)
for _, result := range results {
metricsHandler.Counter(metrics.ScavengerValidationFailuresCount.GetMetricName()).Record(1, metrics.FailureTag(result.failureType))
logger.Info(
"validation failed for execution.",
tag.WorkflowNamespaceID(mutableState.GetExecutionInfo().GetNamespaceId()),
tag.WorkflowID(mutableState.GetExecutionInfo().GetWorkflowId()),
tag.WorkflowRunID(mutableState.GetExecutionState().GetRunId()),
tag.Value(result.failureDetails),
)
}
}