2
0
mirror of https://github.com/hibiken/asynq.git synced 2024-11-14 11:31:18 +08:00
asynq/inspector.go

607 lines
16 KiB
Go
Raw Normal View History

2020-07-13 21:29:41 +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.
package asynq
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/hibiken/asynq/internal/rdb"
)
// Inspector is a client interface to inspect and mutate the state of
// queues and tasks.
type Inspector struct {
rdb *rdb.RDB
}
// New returns a new instance of Inspector.
func NewInspector(r RedisConnOpt) *Inspector {
return &Inspector{
rdb: rdb.NewRDB(createRedisClient(r)),
}
}
2020-09-08 21:52:34 +08:00
// Close closes the connection with redis.
func (i *Inspector) Close() error {
return i.rdb.Close()
}
2020-08-21 12:17:44 +08:00
// Queues returns a list of all queue names.
func (i *Inspector) Queues() ([]string, error) {
return i.rdb.AllQueues()
}
// QueueStats represents a state of queues at a certain time.
type QueueStats struct {
2020-08-17 05:51:56 +08:00
// Name of the queue.
Queue string
// Size is the total number of tasks in the queue.
2020-09-06 03:43:15 +08:00
// The value is the sum of Pending, Active, Scheduled, Retry, and Dead.
Size int
2020-09-05 22:03:43 +08:00
// Number of pending tasks.
Pending int
2020-09-06 03:43:15 +08:00
// Number of active tasks.
Active int
2020-08-17 05:51:56 +08:00
// Number of scheduled tasks.
Scheduled int
// Number of retry tasks.
Retry int
// Number of dead tasks.
Dead int
// Total number of tasks being processed during the given date.
// The number includes both succeeded and failed tasks.
Processed int
// Total number of tasks failed to be processed during the given date.
Failed int
2020-07-13 21:29:41 +08:00
// Paused indicates whether the queue is paused.
2020-08-17 05:51:56 +08:00
// If true, tasks in the queue will not be processed.
2020-07-13 21:29:41 +08:00
Paused bool
2020-08-17 05:51:56 +08:00
// Time when this stats was taken.
Timestamp time.Time
2020-07-13 21:29:41 +08:00
}
2020-08-17 05:51:56 +08:00
// CurrentStats returns a current stats of the given queue.
func (i *Inspector) CurrentStats(qname string) (*QueueStats, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return nil, err
}
2020-08-17 05:51:56 +08:00
stats, err := i.rdb.CurrentStats(qname)
2020-07-13 21:29:41 +08:00
if err != nil {
return nil, err
}
return &QueueStats{
2020-09-06 03:43:15 +08:00
Queue: stats.Queue,
Size: stats.Size,
Pending: stats.Pending,
Active: stats.Active,
Scheduled: stats.Scheduled,
Retry: stats.Retry,
Dead: stats.Dead,
Processed: stats.Processed,
Failed: stats.Failed,
Paused: stats.Paused,
Timestamp: stats.Timestamp,
2020-08-18 11:49:55 +08:00
}, nil
2020-08-17 05:51:56 +08:00
}
// DailyStats holds aggregate data for a given day for a given queue.
2020-07-13 21:29:41 +08:00
type DailyStats struct {
2020-08-17 05:51:56 +08:00
// Name of the queue.
Queue string
// Total number of tasks being processed during the given date.
// The number includes both succeeded and failed tasks.
2020-07-13 21:29:41 +08:00
Processed int
2020-08-17 05:51:56 +08:00
// Total number of tasks failed to be processed during the given date.
Failed int
// Date this stats was taken.
Date time.Time
2020-07-13 21:29:41 +08:00
}
// History returns a list of stats from the last n days.
2020-08-17 05:51:56 +08:00
func (i *Inspector) History(qname string, n int) ([]*DailyStats, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return nil, err
}
2020-08-17 05:51:56 +08:00
stats, err := i.rdb.HistoricalStats(qname, n)
2020-07-13 21:29:41 +08:00
if err != nil {
return nil, err
}
var res []*DailyStats
for _, s := range stats {
res = append(res, &DailyStats{
2020-08-17 05:51:56 +08:00
Queue: s.Queue,
2020-07-13 21:29:41 +08:00
Processed: s.Processed,
Failed: s.Failed,
Date: s.Time,
})
}
return res, nil
}
2020-09-05 22:03:43 +08:00
// PendingTask is a task in a queue and is ready to be processed.
type PendingTask struct {
2020-07-13 21:29:41 +08:00
*Task
ID string
Queue string
}
2020-09-06 03:43:15 +08:00
// ActiveTask is a task that's currently being processed.
type ActiveTask struct {
2020-07-13 21:29:41 +08:00
*Task
2020-08-17 05:51:56 +08:00
ID string
Queue string
2020-07-13 21:29:41 +08:00
}
// ScheduledTask is a task scheduled to be processed in the future.
type ScheduledTask struct {
*Task
ID string
Queue string
2020-09-05 22:11:55 +08:00
NextProcessAt time.Time
2020-07-13 21:29:41 +08:00
score int64
}
// RetryTask is a task scheduled to be retried in the future.
type RetryTask struct {
*Task
ID string
Queue string
2020-09-05 22:11:55 +08:00
NextProcessAt time.Time
2020-07-13 21:29:41 +08:00
MaxRetry int
Retried int
ErrorMsg string
// TODO: LastFailedAt time.Time
score int64
}
// DeadTask is a task exhausted its retries.
// DeadTask won't be retried automatically.
type DeadTask struct {
*Task
ID string
Queue string
MaxRetry int
Retried int
LastFailedAt time.Time
ErrorMsg string
score int64
}
// Key returns a key used to delete, run, and kill the task.
2020-07-13 21:29:41 +08:00
func (t *ScheduledTask) Key() string {
return fmt.Sprintf("s:%v:%v", t.ID, t.score)
}
// Key returns a key used to delete, run, and kill the task.
2020-07-13 21:29:41 +08:00
func (t *RetryTask) Key() string {
return fmt.Sprintf("r:%v:%v", t.ID, t.score)
}
// Key returns a key used to delete, run, and kill the task.
2020-07-13 21:29:41 +08:00
func (t *DeadTask) Key() string {
return fmt.Sprintf("d:%v:%v", t.ID, t.score)
}
// parseTaskKey parses a key string and returns each part of key with proper
// type if valid, otherwise it reports an error.
2020-08-17 05:51:56 +08:00
func parseTaskKey(key string) (id uuid.UUID, score int64, state string, err error) {
2020-07-13 21:29:41 +08:00
parts := strings.Split(key, ":")
if len(parts) != 3 {
return uuid.Nil, 0, "", fmt.Errorf("invalid id")
}
id, err = uuid.Parse(parts[1])
if err != nil {
return uuid.Nil, 0, "", fmt.Errorf("invalid id")
}
score, err = strconv.ParseInt(parts[2], 10, 64)
if err != nil {
return uuid.Nil, 0, "", fmt.Errorf("invalid id")
}
2020-08-17 05:51:56 +08:00
state = parts[0]
if len(state) != 1 || !strings.Contains("srd", state) {
2020-07-13 21:29:41 +08:00
return uuid.Nil, 0, "", fmt.Errorf("invalid id")
}
2020-08-17 05:51:56 +08:00
return id, score, state, nil
2020-07-13 21:29:41 +08:00
}
// ListOption specifies behavior of list operation.
type ListOption interface{}
// Internal list option representations.
type (
pageSizeOpt int
pageNumOpt int
)
type listOption struct {
pageSize int
pageNum int
}
const (
// Page size used by default in list operation.
defaultPageSize = 30
// Page number used by default in list operation.
defaultPageNum = 1
)
func composeListOptions(opts ...ListOption) listOption {
res := listOption{
pageSize: defaultPageSize,
pageNum: defaultPageNum,
}
for _, opt := range opts {
switch opt := opt.(type) {
case pageSizeOpt:
res.pageSize = int(opt)
case pageNumOpt:
res.pageNum = int(opt)
default:
// ignore unexpected option
}
}
return res
}
// PageSize returns an option to specify the page size for list operation.
//
// Negative page size is treated as zero.
func PageSize(n int) ListOption {
if n < 0 {
n = 0
}
return pageSizeOpt(n)
}
// Page returns an option to specify the page number for list operation.
// The value 1 fetches the first page.
//
// Negative page number is treated as one.
func Page(n int) ListOption {
if n < 0 {
n = 1
}
return pageNumOpt(n)
}
2020-09-05 22:03:43 +08:00
// ListPendingTasks retrieves pending tasks from the specified queue.
2020-07-13 21:29:41 +08:00
//
// By default, it retrieves the first 30 tasks.
2020-09-05 22:03:43 +08:00
func (i *Inspector) ListPendingTasks(qname string, opts ...ListOption) ([]*PendingTask, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return nil, err
}
2020-07-13 21:29:41 +08:00
opt := composeListOptions(opts...)
pgn := rdb.Pagination{Size: opt.pageSize, Page: opt.pageNum - 1}
2020-09-05 22:03:43 +08:00
msgs, err := i.rdb.ListPending(qname, pgn)
2020-07-13 21:29:41 +08:00
if err != nil {
return nil, err
}
2020-09-05 22:03:43 +08:00
var tasks []*PendingTask
2020-07-13 21:29:41 +08:00
for _, m := range msgs {
2020-09-05 22:03:43 +08:00
tasks = append(tasks, &PendingTask{
2020-07-13 21:29:41 +08:00
Task: NewTask(m.Type, m.Payload),
ID: m.ID.String(),
Queue: m.Queue,
})
}
return tasks, err
}
2020-09-06 03:43:15 +08:00
// ListActiveTasks retrieves active tasks from the specified queue.
2020-07-13 21:29:41 +08:00
//
// By default, it retrieves the first 30 tasks.
2020-09-06 03:43:15 +08:00
func (i *Inspector) ListActiveTasks(qname string, opts ...ListOption) ([]*ActiveTask, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return nil, err
}
2020-07-13 21:29:41 +08:00
opt := composeListOptions(opts...)
pgn := rdb.Pagination{Size: opt.pageSize, Page: opt.pageNum - 1}
2020-09-06 03:43:15 +08:00
msgs, err := i.rdb.ListActive(qname, pgn)
2020-07-13 21:29:41 +08:00
if err != nil {
return nil, err
}
2020-09-06 03:43:15 +08:00
var tasks []*ActiveTask
2020-07-13 21:29:41 +08:00
for _, m := range msgs {
2020-09-06 03:43:15 +08:00
tasks = append(tasks, &ActiveTask{
2020-08-17 05:51:56 +08:00
Task: NewTask(m.Type, m.Payload),
ID: m.ID.String(),
Queue: m.Queue,
2020-07-13 21:29:41 +08:00
})
}
return tasks, err
}
2020-08-17 05:51:56 +08:00
// ListScheduledTasks retrieves scheduled tasks from the specified queue.
2020-09-05 22:11:55 +08:00
// Tasks are sorted by NextProcessAt field in ascending order.
2020-07-13 21:29:41 +08:00
//
// By default, it retrieves the first 30 tasks.
2020-08-17 05:51:56 +08:00
func (i *Inspector) ListScheduledTasks(qname string, opts ...ListOption) ([]*ScheduledTask, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return nil, err
}
2020-07-13 21:29:41 +08:00
opt := composeListOptions(opts...)
pgn := rdb.Pagination{Size: opt.pageSize, Page: opt.pageNum - 1}
2020-08-17 05:51:56 +08:00
zs, err := i.rdb.ListScheduled(qname, pgn)
2020-07-13 21:29:41 +08:00
if err != nil {
return nil, err
}
var tasks []*ScheduledTask
for _, z := range zs {
2020-09-05 22:11:55 +08:00
processAt := time.Unix(z.Score, 0)
2020-07-13 21:29:41 +08:00
t := NewTask(z.Message.Type, z.Message.Payload)
tasks = append(tasks, &ScheduledTask{
Task: t,
ID: z.Message.ID.String(),
Queue: z.Message.Queue,
2020-09-05 22:11:55 +08:00
NextProcessAt: processAt,
2020-07-13 21:29:41 +08:00
score: z.Score,
})
}
return tasks, nil
}
2020-08-17 05:51:56 +08:00
// ListRetryTasks retrieves retry tasks from the specified queue.
2020-09-05 22:11:55 +08:00
// Tasks are sorted by NextProcessAt field in ascending order.
2020-07-13 21:29:41 +08:00
//
// By default, it retrieves the first 30 tasks.
2020-08-17 05:51:56 +08:00
func (i *Inspector) ListRetryTasks(qname string, opts ...ListOption) ([]*RetryTask, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return nil, err
}
2020-07-13 21:29:41 +08:00
opt := composeListOptions(opts...)
pgn := rdb.Pagination{Size: opt.pageSize, Page: opt.pageNum - 1}
2020-08-17 05:51:56 +08:00
zs, err := i.rdb.ListRetry(qname, pgn)
2020-07-13 21:29:41 +08:00
if err != nil {
return nil, err
}
var tasks []*RetryTask
for _, z := range zs {
2020-09-05 22:11:55 +08:00
processAt := time.Unix(z.Score, 0)
2020-07-13 21:29:41 +08:00
t := NewTask(z.Message.Type, z.Message.Payload)
tasks = append(tasks, &RetryTask{
Task: t,
ID: z.Message.ID.String(),
Queue: z.Message.Queue,
2020-09-05 22:11:55 +08:00
NextProcessAt: processAt,
2020-07-13 21:29:41 +08:00
MaxRetry: z.Message.Retry,
Retried: z.Message.Retried,
// TODO: LastFailedAt: z.Message.LastFailedAt
ErrorMsg: z.Message.ErrorMsg,
score: z.Score,
})
}
return tasks, nil
}
2020-08-17 05:51:56 +08:00
// ListDeadTasks retrieves dead tasks from the specified queue.
2020-07-13 21:29:41 +08:00
// Tasks are sorted by LastFailedAt field in descending order.
//
// By default, it retrieves the first 30 tasks.
2020-08-17 05:51:56 +08:00
func (i *Inspector) ListDeadTasks(qname string, opts ...ListOption) ([]*DeadTask, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return nil, err
}
2020-07-13 21:29:41 +08:00
opt := composeListOptions(opts...)
pgn := rdb.Pagination{Size: opt.pageSize, Page: opt.pageNum - 1}
2020-08-17 05:51:56 +08:00
zs, err := i.rdb.ListDead(qname, pgn)
2020-07-13 21:29:41 +08:00
if err != nil {
return nil, err
}
var tasks []*DeadTask
for _, z := range zs {
failedAt := time.Unix(z.Score, 0)
t := NewTask(z.Message.Type, z.Message.Payload)
tasks = append(tasks, &DeadTask{
Task: t,
ID: z.Message.ID.String(),
Queue: z.Message.Queue,
MaxRetry: z.Message.Retry,
Retried: z.Message.Retried,
LastFailedAt: failedAt,
ErrorMsg: z.Message.ErrorMsg,
score: z.Score,
})
}
return tasks, nil
return nil, nil
}
2020-08-17 05:51:56 +08:00
// DeleteAllScheduledTasks deletes all scheduled tasks from the specified queue,
2020-07-13 21:29:41 +08:00
// and reports the number tasks deleted.
2020-08-17 05:51:56 +08:00
func (i *Inspector) DeleteAllScheduledTasks(qname string) (int, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return 0, err
}
2020-08-17 05:51:56 +08:00
n, err := i.rdb.DeleteAllScheduledTasks(qname)
2020-07-13 21:29:41 +08:00
return int(n), err
}
2020-08-17 05:51:56 +08:00
// DeleteAllRetryTasks deletes all retry tasks from the specified queue,
2020-07-13 21:29:41 +08:00
// and reports the number tasks deleted.
2020-08-17 05:51:56 +08:00
func (i *Inspector) DeleteAllRetryTasks(qname string) (int, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return 0, err
}
2020-08-17 05:51:56 +08:00
n, err := i.rdb.DeleteAllRetryTasks(qname)
2020-07-13 21:29:41 +08:00
return int(n), err
}
2020-08-17 05:51:56 +08:00
// DeleteAllDeadTasks deletes all dead tasks from the specified queue,
2020-07-13 21:29:41 +08:00
// and reports the number tasks deleted.
2020-08-17 05:51:56 +08:00
func (i *Inspector) DeleteAllDeadTasks(qname string) (int, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return 0, err
}
2020-08-17 05:51:56 +08:00
n, err := i.rdb.DeleteAllDeadTasks(qname)
2020-07-13 21:29:41 +08:00
return int(n), err
}
2020-08-17 05:51:56 +08:00
// DeleteTaskByKey deletes a task with the given key from the given queue.
func (i *Inspector) DeleteTaskByKey(qname, key string) error {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return err
}
2020-08-17 05:51:56 +08:00
id, score, state, err := parseTaskKey(key)
2020-07-13 21:29:41 +08:00
if err != nil {
return err
}
2020-08-17 05:51:56 +08:00
switch state {
2020-07-13 21:29:41 +08:00
case "s":
2020-08-17 05:51:56 +08:00
return i.rdb.DeleteScheduledTask(qname, id, score)
2020-07-13 21:29:41 +08:00
case "r":
2020-08-17 05:51:56 +08:00
return i.rdb.DeleteRetryTask(qname, id, score)
2020-07-13 21:29:41 +08:00
case "d":
2020-08-17 05:51:56 +08:00
return i.rdb.DeleteDeadTask(qname, id, score)
2020-07-13 21:29:41 +08:00
default:
return fmt.Errorf("invalid key")
}
}
// RunAllScheduledTasks transition all scheduled tasks to pending state within the given queue,
// and reports the number of tasks transitioned.
func (i *Inspector) RunAllScheduledTasks(qname string) (int, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return 0, err
}
n, err := i.rdb.RunAllScheduledTasks(qname)
2020-07-13 21:29:41 +08:00
return int(n), err
}
// RunAllRetryTasks transition all retry tasks to pending state within the given queue,
// and reports the number of tasks transitioned.
func (i *Inspector) RunAllRetryTasks(qname string) (int, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return 0, err
}
n, err := i.rdb.RunAllRetryTasks(qname)
2020-07-13 21:29:41 +08:00
return int(n), err
}
// RunAllDeadTasks transition all dead tasks to pending state within the given queue,
// and reports the number of tasks transitioned.
func (i *Inspector) RunAllDeadTasks(qname string) (int, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return 0, err
}
n, err := i.rdb.RunAllDeadTasks(qname)
2020-07-13 21:29:41 +08:00
return int(n), err
}
// RunTaskByKey transition a task to pending state given task key and queue name.
func (i *Inspector) RunTaskByKey(qname, key string) error {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return err
}
2020-08-17 05:51:56 +08:00
id, score, state, err := parseTaskKey(key)
2020-07-13 21:29:41 +08:00
if err != nil {
return err
}
2020-08-17 05:51:56 +08:00
switch state {
2020-07-13 21:29:41 +08:00
case "s":
return i.rdb.RunScheduledTask(qname, id, score)
2020-07-13 21:29:41 +08:00
case "r":
return i.rdb.RunRetryTask(qname, id, score)
2020-07-13 21:29:41 +08:00
case "d":
return i.rdb.RunDeadTask(qname, id, score)
2020-07-13 21:29:41 +08:00
default:
return fmt.Errorf("invalid key")
}
}
2020-08-17 05:51:56 +08:00
// KillAllScheduledTasks kills all scheduled tasks within the given queue,
2020-07-13 21:29:41 +08:00
// and reports the number of tasks killed.
2020-08-17 05:51:56 +08:00
func (i *Inspector) KillAllScheduledTasks(qname string) (int, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return 0, err
}
2020-08-17 05:51:56 +08:00
n, err := i.rdb.KillAllScheduledTasks(qname)
2020-07-13 21:29:41 +08:00
return int(n), err
}
2020-08-17 05:51:56 +08:00
// KillAllRetryTasks kills all retry tasks within the given queue,
2020-07-13 21:29:41 +08:00
// and reports the number of tasks killed.
2020-08-17 05:51:56 +08:00
func (i *Inspector) KillAllRetryTasks(qname string) (int, error) {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return 0, err
}
2020-08-17 05:51:56 +08:00
n, err := i.rdb.KillAllRetryTasks(qname)
2020-07-13 21:29:41 +08:00
return int(n), err
}
2020-08-17 05:51:56 +08:00
// KillTaskByKey kills a task with the given key in the given queue.
func (i *Inspector) KillTaskByKey(qname, key string) error {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return err
}
2020-08-17 05:51:56 +08:00
id, score, state, err := parseTaskKey(key)
2020-07-13 21:29:41 +08:00
if err != nil {
return err
}
2020-08-17 05:51:56 +08:00
switch state {
2020-07-13 21:29:41 +08:00
case "s":
2020-08-17 05:51:56 +08:00
return i.rdb.KillScheduledTask(qname, id, score)
2020-07-13 21:29:41 +08:00
case "r":
2020-08-17 05:51:56 +08:00
return i.rdb.KillRetryTask(qname, id, score)
2020-07-13 21:29:41 +08:00
case "d":
return fmt.Errorf("task already dead")
default:
return fmt.Errorf("invalid key")
}
}
// PauseQueue pauses task processing on the specified queue.
// If the queue is already paused, it will return a non-nil error.
func (i *Inspector) PauseQueue(qname string) error {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return err
}
return i.rdb.Pause(qname)
}
// UnpauseQueue resumes task processing on the specified queue.
// If the queue is not paused, it will return a non-nil error.
func (i *Inspector) UnpauseQueue(qname string) error {
2020-08-31 20:53:17 +08:00
if err := validateQueueName(qname); err != nil {
return err
}
return i.rdb.Unpause(qname)
}
// ClusterKeySlot returns an integer identifying the hash slot the given queue hashes to.
func (i *Inspector) ClusterKeySlot(qname string) (int64, error) {
return i.rdb.ClusterKeySlot(qname)
}
// ClusterNode describes a node in redis cluster.
type ClusterNode struct {
// Node ID in the cluster.
ID string
// Address of the node.
Addr string
}
// ClusterNode returns a list of nodes the given queue belongs to.
func (i *Inspector) ClusterNodes(qname string) ([]ClusterNode, error) {
nodes, err := i.rdb.ClusterNodes(qname)
if err != nil {
return nil, err
}
var res []ClusterNode
for _, node := range nodes {
res = append(res, ClusterNode{ID: node.ID, Addr: node.Addr})
}
return res, nil
}