-
Notifications
You must be signed in to change notification settings - Fork 6
/
worker.go
278 lines (237 loc) · 7.36 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
package beanstalkworker
import (
"context"
"encoding/json"
"github.com/beanstalkd/go-beanstalk"
"reflect"
"strconv"
"sync"
"time"
)
// Handler provides an interface type for callback functions.
type Handler interface{}
// Worker represents a single process that is connecting to beanstalkd
// and is consuming jobs from one or more tubes.
type Worker struct {
addr string
tubeSubs map[string]func(*RawJob)
numWorkers int
wg sync.WaitGroup
log *Logger
unmarshalErrorAction string
}
// NewWorker creates a new worker process,
// but does not actually connect to beanstalkd server yet.
func NewWorker(addr string) *Worker {
return &Worker{
addr: addr,
tubeSubs: make(map[string]func(*RawJob)),
log: NewDefaultLogger(),
unmarshalErrorAction: ActionReleaseJob, // It ensures the job is released to the queue by default for unmarshal error.
}
}
// SetNumWorkers sets the number of concurrent workers threads that should be started.
// Each thread establishes a separate connection to the beanstalkd server.
func (w *Worker) SetNumWorkers(numWorkers int) {
w.numWorkers = numWorkers
}
// SetLogger switches logging to use a custom Logger.
func (w *Worker) SetLogger(cl CustomLogger) {
w.log.Info = cl.Info
w.log.Infof = cl.Infof
w.log.Error = cl.Error
w.log.Errorf = cl.Errorf
}
// Subscribe adds a handler function to be run for jobs coming from a particular tube.
func (w *Worker) Subscribe(tube string, cb Handler) {
w.tubeSubs[tube] = func(job *RawJob) {
jobVal := reflect.ValueOf(job)
cbFunc := reflect.ValueOf(cb)
cbType := reflect.TypeOf(cb)
if cbType.Kind() != reflect.Func {
panic("Handler needs to be a func")
}
dataType := cbType.In(1)
dataPtr := reflect.New(dataType)
if err := json.Unmarshal(*job.body, dataPtr.Interface()); err != nil {
job.LogError("Error decoding JSON for job: ", err, ", '", string(*job.body), "', "+w.unmarshalErrorAction+"...")
// Delete, Bury or Release (default behaviour) the job to the queue, depending on the user choice.
job.unmarshalErrorAction(w.unmarshalErrorAction)
return
}
cbFunc.Call([]reflect.Value{jobVal, reflect.Indirect(dataPtr)})
}
}
// Run starts one or more worker threads based on the numWorkers value.
// If numWorkers is set to zero or less then 1 worker is started.
func (w *Worker) Run(ctx context.Context) {
if w.numWorkers <= 0 {
w.numWorkers = 1
}
if len(w.tubeSubs) <= 0 {
w.log.Error("No job subscriptions defined, cannot proceed.")
return
}
for i := 0; i < w.numWorkers; i++ {
w.wg.Add(1) //Increment wait group count to represent new worker.
go w.startWorker(ctx)
}
w.wg.Wait() //Block here until all workers cleanly finish.
}
// SetUnmarshalErrorAction defines what to do if there is an unmarshal error.
func (w *Worker) SetUnmarshalErrorAction(action string) {
// If this action is different than Delete, Bury or Release, the last one will be chosen
// as the default action in case of an unmarshal error, via the method job.unmarshalErrorHandling.
if action != ActionDeleteJob && action != ActionBuryJob {
w.unmarshalErrorAction = ActionReleaseJob // By safety only and to keep log message consistent with the action.
return
}
w.unmarshalErrorAction = action
}
// startWorker activates a single worker and attempts to maintain a connection to the beanstalkd server.
func (w *Worker) startWorker(ctx context.Context) {
defer w.log.Info("Worker stopped!")
defer w.wg.Done()
for {
//Check the process hasn't been cancelled whilst we are connecting.
select {
case <-ctx.Done():
return
default:
}
conn, err := beanstalk.Dial("tcp", w.addr)
if err != nil {
w.log.Error("Error connecting to beanstalkd: ", err)
time.Sleep(5 * time.Second)
continue
}
defer conn.Close()
watchTubes := make([]string, 0, len(w.tubeSubs))
for tube := range w.tubeSubs {
watchTubes = append(watchTubes, tube)
}
tubes := beanstalk.NewTubeSet(conn, watchTubes...)
w.log.Infof("Connected, watching %v for new jobs", watchTubes)
jobCh := make(chan *RawJob)
loop:
for {
go w.getNextJob(jobCh, tubes)
select {
case <-ctx.Done():
//Context has been cancelled, time to finish up.
return
case job := <-jobCh:
//Handle job from the beanstalkd server.
if job.err != nil {
if job.err.Error() == "reserve-with-timeout: timeout" {
continue
} else if job.err.Error() == "reserve-with-timeout: deadline soon" {
//Dont re-poll too often. This is important because otherwise we
//end up in a busy wait loop for 1s spinning up go routines.
time.Sleep(2 * time.Second)
continue
}
//Some other problem so restart connection to beanstalkd.
w.log.Error("Error getting job from tube: ", job.err)
break loop
}
w.subHandler(job)
}
}
conn.Close() //We will reconnect in next loop iteration.
}
}
// getNextJob retrieves the next job from the tubes being watched.
func (w *Worker) getNextJob(jobCh chan *RawJob, tubes *beanstalk.TubeSet) {
id, body, err := tubes.Reserve(60 * time.Second)
job := &RawJob{
id: id,
body: &body,
err: err,
conn: tubes.Conn,
log: w.log,
}
if err != nil {
jobCh <- job
return
}
//Look up job stats.
stats, err := tubes.Conn.StatsJob(job.id)
if err != nil {
job.err = err
jobCh <- job
return
}
//Cache tube job was received from in the job.
job.tube = stats["tube"]
///Convert string age into time.Duration and cache in job.
age, err := strconv.Atoi(stats["age"])
if err != nil {
job.err = err
jobCh <- job
return
}
job.age = time.Duration(age) * time.Second
///Convert string delay into time.Duration and cache in job.
delay, err := strconv.Atoi(stats["delay"])
if err != nil {
job.err = err
jobCh <- job
return
}
job.delay = time.Duration(delay) * time.Second
//Initialise the return delay as the current delay.
job.returnDelay = job.delay
//If the initial returnDelay is 0s, then set to 60s.
//This ensures that if job umarshalling fails that we don't get the job
//repeatedly re-released without any delay.
//If you do need a 0s delay, use SetReturnDelay() in the handler function.
if job.returnDelay <= 0 {
job.returnDelay = 60 * time.Second
}
//Convert string priority into uint32 and cache in job.
prio, err := strconv.Atoi(stats["pri"])
if err != nil {
job.err = err
jobCh <- job
return
}
job.prio = uint32(prio)
//Initialise the return priority as the current priority.
job.returnPrio = job.prio
//Convert string releases into uint32 and cache in job.
releases, err := strconv.Atoi(stats["releases"])
if err != nil {
job.err = err
jobCh <- job
return
}
job.releases = uint32(releases)
//Convert string reserves into uint32 and cache in job.
reserves, err := strconv.Atoi(stats["reserves"])
if err != nil {
job.err = err
jobCh <- job
return
}
job.reserves = uint32(reserves)
//Convert string timeouts into uint32 and cache in job.
timeouts, err := strconv.Atoi(stats["timeouts"])
if err != nil {
job.err = err
jobCh <- job
return
}
job.timeouts = uint32(timeouts)
//Send the job to the receiver channel.
jobCh <- job
}
// subHandler finds and executes any subcriber function for a job.
func (w *Worker) subHandler(job *RawJob) {
tube := job.GetTube()
if cb, ok := w.tubeSubs[tube]; ok {
cb(job)
} else {
panic("Should not get a job with no handler function")
}
}