-
Notifications
You must be signed in to change notification settings - Fork 74
/
queue.go
236 lines (203 loc) · 6.32 KB
/
queue.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
package redismq
import (
"fmt"
"strconv"
"time"
"gopkg.in/redis.v3"
)
// Queue is the central element of this library.
// Packages can be put into or get from the queue.
// To read from a queue you need a consumer.
type Queue struct {
redisClient *redis.Client
Name string
rateStatsCache map[int64]map[string]int64
rateStatsChan chan (*dataPoint)
lastStatsWrite int64
}
type dataPoint struct {
name string
value int64
incr bool
}
// CreateQueue return a queue that you can Put() or AddConsumer() to
// Works like SelectQueue for existing queues
func CreateQueue(redisHost, redisPort, redisPassword string, redisDB int64, name string) *Queue {
return newQueue(redisHost, redisPort, redisPassword, redisDB, name)
}
// SelectQueue returns a Queue if a queue with the name exists
func SelectQueue(redisHost, redisPort, redisPassword string, redisDB int64, name string) (queue *Queue, err error) {
redisClient := redis.NewClient(&redis.Options{
Addr: redisHost + ":" + redisPort,
Password: redisPassword,
DB: redisDB,
})
defer redisClient.Close()
isMember, err := redisClient.SIsMember(masterQueueKey(), name).Result()
if err != nil {
return nil, err
}
if !isMember {
return nil, fmt.Errorf("queue with this name doesn't exist")
}
return newQueue(redisHost, redisPort, redisPassword, redisDB, name), nil
}
func newQueue(redisHost, redisPort, redisPassword string, redisDB int64, name string) *Queue {
q := &Queue{Name: name}
q.redisClient = redis.NewClient(&redis.Options{
Addr: redisHost + ":" + redisPort,
Password: redisPassword,
DB: redisDB,
})
q.redisClient.SAdd(masterQueueKey(), name)
q.startStatsWriter()
return q
}
// Delete clears all input and failed queues as well as all consumers
// will not proceed as long as consumers are running
func (queue *Queue) Delete() error {
consumers, err := queue.getConsumers()
if err != nil {
return err
}
for _, name := range consumers {
if queue.isActiveConsumer(name) {
return fmt.Errorf("cannot delete queue with active consumers")
}
consumer, err := queue.AddConsumer(name)
if err != nil {
return err
}
err = consumer.ResetWorking()
if err != nil {
return err
}
err = queue.redisClient.SRem(queueWorkersKey(queue.Name), name).Err()
if err != nil {
return err
}
}
err = queue.ResetInput()
if err != nil {
return err
}
err = queue.ResetFailed()
if err != nil {
return err
}
err = queue.redisClient.SRem(masterQueueKey(), queue.Name).Err()
if err != nil {
return err
}
err = queue.redisClient.Del(queueWorkersKey(queue.Name)).Err()
if err != nil {
return err
}
queue.redisClient.Close()
return nil
}
// Put writes the payload into the input queue
func (queue *Queue) Put(payload string) error {
p := &Package{CreatedAt: time.Now(), Payload: payload, Queue: queue}
lpush := queue.redisClient.LPush(queueInputKey(queue.Name), p.getString())
queue.incrRate(queueInputRateKey(queue.Name), 1)
return lpush.Err()
}
// RequeueFailed moves all failed packages back to the input queue
func (queue *Queue) RequeueFailed() error {
l := queue.GetFailedLength()
// TODO implement this in lua
for l > 0 {
err := queue.redisClient.RPopLPush(queueFailedKey(queue.Name), queueInputKey(queue.Name)).Err()
if err != nil {
return err
}
queue.incrRate(queueInputRateKey(queue.Name), 1)
l--
}
return nil
}
// ResetInput deletes all packages from the input queue
func (queue *Queue) ResetInput() error {
return queue.redisClient.Del(queueInputKey(queue.Name)).Err()
}
// ResetFailed deletes all packages from the failed queue
func (queue *Queue) ResetFailed() error {
return queue.redisClient.Del(queueFailedKey(queue.Name)).Err()
}
// GetInputLength returns the number of packages in the input queue
func (queue *Queue) GetInputLength() int64 {
return queue.redisClient.LLen(queueInputKey(queue.Name)).Val()
}
// GetFailedLength returns the number of packages in the failed queue
func (queue *Queue) GetFailedLength() int64 {
return queue.redisClient.LLen(queueFailedKey(queue.Name)).Val()
}
func (queue *Queue) getConsumers() (consumers []string, err error) {
return queue.redisClient.SMembers(queueWorkersKey(queue.Name)).Result()
}
func (queue *Queue) incrRate(name string, value int64) {
dp := &dataPoint{name: name, value: value}
queue.rateStatsChan <- dp
}
func (queue *Queue) startStatsWriter() {
queue.rateStatsCache = make(map[int64]map[string]int64)
queue.rateStatsChan = make(chan *dataPoint, 2E6)
writing := false
go func() {
for dp := range queue.rateStatsChan {
now := time.Now().UTC().Unix()
if queue.rateStatsCache[now] == nil {
queue.rateStatsCache[now] = make(map[string]int64)
}
queue.rateStatsCache[now][dp.name] += dp.value
if now > queue.lastStatsWrite && !writing {
writing = true
queue.writeStatsCacheToRedis(now)
writing = false
}
}
}()
return
}
func (queue *Queue) writeStatsCacheToRedis(now int64) {
for sec := range queue.rateStatsCache {
if sec >= now-1 {
continue
}
for name, value := range queue.rateStatsCache[sec] {
key := fmt.Sprintf("%s::%d", name, sec)
// incrby can handle the situation where multiple inputs are counted
queue.redisClient.IncrBy(key, value)
// save stats to redis with 2h expiration
queue.redisClient.Expire(key, 2*time.Hour)
}
// track queue lengths
inputKey := fmt.Sprintf("%s::%d", queueInputSizeKey(queue.Name), now)
failKey := fmt.Sprintf("%s::%d", queueFailedSizeKey(queue.Name), now)
queue.redisClient.Set(inputKey, strconv.FormatInt(queue.GetInputLength(), 10), 2*time.Hour)
queue.redisClient.Set(failKey, strconv.FormatInt(queue.GetFailedLength(), 10), 2*time.Hour)
delete(queue.rateStatsCache, sec)
}
queue.lastStatsWrite = now
}
// AddConsumer returns a conumser that can write from the queue
func (queue *Queue) AddConsumer(name string) (c *Consumer, err error) {
c = &Consumer{Name: name, Queue: queue}
//check uniqueness and start heartbeat
added, err := queue.redisClient.SAdd(queueWorkersKey(queue.Name), name).Result()
if err != nil {
return nil, err
}
if added == 0 {
if queue.isActiveConsumer(name) {
return nil, fmt.Errorf("consumer with this name is already active")
}
}
c.startHeartbeat()
return c, nil
}
func (queue *Queue) isActiveConsumer(name string) bool {
val := queue.redisClient.Get(consumerHeartbeatKey(queue.Name, name)).Val()
return val == "ping"
}