This repository has been archived by the owner on Feb 17, 2021. It is now read-only.
forked from gocraft/work
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker_pool.go
494 lines (417 loc) · 14.4 KB
/
worker_pool.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
package work
import (
"reflect"
"sort"
"strings"
"sync"
"github.com/gomodule/redigo/redis"
"github.com/robfig/cron/v3"
)
// WorkerPool represents a pool of workers. It forms the primary API of gocraft/work. WorkerPools provide the public API of gocraft/work. You can attach jobs and middlware to them. You can start and stop them. Based on their concurrency setting, they'll spin up N worker goroutines.
type WorkerPool struct {
workerPoolID string
concurrency uint
namespace string // eg, "myapp-work"
pool *redis.Pool
sleepBackoffs []int64
contextType reflect.Type
jobTypes map[string]*jobType
middleware []*middlewareHandler
started bool
periodicJobs []*periodicJob
workers []*worker
heartbeater *workerPoolHeartbeater
retrier *requeuer
scheduler *requeuer
deadPoolReaper *deadPoolReaper
periodicEnqueuer *periodicEnqueuer
mu *sync.Mutex
}
type jobType struct {
Name string
JobOptions
IsGeneric bool
GenericHandler GenericHandler
DynamicHandler reflect.Value
}
func (jt *jobType) calcBackoff(j *Job) int64 {
if jt.Backoff == nil {
return defaultBackoffCalculator(j)
}
return jt.Backoff(j)
}
// You may provide your own backoff function for retrying failed jobs or use the builtin one.
// Returns the number of seconds to wait until the next attempt.
//
// The builtin backoff calculator provides an exponentially increasing wait function.
type BackoffCalculator func(job *Job) int64
// JobOptions can be passed to JobWithOptions.
type JobOptions struct {
Priority uint // Priority from 1 to 10000
MaxFails uint // 1: send straight to dead (unless SkipDead)
SkipDead bool // If true, don't send failed jobs to the dead queue when retries are exhausted.
MaxConcurrency uint // Max number of jobs to keep in flight (default is 0, meaning no max)
Backoff BackoffCalculator // If not set, uses the default backoff algorithm
}
// WorkerPoolOptions can be passed to NewWorkerPoolWithOptions.
type WorkerPoolOptions struct {
SleepBackoffs []int64 // Sleep backoffs in milliseconds
}
// GenericHandler is a job handler without any custom context.
type GenericHandler func(*Job) error
// GenericMiddlewareHandler is a middleware without any custom context.
type GenericMiddlewareHandler func(*Job, NextMiddlewareFunc) error
// NextMiddlewareFunc is a function type (whose instances are named 'next') that you call to advance to the next middleware.
type NextMiddlewareFunc func() error
type middlewareHandler struct {
IsGeneric bool
DynamicMiddleware reflect.Value
GenericMiddlewareHandler GenericMiddlewareHandler
}
// NewWorkerPool creates a new worker pool. ctx should be a struct literal whose type will be used for middleware and handlers.
// concurrency specifies how many workers to spin up - each worker can process jobs concurrently.
func NewWorkerPool(ctx interface{}, concurrency uint, namespace string, pool *redis.Pool) *WorkerPool {
return NewWorkerPoolWithOptions(ctx, concurrency, namespace, pool, WorkerPoolOptions{})
}
// NewWorkerPoolWithOptions creates a new worker pool as per the NewWorkerPool function, but permits you to specify
// additional options such as sleep backoffs.
func NewWorkerPoolWithOptions(ctx interface{}, concurrency uint, namespace string, pool *redis.Pool, workerPoolOpts WorkerPoolOptions) *WorkerPool {
if pool == nil {
panic("NewWorkerPool needs a non-nil *redis.Pool")
}
ctxType := reflect.TypeOf(ctx)
validateContextType(ctxType)
wp := &WorkerPool{
workerPoolID: makeIdentifier(),
concurrency: concurrency,
namespace: namespace,
pool: pool,
sleepBackoffs: workerPoolOpts.SleepBackoffs,
contextType: ctxType,
jobTypes: make(map[string]*jobType),
mu: &sync.Mutex{},
}
for i := uint(0); i < wp.concurrency; i++ {
w := newWorker(wp.namespace, wp.workerPoolID, wp.pool, wp.contextType, nil, wp.jobTypes, wp.sleepBackoffs)
wp.workers = append(wp.workers, w)
}
return wp
}
// Middleware appends the specified function to the middleware chain. The fn can take one of these forms:
// (*ContextType).func(*Job, NextMiddlewareFunc) error, (ContextType matches the type of ctx specified when creating a pool)
// func(*Job, NextMiddlewareFunc) error, for the generic middleware format.
func (wp *WorkerPool) Middleware(fn interface{}) *WorkerPool {
vfn := reflect.ValueOf(fn)
validateMiddlewareType(wp.contextType, vfn)
mw := &middlewareHandler{
DynamicMiddleware: vfn,
}
if gmh, ok := fn.(func(*Job, NextMiddlewareFunc) error); ok {
mw.IsGeneric = true
mw.GenericMiddlewareHandler = gmh
}
wp.middleware = append(wp.middleware, mw)
for _, w := range wp.workers {
w.updateMiddlewareAndJobTypes(wp.middleware, wp.jobTypes)
}
return wp
}
// Job registers the job name to the specified handler fn. For instance, when workers pull jobs from the name queue they'll be processed by the specified handler function.
// fn can take one of these forms:
// (*ContextType).func(*Job) error, (ContextType matches the type of ctx specified when creating a pool)
// func(*Job) error, for the generic handler format.
func (wp *WorkerPool) Job(name string, fn interface{}) *WorkerPool {
return wp.JobWithOptions(name, JobOptions{}, fn)
}
// JobWithOptions adds a handler for 'name' jobs as per the Job function, but permits you specify additional options
// such as a job's priority, retry count, and whether to send dead jobs to the dead job queue or trash them.
func (wp *WorkerPool) JobWithOptions(name string, jobOpts JobOptions, fn interface{}) *WorkerPool {
jobOpts = applyDefaultsAndValidate(jobOpts)
vfn := reflect.ValueOf(fn)
validateHandlerType(wp.contextType, vfn)
jt := &jobType{
Name: name,
DynamicHandler: vfn,
JobOptions: jobOpts,
}
if gh, ok := fn.(func(*Job) error); ok {
jt.IsGeneric = true
jt.GenericHandler = gh
}
wp.jobTypes[name] = jt
for _, w := range wp.workers {
w.updateMiddlewareAndJobTypes(wp.middleware, wp.jobTypes)
}
if wp.started {
wp.writeConcurrencyControlsToRedis(map[string]*jobType{name: jt})
wp.mu.Lock()
jobNames := strings.Split(wp.heartbeater.jobNames, ",")
exists := false
for _, job := range jobNames {
if job == name {
exists = true
break
}
}
if !exists {
wp.heartbeater.jobNames += "," + name
}
wp.mu.Unlock()
}
return wp
}
// PeriodicallyEnqueue will periodically enqueue jobName according to the cron-based spec.
// The spec format is based on https://godoc.org/github.com/robfig/cron, which is a relatively standard cron format.
// Note that the first value is the seconds!
// If you have multiple worker pools on different machines, they'll all coordinate and only enqueue your job once.
func (wp *WorkerPool) PeriodicallyEnqueue(spec string, jobName string) *WorkerPool {
p := cron.NewParser(cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)
schedule, err := p.Parse(spec)
if err != nil {
panic(err)
}
wp.periodicJobs = append(wp.periodicJobs, &periodicJob{jobName: jobName, spec: spec, schedule: schedule})
return wp
}
// Start starts the workers and associated processes.
func (wp *WorkerPool) Start() {
if wp.started {
return
}
wp.started = true
// TODO: we should cleanup stale keys on startup from previously registered jobs
wp.writeConcurrencyControlsToRedis(wp.jobTypes)
go wp.writeKnownJobsToRedis()
for _, w := range wp.workers {
go w.start()
}
wp.heartbeater = newWorkerPoolHeartbeater(wp.namespace, wp.pool, wp.workerPoolID, wp.jobTypes, wp.concurrency, wp.workerIDs())
wp.heartbeater.start()
wp.startRequeuers()
wp.periodicEnqueuer = newPeriodicEnqueuer(wp.namespace, wp.pool, wp.periodicJobs)
wp.periodicEnqueuer.start()
}
// Stop stops the workers and associated processes.
func (wp *WorkerPool) Stop() {
if !wp.started {
return
}
wp.started = false
wg := sync.WaitGroup{}
for _, w := range wp.workers {
wg.Add(1)
go func(w *worker) {
w.stop()
wg.Done()
}(w)
}
wg.Wait()
wp.heartbeater.stop()
wp.retrier.stop()
wp.scheduler.stop()
wp.deadPoolReaper.stop()
wp.periodicEnqueuer.stop()
}
// Drain drains all jobs in the queue before returning. Note that if jobs are added faster than we can process them, this function wouldn't return.
func (wp *WorkerPool) Drain() {
wg := sync.WaitGroup{}
for _, w := range wp.workers {
wg.Add(1)
go func(w *worker) {
w.drain()
wg.Done()
}(w)
}
wg.Wait()
}
func (wp *WorkerPool) startRequeuers() {
jobNames := make([]string, 0, len(wp.jobTypes))
for k := range wp.jobTypes {
jobNames = append(jobNames, k)
}
wp.retrier = newRequeuer(wp.namespace, wp.pool, redisKeyRetry(wp.namespace), jobNames)
wp.scheduler = newRequeuer(wp.namespace, wp.pool, redisKeyScheduled(wp.namespace), jobNames)
wp.deadPoolReaper = newDeadPoolReaper(wp.namespace, wp.pool, jobNames)
wp.retrier.start()
wp.scheduler.start()
wp.deadPoolReaper.start()
}
func (wp *WorkerPool) workerIDs() []string {
wids := make([]string, 0, len(wp.workers))
for _, w := range wp.workers {
wids = append(wids, w.workerID)
}
sort.Strings(wids)
return wids
}
func (wp *WorkerPool) writeKnownJobsToRedis() {
if len(wp.jobTypes) == 0 {
return
}
conn := wp.pool.Get()
defer conn.Close()
key := redisKeyKnownJobs(wp.namespace)
jobNames := make([]interface{}, 0, len(wp.jobTypes)+1)
jobNames = append(jobNames, key)
for k := range wp.jobTypes {
jobNames = append(jobNames, k)
}
if _, err := conn.Do("SADD", jobNames...); err != nil {
logError("write_known_jobs", err)
}
}
func (wp *WorkerPool) writeConcurrencyControlsToRedis(jobTypes map[string]*jobType) {
if len(jobTypes) == 0 {
return
}
conn := wp.pool.Get()
defer conn.Close()
for jobName, jobType := range jobTypes {
if _, err := conn.Do("SET", redisKeyJobsConcurrency(wp.namespace, jobName), jobType.MaxConcurrency); err != nil {
logError("write_concurrency_controls_max_concurrency", err)
}
}
}
// validateContextType will panic if context is invalid
func validateContextType(ctxType reflect.Type) {
if ctxType.Kind() != reflect.Struct {
panic("work: Context needs to be a struct type")
}
}
func validateHandlerType(ctxType reflect.Type, vfn reflect.Value) {
if !isValidHandlerType(ctxType, vfn) {
panic(instructiveMessage(vfn, "a handler", "handler", "job *work.Job", ctxType))
}
}
func validateMiddlewareType(ctxType reflect.Type, vfn reflect.Value) {
if !isValidMiddlewareType(ctxType, vfn) {
panic(instructiveMessage(vfn, "middleware", "middleware", "job *work.Job, next NextMiddlewareFunc", ctxType))
}
}
// Since it's easy to pass the wrong method as a middleware/handler, and since the user can't rely on static type checking since we use reflection,
// lets be super helpful about what they did and what they need to do.
// Arguments:
// - vfn is the failed method
// - addingType is for "You are adding {addingType} to a worker pool...". Eg, "middleware" or "a handler"
// - yourType is for "Your {yourType} function can have...". Eg, "middleware" or "handler" or "error handler"
// - args is like "rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc"
// - NOTE: args can be calculated if you pass in each type. BUT, it doesn't have example argument name, so it has less copy/paste value.
func instructiveMessage(vfn reflect.Value, addingType string, yourType string, args string, ctxType reflect.Type) string {
// Get context type without package.
ctxString := ctxType.String()
splitted := strings.Split(ctxString, ".")
if len(splitted) <= 1 {
ctxString = splitted[0]
} else {
ctxString = splitted[1]
}
str := "\n" + strings.Repeat("*", 120) + "\n"
str += "* You are adding " + addingType + " to a worker pool with context type '" + ctxString + "'\n"
str += "*\n*\n"
str += "* Your " + yourType + " function can have one of these signatures:\n"
str += "*\n"
str += "* // If you don't need context:\n"
str += "* func YourFunctionName(" + args + ") error\n"
str += "*\n"
str += "* // If you want your " + yourType + " to accept a context:\n"
str += "* func (c *" + ctxString + ") YourFunctionName(" + args + ") error // or,\n"
str += "* func YourFunctionName(c *" + ctxString + ", " + args + ") error\n"
str += "*\n"
str += "* Unfortunately, your function has this signature: " + vfn.Type().String() + "\n"
str += "*\n"
str += strings.Repeat("*", 120) + "\n"
return str
}
func isValidHandlerType(ctxType reflect.Type, vfn reflect.Value) bool {
fnType := vfn.Type()
if fnType.Kind() != reflect.Func {
return false
}
numIn := fnType.NumIn()
numOut := fnType.NumOut()
if numOut != 1 {
return false
}
outType := fnType.Out(0)
var e *error
if outType != reflect.TypeOf(e).Elem() {
return false
}
var j *Job
if numIn == 1 {
if fnType.In(0) != reflect.TypeOf(j) {
return false
}
} else if numIn == 2 {
//if handler context is an interface
if fnType.In(0).Kind() == reflect.Interface && !reflect.PtrTo(ctxType).Implements(fnType.In(0)) {
return false
}
//if handler context is not an interface
if fnType.In(0).Kind() != reflect.Interface && fnType.In(0) != reflect.PtrTo(ctxType) {
return false
}
if fnType.In(1) != reflect.TypeOf(j) {
return false
}
} else {
return false
}
return true
}
func isValidMiddlewareType(ctxType reflect.Type, vfn reflect.Value) bool {
fnType := vfn.Type()
if fnType.Kind() != reflect.Func {
return false
}
numIn := fnType.NumIn()
numOut := fnType.NumOut()
if numOut != 1 {
return false
}
outType := fnType.Out(0)
var e *error
if outType != reflect.TypeOf(e).Elem() {
return false
}
var j *Job
var nfn NextMiddlewareFunc
if numIn == 2 {
if fnType.In(0) != reflect.TypeOf(j) {
return false
}
if fnType.In(1) != reflect.TypeOf(nfn) {
return false
}
} else if numIn == 3 {
//if middleware context is an interface
if fnType.In(0).Kind() == reflect.Interface && !reflect.PtrTo(ctxType).Implements(fnType.In(0)) {
return false
}
// if middlware context is not an interface
if fnType.In(0).Kind() != reflect.Interface && fnType.In(0) != reflect.PtrTo(ctxType) {
return false
}
if fnType.In(1) != reflect.TypeOf(j) {
return false
}
if fnType.In(2) != reflect.TypeOf(nfn) {
return false
}
} else {
return false
}
return true
}
func applyDefaultsAndValidate(jobOpts JobOptions) JobOptions {
if jobOpts.Priority == 0 {
jobOpts.Priority = 1
}
if jobOpts.MaxFails == 0 {
jobOpts.MaxFails = 4
}
if jobOpts.Priority > 100000 {
panic("work: JobOptions.Priority must be between 1 and 100000")
}
return jobOpts
}