2020-01-03 10:13:16 +08:00
|
|
|
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
|
|
|
|
2019-11-19 22:48:54 +08:00
|
|
|
package asynq
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2020-01-07 23:03:39 +08:00
|
|
|
"math/rand"
|
2020-01-12 23:46:51 +08:00
|
|
|
"sort"
|
2019-12-17 22:18:22 +08:00
|
|
|
"sync"
|
2019-11-19 22:48:54 +08:00
|
|
|
"time"
|
2019-12-04 13:01:26 +08:00
|
|
|
|
2019-12-22 23:15:45 +08:00
|
|
|
"github.com/hibiken/asynq/internal/base"
|
2019-12-04 13:01:26 +08:00
|
|
|
"github.com/hibiken/asynq/internal/rdb"
|
2020-01-22 22:28:47 +08:00
|
|
|
"golang.org/x/time/rate"
|
2019-11-19 22:48:54 +08:00
|
|
|
)
|
|
|
|
|
2019-11-21 12:08:03 +08:00
|
|
|
type processor struct {
|
2019-12-04 13:01:26 +08:00
|
|
|
rdb *rdb.RDB
|
2019-11-19 22:48:54 +08:00
|
|
|
|
2020-02-02 14:22:48 +08:00
|
|
|
pinfo *base.ProcessInfo
|
|
|
|
|
2019-12-03 12:42:21 +08:00
|
|
|
handler Handler
|
2019-11-19 22:48:54 +08:00
|
|
|
|
2020-01-06 23:15:59 +08:00
|
|
|
queueConfig map[string]uint
|
|
|
|
|
2020-01-12 23:46:51 +08:00
|
|
|
// orderedQueues is set only in strict-priority mode.
|
|
|
|
orderedQueues []string
|
|
|
|
|
2019-12-30 09:43:19 +08:00
|
|
|
retryDelayFunc retryDelayFunc
|
|
|
|
|
2020-01-18 23:32:06 +08:00
|
|
|
// channel via which to send sync requests to syncer.
|
|
|
|
syncRequestCh chan<- *syncRequest
|
|
|
|
|
2020-01-22 22:28:47 +08:00
|
|
|
// rate limiter to prevent spamming logs with a bunch of errors.
|
|
|
|
errLogLimiter *rate.Limiter
|
|
|
|
|
2019-11-19 22:48:54 +08:00
|
|
|
// sema is a counting semaphore to ensure the number of active workers
|
2019-11-30 04:48:54 +08:00
|
|
|
// does not exceed the limit.
|
2019-11-19 22:48:54 +08:00
|
|
|
sema chan struct{}
|
|
|
|
|
2019-11-21 12:08:03 +08:00
|
|
|
// channel to communicate back to the long running "processor" goroutine.
|
2019-12-18 12:34:56 +08:00
|
|
|
// once is used to send value to the channel only once.
|
2019-11-19 22:48:54 +08:00
|
|
|
done chan struct{}
|
2019-12-18 12:34:56 +08:00
|
|
|
once sync.Once
|
2019-12-18 12:07:17 +08:00
|
|
|
|
2019-12-19 10:57:48 +08:00
|
|
|
// abort channel is closed when the shutdown of the "processor" goroutine starts.
|
|
|
|
abort chan struct{}
|
2019-12-16 13:00:09 +08:00
|
|
|
|
|
|
|
// quit channel communicates to the in-flight worker goroutines to stop.
|
|
|
|
quit chan struct{}
|
2019-11-19 22:48:54 +08:00
|
|
|
}
|
|
|
|
|
2019-12-30 09:43:19 +08:00
|
|
|
type retryDelayFunc func(n int, err error, task *Task) time.Duration
|
|
|
|
|
2020-01-12 23:46:51 +08:00
|
|
|
// newProcessor constructs a new processor.
|
2020-02-02 14:22:48 +08:00
|
|
|
func newProcessor(r *rdb.RDB, pinfo *base.ProcessInfo, fn retryDelayFunc, syncRequestCh chan<- *syncRequest) *processor {
|
|
|
|
qcfg := normalizeQueueCfg(pinfo.Queues)
|
2020-01-12 23:46:51 +08:00
|
|
|
orderedQueues := []string(nil)
|
2020-02-02 14:22:48 +08:00
|
|
|
if pinfo.StrictPriority {
|
2020-01-12 23:46:51 +08:00
|
|
|
orderedQueues = sortByPriority(qcfg)
|
|
|
|
}
|
2019-11-21 12:08:03 +08:00
|
|
|
return &processor{
|
2019-12-04 13:01:26 +08:00
|
|
|
rdb: r,
|
2020-02-02 14:22:48 +08:00
|
|
|
pinfo: pinfo,
|
2020-01-06 23:15:59 +08:00
|
|
|
queueConfig: qcfg,
|
2020-01-12 23:46:51 +08:00
|
|
|
orderedQueues: orderedQueues,
|
2019-12-30 09:43:19 +08:00
|
|
|
retryDelayFunc: fn,
|
2020-01-18 23:32:06 +08:00
|
|
|
syncRequestCh: syncRequestCh,
|
2020-01-22 22:28:47 +08:00
|
|
|
errLogLimiter: rate.NewLimiter(rate.Every(3*time.Second), 1),
|
2020-02-02 14:22:48 +08:00
|
|
|
sema: make(chan struct{}, pinfo.Concurrency),
|
2019-11-30 04:48:54 +08:00
|
|
|
done: make(chan struct{}),
|
2019-12-19 10:57:48 +08:00
|
|
|
abort: make(chan struct{}),
|
2019-12-16 13:00:09 +08:00
|
|
|
quit: make(chan struct{}),
|
2019-12-30 09:43:19 +08:00
|
|
|
handler: HandlerFunc(func(t *Task) error { return fmt.Errorf("handler not set") }),
|
2019-11-19 22:48:54 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-17 22:18:22 +08:00
|
|
|
// Note: stops only the "processor" goroutine, does not stop workers.
|
|
|
|
// It's safe to call this method multiple times.
|
|
|
|
func (p *processor) stop() {
|
2019-12-18 12:34:56 +08:00
|
|
|
p.once.Do(func() {
|
2020-01-21 23:17:41 +08:00
|
|
|
logger.info("Processor shutting down...")
|
2019-12-18 12:34:56 +08:00
|
|
|
// Unblock if processor is waiting for sema token.
|
2019-12-19 10:57:48 +08:00
|
|
|
close(p.abort)
|
2019-12-18 12:34:56 +08:00
|
|
|
// Signal the processor goroutine to stop processing tasks
|
|
|
|
// from the queue.
|
|
|
|
p.done <- struct{}{}
|
|
|
|
})
|
2019-12-17 22:18:22 +08:00
|
|
|
}
|
|
|
|
|
2019-11-30 04:48:54 +08:00
|
|
|
// NOTE: once terminated, processor cannot be re-started.
|
2019-11-21 12:08:03 +08:00
|
|
|
func (p *processor) terminate() {
|
2019-12-17 22:18:22 +08:00
|
|
|
p.stop()
|
2019-11-19 23:38:09 +08:00
|
|
|
|
2019-12-30 23:10:13 +08:00
|
|
|
// IDEA: Allow user to customize this timeout value.
|
2019-12-16 13:00:09 +08:00
|
|
|
const timeout = 8 * time.Second
|
|
|
|
time.AfterFunc(timeout, func() { close(p.quit) })
|
2020-01-21 23:17:41 +08:00
|
|
|
logger.info("Waiting for all workers to finish...")
|
2019-11-28 11:36:56 +08:00
|
|
|
// block until all workers have released the token
|
2019-11-21 12:08:03 +08:00
|
|
|
for i := 0; i < cap(p.sema); i++ {
|
|
|
|
p.sema <- struct{}{}
|
2019-11-19 23:38:09 +08:00
|
|
|
}
|
2020-01-21 23:17:41 +08:00
|
|
|
logger.info("All workers have finished")
|
2019-12-16 13:00:09 +08:00
|
|
|
p.restore() // move any unfinished tasks back to the queue.
|
2019-11-19 22:48:54 +08:00
|
|
|
}
|
|
|
|
|
2019-11-21 12:08:03 +08:00
|
|
|
func (p *processor) start() {
|
2019-11-24 07:09:50 +08:00
|
|
|
// NOTE: The call to "restore" needs to complete before starting
|
|
|
|
// the processor goroutine.
|
|
|
|
p.restore()
|
2019-11-19 22:48:54 +08:00
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
2019-11-21 12:08:03 +08:00
|
|
|
case <-p.done:
|
2020-01-21 23:17:41 +08:00
|
|
|
logger.info("Processor done")
|
2019-11-19 23:38:09 +08:00
|
|
|
return
|
2019-11-19 22:48:54 +08:00
|
|
|
default:
|
2019-11-21 12:08:03 +08:00
|
|
|
p.exec()
|
2019-11-19 22:48:54 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
2019-11-22 13:45:27 +08:00
|
|
|
// exec pulls a task out of the queue and starts a worker goroutine to
|
|
|
|
// process the task.
|
2019-11-21 12:08:03 +08:00
|
|
|
func (p *processor) exec() {
|
2020-01-07 23:03:39 +08:00
|
|
|
qnames := p.queues()
|
2020-01-07 22:28:34 +08:00
|
|
|
msg, err := p.rdb.Dequeue(qnames...)
|
|
|
|
if err == rdb.ErrNoProcessableTask {
|
|
|
|
// queues are empty, this is a normal behavior.
|
2020-01-14 22:29:05 +08:00
|
|
|
if len(p.queueConfig) > 1 {
|
|
|
|
// sleep to avoid slamming redis and let scheduler move tasks into queues.
|
|
|
|
// Note: With multiple queues, we are not using blocking pop operation and
|
|
|
|
// polling queues instead. This adds significant load to redis.
|
|
|
|
time.Sleep(time.Second)
|
|
|
|
}
|
2019-11-28 11:36:56 +08:00
|
|
|
return
|
|
|
|
}
|
2019-11-19 22:48:54 +08:00
|
|
|
if err != nil {
|
2020-01-22 22:28:47 +08:00
|
|
|
if p.errLogLimiter.Allow() {
|
|
|
|
logger.error("Dequeue error: %v", err)
|
|
|
|
}
|
2019-11-28 11:36:56 +08:00
|
|
|
return
|
2019-11-19 22:48:54 +08:00
|
|
|
}
|
|
|
|
|
2019-12-18 12:07:17 +08:00
|
|
|
select {
|
2019-12-19 10:57:48 +08:00
|
|
|
case <-p.abort:
|
2019-12-18 12:07:17 +08:00
|
|
|
// shutdown is starting, return immediately after requeuing the message.
|
|
|
|
p.requeue(msg)
|
|
|
|
return
|
|
|
|
case p.sema <- struct{}{}: // acquire token
|
2020-02-02 14:22:48 +08:00
|
|
|
p.pinfo.IncrActiveWorkerCount(1)
|
2019-12-16 13:00:09 +08:00
|
|
|
go func() {
|
2020-02-02 14:22:48 +08:00
|
|
|
defer func() {
|
|
|
|
<-p.sema /* release token */
|
|
|
|
p.pinfo.IncrActiveWorkerCount(-1)
|
|
|
|
}()
|
2019-12-18 12:07:17 +08:00
|
|
|
|
|
|
|
resCh := make(chan error, 1)
|
2020-01-05 05:13:46 +08:00
|
|
|
task := NewTask(msg.Type, msg.Payload)
|
2019-12-18 12:07:17 +08:00
|
|
|
go func() {
|
|
|
|
resCh <- perform(p.handler, task)
|
|
|
|
}()
|
2019-12-16 13:00:09 +08:00
|
|
|
|
2019-12-18 12:07:17 +08:00
|
|
|
select {
|
|
|
|
case <-p.quit:
|
|
|
|
// time is up, quit this worker goroutine.
|
2020-01-21 23:17:41 +08:00
|
|
|
logger.warn("Quitting worker to process task id=%s", msg.ID)
|
2019-12-18 12:07:17 +08:00
|
|
|
return
|
|
|
|
case resErr := <-resCh:
|
|
|
|
// Note: One of three things should happen.
|
|
|
|
// 1) Done -> Removes the message from InProgress
|
|
|
|
// 2) Retry -> Removes the message from InProgress & Adds the message to Retry
|
|
|
|
// 3) Kill -> Removes the message from InProgress & Adds the message to Dead
|
|
|
|
if resErr != nil {
|
|
|
|
if msg.Retried >= msg.Retry {
|
2019-12-30 09:43:19 +08:00
|
|
|
p.kill(msg, resErr)
|
2019-12-26 12:04:29 +08:00
|
|
|
} else {
|
2019-12-30 09:43:19 +08:00
|
|
|
p.retry(msg, resErr)
|
2019-12-18 12:07:17 +08:00
|
|
|
}
|
2019-12-16 13:00:09 +08:00
|
|
|
return
|
|
|
|
}
|
2019-12-18 12:07:17 +08:00
|
|
|
p.markAsDone(msg)
|
2019-11-22 13:45:27 +08:00
|
|
|
}
|
2019-12-18 12:07:17 +08:00
|
|
|
}()
|
|
|
|
}
|
2019-11-19 22:48:54 +08:00
|
|
|
}
|
2019-11-24 07:09:50 +08:00
|
|
|
|
|
|
|
// restore moves all tasks from "in-progress" back to queue
|
|
|
|
// to restore all unfinished tasks.
|
|
|
|
func (p *processor) restore() {
|
2020-02-09 03:06:14 +08:00
|
|
|
n, err := p.rdb.RequeueAll()
|
2019-11-24 07:09:50 +08:00
|
|
|
if err != nil {
|
2020-01-21 23:17:41 +08:00
|
|
|
logger.error("Could not restore unfinished tasks: %v", err)
|
2019-12-16 13:00:09 +08:00
|
|
|
}
|
2019-12-19 10:55:08 +08:00
|
|
|
if n > 0 {
|
2020-01-21 23:17:41 +08:00
|
|
|
logger.info("Restored %d unfinished tasks back to queue", n)
|
2019-12-19 10:55:08 +08:00
|
|
|
}
|
2019-12-16 13:00:09 +08:00
|
|
|
}
|
|
|
|
|
2019-12-22 23:15:45 +08:00
|
|
|
func (p *processor) requeue(msg *base.TaskMessage) {
|
2019-12-18 12:07:17 +08:00
|
|
|
err := p.rdb.Requeue(msg)
|
|
|
|
if err != nil {
|
2020-01-21 23:17:41 +08:00
|
|
|
logger.error("Could not push task id=%s back to queue: %v", msg.ID, err)
|
2019-12-18 12:07:17 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-22 23:15:45 +08:00
|
|
|
func (p *processor) markAsDone(msg *base.TaskMessage) {
|
2019-12-16 13:00:09 +08:00
|
|
|
err := p.rdb.Done(msg)
|
|
|
|
if err != nil {
|
2020-01-21 23:17:41 +08:00
|
|
|
errMsg := fmt.Sprintf("Could not remove task id=%s from %q", msg.ID, base.InProgressQueue)
|
|
|
|
logger.warn("%s; Will retry syncing", errMsg)
|
2020-01-18 23:32:06 +08:00
|
|
|
p.syncRequestCh <- &syncRequest{
|
|
|
|
fn: func() error {
|
|
|
|
return p.rdb.Done(msg)
|
|
|
|
},
|
|
|
|
errMsg: errMsg,
|
|
|
|
}
|
2019-12-16 13:00:09 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-30 09:43:19 +08:00
|
|
|
func (p *processor) retry(msg *base.TaskMessage, e error) {
|
2020-01-05 05:13:46 +08:00
|
|
|
d := p.retryDelayFunc(msg.Retried, e, NewTask(msg.Type, msg.Payload))
|
2019-12-30 09:43:19 +08:00
|
|
|
retryAt := time.Now().Add(d)
|
|
|
|
err := p.rdb.Retry(msg, retryAt, e.Error())
|
2019-12-16 13:00:09 +08:00
|
|
|
if err != nil {
|
2020-01-21 23:17:41 +08:00
|
|
|
errMsg := fmt.Sprintf("Could not move task id=%s from %q to %q", msg.ID, base.InProgressQueue, base.RetryQueue)
|
|
|
|
logger.warn("%s; Will retry syncing", errMsg)
|
2020-01-18 23:32:06 +08:00
|
|
|
p.syncRequestCh <- &syncRequest{
|
|
|
|
fn: func() error {
|
|
|
|
return p.rdb.Retry(msg, retryAt, e.Error())
|
|
|
|
},
|
|
|
|
errMsg: errMsg,
|
|
|
|
}
|
2019-12-16 13:00:09 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-30 09:43:19 +08:00
|
|
|
func (p *processor) kill(msg *base.TaskMessage, e error) {
|
2020-01-21 23:17:41 +08:00
|
|
|
logger.warn("Retry exhausted for task id=%s", msg.ID)
|
2019-12-30 09:43:19 +08:00
|
|
|
err := p.rdb.Kill(msg, e.Error())
|
2019-12-16 13:00:09 +08:00
|
|
|
if err != nil {
|
2020-01-21 23:17:41 +08:00
|
|
|
errMsg := fmt.Sprintf("Could not move task id=%s from %q to %q", msg.ID, base.InProgressQueue, base.DeadQueue)
|
|
|
|
logger.warn("%s; Will retry syncing", errMsg)
|
2020-01-18 23:32:06 +08:00
|
|
|
p.syncRequestCh <- &syncRequest{
|
|
|
|
fn: func() error {
|
|
|
|
return p.rdb.Kill(msg, e.Error())
|
|
|
|
},
|
|
|
|
errMsg: errMsg,
|
|
|
|
}
|
2019-11-24 07:09:50 +08:00
|
|
|
}
|
|
|
|
}
|
2019-11-28 06:03:04 +08:00
|
|
|
|
2020-01-12 23:46:51 +08:00
|
|
|
// queues returns a list of queues to query.
|
|
|
|
// Order of the queue names is based on the priority of each queue.
|
|
|
|
// Queue names is sorted by their priority level if strict-priority is true.
|
|
|
|
// If strict-priority is false, then the order of queue names are roughly based on
|
|
|
|
// the priority level but randomized in order to avoid starving low priority queues.
|
2020-01-07 23:03:39 +08:00
|
|
|
func (p *processor) queues() []string {
|
2020-01-14 22:29:05 +08:00
|
|
|
// skip the overhead of generating a list of queue names
|
|
|
|
// if we are processing one queue.
|
|
|
|
if len(p.queueConfig) == 1 {
|
|
|
|
for qname := range p.queueConfig {
|
|
|
|
return []string{qname}
|
|
|
|
}
|
|
|
|
}
|
2020-01-12 23:46:51 +08:00
|
|
|
if p.orderedQueues != nil {
|
|
|
|
return p.orderedQueues
|
|
|
|
}
|
2020-01-07 23:03:39 +08:00
|
|
|
var names []string
|
|
|
|
for qname, priority := range p.queueConfig {
|
|
|
|
for i := 0; i < int(priority); i++ {
|
|
|
|
names = append(names, qname)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
|
|
|
r.Shuffle(len(names), func(i, j int) { names[i], names[j] = names[j], names[i] })
|
|
|
|
return uniq(names, len(p.queueConfig))
|
|
|
|
}
|
|
|
|
|
2019-11-28 06:03:04 +08:00
|
|
|
// perform calls the handler with the given task.
|
|
|
|
// If the call returns without panic, it simply returns the value,
|
|
|
|
// otherwise, it recovers from panic and returns an error.
|
2019-12-03 12:42:21 +08:00
|
|
|
func perform(h Handler, task *Task) (err error) {
|
2019-11-28 06:03:04 +08:00
|
|
|
defer func() {
|
|
|
|
if x := recover(); x != nil {
|
|
|
|
err = fmt.Errorf("panic: %v", x)
|
|
|
|
}
|
|
|
|
}()
|
2019-12-03 12:42:21 +08:00
|
|
|
return h.ProcessTask(task)
|
2019-11-28 06:03:04 +08:00
|
|
|
}
|
2020-01-07 23:03:39 +08:00
|
|
|
|
|
|
|
// uniq dedupes elements and returns a slice of unique names of length l.
|
|
|
|
// Order of the output slice is based on the input list.
|
|
|
|
func uniq(names []string, l int) []string {
|
|
|
|
var res []string
|
|
|
|
seen := make(map[string]struct{})
|
|
|
|
for _, s := range names {
|
|
|
|
if _, ok := seen[s]; !ok {
|
|
|
|
seen[s] = struct{}{}
|
|
|
|
res = append(res, s)
|
|
|
|
}
|
|
|
|
if len(res) == l {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|
2020-01-12 23:46:51 +08:00
|
|
|
|
2020-01-13 22:50:03 +08:00
|
|
|
// sortByPriority returns a list of queue names sorted by
|
2020-01-12 23:46:51 +08:00
|
|
|
// their priority level in descending order.
|
|
|
|
func sortByPriority(qcfg map[string]uint) []string {
|
|
|
|
var queues []*queue
|
|
|
|
for qname, n := range qcfg {
|
|
|
|
queues = append(queues, &queue{qname, n})
|
|
|
|
}
|
|
|
|
sort.Sort(sort.Reverse(byPriority(queues)))
|
|
|
|
var res []string
|
|
|
|
for _, q := range queues {
|
|
|
|
res = append(res, q.name)
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
|
|
|
|
type queue struct {
|
|
|
|
name string
|
|
|
|
priority uint
|
|
|
|
}
|
|
|
|
|
|
|
|
type byPriority []*queue
|
|
|
|
|
|
|
|
func (x byPriority) Len() int { return len(x) }
|
|
|
|
func (x byPriority) Less(i, j int) bool { return x[i].priority < x[j].priority }
|
|
|
|
func (x byPriority) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
|
2020-02-02 14:22:48 +08:00
|
|
|
|
|
|
|
// normalizeQueueCfg divides priority numbers by their
|
|
|
|
// greatest common divisor.
|
|
|
|
func normalizeQueueCfg(queueCfg map[string]uint) map[string]uint {
|
|
|
|
var xs []uint
|
|
|
|
for _, x := range queueCfg {
|
|
|
|
xs = append(xs, x)
|
|
|
|
}
|
|
|
|
d := gcd(xs...)
|
|
|
|
res := make(map[string]uint)
|
|
|
|
for q, x := range queueCfg {
|
|
|
|
res[q] = x / d
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
|
|
|
|
func gcd(xs ...uint) uint {
|
|
|
|
fn := func(x, y uint) uint {
|
|
|
|
for y > 0 {
|
|
|
|
x, y = y, x%y
|
|
|
|
}
|
|
|
|
return x
|
|
|
|
}
|
|
|
|
res := xs[0]
|
|
|
|
for i := 0; i < len(xs); i++ {
|
|
|
|
res = fn(xs[i], res)
|
|
|
|
if res == 1 {
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|