-
Notifications
You must be signed in to change notification settings - Fork 9
/
rabbit.go
820 lines (660 loc) · 19.8 KB
/
rabbit.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
// Package rabbit is a simple streadway/amqp wrapper library that comes with:
//
// * Auto-reconnect support
//
// * Context support
//
// * Helpers for consuming once or forever and publishing
//
// The library is used internally at https://batch.sh where it powers most of
// the platform's backend services.
//
// For an example, refer to the README.md.
package rabbit
import (
"context"
"crypto/tls"
"fmt"
"sync"
"time"
"github.com/pkg/errors"
amqp "github.com/rabbitmq/amqp091-go"
uuid "github.com/satori/go.uuid"
)
const (
// DefaultRetryReconnectSec determines how long to wait before attempting
// to reconnect to a rabbit server
DefaultRetryReconnectSec = 60
// DefaultStopTimeout is the default amount of time Stop() will wait for
// consume function(s) to exit.
DefaultStopTimeout = 5 * time.Second
// Both means that the client is acting as both a consumer and a producer.
Both Mode = 0
// Consumer means that the client is acting as a consumer.
Consumer Mode = 1
// Producer means that the client is acting as a producer.
Producer Mode = 2
ForceReconnectHeader = "rabbit-force-reconnect"
)
var (
// ErrShutdown will be returned if the client is shutdown via Stop() or Close()
ErrShutdown = errors.New("client is shutdown")
// DefaultConsumerTag is used for identifying consumer
DefaultConsumerTag = "c-rabbit-" + uuid.NewV4().String()[0:8]
// DefaultAppID is used for identifying the producer
DefaultAppID = "p-rabbit-" + uuid.NewV4().String()[0:8]
)
// IRabbit is the interface that the `rabbit` library implements. It's here as
// convenience.
type IRabbit interface {
Consume(ctx context.Context, errChan chan *ConsumeError, f func(msg amqp.Delivery) error)
ConsumeOnce(ctx context.Context, runFunc func(msg amqp.Delivery) error) error
Publish(ctx context.Context, routingKey string, payload []byte, headers ...amqp.Table) error
Stop(timeout ...time.Duration) error
Close() error
}
// Rabbit struct that is instantiated via `New()`. You should not instantiate
// this struct by hand (unless you have a really good reason to do so).
type Rabbit struct {
Conn *amqp.Connection
ConsumerDeliveryChannel <-chan amqp.Delivery
ConsumerRWMutex *sync.RWMutex
ConsumerWG *sync.WaitGroup
NotifyCloseChan chan *amqp.Error
ReconnectChan chan struct{}
ReconnectInProgress bool
ReconnectInProgressMtx *sync.RWMutex
ProducerServerChannel *amqp.Channel
ProducerRWMutex *sync.RWMutex
Options *Options
shutdown bool
ctx context.Context
cancel func()
log Logger
}
// Mode is the type used to represent whether the RabbitMQ
// clients is acting as a consumer, a producer, or both.
type Mode int
// Binding represents the information needed to bind a queue to
// an Exchange.
type Binding struct {
// Required
ExchangeName string
// Bind a queue to one or more routing keys
BindingKeys []string
// Whether to declare/create exchange on connect
ExchangeDeclare bool
// Required if declaring queue (valid: direct, fanout, topic, headers)
ExchangeType string
// Whether exchange should survive/persist server restarts
ExchangeDurable bool
// Whether to delete exchange when its no longer used; used only if ExchangeDeclare set to true
ExchangeAutoDelete bool
}
// Options determines how the `rabbit` library will behave and should be passed
// in to rabbit via `New()`. Many of the options are optional (and will fall
// back to sane defaults).
type Options struct {
// Required; format "amqp://user:pass@host:port"
URLs []string
// In what mode does the library operate (Both, Consumer, Producer)
Mode Mode
// If left empty, server will auto generate queue name
QueueName string
// Bindings is the set of information need to bind a queue to one or
// more exchanges, specifying one or more binding (routing) keys.
Bindings []Binding
// https://godoc.org/github.com/streadway/amqp#Channel.Qos
// Leave unset if no QoS preferences
QosPrefetchCount int
QosPrefetchSize int
// How long to wait before we retry connecting to a server (after disconnect)
RetryReconnectSec int
// Whether queue should survive/persist server restarts (and there are no remaining bindings)
QueueDurable bool
// Whether consumer should be the sole consumer of the queue; used only if
// QueueDeclare set to true
QueueExclusive bool
// Whether to delete queue on consumer disconnect; used only if QueueDeclare set to true
QueueAutoDelete bool
// Whether to declare/create queue on connect; used only if QueueDeclare set to true
QueueDeclare bool
// Additional arguments to pass to the queue declaration or binding
// https://github.com/streamdal/plumber/issues/210
QueueArgs map[string]interface{}
// Whether to automatically acknowledge consumed message(s)
AutoAck bool
// Used for identifying consumer
ConsumerTag string
// Used as a property to identify producer
AppID string
// Use TLS
UseTLS bool
// Skip cert verification (only applies if UseTLS is true)
SkipVerifyTLS bool
// Log is the (optional) logger to use for writing out log messages.
Log Logger
}
// ConsumeError will be passed down the error channel if/when `f()` func runs
// into an error during `Consume()`.
type ConsumeError struct {
Message *amqp.Delivery
Error error
}
// New is used for instantiating the library.
func New(opts *Options) (*Rabbit, error) {
if err := ValidateOptions(opts); err != nil {
return nil, errors.Wrap(err, "invalid options")
}
var ac *amqp.Connection
var err error
// try all available URLs in a loop and quit as soon as it
// can successfully establish a connection to one of them
for _, url := range opts.URLs {
if opts.UseTLS {
tlsConfig := &tls.Config{}
if opts.SkipVerifyTLS {
tlsConfig.InsecureSkipVerify = true
}
ac, err = amqp.DialTLS(url, tlsConfig)
} else {
ac, err = amqp.Dial(url)
}
if err == nil {
// yes, we made it!
break
}
}
if err != nil {
return nil, errors.Wrap(err, "unable to dial server")
}
ctx, cancel := context.WithCancel(context.Background())
r := &Rabbit{
Conn: ac,
ConsumerRWMutex: &sync.RWMutex{},
ConsumerWG: &sync.WaitGroup{},
NotifyCloseChan: make(chan *amqp.Error),
ReconnectChan: make(chan struct{}, 1),
ReconnectInProgress: false,
ReconnectInProgressMtx: &sync.RWMutex{},
ProducerRWMutex: &sync.RWMutex{},
Options: opts,
ctx: ctx,
cancel: cancel,
log: opts.Log,
}
if opts.Mode != Producer {
if err := r.newConsumerChannel(); err != nil {
return nil, errors.Wrap(err, "unable to get initial delivery channel")
}
}
ac.NotifyClose(r.NotifyCloseChan)
// Launch connection watcher/reconnect
go r.runWatcher()
return r, nil
}
// ValidateOptions validates various combinations of options.
func ValidateOptions(opts *Options) error {
if opts == nil {
return errors.New("Options cannot be nil")
}
validURL := false
for _, url := range opts.URLs {
if len(url) > 0 {
validURL = true
break
}
}
if !validURL {
return errors.New("At least one non-empty URL must be provided")
}
if len(opts.Bindings) == 0 {
return errors.New("At least one Exchange must be specified")
}
if err := validateBindings(opts); err != nil {
return errors.Wrap(err, "binding validation failed")
}
applyDefaults(opts)
if err := validMode(opts.Mode); err != nil {
return err
}
return nil
}
func validateBindings(opts *Options) error {
if opts.Mode == Producer || opts.Mode == Both {
if len(opts.Bindings) > 1 {
return errors.New("Exactly one Exchange must be specified when publishing messages")
}
}
for _, binding := range opts.Bindings {
if binding.ExchangeDeclare {
if binding.ExchangeType == "" {
return errors.New("ExchangeType cannot be empty if ExchangeDeclare set to true")
}
}
if binding.ExchangeName == "" {
return errors.New("ExchangeName cannot be empty")
}
// BindingKeys are only needed if Consumer or Both
if opts.Mode != Producer {
if len(binding.BindingKeys) < 1 {
return errors.New("At least one BindingKeys must be specified")
}
}
}
return nil
}
func applyDefaults(opts *Options) {
if opts == nil {
return
}
if opts.RetryReconnectSec == 0 {
opts.RetryReconnectSec = DefaultRetryReconnectSec
}
if opts.AppID == "" {
opts.AppID = DefaultAppID
}
if opts.ConsumerTag == "" {
opts.ConsumerTag = DefaultConsumerTag
}
if opts.Log == nil {
opts.Log = &NoOpLogger{}
}
if opts.QueueArgs == nil {
opts.QueueArgs = make(map[string]interface{})
}
}
func validMode(mode Mode) error {
validModes := []Mode{Both, Producer, Consumer}
var found bool
for _, validMode := range validModes {
if validMode == mode {
found = true
}
}
if !found {
return fmt.Errorf("invalid mode '%d'", mode)
}
return nil
}
// Consume consumes messages from the configured queue (`Options.QueueName`) and
// executes `f` for every received message.
//
// `Consume()` will block until it is stopped either via the passed in `ctx` OR
// by calling `Stop()`
//
// It is also possible to see the errors that `f()` runs into by passing in an
// error channel (`chan *ConsumeError`).
//
// Both `ctx` and `errChan` can be `nil`.
//
// If the server goes away, `Consume` will automatically attempt to reconnect.
// Subsequent reconnect attempts will sleep/wait for `DefaultRetryReconnectSec`
// between attempts.
func (r *Rabbit) Consume(ctx context.Context, errChan chan *ConsumeError, f func(msg amqp.Delivery) error) {
if r.shutdown {
r.log.Error(ErrShutdown)
return
}
if r.Options.Mode == Producer {
r.log.Error("unable to Consume() - library is configured in Producer mode")
return
}
r.ConsumerWG.Add(1)
defer r.ConsumerWG.Done()
if ctx == nil {
ctx = context.Background()
}
r.log.Debug("waiting for messages from rabbit ...")
MAIN:
for {
select {
case msg := <-r.delivery():
if _, ok := msg.Headers[ForceReconnectHeader]; ok || msg.Acknowledger == nil {
r.writeError(errChan, &ConsumeError{
Message: &msg,
Error: errors.New("nil acknowledger detected - sending reconnect signal"),
})
r.ReconnectChan <- struct{}{}
// No point in continuing execution of consumer func as the
// delivery msg is incomplete/invalid.
continue
}
if err := f(msg); err != nil {
r.writeError(errChan, &ConsumeError{
Message: &msg,
Error: fmt.Errorf("error during consume: %s", err),
})
}
case <-ctx.Done():
r.log.Warn("stopped via context")
break MAIN
case <-r.ctx.Done():
r.log.Warn("stopped via Stop()")
break MAIN
}
}
r.log.Debug("Consume finished - exiting")
}
func (r *Rabbit) writeError(errChan chan *ConsumeError, err *ConsumeError) {
if err == nil {
r.log.Error("nil 'err' passed to writeError - bug?")
return
}
r.log.Warnf("writeError(): %s", err.Error)
if errChan == nil {
// Don't have an error channel, nothing else to do
return
}
// Only write to errChan if it's not full (to avoid goroutine leak)
if len(errChan) > 0 {
r.log.Warn("errChan is full - dropping message")
return
}
go func() {
errChan <- err
}()
}
// ConsumeOnce will consume exactly one message from the configured queue,
// execute `runFunc()` on the message and return.
//
// Same as with `Consume()`, you can pass in a context to cancel `ConsumeOnce()`
// or run `Stop()`.
func (r *Rabbit) ConsumeOnce(ctx context.Context, runFunc func(msg amqp.Delivery) error) error {
if r.shutdown {
return ErrShutdown
}
if r.Options.Mode == Producer {
return errors.New("unable to ConsumeOnce - library is configured in Producer mode")
}
if ctx == nil {
ctx = context.Background()
}
r.log.Debug("waiting for a single message from rabbit ...")
select {
case msg := <-r.delivery():
if msg.Acknowledger == nil {
r.log.Warn("Detected nil acknowledger - sending signal to rabbit lib to reconnect")
r.ReconnectChan <- struct{}{}
return errors.New("detected nil acknowledger - sent signal to reconnect to RabbitMQ")
}
if err := runFunc(msg); err != nil {
return err
}
case <-ctx.Done():
r.log.Warn("stopped via context")
return nil
case <-r.ctx.Done():
r.log.Warn("stopped via Stop()")
return nil
}
r.log.Debug("ConsumeOnce finished - exiting")
return nil
}
// Publish publishes one message to the configured exchange, using the specified
// routing key.
func (r *Rabbit) Publish(ctx context.Context, routingKey string, body []byte, headers ...amqp.Table) error {
if ctx == nil {
ctx = context.Background()
}
if r.shutdown {
return ErrShutdown
}
if r.Options.Mode == Consumer {
return errors.New("unable to Publish - library is configured in Consumer mode")
}
// Is this the first time we're publishing?
if r.ProducerServerChannel == nil {
ch, err := r.newServerChannel()
if err != nil {
return errors.Wrap(err, "unable to create server channel")
}
r.ProducerRWMutex.Lock()
r.ProducerServerChannel = ch
r.ProducerRWMutex.Unlock()
}
r.ProducerRWMutex.RLock()
defer r.ProducerRWMutex.RUnlock()
// Create channels for error and done signals
chanErr := make(chan error)
chanDone := make(chan struct{})
go func() {
var realHeaders amqp.Table
if len(headers) > 0 {
realHeaders = headers[0]
}
if err := r.ProducerServerChannel.Publish(r.Options.Bindings[0].ExchangeName, routingKey, false, false, amqp.Publishing{
DeliveryMode: amqp.Persistent,
Body: body,
AppId: r.Options.AppID,
Headers: realHeaders,
}); err != nil {
// Signal there is an error
chanErr <- err
}
// Signal we are done
chanDone <- struct{}{}
}()
select {
case <-chanDone:
// We did it!
return nil
case err := <-chanErr:
return errors.Wrap(err, "failed to publish message")
case <-ctx.Done():
r.log.Warn("stopped via context")
err := r.ProducerServerChannel.Close()
if err != nil {
return errors.Wrap(err, "failed to close producer channel")
}
return errors.New("context cancelled")
}
}
// Stop stops an in-progress `Consume()` or `ConsumeOnce()`
func (r *Rabbit) Stop(timeout ...time.Duration) error {
r.cancel()
doneCh := make(chan struct{})
// This will leak if consumer(s) don't exit within timeout
go func() {
r.ConsumerWG.Wait()
doneCh <- struct{}{}
}()
stopTimeout := DefaultStopTimeout
if len(timeout) > 0 {
stopTimeout = timeout[0]
}
select {
case <-doneCh:
return nil
case <-time.After(stopTimeout):
return fmt.Errorf("timeout waiting for consumer to stop after '%v'", stopTimeout)
}
}
// Close stops any active Consume and closes the amqp connection (and channels using the conn)
//
// You should re-instantiate the rabbit lib once this is called.
func (r *Rabbit) Close() error {
if r.shutdown {
return ErrShutdown
}
r.cancel()
if err := r.Conn.Close(); err != nil {
return fmt.Errorf("unable to close amqp connection: %s", err)
}
r.shutdown = true
return nil
}
func (r *Rabbit) getReconnectInProgress() bool {
r.ReconnectInProgressMtx.RLock()
defer r.ReconnectInProgressMtx.RUnlock()
return r.ReconnectInProgress
}
func (r *Rabbit) runWatcher() {
for {
select {
case closeErr := <-r.NotifyCloseChan:
r.log.Debugf("received message on notify close channel: '%+v' (reconnecting)", closeErr)
case <-r.ReconnectChan:
if r.getReconnectInProgress() {
// Already reconnecting, nothing to do
r.log.Debug("received reconnect signal (already reconnecting)")
return
}
r.ReconnectInProgressMtx.Lock()
r.ReconnectInProgress = true
r.log.Debug("received reconnect signal (reconnecting)")
}
// Acquire mutex to pause all consumers/producers while we reconnect AND prevent
// access to the channel map
r.ConsumerRWMutex.Lock()
r.ProducerRWMutex.Lock()
var attempts int
for {
attempts++
if err := r.reconnect(); err != nil {
r.log.Warnf("unable to complete reconnect: %s; retrying in %d", err, r.Options.RetryReconnectSec)
time.Sleep(time.Duration(r.Options.RetryReconnectSec) * time.Second)
continue
}
r.log.Debugf("successfully reconnected after %d attempts", attempts)
break
}
// Create and set a new notify close channel (since old one may have gotten shutdown)
r.NotifyCloseChan = make(chan *amqp.Error, 0)
r.Conn.NotifyClose(r.NotifyCloseChan)
// Update channel
if r.Options.Mode == Producer {
serverChannel, err := r.newServerChannel()
if err != nil {
r.log.Errorf("unable to set new channel: %s", err)
panic(fmt.Sprintf("unable to set new channel: %s", err))
}
r.ProducerServerChannel = serverChannel
} else {
if err := r.newConsumerChannel(); err != nil {
r.log.Errorf("unable to set new channel: %s", err)
// TODO: This is super shitty. Should address this.
panic(fmt.Sprintf("unable to set new channel: %s", err))
}
}
// Unlock so that consumers/producers can begin reading messages from a new channel
r.ConsumerRWMutex.Unlock()
r.ProducerRWMutex.Unlock()
// If this was a requested reconnect - reset in progress flag
if r.ReconnectInProgress {
r.ReconnectInProgress = false
r.ReconnectInProgressMtx.Unlock()
}
r.log.Debug("runWatcher iteration has completed successfully")
}
}
func (r *Rabbit) newServerChannel() (*amqp.Channel, error) {
if r.Conn == nil {
return nil, errors.New("r.Conn is nil - did this get instantiated correctly? bug?")
}
ch, err := r.Conn.Channel()
if err != nil {
return nil, errors.Wrap(err, "unable to instantiate channel")
}
if err := ch.Qos(r.Options.QosPrefetchCount, r.Options.QosPrefetchSize, false); err != nil {
return nil, errors.Wrap(err, "unable to set qos policy")
}
// Only declare queue if in Both or Consumer mode
if r.Options.Mode != Producer {
if r.Options.QueueDeclare {
if _, err := ch.QueueDeclare(
r.Options.QueueName,
r.Options.QueueDurable,
r.Options.QueueAutoDelete,
r.Options.QueueExclusive,
false,
r.Options.QueueArgs,
); err != nil {
return nil, err
}
}
}
for _, binding := range r.Options.Bindings {
if binding.ExchangeDeclare {
if err := ch.ExchangeDeclare(
binding.ExchangeName,
binding.ExchangeType,
binding.ExchangeDurable,
binding.ExchangeAutoDelete,
false,
false,
nil,
); err != nil {
return nil, errors.Wrap(err, "unable to declare exchange")
}
}
// Only bind queue if in Both or Consumer mode
if r.Options.Mode != Producer {
for _, bindingKey := range binding.BindingKeys {
if err := ch.QueueBind(
r.Options.QueueName,
bindingKey,
binding.ExchangeName,
false,
r.Options.QueueArgs,
); err != nil {
return nil, errors.Wrap(err, "unable to bind queue")
}
}
}
}
return ch, nil
}
func (r *Rabbit) newConsumerChannel() error {
serverChannel, err := r.newServerChannel()
if err != nil {
return errors.Wrap(err, "unable to create new server channel")
}
deliveryChannel, err := serverChannel.Consume(
r.Options.QueueName,
r.Options.ConsumerTag,
r.Options.AutoAck,
r.Options.QueueExclusive,
false,
false,
nil,
)
if err != nil {
return errors.Wrap(err, "unable to create delivery channel")
}
r.ProducerServerChannel = serverChannel
r.ConsumerDeliveryChannel = deliveryChannel
return nil
}
func (r *Rabbit) reconnect() error {
var ac *amqp.Connection
var err error
// try all available URLs in a loop and quit as soon as it
// can successfully establish a connection to one of them
for _, url := range r.Options.URLs {
if r.Options.UseTLS {
tlsConfig := &tls.Config{}
if r.Options.SkipVerifyTLS {
tlsConfig.InsecureSkipVerify = true
}
ac, err = amqp.DialTLS(url, tlsConfig)
} else {
ac, err = amqp.Dial(url)
}
if err == nil {
// yes, we made it!
break
}
}
if err != nil {
return errors.Wrap(err, "all servers failed on reconnect")
}
r.Conn = ac
return nil
}
func (r *Rabbit) delivery() <-chan amqp.Delivery {
// Acquire lock (in case we are reconnecting and channels are being swapped)
r.ConsumerRWMutex.RLock()
defer r.ConsumerRWMutex.RUnlock()
return r.ConsumerDeliveryChannel
}