forked from nsqio/go-nsq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
1397 lines (1229 loc) · 38.5 KB
/
reader.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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package nsq
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"log"
"math"
"math/rand"
"net"
"net/url"
"os"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
// returned from ConnectToNSQ when already connected
var ErrAlreadyConnected = errors.New("already connected")
// returned from updateRdy if over max-in-flight
var ErrOverMaxInFlight = errors.New("over configure max-inflight")
// returned from ConnectToLookupd when given lookupd address exists already
var ErrLookupdAddressExists = errors.New("lookupd address already exists")
// Handler is the synchronous interface to Reader.
//
// Implement this interface for handlers that return whether or not message
// processing completed successfully.
//
// When the return value is nil Reader will automatically handle FINishing.
//
// When the returned value is non-nil Reader will automatically handle REQueing.
type Handler interface {
HandleMessage(message *Message) error
}
// AsyncHandler is the asynchronous interface to Reader.
//
// Implement this interface for handlers that wish to defer responding until later.
// This is particularly useful if you want to batch work together.
//
// An AsyncHandler must send:
//
// &FinishedMessage{messageID, requeueDelay, true|false}
//
// To the supplied responseChan to indicate that a message is processed.
type AsyncHandler interface {
HandleMessage(message *Message, responseChan chan *FinishedMessage)
}
// FinishedMessage is the data type used over responseChan in AsyncHandlers
type FinishedMessage struct {
Id MessageID
RequeueDelayMs int
Success bool
}
// FailedMessageLogger is an interface that can be implemented by handlers that wish
// to receive a callback when a message is deemed "failed" (i.e. the number of attempts
// exceeded the Reader specified MaxAttemptCount)
type FailedMessageLogger interface {
LogFailedMessage(message *Message)
}
// Reader is a high-level type to consume from NSQ.
//
// A Reader instance is supplied handler(s) that will be executed
// concurrently via goroutines to handle processing the stream of messages
// consumed from the specified topic/channel. See: AsyncHandler and Handler
// for details on implementing those interfaces to create handlers.
//
// If configured, it will poll nsqlookupd instances and handle connection (and
// reconnection) to any discovered nsqds.
type Reader struct {
// 64bit atomic vars need to be first for proper alignment on 32bit platforms
MessagesReceived uint64 // an atomic counter - # of messages received
MessagesFinished uint64 // an atomic counter - # of messages FINished
MessagesRequeued uint64 // an atomic counter - # of messages REQueued
totalRdyCount int64
messagesInFlight int64
backoffDuration int64
sync.RWMutex
// basics
TopicName string // name of topic to subscribe to
ChannelName string // name of channel to subscribe to
ShortIdentifier string // an identifier to send to nsqd when connecting (defaults: short hostname)
LongIdentifier string // an identifier to send to nsqd when connecting (defaults: long hostname)
VerboseLogging bool // enable verbose logging
ExitChan chan int // read from this channel to block your main loop
// network deadlines
ReadTimeout time.Duration // the deadline set for network reads
WriteTimeout time.Duration // the deadline set for network writes
// lookupd
LookupdPollInterval time.Duration // duration between polling lookupd for new connections
LookupdPollJitter float64 // Maximum fractional amount of jitter to add to the lookupd pool loop. This helps evenly distribute requests even if multiple consumers restart at the same time.
// requeue delays
MaxRequeueDelay time.Duration // the maximum duration when REQueueing (for doubling of deferred requeue)
DefaultRequeueDelay time.Duration // the default duration when REQueueing
BackoffMultiplier time.Duration // the unit of time for calculating reader backoff
// misc
MaxAttemptCount uint16 // maximum number of times this reader will attempt to process a message
LowRdyIdleTimeout time.Duration // the amount of time in seconds to wait for a message from a producer when in a state where RDY counts are re-distributed (ie. max_in_flight < num_producers)
// transport layer security
TLSv1 bool // negotiate enabling TLS
TLSConfig *tls.Config // client TLS configuration
// compression
Deflate bool // negotiate enabling Deflate compression
DeflateLevel int // the compression level to negotiate for Deflate
Snappy bool // negotiate enabling Snappy compression
SampleRate int32 // set the sampleRate of the client's messagePump (requires nsqd 0.2.25+)
// internal variables
maxBackoffDuration time.Duration
maxBackoffCount int32
maxInFlight int
backoffChan chan bool
rdyChan chan *nsqConn
needRDYRedistributed int32
backoffCounter int32
incomingMessages chan *Message
pendingConnections map[string]bool
nsqConnections map[string]*nsqConn
lookupdRecheckChan chan int
lookupdHTTPAddrs []string
lookupdQueryIndex int
runningHandlers int32
stopFlag int32
stopHandler sync.Once
authenticationPassword string
}
// NewReader creates a new instance of Reader for the specified topic/channel
//
// The returned Reader instance is setup with sane default values. To modify
// configuration, update the values on the returned instance before connecting.
func NewReader(topic string, channel string, authenticationPassword string) (*Reader, error) {
if !IsValidTopicName(topic) {
return nil, errors.New("invalid topic name")
}
if !IsValidChannelName(channel) {
return nil, errors.New("invalid channel name")
}
hostname, err := os.Hostname()
if err != nil {
log.Fatalf("ERROR: unable to get hostname %s", err.Error())
}
q := &Reader{
TopicName: topic,
ChannelName: channel,
MaxAttemptCount: 5,
LookupdPollInterval: 60 * time.Second,
LookupdPollJitter: 0.3,
LowRdyIdleTimeout: 10 * time.Second,
DefaultRequeueDelay: 90 * time.Second,
MaxRequeueDelay: 15 * time.Minute,
BackoffMultiplier: time.Second,
ShortIdentifier: strings.Split(hostname, ".")[0],
LongIdentifier: hostname,
ReadTimeout: DefaultClientTimeout,
WriteTimeout: time.Second,
DeflateLevel: 6,
incomingMessages: make(chan *Message),
pendingConnections: make(map[string]bool),
nsqConnections: make(map[string]*nsqConn),
lookupdRecheckChan: make(chan int, 1), // used at connection close to force a possible reconnect
maxInFlight: 1,
backoffChan: make(chan bool),
rdyChan: make(chan *nsqConn, 1),
ExitChan: make(chan int),
authenticationPassword: authenticationPassword,
}
q.SetMaxBackoffDuration(120 * time.Second)
go q.rdyLoop()
return q, nil
}
// Configure takes an option as a string and a value as an interface and
// attempts to set the appropriate configuration option on the reader instance.
//
// It attempts to coerce the value into the right format depending on the named
// option and the underlying type of the value passed in.
//
// It returns an error for an invalid option or value.
func (q *Reader) Configure(option string, value interface{}) error {
getDuration := func(v interface{}) (time.Duration, error) {
switch v.(type) {
case string:
return time.ParseDuration(v.(string))
case int, int16, uint16, int32, uint32, int64, uint64:
// treat like ms
return time.Duration(reflect.ValueOf(v).Int()) * time.Millisecond, nil
case time.Duration:
return v.(time.Duration), nil
}
return 0, errors.New("invalid value type")
}
getBool := func(v interface{}) (bool, error) {
switch value.(type) {
case bool:
return value.(bool), nil
case string:
return strconv.ParseBool(v.(string))
case int, int16, uint16, int32, uint32, int64, uint64:
return reflect.ValueOf(value).Int() == 0, nil
}
return false, errors.New("invalid value type")
}
getFloat64 := func(v interface{}) (float64, error) {
switch value.(type) {
case string:
return strconv.ParseFloat(value.(string), 64)
case int, int16, uint16, int32, uint32, int64, uint64:
return float64(reflect.ValueOf(value).Int()), nil
case float64:
return value.(float64), nil
}
return 0, errors.New("invalid value type")
}
getInt64 := func(v interface{}) (int64, error) {
switch value.(type) {
case string:
return strconv.ParseInt(v.(string), 10, 64)
case int, int16, uint16, int32, uint32, int64, uint64:
return reflect.ValueOf(value).Int(), nil
}
return 0, errors.New("invalid value type")
}
switch option {
case "read_timeout":
v, err := getDuration(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v > 5*time.Minute || v < 100*time.Millisecond {
return errors.New(fmt.Sprintf("invalid %s ! 100ms <= %s <= 5m", option, v))
}
q.ReadTimeout = v
case "write_timeout":
v, err := getDuration(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v > 5*time.Minute || v < 100*time.Millisecond {
return errors.New(fmt.Sprintf("invalid %s ! 100ms <= %s <= 5m", option, v))
}
q.WriteTimeout = v
case "lookupd_poll_interval":
v, err := getDuration(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v > 5*time.Minute || v < 5*time.Second {
return errors.New(fmt.Sprintf("invalid %s ! 5s <= %s <= 5m", option, v))
}
q.LookupdPollInterval = v
case "lookupd_poll_jitter":
v, err := getFloat64(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v < 0 || v > 1 {
return errors.New(fmt.Sprintf("invalid %s ! 0 <= %d <= 1", option, v))
}
q.LookupdPollJitter = v
case "max_requeue_delay":
v, err := getDuration(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v > 60*time.Minute || v < 0 {
return errors.New(fmt.Sprintf("invalid %s ! 0 <= %s <= 60m", option, v))
}
q.MaxRequeueDelay = v
case "default_requeue_delay":
v, err := getDuration(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v > 60*time.Minute || v < 0 {
return errors.New(fmt.Sprintf("invalid %s ! 0 <= %s <= 60m", option, v))
}
q.DefaultRequeueDelay = v
case "backoff_multiplier":
v, err := getDuration(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v > 60*time.Minute || v < time.Second {
return errors.New(fmt.Sprintf("invalid %s ! 1s <= %s <= 60m", option, v))
}
q.BackoffMultiplier = v
case "max_attempt_count":
v, err := getInt64(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v < 1 || v > 65535 {
return errors.New(fmt.Sprintf("invalid %s ! 1 <= %d <= 65535", option, v))
}
q.MaxAttemptCount = uint16(v)
case "low_rdy_idle_timeout":
v, err := getDuration(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v > 5*time.Minute || v < time.Second {
return errors.New(fmt.Sprintf("invalid %s ! 1s <= %s <= 5m", option, v))
}
q.LowRdyIdleTimeout = v
case "tls_v1":
v, err := getBool(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
q.TLSv1 = v
case "deflate":
v, err := getBool(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
q.Deflate = v
case "deflate_level":
v, err := getInt64(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v < 1 || v > 9 {
return errors.New(fmt.Sprintf("invalid %s ! 1 <= %d <= 9", option, v))
}
q.DeflateLevel = int(v)
case "sample_rate":
v, err := getInt64(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v < 0 || v > 99 {
return errors.New(fmt.Sprintf("invalid %s ! 0 <= %d <= 99", option, err))
}
q.SampleRate = int32(v)
case "snappy":
v, err := getBool(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
q.Snappy = v
case "max_in_flight":
v, err := getInt64(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v < 1 {
return errors.New(fmt.Sprintf("invalid %s ! 1 <= %d", option, v))
}
q.SetMaxInFlight(int(v))
case "max_backoff_duration":
v, err := getDuration(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
if v > 60*time.Minute || v < 0 {
return errors.New(fmt.Sprintf("invalid %s ! 0 <= %s <= 60m", option, v))
}
q.SetMaxBackoffDuration(v)
case "verbose":
v, err := getBool(value)
if err != nil {
return errors.New(fmt.Sprintf("invalid %s - %s", option, err))
}
q.VerboseLogging = v
}
return nil
}
// ConnectionMaxInFlight calculates the per-connection max-in-flight count.
//
// This may change dynamically based on the number of connections to nsqd the Reader
// is responsible for.
func (q *Reader) ConnectionMaxInFlight() int64 {
q.RLock()
defer q.RUnlock()
b := float64(q.MaxInFlight())
s := b / float64(len(q.nsqConnections))
return int64(math.Min(math.Max(1, s), b))
}
// IsStarved indicates whether any connections for this reader are blocked on processing
// before being able to receive more messages (ie. RDY count of 0 and not exiting)
func (q *Reader) IsStarved() bool {
q.RLock()
defer q.RUnlock()
for _, conn := range q.nsqConnections {
threshold := int64(float64(atomic.LoadInt64(&conn.lastRdyCount)) * 0.85)
inFlight := atomic.LoadInt64(&conn.messagesInFlight)
if inFlight >= threshold && inFlight > 0 && atomic.LoadInt32(&conn.stopFlag) != 1 {
return true
}
}
return false
}
// SetMaxInFlight sets the maximum number of messages this reader instance
// will allow in-flight.
//
// If already connected, it updates the reader RDY state for each connection.
func (q *Reader) SetMaxInFlight(maxInFlight int) {
if atomic.LoadInt32(&q.stopFlag) == 1 {
return
}
q.Lock()
if q.maxInFlight == maxInFlight {
q.Unlock()
return
}
q.maxInFlight = maxInFlight
q.Unlock()
q.RLock()
defer q.RUnlock()
for _, c := range q.nsqConnections {
c.rdyChan <- c
}
}
// SetMaxBackoffDuration sets the maximum duration a connection will backoff from message processing
func (q *Reader) SetMaxBackoffDuration(duration time.Duration) {
q.maxBackoffDuration = duration
atomic.StoreInt32(&q.maxBackoffCount,
int32(math.Max(1, math.Ceil(math.Log2(duration.Seconds())))))
}
// MaxInFlight returns the configured maximum number of messages to allow in-flight.
func (q *Reader) MaxInFlight() int {
q.RLock()
defer q.RUnlock()
return q.maxInFlight
}
// ConnectToLookupd adds an nsqlookupd address to the list for this Reader instance.
//
// If it is the first to be added, it initiates an HTTP request to discover nsqd
// producers for the configured topic.
//
// A goroutine is spawned to handle continual polling.
func (q *Reader) ConnectToLookupd(addr string) error {
q.Lock()
for _, x := range q.lookupdHTTPAddrs {
if x == addr {
q.Unlock()
return ErrLookupdAddressExists
}
}
q.lookupdHTTPAddrs = append(q.lookupdHTTPAddrs, addr)
numLookupd := len(q.lookupdHTTPAddrs)
q.Unlock()
// if this is the first one, kick off the go loop
if numLookupd == 1 {
q.queryLookupd()
go q.lookupdLoop()
}
return nil
}
// poll all known lookup servers every LookupdPollInterval
func (q *Reader) lookupdLoop() {
// add some jitter so that multiple consumers discovering the same topic,
// when restarted at the same time, dont all connect at once.
rand.Seed(time.Now().UnixNano())
jitter := time.Duration(int64(rand.Float64() * q.LookupdPollJitter * float64(q.LookupdPollInterval)))
ticker := time.NewTicker(q.LookupdPollInterval)
select {
case <-time.After(jitter):
case <-q.ExitChan:
goto exit
}
for {
select {
case <-ticker.C:
q.queryLookupd()
case <-q.lookupdRecheckChan:
q.queryLookupd()
case <-q.ExitChan:
goto exit
}
}
exit:
ticker.Stop()
log.Printf("exiting lookupdLoop")
}
// make an HTTP req to the /lookup endpoint of one of the
// configured nsqlookupd instances to discover which nsqd provide
// the topic we are consuming.
//
// initiate a connection to any new producers that are identified.
func (q *Reader) queryLookupd() {
q.RLock()
addr := q.lookupdHTTPAddrs[q.lookupdQueryIndex]
num := len(q.lookupdHTTPAddrs)
q.RUnlock()
q.lookupdQueryIndex = (q.lookupdQueryIndex + 1) % num
endpoint := fmt.Sprintf("http://%s/lookup?topic=%s", addr, url.QueryEscape(q.TopicName))
log.Printf("LOOKUPD: querying %s", endpoint)
data, err := ApiRequest(endpoint)
if err != nil {
log.Printf("ERROR: lookupd %s - %s", addr, err.Error())
return
}
// {
// "data": {
// "channels": [],
// "producers": [
// {
// "broadcast_address": "jehiah-air.local",
// "http_port": 4151,
// "tcp_port": 4150
// }
// ],
// "timestamp": 1340152173
// },
// "status_code": 200,
// "status_txt": "OK"
// }
for i, _ := range data.Get("producers").MustArray() {
producer := data.Get("producers").GetIndex(i)
address := producer.Get("address").MustString()
broadcastAddress, ok := producer.CheckGet("broadcast_address")
if ok {
address = broadcastAddress.MustString()
}
port := producer.Get("tcp_port").MustInt()
// make an address, start a connection
joined := net.JoinHostPort(address, strconv.Itoa(port))
err = q.ConnectToNSQ(joined)
if err != nil && err != ErrAlreadyConnected {
log.Printf("ERROR: failed to connect to nsqd (%s) - %s", joined, err.Error())
continue
}
}
}
// ConnectToNSQ takes a nsqd address to connect directly to.
//
// It is recommended to use ConnectToLookupd so that topics are discovered
// automatically. This method is useful when you want to connect to a single, local,
// instance.
func (q *Reader) ConnectToNSQ(addr string) error {
var buf bytes.Buffer
if atomic.LoadInt32(&q.stopFlag) == 1 {
return errors.New("reader stopped")
}
if atomic.LoadInt32(&q.runningHandlers) == 0 {
return errors.New("no handlers")
}
q.RLock()
_, ok := q.nsqConnections[addr]
_, pendingOk := q.pendingConnections[addr]
if ok || pendingOk {
q.RUnlock()
return ErrAlreadyConnected
}
q.RUnlock()
log.Printf("[%s] connecting to nsqd", addr)
connection, err := newNSQConn(q.rdyChan, addr, q.ReadTimeout, q.WriteTimeout)
if err != nil {
return err
}
cleanupConnection := func() {
q.Lock()
delete(q.pendingConnections, addr)
q.Unlock()
connection.Close()
}
q.pendingConnections[addr] = true
ci := make(map[string]interface{})
ci["short_id"] = q.ShortIdentifier
ci["long_id"] = q.LongIdentifier
ci["tls_v1"] = q.TLSv1
ci["deflate"] = q.Deflate
ci["deflate_level"] = q.DeflateLevel
ci["snappy"] = q.Snappy
ci["feature_negotiation"] = true
ci["sample_rate"] = q.SampleRate
ci["authentication_password"] = q.authenticationPassword
cmd, err := Identify(ci)
if err != nil {
cleanupConnection()
return fmt.Errorf("[%s] failed to create identify command - %s", connection, err.Error())
}
err = connection.sendCommand(&buf, cmd)
if err != nil {
cleanupConnection()
return fmt.Errorf("[%s] failed to identify - %s", connection, err.Error())
}
_, data, err := connection.readUnpackedResponse()
if err != nil {
cleanupConnection()
return fmt.Errorf("[%s] error reading response %s", connection, err.Error())
}
// check to see if the server was able to respond w/ capabilities
if data[0] == '{' {
resp := struct {
MaxRdyCount int64 `json:"max_rdy_count"`
TLSv1 bool `json:"tls_v1"`
Deflate bool `json:"deflate"`
Snappy bool `json:"snappy"`
SampleRate int32 `json:"sample_rate"`
}{}
err := json.Unmarshal(data, &resp)
if err != nil {
cleanupConnection()
return fmt.Errorf("[%s] error (%s) unmarshaling IDENTIFY response %s", connection, err.Error(), data)
}
log.Printf("[%s] IDENTIFY response: %+v", connection, resp)
connection.maxRdyCount = resp.MaxRdyCount
if resp.MaxRdyCount < int64(q.MaxInFlight()) {
log.Printf("[%s] max RDY count %d < reader max in flight %d, truncation possible",
connection, resp.MaxRdyCount, q.MaxInFlight())
}
if resp.TLSv1 {
log.Printf("[%s] upgrading to TLS", connection)
err := connection.upgradeTLS(q.TLSConfig)
if err != nil {
cleanupConnection()
return fmt.Errorf("[%s] error (%s) upgrading to TLS", connection, err.Error())
}
}
if resp.Deflate {
log.Printf("[%s] upgrading to Deflate", connection)
err := connection.upgradeDeflate(q.DeflateLevel)
if err != nil {
connection.Close()
return fmt.Errorf("[%s] error (%s) upgrading to deflate", connection, err.Error())
}
}
if resp.Snappy {
log.Printf("[%s] upgrading to Snappy", connection)
err := connection.upgradeSnappy()
if err != nil {
connection.Close()
return fmt.Errorf("[%s] error (%s) upgrading to snappy", connection, err.Error())
}
}
}
cmd = Subscribe(q.TopicName, q.ChannelName)
err = connection.sendCommand(&buf, cmd)
if err != nil {
cleanupConnection()
return fmt.Errorf("[%s] failed to subscribe to %s:%s - %s", connection, q.TopicName, q.ChannelName, err.Error())
}
q.Lock()
delete(q.pendingConnections, addr)
q.nsqConnections[connection.String()] = connection
q.Unlock()
// pre-emptive signal to existing connections to lower their RDY count
q.RLock()
for _, c := range q.nsqConnections {
c.rdyChan <- c
}
q.RUnlock()
connection.wg.Add(2)
go q.readLoop(connection)
go q.finishLoop(connection)
return nil
}
func handleError(q *Reader, c *nsqConn, errMsg string) {
log.Printf(errMsg)
atomic.StoreInt32(&c.stopFlag, 1)
q.RLock()
numLookupd := len(q.lookupdHTTPAddrs)
q.RUnlock()
if numLookupd == 0 {
go func(addr string) {
for {
log.Printf("[%s] re-connecting in 15 seconds...", addr)
time.Sleep(15 * time.Second)
if atomic.LoadInt32(&q.stopFlag) == 1 {
break
}
err := q.ConnectToNSQ(addr)
if err != nil && err != ErrAlreadyConnected {
log.Printf("ERROR: failed to connect to %s - %s",
addr, err.Error())
continue
}
break
}
}(c.RemoteAddr().String())
}
}
func (q *Reader) readLoop(c *nsqConn) {
for {
if atomic.LoadInt32(&c.stopFlag) == 1 || atomic.LoadInt32(&q.stopFlag) == 1 {
// start the connection close
if atomic.LoadInt64(&c.messagesInFlight) == 0 {
q.stopFinishLoop(c)
} else {
log.Printf("[%s] delaying close, %d outstanding messages",
c, c.messagesInFlight)
}
goto exit
}
frameType, data, err := c.readUnpackedResponse()
if err != nil {
handleError(q, c, fmt.Sprintf("[%s] error (%s) reading response %d %s",
c, err.Error(), frameType, data))
continue
}
switch frameType {
case FrameTypeMessage:
msg, err := DecodeMessage(data)
msg.cmdChan = c.cmdChan
msg.responseChan = c.finishedMessages
if err != nil {
handleError(q, c, fmt.Sprintf("[%s] error (%s) decoding message %s",
c, err.Error(), data))
continue
}
remain := atomic.AddInt64(&c.rdyCount, -1)
atomic.AddInt64(&q.totalRdyCount, -1)
atomic.AddUint64(&c.messagesReceived, 1)
atomic.AddUint64(&q.MessagesReceived, 1)
atomic.AddInt64(&c.messagesInFlight, 1)
atomic.AddInt64(&q.messagesInFlight, 1)
atomic.StoreInt64(&c.lastMsgTimestamp, time.Now().UnixNano())
if q.VerboseLogging {
log.Printf("[%s] (remain %d) FrameTypeMessage: %s - %s",
c, remain, msg.Id, msg.Body)
}
q.incomingMessages <- msg
c.rdyChan <- c
case FrameTypeResponse:
switch {
case bytes.Equal(data, []byte("CLOSE_WAIT")):
// server is ready for us to close (it ack'd our StartClose)
// we can assume we will not receive any more messages over this channel
// (but we can still write back responses)
log.Printf("[%s] received ACK from nsqd - now in CLOSE_WAIT", c)
atomic.StoreInt32(&c.stopFlag, 1)
case bytes.Equal(data, []byte("_heartbeat_")):
var buf bytes.Buffer
log.Printf("[%s] heartbeat received", c)
err := c.sendCommand(&buf, Nop())
if err != nil {
handleError(q, c, fmt.Sprintf("[%s] error sending NOP - %s",
c, err.Error()))
goto exit
}
}
case FrameTypeError:
log.Printf("[%s] error from nsqd %s", c, data)
default:
log.Printf("[%s] unknown message type %d", c, frameType)
}
}
exit:
c.wg.Done()
log.Printf("[%s] readLoop exiting", c)
}
func (q *Reader) finishLoop(c *nsqConn) {
var buf bytes.Buffer
for {
select {
case <-c.exitChan:
log.Printf("[%s] breaking out of finish loop", c)
// Indicate drainReady because we will not pull any more off finishedMessages
close(c.drainReady)
goto exit
case cmd := <-c.cmdChan:
err := c.sendCommand(&buf, cmd)
if err != nil {
log.Printf("[%s] error sending command %s - %s", c, cmd, err)
q.stopFinishLoop(c)
continue
}
case msg := <-c.finishedMessages:
// Decrement this here so it is correct even if we can't respond to nsqd
atomic.AddInt64(&q.messagesInFlight, -1)
atomic.AddInt64(&c.messagesInFlight, -1)
if msg.Success {
if q.VerboseLogging {
log.Printf("[%s] finishing %s", c, msg.Id)
}
err := c.sendCommand(&buf, Finish(msg.Id))
if err != nil {
log.Printf("[%s] error finishing %s - %s", c, msg.Id, err.Error())
q.stopFinishLoop(c)
continue
}
atomic.AddUint64(&c.messagesFinished, 1)
atomic.AddUint64(&q.MessagesFinished, 1)
} else {
if q.VerboseLogging {
log.Printf("[%s] requeuing %s", c, msg.Id)
}
err := c.sendCommand(&buf, Requeue(msg.Id, msg.RequeueDelayMs))
if err != nil {
log.Printf("[%s] error requeueing %s - %s", c, msg.Id, err.Error())
q.stopFinishLoop(c)
continue
}
atomic.AddUint64(&c.messagesRequeued, 1)
atomic.AddUint64(&q.MessagesRequeued, 1)
}
q.backoffChan <- msg.Success
if atomic.LoadInt64(&c.messagesInFlight) == 0 &&
(atomic.LoadInt32(&c.stopFlag) == 1 || atomic.LoadInt32(&q.stopFlag) == 1) {
q.stopFinishLoop(c)
continue
}
}
}
exit:
c.wg.Done()
log.Printf("[%s] finishLoop exiting", c)
}
func (q *Reader) stopFinishLoop(c *nsqConn) {
c.stopper.Do(func() {
log.Printf("[%s] beginning stopFinishLoop", c)
close(c.exitChan)
c.Close()
go q.cleanupConnection(c)
})
}
func (q *Reader) cleanupConnection(c *nsqConn) {
go func() {
<-c.drainReady
ticker := time.NewTicker(100 * time.Millisecond)
// finishLoop has exited, drain any remaining in flight messages
for {
// we're racing with readLoop which potentially has a message
// for handling...
//
// infinitely loop until the connection's waitgroup is satisfied,
// ensuring that both finishLoop and readLoop have exited, at which
// point we can be guaranteed that messagesInFlight accurately
// represents whatever is left... continue until 0.
var msgsInFlight int64
select {
case <-c.finishedMessages:
msgsInFlight = atomic.AddInt64(&c.messagesInFlight, -1)
case <-ticker.C:
msgsInFlight = atomic.LoadInt64(&c.messagesInFlight)
}
if msgsInFlight > 0 {
log.Printf("[%s] draining... waiting for %d messages in flight", c, msgsInFlight)
continue
}
log.Printf("[%s] done draining finishedMessages", c)
ticker.Stop()
return
}
}()
// this blocks until finishLoop and readLoop have exited
c.wg.Wait()
// remove this connections RDY count from the reader's total
rdyCount := atomic.LoadInt64(&c.rdyCount)
atomic.AddInt64(&q.totalRdyCount, -rdyCount)
c.Lock()
hasRDYRetryTimer := c.rdyRetryTimer != nil
if c.rdyRetryTimer != nil {
// stop any pending retry of an old RDY update
c.rdyRetryTimer.Stop()
c.rdyRetryTimer = nil
}
c.Unlock()
q.Lock()
delete(q.nsqConnections, c.String())
left := len(q.nsqConnections)
q.Unlock()
log.Printf("there are %d connections left alive", left)
if (hasRDYRetryTimer || rdyCount > 0) &&
(left == q.MaxInFlight() || q.inBackoff()) {
// we're toggling out of (normal) redistribution cases and this conn
// had a RDY count...
//
// trigger RDY redistribution to make sure this RDY is moved
// to a new connection
atomic.StoreInt32(&q.needRDYRedistributed, 1)
}
// we were the last one (and stopping)
if left == 0 && atomic.LoadInt32(&q.stopFlag) == 1 {
q.stopHandlers()
return
}
q.RLock()
numLookupd := len(q.lookupdHTTPAddrs)
q.RUnlock()
if numLookupd != 0 && atomic.LoadInt32(&q.stopFlag) == 0 {
// trigger a poll of the lookupd
select {
case q.lookupdRecheckChan <- 1:
default:
}
}
}