-
Notifications
You must be signed in to change notification settings - Fork 285
/
sqlstore.go
2315 lines (2159 loc) · 67.8 KB
/
sqlstore.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
// Copyright 2017-2019 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package stores
import (
"database/sql"
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nats-io/nats-streaming-server/logger"
"github.com/nats-io/nats-streaming-server/spb"
"github.com/nats-io/nats-streaming-server/util"
"github.com/nats-io/nuid"
"github.com/nats-io/stan.go/pb"
)
const (
driverMySQL = "mysql"
driverPostgres = "postgres"
)
const (
sqlDBLockSelect = iota
sqlDBLockInsert
sqlDBLockUpdate
sqlHasServerInfoRow
sqlUpdateServerInfo
sqlAddServerInfo
sqlAddClient
sqlDeleteClient
sqlAddChannel
sqlStoreMsg
sqlLookupMsg
sqlGetSequenceFromTimestamp
sqlUpdateChannelMaxSeq
sqlGetExpiredMessages
sqlGetFirstMsgTimestamp
sqlDeletedMsgsWithSeqLowerThan
sqlGetSizeOfMessage
sqlDeleteMessage
sqlCheckMaxSubs
sqlCreateSub
sqlUpdateSub
sqlMarkSubscriptionAsDeleted
sqlDeleteSubscription
sqlDeleteSubMarkedAsDeleted
sqlDeleteSubPendingMessages
sqlSubUpdateLastSent
sqlSubAddPending
sqlSubAddPendingRow
sqlSubDeletePending
sqlSubDeletePendingRow
sqlRecoverServerInfo
sqlRecoverClients
sqlRecoverMaxChannelID
sqlRecoverMaxSubID
sqlRecoverChannelsList
sqlRecoverChannelMsgs
sqlRecoverChannelSubs
sqlRecoverDoPurgeSubsPending
sqlRecoverSubPending
sqlRecoverGetChannelLimits
sqlRecoverDoExpireMsgs
sqlRecoverGetMessagesCount
sqlRecoverGetSeqFloorForMaxMsgs
sqlRecoverGetChannelTotalSize
sqlRecoverGetSeqFloorForMaxBytes
sqlRecoverUpdateChannelLimits
sqlDeleteChannelFast
sqlDeleteChannelGetSubIds
sqlDeleteChannelDelSubsPending
sqlDeleteChannelDelSubscriptions
sqlDeleteChannelGetSomeMessagesSeq
sqlDeleteChannelDelSomeMessages
sqlDeleteChannelDelChannel
sqlGetLastSeq
)
var sqlStmts = []string{
"SELECT id, tick from StoreLock FOR UPDATE", // sqlDBLockSelect
"INSERT INTO StoreLock (id, tick) VALUES (?, ?)", // sqlDBLockInsert
"UPDATE StoreLock SET id=?, tick=?", // sqlDBLockUpdate
"SELECT COUNT(uniquerow) FROM ServerInfo", // sqlHasServerInfoRow
"UPDATE ServerInfo SET id=?, proto=?, version=? WHERE uniquerow=1", // sqlUpdateServerInfo
"INSERT INTO ServerInfo (id, proto, version) VALUES (?, ?, ?)", // sqlAddServerInfo
"INSERT INTO Clients (id, hbinbox, proto) VALUES (?, ?, ?)", // sqlAddClient
"DELETE FROM Clients WHERE id=?", // sqlDeleteClient
"INSERT INTO Channels (id, name, maxmsgs, maxbytes, maxage) VALUES (?, ?, ?, ?, ?)", // sqlAddChannel
"INSERT INTO Messages VALUES (?, ?, ?, ?, ?)", // sqlStoreMsg
"SELECT timestamp, data FROM Messages WHERE id=? AND seq=?", // sqlLookupMsg
"SELECT seq FROM Messages WHERE id=? AND timestamp>=? ORDER BY seq LIMIT 1", // sqlGetSequenceFromTimestamp
"UPDATE Channels SET maxseq=? WHERE id=?", // sqlUpdateChannelMaxSeq
"SELECT COUNT(seq), COALESCE(MAX(seq), 0), COALESCE(SUM(size), 0) FROM Messages WHERE id=? AND timestamp<=?", // sqlGetExpiredMessages
"SELECT timestamp FROM Messages WHERE id=? AND seq>=? ORDER BY seq LIMIT 1", // sqlGetFirstMsgTimestamp
"DELETE FROM Messages WHERE id=? AND seq<=?", // sqlDeletedMsgsWithSeqLowerThan
"SELECT size FROM Messages WHERE id=? AND seq=?", // sqlGetSizeOfMessage
"DELETE FROM Messages WHERE id=? AND seq=?", // sqlDeleteMessage
"SELECT COUNT(subid) FROM Subscriptions WHERE id=? AND deleted=FALSE", // sqlCheckMaxSubs
"INSERT INTO Subscriptions (id, subid, proto) VALUES (?, ?, ?)", // sqlCreateSub
"UPDATE Subscriptions SET proto=? WHERE id=? AND subid=?", // sqlUpdateSub
"UPDATE Subscriptions SET deleted=TRUE WHERE id=? AND subid=?", // sqlMarkSubscriptionAsDeleted
"DELETE FROM Subscriptions WHERE id=? AND subid=?", // sqlDeleteSubscription
"DELETE FROM Subscriptions WHERE id=? AND deleted=TRUE", // sqlDeleteSubMarkedAsDeleted
"DELETE FROM SubsPending WHERE subid=?", // sqlDeleteSubPendingMessages
"UPDATE Subscriptions SET lastsent=? WHERE id=? AND subid=?", // sqlSubUpdateLastSent
"INSERT INTO SubsPending (subid, `row`, seq) VALUES (?, ?, ?)", // sqlSubAddPending
"INSERT INTO SubsPending (subid, `row`, lastsent, pending, acks) VALUES (?, ?, ?, ?, ?)", // sqlSubAddPendingRow
"DELETE FROM SubsPending WHERE subid=? AND seq=?", // sqlSubDeletePending
"DELETE FROM SubsPending WHERE subid=? AND `row`=?", // sqlSubDeletePendingRow
"SELECT id, proto, version FROM ServerInfo WHERE uniquerow=1", // sqlRecoverServerInfo
"SELECT id, hbinbox, proto FROM Clients", // sqlRecoverClients
"SELECT COALESCE(MAX(id), 0) FROM Channels", // sqlRecoverMaxChannelID
"SELECT COALESCE(MAX(subid), 0) FROM Subscriptions", // sqlRecoverMaxSubID
"SELECT id, name, maxseq FROM Channels WHERE deleted=FALSE", // sqlRecoverChannelsList
"SELECT COUNT(seq), COALESCE(MIN(seq), 0), COALESCE(MAX(seq), 0), COALESCE(SUM(size), 0), COALESCE(MAX(timestamp), 0) FROM Messages WHERE id=?", // sqlRecoverChannelMsgs
"SELECT lastsent, proto FROM Subscriptions WHERE id=? AND deleted=FALSE", // sqlRecoverChannelSubs
"DELETE FROM SubsPending WHERE subid=? AND (seq > 0 AND seq<?)", // sqlRecoverDoPurgeSubsPending
"SELECT `row`, seq, lastsent, pending, acks FROM SubsPending WHERE subid=?", // sqlRecoverSubPending
"SELECT maxmsgs, maxbytes, maxage FROM Channels WHERE id=?", // sqlRecoverGetChannelLimits
"DELETE FROM Messages WHERE id=? AND timestamp<=?", // sqlRecoverDoExpireMsgs
"SELECT COUNT(seq) FROM Messages WHERE id=?", // sqlRecoverGetMessagesCount
"SELECT MIN(t.seq) FROM (SELECT seq FROM Messages WHERE id=? ORDER BY seq DESC LIMIT ?)t", // sqlRecoverGetSeqFloorForMaxMsgs
"SELECT COALESCE(SUM(size), 0) FROM Messages WHERE id=?", // sqlRecoverGetChannelTotalSize
"SELECT COALESCE(MIN(seq), 0) FROM (SELECT seq, @sum:=@sum+size AS total FROM Messages JOIN (SELECT @sum:=0)m WHERE id=? ORDER BY seq DESC)t WHERE t.total<=?", // sqlRecoverGetSeqFloorForMaxBytes
"UPDATE Channels SET maxmsgs=?, maxbytes=?, maxage=? WHERE id=?", // sqlRecoverUpdateChannelLimits
"UPDATE Channels SET deleted=true WHERE id=?", // sqlDeleteChannelFast
"SELECT DISTINCT(SubsPending.subid) FROM SubsPending INNER JOIN Subscriptions ON Subscriptions.id=? AND Subscriptions.subid=SubsPending.subid LIMIT ?", // sqlDeleteChannelGetSubIds
"DELETE FROM SubsPending WHERE subid=?", // sqlDeleteChannelDelSubsPending
"DELETE FROM Subscriptions WHERE id=?", // sqlDeleteChannelDelSubscriptions
"SELECT COALESCE(MAX(seq), 0) FROM (SELECT seq FROM Messages WHERE id=? ORDER BY seq LIMIT ?) AS t1", // sqlDeleteChannelGetSomeMessagesSeq
"DELETE FROM Messages WHERE id=? AND seq<=?", // sqlDeleteChannelDelSomeMessages
"DELETE FROM Channels WHERE id=?", // sqlDeleteChannelDelChannel
"SELECT COALESCE(MAX(seq), 0) FROM Messages WHERE id=?", // sqlGetLastSeq
}
var initSQLStmts = sync.Once{}
const (
// This is to detect changes in the tables, etc...
sqlVersion = 1
// If any of the SQL queries fail when finding out messages that
// need to be expired, use this as the default retry interval
sqlDefaultExpirationIntervalOnError = time.Second
// Interval at which time is captured.
sqlDefaultTimeTickInterval = time.Second
// Max number of elements in the pending or acks column in SubsPending table
// after which a flush is forced.
sqlDefaultMaxPendingAcks = 2000
// The SubStore flusher timer is created once and reset to this
// duration to indicate that it is idle.
sqlDefaultSubStoreFlushIdleInterval = time.Hour
// This is the default interval after which the SubStore will be
// flushed when a subspending row need updating
sqlDefaultSubStoreFlushInterval = time.Second
// This is the default interval at which the lock table is updated
// when GetExclusiveLock() has returned that the lock is acquired.
sqlDefaultLockUpdateInterval = time.Second
// Number of missed update interval after which the lock is assumed
// lost and another instance can update it.
sqlDefaultLockLostCount = 3
// Limit of number of messages in the cache before message store
// is automatically flushed on a Store() call.
sqlDefaultMsgCacheLimit = 1024
// If bulk insert limit is set, the server will still insert messages
// using tx if the limit is below this threshold.
sqlMinBulkInsertLimit = 5
)
// These are initialized based on the constants that have reasonable values.
// But for tests, it is often interesting to be able to lower values to
// make tests finish faster.
var (
sqlExpirationIntervalOnError = sqlDefaultExpirationIntervalOnError
sqlTimeTickInterval = sqlDefaultTimeTickInterval
sqlMaxPendingAcks = sqlDefaultMaxPendingAcks
sqlSubStoreFlushIdleInterval = sqlDefaultSubStoreFlushIdleInterval
sqlSubStoreFlushInterval = sqlDefaultSubStoreFlushInterval
sqlLockUpdateInterval = sqlDefaultLockUpdateInterval
sqlLockLostCount = sqlDefaultLockLostCount
sqlNoPanic = false // Used in tests to avoid go-routine to panic
sqlMsgCacheLimit = sqlDefaultMsgCacheLimit
)
// SQLStoreOptions are used to configure the SQL Store.
type SQLStoreOptions struct {
Driver string
Source string
// By default, MsgStore.Store(), SubStore.AddSeqPending() and
// SubStore.AckSeqPending() are storing the actions in memory, and
// actual SQL statements are executed only when MsgStore.Flush()
// and SubStore.Flush() are called.
// If this option is set to `true`, each call to aforementioned
// APIs will cause execution of their respective SQL statements.
NoCaching bool
// If this is non 0, and NoCaching is not enabled, the server will perform
// bulk insert of messages. This is the limit of values added to the SQL statement
// "INSERT INTO Messages (..) VALUES (..)[,(..)*]".
BulkInsertLimit int
// Maximum number of open connections to the database.
// If <= 0, then there is no limit on the number of open connections.
// The default is 0 (unlimited).
MaxOpenConns int
}
// DefaultSQLStoreOptions returns default store options for an SQL Store
func DefaultSQLStoreOptions() *SQLStoreOptions {
return &SQLStoreOptions{
NoCaching: false,
MaxOpenConns: 0,
}
}
// SQLStoreOption is a function on the options for a SQL Store
type SQLStoreOption func(*SQLStoreOptions) error
// SQLNoCaching sets the NoCaching option
func SQLNoCaching(noCaching bool) SQLStoreOption {
return func(o *SQLStoreOptions) error {
o.NoCaching = noCaching
return nil
}
}
// SQLBulkInsertLimit sets the BulkInsertLimit option
func SQLBulkInsertLimit(limit int) SQLStoreOption {
return func(o *SQLStoreOptions) error {
o.BulkInsertLimit = limit
return nil
}
}
// SQLMaxOpenConns sets the MaxOpenConns option
func SQLMaxOpenConns(max int) SQLStoreOption {
return func(o *SQLStoreOptions) error {
o.MaxOpenConns = max
return nil
}
}
// SQLAllOptions is a convenient option to pass all options from a SQLStoreOptions
// structure to the constructor.
func SQLAllOptions(opts *SQLStoreOptions) SQLStoreOption {
return func(o *SQLStoreOptions) error {
o.NoCaching = opts.NoCaching
o.MaxOpenConns = opts.MaxOpenConns
o.BulkInsertLimit = opts.BulkInsertLimit
return nil
}
}
// SQLStore is a factory for message and subscription stores backed by
// a SQL Database.
type SQLStore struct {
// These are used with atomic operations and need to be 64-bit aligned.
// Position them at the beginning of the structure.
maxSubID uint64
nowInNano int64
genericStore
dbLock *sqlDBLock
opts *SQLStoreOptions
db *sql.DB
maxChannelID int64
doneCh chan struct{}
wg sync.WaitGroup
preparedStmts []*sql.Stmt
ssFlusher *subStoresFlusher
postgres bool
bulkInserts []string
}
type sqlDBLock struct {
sync.Mutex
db *sql.DB
id string
isOwner bool
}
type subStoresFlusher struct {
sync.Mutex
stores map[*SQLSubStore]struct{}
signalCh chan struct{}
signaled bool
}
// SQLSubStore is a subscription store backed by an SQL Database
type SQLSubStore struct {
commonStore
maxSubID *uint64 // Points to the uint64 stored in SQLStore and is used with atomic operations
channelID int64
sqlStore *SQLStore // Reference to "parent" store
limits SubStoreLimits
hasMarkedAsDel bool
subLastSent map[uint64]uint64
curRow uint64
cache *sqlSubAcksPendingCache
}
type sqlSubAcksPendingCache struct {
subs map[uint64]*sqlSubAcksPending // Key is subscription ID.
needsFlush bool
}
type sqlSubAcksPending struct {
lastSent uint64
prevLastSent uint64
msgToRow map[uint64]*sqlSubsPendingRow
ackToRow map[uint64]*sqlSubsPendingRow
msgs map[uint64]struct{}
acks map[uint64]struct{}
}
type sqlSubsPendingRow struct {
ID uint64
msgs map[uint64]struct{}
msgsRefs int
acksRefs int
}
// SQLMsgStore is a per channel message store backed by an SQL Database
type SQLMsgStore struct {
genericMsgStore
channelID int64
sqlStore *SQLStore // Reference to "parent" store
expireTimer *time.Timer
fTimestamp int64
wg sync.WaitGroup
// If option NoBuffering is false, uses this cache for storing Store()
// commands until caller calls Flush() in which case we use transaction
// to execute all pending store commands.
// The cache is also used in Lookup since messages may not be yet in the
// database.
writeCache *sqlMsgsCache
}
type sqlMsgsCache struct {
msgs map[uint64]*sqlCachedMsg
head *sqlCachedMsg
tail *sqlCachedMsg
free *sqlCachedMsg
count int
}
type sqlCachedMsg struct {
msg *pb.MsgProto
data []byte
next *sqlCachedMsg
}
// sqlStmtError returns an error including the text of the offending SQL statement.
func sqlStmtError(code int, err error) error {
return fmt.Errorf("sql: error executing %q: %v", sqlStmts[code], err)
}
var sqlSeqMapPool = &sync.Pool{
New: func() interface{} {
return make(map[uint64]struct{})
},
}
var sqlSeqArrayPool = &sync.Pool{
New: func() interface{} {
// This is to silence megacheck that says that sync.Pool should
// only be used with pointers.
a := make([]uint64, 0, 1024)
return &a
},
}
////////////////////////////////////////////////////////////////////////////
// SQLStore methods
////////////////////////////////////////////////////////////////////////////
// NewSQLStore returns a factory for stores held in memory.
// If not limits are provided, the store will be created with
// DefaultStoreLimits.
func NewSQLStore(log logger.Logger, driver, source string, limits *StoreLimits, options ...SQLStoreOption) (*SQLStore, error) {
initSQLStmts.Do(func() { initSQLStmtsTable(driver) })
realDriver := driver
if driver == driverPostgres {
realDriver = "pq-deadlines"
}
db, err := sql.Open(realDriver, source)
if err != nil {
return nil, err
}
if err := db.Ping(); err != nil {
db.Close()
return nil, err
}
// Start with empty options
opts := DefaultSQLStoreOptions()
// And apply whatever is given to us as options.
for _, opt := range options {
if err := opt(opts); err != nil {
return nil, err
}
}
db.SetMaxOpenConns(opts.MaxOpenConns)
s := &SQLStore{
opts: opts,
db: db,
doneCh: make(chan struct{}),
preparedStmts: make([]*sql.Stmt, 0, len(sqlStmts)),
postgres: driver == driverPostgres,
}
if err := s.init(TypeSQL, log, limits); err != nil {
s.Close()
return nil, err
}
if s.postgres && opts.BulkInsertLimit > 0 {
limit := opts.BulkInsertLimit
s.bulkInserts = make([]string, limit)
for i := 0; i < limit; i++ {
j := i * 5
s.bulkInserts[i] = fmt.Sprintf("($%d,$%d,$%d,$%d,$%d)", j+1, j+2, j+3, j+4, j+5)
}
}
if err := s.createPreparedStmts(); err != nil {
s.Close()
return nil, err
}
s.Lock()
s.wg.Add(1)
go s.timeTick()
if !s.opts.NoCaching {
s.wg.Add(1)
s.ssFlusher = &subStoresFlusher{
stores: make(map[*SQLSubStore]struct{}),
signalCh: make(chan struct{}, 1),
}
go s.subStoresFlusher()
}
s.Unlock()
return s, nil
}
// GetExclusiveLock implements the Store interface
func (s *SQLStore) GetExclusiveLock() (bool, error) {
s.Lock()
defer s.Unlock()
if s.closed {
return false, nil
}
if s.dbLock == nil {
s.dbLock = &sqlDBLock{
id: nuid.Next(),
db: s.db,
}
}
if s.dbLock.isOwner {
return true, nil
}
hasLock, id, tick, err := s.acquireDBLock(false)
if err != nil {
return false, err
}
if !hasLock {
// We did not get the lock. Try to see if the table is updated
// after 1 interval. If so, consider the lock "healthy" and just
// return that we did not get the lock. If after a configured
// number of tries the tick for current owner is not updated,
// steal the lock.
prevID := id
prevTick := tick
for i := 0; i < sqlLockLostCount; i++ {
time.Sleep(time.Duration(1.5 * float64(sqlLockUpdateInterval)))
hasLock, id, tick, err = s.acquireDBLock(false)
// If the current lock owner is closed, the lockID is being
// cleaned from the entry in the table, which could allow the
// call above to acquired the lock even though the "steal"
// boolean is false. If we got the lock, ensure we start the
// "tick" update process.
if hasLock {
break
}
// If we got an error or ID and/or tick has changed, simply
// return that we don't have the lock.
if err != nil || id != prevID || tick != prevTick {
return false, err
}
prevTick = tick
}
if !hasLock {
// Still did not get the lock but there was no update to the
// lock table, so try to steal.
hasLock, _, _, err = s.acquireDBLock(true)
}
}
if hasLock {
// Success. Keep track that we own the lock so we can clear
// the table on clean shutdown to release the lock immediately.
s.dbLock.Lock()
s.dbLock.isOwner = true
s.wg.Add(1)
go s.updateDBLock()
s.dbLock.Unlock()
}
return hasLock, err
}
// This go-routine updates the DB store lock at regular intervals.
func (s *SQLStore) updateDBLock() {
defer s.wg.Done()
var (
ticker = time.NewTicker(sqlLockUpdateInterval)
hasLock bool
err error
failed int
)
for {
select {
case <-ticker.C:
hasLock, _, _, err = s.acquireDBLock(false)
if !hasLock || err != nil {
// If there is no error but we did not get the lock,
// something is really wrong, abort right away.
stopNow := !hasLock && err == nil
if err != nil {
failed++
s.log.Errorf("Unable to update store lock (failed=%v err=%v)", failed, err)
}
if stopNow || failed == sqlLockLostCount {
if sqlNoPanic {
s.log.Fatalf("Aborting")
return
}
panic("lost store lock, aborting")
}
} else {
failed = 0
}
case <-s.doneCh:
ticker.Stop()
return
}
}
}
// Returns if lock is acquired, the owner and tick value of the lock record.
func (s *SQLStore) acquireDBLock(steal bool) (bool, string, uint64, error) {
s.dbLock.Lock()
defer s.dbLock.Unlock()
var (
lockID string
tick uint64
hasLock bool
)
tx, err := s.dbLock.db.Begin()
if err != nil {
return false, "", 0, err
}
defer func() {
if tx != nil {
tx.Rollback()
}
}()
r := tx.QueryRow(sqlStmts[sqlDBLockSelect])
err = r.Scan(&lockID, &tick)
if err != nil && err != sql.ErrNoRows {
return false, "", 0, sqlStmtError(sqlDBLockSelect, err)
}
if err == sql.ErrNoRows || steal || lockID == "" || lockID == s.dbLock.id {
// If we are stealing, reset tick to 0 (so it will become 1 in update statement)
if steal {
tick = 0
}
stmt := sqlStmts[sqlDBLockUpdate]
if err == sql.ErrNoRows {
stmt = sqlStmts[sqlDBLockInsert]
}
if _, err := tx.Exec(stmt, s.dbLock.id, tick+1); err != nil {
return false, "", 0, sqlStmtError(sqlDBLockUpdate, err)
}
hasLock = true
}
if err := tx.Commit(); err != nil {
return false, "", 0, err
}
tx = nil
return hasLock, lockID, tick, nil
}
// Release the store lock if this store was the owner of the lock
func (s *SQLStore) releaseDBLockIfOwner() {
s.dbLock.Lock()
defer s.dbLock.Unlock()
if s.dbLock.isOwner {
s.dbLock.db.Exec(sqlStmts[sqlDBLockUpdate], "", 0)
}
}
// When a SubStore adds a pending message or an ack, it will
// notify this go-routine so that the store gets flushed after
// some time should it not be flushed explicitly.
// This go routine waits to be signaled and when that happens
// reset a timer to fire in a short period of time. It then
// go through the list of SubStore that have been registered
// as needing a flush and call Flush() on them.
func (s *SQLStore) subStoresFlusher() {
defer s.wg.Done()
s.Lock()
flusher := s.ssFlusher
s.Unlock()
var (
stores []*SQLSubStore
tm = time.NewTimer(sqlSubStoreFlushIdleInterval)
)
for {
select {
case <-s.doneCh:
return
case <-flusher.signalCh:
if !tm.Stop() {
<-tm.C
}
tm.Reset(sqlSubStoreFlushInterval)
case <-tm.C:
flusher.Lock()
for ss := range flusher.stores {
stores = append(stores, ss)
delete(flusher.stores, ss)
}
flusher.signaled = false
flusher.Unlock()
for _, ss := range stores {
ss.Flush()
}
stores = stores[:0]
tm.Reset(sqlSubStoreFlushIdleInterval)
}
}
}
// Add this store to the list of SubStore needing flushing
// and signal the go-routine responsible for flushing if
// need be.
func (s *SQLStore) scheduleSubStoreFlush(ss *SQLSubStore) {
needSignal := false
f := s.ssFlusher
f.Lock()
f.stores[ss] = struct{}{}
if !f.signaled {
f.signaled = true
needSignal = true
}
f.Unlock()
if needSignal {
select {
case f.signalCh <- struct{}{}:
default:
}
}
}
// creates an instance of a SQLMsgStore
func (s *SQLStore) newSQLMsgStore(channel string, channelID int64, limits *MsgStoreLimits) *SQLMsgStore {
msgStore := &SQLMsgStore{
sqlStore: s,
channelID: channelID,
}
msgStore.init(channel, s.log, limits)
if !s.opts.NoCaching {
msgStore.writeCache = &sqlMsgsCache{msgs: make(map[uint64]*sqlCachedMsg)}
}
return msgStore
}
// creates an instance of SQLSubStore
func (s *SQLStore) newSQLSubStore(channelID int64, limits *SubStoreLimits) *SQLSubStore {
subStore := &SQLSubStore{
sqlStore: s,
channelID: channelID,
maxSubID: &s.maxSubID,
limits: *limits,
}
subStore.log = s.log
if s.opts.NoCaching {
subStore.subLastSent = make(map[uint64]uint64)
} else {
subStore.cache = &sqlSubAcksPendingCache{
subs: make(map[uint64]*sqlSubAcksPending),
}
}
return subStore
}
func (s *SQLStore) createPreparedStmts() error {
s.preparedStmts = []*sql.Stmt{}
for _, stmt := range sqlStmts {
ps, err := s.db.Prepare(stmt)
if err != nil {
return fmt.Errorf("unable to prepare statement %q: %v", stmt, err)
}
s.preparedStmts = append(s.preparedStmts, ps)
}
return nil
}
// initialize the global sqlStmts table to driver's one.
func initSQLStmtsTable(driver string) {
// The sqlStmts table is initialized with MySQL statements.
// Update the statements for the selected driver.
if driver == driverPostgres {
// Replace ? with $1, $2, etc...
for i, stmt := range sqlStmts {
n := 0
for strings.IndexByte(stmt, '?') != -1 {
n++
param := "$" + strconv.Itoa(n)
stmt = strings.Replace(stmt, "?", param, 1)
}
sqlStmts[i] = stmt
}
// Replace `row` with row
for i, stmt := range sqlStmts {
stmt := strings.Replace(stmt, "`row`", "row", -1)
sqlStmts[i] = stmt
}
// OVER (PARTITION ...) is not supported in older MySQL servers.
// So the default SQL statement is specific to MySQL and uses variables.
// For Postgres, replace with this statement:
sqlStmts[sqlRecoverGetSeqFloorForMaxBytes] = "SELECT COALESCE(MIN(seq), 0) FROM (SELECT seq, SUM(size) OVER (PARTITION BY id ORDER BY seq DESC) AS total FROM Messages WHERE id=$1)t WHERE t.total<=$2"
}
}
// Init implements the Store interface
func (s *SQLStore) Init(info *spb.ServerInfo) error {
s.Lock()
defer s.Unlock()
count := 0
r := s.db.QueryRow(sqlStmts[sqlHasServerInfoRow])
if err := r.Scan(&count); err != nil && err != sql.ErrNoRows {
return sqlStmtError(sqlHasServerInfoRow, err)
}
infoBytes, _ := info.Marshal()
if count == 0 {
if _, err := s.db.Exec(sqlStmts[sqlAddServerInfo], info.ClusterID, infoBytes, sqlVersion); err != nil {
return sqlStmtError(sqlAddServerInfo, err)
}
} else {
if _, err := s.db.Exec(sqlStmts[sqlUpdateServerInfo], info.ClusterID, infoBytes, sqlVersion); err != nil {
return sqlStmtError(sqlUpdateServerInfo, err)
}
}
return nil
}
// Recover implements the Store interface
func (s *SQLStore) Recover() (*RecoveredState, error) {
s.Lock()
defer s.Unlock()
var (
clusterID string
data []byte
version int
err error
)
r := s.db.QueryRow(sqlStmts[sqlRecoverServerInfo])
if err := r.Scan(&clusterID, &data, &version); err != nil {
// If there is no row, that means nothing to recover. Return nil for the
// state and no error.
if err == sql.ErrNoRows {
// If there are channels, we should return an error.
var maxChannelID int64
r := s.db.QueryRow(sqlStmts[sqlRecoverMaxChannelID])
r.Scan(&maxChannelID)
if maxChannelID > 0 {
return nil, ErrNoSrvButChannels
}
return nil, nil
}
return nil, sqlStmtError(sqlRecoverServerInfo, err)
}
if version != sqlVersion {
return nil, fmt.Errorf("sql: unsupported version: %v (supports [1..%v])", version, sqlVersion)
}
info := &spb.ServerInfo{}
if err := info.Unmarshal(data); err != nil {
return nil, err
}
if info.ClusterID != clusterID {
return nil, fmt.Errorf("sql: id %q in column does not match cluster ID in data %q", clusterID, info.ClusterID)
}
// Create recovered state structure and fill it with server info.
rs := &RecoveredState{
Info: info,
}
var clients []*Client
cliRows, err := s.db.Query(sqlStmts[sqlRecoverClients])
if err != nil && err != sql.ErrNoRows {
return nil, sqlStmtError(sqlRecoverClients, err)
}
defer cliRows.Close()
for cliRows.Next() {
var (
clientID string
hbInbox string
proto []byte
)
if err := cliRows.Scan(&clientID, &hbInbox, &proto); err != nil {
return nil, err
}
var client *Client
if len(proto) == 0 {
client = &Client{spb.ClientInfo{ID: clientID, HbInbox: hbInbox}}
} else {
info := spb.ClientInfo{}
info.Unmarshal(proto)
client = &Client{info}
}
clients = append(clients, client)
}
cliRows.Close()
// Set clients into recovered state.
rs.Clients = clients
// Get the maxChannelID
r = s.db.QueryRow(sqlStmts[sqlRecoverMaxChannelID])
err = r.Scan(&s.maxChannelID)
if err != nil && err != sql.ErrNoRows {
return nil, sqlStmtError(sqlRecoverMaxChannelID, err)
}
// If there was no channel recovered, we are done
if s.maxChannelID == 0 {
return rs, nil
}
// Get the maxSubID
r = s.db.QueryRow(sqlStmts[sqlRecoverMaxSubID])
if err := r.Scan(&s.maxSubID); err != nil && err != sql.ErrNoRows {
return nil, sqlStmtError(sqlRecoverMaxSubID, err)
}
// Recover individual channels
var channels map[string]*RecoveredChannel
channelRows, err := s.db.Query(sqlStmts[sqlRecoverChannelsList])
if err != nil && err != sql.ErrNoRows {
return nil, sqlStmtError(sqlRecoverChannelsList, err)
}
defer channelRows.Close()
for channelRows.Next() {
var (
channelID int64
name string
maxseq uint64 // We get that from the Channels table.
mmseq uint64 // This is the max seq found in the Messages table for given channel.
)
if err := channelRows.Scan(&channelID, &name, &maxseq); err != nil {
return nil, err
}
channelLimits := s.genericStore.getChannelLimits(name)
msgStore := s.newSQLMsgStore(name, channelID, &channelLimits.MsgStoreLimits)
// We need to get the last seq from messages table before possibly expiring messages.
r = s.preparedStmts[sqlGetLastSeq].QueryRow(channelID)
if err := r.Scan(&mmseq); err != nil {
return nil, sqlStmtError(sqlGetLastSeq, err)
}
// If it is more than the one that was updated in the Channel row, then use this one.
if mmseq > maxseq {
maxseq = mmseq
}
if err := s.applyLimitsOnRecovery(msgStore); err != nil {
return nil, err
}
r = s.preparedStmts[sqlRecoverChannelMsgs].QueryRow(channelID)
var (
totalCount int
first uint64
last uint64
totalBytes uint64
lastTimestamp int64
)
if err := r.Scan(&totalCount, &first, &last, &totalBytes, &lastTimestamp); err != nil && err != sql.ErrNoRows {
return nil, sqlStmtError(sqlRecoverChannelMsgs, err)
}
msgStore.first = first
msgStore.last = last
msgStore.totalCount = totalCount
msgStore.totalBytes = totalBytes
subStore := s.newSQLSubStore(channelID, &channelLimits.SubStoreLimits)
// Prevent scheduling to flusher while we are recovering
if !s.opts.NoCaching {
// By setting this to true, we prevent scheduling since
// scheduling would occur only if needsFlush is false.
subStore.cache.needsFlush = true
}
var subscriptions []*RecoveredSubscription
subRows, err := s.preparedStmts[sqlRecoverChannelSubs].Query(channelID)
if err != nil {
return nil, sqlStmtError(sqlRecoverChannelSubs, err)
}
defer subRows.Close()
for subRows.Next() {
var (
lastSent uint64
protoBytes []byte
ap *sqlSubAcksPending
)
if err := subRows.Scan(&lastSent, &protoBytes); err != nil && err != sql.ErrNoRows {
return nil, err
}
if protoBytes != nil {
sub := &spb.SubState{}
if err := sub.Unmarshal(protoBytes); err != nil {
return nil, err
}
// We need to use the max of lastSent column or the one in the proto
if lastSent > sub.LastSent {
sub.LastSent = lastSent
}
if s.opts.NoCaching {
// We can remove entries for sequence that are below the smallest
// sequence that was found in Messages.
if _, err := s.preparedStmts[sqlRecoverDoPurgeSubsPending].Exec(sub.ID, msgStore.first); err != nil {
return nil, sqlStmtError(sqlRecoverDoPurgeSubsPending, err)
}
} else {
ap = subStore.getOrCreateAcksPending(sub.ID, 0)
}
rows, err := s.preparedStmts[sqlRecoverSubPending].Query(sub.ID)
if err != nil {
return nil, sqlStmtError(sqlRecoverSubPending, err)
}
defer rows.Close()
pendingAcks := make(PendingAcks)
var gcedRows map[uint64]struct{}
if !s.opts.NoCaching {
gcedRows = make(map[uint64]struct{})
}
for rows.Next() {
if err := subStore.recoverPendingRow(rows, sub, ap, pendingAcks, gcedRows); err != nil {
return nil, err
}
}
rows.Close()
if s.opts.NoCaching {
// Update the in-memory map tracking last sent
subStore.subLastSent[sub.ID] = sub.LastSent
} else {
// Go over garbage collected rows and delete them
for rowID := range gcedRows {
if err := subStore.deleteSubPendingRow(sub.ID, rowID); err != nil {
return nil, err
}
}
}
// Add to the recovered subscriptions
if sub.LastSent > maxseq {
maxseq = sub.LastSent
}
subscriptions = append(subscriptions, &RecoveredSubscription{Sub: sub, Pending: pendingAcks})
} else if lastSent > maxseq {
maxseq = lastSent
}
}
subRows.Close()