/
redis.go
487 lines (413 loc) · 12.3 KB
/
redis.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
package redis
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math"
"runtime"
"sync"
"time"
"github.com/go-redsync/redsync/v4"
redsyncredis "github.com/go-redsync/redsync/v4/redis/redigo"
"github.com/gomodule/redigo/redis"
"github.com/RichardKnop/machinery/v2/brokers/errs"
"github.com/RichardKnop/machinery/v2/brokers/iface"
"github.com/RichardKnop/machinery/v2/common"
"github.com/RichardKnop/machinery/v2/config"
"github.com/RichardKnop/machinery/v2/log"
"github.com/RichardKnop/machinery/v2/tasks"
)
const defaultRedisDelayedTasksKey = "delayed_tasks"
// Broker represents a Redis broker
type Broker struct {
common.Broker
common.RedisConnector
host string
password string
db int
pool *redis.Pool
consumingWG sync.WaitGroup // wait group to make sure whole consumption completes
processingWG sync.WaitGroup // use wait group to make sure task processing completes
delayedWG sync.WaitGroup
// If set, path to a socket file overrides hostname
socketPath string
redsync *redsync.Redsync
redisOnce sync.Once
redisDelayedTasksKey string
}
// New creates new Broker instance
func New(cnf *config.Config, host, password, socketPath string, db int) iface.Broker {
b := &Broker{Broker: common.NewBroker(cnf)}
b.host = host
b.db = db
b.password = password
b.socketPath = socketPath
if cnf.Redis != nil && cnf.Redis.DelayedTasksKey != "" {
b.redisDelayedTasksKey = cnf.Redis.DelayedTasksKey
} else {
b.redisDelayedTasksKey = defaultRedisDelayedTasksKey
}
return b
}
// StartConsuming enters a loop and waits for incoming messages
func (b *Broker) StartConsuming(consumerTag string, concurrency int, taskProcessor iface.TaskProcessor) (bool, error) {
b.consumingWG.Add(1)
defer b.consumingWG.Done()
if concurrency < 1 {
concurrency = runtime.NumCPU() * 2
}
b.Broker.StartConsuming(consumerTag, concurrency, taskProcessor)
conn := b.open()
defer conn.Close()
// Ping the server to make sure connection is live
_, err := conn.Do("PING")
if err != nil {
b.GetRetryFunc()(b.GetRetryStopChan())
// Return err if retry is still true.
// If retry is false, broker.StopConsuming() has been called and
// therefore Redis might have been stopped. Return nil exit
// StartConsuming()
if b.GetRetry() {
return b.GetRetry(), err
}
return b.GetRetry(), errs.ErrConsumerStopped
}
// Channel to which we will push tasks ready for processing by worker
deliveries := make(chan []byte, concurrency)
pool := make(chan struct{}, concurrency)
// initialize worker pool with maxWorkers workers
for i := 0; i < concurrency; i++ {
pool <- struct{}{}
}
// A receiving goroutine keeps popping messages from the queue by BLPOP
// If the message is valid and can be unmarshaled into a proper structure
// we send it to the deliveries channel
go func() {
log.INFO.Print("[*] Waiting for messages. To exit press CTRL+C")
for {
select {
// A way to stop this goroutine from b.StopConsuming
case <-b.GetStopChan():
close(deliveries)
return
case <-pool:
select {
case <-b.GetStopChan():
close(deliveries)
return
default:
}
if taskProcessor.PreConsumeHandler() {
task, _ := b.nextTask(getQueue(b.GetConfig(), taskProcessor))
//TODO: should this error be ignored?
if len(task) > 0 {
deliveries <- task
}
}
pool <- struct{}{}
}
}
}()
// A goroutine to watch for delayed tasks and push them to deliveries
// channel for consumption by the worker
b.delayedWG.Add(1)
go func() {
defer b.delayedWG.Done()
for {
select {
// A way to stop this goroutine from b.StopConsuming
case <-b.GetStopChan():
return
default:
task, err := b.nextDelayedTask(b.redisDelayedTasksKey)
if err != nil {
continue
}
signature := new(tasks.Signature)
decoder := json.NewDecoder(bytes.NewReader(task))
decoder.UseNumber()
if err := decoder.Decode(signature); err != nil {
log.ERROR.Print(errs.NewErrCouldNotUnmarshalTaskSignature(task, err))
}
if err := b.Publish(context.Background(), signature); err != nil {
log.ERROR.Print(err)
}
}
}
}()
if err := b.consume(deliveries, concurrency, taskProcessor); err != nil {
return b.GetRetry(), err
}
// Waiting for any tasks being processed to finish
b.processingWG.Wait()
return b.GetRetry(), nil
}
// StopConsuming quits the loop
func (b *Broker) StopConsuming() {
b.Broker.StopConsuming()
// Waiting for the delayed tasks goroutine to have stopped
b.delayedWG.Wait()
// Waiting for consumption to finish
b.consumingWG.Wait()
// Wait for currently processing tasks to finish as well.
b.processingWG.Wait()
if b.pool != nil {
b.pool.Close()
}
}
// Publish places a new message on the default queue
func (b *Broker) Publish(ctx context.Context, signature *tasks.Signature) error {
// Adjust routing key (this decides which queue the message will be published to)
b.Broker.AdjustRoutingKey(signature)
msg, err := json.Marshal(signature)
if err != nil {
return fmt.Errorf("JSON marshal error: %s", err)
}
conn := b.open()
defer conn.Close()
// Check the ETA signature field, if it is set and it is in the future,
// delay the task
if signature.ETA != nil {
now := time.Now().UTC()
if signature.ETA.After(now) {
score := signature.ETA.UnixNano()
_, err = conn.Do("ZADD", b.redisDelayedTasksKey, score, msg)
return err
}
}
_, err = conn.Do("RPUSH", signature.RoutingKey, msg)
return err
}
// GetPendingTasks returns a slice of task signatures waiting in the queue
func (b *Broker) GetPendingTasks(queue string) ([]*tasks.Signature, error) {
conn := b.open()
defer conn.Close()
if queue == "" {
queue = b.GetConfig().DefaultQueue
}
dataBytes, err := conn.Do("LRANGE", queue, 0, -1)
if err != nil {
return nil, err
}
results, err := redis.ByteSlices(dataBytes, err)
if err != nil {
return nil, err
}
taskSignatures := make([]*tasks.Signature, len(results))
for i, result := range results {
signature := new(tasks.Signature)
decoder := json.NewDecoder(bytes.NewReader(result))
decoder.UseNumber()
if err := decoder.Decode(signature); err != nil {
return nil, err
}
taskSignatures[i] = signature
}
return taskSignatures, nil
}
// GetDelayedTasks returns a slice of task signatures that are scheduled, but not yet in the queue
func (b *Broker) GetDelayedTasks() ([]*tasks.Signature, error) {
conn := b.open()
defer conn.Close()
dataBytes, err := conn.Do("ZRANGE", b.redisDelayedTasksKey, 0, -1)
if err != nil {
return nil, err
}
results, err := redis.ByteSlices(dataBytes, err)
if err != nil {
return nil, err
}
taskSignatures := make([]*tasks.Signature, len(results))
for i, result := range results {
signature := new(tasks.Signature)
decoder := json.NewDecoder(bytes.NewReader(result))
decoder.UseNumber()
if err := decoder.Decode(signature); err != nil {
return nil, err
}
taskSignatures[i] = signature
}
return taskSignatures, nil
}
// consume takes delivered messages from the channel and manages a worker pool
// to process tasks concurrently
func (b *Broker) consume(deliveries <-chan []byte, concurrency int, taskProcessor iface.TaskProcessor) error {
errorsChan := make(chan error, concurrency*2)
pool := make(chan struct{}, concurrency)
// init pool for Worker tasks execution, as many slots as Worker concurrency param
go func() {
for i := 0; i < concurrency; i++ {
pool <- struct{}{}
}
}()
for {
select {
case err := <-errorsChan:
return err
case d, open := <-deliveries:
if !open {
return nil
}
if concurrency > 0 {
// get execution slot from pool (blocks until one is available)
select {
case <-b.GetStopChan():
b.requeueMessage(d, taskProcessor)
continue
case <-pool:
}
}
b.processingWG.Add(1)
// Consume the task inside a goroutine so multiple tasks
// can be processed concurrently
go func() {
if err := b.consumeOne(d, taskProcessor); err != nil {
errorsChan <- err
}
b.processingWG.Done()
if concurrency > 0 {
// give slot back to pool
pool <- struct{}{}
}
}()
}
}
}
// consumeOne processes a single message using TaskProcessor
func (b *Broker) consumeOne(delivery []byte, taskProcessor iface.TaskProcessor) error {
signature := new(tasks.Signature)
decoder := json.NewDecoder(bytes.NewReader(delivery))
decoder.UseNumber()
if err := decoder.Decode(signature); err != nil {
return errs.NewErrCouldNotUnmarshalTaskSignature(delivery, err)
}
// If the task is not registered, we requeue it,
// there might be different workers for processing specific tasks
if !b.IsTaskRegistered(signature.Name) {
if signature.IgnoreWhenTaskNotRegistered {
return nil
}
log.INFO.Printf("Task not registered with this worker. Requeuing message: %s", delivery)
b.requeueMessage(delivery, taskProcessor)
return nil
}
log.DEBUG.Printf("Received new message: %s", delivery)
return taskProcessor.Process(signature)
}
// nextTask pops next available task from the default queue
func (b *Broker) nextTask(queue string) (result []byte, err error) {
conn := b.open()
defer conn.Close()
pollPeriodMilliseconds := 1000 // default poll period for normal tasks
if b.GetConfig().Redis != nil {
configuredPollPeriod := b.GetConfig().Redis.NormalTasksPollPeriod
if configuredPollPeriod > 0 {
pollPeriodMilliseconds = configuredPollPeriod
}
}
pollPeriod := time.Duration(pollPeriodMilliseconds) * time.Millisecond
// Issue 548: BLPOP expects an integer timeout expresses in seconds.
// The call will if the value is a float. Convert to integer using
// math.Ceil():
// math.Ceil(0.0) --> 0 (block indefinitely)
// math.Ceil(0.2) --> 1 (timeout after 1 second)
pollPeriodSeconds := math.Ceil(pollPeriod.Seconds())
items, err := redis.ByteSlices(conn.Do("BLPOP", queue, pollPeriodSeconds))
if err != nil {
return []byte{}, err
}
// items[0] - the name of the key where an element was popped
// items[1] - the value of the popped element
if len(items) != 2 {
return []byte{}, redis.ErrNil
}
result = items[1]
return result, nil
}
// nextDelayedTask pops a value from the ZSET key using WATCH/MULTI/EXEC commands.
// https://github.com/gomodule/redigo/blob/master/redis/zpop_example_test.go
func (b *Broker) nextDelayedTask(key string) (result []byte, err error) {
conn := b.open()
defer conn.Close()
defer func() {
// Return connection to normal state on error.
// https://redis.io/commands/discard
// https://redis.io/commands/unwatch
if err == redis.ErrNil {
conn.Do("UNWATCH")
} else if err != nil {
conn.Do("DISCARD")
}
}()
var (
items [][]byte
reply interface{}
)
pollPeriod := 500 // default poll period for delayed tasks
if b.GetConfig().Redis != nil {
configuredPollPeriod := b.GetConfig().Redis.DelayedTasksPollPeriod
// the default period is 0, which bombards redis with requests, despite
// our intention of doing the opposite
if configuredPollPeriod > 0 {
pollPeriod = configuredPollPeriod
}
}
for {
// Space out queries to ZSET so we don't bombard redis
// server with relentless ZRANGEBYSCOREs
time.Sleep(time.Duration(pollPeriod) * time.Millisecond)
if _, err = conn.Do("WATCH", key); err != nil {
return
}
now := time.Now().UTC().UnixNano()
// https://redis.io/commands/zrangebyscore
items, err = redis.ByteSlices(conn.Do(
"ZRANGEBYSCORE",
key,
0,
now,
"LIMIT",
0,
1,
))
if err != nil {
return
}
if len(items) != 1 {
err = redis.ErrNil
return
}
_ = conn.Send("MULTI")
_ = conn.Send("ZREM", key, items[0])
reply, err = conn.Do("EXEC")
if err != nil {
return
}
if reply != nil {
result = items[0]
break
}
}
return
}
// open returns or creates instance of Redis connection
func (b *Broker) open() redis.Conn {
b.redisOnce.Do(func() {
b.pool = b.NewPool(b.socketPath, b.host, b.password, b.db, b.GetConfig().Redis, b.GetConfig().TLSConfig)
b.redsync = redsync.New(redsyncredis.NewPool(b.pool))
})
return b.pool.Get()
}
func getQueue(config *config.Config, taskProcessor iface.TaskProcessor) string {
customQueue := taskProcessor.CustomQueue()
if customQueue == "" {
return config.DefaultQueue
}
return customQueue
}
func (b *Broker) requeueMessage(delivery []byte, taskProcessor iface.TaskProcessor) {
conn := b.open()
defer conn.Close()
conn.Do("RPUSH", getQueue(b.GetConfig(), taskProcessor), delivery)
}