forked from RichardKnop/machinery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
373 lines (309 loc) · 8.37 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
package brokers
import (
"encoding/json"
"fmt"
"sync"
"time"
"github.com/RichardKnop/machinery/v1/common"
"github.com/RichardKnop/machinery/v1/config"
"github.com/RichardKnop/machinery/v1/log"
"github.com/RichardKnop/machinery/v1/tasks"
"github.com/garyburd/redigo/redis"
"gopkg.in/redsync.v1"
)
var redisDelayedTasksKey = "delayed_tasks"
// RedisBroker represents a Redis broker
type RedisBroker struct {
host string
password string
db int
pool *redis.Pool
stopReceivingChan chan int
stopDelayedChan chan int
receivingWG sync.WaitGroup
delayedWG sync.WaitGroup
// If set, path to a socket file overrides hostname
socketPath string
redsync *redsync.Redsync
Broker
common.RedisConnector
}
// NewRedisBroker creates new RedisBroker instance
func NewRedisBroker(cnf *config.Config, host, password, socketPath string, db int) Interface {
b := &RedisBroker{Broker: New(cnf)}
b.host = host
b.db = db
b.password = password
b.socketPath = socketPath
return b
}
// StartConsuming enters a loop and waits for incoming messages
func (b *RedisBroker) StartConsuming(consumerTag string, concurrency int, taskProcessor TaskProcessor) (bool, error) {
b.startConsuming(consumerTag, taskProcessor)
b.pool = nil
conn := b.open()
defer conn.Close()
defer b.pool.Close()
// Ping the server to make sure connection is live
_, err := conn.Do("PING")
if err != nil {
b.retryFunc(b.retryStopChan)
return b.retry, err
}
// Channels and wait groups used to properly close down goroutines
b.stopReceivingChan = make(chan int)
b.stopDelayedChan = make(chan int)
b.receivingWG.Add(1)
b.delayedWG.Add(1)
// Channel to which we will push tasks ready for processing by worker
deliveries := make(chan []byte)
// A receivig 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() {
defer b.receivingWG.Done()
log.INFO.Print("[*] Waiting for messages. To exit press CTRL+C")
for {
select {
// A way to stop this goroutine from b.StopConsuming
case <-b.stopReceivingChan:
return
default:
task, err := b.nextTask(b.cnf.DefaultQueue)
if err != nil {
continue
}
deliveries <- task
}
}
}()
// A goroutine to watch for delayed tasks and push them to deliveries
// channel for consumption by the worker
go func() {
defer b.delayedWG.Done()
for {
select {
// A way to stop this goroutine from b.StopConsuming
case <-b.stopDelayedChan:
return
default:
delayedTask, err := b.nextDelayedTask(redisDelayedTasksKey)
if err != nil {
continue
}
deliveries <- delayedTask
}
}
}()
if err := b.consume(deliveries, concurrency, taskProcessor); err != nil {
return b.retry, err
}
return b.retry, nil
}
// StopConsuming quits the loop
func (b *RedisBroker) StopConsuming() {
// Stop the receiving goroutine
b.stopReceiving()
// Stop the delayed tasks goroutine
b.stopDelayed()
b.stopConsuming()
}
// Publish places a new message on the default queue
func (b *RedisBroker) Publish(signature *tasks.Signature) error {
msg, err := json.Marshal(signature)
if err != nil {
return fmt.Errorf("JSON marshal error: %s", err)
}
b.AdjustRoutingKey(signature)
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", 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 *RedisBroker) GetPendingTasks(queue string) ([]*tasks.Signature, error) {
conn := b.open()
defer conn.Close()
if queue == "" {
queue = b.cnf.DefaultQueue
}
bytes, err := conn.Do("LRANGE", queue, 0, 10)
if err != nil {
return nil, err
}
results, err := redis.ByteSlices(bytes, err)
if err != nil {
return nil, err
}
taskSignatures := make([]*tasks.Signature, len(results))
for i, result := range results {
sig := new(tasks.Signature)
if err := json.Unmarshal(result, sig); err != nil {
return nil, err
}
taskSignatures[i] = sig
}
return taskSignatures, nil
}
// consume takes delivered messages from the channel and manages a worker pool
// to process tasks concurrently
func (b *RedisBroker) consume(deliveries <-chan []byte, concurrency int, taskProcessor TaskProcessor) error {
pool := make(chan struct{}, concurrency)
// initialize worker pool with maxWorkers workers
go func() {
for i := 0; i < concurrency; i++ {
pool <- struct{}{}
}
}()
errorsChan := make(chan error, concurrency*2)
//errorsChan := make(chan error)
// Use wait group to make sure task processing completes on interrupt signal
var wg sync.WaitGroup
defer wg.Wait()
for {
select {
case err := <-errorsChan:
return err
case d := <-deliveries:
if concurrency > 0 {
// get worker from pool (blocks until one is available)
<-pool
}
wg.Add(1)
// Consume the task inside a gotourine so multiple tasks
// can be processed concurrently
go func() {
defer wg.Done()
if err := b.consumeOne(d, taskProcessor); err != nil {
errorsChan <- err
}
if concurrency > 0 {
// give worker back to pool
pool <- struct{}{}
}
}()
case <-b.Broker.stopChan:
return nil
}
}
}
// consumeOne processes a single message using TaskProcessor
func (b *RedisBroker) consumeOne(delivery []byte, taskProcessor TaskProcessor) error {
log.INFO.Printf("Received new message: %s", delivery)
sig := new(tasks.Signature)
if err := json.Unmarshal(delivery, sig); err != nil {
return err
}
// If the task is not registered, we requeue it,
// there might be different workers for processing specific tasks
if !b.IsTaskRegistered(sig.Name) {
conn := b.open()
defer conn.Close()
conn.Do("RPUSH", b.cnf.DefaultQueue, delivery)
return nil
}
return taskProcessor.Process(sig)
}
// nextTask pops next available task from the default queue
func (b *RedisBroker) nextTask(queue string) (result []byte, err error) {
conn := b.open()
defer conn.Close()
items, err := redis.ByteSlices(conn.Do("BLPOP", queue, 1))
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/garyburd/redigo/blob/master/redis/zpop_example_test.go
func (b *RedisBroker) 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
if err != nil {
conn.Do("DISCARD")
}
}()
var (
items [][]byte
reply interface{}
)
for {
// Space out queries to ZSET to 20ms intervals so we don't bombard redis
// server with relentless ZRANGEBYSCOREs
<-time.After(20 * 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
}
// Stops the receiving goroutine
func (b *RedisBroker) stopReceiving() {
b.stopReceivingChan <- 1
// Waiting for the receiving goroutine to have stopped
b.receivingWG.Wait()
}
// Stops the delayed tasks goroutine
func (b *RedisBroker) stopDelayed() {
b.stopDelayedChan <- 1
// Waiting for the delayed tasks goroutine to have stopped
b.delayedWG.Wait()
}
// open returns or creates instance of Redis connection
func (b *RedisBroker) open() redis.Conn {
if b.pool == nil {
b.pool = b.NewPool(b.socketPath, b.host, b.password, b.db)
}
if b.redsync == nil {
var pools = []redsync.Pool{b.pool}
b.redsync = redsync.New(pools)
}
return b.pool.Get()
}