- Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathaccounts.go
4736 lines (4330 loc) · 133 KB
/
accounts.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 2018-2025 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 server
import (
"bytes"
"cmp"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"math"
"math/rand"
"net/http"
"net/textproto"
"reflect"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nats-io/jwt/v2"
"github.com/nats-io/nats-server/v2/internal/fastrand"
"github.com/nats-io/nkeys"
"github.com/nats-io/nuid"
)
// For backwards compatibility with NATS < 2.0, users who are not explicitly defined into an
// account will be grouped in the default global account.
constglobalAccountName=DEFAULT_GLOBAL_ACCOUNT
constdefaultMaxSubLimitReportThreshold=int64(2*time.Second)
varmaxSubLimitReportThreshold=defaultMaxSubLimitReportThreshold
// Account are subject namespace definitions. By default no messages are shared between accounts.
// You can share via Exports and Imports of Streams and Services.
typeAccountstruct {
stats
gwReplyMapping
Namestring
Nkeystring
Issuerstring
claimJWTstring
updated time.Time
mu sync.RWMutex
sqmu sync.Mutex
sl*Sublist
ic*client
sq*sendq
isiduint64
etmr*time.Timer
ctmr*time.Timer
strackmap[string]sconns
nrclientsint32
sysclientsint32
nleafsint32
nrleafsint32
clientsmap[*client]struct{}
rmmap[string]int32
lqwsmap[string]int32
usersRevokedmap[string]int64
mappings []*mapping
hasMapped atomic.Bool
lmu sync.RWMutex
lleafs []*client
leafClustersmap[string]uint64
importsimportMap
exportsexportMap
js*jsAccount
jsLimitsmap[string]JetStreamAccountLimits
nrgAccountstring
limits
expired atomic.Bool
incompletebool
signingKeysmap[string]jwt.Scope
extAuth*jwt.ExternalAuthorization
srv*Server// server this account is registered with (possibly nil)
ldsstring// loop detection subject for leaf nodes
siReply []byte// service reply prefix, will form wildcard subscription.
eventIds*nuid.NUID
eventIdsMu sync.Mutex
defaultPerms*Permissions
tags jwt.TagList
nameTagstring
lastLimErrint64
routePoolIdxint
// If the trace destination is specified and a message with a traceParentHdr
// is received, and has the least significant bit of the last token set to 1,
// then if traceDestSampling is > 0 and < 100, a random value will be selected
// and if it falls between 0 and that value, message tracing will be triggered.
traceDeststring
traceDestSamplingint
// Guarantee that only one goroutine can be running either checkJetStreamMigrate
// or clearObserverState at a given time for this account to prevent interleaving.
jscmMu sync.Mutex
}
const (
accDedicatedRoute=-1
accTransitioningToDedicatedRoute=-2
)
// Account based limits.
typelimitsstruct {
mpayint32
msubsint32
mconnsint32
mleafsint32
disallowBearerbool
}
// Used to track remote clients and leafnodes per remote server.
typesconnsstruct {
connsint32
leafsint32
}
// Import stream mapping struct
typestreamImportstruct {
acc*Account
fromstring
tostring
tr*subjectTransform
rtr*subjectTransform
claim*jwt.Import
usePubbool
invalidbool
// This is `allow_trace` and when true and message tracing is happening,
// we will trace egresses past the account boundary, if `false`, we stop
// at the account boundary.
atrcbool
}
constClientInfoHdr="Nats-Request-Info"
// Import service mapping struct
typeserviceImportstruct {
acc*Account
claim*jwt.Import
se*serviceExport
sid []byte
fromstring
tostring
tr*subjectTransform
tsint64
rtServiceRespType
latency*serviceLatency
m1*ServiceLatency
rc*client
usePubbool
responsebool
invalidbool
sharebool
trackingbool
didDeliverbool
atrcbool// allow trace (got from service export)
trackingHdr http.Header// header from request
}
// This is used to record when we create a mapping for implicit service
// imports. We use this to clean up entries that are not singletons when
// we detect that interest is no longer present. The key to the map will
// be the actual interest. We record the mapped subject and the account.
typeserviceRespEntrystruct {
acc*Account
msubstring
}
// ServiceRespType represents the types of service request response types.
typeServiceRespTypeuint8
// Service response types. Defaults to a singleton.
const (
SingletonServiceRespType=iota
Streamed
Chunked
)
// String helper.
func (rtServiceRespType) String() string {
switchrt {
caseSingleton:
return"Singleton"
caseStreamed:
return"Streamed"
caseChunked:
return"Chunked"
}
return"Unknown ServiceResType"
}
// exportAuth holds configured approvals or boolean indicating an
// auth token is required for import.
typeexportAuthstruct {
tokenReqbool
accountPosuint
approvedmap[string]*Account
actsRevokedmap[string]int64
}
// streamExport
typestreamExportstruct {
exportAuth
}
// serviceExport holds additional information for exported services.
typeserviceExportstruct {
exportAuth
acc*Account
respTypeServiceRespType
latency*serviceLatency
rtmr*time.Timer
respThresh time.Duration
// This is `allow_trace` and when true and message tracing is happening,
// when processing a service import we will go through account boundary
// and trace egresses on that other account. If `false`, we stop at the
// account boundary.
atrcbool
}
// Used to track service latency.
typeserviceLatencystruct {
samplingint8// percentage from 1-100 or 0 to indicate triggered by header
subjectstring
}
// exportMap tracks the exported streams and services.
typeexportMapstruct {
streamsmap[string]*streamExport
servicesmap[string]*serviceExport
responsesmap[string]*serviceImport
}
// importMap tracks the imported streams and services.
// For services we will also track the response mappings as well.
typeimportMapstruct {
streams []*streamImport
servicesmap[string][]*serviceImport
rrMapmap[string][]*serviceRespEntry
}
// NewAccount creates a new unlimited account with the given name.
funcNewAccount(namestring) *Account {
a:=&Account{
Name: name,
limits: limits{-1, -1, -1, -1, false},
eventIds: nuid.New(),
}
returna
}
func (a*Account) String() string {
returna.Name
}
func (a*Account) setTraceDest(deststring) {
a.mu.Lock()
a.traceDest=dest
a.mu.Unlock()
}
func (a*Account) getTraceDestAndSampling() (string, int) {
a.mu.RLock()
dest:=a.traceDest
sampling:=a.traceDestSampling
a.mu.RUnlock()
returndest, sampling
}
// Used to create shallow copies of accounts for transfer
// from opts to real accounts in server struct.
// Account `na` write lock is expected to be held on entry
// while account `a` is the one from the Options struct
// being loaded/reloaded and do not need locking.
func (a*Account) shallowCopy(na*Account) {
na.Nkey=a.Nkey
na.Issuer=a.Issuer
na.traceDest, na.traceDestSampling=a.traceDest, a.traceDestSampling
ifa.imports.streams!=nil {
na.imports.streams=make([]*streamImport, 0, len(a.imports.streams))
for_, v:=rangea.imports.streams {
si:=*v
na.imports.streams=append(na.imports.streams, &si)
}
}
ifa.imports.services!=nil {
na.imports.services=make(map[string][]*serviceImport)
fork, v:=rangea.imports.services {
sis:=make([]*serviceImport, 0, len(v))
for_, si:=rangev {
csi:=*si
sis=append(sis, &csi)
}
na.imports.services[k] =sis
}
}
ifa.exports.streams!=nil {
na.exports.streams=make(map[string]*streamExport)
fork, v:=rangea.exports.streams {
ifv!=nil {
se:=*v
na.exports.streams[k] =&se
} else {
na.exports.streams[k] =nil
}
}
}
ifa.exports.services!=nil {
na.exports.services=make(map[string]*serviceExport)
fork, v:=rangea.exports.services {
ifv!=nil {
se:=*v
na.exports.services[k] =&se
} else {
na.exports.services[k] =nil
}
}
}
na.mappings=a.mappings
na.hasMapped.Store(len(na.mappings) >0)
// JetStream
na.jsLimits=a.jsLimits
// Server config account limits.
na.limits=a.limits
}
// nextEventID uses its own lock for better concurrency.
func (a*Account) nextEventID() string {
a.eventIdsMu.Lock()
id:=a.eventIds.Next()
a.eventIdsMu.Unlock()
returnid
}
// Returns a slice of clients stored in the account, or nil if none is present.
// Lock is held on entry.
func (a*Account) getClientsLocked() []*client {
iflen(a.clients) ==0 {
returnnil
}
clients:=make([]*client, 0, len(a.clients))
forc:=rangea.clients {
clients=append(clients, c)
}
returnclients
}
// Returns a slice of clients stored in the account, or nil if none is present.
func (a*Account) getClients() []*client {
a.mu.RLock()
clients:=a.getClientsLocked()
a.mu.RUnlock()
returnclients
}
// Called to track a remote server and connections and leafnodes it
// has for this account.
func (a*Account) updateRemoteServer(m*AccountNumConns) []*client {
a.mu.Lock()
ifa.strack==nil {
a.strack=make(map[string]sconns)
}
// This does not depend on receiving all updates since each one is idempotent.
// FIXME(dlc) - We should cleanup when these both go to zero.
prev:=a.strack[m.Server.ID]
a.strack[m.Server.ID] =sconns{conns: int32(m.Conns), leafs: int32(m.LeafNodes)}
a.nrclients+=int32(m.Conns) -prev.conns
a.nrleafs+=int32(m.LeafNodes) -prev.leafs
mtce:=a.mconns!=jwt.NoLimit&& (len(a.clients)-int(a.sysclients)+int(a.nrclients) >int(a.mconns))
// If we are over here some have snuck in and we need to rebalance.
// All others will probably be doing the same thing but better to be
// conservative and bit harsh here. Clients will reconnect if we over compensate.
varclients []*client
ifmtce {
clients=a.getClientsLocked()
slices.SortFunc(clients, func(i, j*client) int { return-i.start.Compare(j.start) }) // reserve
over:= (len(a.clients) -int(a.sysclients) +int(a.nrclients)) -int(a.mconns)
ifover<len(clients) {
clients=clients[:over]
}
}
// Now check leafnodes.
mtlce:=a.mleafs!=jwt.NoLimit&& (a.nleafs+a.nrleafs>a.mleafs)
ifmtlce {
// Take ones from the end.
a.lmu.RLock()
leafs:=a.lleafs
over:=int(a.nleafs+a.nrleafs-a.mleafs)
ifover<len(leafs) {
leafs=leafs[len(leafs)-over:]
}
clients=append(clients, leafs...)
a.lmu.RUnlock()
}
a.mu.Unlock()
// If we have exceeded our max clients this will be populated.
returnclients
}
// Removes tracking for a remote server that has shutdown.
func (a*Account) removeRemoteServer(sidstring) {
a.mu.Lock()
ifa.strack!=nil {
prev:=a.strack[sid]
delete(a.strack, sid)
a.nrclients-=prev.conns
a.nrleafs-=prev.leafs
}
a.mu.Unlock()
}
// When querying for subject interest this is the number of
// expected responses. We need to actually check that the entry
// has active connections.
func (a*Account) expectedRemoteResponses() (expectedint32) {
a.mu.RLock()
for_, sc:=rangea.strack {
ifsc.conns>0||sc.leafs>0 {
expected++
}
}
a.mu.RUnlock()
return
}
// Clears eventing and tracking for this account.
func (a*Account) clearEventing() {
a.mu.Lock()
a.nrclients=0
// Now clear state
clearTimer(&a.etmr)
clearTimer(&a.ctmr)
a.clients=nil
a.strack=nil
a.mu.Unlock()
}
// GetName will return the accounts name.
func (a*Account) GetName() string {
ifa==nil {
return"n/a"
}
a.mu.RLock()
name:=a.Name
a.mu.RUnlock()
returnname
}
// getNameTag will return the name tag or the account name if not set.
func (a*Account) getNameTag() string {
ifa==nil {
return_EMPTY_
}
a.mu.RLock()
defera.mu.RUnlock()
returna.getNameTagLocked()
}
// getNameTagLocked will return the name tag or the account name if not set.
// Lock should be held.
func (a*Account) getNameTagLocked() string {
ifa==nil {
return_EMPTY_
}
nameTag:=a.nameTag
ifnameTag==_EMPTY_ {
nameTag=a.Name
}
returnnameTag
}
// NumConnections returns active number of clients for this account for
// all known servers.
func (a*Account) NumConnections() int {
a.mu.RLock()
nc:=len(a.clients) -int(a.sysclients) +int(a.nrclients)
a.mu.RUnlock()
returnnc
}
// NumRemoteConnections returns the number of client or leaf connections that
// are not on this server.
func (a*Account) NumRemoteConnections() int {
a.mu.RLock()
nc:=int(a.nrclients+a.nrleafs)
a.mu.RUnlock()
returnnc
}
// NumLocalConnections returns active number of clients for this account
// on this server.
func (a*Account) NumLocalConnections() int {
a.mu.RLock()
nlc:=a.numLocalConnections()
a.mu.RUnlock()
returnnlc
}
// Do not account for the system accounts.
func (a*Account) numLocalConnections() int {
returnlen(a.clients) -int(a.sysclients) -int(a.nleafs)
}
// This is for extended local interest.
// Lock should not be held.
func (a*Account) numLocalAndLeafConnections() int {
a.mu.RLock()
nlc:=len(a.clients) -int(a.sysclients)
a.mu.RUnlock()
returnnlc
}
func (a*Account) numLocalLeafNodes() int {
returnint(a.nleafs)
}
// MaxTotalConnectionsReached returns if we have reached our limit for number of connections.
func (a*Account) MaxTotalConnectionsReached() bool {
varmtcebool
a.mu.RLock()
ifa.mconns!=jwt.NoLimit {
mtce=len(a.clients)-int(a.sysclients)+int(a.nrclients) >=int(a.mconns)
}
a.mu.RUnlock()
returnmtce
}
// MaxActiveConnections return the set limit for the account system
// wide for total number of active connections.
func (a*Account) MaxActiveConnections() int {
a.mu.RLock()
mconns:=int(a.mconns)
a.mu.RUnlock()
returnmconns
}
// MaxTotalLeafNodesReached returns if we have reached our limit for number of leafnodes.
func (a*Account) MaxTotalLeafNodesReached() bool {
a.mu.RLock()
mtc:=a.maxTotalLeafNodesReached()
a.mu.RUnlock()
returnmtc
}
func (a*Account) maxTotalLeafNodesReached() bool {
ifa.mleafs!=jwt.NoLimit {
returna.nleafs+a.nrleafs>=a.mleafs
}
returnfalse
}
// NumLeafNodes returns the active number of local and remote
// leaf node connections.
func (a*Account) NumLeafNodes() int {
a.mu.RLock()
nln:=int(a.nleafs+a.nrleafs)
a.mu.RUnlock()
returnnln
}
// NumRemoteLeafNodes returns the active number of remote
// leaf node connections.
func (a*Account) NumRemoteLeafNodes() int {
a.mu.RLock()
nrn:=int(a.nrleafs)
a.mu.RUnlock()
returnnrn
}
// MaxActiveLeafNodes return the set limit for the account system
// wide for total number of leavenode connections.
// NOTE: these are tracked separately.
func (a*Account) MaxActiveLeafNodes() int {
a.mu.RLock()
mleafs:=int(a.mleafs)
a.mu.RUnlock()
returnmleafs
}
// RoutedSubs returns how many subjects we would send across a route when first
// connected or expressing interest. Local client subs.
func (a*Account) RoutedSubs() int {
a.mu.RLock()
defera.mu.RUnlock()
returnlen(a.rm)
}
// TotalSubs returns total number of Subscriptions for this account.
func (a*Account) TotalSubs() int {
a.mu.RLock()
defera.mu.RUnlock()
ifa.sl==nil {
return0
}
returnint(a.sl.Count())
}
func (a*Account) shouldLogMaxSubErr() bool {
ifa==nil {
returntrue
}
a.mu.RLock()
last:=a.lastLimErr
a.mu.RUnlock()
ifnow:=time.Now().UnixNano(); now-last>=maxSubLimitReportThreshold {
a.mu.Lock()
a.lastLimErr=now
a.mu.Unlock()
returntrue
}
returnfalse
}
// MapDest is for mapping published subjects for clients.
typeMapDeststruct {
Subjectstring`json:"subject"`
Weightuint8`json:"weight"`
Clusterstring`json:"cluster,omitempty"`
}
funcNewMapDest(subjectstring, weightuint8) *MapDest {
return&MapDest{subject, weight, _EMPTY_}
}
// destination is for internal representation for a weighted mapped destination.
typedestinationstruct {
tr*subjectTransform
weightuint8
}
// mapping is an internal entry for mapping subjects.
typemappingstruct {
srcstring
wcbool
dests []*destination
cdestsmap[string][]*destination
}
// AddMapping adds in a simple route mapping from src subject to dest subject
// for inbound client messages.
func (a*Account) AddMapping(src, deststring) error {
returna.AddWeightedMappings(src, NewMapDest(dest, 100))
}
// AddWeightedMappings will add in a weighted mappings for the destinations.
func (a*Account) AddWeightedMappings(srcstring, dests...*MapDest) error {
a.mu.Lock()
defera.mu.Unlock()
if!IsValidSubject(src) {
returnErrBadSubject
}
m:=&mapping{src: src, wc: subjectHasWildcard(src), dests: make([]*destination, 0, len(dests)+1)}
seen:=make(map[string]struct{})
vartw=make(map[string]uint8)
for_, d:=rangedests {
if_, ok:=seen[d.Subject]; ok {
returnfmt.Errorf("duplicate entry for %q", d.Subject)
}
seen[d.Subject] =struct{}{}
ifd.Weight>100 {
returnfmt.Errorf("individual weights need to be <= 100")
}
tw[d.Cluster] +=d.Weight
iftw[d.Cluster] >100 {
returnfmt.Errorf("total weight needs to be <= 100")
}
err:=ValidateMapping(src, d.Subject)
iferr!=nil {
returnerr
}
tr, err:=NewSubjectTransform(src, d.Subject)
iferr!=nil {
returnerr
}
ifd.Cluster==_EMPTY_ {
m.dests=append(m.dests, &destination{tr, d.Weight})
} else {
// We have a cluster scoped filter.
ifm.cdests==nil {
m.cdests=make(map[string][]*destination)
}
ad:=m.cdests[d.Cluster]
ad=append(ad, &destination{tr, d.Weight})
m.cdests[d.Cluster] =ad
}
}
processDestinations:=func(dests []*destination) ([]*destination, error) {
varltwuint8
for_, d:=rangedests {
ltw+=d.weight
}
// Auto add in original at weight difference if all entries weight does not total to 100.
// Iff the src was not already added in explicitly, meaning they want loss.
_, haveSrc:=seen[src]
ifltw!=100&&!haveSrc {
dest:=src
ifm.wc {
// We need to make the appropriate markers for the wildcards etc.
dest=transformTokenize(dest)
}
tr, err:=NewSubjectTransform(src, dest)
iferr!=nil {
returnnil, err
}
aw:=100-ltw
iflen(dests) ==0 {
aw=100
}
dests=append(dests, &destination{tr, aw})
}
slices.SortFunc(dests, func(i, j*destination) int { returncmp.Compare(i.weight, j.weight) })
varlwuint8
for_, d:=rangedests {
d.weight+=lw
lw=d.weight
}
returndests, nil
}
varerrerror
ifm.dests, err=processDestinations(m.dests); err!=nil {
returnerr
}
// Option cluster scoped destinations
forcluster, dests:=rangem.cdests {
ifdests, err=processDestinations(dests); err!=nil {
returnerr
}
m.cdests[cluster] =dests
}
// Replace an old one if it exists.
fori, em:=rangea.mappings {
ifem.src==src {
a.mappings[i] =m
returnnil
}
}
// If we did not replace add to the end.
a.mappings=append(a.mappings, m)
a.hasMapped.Store(len(a.mappings) >0)
// If we have connected leafnodes make sure to update.
ifa.nleafs>0 {
// Need to release because lock ordering is client -> account
a.mu.Unlock()
// Now grab the leaf list lock. We can hold client lock under this one.
a.lmu.RLock()
for_, lc:=rangea.lleafs {
lc.forceAddToSmap(src)
}
a.lmu.RUnlock()
a.mu.Lock()
}
returnnil
}
// RemoveMapping will remove an existing mapping.
func (a*Account) RemoveMapping(srcstring) bool {
a.mu.Lock()
defera.mu.Unlock()
fori, m:=rangea.mappings {
ifm.src==src {
// Swap last one into this spot. Its ok to change order.
a.mappings[i] =a.mappings[len(a.mappings)-1]
a.mappings[len(a.mappings)-1] =nil// gc
a.mappings=a.mappings[:len(a.mappings)-1]
a.hasMapped.Store(len(a.mappings) >0)
// If we have connected leafnodes make sure to update.
ifa.nleafs>0 {
// Need to release because lock ordering is client -> account
a.mu.Unlock()
// Now grab the leaf list lock. We can hold client lock under this one.
a.lmu.RLock()
for_, lc:=rangea.lleafs {
lc.forceRemoveFromSmap(src)
}
a.lmu.RUnlock()
a.mu.Lock()
}
returntrue
}
}
returnfalse
}
// Indicates we have mapping entries.
func (a*Account) hasMappings() bool {
ifa==nil {
returnfalse
}
returna.hasMapped.Load()
}
// This performs the logic to map to a new dest subject based on mappings.
// Should only be called from processInboundClientMsg or service import processing.
func (a*Account) selectMappedSubject(deststring) (string, bool) {
if!a.hasMappings() {
returndest, false
}
a.mu.RLock()
// In case we have to tokenize for subset matching.
tsa:= [32]string{}
tts:=tsa[:0]
varm*mapping
for_, rm:=rangea.mappings {
if!rm.wc&&rm.src==dest {
m=rm
break
} else {
// tokenize and reuse for subset matching.
iflen(tts) ==0 {
start:=0
subject:=dest
fori:=0; i<len(subject); i++ {
ifsubject[i] ==btsep {
tts=append(tts, subject[start:i])
start=i+1
}
}
tts=append(tts, subject[start:])
}
ifisSubsetMatch(tts, rm.src) {
m=rm
break
}
}
}
ifm==nil {
a.mu.RUnlock()
returndest, false
}
// The selected destination for the mapping.
vard*destination
varndeststring
dests:=m.dests
iflen(m.cdests) >0 {
cn:=a.srv.cachedClusterName()
dests=m.cdests[cn]
ifdests==nil {
// Fallback to main if we do not match the cluster.
dests=m.dests
}
}
// Optimize for single entry case.
iflen(dests) ==1&&dests[0].weight==100 {
d=dests[0]
} else {
w:=uint8(fastrand.Uint32n(100))
for_, rm:=rangedests {
ifw<rm.weight {
d=rm
break
}
}
}
ifd!=nil {
iflen(d.tr.dtokmftokindexesargs) ==0 {
ndest=d.tr.dest
} else {
ndest=d.tr.TransformTokenizedSubject(tts)
}
}
a.mu.RUnlock()
returnndest, true
}
// SubscriptionInterest returns true if this account has a matching subscription
// for the given `subject`.
func (a*Account) SubscriptionInterest(subjectstring) bool {
returna.Interest(subject) >0
}
// Interest returns the number of subscriptions for a given subject that match.
func (a*Account) Interest(subjectstring) int {
varnmsint
a.mu.RLock()
ifa.sl!=nil {
np, nq:=a.sl.NumInterest(subject)
nms=np+nq
}
a.mu.RUnlock()
returnnms
}
// addClient keeps our accounting of local active clients or leafnodes updated.
// Returns previous total.
func (a*Account) addClient(c*client) int {
a.mu.Lock()
n:=len(a.clients)
// Could come here earlier than the account is registered with the server.
// Make sure we can still track clients.
ifa.clients==nil {
a.clients=make(map[*client]struct{})
}
a.clients[c] =struct{}{}
// If we did not add it, we are done
ifn==len(a.clients) {
a.mu.Unlock()
returnn
}
ifc.kind!=CLIENT&&c.kind!=LEAF {
a.sysclients++
} elseifc.kind==LEAF {
a.nleafs++
}
a.mu.Unlock()
// If we added a new leaf use the list lock and add it to the list.
ifc.kind==LEAF {
a.lmu.Lock()
a.lleafs=append(a.lleafs, c)
a.lmu.Unlock()
}
ifc!=nil&&c.srv!=nil {
c.srv.accConnsUpdate(a)
}
returnn
}
// For registering clusters for remote leafnodes.
// We only register as the hub.
func (a*Account) registerLeafNodeCluster(clusterstring) {
a.mu.Lock()
defera.mu.Unlock()
ifa.leafClusters==nil {
a.leafClusters=make(map[string]uint64)
}
a.leafClusters[cluster]++
}
// Check to see if we already have this cluster registered.
func (a*Account) hasLeafNodeCluster(clusterstring) bool {
a.mu.RLock()
defera.mu.RUnlock()
returna.leafClusters[cluster] >0
}
// Check to see if this cluster is isolated, meaning the only one.
// Read Lock should be held.
func (a*Account) isLeafNodeClusterIsolated(clusterstring) bool {
ifcluster==_EMPTY_ {
returnfalse
}
iflen(a.leafClusters) >1 {
returnfalse
}
returna.leafClusters[cluster] ==uint64(a.nleafs)
}
// Helper function to remove leaf nodes. If number of leafnodes gets large
// this may need to be optimized out of linear search but believe number
// of active leafnodes per account scope to be small and therefore cache friendly.
// Lock should not be held on general account lock.
func (a*Account) removeLeafNode(c*client) {
// Make sure we hold the list lock as well.
a.lmu.Lock()
defera.lmu.Unlock()
ll:=len(a.lleafs)
fori, l:=rangea.lleafs {
ifl==c {
a.lleafs[i] =a.lleafs[ll-1]