-
Notifications
You must be signed in to change notification settings - Fork 106
/
channel.go
2335 lines (2128 loc) · 66.6 KB
/
channel.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 nsqd
import (
"errors"
"fmt"
"math"
"path"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/youzan/nsq/internal/protocol"
simpleJson "github.com/bitly/go-simplejson"
"github.com/youzan/nsq/internal/ext"
"github.com/youzan/nsq/internal/levellogger"
"github.com/youzan/nsq/internal/quantile"
)
const (
resetReaderTimeoutSec = 10
MaxMemReqTimes = 10
MaxWaitingDelayed = 100
MaxDepthReqToEnd = 1000000
ZanTestSkip = 0
ZanTestUnskip = 1
)
var (
ErrMsgNotInFlight = errors.New("Message ID not in flight")
ErrMsgDeferredTooMuch = errors.New("Too much deferred messages in flight")
ErrMsgAlreadyInFlight = errors.New("Message ID already in flight")
ErrConsumeDisabled = errors.New("Consume is disabled currently")
ErrMsgDeferred = errors.New("Message is deferred")
ErrSetConsumeOffsetNotFirstClient = errors.New("consume offset can only be changed by the first consume client")
ErrNotDiskQueueReader = errors.New("the consume channel is not disk queue reader")
)
type Consumer interface {
SkipZanTest()
UnskipZanTest()
UnPause()
Pause()
TimedOutMessage()
RequeuedMessage()
FinishedMessage()
Stats() ClientStats
Exit()
Empty()
String() string
GetID() int64
}
type resetChannelData struct {
Offset BackendOffset
Cnt int64
ClearConfirmed bool
}
type MsgChanData struct {
MsgChan chan *Message
ClientCnt int64
}
type delayedMessage struct {
msg Message
deliveryTs time.Time
}
// Channel represents the concrete type for a NSQ channel (and also
// implements the Queue interface)
//
// There can be multiple channels per topic, each with there own unique set
// of subscribers (clients).
//
// Channels maintain all client and message metadata, orchestrating in-flight
// messages, timeouts, requeuing, etc.
type Channel struct {
// 64bit atomic vars need to be first for proper alignment on 32bit platforms
requeueCount uint64
timeoutCount uint64
deferredCount int64
deferredFromDelay int64
sync.RWMutex
topicName string
topicPart int
name string
nsqdNotify INsqdNotify
option *Options
backend BackendQueueReader
requeuedMsgChan chan *Message
waitingRequeueChanMsgs map[MessageID]*Message
waitingRequeueMsgs map[MessageID]*Message
tagMsgChansMutex sync.RWMutex
//mapping from tag to messages chan
tagMsgChans map[string]*MsgChanData
tagChanInitChan chan string
tagChanRemovedChan chan string
clientMsgChan chan *Message
exitChan chan int
exitSyncChan chan bool
exitFlag int32
exitMutex sync.RWMutex
// state tracking
clients map[int64]Consumer
paused int32
skipped int32
zanTestSkip int32
ephemeral bool
deleteCallback func(*Channel)
deleter sync.Once
moreDataCallback func(*Channel)
// Stats tracking
e2eProcessingLatencyStream *quantile.Quantile
inFlightMessages map[MessageID]*Message
inFlightPQ inFlightPqueue
inFlightMutex sync.Mutex
confirmedMsgs *IntervalSkipList
confirmMutex sync.Mutex
waitingConfirm int32
tryReadBackend chan bool
readerChanged chan resetChannelData
endUpdatedChan chan bool
needNotifyRead int32
consumeDisabled int32
// stat counters
EnableTrace int32
EnableSlowTrace int32
Ext int32
requireOrder int32
// 1 - reset
// 2 - reset and clear confirmed
needResetReader int32
processResetReaderTime int64
waitingProcessMsgTs int64
waitingDeliveryState int32
delayedLock sync.RWMutex
delayedQueue *DelayQueue
delayedConfirmedMsgs map[MessageID]Message
peekedMsgs []Message
//channel msg stats
channelStatsInfo *ChannelStatsInfo
}
// NewChannel creates a new instance of the Channel type and returns a pointer
func NewChannel(topicName string, part int, channelName string, chEnd BackendQueueEnd, opt *Options,
deleteCallback func(*Channel), moreDataCallback func(*Channel), consumeDisabled int32,
notify INsqdNotify, ext int32, queueStart BackendQueueEnd) *Channel {
c := &Channel{
topicName: topicName,
topicPart: part,
name: channelName,
requeuedMsgChan: make(chan *Message, opt.MaxRdyCount+1),
waitingRequeueChanMsgs: make(map[MessageID]*Message, 100),
waitingRequeueMsgs: make(map[MessageID]*Message, 100),
clientMsgChan: make(chan *Message),
tagMsgChans: make(map[string]*MsgChanData),
tagChanInitChan: make(chan string, 2),
tagChanRemovedChan: make(chan string, 2),
exitChan: make(chan int),
exitSyncChan: make(chan bool),
clients: make(map[int64]Consumer),
confirmedMsgs: NewIntervalSkipList(),
tryReadBackend: make(chan bool, 1),
readerChanged: make(chan resetChannelData, 10),
endUpdatedChan: make(chan bool, 1),
deleteCallback: deleteCallback,
moreDataCallback: moreDataCallback,
option: opt,
nsqdNotify: notify,
consumeDisabled: consumeDisabled,
delayedConfirmedMsgs: make(map[MessageID]Message, MaxWaitingDelayed),
peekedMsgs: make([]Message, MaxWaitingDelayed),
Ext: ext,
}
if len(opt.E2EProcessingLatencyPercentiles) > 0 {
c.e2eProcessingLatencyStream = quantile.New(
opt.E2EProcessingLatencyWindowTime,
opt.E2EProcessingLatencyPercentiles,
)
}
// channel no need sync so much.
syncEvery := opt.SyncEvery * 1000
if syncEvery < 1 {
syncEvery = 1
}
//initialize channel stats
c.channelStatsInfo = &ChannelStatsInfo{}
c.initPQ()
if protocol.IsEphemeral(channelName) {
c.ephemeral = true
}
// backend names, for uniqueness, automatically include the topic...
backendReaderName := getBackendReaderName(c.topicName, c.topicPart, channelName)
backendName := getBackendName(c.topicName, c.topicPart)
c.backend = newDiskQueueReader(backendName, backendReaderName,
path.Join(opt.DataPath, c.topicName),
opt.MaxBytesPerFile,
int32(minValidMsgLength),
int32(opt.MaxMsgSize)+minValidMsgLength,
syncEvery,
opt.SyncTimeout,
chEnd,
false)
if queueStart != nil {
// The old closed channel (on slave) may have the invalid read start if the
// topic disk data is cleaned already. So we check here for new opened channel
c.checkAndFixStart(queueStart)
}
go c.messagePump()
c.nsqdNotify.NotifyStateChanged(c, true)
return c
}
func (c *Channel) GetName() string {
return c.name
}
func (c *Channel) GetTopicName() string {
return c.topicName
}
func (c *Channel) GetTopicPart() int {
return c.topicPart
}
func (c *Channel) checkAndFixStart(start BackendQueueEnd) {
if c.GetConfirmed().Offset() >= start.Offset() {
return
}
nsqLog.Infof("%v-%v confirm start need be fixed %v, %v", c.GetTopicName(), c.GetName(),
start, c.GetConfirmed())
newStart, err := c.backend.SkipReadToOffset(start.Offset(), start.TotalMsgCnt())
if err != nil {
nsqLog.Warningf("%v-%v skip to new start failed: %v", c.GetTopicName(), c.GetName(),
err)
newStart, err = c.backend.SkipReadToEnd()
if err != nil {
nsqLog.Warningf("%v-%v skip to new start failed: %v", c.GetTopicName(), c.GetName(),
err)
} else {
nsqLog.Infof("%v-%v skip to end : %v", c.GetTopicName(), c.GetName(),
newStart)
}
}
}
func (c *Channel) closeClientMsgChannels() {
c.tagMsgChansMutex.Lock()
defer c.tagMsgChansMutex.Unlock()
for tag := range c.tagMsgChans {
delete(c.tagMsgChans, tag)
}
}
func (c *Channel) RemoveTagClientMsgChannel(tag string) {
c.tagMsgChansMutex.Lock()
defer c.tagMsgChansMutex.Unlock()
tagCh, ok := c.tagMsgChans[tag]
if !ok {
return
}
cnt := tagCh.ClientCnt
if cnt-1 > int64(0) {
tagCh.ClientCnt = cnt - 1
} else {
tagCh.ClientCnt = 0
delete(c.tagMsgChans, tag)
select {
case c.tagChanRemovedChan <- tag:
default:
select {
case c.tagChanRemovedChan <- tag:
case <-time.After(time.Millisecond):
nsqLog.Infof("%v-%v timeout sending tag channel remove signal for %v", c.GetTopicName(), c.GetName(), tag)
}
}
}
}
//get or create tag message chanel, invoked from protocol_v2.messagePump()
func (c *Channel) GetOrCreateClientMsgChannel(tag string) chan *Message {
c.tagMsgChansMutex.Lock()
defer c.tagMsgChansMutex.Unlock()
tagMsgChanData, exist := c.tagMsgChans[tag]
if exist {
tagMsgChanData.ClientCnt = tagMsgChanData.ClientCnt + 1
} else {
//initialize tag channel
c.tagMsgChans[string(tag)] = &MsgChanData{
make(chan *Message),
1,
}
select {
case c.tagChanInitChan <- tag:
case <-time.After(time.Millisecond):
nsqLog.Infof("%v-%v timeout sending tag channel init signal for %v", c.GetTopicName(), c.GetName(), tag)
}
}
return c.tagMsgChans[tag].MsgChan
}
func (c *Channel) GetClientMsgChan() chan *Message {
return c.clientMsgChan
}
/**
get active tag channel or default message channel from tag channel map
*/
func (c *Channel) GetClientTagMsgChan(tag string) (chan *Message, bool) {
c.tagMsgChansMutex.RLock()
defer c.tagMsgChansMutex.RUnlock()
msgChanData, exist := c.tagMsgChans[tag]
if !exist {
nsqLog.Debugf("channel %v for tag %v not found.", c.GetName(), tag)
return nil, false
}
return msgChanData.MsgChan, true
}
func (c *Channel) isNeedParseMsgExt() bool {
c.tagMsgChansMutex.RLock()
tagChLen := len(c.tagMsgChans)
c.tagMsgChansMutex.RUnlock()
if tagChLen > 0 {
return true
}
// TODO: if the channel need filter, we need parse ext
return false
}
func (c *Channel) IsSlowTraced() bool {
return atomic.LoadInt32(&c.EnableSlowTrace) == 1
}
func (c *Channel) IsTraced() bool {
return atomic.LoadInt32(&c.EnableTrace) == 1
}
func (c *Channel) IsEphemeral() bool {
return c.ephemeral
}
func (c *Channel) SetDelayedQueue(dq *DelayQueue) {
c.delayedLock.Lock()
c.delayedQueue = dq
c.delayedLock.Unlock()
}
func (c *Channel) GetDelayedQueue() *DelayQueue {
c.delayedLock.RLock()
dq := c.delayedQueue
c.delayedLock.RUnlock()
return dq
}
func (c *Channel) SetExt(isExt bool) {
if isExt {
atomic.StoreInt32(&c.Ext, 1)
} else {
atomic.StoreInt32(&c.Ext, 0)
}
}
func (c *Channel) IsExt() bool {
return atomic.LoadInt32(&c.Ext) == 1
}
func (c *Channel) SetSlowTrace(enable bool) {
if enable {
atomic.StoreInt32(&c.EnableSlowTrace, 1)
} else {
atomic.StoreInt32(&c.EnableSlowTrace, 0)
}
}
func (c *Channel) SetTrace(enable bool) {
if enable {
atomic.StoreInt32(&c.EnableTrace, 1)
} else {
atomic.StoreInt32(&c.EnableTrace, 0)
}
}
func (c *Channel) SetConsumeOffset(offset BackendOffset, cnt int64, force bool) error {
c.Lock()
defer c.Unlock()
num := len(c.clients)
if num > 1 && !force {
return ErrSetConsumeOffsetNotFirstClient
}
if c.IsConsumeDisabled() {
return ErrConsumeDisabled
}
_, ok := c.backend.(*diskQueueReader)
if ok {
select {
case c.readerChanged <- resetChannelData{offset, cnt, true}:
default:
nsqLog.Logf("ignored the reader reset: %v:%v", offset, cnt)
if offset > 0 && cnt > 0 {
select {
case c.readerChanged <- resetChannelData{offset, cnt, true}:
case <-time.After(time.Millisecond * 10):
nsqLog.Logf("ignored the reader reset finally: %v:%v", offset, cnt)
}
}
}
} else {
return ErrNotDiskQueueReader
}
return nil
}
func (c *Channel) SetOrdered(enable bool) {
if enable {
if !atomic.CompareAndSwapInt32(&c.requireOrder, 0, 1) {
return
}
select {
case c.readerChanged <- resetChannelData{BackendOffset(-1), 0, true}:
default:
}
} else {
if c.GetClientsCount() == 0 {
atomic.StoreInt32(&c.requireOrder, 0)
select {
case c.tryReadBackend <- true:
default:
}
} else {
nsqLog.Logf("can not set ordered to false while the channel is still consuming by client")
}
}
}
func (c *Channel) IsOrdered() bool {
return atomic.LoadInt32(&c.requireOrder) == 1
}
func (c *Channel) initPQ() {
pqSize := int(math.Max(1, float64(c.option.MemQueueSize)/10))
c.inFlightMutex.Lock()
for _, m := range c.inFlightMessages {
if m.belongedConsumer != nil {
m.belongedConsumer.Empty()
}
}
c.inFlightMessages = make(map[MessageID]*Message, pqSize)
c.inFlightPQ = newInFlightPqueue(pqSize)
atomic.StoreInt64(&c.deferredCount, 0)
c.inFlightMutex.Unlock()
}
// Exiting returns a boolean indicating if this channel is closed/exiting
func (c *Channel) Exiting() bool {
return atomic.LoadInt32(&c.exitFlag) == 1
}
// Delete empties the channel and closes
func (c *Channel) Delete() error {
return c.exit(true)
}
// Close cleanly closes the Channel
func (c *Channel) Close() error {
return c.exit(false)
}
// waiting more data may include :
// waiting more disk read
// waiting in memory inflight
// waiting in delayed inflight
// waiting requeued
func (c *Channel) IsWaitingMoreDiskData() bool {
if c.IsPaused() || c.IsConsumeDisabled() || c.IsSkipped() {
return false
}
d, ok := c.backend.(*diskQueueReader)
if ok {
return d.isReadToEnd()
}
return false
}
// waiting more data is indicated all msgs are consumed
// if some delayed message in channel, waiting more data is not true
func (c *Channel) IsWaitingMoreData() bool {
if c.IsPaused() || c.IsConsumeDisabled() || c.IsSkipped() {
return false
}
d, ok := c.backend.(*diskQueueReader)
if ok {
return d.IsWaitingMoreData()
}
return false
}
func (c *Channel) exit(deleted bool) error {
c.exitMutex.Lock()
defer c.exitMutex.Unlock()
if !atomic.CompareAndSwapInt32(&c.exitFlag, 0, 1) {
return ErrExiting
}
if deleted {
nsqLog.Logf("CHANNEL(%s): deleting", c.name)
// since we are explicitly deleting a channel (not just at system exit time)
// de-register this from the lookupd
c.nsqdNotify.NotifyStateChanged(c, true)
} else {
nsqLog.Logf("CHANNEL(%s): closing", c.name)
}
// this forceably closes clients, client will be removed by client before the
// client read loop exit.
c.RLock()
for _, client := range c.clients {
client.Exit()
}
c.RUnlock()
close(c.exitChan)
<-c.exitSyncChan
// write anything leftover to disk
c.flush()
if deleted {
// empty the queue (deletes the backend files, too)
if c.GetDelayedQueue() != nil {
c.GetDelayedQueue().EmptyDelayedChannel(c.GetName())
}
c.skipChannelToEnd()
return c.backend.Delete()
}
return c.backend.Close()
}
func (c *Channel) skipChannelToEnd() (BackendQueueEnd, error) {
c.Lock()
defer c.Unlock()
e, err := c.backend.SkipReadToEnd()
if err != nil {
nsqLog.Warningf("failed to reset reader to end %v", err)
} else {
c.drainChannelWaiting(true, nil, nil)
}
return e, nil
}
func (c *Channel) flush() error {
if c.ephemeral {
return nil
}
d, ok := c.backend.(*diskQueueReader)
if ok {
d.Flush()
}
return nil
}
func (c *Channel) Depth() int64 {
return c.backend.Depth()
}
func (c *Channel) DepthSize() int64 {
if d, ok := c.backend.(*diskQueueReader); ok {
return d.DepthSize()
}
return 0
}
func (c *Channel) DepthTimestamp() int64 {
return atomic.LoadInt64(&c.waitingProcessMsgTs)
}
func (c *Channel) IsZanTestSkipped() bool {
return c.IsExt() && c.option.AllowZanTestSkip && atomic.LoadInt32(&c.zanTestSkip) == ZanTestSkip
}
func (c *Channel) SkipZanTest() error {
return c.doSkipZanTest(true)
}
func (c *Channel) UnskipZanTest() error {
return c.doSkipZanTest(false)
}
func (c *Channel) doSkipZanTest(skipped bool) error {
if skipped {
atomic.StoreInt32(&c.zanTestSkip, ZanTestSkip)
//
} else {
atomic.StoreInt32(&c.zanTestSkip, ZanTestUnskip)
}
c.RLock()
for _, client := range c.clients {
if skipped {
client.SkipZanTest()
} else {
client.UnskipZanTest()
}
}
c.RUnlock()
return nil
}
func (c *Channel) Pause() error {
return c.doPause(true)
}
func (c *Channel) UnPause() error {
return c.doPause(false)
}
func (c *Channel) doPause(pause bool) error {
if pause {
atomic.StoreInt32(&c.paused, 1)
} else {
atomic.StoreInt32(&c.paused, 0)
}
c.RLock()
for _, client := range c.clients {
if pause {
client.Pause()
} else {
client.UnPause()
}
}
c.RUnlock()
return nil
}
func (c *Channel) IsPaused() bool {
return atomic.LoadInt32(&c.paused) == 1
}
func (c *Channel) Skip() error {
return c.doSkip(true)
}
func (c *Channel) UnSkip() error {
return c.doSkip(false)
}
func (c *Channel) IsSkipped() bool {
return atomic.LoadInt32(&c.skipped) == 1
}
func (c *Channel) doSkip(skipped bool) error {
if skipped {
atomic.StoreInt32(&c.skipped, 1)
if c.GetDelayedQueue() != nil {
c.GetDelayedQueue().EmptyDelayedChannel(c.GetName())
}
} else {
atomic.StoreInt32(&c.skipped, 0)
}
return nil
}
// When topic message is put, update the new end of the queue
func (c *Channel) UpdateQueueEnd(end BackendQueueEnd, forceReload bool) error {
if end == nil {
return nil
}
changed, err := c.backend.UpdateQueueEnd(end, forceReload)
if !changed || err != nil {
return err
}
if c.IsConsumeDisabled() {
} else {
select {
case c.endUpdatedChan <- true:
default:
}
}
return err
}
// TouchMessage resets the timeout for an in-flight message
func (c *Channel) TouchMessage(clientID int64, id MessageID, clientMsgTimeout time.Duration) error {
c.inFlightMutex.Lock()
msg, ok := c.inFlightMessages[id]
if !ok {
c.inFlightMutex.Unlock()
nsqLog.Logf("failed while touch: %v, msg not exist", id)
return ErrMsgNotInFlight
}
if msg.GetClientID() != clientID {
c.inFlightMutex.Unlock()
return fmt.Errorf("client does not own message : %v vs %v",
msg.GetClientID(), clientID)
}
newTimeout := time.Now().Add(clientMsgTimeout)
if newTimeout.Sub(msg.deliveryTS) >=
c.option.MaxMsgTimeout {
// we would have gone over, set to the max
newTimeout = msg.deliveryTS.Add(c.option.MaxMsgTimeout)
}
msg.pri = newTimeout.UnixNano()
if msg.index != -1 {
c.inFlightPQ.Remove(msg.index)
}
c.inFlightPQ.Push(msg)
c.inFlightMutex.Unlock()
return nil
}
func (c *Channel) ConfirmBackendQueueOnSlave(offset BackendOffset, cnt int64, allowBackward bool) error {
if cnt == 0 && offset != 0 {
nsqLog.LogWarningf("channel (%v) the count is not valid: %v:%v. (This may happen while upgrade from old)", c.GetName(), offset, cnt)
return nil
}
// confirm on slave may exceed the current end, because the buffered write
// may need to be flushed on slave.
c.confirmMutex.Lock()
defer c.confirmMutex.Unlock()
var err error
var newConfirmed BackendQueueEnd
if offset < c.GetConfirmed().Offset() {
if nsqLog.Level() > levellogger.LOG_DEBUG {
nsqLog.LogDebugf("confirm offset less than current: %v, %v", offset, c.GetConfirmed())
}
if allowBackward {
d, ok := c.backend.(*diskQueueReader)
if ok {
newConfirmed, err = d.ResetReadToOffset(offset, cnt)
nsqLog.LogDebugf("channel (%v) reset to backward: %v", c.GetName(), newConfirmed)
}
}
} else {
if allowBackward {
d, ok := c.backend.(*diskQueueReader)
if ok {
newConfirmed, err = d.ResetReadToOffset(offset, cnt)
nsqLog.LogDebugf("channel (%v) reset to backward: %v", c.GetName(), newConfirmed)
}
} else {
_, err = c.backend.SkipReadToOffset(offset, cnt)
c.confirmedMsgs.DeleteLower(int64(offset))
atomic.StoreInt32(&c.waitingConfirm, int32(c.confirmedMsgs.Len()))
}
}
if err != nil {
if err != ErrExiting {
nsqLog.Logf("confirm read failed: %v, offset: %v", err, offset)
}
}
return err
}
// if a message confirmed without goto inflight first, then we
// should clean the waiting state from requeue
func (c *Channel) CleanWaitingRequeueChan(msg *Message) {
c.inFlightMutex.Lock()
if _, ok := c.waitingRequeueChanMsgs[msg.ID]; ok {
c.waitingRequeueChanMsgs[msg.ID] = nil
delete(c.waitingRequeueChanMsgs, msg.ID)
}
c.inFlightMutex.Unlock()
}
func (c *Channel) ConfirmDelayedMessage(msg *Message) (BackendOffset, int64, bool) {
c.confirmMutex.Lock()
defer c.confirmMutex.Unlock()
needNotify := false
curConfirm := c.GetConfirmed()
if msg.DelayedOrigID > 0 && msg.DelayedType == ChannelDelayed && c.GetDelayedQueue() != nil {
c.GetDelayedQueue().ConfirmedMessage(msg)
c.delayedConfirmedMsgs[msg.ID] = *msg
if atomic.AddInt64(&c.deferredFromDelay, -1) <= 0 {
c.nsqdNotify.NotifyScanDelayed(c)
needNotify = true
}
}
return curConfirm.Offset(), curConfirm.TotalMsgCnt(), needNotify
}
// in order not to make the confirm map too large,
// we need handle this case: a old message is not confirmed,
// and we keep all the newer confirmed messages so we can confirm later.
// indicated weather the confirmed offset is changed
func (c *Channel) ConfirmBackendQueue(msg *Message) (BackendOffset, int64, bool) {
c.confirmMutex.Lock()
defer c.confirmMutex.Unlock()
curConfirm := c.GetConfirmed()
if msg.DelayedType == ChannelDelayed {
nsqLog.Logf("should not confirm delayed here: %v", msg)
return curConfirm.Offset(), curConfirm.TotalMsgCnt(), false
}
if msg.Offset < curConfirm.Offset() {
nsqLog.LogDebugf("confirmed msg is less than current confirmed offset: %v-%v, %v", msg.ID, msg.Offset, curConfirm)
return curConfirm.Offset(), curConfirm.TotalMsgCnt(), false
}
//c.confirmedMsgs[int64(msg.offset)] = msg
mergedInterval := c.confirmedMsgs.AddOrMerge(&queueInterval{start: int64(msg.Offset),
end: int64(msg.Offset) + int64(msg.RawMoveSize),
endCnt: uint64(msg.queueCntIndex),
})
reduced := false
newConfirmed := curConfirm.Offset()
confirmedCnt := curConfirm.TotalMsgCnt()
if mergedInterval.End() <= int64(newConfirmed) {
c.confirmedMsgs.DeleteLower(int64(newConfirmed))
} else if mergedInterval.Start() <= int64(newConfirmed) {
newConfirmed = BackendOffset(mergedInterval.End())
confirmedCnt = int64(mergedInterval.EndCnt())
reduced = true
} else {
}
//atomic.StoreInt32(&c.waitingConfirm, int32(len(c.confirmedMsgs)))
atomic.StoreInt32(&c.waitingConfirm, int32(c.confirmedMsgs.Len()))
if reduced {
err := c.backend.ConfirmRead(newConfirmed, confirmedCnt)
if err != nil {
if err != ErrExiting {
nsqLog.LogWarningf("channel (%v): confirm read failed: %v, msg: %v", c.GetName(), err, msg)
// rollback removed confirmed messages
//for _, m := range c.tmpRemovedConfirmed {
// c.confirmedMsgs[int64(msg.offset)] = m
//}
//atomic.StoreInt32(&c.waitingConfirm, int32(len(c.confirmedMsgs)))
}
return curConfirm.Offset(), curConfirm.TotalMsgCnt(), reduced
} else {
if nsqLog.Level() >= levellogger.LOG_DETAIL {
nsqLog.Debugf("channel %v merge msg %v( %v) to interval %v, confirmed to %v", c.GetName(),
msg.Offset, msg.queueCntIndex, mergedInterval, newConfirmed)
}
c.confirmedMsgs.DeleteLower(int64(newConfirmed))
atomic.StoreInt32(&c.waitingConfirm, int32(c.confirmedMsgs.Len()))
}
if int64(c.confirmedMsgs.Len()) < c.option.MaxConfirmWin/2 &&
atomic.LoadInt32(&c.needNotifyRead) == 1 &&
!c.IsOrdered() {
select {
case c.tryReadBackend <- true:
default:
}
}
}
if nsqLog.Level() >= levellogger.LOG_DEBUG && int64(c.confirmedMsgs.Len()) > c.option.MaxConfirmWin {
curConfirm = c.GetConfirmed()
flightCnt := len(c.inFlightMessages)
if flightCnt == 0 {
nsqLog.LogDebugf("lots of confirmed messages : %v, %v, %v",
c.confirmedMsgs.Len(), curConfirm, flightCnt)
}
}
return newConfirmed, confirmedCnt, reduced
// TODO: if some messages lost while re-queue, it may happen that some messages not
// in inflight queue and also not wait confirm. In this way, we need reset
// backend queue to force read the data from disk again.
}
func (c *Channel) ShouldWaitDelayed(msg *Message) bool {
if c.IsOrdered() {
return false
}
// while there are some waiting confirmed messages and some disk delayed messages, if we
// switched leader, we reset the read offset to the oldest confirmed. This will cause lots of
// messages read from normal disk queue but these messages should be delayed.
dq := c.GetDelayedQueue()
if msg.DelayedOrigID > 0 && msg.DelayedType == ChannelDelayed && dq != nil {
return false
}
// check if this is in delayed queue
// (it may happen while the reader is reset to the confirmed for leader changed or other event trigger)
if dq != nil {
if dq.IsChannelMessageDelayed(msg.ID, c.GetName()) {
if msg.TraceID != 0 || c.IsTraced() || nsqLog.Level() >= levellogger.LOG_DEBUG {
nsqLog.LogDebugf("non-delayed msg %v should be delayed since in delayed queue", msg)
nsqMsgTracer.TraceSub(c.GetTopicName(), c.GetName(), "IGNORE_DELAY_CONFIRMED", msg.TraceID, msg, "", 0)
}
return true
}
}
return false
}
func (c *Channel) IsConfirmed(msg *Message) bool {
if msg.DelayedOrigID > 0 && msg.DelayedType == ChannelDelayed && c.GetDelayedQueue() != nil {
return false
}
c.confirmMutex.Lock()
ok := c.confirmedMsgs.IsCompleteOverlap(&queueInterval{start: int64(msg.Offset),
end: int64(msg.Offset) + int64(msg.RawMoveSize),
endCnt: uint64(msg.queueCntIndex)})
c.confirmMutex.Unlock()
if ok {
if msg.TraceID != 0 || c.IsTraced() || nsqLog.Level() >= levellogger.LOG_DEBUG {
nsqLog.LogDebugf("msg %v is already confirmed", msg)
nsqMsgTracer.TraceSub(c.GetTopicName(), c.GetName(), "IGNORE_CONFIRMED", msg.TraceID, msg, "", 0)
}
}
return ok
}
func (c *Channel) FinishMessage(clientID int64, clientAddr string,
id MessageID) (BackendOffset, int64, bool, *Message, error) {
return c.internalFinishMessage(clientID, clientAddr, id, false)
}
func (c *Channel) FinishMessageForce(clientID int64, clientAddr string,
id MessageID, forceFin bool) (BackendOffset, int64, bool, *Message, error) {
if forceFin {
nsqLog.Logf("topic %v channel %v force finish msg %v", c.GetTopicName(), c.GetName(), id)
}
return c.internalFinishMessage(clientID, clientAddr, id, forceFin)
}
// FinishMessage successfully discards an in-flight message
func (c *Channel) internalFinishMessage(clientID int64, clientAddr string,
id MessageID, forceFin bool) (BackendOffset, int64, bool, *Message, error) {
c.inFlightMutex.Lock()
defer c.inFlightMutex.Unlock()
if forceFin {
oldMsg, ok := c.inFlightMessages[id]
if ok {
clientID = oldMsg.GetClientID()
}
}
msg, err := c.popInFlightMessage(clientID, id, true)
if err != nil {
nsqLog.LogDebugf("channel (%v): message %v fin error: %v from client %v", c.GetName(), id, err,
clientID)
return 0, 0, false, nil, err
}
now := time.Now()
ackCost := now.UnixNano() - msg.deliveryTS.UnixNano()
isOldDeferred := msg.IsDeferred()
if msg.TraceID != 0 || c.IsTraced() || nsqLog.Level() >= levellogger.LOG_DETAIL {
// if fin by no client address, means fin by internal delayed queue or by http api
if clientAddr != "" {
nsqMsgTracer.TraceSub(c.GetTopicName(), c.GetName(), "FIN", msg.TraceID, msg, clientAddr, ackCost)
} else {
nsqMsgTracer.TraceSub(c.GetTopicName(), c.GetName(), "FIN_INTERNAL", msg.TraceID, msg, clientAddr, ackCost)
}
}
if c.e2eProcessingLatencyStream != nil {
c.e2eProcessingLatencyStream.Insert(msg.Timestamp)
}
expectTimeout := msg.pri - msg.deliveryTS.UnixNano()
if ackCost >= time.Second.Nanoseconds() &&
(c.IsTraced() || msg.TraceID != 0 || c.IsSlowTraced() ||
ackCost >= expectTimeout/10 || nsqLog.Level() >= levellogger.LOG_DEBUG) {
if clientAddr != "" {
nsqMsgTracer.TraceSub(c.GetTopicName(), c.GetName(), "SLOW_ACK", msg.TraceID, msg, clientAddr, ackCost)
}
}
c.channelStatsInfo.UpdateDelivery2ACKStats(ackCost / int64(time.Millisecond))
c.channelStatsInfo.UpdateChannelStats((now.UnixNano() - msg.Timestamp) / int64(time.Millisecond))
var offset BackendOffset
var cnt int64
var changed bool
// confirm should be no error, since the inflight has been poped
if msg.DelayedType == ChannelDelayed {
offset, cnt, changed = c.ConfirmDelayedMessage(msg)
} else {
offset, cnt, changed = c.ConfirmBackendQueue(msg)
}