/
workflow_shadower_activities.go
245 lines (212 loc) · 7.79 KB
/
workflow_shadower_activities.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
// Copyright (c) 2017-2021 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 internal
import (
"context"
"math/rand"
"strings"
"time"
"go.uber.org/zap"
"go.uber.org/cadence/.gen/go/cadence/workflowserviceclient"
"go.uber.org/cadence/.gen/go/shadower"
"go.uber.org/cadence/.gen/go/shared"
"go.uber.org/cadence/internal/common"
"go.uber.org/cadence/internal/common/backoff"
"go.uber.org/cadence/internal/common/metrics"
)
type (
replayWorkflowActivityProgress struct {
Result shadower.ReplayWorkflowActivityResult
NextExecutionIdx int
}
)
const (
serviceClientContextKey contextKey = "serviceClient"
workflowReplayerContextKey contextKey = "workflowReplayer"
)
const (
minScanWorkflowResultSize = 10
ratioToCompleteScanWorkflow = 0.8
scanWorkflowWaitPeriod = 100 * time.Millisecond
)
func scanWorkflowActivity(
ctx context.Context,
params shadower.ScanWorkflowActivityParams,
) (shadower.ScanWorkflowActivityResult, error) {
logger := GetActivityLogger(ctx)
service := ctx.Value(serviceClientContextKey).(workflowserviceclient.Interface)
scanResult, err := scanWorkflowExecutionsHelper(ctx, service, params, logger)
switch err.(type) {
case *shared.EntityNotExistsError:
err = NewCustomError(shadower.ErrReasonDomainNotExists, err.Error())
case *shared.BadRequestError:
err = NewCustomError(shadower.ErrReasonInvalidQuery, err.Error())
}
return scanResult, err
}
func scanWorkflowExecutionsHelper(
ctx context.Context,
service workflowserviceclient.Interface,
params shadower.ScanWorkflowActivityParams,
logger *zap.Logger,
) (shadower.ScanWorkflowActivityResult, error) {
var completionTime time.Time
if deadline, ok := ctx.Deadline(); ok {
now := time.Now()
activityTimeout := deadline.Sub(now)
completionTime = now.Add(time.Duration(ratioToCompleteScanWorkflow * float32(activityTimeout)))
}
request := &shared.ListWorkflowExecutionsRequest{
Domain: params.Domain,
Query: params.WorkflowQuery,
NextPageToken: params.NextPageToken,
PageSize: params.PageSize,
}
result := shadower.ScanWorkflowActivityResult{}
for {
var resp *shared.ListWorkflowExecutionsResponse
if err := backoff.Retry(ctx,
func() error {
tchCtx, cancel, opt := newChannelContext(ctx, FeatureFlags{})
var err error
resp, err = service.ScanWorkflowExecutions(tchCtx, request, opt...)
cancel()
return err
},
createDynamicServiceRetryPolicy(ctx),
isServiceTransientError,
); err != nil {
logger.Error("Failed to scan workflow executions",
zap.String(tagDomain, params.GetDomain()),
zap.String(tagVisibilityQuery, params.GetWorkflowQuery()),
zap.Error(err),
)
return shadower.ScanWorkflowActivityResult{}, err
}
for _, execution := range resp.Executions {
if shouldReplay(params.GetSamplingRate()) {
result.Executions = append(result.Executions, execution.Execution)
}
}
request.NextPageToken = resp.NextPageToken
if len(request.NextPageToken) == 0 ||
len(result.Executions) >= minScanWorkflowResultSize ||
(!completionTime.IsZero() && time.Now().After(completionTime)) {
result.NextPageToken = request.NextPageToken
break
}
time.Sleep(scanWorkflowWaitPeriod)
}
return result, nil
}
func shouldReplay(probability float64) bool {
if probability == 0 {
return true
}
return rand.Float64() <= probability
}
func replayWorkflowActivity(
ctx context.Context,
params shadower.ReplayWorkflowActivityParams,
) (shadower.ReplayWorkflowActivityResult, error) {
logger := GetActivityLogger(ctx)
scope := tagScope(GetActivityMetricsScope(ctx), tagDomain, params.GetDomain(), tagTaskList, GetActivityInfo(ctx).TaskList)
service := ctx.Value(serviceClientContextKey).(workflowserviceclient.Interface)
replayer := ctx.Value(workflowReplayerContextKey).(*WorkflowReplayer)
var progress replayWorkflowActivityProgress
if err := GetHeartbeatDetails(ctx, &progress); err != nil {
progress = replayWorkflowActivityProgress{
NextExecutionIdx: 0,
Result: shadower.ReplayWorkflowActivityResult{
Succeeded: common.Int32Ptr(0),
Skipped: common.Int32Ptr(0),
Failed: common.Int32Ptr(0),
},
}
}
// following code assumes all pointers in progress.Result are not nil, this is ensured by:
// 1. if not previous progress, init to pointer to 0
// 2. if has previous progress, the progress uploaded during heartbeat has non nil pointers
for _, execution := range params.Executions[progress.NextExecutionIdx:] {
if execution == nil {
continue
}
sw := scope.Timer(metrics.ReplayLatency).Start()
success, err := replayWorkflowExecutionHelper(ctx, replayer, service, logger, params.GetDomain(), WorkflowExecution{
ID: execution.GetWorkflowId(),
RunID: execution.GetRunId(),
})
if err != nil {
scope.Counter(metrics.ReplayFailedCounter).Inc(1)
*progress.Result.Failed++
if isWorkflowTypeNotRegisteredError(err) {
// this should fail the replay workflow as it requires worker deployment to fix the workflow registration.
return progress.Result, NewCustomError(shadower.ErrReasonWorkflowTypeNotRegistered, err.Error())
}
} else if success {
scope.Counter(metrics.ReplaySucceedCounter).Inc(1)
*progress.Result.Succeeded++
} else {
scope.Counter(metrics.ReplaySkippedCounter).Inc(1)
*progress.Result.Skipped++
}
sw.Stop()
progress.NextExecutionIdx++
RecordActivityHeartbeat(ctx, progress)
}
return progress.Result, nil
}
func replayWorkflowExecutionHelper(
ctx context.Context,
replayer *WorkflowReplayer,
service workflowserviceclient.Interface,
logger *zap.Logger,
domain string,
execution WorkflowExecution,
) (bool, error) {
taggedLogger := logger.With(
zap.String(tagWorkflowID, execution.ID),
zap.String(tagRunID, execution.RunID),
)
err := replayer.ReplayWorkflowExecution(ctx, service, logger, domain, execution)
if err == nil {
taggedLogger.Info("Successfully replayed workflow")
return true, nil
}
if isNondeterministicErr(err) || isWorkflowTypeNotRegisteredError(err) {
taggedLogger.Error("Replay workflow failed", zap.Error(err))
return false, err
}
taggedLogger.Info("Skipped replaying workflow", zap.Error(err))
return false, nil
}
func isNondeterministicErr(err error) bool {
// There're a few expected replay errors, for example:
// 1. errReplayHistoryTooShort
// 2. workflow not exist
// 3. internal service error when reading workflow history
// since we can't get an exhaustive list of expected errors, we only treat replay as failed
// when we are sure the error is due to non-determinisim to make sure there's no false positive.
// as shadowing doesn't guarantee to catch all nondeterministic errors.
return strings.Contains(err.Error(), "nondeterministic")
}
func isWorkflowTypeNotRegisteredError(err error) bool {
return strings.Contains(err.Error(), errMsgUnknownWorkflowType)
}