/
server.go
3722 lines (3379 loc) · 112 KB
/
server.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 2016-2017 Apcera Inc. All rights reserved.
package server
import (
"errors"
"fmt"
"net"
"net/url"
"os"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
natsdLogger "github.com/nats-io/gnatsd/logger"
"github.com/nats-io/gnatsd/server"
"github.com/nats-io/go-nats"
"github.com/nats-io/go-nats-streaming/pb"
"github.com/nats-io/nats-streaming-server/logger"
"github.com/nats-io/nats-streaming-server/spb"
"github.com/nats-io/nats-streaming-server/stores"
"github.com/nats-io/nats-streaming-server/util"
"github.com/nats-io/nuid"
)
// A single STAN server
// Server defaults.
const (
// VERSION is the current version for the NATS Streaming server.
VERSION = "0.6.0"
DefaultClusterID = "test-cluster"
DefaultDiscoverPrefix = "_STAN.discover"
DefaultPubPrefix = "_STAN.pub"
DefaultSubPrefix = "_STAN.sub"
DefaultSubClosePrefix = "_STAN.subclose"
DefaultUnSubPrefix = "_STAN.unsub"
DefaultClosePrefix = "_STAN.close"
DefaultStoreType = stores.TypeMemory
// The prefixes should not have been made public (since we do not expose ways
// to change them). Add the new ones as private.
acksSubsPoolPrefix = "_STAN.subacks"
// Prefix of subject active server is sending HBs to
ftHBPrefix = "_STAN.ft"
// DefaultHeartBeatInterval is the interval at which server sends heartbeat to a client
DefaultHeartBeatInterval = 30 * time.Second
// DefaultClientHBTimeout is how long server waits for a heartbeat response
DefaultClientHBTimeout = 10 * time.Second
// DefaultMaxFailedHeartBeats is the number of failed heartbeats before server closes
// the client connection (total= (heartbeat interval + heartbeat timeout) * (fail count + 1)
DefaultMaxFailedHeartBeats = int((5 * time.Minute) / DefaultHeartBeatInterval)
// Max number of outstanding go-routines handling connect requests for
// duplicate client IDs.
defaultMaxDupCIDRoutines = 100
// Timeout used to ping the known client when processing a connection
// request for a duplicate client ID.
defaultCheckDupCIDTimeout = 500 * time.Millisecond
// DefaultIOBatchSize is the maximum number of messages to accumulate before flushing a store.
DefaultIOBatchSize = 1024
// DefaultIOSleepTime is the duration (in micro-seconds) the server waits for more messages
// before starting processing. Set to 0 (or negative) to disable the wait.
DefaultIOSleepTime = int64(0)
// Length of the channel used to schedule subscriptions start requests.
// Subscriptions requests are processed from the same NATS subscription.
// When a subscriber starts and it has pending messages, the server
// processes the new subscription request and sends avail messages out
// (up to MaxInflight). When done in place, this can cause other
// new subscriptions requests to timeout. Server uses a channel to schedule
// start (that is sending avail messages) of new subscriptions. This is
// the default length of that channel.
defaultSubStartChanLen = 2048
// Length of the NATS Inbox prefix
natsInboxPrefixLen = len(nats.InboxPrefix)
// First character of a NATS Inbox. When using the ackSub pool,
// ackInboxes will start with a number.
natsInboxFirstChar = '_'
// Length of a NATS inbox
natsInboxLen = 29 // _INBOX.<nuid: 22 characters>
)
// Constant to indicate that sendMsgToSub() should check number of acks pending
// against MaxInFlight to know if message should be sent out.
const (
forceDelivery = true
honorMaxInFlight = false
)
// Errors.
var (
ErrInvalidSubject = errors.New("stan: invalid subject")
ErrInvalidStart = errors.New("stan: invalid start position")
ErrInvalidSub = errors.New("stan: invalid subscription")
ErrInvalidClient = errors.New("stan: clientID already registered")
ErrMissingClient = errors.New("stan: clientID missing")
ErrInvalidClientID = errors.New("stan: invalid clientID: only alphanumeric and `-` or `_` characters allowed")
ErrInvalidAckWait = errors.New("stan: invalid ack wait time, should be >= 1s")
ErrInvalidMaxInflight = errors.New("stan: invalid MaxInflight, should be >= 1")
ErrInvalidConnReq = errors.New("stan: invalid connection request")
ErrInvalidPubReq = errors.New("stan: invalid publish request")
ErrInvalidSubReq = errors.New("stan: invalid subscription request")
ErrInvalidUnsubReq = errors.New("stan: invalid unsubscribe request")
ErrInvalidCloseReq = errors.New("stan: invalid close request")
ErrDupDurable = errors.New("stan: duplicate durable registration")
ErrInvalidDurName = errors.New("stan: durable name of a durable queue subscriber can't contain the character ':'")
ErrUnknownClient = errors.New("stan: unknown clientID")
ErrNoChannel = errors.New("stan: no configured channel")
)
// Shared regular expression to check clientID validity.
// No lock required since from doc: https://golang.org/pkg/regexp/
// A Regexp is safe for concurrent use by multiple goroutines.
var clientIDRegEx *regexp.Regexp
func init() {
if re, err := regexp.Compile("^[a-zA-Z0-9_-]+$"); err != nil {
panic("Unable to compile regular expression")
} else {
clientIDRegEx = re
}
}
// ioPendingMsg is a record that embeds the pointer to the incoming
// NATS Message, the PubMsg and PubAck structures so we reduce the
// number of memory allocations to 1 when processing a message from
// producer.
type ioPendingMsg struct {
m *nats.Msg
pm pb.PubMsg
pa pb.PubAck
}
// Constant that defines the size of the channel that feeds the IO thread.
const ioChannelSize = 64 * 1024
const (
useLocking = true
dontUseLocking = false
)
const (
scheduleRequest = true
processRequest = false
)
// subStartInfo contains information used when a subscription request
// is successful and the start (sending avail messages) is scheduled.
type subStartInfo struct {
c *channel
sub *subState
qs *queueState
isDurable bool
}
// State represents the possible server states
type State int8
// Possible server states
const (
Standalone State = iota
FTActive
FTStandby
Failed
Shutdown
)
func (state State) String() string {
switch state {
case Standalone:
return "STANDALONE"
case FTActive:
return "FT_ACTIVE"
case FTStandby:
return "FT_STANDBY"
case Failed:
return "FAILED"
case Shutdown:
return "SHUTDOWN"
default:
return "UNKNOW STATE"
}
}
type channelStore struct {
sync.RWMutex
channels map[string]*channel
store stores.Store
}
func newChannelStore(s stores.Store) *channelStore {
cs := &channelStore{
channels: make(map[string]*channel),
store: s,
}
return cs
}
func (cs *channelStore) get(name string) *channel {
cs.RLock()
c := cs.channels[name]
cs.RUnlock()
return c
}
func (cs *channelStore) createChannel(s *StanServer, name string) (*channel, error) {
cs.Lock()
defer cs.Unlock()
// It is possible that there were 2 concurrent calls to lookupOrCreateChannel
// which first uses `channelStore.get()` and if not found, calls this function.
// So we need to check now that we have the write lock that the channel has
// not already been created.
c := cs.channels[name]
if c != nil {
return c, nil
}
sc, err := cs.store.CreateChannel(name)
if err != nil {
return nil, err
}
return cs.create(s, name, sc), nil
}
// low-level creation and storage in memory of a *channel
// Lock is held on entry or not needed.
func (cs *channelStore) create(s *StanServer, name string, sc *stores.Channel) *channel {
c := &channel{name: name, store: sc, ss: s.createSubStore()}
cs.channels[name] = c
return c
}
func (cs *channelStore) getAll() map[string]*channel {
cs.RLock()
m := make(map[string]*channel, len(cs.channels))
for k, v := range cs.channels {
m[k] = v
}
cs.RUnlock()
return m
}
func (cs *channelStore) msgsState(channelName string) (int, uint64, error) {
cs.RLock()
defer cs.RUnlock()
if channelName != "" {
c := cs.channels[channelName]
if c == nil {
return 0, 0, fmt.Errorf("channel %q not found", channelName)
}
return c.store.Msgs.State()
}
var (
count int
bytes uint64
)
for _, c := range cs.channels {
m, b, err := c.store.Msgs.State()
if err != nil {
return 0, 0, err
}
count += m
bytes += b
}
return count, bytes, nil
}
func (cs *channelStore) count() int {
cs.RLock()
count := len(cs.channels)
cs.RUnlock()
return count
}
type channel struct {
name string
store *stores.Channel
ss *subStore
}
// StanServer structure represents the STAN server
type StanServer struct {
// Keep all members for which we use atomic at the beginning of the
// struct and make sure they are all 64bits (or use padding if necessary).
// atomic.* functions crash on 32bit machines if operand is not aligned
// at 64bit. See https://github.com/golang/go/issues/599
ioChannelStatsMaxBatchSize int64 // stats of the max number of messages than went into a single batch
mu sync.RWMutex
shutdown bool
serverID string
info spb.ServerInfo // Contains cluster ID and subjects
natsServer *server.Server
opts *Options
startTime time.Time
// For scalability, a dedicated connection is used to publish
// messages to subscribers.
nc *nats.Conn // used for most protocol messages
ncs *nats.Conn // used for sending to subscribers and acking publishers
wg sync.WaitGroup // Wait on go routines during shutdown
// Used when processing connect requests for client ID already registered
dupCIDGuard sync.RWMutex
dupCIDMap map[string]struct{}
dupCIDwg sync.WaitGroup // To wait for one routine to end when we have reached the max.
dupCIDswg bool // To instruct one go routine to decrement the wait group.
dupCIDTimeout time.Duration
dupMaxCIDRoutines int
// Clients
clients *clientStore
// channels
channels *channelStore
// Store
store stores.Store
// Monitoring
monMu sync.RWMutex
numSubs int
// IO Channel
ioChannel chan *ioPendingMsg
ioChannelQuit chan struct{}
ioChannelWG sync.WaitGroup
// Used to fix out-of-order processing of subUnsub/subClose/connClose
// requests due to use of different NATS subscribers for various
// protocols.
closeProtosMu sync.Mutex // Mutex used for unsub/close requests.
connCloseReqs map[string]int // Key: clientID Value: ref count
tmpBuf []byte // Used to marshal protocols (right now, only PubAck)
subStartCh chan *subStartInfo
subStartQuit chan struct{}
// By default we create a subscription on AckInbox per subscription,
// but still use a single connection to receive all ACKs. So
// effectively, this means having a go-routine per subscription for
// processing of client's ACKs. The more subscriptions there are,
// the more go-routines the system will need. To curb this growth,
// there is an option to use a pool of ack subscribers.
acksSubsPoolSize int
acksSubsIndex int
acksSubs []*nats.Subscription
acksSubsPrefix string
acksSubsPrefixLen int
// For FT mode
ftnc *nats.Conn
ftSubject string
ftHBInterval time.Duration
ftHBMissedInterval time.Duration
ftHBCh chan *nats.Msg
ftQuit chan struct{}
state State
// This is in cases where a fatal error occurs after the server was
// started. We call Fatalf, but for users starting the server
// programmatically, it is a way to report what the error was.
lastError error
// Will be created only when running in partitioning mode.
partitions *partitions
// Use these flags for Debug/Trace in places where speed matters.
// Normally, Debugf and Tracef will check an internal variable to
// figure out if the statement should be logged, however, the
// cost of calling Debugf/Tracef is still significant since there
// may be memory allocations to format the string passed to these
// calls. So in those situations, use these flags to surround the
// calls to Debugf/Tracef.
trace bool
debug bool
log *logger.StanLogger
}
// subStore holds all known state for all subscriptions
type subStore struct {
sync.RWMutex
psubs []*subState // plain subscribers
qsubs map[string]*queueState // queue subscribers
durables map[string]*subState // durables lookup
acks map[string]*subState // ack inbox lookup
stan *StanServer // back link to Stan server
}
// Holds all queue subsribers for a subject/group and
// tracks lastSent for the group.
type queueState struct {
sync.RWMutex
lastSent uint64
subs []*subState
stalled bool
shadow *subState // For durable case, when last member leaves and group is not closed.
}
// When doing message redelivery due to ack expiration, the function
// makeSortedPendingMsgs return an array of pendingMsg objects,
// ordered by their expiration date.
type pendingMsg struct {
seq uint64
expire int64
}
// Holds Subscription state
type subState struct {
sync.RWMutex
spb.SubState // Embedded protobuf. Used for storage.
subject string
qstate *queueState
ackWait time.Duration // SubState.AckWaitInSecs expressed as a time.Duration
ackTimer *time.Timer
ackSub *nats.Subscription
acksPending map[uint64]int64 // key is message sequence, value is expiration time.
store stores.SubStore // for easy access to the store interface
// So far, compacting these booleans into a byte flag would not save space.
// May change if we need to add more.
initialized bool // false until the subscription response has been sent to prevent data to be sent too early.
stalled bool
newOnHold bool // Prevents delivery of new msgs until old are redelivered (on restart)
hasFailedHB bool // This is set when server sends heartbeat to this subscriber's client.
removed bool // This is true when subStore.Remove() has been invoked for this subscription.
}
// Looks up, or create a new channel if it does not exist
func (s *StanServer) lookupOrCreateChannel(name string) (*channel, error) {
c := s.channels.get(name)
if c != nil {
return c, nil
}
return s.channels.createChannel(s, name)
}
// createSubStore creates a new instance of `subStore`.
func (s *StanServer) createSubStore() *subStore {
subs := &subStore{
psubs: make([]*subState, 0, 4),
qsubs: make(map[string]*queueState),
durables: make(map[string]*subState),
acks: make(map[string]*subState),
stan: s,
}
return subs
}
// Store adds this subscription to the server's `subStore` and also in storage
func (ss *subStore) Store(sub *subState) error {
if sub == nil {
return nil
}
// `sub` has just been created and can't be referenced anywhere else in
// the code, so we don't need locking.
// Adds to storage.
err := sub.store.CreateSub(&sub.SubState)
if err != nil {
ss.stan.log.Errorf("Unable to store subscription [%v:%v] on [%s]: %v", sub.ClientID, sub.Inbox, sub.subject, err)
return err
}
ss.Lock()
ss.updateState(sub)
ss.Unlock()
return nil
}
// Updates the subStore state with this sub.
// The subStore is locked on entry (or does not need, as during server restart).
// However, `sub` does not need locking since it has just been created.
func (ss *subStore) updateState(sub *subState) {
// First store by ackInbox for ack direct lookup
ss.acks[sub.AckInbox] = sub
// Store by type
if sub.isQueueSubscriber() {
// Queue subscriber.
qs := ss.qsubs[sub.QGroup]
if qs == nil {
qs = &queueState{
subs: make([]*subState, 0, 4),
}
ss.qsubs[sub.QGroup] = qs
}
qs.Lock()
// The recovered shadow queue sub will have ClientID=="",
// keep a reference to it until a member re-joins the group.
if sub.ClientID == "" {
// There should be only one shadow queue subscriber, but
// we found in https://github.com/nats-io/nats-streaming-server/issues/322
// that some datastore had 2 of those (not sure how this happened except
// maybe due to upgrades from much older releases that had bugs?).
// So don't panic and use as the shadow the one with the highest LastSent
// value.
if qs.shadow == nil || sub.LastSent > qs.lastSent {
qs.shadow = sub
}
} else {
qs.subs = append(qs.subs, sub)
}
// Needed in the case of server restart, where
// the queue group's last sent needs to be updated
// based on the recovered subscriptions.
if sub.LastSent > qs.lastSent {
qs.lastSent = sub.LastSent
}
qs.Unlock()
sub.qstate = qs
} else {
// Plain subscriber.
ss.psubs = append(ss.psubs, sub)
}
// Hold onto durables in special lookup.
if sub.isDurableSubscriber() {
ss.durables[sub.durableKey()] = sub
}
}
// Remove a subscriber from the subscription store, leaving durable
// subscriptions unless `unsubscribe` is true.
func (ss *subStore) Remove(c *channel, sub *subState, unsubscribe bool) {
if sub == nil {
return
}
sub.Lock()
subject := sub.subject
clientID := sub.ClientID
sub.removed = true
sub.clearAckTimer()
durableKey := ""
// Do this before clearing the sub.ClientID since this is part of the key!!!
if sub.isDurableSubscriber() {
durableKey = sub.durableKey()
}
// Clear the subscriptions clientID
sub.ClientID = ""
if sub.ackSub != nil {
sub.ackSub.Unsubscribe()
sub.ackSub = nil
}
ackInbox := sub.AckInbox
qs := sub.qstate
isDurable := sub.IsDurable
subid := sub.ID
store := sub.store
qgroup := sub.QGroup
sub.Unlock()
reportError := func(err error) {
ss.stan.log.Errorf("Error deleting subscription subid=%d, subject=%s, err=%v", subid, subject, err)
}
// Delete from storage non durable subscribers on either connection
// close or call to Unsubscribe(), and durable subscribers only on
// Unsubscribe(). Leave durable queue subs for now, they need to
// be treated differently.
if !isDurable || (unsubscribe && durableKey != "") {
if err := store.DeleteSub(subid); err != nil {
reportError(err)
}
}
var (
log logger.Logger
queueGroupIsEmpty bool
)
ss.Lock()
if ss.stan.debug {
log = ss.stan.log
}
// Delete from ackInbox lookup.
delete(ss.acks, ackInbox)
// Delete from durable if needed
if unsubscribe && durableKey != "" {
delete(ss.durables, durableKey)
}
var qsubs map[uint64]*subState
// Delete ourselves from the list
if qs != nil {
storageUpdate := false
// For queue state, we need to lock specifically,
// because qs.subs can be modified by findBestQueueSub,
// for which we don't have substore lock held.
qs.Lock()
qs.subs, _ = sub.deleteFromList(qs.subs)
if len(qs.subs) == 0 {
queueGroupIsEmpty = true
// If it was the last being removed, also remove the
// queue group from the subStore map, but only if
// non durable or explicit unsubscribe.
if !isDurable || unsubscribe {
delete(ss.qsubs, qgroup)
// Delete from storage too.
if err := store.DeleteSub(subid); err != nil {
reportError(err)
}
} else {
// Group is durable and last member just left the group,
// but didn't call Unsubscribe(). Need to keep a reference
// to this sub to maintain the state.
qs.shadow = sub
// Clear the stalled flag
qs.stalled = false
// Will need to update the LastSent and clear the ClientID
// with a storage update.
storageUpdate = true
}
} else {
now := time.Now().UnixNano()
// If there are pending messages in this sub, they need to be
// transferred to remaining queue subscribers.
numQSubs := len(qs.subs)
idx := 0
sub.RLock()
// Need to update if this member was the one with the last
// message of the group.
storageUpdate = sub.LastSent == qs.lastSent
sortedPendingMsgs := makeSortedPendingMsgs(sub.acksPending)
for _, pm := range sortedPendingMsgs {
m, err := c.store.Msgs.Lookup(pm.seq)
if err != nil {
ss.stan.log.Errorf("Unable to update subscription for %s:%v (%v)", sub.subject, pm.seq, err)
continue
}
// This is possible if message has expired or removed from channel
// due to limits. No need to ack it since we are destroying this
// subscription.
if m == nil {
continue
}
// Get one of the remaning queue subscribers.
qsub := qs.subs[idx]
qsub.Lock()
// Store in storage
if err := qsub.store.AddSeqPending(qsub.ID, m.Sequence); err != nil {
ss.stan.log.Errorf("[Client:%s] Unable to transfer message to subid=%d, subject=%s, seq=%d, err=%v",
clientID, subid, subject, m.Sequence, err)
qsub.Unlock()
continue
}
// We don't need to update if the sub's lastSent is transferred
// to another queue subscriber.
if storageUpdate && m.Sequence == qs.lastSent {
storageUpdate = false
}
// Update LastSent if applicable
if m.Sequence > qsub.LastSent {
qsub.LastSent = m.Sequence
}
// As of now, members can have different AckWait values.
expirationTime := pm.expire
// If the member the message is transferred to has a higher AckWait,
// keep original expiration time, otherwise check that it is smaller
// than the new AckWait.
if sub.ackWait > qsub.ackWait && expirationTime-now > 0 {
expirationTime = now + int64(qsub.ackWait)
}
// Store in ackPending.
qsub.acksPending[m.Sequence] = expirationTime
// Keep track of this qsub
if qsubs == nil {
qsubs = make(map[uint64]*subState)
}
if _, tracked := qsubs[qsub.ID]; !tracked {
qsubs[qsub.ID] = qsub
}
qsub.Unlock()
// Move to the next queue subscriber, going back to first if needed.
idx++
if idx == numQSubs {
idx = 0
}
}
sub.RUnlock()
// Even for durable queue subscribers, if this is not the last
// member, we need to delete from storage (we did that higher in
// that function for non durable case). Issue #215.
if isDurable {
if err := store.DeleteSub(subid); err != nil {
reportError(err)
}
}
}
if storageUpdate {
// If we have a shadow sub, use that one, othewise any queue subscriber
// will do, so use the first.
qsub := qs.shadow
if qsub == nil {
qsub = qs.subs[0]
}
qsub.Lock()
qsub.LastSent = qs.lastSent
qsub.store.UpdateSub(&qsub.SubState)
qsub.Unlock()
}
qs.Unlock()
} else {
ss.psubs, _ = sub.deleteFromList(ss.psubs)
}
ss.Unlock()
// Calling this will sort current pending messages and ensure
// that the ackTimer is properly set. It does not necessarily
// mean that messages are going to be redelivered on the spot.
for _, qsub := range qsubs {
ss.stan.performAckExpirationRedelivery(qsub)
}
if log != nil {
strace := subTrace{clientID: clientID, isRemove: true, isUnsubscribe: unsubscribe, isGroupEmpty: queueGroupIsEmpty}
traceSubStartCloseOrUnsubscribe(log, sub, &strace)
}
}
// Lookup by durable name.
func (ss *subStore) LookupByDurable(durableName string) *subState {
ss.RLock()
sub := ss.durables[durableName]
ss.RUnlock()
return sub
}
// Lookup by ackInbox name.
func (ss *subStore) LookupByAckInbox(ackInbox string) *subState {
aiLen := len(ackInbox)
ss.RLock()
if aiLen != natsInboxLen {
if aiLen <= ss.stan.acksSubsPrefixLen {
ss.RUnlock()
return nil
}
// Extract the actual AckInbox
ackInbox = ackInbox[ss.stan.acksSubsPrefixLen:]
}
sub := ss.acks[ackInbox]
ss.RUnlock()
return sub
}
// Options for STAN Server
type Options struct {
ID string
DiscoverPrefix string
StoreType string
FilestoreDir string
FileStoreOpts stores.FileStoreOptions
stores.StoreLimits // Store limits (MaxChannels, etc..)
EnableLogging bool // Enables logging
CustomLogger logger.Logger // Server will start with the provided logger
Trace bool // Verbose trace
Debug bool // Debug trace
HandleSignals bool // Should the server setup a signal handler (for Ctrl+C, etc...)
Secure bool // Create a TLS enabled connection w/o server verification
ClientCert string // Client Certificate for TLS
ClientKey string // Client Key for TLS
ClientCA string // Client CAs for TLS
IOBatchSize int // Maximum number of messages collected from clients before starting their processing.
IOSleepTime int64 // Duration (in micro-seconds) the server waits for more message to fill up a batch.
NATSServerURL string // URL for external NATS Server to connect to. If empty, NATS Server is embedded.
ClientHBInterval time.Duration // Interval at which server sends heartbeat to a client.
ClientHBTimeout time.Duration // How long server waits for a heartbeat response.
ClientHBFailCount int // Number of failed heartbeats before server closes client connection.
AckSubsPoolSize int // Number of internal subscriptions handling incoming ACKs (0 means one per client's subscription).
FTGroupName string // Name of the FT Group. A group can be 2 or more servers with a single active server and all sharing the same datastore.
Partitioning bool // Specify if server only accepts messages/subscriptions on channels defined in StoreLimits.
}
// Clone returns a deep copy of the Options object.
func (o *Options) Clone() *Options {
// A simple copy covers pretty much everything
clone := *o
// But we have the problem of the PerChannel map that needs
// to be copied.
clone.PerChannel = (&o.StoreLimits).ClonePerChannelMap()
return &clone
}
// DefaultOptions are default options for the STAN server
var defaultOptions = Options{
ID: DefaultClusterID,
DiscoverPrefix: DefaultDiscoverPrefix,
StoreType: DefaultStoreType,
FileStoreOpts: stores.DefaultFileStoreOptions,
IOBatchSize: DefaultIOBatchSize,
IOSleepTime: DefaultIOSleepTime,
NATSServerURL: "",
ClientHBInterval: DefaultHeartBeatInterval,
ClientHBTimeout: DefaultClientHBTimeout,
ClientHBFailCount: DefaultMaxFailedHeartBeats,
}
// GetDefaultOptions returns default options for the STAN server
func GetDefaultOptions() (o *Options) {
opts := defaultOptions
opts.StoreLimits = stores.DefaultStoreLimits
return &opts
}
// DefaultNatsServerOptions are default options for the NATS server
var DefaultNatsServerOptions = server.Options{
Host: "localhost",
Port: 4222,
NoLog: true,
NoSigs: true,
}
func (s *StanServer) stanDisconnectedHandler(nc *nats.Conn) {
if nc.LastError() != nil {
s.log.Errorf("connection %q has been disconnected: %v",
nc.Opts.Name, nc.LastError())
}
}
func (s *StanServer) stanReconnectedHandler(nc *nats.Conn) {
s.log.Noticef("connection %q reconnected to NATS Server at %q",
nc.Opts.Name, nc.ConnectedUrl())
}
func (s *StanServer) stanClosedHandler(nc *nats.Conn) {
s.log.Debugf("connection %q has been closed", nc.Opts.Name)
}
func (s *StanServer) stanErrorHandler(nc *nats.Conn, sub *nats.Subscription, err error) {
s.log.Errorf("Asynchronous error on connection %s, subject %s: %s",
nc.Opts.Name, sub.Subject, err)
}
func (s *StanServer) buildServerURLs(sOpts *Options, opts *server.Options) ([]string, error) {
var hostport string
natsURL := sOpts.NATSServerURL
// If the URL to an external NATS is provided...
if natsURL != "" {
// If it has user/pwd info or is a list of urls...
if strings.Contains(natsURL, "@") || strings.Contains(natsURL, ",") {
// Return the array
urls := strings.Split(natsURL, ",")
for i, s := range urls {
urls[i] = strings.Trim(s, " ")
}
return urls, nil
}
// Otherwise, prepare the host and port and continue to see
// if user/pass needs to be added.
// First trim the protocol.
parts := strings.Split(natsURL, "://")
if len(parts) != 2 {
return nil, fmt.Errorf("malformed url: %v", natsURL)
}
natsURL = parts[1]
host, port, err := net.SplitHostPort(natsURL)
if err != nil {
return nil, err
}
// Use net.Join to support IPV6 addresses.
hostport = net.JoinHostPort(host, port)
} else {
// We embed the server, so it is local. If host is "any",
// use 127.0.0.1 or ::1 for host address (important for
// Windows since connect with 0.0.0.0 or :: fails).
sport := strconv.Itoa(opts.Port)
if opts.Host == "0.0.0.0" {
hostport = net.JoinHostPort("127.0.0.1", sport)
} else if opts.Host == "::" || opts.Host == "[::]" {
hostport = net.JoinHostPort("::1", sport)
} else {
hostport = net.JoinHostPort(opts.Host, sport)
}
}
var userpart string
if opts.Authorization != "" {
userpart = opts.Authorization
} else if opts.Username != "" {
userpart = fmt.Sprintf("%s:%s", opts.Username, opts.Password)
}
if userpart != "" {
return []string{fmt.Sprintf("nats://%s@%s", userpart, hostport)}, nil
}
return []string{fmt.Sprintf("nats://%s", hostport)}, nil
}
// createNatsClientConn creates a connection to the NATS server, using
// TLS if configured. Pass in the NATS server options to derive a
// connection url, and for other future items (e.g. auth)
func (s *StanServer) createNatsClientConn(name string, sOpts *Options, nOpts *server.Options) (*nats.Conn, error) {
var err error
ncOpts := nats.DefaultOptions
ncOpts.Servers, err = s.buildServerURLs(sOpts, nOpts)
if err != nil {
return nil, err
}
ncOpts.Name = fmt.Sprintf("_NSS-%s-%s", sOpts.ID, name)
if err = nats.ErrorHandler(s.stanErrorHandler)(&ncOpts); err != nil {
return nil, err
}
if err = nats.ReconnectHandler(s.stanReconnectedHandler)(&ncOpts); err != nil {
return nil, err
}
if err = nats.ClosedHandler(s.stanClosedHandler)(&ncOpts); err != nil {
return nil, err
}
if err = nats.DisconnectHandler(s.stanDisconnectedHandler)(&ncOpts); err != nil {
return nil, err
}
if sOpts.Secure {
if err = nats.Secure()(&ncOpts); err != nil {
return nil, err
}
}
if sOpts.ClientCA != "" {
if err = nats.RootCAs(sOpts.ClientCA)(&ncOpts); err != nil {
return nil, err
}
}
if sOpts.ClientCert != "" {
if err = nats.ClientCert(sOpts.ClientCert, sOpts.ClientKey)(&ncOpts); err != nil {
return nil, err
}
}
// Shorten the time we wait to try to reconnect.
// Don't make it too often because it may exhaust the number of FDs.
ncOpts.ReconnectWait = 250 * time.Millisecond
// Make it try to reconnect for ever.
ncOpts.MaxReconnect = -1
// For FT make the reconnect buffer as small as possible since
// we don't really want FT HBs to be buffered while we are disconnected
// and be sent as a burst on reconnect.
if name == "ft" {
ncOpts.ReconnectBufSize = 128
}
s.log.Tracef(" NATS conn opts: %v", ncOpts)
var nc *nats.Conn
if nc, err = ncOpts.Connect(); err != nil {
return nil, err
}
return nc, err
}
func (s *StanServer) createNatsConnections(sOpts *Options, nOpts *server.Options) error {
var err error
s.ncs, err = s.createNatsClientConn("send", sOpts, nOpts)
if err == nil {
s.nc, err = s.createNatsClientConn("general", sOpts, nOpts)
}
if err == nil && sOpts.FTGroupName != "" {
s.ftnc, err = s.createNatsClientConn("ft", sOpts, nOpts)
}
return err
}
// RunServer will startup an embedded STAN server and a nats-server to support it.
func RunServer(ID string) (*StanServer, error) {
sOpts := GetDefaultOptions()
sOpts.ID = ID
nOpts := DefaultNatsServerOptions
return RunServerWithOpts(sOpts, &nOpts)
}
// RunServerWithOpts will startup an embedded STAN server and a nats-server to support it.
func RunServerWithOpts(stanOpts *Options, natsOpts *server.Options) (newServer *StanServer, returnedError error) {
var sOpts *Options
var nOpts *server.Options
// Make a copy of the options so we own them.
if stanOpts == nil {
sOpts = GetDefaultOptions()
} else {
sOpts = stanOpts.Clone()
}
if natsOpts == nil {
no := DefaultNatsServerOptions
nOpts = &no
} else {
nOpts = natsOpts.Clone()