-
Notifications
You must be signed in to change notification settings - Fork 13
/
producer.go
2195 lines (2011 loc) · 61.6 KB
/
producer.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"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/url"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
MAX_PARTITION_NUM = 1024
MIN_RETRY_SLEEP = time.Millisecond * 8
)
var (
ErrTopicNotSet = errors.New("topic is not set as producer")
ErrNoProducer = errors.New("topic producer not found")
ErrRetryBackground = errors.New("retrying in background")
errMissingShardingKey = errors.New("missing sharding key for ordered publish")
removingKeepTime = time.Minute * 10
testingTimeout = false
testingSendTimeout = false
)
type producerConn interface {
String() string
SetLogger(logger, LogLevel, string)
Connect() (*IdentifyResponse, error)
CloseAll()
CloseRead() error
WriteCommand(*Command) error
}
type pubLoadHandler interface {
AddPending(c int64)
AddCost(time.Duration)
GetCost() int64
GetPending() int64
}
// Producer is a high-level type to publish to NSQ.
//
// A Producer instance is 1:1 with a destination `nsqd`
// and will lazily connect to that instance (and re-connect)
// when Publish commands are executed.
type Producer struct {
id int64
addr string
conn producerConn
connDelegateFunc func(*Producer) ConnDelegate
config Config
logger logger
logLvl LogLevel
logGuard sync.RWMutex
responseChan chan []byte
errorChan chan []byte
closeChan chan int
transactionChan chan *ProducerTransaction
transactions []*ProducerTransaction
state int32
concurrentProducers int32
stopFlag int32
exitChan chan int
wg sync.WaitGroup
guard sync.Mutex
failedCnt int32
pubLoad pubLoadHandler
}
// ProducerTransaction is returned by the async publish methods
// to retrieve metadata about the command after the
// response is received.
type ProducerTransaction struct {
cmd *Command
doneChan chan *ProducerTransaction
Error error // the error (or nil) of the publish command
Args []interface{} // the slice of variadic arguments passed to PublishAsync or MultiPublishAsync
ResponseData []byte
}
func (t *ProducerTransaction) finish(stop chan int) {
if t.doneChan != nil {
select {
case t.doneChan <- t:
case <-stop:
}
}
}
// NewProducer returns an instance of Producer for the specified address
//
// The only valid way to create a Config is via NewConfig, using a struct literal will panic.
// After Config is passed into NewProducer the values are no longer mutable (they are copied).
func NewProducer(addr string, config *Config) (*Producer, error) {
config.assertInitialized()
err := config.Validate()
if err != nil {
return nil, err
}
p := &Producer{
id: atomic.AddInt64(&instCount, 1),
addr: addr,
config: *config,
logger: log.New(os.Stderr, "", log.Flags()),
logLvl: LogLevelInfo,
transactionChan: make(chan *ProducerTransaction),
exitChan: make(chan int),
responseChan: make(chan []byte),
errorChan: make(chan []byte),
connDelegateFunc: func(producer *Producer) ConnDelegate {
return &producerConnDelegate{producer}
},
}
return p, nil
}
// Ping causes the Producer to connect to it's configured nsqd (if not already
// connected) and send a `Nop` command, returning any error that might occur.
//
// This method can be used to verify that a newly-created Producer instance is
// configured correctly, rather than relying on the lazy "connect on Publish"
// behavior of a Producer.
func (w *Producer) Ping() error {
if atomic.LoadInt32(&w.state) != StateConnected {
err := w.connect()
if err != nil {
return err
}
}
return w.conn.WriteCommand(Nop())
}
// SetLogger assigns the logger to use as well as a level
//
// The logger parameter is an interface that requires the following
// method to be implemented (such as the the stdlib log.Logger):
//
// Output(calldepth int, s string)
//
func (w *Producer) SetLogger(l logger, lvl LogLevel) {
w.logGuard.Lock()
defer w.logGuard.Unlock()
w.logger = l
w.logLvl = lvl
}
func (w *Producer) getLogger() (logger, LogLevel) {
w.logGuard.RLock()
defer w.logGuard.RUnlock()
return w.logger, w.logLvl
}
// String returns the address of the Producer
func (w *Producer) String() string {
return w.addr
}
func (w *Producer) FailedConnCnt() int32 {
return atomic.LoadInt32(&w.failedCnt)
}
func (w *Producer) AddPubCost(c time.Duration) {
if w.pubLoad == nil {
return
}
w.pubLoad.AddCost(c)
}
func (w *Producer) GetAvgPubCost() int64 {
if w.pubLoad == nil {
return 0
}
return w.pubLoad.GetCost()
}
// Stop initiates a graceful stop of the Producer (permanent)
//
// NOTE: this blocks until completion
func (w *Producer) Stop() {
w.guard.Lock()
if !atomic.CompareAndSwapInt32(&w.stopFlag, 0, 1) {
w.guard.Unlock()
return
}
w.log(LogLevelInfo, "stopping")
close(w.exitChan)
w.close(false)
w.guard.Unlock()
w.wg.Wait()
}
// PublishAsync publishes a message body to the specified topic
// but does not wait for the response from `nsqd`.
//
// When the Producer eventually receives the response from `nsqd`,
// the supplied `doneChan` (if specified)
// will receive a `ProducerTransaction` instance with the supplied variadic arguments
// and the response error if present
func (w *Producer) PublishAsync(topic string, body []byte, doneChan chan *ProducerTransaction,
args ...interface{}) error {
return w.sendCommandAsync(Publish(topic, body), doneChan, args)
}
func (w *Producer) PublishWithPartitionIdAsync(topic string, partition string, body []byte, ext *MsgExt, doneChan chan *ProducerTransaction,
args ...interface{}) error {
var cmd *Command
var err error
if ext != nil {
cmd, err = PublishWithJsonExt(topic, partition, body, ext.ToJson())
if err != nil {
return err
}
} else {
cmd = PublishWithPart(topic, partition, body)
}
return w.sendCommandAsync(cmd, doneChan, args)
}
// MultiPublishAsync publishes a slice of message bodies to the specified topic
// but does not wait for the response from `nsqd`.
//
// When the Producer eventually receives the response from `nsqd`,
// the supplied `doneChan` (if specified)
// will receive a `ProducerTransaction` instance with the supplied variadic arguments
// and the response error if present
func (w *Producer) MultiPublishAsync(topic string, body [][]byte, doneChan chan *ProducerTransaction,
args ...interface{}) error {
cmd, err := MultiPublish(topic, body)
if err != nil {
return err
}
return w.sendCommandAsync(cmd, doneChan, args)
}
// Publish synchronously publishes a message body to the specified topic, returning
// an error if publish failed
func (w *Producer) Publish(topic string, body []byte) error {
_, err := w.sendCommand(Publish(topic, body))
return err
}
// MultiPublish synchronously publishes a slice of message bodies to the specified topic, returning
// an error if publish failed
func (w *Producer) MultiPublish(topic string, body [][]byte) error {
cmd, err := MultiPublish(topic, body)
if err != nil {
return err
}
_, err = w.sendCommand(cmd)
return err
}
func (w *Producer) sendCommandWithContext(ctx context.Context, cmd *Command) ([]byte, error) {
doneChan := make(chan *ProducerTransaction, 1)
err := w.sendCommandAsyncWithContext(ctx, cmd, doneChan, nil)
if err != nil {
return nil, err
}
select {
case <-ctx.Done():
err := errors.New("pub failed : " + ctx.Err().Error())
return nil, err
case t := <-doneChan:
return t.ResponseData, t.Error
}
}
func (w *Producer) sendCommand(cmd *Command) ([]byte, error) {
ctx := context.Background()
if w.config.PubTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, w.config.PubTimeout)
defer cancel()
}
return w.sendCommandWithContext(ctx, cmd)
}
func (w *Producer) sendCommandAsync(cmd *Command, doneChan chan *ProducerTransaction,
args []interface{}) error {
ctx := context.Background()
if w.config.PubTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, w.config.PubTimeout)
defer cancel()
}
return w.sendCommandAsyncWithContext(ctx, cmd, doneChan, args)
}
func (w *Producer) sendCommandAsyncWithContext(ctx context.Context, cmd *Command, doneChan chan *ProducerTransaction,
args []interface{}) error {
// keep track of how many outstanding producers we're dealing with
// in order to later ensure that we clean them all up...
atomic.AddInt32(&w.concurrentProducers, 1)
defer atomic.AddInt32(&w.concurrentProducers, -1)
if atomic.LoadInt32(&w.state) != StateConnected {
err := w.connect()
if err != nil {
return err
}
}
t := &ProducerTransaction{
cmd: cmd,
doneChan: doneChan,
Args: args,
}
select {
case w.transactionChan <- t:
case <-w.exitChan:
return ErrStopped
case <-ctx.Done():
return ctx.Err()
}
return nil
}
func (w *Producer) setConnDelegateFunc(f func(*Producer) ConnDelegate) {
w.connDelegateFunc = f;
}
func (w *Producer) connect() error {
w.guard.Lock()
defer w.guard.Unlock()
if atomic.LoadInt32(&w.stopFlag) == 1 {
return ErrStopped
}
switch state := atomic.LoadInt32(&w.state); state {
case StateInit:
case StateConnected:
return nil
default:
return ErrNotConnected
}
w.log(LogLevelInfo, "(%s) connecting to nsqd", w.addr)
logger, logLvl := w.getLogger()
w.conn = NewConn(w.addr, &w.config, w.connDelegateFunc(w))
w.conn.SetLogger(logger, logLvl, fmt.Sprintf("%3d (%%s)", w.id))
atomic.StoreInt32(&w.state, StateConnecting)
_, err := w.conn.Connect()
if err != nil {
w.conn.CloseAll()
w.log(LogLevelError, "(%s) error connecting to nsqd - %s", w.addr, err)
atomic.AddInt32(&w.failedCnt, 1)
return err
}
atomic.StoreInt32(&w.state, StateConnected)
atomic.StoreInt32(&w.failedCnt, 0)
w.closeChan = make(chan int)
w.wg.Add(1)
go w.router(w.closeChan)
return nil
}
func (w *Producer) close(force bool) {
if !atomic.CompareAndSwapInt32(&w.state, StateConnected, StateDisconnected) {
return
}
if force {
w.conn.CloseAll()
} else {
w.conn.CloseRead()
}
go func() {
// we need to handle this in a goroutine so we don't
// block the caller from making progress
w.wg.Wait()
atomic.StoreInt32(&w.state, StateInit)
}()
}
func (w *Producer) router(closeChan <-chan int) {
for {
select {
case t := <-w.transactionChan:
if testingSendTimeout {
continue
}
w.transactions = append(w.transactions, t)
if w.pubLoad != nil {
w.pubLoad.AddPending(1)
}
err := w.conn.WriteCommand(t.cmd)
if err != nil {
w.log(LogLevelError, "(%s) sending command - %s", w.conn.String(), err)
w.close(true)
}
case data := <-w.responseChan:
w.popTransaction(FrameTypeResponse, data)
case data := <-w.errorChan:
w.popTransaction(FrameTypeError, data)
case <- closeChan:
goto exit
case <-w.exitChan:
goto exit
}
}
exit:
w.transactionCleanup()
w.wg.Done()
w.log(LogLevelInfo, "exiting router")
}
func (w *Producer) popTransaction(frameType int32, data []byte) {
t := w.transactions[0]
if w.pubLoad != nil {
w.pubLoad.AddPending(-1)
}
w.transactions = w.transactions[1:]
if frameType == FrameTypeError {
t.Error = ErrProtocol{string(data)}
if IsFailedOnNotLeader(t.Error) || IsTopicNotExist(t.Error) || IsFailedOnNotWritable(t.Error) {
// TODO: notify to reload topic-producer relation.
}
} else {
t.ResponseData = data
}
if testingTimeout {
return
}
t.finish(w.exitChan)
}
func (w *Producer) transactionCleanup() {
// clean up transactions we can easily account for
for _, t := range w.transactions {
t.Error = ErrNotConnected
t.finish(w.exitChan)
}
if w.pubLoad != nil {
w.pubLoad.AddPending(int64(-1 * len(w.transactions)))
}
w.transactions = w.transactions[:0]
// spin and free up any writes that might have raced
// with the cleanup process (blocked on writing
// to transactionChan)
for {
select {
case t := <-w.transactionChan:
t.Error = ErrNotConnected
t.finish(w.exitChan)
default:
// keep spinning until there are 0 concurrent producers
if atomic.LoadInt32(&w.concurrentProducers) == 0 {
return
}
// give the runtime a chance to schedule other racing goroutines
time.Sleep(5 * time.Millisecond)
}
}
}
func (w *Producer) log(lvl LogLevel, line string, args ...interface{}) {
logger, logLvl := w.getLogger()
if logger == nil {
return
}
if logLvl > lvl {
return
}
logger.Output(2, fmt.Sprintf("%-4s %3d %s", lvl, w.id, fmt.Sprintf(line, args...)))
}
func (w *Producer) onConnResponse(c *Conn, data []byte) {
w.responseChan <- data
}
func (w *Producer) onConnError(c *Conn, data []byte) { w.errorChan <- data }
func (w *Producer) onConnHeartbeat(c *Conn) {}
func (w *Producer) onConnIOError(c *Conn, err error) { w.close(true) }
func (w *Producer) onConnClose(c *Conn) {
w.guard.Lock()
defer w.guard.Unlock()
if atomic.LoadInt32(&w.state) == StateConnecting {
atomic.StoreInt32(&w.state, StateInit)
} else if w.closeChan != nil {
//close close chan, only when producer's connection equals with passin *Conn
close(w.closeChan)
//guard from close closed ch by setting nil
w.closeChan = nil
}
}
// the strategy how the message publish on different partitions
type PubStrategyType int
const (
PubRR PubStrategyType = iota
// choose the pub node based on the pending and avg rt
PubDynamicLoad
)
type AddrPartInfo struct {
addr string
pid int
}
type TopicPartProducerInfo struct {
currentIndex uint32
allPartitions []AddrPartInfo
meta metaInfo
isMetaValid bool
}
func NewTopicPartProducerInfo(meta metaInfo, isMetaValid bool) *TopicPartProducerInfo {
return &TopicPartProducerInfo{
currentIndex: 0,
allPartitions: make([]AddrPartInfo, 0, meta.PartitionNum),
meta: meta,
isMetaValid: isMetaValid,
}
}
func (self *TopicPartProducerInfo) updatePartitionInfo(index uint32, addrInfo AddrPartInfo) {
for len(self.allPartitions) <= int(index) {
self.allPartitions = append(self.allPartitions, AddrPartInfo{})
}
self.allPartitions[index] = addrInfo
}
func (self *TopicPartProducerInfo) removePartitionInfo(index uint32) AddrPartInfo {
if len(self.allPartitions) <= int(index) {
return AddrPartInfo{}
}
removed := self.allPartitions[index]
self.allPartitions[index] = AddrPartInfo{}
return removed
}
func (self *TopicPartProducerInfo) getMultiPartitionInfoForPick(num int) []AddrPartInfo {
total := len(self.allPartitions)
index := atomic.AddUint32(&self.currentIndex, 1)
addrs := make([]AddrPartInfo, 0, num)
for i := index; i < index+uint32(num); i++ {
addrInfo1 := self.getPartitionInfo(i % uint32(total))
addrs = append(addrs, addrInfo1)
}
return addrs
}
func (self *TopicPartProducerInfo) getPartitionInfo(index uint32) AddrPartInfo {
if len(self.allPartitions) <= int(index) {
return AddrPartInfo{}
}
addr := self.allPartitions[index]
return addr
}
func (self *TopicPartProducerInfo) getSpecificPartitionInfo(pid int) AddrPartInfo {
if pid < 0 {
return AddrPartInfo{}
}
if pid < len(self.allPartitions) {
addrInfo := self.allPartitions[pid]
if addrInfo.pid == pid {
return addrInfo
}
}
for _, addrInfo := range self.allPartitions {
if addrInfo.pid == pid {
return addrInfo
}
}
return AddrPartInfo{}
}
func FindString(src []string, f string) int {
for i, v := range src {
if f == v {
return i
}
}
return -1
}
type RemoveProducerInfo struct {
producer *producerPool
ts time.Time
}
type CmdFuncT func(pid int) (*Command, error)
type backgroundCommand struct {
StartTs time.Time
RetryCnt uint32
Topic string
partitionKey []byte
commandFunc CmdFuncT
done bool
rawBytes []byte
}
type producerLoadComputer struct {
lastAvg int64
pendingCnt int64
// this is used to avoid some large avg rt will never be get updated since no request will be send to this
avgResetLeft int64
}
func (rtc *producerLoadComputer) AddPending(c int64) {
atomic.AddInt64(&rtc.pendingCnt, c)
}
func (rtc *producerLoadComputer) GetPending() int64 {
return atomic.LoadInt64(&rtc.pendingCnt)
}
func (rtc *producerLoadComputer) AddCost(c time.Duration) {
last := atomic.LoadInt64(&rtc.lastAvg)
atomic.StoreInt64(&rtc.avgResetLeft, 10)
if c >= time.Second {
// avoid exception for avg
// too slow will cost the pending increase, which can avoid be chosen
// we only consider the rt while pending is not much
return
}
if last <= 0 {
atomic.StoreInt64(&rtc.lastAvg, c.Nanoseconds())
} else {
last = (last*4 + c.Nanoseconds()) / 5
atomic.StoreInt64(&rtc.lastAvg, last)
}
}
func (rtc *producerLoadComputer) DecrLeftCount() {
atomic.AddInt64(&rtc.avgResetLeft, -1)
}
func (rtc *producerLoadComputer) GetCost() int64 {
left := atomic.LoadInt64(&rtc.avgResetLeft)
if left <= 0 {
atomic.StoreInt64(&rtc.lastAvg, 0)
return 0
}
return atomic.LoadInt64(&rtc.lastAvg)
}
type producerPool struct {
addr string
index uint64
producerList []*Producer
loadComputer *producerLoadComputer
}
func newProducerPool(addr string, config *Config) (*producerPool, error) {
pp := &producerPool{
addr: addr,
producerList: make([]*Producer, config.ProducerPoolSize),
loadComputer: &producerLoadComputer{},
}
for i := 0; i < len(pp.producerList); i++ {
p, err := NewProducer(addr, config)
if err != nil {
return nil, err
}
p.pubLoad = pp.loadComputer
pp.producerList[i] = p
}
return pp, nil
}
func (pp *producerPool) SetLogger(l logger, lvl LogLevel) {
for _, p := range pp.producerList {
p.SetLogger(l, lvl)
}
}
func (pp *producerPool) IsLessLoad(other *producerPool) bool {
if other == nil {
return true
}
if pp.Pending() < other.Pending() {
return true
} else if pp.Pending() == other.Pending() {
// for small pending, we always choose the first to keep rr strategy
if pp.Pending() <= 1 {
return true
}
if pp.AvgPubRT() < other.AvgPubRT() {
return true
}
}
return false
}
func (pp *producerPool) Pending() int64 {
return pp.loadComputer.GetPending()
}
func (pp *producerPool) AvgPubRT() int64 {
return pp.loadComputer.GetCost()
}
func (pp *producerPool) getProducer() *Producer {
i := atomic.AddUint64(&pp.index, 1)
return pp.producerList[i%uint64(len(pp.producerList))]
}
func (pp *producerPool) DecrLeftCount() {
pp.loadComputer.DecrLeftCount()
}
func (pp *producerPool) stopAll() {
for _, p := range pp.producerList {
p.Stop()
}
}
type TopicProducerMgr struct {
pubStrategy PubStrategyType
producerMtx sync.RWMutex
topicMtx sync.RWMutex
hashMtx sync.Mutex
topics map[string]*TopicPartProducerInfo
producers map[string]*producerPool
removingProducers map[string]*RemoveProducerInfo
config Config
etcdServers []string
etcdClusterID string
etcdLookupPath string
lookupdHTTPAddrs []string
logger logger
logLvl LogLevel
logGuard sync.RWMutex
mtx sync.RWMutex
lookupdQueryIndex int
exitChan chan int
wg sync.WaitGroup
lookupdRecheckChan chan int
newTopicChan chan string
newTopicRspChan chan int
backgroundBuffer chan *backgroundCommand
topicForCompress map[string]bool
codec NSQClientCompressCodec
}
// use part=-1 to handle all partitions of topic
func NewTopicProducerMgr(topics []string, conf *Config) (*TopicProducerMgr, error) {
conf.assertInitialized()
err := conf.Validate()
if err != nil {
return nil, err
}
mgr := &TopicProducerMgr{
topics: make(map[string]*TopicPartProducerInfo, len(topics)),
pubStrategy: PubStrategyType(conf.PubStrategy),
producers: make(map[string]*producerPool),
removingProducers: make(map[string]*RemoveProducerInfo),
config: *conf,
lookupdRecheckChan: make(chan int),
exitChan: make(chan int),
newTopicChan: make(chan string),
newTopicRspChan: make(chan int),
topicForCompress: make(map[string]bool),
}
mgr.backgroundBuffer = make(chan *backgroundCommand, conf.PubBackgroundBuffer)
for _, t := range topics {
mgr.topics[t] = NewTopicPartProducerInfo(metaInfo{}, false)
}
mgr.codec, err = GetNSQClientCompressCodec(conf.ClientCompressDecodec)
if err != nil {
return nil, err
}
//init topc for compress map
for _, t := range conf.TopicsForCompress {
mgr.topicForCompress[t] = true
}
mgr.wg.Add(1)
go mgr.handleBackgroundRetry()
return mgr, nil
}
func (self *TopicProducerMgr) ConnectToSeeds() error {
for _, lookup := range self.config.LookupdSeeds {
err := self.ConnectToNSQLookupd(lookup)
if err != nil {
return err
}
}
return nil
}
func (self *TopicProducerMgr) Stop() {
close(self.exitChan)
self.producerMtx.RLock()
for _, p := range self.producers {
p.stopAll()
}
for _, p := range self.removingProducers {
p.producer.stopAll()
}
self.producerMtx.RUnlock()
self.wg.Wait()
}
type ProducerStat struct {
Pending int64
AvgRt int64
}
func (self *TopicProducerMgr) Stat() map[string]ProducerStat {
stat := make(map[string]ProducerStat)
self.producerMtx.RLock()
defer self.producerMtx.RUnlock()
for addr, pp := range self.producers {
stat[addr] = ProducerStat{
Pending: pp.Pending(),
AvgRt: pp.AvgPubRT(),
}
}
return stat
}
func (self *TopicProducerMgr) SetEtcdConf(servers []string, cluster string, lookupPath string) {
self.etcdServers = servers
self.etcdClusterID = cluster
self.etcdLookupPath = lookupPath
}
func (self *TopicProducerMgr) AddLookupdNodes(addresses []string) {
for _, addr := range addresses {
self.ConnectToNSQLookupd(addr)
}
}
func (self *TopicProducerMgr) ConnectToNSQLookupd(addr string) error {
if err := validatedLookupAddr(addr); err != nil {
return err
}
self.mtx.Lock()
for _, x := range self.lookupdHTTPAddrs {
if x == addr {
self.mtx.Unlock()
return nil
}
}
self.lookupdHTTPAddrs = append(self.lookupdHTTPAddrs, addr)
numLookupd := len(self.lookupdHTTPAddrs)
self.mtx.Unlock()
self.log(LogLevelInfo, "new lookupd address added: %s", addr)
// if this is the first one, kick off the go loop
if numLookupd == 1 {
self.queryLookupd("")
self.wg.Add(1)
go self.lookupLoop()
}
return nil
}
// for async operation, the async error should be check by the application if async operation has error.
func (self *TopicProducerMgr) TriggerCheckForError(err error, delay time.Duration) {
if err == nil {
return
}
if IsFailedOnNotLeader(err) || IsTopicNotExist(err) || IsFailedOnNotWritable(err) {
time.Sleep(delay)
select {
case self.lookupdRecheckChan <- 1:
default:
}
}
}
// TODO: may be we can move the lookup query to some other manager class and all producer share the
// lookup manager
func (self *TopicProducerMgr) nextLookupdEndpoint(newTopic string) (string, map[string]string, string) {
self.mtx.RLock()
if self.lookupdQueryIndex >= len(self.lookupdHTTPAddrs) {
self.lookupdQueryIndex = 0
}
addr := self.lookupdHTTPAddrs[self.lookupdQueryIndex]
num := len(self.lookupdHTTPAddrs)
self.mtx.RUnlock()
self.lookupdQueryIndex = (self.lookupdQueryIndex + 1) % num
urlString := addr
if !strings.Contains(urlString, "://") {
urlString = "http://" + addr
}
u, err := url.Parse(urlString)
if err != nil {
panic(err)
}
listUrl := *u
if u.Path == "/" || u.Path == "" {
u.Path = "/lookup"
}
listUrl.Path = "/listlookup"
urlList := make(map[string]string, 0)
if newTopic != "" {
tmpUrl := *u
v, _ := url.ParseQuery(tmpUrl.RawQuery)
v.Add("topic", newTopic)
v.Add("metainfo", "true")
v.Add("access", "w")
tmpUrl.RawQuery = v.Encode()
urlList[newTopic] = tmpUrl.String()
} else {
for t, _ := range self.topics {
tmpUrl := *u
v, _ := url.ParseQuery(tmpUrl.RawQuery)
v.Add("topic", t)
v.Add("metainfo", "true")
v.Add("access", "w")
tmpUrl.RawQuery = v.Encode()
urlList[t] = tmpUrl.String()
}
}
return addr, urlList, listUrl.String()
}
func (self *TopicProducerMgr) queryLookupd(newTopic string) {
if newTopic != "" {
self.log(LogLevelInfo, "new topic %v added", newTopic)
}
addr, topicQueryList, discoveryUrl := self.nextLookupdEndpoint(newTopic)
// discovery other lookupd nodes from current lookupd or from etcd
self.log(LogLevelDebug, "discovery nsqlookupd %s", discoveryUrl)
var lookupdList lookupListResp
err := apiRequestNegotiateV1("GET", discoveryUrl, nil, &lookupdList)
if err != nil {
self.log(LogLevelError, "error discovery nsqlookupd (%s) - %s", discoveryUrl, err)
if strings.Contains(strings.ToLower(err.Error()), "connection refused") &&
FindString(self.config.LookupdSeeds, addr) == -1 {
self.mtx.Lock()
// remove failed
self.log(LogLevelInfo, "removing failed lookup : %v", addr)
newLookupList := make([]string, 0)
for _, v := range self.lookupdHTTPAddrs {
if v == addr {
continue
} else {
newLookupList = append(newLookupList, v)
}
}
if len(newLookupList) > 0 {
self.lookupdHTTPAddrs = newLookupList
}
self.mtx.Unlock()
select {
case self.lookupdRecheckChan <- 1:
self.log(LogLevelInfo, "trigger tend for err: %v", err)
default:
}
return
}
} else {
for _, node := range lookupdList.LookupdNodes {
addr := net.JoinHostPort(node.NodeIp, node.HttpPort)
self.ConnectToNSQLookupd(addr)
}
}
allTopicParts := make([]AddrPartInfo, 0)
hasErr := false