forked from dayorbyte/dispatchd
/
queue.go
407 lines (369 loc) · 9.4 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
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
package queue
import (
"container/list"
"encoding/json"
"errors"
"fmt"
"github.com/boltdb/bolt"
"github.com/ernestrc/dispatchd/amqp"
"github.com/ernestrc/dispatchd/consumer"
"github.com/ernestrc/dispatchd/gen"
"github.com/ernestrc/dispatchd/msgstore"
"github.com/ernestrc/dispatchd/persist"
"github.com/ernestrc/dispatchd/stats"
"github.com/gogo/protobuf/proto"
"sync"
"time"
)
var QUEUE_BUCKET_NAME = []byte("queues")
type QueueStateFactory struct{}
func (qsf *QueueStateFactory) New() proto.Unmarshaler {
return &gen.QueueState{}
}
type Queue struct {
gen.QueueState
autoDelete bool
exclusive bool
Closed bool
objLock sync.RWMutex
queue *list.List // int64
queueLock sync.Mutex
consumerLock sync.RWMutex
consumers []*consumer.Consumer // *Consumer
currentConsumer int
statCount uint64
maybeReady chan bool
soleConsumer *consumer.Consumer
ConnId int64
deleteActive time.Time
hasHadConsumers bool
msgStore *msgstore.MessageStore
statProcOne stats.Histogram
deleteChan chan *Queue
}
func NewQueue(
name string,
durable bool,
exclusive bool,
autoDelete bool,
arguments *amqp.Table,
connId int64,
msgStore *msgstore.MessageStore,
deleteChan chan *Queue,
) *Queue {
return &Queue{
QueueState: gen.QueueState{
Name: name,
Durable: durable,
Arguments: arguments,
},
exclusive: exclusive,
autoDelete: autoDelete,
ConnId: connId,
msgStore: msgStore,
deleteChan: deleteChan,
// Fields that aren't passed in
statProcOne: stats.MakeHistogram("queue-proc-one"),
queue: list.New(),
consumers: make([]*consumer.Consumer, 0, 1),
maybeReady: make(chan bool, 1),
}
}
func NewFromPersistedState(state *gen.QueueState, msgStore *msgstore.MessageStore, deleteChan chan *Queue) *Queue {
return &Queue{
QueueState: *state,
exclusive: false,
autoDelete: false,
ConnId: -1,
msgStore: msgStore,
deleteChan: deleteChan,
// Fields that aren't passed in
statProcOne: stats.MakeHistogram("queue-proc-one"),
queue: list.New(),
consumers: make([]*consumer.Consumer, 0, 1),
maybeReady: make(chan bool, 1),
}
}
func (q1 *Queue) EquivalentQueues(q2 *Queue) bool {
if q1 == nil {
return q2 == nil
}
if q2 == nil {
return false
}
// Note: autodelete is not included since the spec says to ignore
// the field if the queue is already created
if q1.Name != q2.Name {
return false
}
if q1.Durable != q2.Durable {
return false
}
if q1.exclusive != q2.exclusive {
return false
}
if !amqp.EquivalentTables(q1.Arguments, q2.Arguments) {
return false
}
return true
}
func (q *Queue) Len() uint32 {
var l = q.queue.Len()
if l < 0 {
panic("Queue length overflow!")
}
return uint32(l)
}
func (q *Queue) ActiveConsumerCount() uint32 {
// TODO(MUST): don't count consumers in the Channel.Flow state once
// that is implemented
return uint32(len(q.consumers))
}
func (q *Queue) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
"name": q.Name,
"durable": q.Durable,
"exclusive": q.exclusive,
"connId": q.ConnId,
"autoDelete": q.autoDelete,
"size": q.queue.Len(),
"consumers": q.consumers,
})
}
func (q *Queue) Persist(db *bolt.DB) error {
return persist.PersistOne(db, QUEUE_BUCKET_NAME, q.Name, q)
}
func (q *Queue) Depersist(db *bolt.DB) error {
return persist.DepersistOne(db, QUEUE_BUCKET_NAME, q.Name)
}
func (q *Queue) DepersistBoltTx(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists(QUEUE_BUCKET_NAME)
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
return persist.DepersistOneBoltTx(bucket, q.Name)
}
func LoadAllQueues(db *bolt.DB, msgStore *msgstore.MessageStore, deleteChan chan *Queue) (map[string]*Queue, error) {
queueStateMap, err := persist.LoadAll(db, QUEUE_BUCKET_NAME, &QueueStateFactory{})
if err != nil {
return nil, err
}
var ret = make(map[string]*Queue)
for key, state := range queueStateMap {
ret[key] = NewFromPersistedState(state.(*gen.QueueState), msgStore, deleteChan)
}
return ret, nil
}
func (q *Queue) LoadFromMsgStore(msgStore *msgstore.MessageStore) {
queueList, err := msgStore.LoadQueueFromDisk(q.Name)
if err != nil {
panic("Integrity error reading queue from disk! " + err.Error())
}
q.queue = queueList
select {
case q.maybeReady <- true:
default:
}
}
func (q *Queue) Close() {
// This discards any messages which would be added. It does not
// do cleanup
q.queueLock.Lock()
defer q.queueLock.Unlock()
q.Closed = true
}
func (q *Queue) Purge() uint32 {
q.queueLock.Lock()
defer q.queueLock.Unlock()
return q.purgeNotThreadSafe()
}
func (q *Queue) purgeNotThreadSafe() uint32 {
var length = q.queue.Len()
q.queue.Init()
return uint32(length)
}
func (q *Queue) Add(qm *amqp.QueueMessage) bool {
// NOTE: I tried using consumeImmediate before adding things to the queue,
// but it caused a pretty significant slowdown.
q.queueLock.Lock()
defer q.queueLock.Unlock()
if !q.Closed {
q.statCount += 1
q.queue.PushBack(qm)
select {
case q.maybeReady <- true:
default:
}
return true
} else {
return false
}
}
func (q *Queue) ConsumeImmediate(qm *amqp.QueueMessage) bool {
// TODO: randomize or round-robin through consumers
q.consumerLock.RLock()
defer q.consumerLock.RUnlock()
for _, consumer := range q.consumers {
var msg, acquired = q.msgStore.Get(qm, consumer.MessageResourceHolders())
if acquired {
consumer.ConsumeImmediate(qm, msg)
return true
}
}
return false
}
func (q *Queue) Delete(ifUnused bool, ifEmpty bool) (uint32, error) {
// Lock
if !q.Closed {
panic("Queue deleted before it was closed!")
}
q.queueLock.Lock()
defer q.queueLock.Unlock()
// Check
var usedOk = !ifUnused || len(q.consumers) == 0
var emptyOk = !ifEmpty || q.queue.Len() == 0
if !usedOk {
return 0, errors.New("if-unused specified and there are consumers")
}
if !emptyOk {
return 0, errors.New("if-empty specified and there are messages in the queue")
}
// Purge
q.cancelConsumers()
return q.purgeNotThreadSafe(), nil
}
func (q *Queue) Readd(queueName string, msg *amqp.QueueMessage) {
// TODO: if there is a consumer available, dispatch
q.queueLock.Lock()
defer q.queueLock.Unlock()
// this method is only called when we get a nack or we shut down a channel,
// so it means the message was not acked.
q.msgStore.IncrDeliveryCount(queueName, msg)
q.queue.PushFront(msg)
select {
case q.maybeReady <- true:
default:
}
}
func (q *Queue) removeConsumer(consumerTag string) {
q.consumerLock.Lock()
defer q.consumerLock.Unlock()
if q.soleConsumer != nil && q.soleConsumer.ConsumerTag == consumerTag {
q.soleConsumer = nil
}
// remove from list
for i, c := range q.consumers {
if c.ConsumerTag == consumerTag {
q.consumers = append(q.consumers[:i], q.consumers[i+1:]...)
}
}
var size = len(q.consumers)
if size == 0 {
q.currentConsumer = 0
if q.autoDelete && q.hasHadConsumers {
go q.autodeleteTimeout()
}
} else {
q.currentConsumer = q.currentConsumer % size
}
}
func (q *Queue) autodeleteTimeout() {
// There's technically a race condition here where a new binding could be
// added right as we check this, but after a 5 second wait with no activity
// I think this is probably safe enough.
var now = time.Now()
q.deleteActive = now
time.Sleep(5 * time.Second)
if q.deleteActive == now {
q.deleteChan <- q
}
}
func (q *Queue) cancelConsumers() {
q.consumerLock.Lock()
defer q.consumerLock.Unlock()
q.soleConsumer = nil
// Send cancel to each consumer
for _, c := range q.consumers {
c.SendCancel()
c.Stop()
}
q.consumers = make([]*consumer.Consumer, 0, 1)
}
func (q *Queue) AddConsumer(c *consumer.Consumer, exclusive bool) (uint16, error) {
if q.Closed {
return 0, nil
}
// Reset auto-delete
q.deleteActive = time.Unix(0, 0)
// Add consumer
q.consumerLock.Lock()
if exclusive {
if len(q.consumers) == 0 {
q.soleConsumer = c
} else {
return 403, fmt.Errorf("Exclusive access denied, %d consumers active", len(q.consumers))
}
}
q.consumers = append(q.consumers, c)
q.hasHadConsumers = true
q.consumerLock.Unlock()
return 0, nil
}
func (q *Queue) Start() {
go func() {
select {
case q.maybeReady <- true:
default:
}
for _ = range q.maybeReady {
if q.Closed {
fmt.Printf("Queue closed!\n")
break
}
q.processOne()
}
}()
}
func (q *Queue) MaybeReady() chan bool {
return q.maybeReady
}
func (q *Queue) processOne() {
defer stats.RecordHisto(q.statProcOne, stats.Start())
q.consumerLock.RLock()
defer q.consumerLock.RUnlock()
var size = len(q.consumers)
if size == 0 {
return
}
for count := 0; count < size; count++ {
q.currentConsumer = (q.currentConsumer + 1) % size
var c = q.consumers[q.currentConsumer]
c.Ping()
}
}
func (q *Queue) GetOneForced() *amqp.QueueMessage {
q.queueLock.Lock()
defer q.queueLock.Unlock()
if q.queue.Len() == 0 {
return nil
}
qMsg := q.queue.Remove(q.queue.Front()).(*amqp.QueueMessage)
return qMsg
}
func (q *Queue) GetOne(rhs ...amqp.MessageResourceHolder) (*amqp.QueueMessage, *amqp.Message) {
q.queueLock.Lock()
defer q.queueLock.Unlock()
// Empty check
if q.queue.Len() == 0 || q.Closed {
return nil, nil
}
// Get one message. If there is a message try to acquire the resources
// from the channel.
var qm = q.queue.Front().Value.(*amqp.QueueMessage)
var msg, acquired = q.msgStore.Get(qm, rhs)
if acquired {
q.queue.Remove(q.queue.Front())
return qm, msg
}
return nil, nil
}