/
scavenger.go
312 lines (281 loc) · 8.76 KB
/
scavenger.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
// Copyright (c) 2019 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 history
import (
"context"
"time"
"go.uber.org/cadence/activity"
"golang.org/x/time/rate"
"github.com/uber/cadence/.gen/go/history"
"github.com/uber/cadence/.gen/go/history/historyserviceclient"
"github.com/uber/cadence/.gen/go/shared"
"github.com/uber/cadence/common"
"github.com/uber/cadence/common/log"
"github.com/uber/cadence/common/log/tag"
"github.com/uber/cadence/common/metrics"
p "github.com/uber/cadence/common/persistence"
)
type (
// ScavengerHeartbeatDetails is the heartbeat detail for HistoryScavengerActivity
ScavengerHeartbeatDetails struct {
NextPageToken []byte
CurrentPage int
SkipCount int
ErrorCount int
SuccCount int
}
// Scavenger is the type that holds the state for history scavenger daemon
Scavenger struct {
db p.HistoryManager
client historyserviceclient.Interface
hbd ScavengerHeartbeatDetails
rps int
limiter *rate.Limiter
metrics metrics.Client
logger log.Logger
isInTest bool
}
taskDetail struct {
domainID string
workflowID string
runID string
treeID string
branchID string
// passing along the current heartbeat details to make heartbeat within a task so that it won't timeout
hbd ScavengerHeartbeatDetails
}
)
const (
// used this to decide how many goroutines to process
rpsPerConcurrency = 50
pageSize = 1000
// only clean up history branches that older than this threshold
// we double the MaxWorkflowRetentionPeriodInDays to avoid racing condition with history archival.
// Our history archiver delete mutable state, and then upload history to blob store and then delete history.
// This scanner will face racing condition with archiver because it relys on describe mutable state returning entityNotExist error.
// That's why we need to keep MaxWorkflowRetentionPeriodInDays stable and not decreasing all the time.
cleanUpThreshold = time.Hour * 24 * common.MaxWorkflowRetentionPeriodInDays * 2
)
// NewScavenger returns an instance of history scavenger daemon
// The Scavenger can be started by calling the Run() method on the
// returned object. Calling the Run() method will result in one
// complete iteration over all of the history branches in the system. For
// each branch, the scavenger will attempt
// - describe the corresponding workflow execution
// - deletion of history itself, if there are no workflow execution
func NewScavenger(
db p.HistoryManager,
rps int,
client historyserviceclient.Interface,
hbd ScavengerHeartbeatDetails,
metricsClient metrics.Client,
logger log.Logger,
) *Scavenger {
rateLimiter := rate.NewLimiter(rate.Limit(rps), rps)
return &Scavenger{
db: db,
client: client,
hbd: hbd,
rps: rps,
limiter: rateLimiter,
metrics: metricsClient,
logger: logger,
}
}
// Run runs the scavenger
func (s *Scavenger) Run(ctx context.Context) (ScavengerHeartbeatDetails, error) {
taskCh := make(chan taskDetail, pageSize)
respCh := make(chan error, pageSize)
concurrency := s.rps/rpsPerConcurrency + 1
for i := 0; i < concurrency; i++ {
go s.startTaskProcessor(ctx, taskCh, respCh)
}
for {
resp, err := s.db.GetAllHistoryTreeBranches(&p.GetAllHistoryTreeBranchesRequest{
PageSize: pageSize,
NextPageToken: s.hbd.NextPageToken,
})
if err != nil {
return s.hbd, err
}
batchCount := len(resp.Branches)
skips := 0
errorsOnSplitting := 0
// send all tasks
for _, br := range resp.Branches {
if time.Now().Add(-cleanUpThreshold).Before(br.ForkTime) {
batchCount--
skips++
s.metrics.IncCounter(metrics.HistoryScavengerScope, metrics.HistoryScavengerSkipCount)
continue
}
domainID, wid, rid, err := p.SplitHistoryGarbageCleanupInfo(br.Info)
if err != nil {
batchCount--
errorsOnSplitting++
s.logger.Error("unable to parse the history cleanup info", tag.DetailInfo(br.Info))
s.metrics.IncCounter(metrics.HistoryScavengerScope, metrics.HistoryScavengerErrorCount)
continue
}
taskCh <- taskDetail{
domainID: domainID,
workflowID: wid,
runID: rid,
treeID: br.TreeID,
branchID: br.BranchID,
hbd: s.hbd,
}
}
succCount := 0
errCount := 0
if batchCount > 0 {
// wait for counters indicate this batch is done
Loop:
for {
select {
case err := <-respCh:
if err == nil {
s.metrics.IncCounter(metrics.HistoryScavengerScope, metrics.HistoryScavengerSuccessCount)
succCount++
} else {
s.metrics.IncCounter(metrics.HistoryScavengerScope, metrics.HistoryScavengerErrorCount)
errCount++
}
if succCount+errCount == batchCount {
break Loop
}
case <-ctx.Done():
return s.hbd, ctx.Err()
}
}
}
s.hbd.CurrentPage++
s.hbd.NextPageToken = resp.NextPageToken
s.hbd.SuccCount += succCount
s.hbd.ErrorCount += errCount + errorsOnSplitting
s.hbd.SkipCount += skips
if !s.isInTest {
activity.RecordHeartbeat(ctx, s.hbd)
}
if len(s.hbd.NextPageToken) == 0 {
break
}
}
return s.hbd, nil
}
func (s *Scavenger) startTaskProcessor(
ctx context.Context,
taskCh chan taskDetail,
respCh chan error,
) {
for {
select {
case <-ctx.Done():
return
case task := <-taskCh:
if isDone(ctx) {
return
}
if !s.isInTest {
activity.RecordHeartbeat(ctx, s.hbd)
}
err := s.limiter.Wait(ctx)
if err != nil {
respCh <- err
s.logger.Error("encounter error when wait for rate limiter",
getTaskLoggingTags(err, task)...)
continue
}
// this checks if the mutableState still exists
// if not then the history branch is garbage, we need to delete the history branch
_, err = s.client.DescribeMutableState(ctx, &history.DescribeMutableStateRequest{
DomainUUID: common.StringPtr(task.domainID),
Execution: &shared.WorkflowExecution{
WorkflowId: common.StringPtr(task.workflowID),
RunId: common.StringPtr(task.runID),
},
})
if err != nil {
if _, ok := err.(*shared.EntityNotExistsError); ok {
//deleting history branch
var branchToken []byte
branchToken, err = p.NewHistoryBranchTokenByBranchID(task.treeID, task.branchID)
if err != nil {
respCh <- err
s.logger.Error("encounter error when creating branch token",
getTaskLoggingTags(err, task)...)
continue
}
err = s.db.DeleteHistoryBranch(&p.DeleteHistoryBranchRequest{
BranchToken: branchToken,
// This is a required argument but it is not needed for Cassandra.
// Since this scanner is only for Cassandra,
// we can fill any number here to let to code go through
ShardID: common.IntPtr(1),
})
if err != nil {
respCh <- err
s.logger.Error("encounter error when deleting garbage history branch",
getTaskLoggingTags(err, task)...)
} else {
// deleted garbage
s.logger.Info("deleted history garbage",
getTaskLoggingTags(nil, task)...)
respCh <- nil
}
} else {
s.logger.Error("encounter error when describing the mutable state",
getTaskLoggingTags(err, task)...)
respCh <- err
}
} else {
// no garbage
respCh <- nil
}
}
}
}
func getTaskLoggingTags(err error, task taskDetail) []tag.Tag {
if err != nil {
return []tag.Tag{
tag.Error(err),
tag.WorkflowDomainID(task.domainID),
tag.WorkflowID(task.workflowID),
tag.WorkflowRunID(task.runID),
tag.WorkflowTreeID(task.treeID),
tag.WorkflowBranchID(task.branchID),
}
}
return []tag.Tag{
tag.WorkflowDomainID(task.domainID),
tag.WorkflowID(task.workflowID),
tag.WorkflowRunID(task.runID),
tag.WorkflowTreeID(task.treeID),
tag.WorkflowBranchID(task.branchID),
}
}
func isDone(ctx context.Context) bool {
select {
case <-ctx.Done():
return true
default:
return false
}
}