-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathgotasks.go
203 lines (165 loc) · 4.75 KB
/
gotasks.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
package gotasks
import (
"context"
"log"
"runtime/debug"
"sync"
"time"
"github.com/jiajunhuang/gotasks/loop"
"github.com/jiajunhuang/gotasks/pool"
"github.com/prometheus/client_golang/prometheus"
)
// gotasks is a job/task framework for Golang.
//
// Note that job will be executed in register order, and every job handle function
// must have a signature which match gotasks.JobHandler, which receives a ArgsMap and
// return a ArgsMap which will be arguments input for next handler.
type AckWhenStatus int
const (
AckWhenAcquired AckWhenStatus = iota
AckWhenSucceed
)
var (
jobMap = map[string][]JobHandler{}
jobMapLock sync.RWMutex
ackWhen = AckWhenSucceed
ackWhenLock sync.Mutex
// gotasks builtin queue
FatalQueueName = "fatal"
// prometheus
taskHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "task_execution_stats",
Help: "task execution duration and status(success/fail)",
}, []string{"queue_name", "job_name", "status"})
taskGuage = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "task_queue_stats",
Help: "task stats in queue",
}, []string{"queue_name"})
)
func init() {
prometheus.MustRegister(taskHistogram)
prometheus.MustRegister(taskGuage)
}
// AckWhen set when will the ack be sent to broker
func AckWhen(i AckWhenStatus) {
ackWhenLock.Lock()
defer ackWhenLock.Unlock()
ackWhen = i
}
func Register(jobName string, handlers ...JobHandler) {
jobMapLock.Lock()
defer jobMapLock.Unlock()
if _, ok := jobMap[jobName]; ok {
log.Panicf("job name %s already exist, check your code", jobName)
return // never executed here
}
jobMap[jobName] = handlers
}
func runHandlers(task *Task) {
jobMapLock.RLock()
defer jobMapLock.RUnlock()
handlers, ok := jobMap[task.JobName]
if !ok {
log.Panicf("can't find job handlers of %s", task.JobName)
return
}
var (
err error
args = task.ArgsMap
)
for i, handler := range handlers {
if task.CurrentHandlerIndex > i {
log.Printf("skip step %d of task %s because it was executed successfully", i, task.ID)
continue
}
task.CurrentHandlerIndex = i
handlerName := getHandlerName(handler)
log.Printf("task %s is executing step %d with handler %s", task.ID, task.CurrentHandlerIndex, handlerName)
reentrantMapLock.RLock()
reentrantOptions, ok := reentrantMap[handlerName]
reentrantMapLock.RUnlock()
if ok { // check if the handler can retry
for j := 0; j < reentrantOptions.MaxTimes; j++ {
args, err = handler(args)
if err == nil {
break
}
time.Sleep(time.Microsecond * time.Duration(reentrantOptions.SleepyMS))
log.Printf("retry step %d of task %s the %d rd time", task.CurrentHandlerIndex, task.ID, j)
}
} else {
args, err = handler(args)
}
// error occurred
if err != nil {
log.Panicf("failed to execute handler %s: %s", handlerName, err)
}
task.ArgsMap = args
broker.Update(task)
}
}
func handleTask(task *Task, queueName string) {
defer func() {
r := recover()
status := "success"
if r != nil {
status = "fail"
task.ResultLog = string(debug.Stack())
broker.Update(task)
log.Printf("recovered from queue %s and task %+v with recover info %+v", queueName, task, r)
}
taskHistogram.WithLabelValues(task.QueueName, task.JobName, status).Observe(task.UpdatedAt.Sub(task.CreatedAt).Seconds())
if r != nil {
// save to fatal queue
task.QueueName = FatalQueueName
broker.Enqueue(task)
}
}()
runHandlers(task)
}
func run(ctx context.Context, wg *sync.WaitGroup, queue *Queue) {
defer wg.Done()
gopool := pool.NewGoPool(pool.WithMaxLimit(queue.MaxLimit))
defer gopool.Wait()
err := loop.Execute(ctx, func() {
fn := func() {
task := broker.Acquire(queue.Name)
if ackWhen == AckWhenAcquired {
ok := broker.Ack(task)
log.Printf("ack broker of task %+v with status %t", task.ID, ok)
}
handleTask(task, queue.Name)
if ackWhen == AckWhenSucceed {
ok := broker.Ack(task)
log.Printf("ack broker of task %+v with status %t", task.ID, ok)
}
}
if queue.Async {
gopool.Submit(fn)
} else {
fn()
}
})
log.Printf("worker quit for queue %s: %s", queue.Name, err)
}
func monitorQueue(ctx context.Context, wg *sync.WaitGroup, queue *Queue) {
defer wg.Done()
err := loop.Execute(ctx, func() {
taskGuage.WithLabelValues(queue.Name).Set(float64(broker.QueueLen(queue.Name)))
time.Sleep(time.Second * time.Duration(queue.MonitorInterval))
})
log.Printf("monitor quit for queue %s: %s", queue.Name, err)
}
// Run a worker that listen on queues
func Run(ctx context.Context, queueNames ...string) {
wg := sync.WaitGroup{}
wg.Add(1)
go monitorQueue(ctx, &wg, NewQueue(FatalQueueName))
for _, queueName := range queueNames {
wg.Add(2)
queue := NewQueue(queueName)
go run(ctx, &wg, queue)
go monitorQueue(ctx, &wg, queue)
}
wg.Wait()
}