forked from gocraft/work
-
Notifications
You must be signed in to change notification settings - Fork 4
/
worker.go
341 lines (289 loc) · 7.82 KB
/
worker.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
package work
import (
"fmt"
"math/rand"
"reflect"
"time"
"github.com/gomodule/redigo/redis"
)
const fetchKeysPerJobType = 6
var sleepBackoffs = []time.Duration{
time.Millisecond * 0,
time.Millisecond * 10,
time.Millisecond * 100,
time.Millisecond * 1000,
time.Millisecond * 5000,
}
type worker struct {
workerID string
poolID string
namespace string
pool Pool
jobTypes map[string]*jobType
middleware []*middlewareHandler
contextType reflect.Type
processedJobs chan<- *Job
redisFetchScript *redis.Script
sampler prioritySampler
*observer
stopChan chan struct{}
doneStoppingChan chan struct{}
drainChan chan struct{}
doneDrainingChan chan struct{}
logger StructuredLogger
}
// Pool represents a pool of connections to a Redis server.
type Pool interface {
Get() redis.Conn
}
func newWorker(
namespace string,
poolID string,
pool Pool,
contextType reflect.Type,
middleware []*middlewareHandler,
jobTypes map[string]*jobType,
logger StructuredLogger,
processedJobs chan<- *Job,
) *worker {
workerID := makeIdentifier()
ob := newObserver(namespace, pool, workerID, logger)
w := &worker{
workerID: workerID,
poolID: poolID,
namespace: namespace,
pool: pool,
contextType: contextType,
processedJobs: processedJobs,
observer: ob,
stopChan: make(chan struct{}),
doneStoppingChan: make(chan struct{}),
drainChan: make(chan struct{}),
doneDrainingChan: make(chan struct{}),
logger: logger,
}
w.updateMiddlewareAndJobTypes(middleware, jobTypes)
return w
}
// note: can't be called while the thing is started
func (w *worker) updateMiddlewareAndJobTypes(middleware []*middlewareHandler, jobTypes map[string]*jobType) {
w.middleware = middleware
sampler := prioritySampler{}
for _, jt := range jobTypes {
sampler.add(jt.Priority,
redisKeyJobs(w.namespace, jt.Name),
redisKeyJobsInProgress(w.namespace, w.poolID, jt.Name),
redisKeyJobsPaused(w.namespace, jt.Name),
redisKeyJobsLock(w.namespace, jt.Name),
redisKeyJobsLockInfo(w.namespace, jt.Name),
redisKeyJobsConcurrency(w.namespace, jt.Name))
}
w.sampler = sampler
w.jobTypes = jobTypes
w.redisFetchScript = redis.NewScript(len(jobTypes)*fetchKeysPerJobType, redisLuaFetchJob)
}
func (w *worker) start() {
go w.loop()
go w.observer.start()
}
func (w *worker) stop() {
w.stopChan <- struct{}{}
<-w.doneStoppingChan
w.observer.drain()
w.observer.stop()
}
func (w *worker) drain() {
w.drainChan <- struct{}{}
<-w.doneDrainingChan
w.observer.drain()
}
func (w *worker) loop() {
var drained bool
var consequtiveNoJobs int64
// Begin immediately. We'll change the duration on each tick with a timer.Reset()
timer := time.NewTimer(0)
defer timer.Stop()
for {
select {
case <-w.stopChan:
w.doneStoppingChan <- struct{}{}
return
case <-w.drainChan:
drained = true
timer.Reset(0)
case <-timer.C:
job, err := w.fetchJob()
if err != nil {
w.logger.Error("worker.fetch", errAttr(err))
timer.Reset(10 * time.Millisecond)
} else if job != nil {
if w.processedJobs != nil {
w.processedJobs <- job
}
w.processJob(job)
consequtiveNoJobs = 0
timer.Reset(0)
} else {
if drained {
w.doneDrainingChan <- struct{}{}
drained = false
}
consequtiveNoJobs++
idx := consequtiveNoJobs
if idx >= int64(len(sleepBackoffs)) {
idx = int64(len(sleepBackoffs)) - 1
}
timer.Reset(sleepBackoffs[idx])
}
}
}
}
func (w *worker) fetchJob() (*Job, error) {
// resort queues
// NOTE: we could optimize this to only resort every second, or something.
w.sampler.sample()
numKeys := len(w.sampler.samples) * fetchKeysPerJobType
var scriptArgs = make([]interface{}, 0, numKeys+1)
for _, s := range w.sampler.samples {
scriptArgs = append(scriptArgs, s.redisJobs, s.redisJobsInProg, s.redisJobsPaused, s.redisJobsLock, s.redisJobsLockInfo, s.redisJobsMaxConcurrency) // KEYS[1-6 * N]
}
scriptArgs = append(scriptArgs, w.poolID) // ARGV[1]
conn := w.pool.Get()
defer conn.Close()
values, err := redis.Values(w.redisFetchScript.Do(conn, scriptArgs...))
if err == redis.ErrNil {
return nil, nil
} else if err != nil {
return nil, err
}
if len(values) != 3 {
return nil, fmt.Errorf("need 3 elements back")
}
rawJSON, ok := values[0].([]byte)
if !ok {
return nil, fmt.Errorf("response msg not bytes")
}
dequeuedFrom, ok := values[1].([]byte)
if !ok {
return nil, fmt.Errorf("response queue not bytes")
}
inProgQueue, ok := values[2].([]byte)
if !ok {
return nil, fmt.Errorf("response in prog not bytes")
}
job, err := newJob(rawJSON, dequeuedFrom, inProgQueue)
if err != nil {
return nil, err
}
return job, nil
}
func (w *worker) processJob(job *Job) {
if job.Unique {
w.deleteUniqueJob(job)
}
var runErr error
jt := w.jobTypes[job.Name]
if jt == nil {
runErr = fmt.Errorf("stray job: no handler")
w.logger.Error("process_job.stray", errAttr(runErr))
} else {
w.observeStarted(job.Name, job.ID, job.Args)
job.observer = w.observer // for Checkin
_, runErr = runJob(job, w.contextType, w.middleware, jt, w.logger)
w.observeDone(job.Name, job.ID, runErr)
}
if runErr != nil {
job.failed(runErr)
}
// Since we've taken the task and completed it, we must keep retrying commits
// until we succeed, otherwise we'll end up with block job.
retryErr(sleepBackoffs, func() error {
err := w.removeJobFromInProgress(job, jt, runErr)
if err != nil {
w.logger.Warn("worker.remove_job_from_in_progress.lrem", errAttr(err))
}
return err
})
}
func (w *worker) deleteUniqueJob(job *Job) {
uniqueKey, err := redisKeyUniqueJob(w.namespace, job.Name, job.Args)
if err != nil {
w.logger.Error("worker.delete_unique_job.key", errAttr(err))
return
}
conn := w.pool.Get()
defer conn.Close()
_, err = conn.Do("DEL", uniqueKey)
if err != nil {
w.logger.Error("worker.delete_unique_job.del", errAttr(err))
}
}
func (w *worker) removeJobFromInProgress(job *Job, jt *jobType, runErr error) error {
var (
forward bool
queue string
score int64
failedJobRawJSON []byte
)
if runErr != nil {
switch {
case jt != nil && jt.SkipDead:
forward = false
case jt != nil && int64(jt.MaxFails)-job.Fails > 0:
forward = true
queue = redisKeyRetry(w.namespace)
score = nowEpochSeconds() + jt.calcBackoff(job)
default:
// NOTE: sidekiq limits the # of jobs: only keep jobs for 6 months, and only keep a max # of jobs
// The max # of jobs seems really horrible. Seems like operations should be on top of it.
// conn.Send("ZREMRANGEBYSCORE", redisKeyDead(w.namespace), "-inf", now - keepInterval)
// conn.Send("ZREMRANGEBYRANK", redisKeyDead(w.namespace), 0, -maxJobs)
forward = true
queue = redisKeyDead(w.namespace)
score = nowEpochSeconds()
}
if forward {
var err error
failedJobRawJSON, err = job.serialize()
if err != nil {
w.logger.Error("worker.removeJobFromInProgress.serialize", errAttr(err))
forward = false
}
}
}
conn := w.pool.Get()
defer conn.Close()
_, err := redisRemoveJobFromInProgress.Do(conn,
job.inProgQueue,
redisKeyJobsLock(w.namespace, job.Name),
redisKeyJobsLockInfo(w.namespace, job.Name),
queue,
w.poolID,
job.rawJSON,
forward,
score,
failedJobRawJSON,
)
return err
}
// Default algorithm returns an fastly increasing backoff counter which grows in an unbounded fashion
func defaultBackoffCalculator(job *Job) int64 {
fails := job.Fails
return (fails * fails * fails * fails) + 15 + (rand.Int63n(30) * (fails + 1))
}
// retryErr retries fn until success.
func retryErr(backoffs []time.Duration, fn func() error) {
for attempt := 0; ; attempt++ {
err := fn()
if err == nil {
break
}
if len(backoffs) != 0 {
idx := attempt
if idx >= len(backoffs) {
idx = len(backoffs) - 1
}
time.Sleep(backoffs[idx])
}
}
}