-
Notifications
You must be signed in to change notification settings - Fork 106
/
delay_queue.go
1612 lines (1490 loc) · 44.3 KB
/
delay_queue.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
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 (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/absolute8511/bolt"
"github.com/youzan/nsq/internal/levellogger"
)
var (
syncedOffsetKey = []byte("synced_offset")
bucketDelayedMsg = []byte("delayed_message")
bucketDelayedMsgIndex = []byte("delayed_message_index")
bucketMeta = []byte("meta")
CompactThreshold = 1024 * 1024 * 16
compactSingleAvgSize = 1024 * 32
errBucketKeyNotFound = errors.New("bucket key not found")
txMaxBatch = 5000
largeDBSize int64 = 1024 * 1024 * 1024 * 4
errDBSizeTooLarge = errors.New("db size too large")
errTooMuchRunningEmpty = errors.New("too much running empty")
)
const (
MinDelayedType = 1
ChannelDelayed = 1
PubDelayed = 2
TransactionDelayed = 3
MaxDelayedType = 4
TxMaxSize = 65536
CompactCntThreshold = 40000
maxEmptyRunning = 5
)
type RecentKeyList [][]byte
func writeDelayedMessageToBackendWithCheck(buf *bytes.Buffer, msg *Message,
checkSize int64, bq *diskQueueWriter,
isExt bool) (BackendOffset, int32, diskQueueEndInfo, error) {
buf.Reset()
wsize, err := msg.WriteDelayedTo(buf, isExt)
if err != nil {
return 0, 0, diskQueueEndInfo{}, err
}
if checkSize > 0 && checkSize != wsize+4 {
return 0, 0, diskQueueEndInfo{}, fmt.Errorf("write message size mismatch: %v vs %v", checkSize, wsize+4)
}
return bq.PutV2(buf.Bytes())
}
func IsValidDelayedMessage(m *Message) bool {
if m.DelayedType == ChannelDelayed {
return m.DelayedOrigID > 0 && len(m.DelayedChannel) > 0 && m.DelayedTs > 0
} else if m.DelayedType == PubDelayed {
return m.DelayedTs > 0
} else if m.DelayedType == TransactionDelayed {
return true
}
return false
}
func getDelayedMsgDBIndexValue(ts int64, id MessageID) []byte {
d := make([]byte, 1+8+8)
pos := 0
d[0] = byte(1)
pos++
binary.BigEndian.PutUint64(d[pos:pos+8], uint64(ts))
pos += 8
binary.BigEndian.PutUint64(d[pos:pos+8], uint64(id))
return d
}
func getDelayedMsgDBKey(dt int, ch string, ts int64, id MessageID) []byte {
msgKey := make([]byte, len(ch)+2+1+2+8+8)
binary.BigEndian.PutUint16(msgKey[:2], uint16(dt))
pos := 2
msgKey[pos] = '-'
pos++
binary.BigEndian.PutUint16(msgKey[pos:pos+2], uint16(len(ch)))
pos += 2
copy(msgKey[pos:pos+len(ch)], []byte(ch))
pos += len(ch)
binary.BigEndian.PutUint64(msgKey[pos:pos+8], uint64(ts))
pos += 8
binary.BigEndian.PutUint64(msgKey[pos:pos+8], uint64(id))
return msgKey
}
func decodeDelayedMsgDBKey(b []byte) (uint16, int64, MessageID, string, error) {
if len(b) < 2+1+2+8+8 {
return 0, 0, 0, "", errors.New("invalid buffer length")
}
dt := binary.BigEndian.Uint16(b[:2])
pos := 2
pos++
chLen := int(binary.BigEndian.Uint16(b[pos : pos+2]))
pos += 2
if len(b) < pos+chLen {
return 0, 0, 0, "", errors.New("invalid buffer length")
}
ch := b[pos : pos+chLen]
pos += chLen
ts := int64(binary.BigEndian.Uint64(b[pos : pos+8]))
pos += 8
id := int64(binary.BigEndian.Uint64(b[pos : pos+8]))
return dt, ts, MessageID(id), string(ch), nil
}
func getDelayedMsgDBIndexKey(dt int, ch string, id MessageID) []byte {
msgKey := make([]byte, len(ch)+2+1+2+8)
binary.BigEndian.PutUint16(msgKey[:2], uint16(dt))
pos := 2
msgKey[pos] = '-'
pos++
binary.BigEndian.PutUint16(msgKey[pos:pos+2], uint16(len(ch)))
pos += 2
copy(msgKey[pos:pos+len(ch)], []byte(ch))
pos += len(ch)
binary.BigEndian.PutUint64(msgKey[pos:pos+8], uint64(id))
return msgKey
}
func decodeDelayedMsgDBIndexKey(b []byte) (uint16, MessageID, string, error) {
if len(b) < 2+1+2+8 {
return 0, 0, "", errors.New("invalid buffer length")
}
dt := binary.BigEndian.Uint16(b[:2])
pos := 2
pos++
chLen := int(binary.BigEndian.Uint16(b[pos : pos+2]))
pos += 2
if len(b) < pos+chLen {
return 0, 0, "", errors.New("invalid buffer length")
}
ch := b[pos : pos+chLen]
pos += chLen
id := int64(binary.BigEndian.Uint64(b[pos : pos+8]))
return dt, MessageID(id), string(ch), nil
}
func getDelayedMsgDBPrefixKey(dt int, ch string) []byte {
msgKey := make([]byte, len(ch)+2+1+2)
binary.BigEndian.PutUint16(msgKey[:2], uint16(dt))
pos := 2
msgKey[pos] = '-'
pos++
binary.BigEndian.PutUint16(msgKey[pos:pos+2], uint16(len(ch)))
pos += 2
copy(msgKey[pos:pos+len(ch)], []byte(ch))
return msgKey
}
func deleteMsgIndex(msgData []byte, tx *bolt.Tx, isExt bool) error {
m, err := DecodeDelayedMessage(msgData, isExt)
if err != nil {
nsqLog.LogErrorf("failed to decode delayed message: %v, %v", msgData, err)
return err
}
msgIndexKey := getDelayedMsgDBIndexKey(int(m.DelayedType), m.DelayedChannel, m.DelayedOrigID)
b := tx.Bucket(bucketDelayedMsgIndex)
err = b.Delete(msgIndexKey)
if err != nil {
nsqLog.Infof("failed to delete delayed index : %v", msgIndexKey)
return err
}
return nil
}
func deleteBucketKey(dt int, ch string, ts int64, id MessageID, tx *bolt.Tx, isExt bool) error {
b := tx.Bucket(bucketDelayedMsg)
msgKey := getDelayedMsgDBKey(dt, ch, ts, id)
oldV := b.Get(msgKey)
err := b.Delete(msgKey)
if err != nil {
nsqLog.Infof("failed to delete delayed message: %v", msgKey)
return err
}
if oldV != nil {
err = deleteMsgIndex(oldV, tx, isExt)
if err != nil {
return err
}
b = tx.Bucket(bucketMeta)
cntKey := append([]byte("counter_"), getDelayedMsgDBPrefixKey(dt, ch)...)
cnt := uint64(0)
cntBytes := b.Get(cntKey)
if cntBytes != nil && len(cntBytes) == 8 {
cnt = binary.BigEndian.Uint64(cntBytes)
}
if cnt > 0 {
cnt--
cntBytes = make([]byte, 8)
binary.BigEndian.PutUint64(cntBytes[:8], cnt)
err = b.Put(cntKey, cntBytes)
if err != nil {
nsqLog.Infof("failed to update the meta count: %v, %v", cntKey, err)
return err
}
}
} else {
nsqLog.Infof("failed to get the deleting delayed message: %v", msgKey)
return errBucketKeyNotFound
}
return nil
}
type DelayQueue struct {
tname string
fullName string
partition int
backend *diskQueueWriter
dataPath string
exitFlag int32
msgIDCursor MsgIDGenerator
defaultIDSeq uint64
needFlush int32
putBuffer bytes.Buffer
kvStore *bolt.DB
EnableTrace int32
SyncEvery int64
lastSyncCnt int64
needFixData int32
isExt int32
dbLock sync.Mutex
// prevent write while compact db
compactMutex sync.Mutex
oldestChannelDelayedTs map[string]int64
oldestMutex sync.Mutex
changedTs int64
updateConsumeCnt int64
}
func NewDelayQueueForRead(topicName string, part int, dataPath string, opt *Options,
idGen MsgIDGenerator, isExt bool) (*DelayQueue, error) {
ro := &bolt.Options{
Timeout: time.Second,
ReadOnly: true,
FreelistType: bolt.FreelistMapType,
}
return newDelayQueue(topicName, part, dataPath, opt, idGen, isExt, ro)
}
func NewDelayQueue(topicName string, part int, dataPath string, opt *Options,
idGen MsgIDGenerator, isExt bool) (*DelayQueue, error) {
return newDelayQueue(topicName, part, dataPath, opt, idGen, isExt, nil)
}
func newDelayQueue(topicName string, part int, dataPath string, opt *Options,
idGen MsgIDGenerator, isExt bool, ro *bolt.Options) (*DelayQueue, error) {
dataPath = path.Join(dataPath, "delayed_queue")
readOnly := false
if ro != nil && ro.ReadOnly {
readOnly = true
}
if !readOnly {
os.MkdirAll(dataPath, 0755)
}
q := &DelayQueue{
tname: topicName,
partition: part,
putBuffer: bytes.Buffer{},
dataPath: dataPath,
msgIDCursor: idGen,
oldestChannelDelayedTs: make(map[string]int64),
}
if isExt {
q.isExt = 1
}
q.fullName = GetTopicFullName(q.tname, q.partition)
backendName := getDelayQueueBackendName(q.tname, q.partition)
// max delay message size need add the delay ts and channel name
queue, err := newDiskQueueWriter(backendName,
q.dataPath,
opt.MaxBytesPerFile,
int32(minValidMsgLength),
int32(opt.MaxMsgSize)+minValidMsgLength+8+255, 0, readOnly)
if err != nil {
nsqLog.LogErrorf("topic(%v) failed to init delayed disk queue: %v , %v ", q.fullName, err, backendName)
return nil, err
}
q.backend = queue.(*diskQueueWriter)
if ro == nil {
ro = &bolt.Options{
Timeout: time.Second,
ReadOnly: false,
FreelistType: bolt.FreelistMapType,
}
}
// since the bolt will fail to open in read mode if no db file, but leave the db file created.
// So we check here before open
dbFile := path.Join(q.dataPath, getDelayQueueDBName(q.tname, q.partition))
if readOnly {
_, err := os.Stat(dbFile)
if os.IsNotExist(err) {
return nil, err
}
}
q.kvStore, err = bolt.Open(dbFile, 0644, ro)
if err != nil {
nsqLog.LogErrorf("topic(%v) failed to init delayed db: %v , %v ", q.fullName, err, backendName)
return nil, err
}
q.kvStore.NoSync = true
if readOnly {
return q, nil
}
err = q.kvStore.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists(bucketDelayedMsg)
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists(bucketDelayedMsgIndex)
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists(bucketMeta)
return err
})
if err != nil {
nsqLog.LogErrorf("topic(%v) failed to init delayed db: %v , %v ", q.fullName, err, backendName)
if ro == nil || !ro.ReadOnly {
return nil, err
}
}
return q, nil
}
func (q *DelayQueue) CheckConsistence() error {
// Perform consistency check.
return q.getStore().View(func(tx *bolt.Tx) error {
var count int
ch := tx.Check()
done := false
for !done {
select {
case err, ok := <-ch:
if !ok {
done = true
break
}
nsqLog.LogErrorf("topic(%v) failed to check delayed db: %v ", q.fullName, err)
if err != nil && strings.Contains(err.Error(), "unreachable unfreed") {
continue
}
count++
}
}
if count > 0 {
nsqLog.LogErrorf("topic(%v) failed to check delayed db, %d errors found ", q.fullName, count)
return errors.New("boltdb file corrupt")
}
return nil
})
}
func (q *DelayQueue) Stats() string {
s := q.getStore().Stats()
d, _ := json.MarshalIndent(s, "", " ")
return string(d)
}
func (q *DelayQueue) reOpenStore() error {
var err error
ro := &bolt.Options{
Timeout: time.Second,
ReadOnly: false,
FreelistType: bolt.FreelistMapType,
}
q.kvStore, err = bolt.Open(path.Join(q.dataPath, getDelayQueueDBName(q.tname, q.partition)), 0644, ro)
if err != nil {
nsqLog.LogErrorf("topic(%v) failed to open delayed db: %v ", q.fullName, err)
return err
}
q.oldestMutex.Lock()
q.oldestChannelDelayedTs = make(map[string]int64)
q.oldestMutex.Unlock()
q.kvStore.NoSync = true
err = q.kvStore.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists(bucketDelayedMsg)
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists(bucketDelayedMsgIndex)
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists(bucketMeta)
return err
})
if err != nil {
nsqLog.LogErrorf("topic(%v) failed to init delayed db: %v", q.fullName, err)
return err
}
return nil
}
func (q *DelayQueue) getStore() *bolt.DB {
q.dbLock.Lock()
d := q.kvStore
q.dbLock.Unlock()
return d
}
func (q *DelayQueue) GetFullName() string {
return q.fullName
}
func (q *DelayQueue) GetTopicName() string {
return q.tname
}
func (q *DelayQueue) GetTopicPart() int {
return q.partition
}
func (q *DelayQueue) SetTrace(enable bool) {
if enable {
atomic.StoreInt32(&q.EnableTrace, 1)
} else {
atomic.StoreInt32(&q.EnableTrace, 0)
}
}
func (q *DelayQueue) setExt() {
atomic.StoreInt32(&q.isExt, 1)
}
func (q *DelayQueue) IsExt() bool {
return atomic.LoadInt32(&q.isExt) == 1
}
func (q *DelayQueue) nextMsgID() MessageID {
id := uint64(0)
if q.msgIDCursor != nil {
id = q.msgIDCursor.NextID()
} else {
id = atomic.AddUint64(&q.defaultIDSeq, 1)
}
return MessageID(id)
}
func (q *DelayQueue) RollbackNoLock(vend BackendOffset, diffCnt uint64) error {
old := q.backend.GetQueueWriteEnd()
nsqLog.Logf("reset the backend from %v to : %v, %v", old, vend, diffCnt)
_, err := q.backend.RollbackWriteV2(vend, diffCnt)
atomic.StoreInt32(&q.needFlush, 1)
return err
}
func (q *DelayQueue) ResetBackendEndNoLock(vend BackendOffset, totalCnt int64) error {
old := q.backend.GetQueueWriteEnd()
if old.Offset() == vend && old.TotalMsgCnt() == totalCnt {
return nil
}
nsqLog.Logf("topic %v reset the backend from %v to : %v, %v", q.GetFullName(), old, vend, totalCnt)
_, err := q.backend.ResetWriteEndV2(vend, totalCnt)
if err != nil {
nsqLog.LogErrorf("topic %v reset backend to %v error: %v", q.fullName, vend, err)
}
atomic.StoreInt32(&q.needFlush, 1)
return err
}
func (q *DelayQueue) TryFixQueueEnd(vend BackendOffset, totalCnt int64) error {
old := q.backend.GetQueueWriteEnd()
if old.Offset() == vend && old.TotalMsgCnt() == totalCnt {
return nil
}
nsqLog.Logf("topic %v try fix the backend end from %v to : %v, %v", q.GetFullName(), old, vend, totalCnt)
_, err := q.backend.TryFixWriteEnd(vend, totalCnt)
if err != nil {
nsqLog.LogErrorf("fix backend to %v error: %v", vend, err)
}
atomic.StoreInt32(&q.needFlush, 1)
return err
}
func (q *DelayQueue) ResetBackendWithQueueStartNoLock(queueStartOffset int64, queueStartCnt int64) error {
if queueStartOffset < 0 || queueStartCnt < 0 {
return errors.New("queue start should not less than 0")
}
queueStart := q.backend.GetQueueWriteEnd().(*diskQueueEndInfo)
queueStart.virtualEnd = BackendOffset(queueStartOffset)
queueStart.totalMsgCnt = queueStartCnt
nsqLog.Warningf("reset the topic %v backend with queue start: %v", q.GetFullName(), queueStart)
err := q.backend.ResetWriteWithQueueStart(queueStart)
if err != nil {
return err
}
atomic.StoreInt32(&q.needFlush, 1)
return nil
}
func (q *DelayQueue) GetDiskQueueSnapshot() *DiskQueueSnapshot {
e := q.backend.GetQueueReadEnd()
start := q.backend.GetQueueReadStart()
d := NewDiskQueueSnapshot(getDelayQueueBackendName(q.tname, q.partition), q.dataPath, e)
d.SetQueueStart(start)
return d
}
func (q *DelayQueue) IsDataNeedFix() bool {
return atomic.LoadInt32(&q.needFixData) == 1
}
func (q *DelayQueue) SetDataFixState(needFix bool) {
if needFix {
atomic.StoreInt32(&q.needFixData, 1)
} else {
atomic.StoreInt32(&q.needFixData, 0)
}
}
func (q *DelayQueue) TotalMessageCnt() uint64 {
return uint64(q.backend.GetQueueWriteEnd().TotalMsgCnt())
}
func (q *DelayQueue) TotalDataSize() int64 {
e := q.backend.GetQueueWriteEnd()
if e == nil {
return 0
}
return int64(e.Offset())
}
func (q *DelayQueue) GetDBSize() (int64, error) {
totalSize := int64(0)
err := q.getStore().View(func(tx *bolt.Tx) error {
totalSize = tx.Size()
return nil
})
return totalSize, err
}
func (q *DelayQueue) BackupKVStoreTo(w io.Writer) (int64, error) {
totalSize := int64(0)
err := q.getStore().View(func(tx *bolt.Tx) error {
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, uint64(tx.Size()))
_, err := w.Write(buf)
if err != nil {
return err
}
totalSize = tx.Size() + 8
_, err = tx.WriteTo(w)
return err
})
return totalSize, err
}
func (q *DelayQueue) ReopenWithEmpty() error {
q.compactMutex.Lock()
defer q.compactMutex.Unlock()
kvPath := path.Join(q.dataPath, getDelayQueueDBName(q.tname, q.partition))
nsqLog.Logf("topic(%v) reopen empty delayed db: %v", q.fullName, kvPath)
q.dbLock.Lock()
defer q.dbLock.Unlock()
q.kvStore.Close()
os.Remove(kvPath)
err := q.reOpenStore()
if err != nil {
nsqLog.LogErrorf("topic(%v) failed to reopen empty delayed db: %v , %v ", q.fullName, err, kvPath)
return err
}
atomic.StoreInt64(&q.changedTs, time.Now().UnixNano())
return nil
}
func (q *DelayQueue) RestoreKVStoreFrom(body io.Reader) error {
buf := make([]byte, 8)
n, err := body.Read(buf)
if err != nil {
return err
}
if n != len(buf) {
return errors.New("unexpected length for body length")
}
bodyLen := int64(binary.BigEndian.Uint64(buf))
tmpPath := path.Join(q.dataPath, getDelayQueueDBName(q.tname, q.partition)+"-tmp.restore")
err = os.Remove(tmpPath)
if err != nil {
if !os.IsNotExist(err) {
return err
}
}
f, err := os.Create(tmpPath)
if err != nil {
return err
}
_, err = io.CopyN(f, body, bodyLen)
if err != nil {
f.Close()
return err
}
err = f.Sync()
if err != nil {
f.Close()
return err
}
err = f.Close()
if err != nil {
return err
}
q.compactMutex.Lock()
defer q.compactMutex.Unlock()
kvPath := path.Join(q.dataPath, getDelayQueueDBName(q.tname, q.partition))
q.dbLock.Lock()
defer q.dbLock.Unlock()
q.kvStore.Close()
err = os.Rename(tmpPath, kvPath)
if err != nil {
return err
}
err = q.reOpenStore()
if err != nil {
nsqLog.LogErrorf("topic(%v) failed to restore delayed db: %v , %v ", q.fullName, err, kvPath)
return err
}
atomic.StoreInt64(&q.changedTs, time.Now().UnixNano())
return nil
}
func (q *DelayQueue) PutDelayMessage(m *Message) (MessageID, BackendOffset, int32, BackendQueueEnd, error) {
if atomic.LoadInt32(&q.exitFlag) == 1 {
return 0, 0, 0, nil, errors.New("exiting")
}
if m.ID > 0 {
nsqLog.Logf("should not pass id in message ")
return 0, 0, 0, nil, ErrInvalidMessageID
}
if !IsValidDelayedMessage(m) {
return 0, 0, 0, nil, errors.New("invalid delayed message")
}
id, offset, writeBytes, dend, err := q.put(m, nil, true, 0)
return id, offset, writeBytes, &dend, err
}
func (q *DelayQueue) PutRawDataOnReplica(rawData []byte, offset BackendOffset, checkSize int64, msgNum int32) (BackendQueueEnd, error) {
if atomic.LoadInt32(&q.exitFlag) == 1 {
return nil, ErrExiting
}
wend := q.backend.GetQueueWriteEnd()
if wend.Offset() != offset {
nsqLog.LogErrorf("topic %v: write offset mismatch: %v, %v", q.GetFullName(), offset, wend)
return nil, ErrWriteOffsetMismatch
}
if msgNum != 1 {
return nil, errors.New("delayed raw message number must be 1.")
}
var m Message
_, _, _, dend, err := q.put(&m, rawData, false, checkSize)
if err != nil {
q.ResetBackendEndNoLock(wend.Offset(), wend.TotalMsgCnt())
return nil, err
}
return &dend, nil
}
func (q *DelayQueue) PutMessageOnReplica(m *Message, offset BackendOffset, checkSize int64) (BackendQueueEnd, error) {
if atomic.LoadInt32(&q.exitFlag) == 1 {
return nil, ErrExiting
}
wend := q.backend.GetQueueWriteEnd()
if wend.Offset() != offset {
nsqLog.LogErrorf("topic %v: write offset mismatch: %v, %v", q.GetFullName(), offset, wend)
return nil, ErrWriteOffsetMismatch
}
if !IsValidDelayedMessage(m) {
return nil, errors.New("invalid delayed message")
}
_, _, _, dend, err := q.put(m, nil, false, checkSize)
if err != nil {
q.ResetBackendEndNoLock(wend.Offset(), wend.TotalMsgCnt())
return nil, err
}
return &dend, nil
}
func (q *DelayQueue) put(m *Message, rawData []byte, trace bool, checkSize int64) (MessageID, BackendOffset, int32, diskQueueEndInfo, error) {
var err error
var dend diskQueueEndInfo
// it may happened while the topic is upgraded to extend topic, so the message from leader will be raw.
if rawData != nil {
if len(rawData) < 4 {
return 0, 0, 0, dend, fmt.Errorf("invalid raw message data: %v", rawData)
}
m, err = DecodeDelayedMessage(rawData[4:], q.IsExt())
if err != nil {
return 0, 0, 0, dend, err
}
}
if m.ID <= 0 {
m.ID = q.nextMsgID()
}
var offset BackendOffset
var writeBytes int32
if rawData != nil {
q.putBuffer.Reset()
_, err := m.WriteDelayedTo(&q.putBuffer, q.IsExt())
if err != nil {
return 0, 0, 0, dend, err
}
offset, writeBytes, dend, err = q.backend.PutRawV2(rawData, 1)
if checkSize > 0 && checkSize != int64(writeBytes) {
return 0, 0, 0, dend, err
}
} else {
offset, writeBytes, dend, err = writeDelayedMessageToBackendWithCheck(&q.putBuffer,
m, checkSize, q.backend, q.IsExt())
}
atomic.StoreInt32(&q.needFlush, 1)
if err != nil {
nsqLog.LogErrorf(
"TOPIC(%s) : failed to write delayed message to backend - %s",
q.GetFullName(), err)
return m.ID, offset, writeBytes, dend, err
}
msgKey := getDelayedMsgDBKey(int(m.DelayedType), m.DelayedChannel, m.DelayedTs, m.ID)
wstart := time.Now()
q.compactMutex.Lock()
err = q.getStore().Update(func(tx *bolt.Tx) error {
b := tx.Bucket(bucketDelayedMsg)
oldV := b.Get(msgKey)
exists := oldV != nil
if exists && bytes.Equal(oldV, q.putBuffer.Bytes()) {
} else {
err := b.Put(msgKey, q.putBuffer.Bytes())
if err != nil {
return err
}
if oldV != nil {
err = deleteMsgIndex(oldV, tx, q.IsExt())
if err != nil {
nsqLog.Infof("failed to delete old delayed index : %v, %v", oldV, err)
return err
}
}
b = tx.Bucket(bucketDelayedMsgIndex)
newIndexKey := getDelayedMsgDBIndexKey(int(m.DelayedType), m.DelayedChannel, m.DelayedOrigID)
d := getDelayedMsgDBIndexValue(m.DelayedTs, m.DelayedOrigID)
err = b.Put(newIndexKey, d)
if err != nil {
return err
}
}
b = tx.Bucket(bucketMeta)
if !exists {
cntKey := append([]byte("counter_"), getDelayedMsgDBPrefixKey(int(m.DelayedType), m.DelayedChannel)...)
cnt := uint64(0)
cntBytes := b.Get(cntKey)
if cntBytes != nil && len(cntBytes) == 8 {
cnt = binary.BigEndian.Uint64(cntBytes)
}
cnt++
cntBytes = make([]byte, 8)
binary.BigEndian.PutUint64(cntBytes[:8], cnt)
err = b.Put(cntKey, cntBytes)
if err != nil {
return err
}
}
return b.Put(syncedOffsetKey, []byte(strconv.Itoa(int(dend.Offset()))))
})
atomic.StoreInt64(&q.changedTs, time.Now().UnixNano())
q.compactMutex.Unlock()
if err != nil {
nsqLog.LogErrorf(
"TOPIC(%s) : failed to write delayed message %v to kv store- %s",
q.GetFullName(), m, err)
return m.ID, offset, writeBytes, dend, err
}
if m.DelayedType == ChannelDelayed {
q.oldestMutex.Lock()
oldest, ok := q.oldestChannelDelayedTs[m.DelayedChannel]
if !ok || oldest == 0 || m.DelayedTs < oldest {
q.oldestChannelDelayedTs[m.DelayedChannel] = m.DelayedTs
}
q.oldestMutex.Unlock()
}
if nsqLog.Level() >= levellogger.LOG_DEBUG {
cost := time.Since(wstart)
if cost > time.Millisecond*2 {
nsqLog.Logf("write local delayed queue db cost :%v", cost)
}
}
if trace {
if m.TraceID != 0 || atomic.LoadInt32(&q.EnableTrace) == 1 || nsqLog.Level() >= levellogger.LOG_DETAIL {
nsqMsgTracer.TracePub(q.GetTopicName(), q.GetTopicPart(), "DELAY_QUEUE_PUB", m.TraceID, m, offset, dend.TotalMsgCnt())
}
}
syncEvery := atomic.LoadInt64(&q.SyncEvery)
if syncEvery == 1 ||
dend.TotalMsgCnt()-atomic.LoadInt64(&q.lastSyncCnt) >= syncEvery {
q.flush(false)
}
return m.ID, offset, writeBytes, dend, nil
}
func (q *DelayQueue) Delete() error {
return q.exit(true)
}
func (q *DelayQueue) Close() error {
return q.exit(false)
}
func (q *DelayQueue) exit(deleted bool) error {
if !atomic.CompareAndSwapInt32(&q.exitFlag, 0, 1) {
return errors.New("exiting")
}
if deleted {
q.getStore().Close()
os.RemoveAll(path.Join(q.dataPath, getDelayQueueDBName(q.tname, q.partition)))
return q.backend.Delete()
}
// write anything leftover to disk
q.flush(true)
q.getStore().Close()
return q.backend.Close()
}
func (q *DelayQueue) ForceFlush() {
q.flush(false)
}
func (q *DelayQueue) flush(fsync bool) error {
ok := atomic.CompareAndSwapInt32(&q.needFlush, 1, 0)
if !ok {
return nil
}
s := time.Now()
atomic.StoreInt64(&q.lastSyncCnt, q.backend.GetQueueWriteEnd().TotalMsgCnt())
err := q.backend.Flush(fsync)
if err != nil {
nsqLog.LogErrorf("failed flush: %v", err)
return err
}
q.getStore().Sync()
cost := time.Now().Sub(s)
if cost > slowCost {
nsqLog.Logf("topic(%s): flush cost: %v", q.GetFullName(), cost)
}
if nsqLog.Level() >= levellogger.LOG_DEBUG {
if cost > time.Millisecond*5 {
nsqLog.Logf("flush local delayed queue db cost :%v", cost)
}
}
return err
}
func (q *DelayQueue) GetChangedTs() int64 {
return atomic.LoadInt64(&q.changedTs)
}
func (q *DelayQueue) emptyDelayedUntil(dt int, peekTs int64, id MessageID, ch string, emptyAll bool) (int64, error) {
cleanedTs := int64(0)
totalCnt, err := q.GetCurrentDelayedCnt(dt, ch)
if err != nil {
nsqLog.Infof("get delayed counter error while empty %v, %v", ch, err.Error())
return cleanedTs, err
}
db := q.getStore()
prefix := getDelayedMsgDBPrefixKey(dt, ch)
if totalCnt < uint64(txMaxBatch) {
if ds, _ := q.GetDBSize(); ds > largeDBSize {
nsqLog.Infof("topic %v empty return early since exceed max size %v, %v, %v", q.GetFullName(), string(prefix), ds, totalCnt)
// we just ignore large db error
return cleanedTs, nil
}
}
q.compactMutex.Lock()
defer q.compactMutex.Unlock()
// 1. to avoid too much in batch, we should empty at most 10000 at each tx
// 2. some large db size with less data may need long time to scan the batch size, so
// we need check the scan time also (however, we can not handle the slow if the first seek is slow)
scanStart := time.Now()
batched := 0
exceedMaxBatch := false
err = db.Update(func(tx *bolt.Tx) error {
dbSize := tx.Size()
b := tx.Bucket(bucketDelayedMsg)
c := b.Cursor()
for k, _ := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, _ = c.Next() {
if batched > txMaxBatch {
exceedMaxBatch = true
nsqLog.Infof("topic %v empty return early since exceed max batch : %v, %v", q.GetFullName(), string(prefix), batched)
break
}
if dbSize > largeDBSize/4 && time.Since(scanStart) >= time.Second {
exceedMaxBatch = true
nsqLog.Infof("topic %v empty return early since exceed max time: %v, %v, %v", q.GetFullName(), string(prefix), batched, dbSize)
break
}
delayedType, delayedTs, delayedID, delayedCh, err := decodeDelayedMsgDBKey(k)
if err != nil {
nsqLog.Infof("decode key failed : %v, %v", k, err)
continue
}
if delayedType != uint16(dt) {
continue
}
if !emptyAll {
if delayedTs > peekTs {
break
}
if delayedTs == peekTs && delayedID >= id {
break
}
if delayedCh != ch {
continue
}
} else {
if ch != "" && delayedCh != ch {
continue
}
}
err = deleteBucketKey(dt, delayedCh, delayedTs, delayedID, tx, q.IsExt())
if err != nil {
if err != errBucketKeyNotFound {
nsqLog.Warningf("failed to delete : %v, %v", k, err)
return err
}
}
cleanedTs = delayedTs
batched++
}
if batched == 0 && !exceedMaxBatch && emptyAll && ch != "" {
bm := tx.Bucket(bucketMeta)
cntKey := append([]byte("counter_"), getDelayedMsgDBPrefixKey(dt, ch)...)
cnt := uint64(0)
cntBytes := bm.Get(cntKey)
if cntBytes != nil && len(cntBytes) == 8 {
cnt = binary.BigEndian.Uint64(cntBytes)
}
if cnt > 0 {
nsqLog.Warningf("topic %v empty delayed counter need fix: %v, %v", q.GetFullName(), string(prefix), cnt)
cnt = 0
cntBytes = make([]byte, 8)
binary.BigEndian.PutUint64(cntBytes[:8], cnt)
err = bm.Put(cntKey, cntBytes)
if err != nil {
nsqLog.Infof("failed to update the meta count: %v, %v", cntKey, err)
return err
}
}
}
return nil
})
if err != nil {
if err == errDBSizeTooLarge {
return cleanedTs, nil
}
return cleanedTs, err
}
if batched == 0 {
return cleanedTs, nil
}
if emptyAll || exceedMaxBatch {
nsqLog.Infof("topic %v empty delayed: %v, %v, %v", q.GetFullName(), string(prefix), batched, peekTs)
}
atomic.StoreInt64(&q.changedTs, time.Now().UnixNano())
if dt == ChannelDelayed && ch != "" {
q.oldestMutex.Lock()
q.oldestChannelDelayedTs[ch] = cleanedTs
if emptyAll && !exceedMaxBatch {