/
route.go
2905 lines (2656 loc) · 83.5 KB
/
route.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 2013-2023 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"
"crypto/tls"
"encoding/json"
"fmt"
"math/rand"
"net"
"net/url"
"reflect"
"runtime"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/klauspost/compress/s2"
)
// RouteType designates the router type
type RouteType int
// Type of Route
const (
// This route we learned from speaking to other routes.
Implicit RouteType = iota
// This route was explicitly configured.
Explicit
)
const (
// RouteProtoZero is the original Route protocol from 2009.
// http://nats.io/documentation/internals/nats-protocol/
RouteProtoZero = iota
// RouteProtoInfo signals a route can receive more then the original INFO block.
// This can be used to update remote cluster permissions, etc...
RouteProtoInfo
// RouteProtoV2 is the new route/cluster protocol that provides account support.
RouteProtoV2
)
// Include the space for the proto
var (
aSubBytes = []byte{'A', '+', ' '}
aUnsubBytes = []byte{'A', '-', ' '}
rSubBytes = []byte{'R', 'S', '+', ' '}
rUnsubBytes = []byte{'R', 'S', '-', ' '}
lSubBytes = []byte{'L', 'S', '+', ' '}
lUnsubBytes = []byte{'L', 'S', '-', ' '}
)
// Used by tests
func setRouteProtoForTest(wantedProto int) int {
return (wantedProto + 1) * -1
}
type route struct {
remoteID string
remoteName string
didSolicit bool
retry bool
lnoc bool
routeType RouteType
url *url.URL
authRequired bool
tlsRequired bool
jetstream bool
connectURLs []string
wsConnURLs []string
gatewayURL string
leafnodeURL string
hash string
idHash string
// Location of the route in the slice: s.routes[remoteID][]*client.
// Initialized to -1 on creation, as to indicate that it is not
// added to the list.
poolIdx int
// If this is set, it means that the route is dedicated for this
// account and the account name will not be included in protocols.
accName []byte
// This is set to true if this is a route connection to an old
// server or a server that has pooling completely disabled.
noPool bool
// Selected compression mode, which may be different from the
// server configured mode.
compression string
}
type connectInfo struct {
Echo bool `json:"echo"`
Verbose bool `json:"verbose"`
Pedantic bool `json:"pedantic"`
User string `json:"user,omitempty"`
Pass string `json:"pass,omitempty"`
TLS bool `json:"tls_required"`
Headers bool `json:"headers"`
Name string `json:"name"`
Cluster string `json:"cluster"`
Dynamic bool `json:"cluster_dynamic,omitempty"`
LNOC bool `json:"lnoc,omitempty"`
Gateway string `json:"gateway,omitempty"`
}
// Route protocol constants
const (
ConProto = "CONNECT %s" + _CRLF_
InfoProto = "INFO %s" + _CRLF_
)
const (
// Warning when user configures cluster TLS insecure
clusterTLSInsecureWarning = "TLS certificate chain and hostname of solicited routes will not be verified. DO NOT USE IN PRODUCTION!"
// The default ping interval is set to 2 minutes, which is fine for client
// connections, etc.. but for route compression, the CompressionS2Auto
// mode uses RTT measurements (ping/pong) to decide which compression level
// to use, we want the interval to not be that high.
defaultRouteMaxPingInterval = 30 * time.Second
)
// Can be changed for tests
var (
routeConnectDelay = DEFAULT_ROUTE_CONNECT
routeMaxPingInterval = defaultRouteMaxPingInterval
)
// removeReplySub is called when we trip the max on remoteReply subs.
func (c *client) removeReplySub(sub *subscription) {
if sub == nil {
return
}
// Lookup the account based on sub.sid.
if i := bytes.Index(sub.sid, []byte(" ")); i > 0 {
// First part of SID for route is account name.
if v, ok := c.srv.accounts.Load(string(sub.sid[:i])); ok {
(v.(*Account)).sl.Remove(sub)
}
c.mu.Lock()
delete(c.subs, string(sub.sid))
c.mu.Unlock()
}
}
func (c *client) processAccountSub(arg []byte) error {
accName := string(arg)
if c.kind == GATEWAY {
return c.processGatewayAccountSub(accName)
}
return nil
}
func (c *client) processAccountUnsub(arg []byte) {
accName := string(arg)
if c.kind == GATEWAY {
c.processGatewayAccountUnsub(accName)
}
}
// Process an inbound LMSG specification from the remote route. This means
// we have an origin cluster and we force header semantics.
func (c *client) processRoutedOriginClusterMsgArgs(arg []byte) error {
// Unroll splitArgs to avoid runtime/heap issues
a := [MAX_HMSG_ARGS + 1][]byte{}
args := a[:0]
start := -1
for i, b := range arg {
switch b {
case ' ', '\t', '\r', '\n':
if start >= 0 {
args = append(args, arg[start:i])
start = -1
}
default:
if start < 0 {
start = i
}
}
}
if start >= 0 {
args = append(args, arg[start:])
}
var an []byte
if c.kind == ROUTER {
if an = c.route.accName; len(an) > 0 && len(args) > 2 {
args = append(args[:2], args[1:]...)
args[1] = an
}
}
c.pa.arg = arg
switch len(args) {
case 0, 1, 2, 3, 4:
return fmt.Errorf("processRoutedOriginClusterMsgArgs Parse Error: '%s'", args)
case 5:
c.pa.reply = nil
c.pa.queues = nil
c.pa.hdb = args[3]
c.pa.hdr = parseSize(args[3])
c.pa.szb = args[4]
c.pa.size = parseSize(args[4])
case 6:
c.pa.reply = args[3]
c.pa.queues = nil
c.pa.hdb = args[4]
c.pa.hdr = parseSize(args[4])
c.pa.szb = args[5]
c.pa.size = parseSize(args[5])
default:
// args[2] is our reply indicator. Should be + or | normally.
if len(args[3]) != 1 {
return fmt.Errorf("processRoutedOriginClusterMsgArgs Bad or Missing Reply Indicator: '%s'", args[3])
}
switch args[3][0] {
case '+':
c.pa.reply = args[4]
case '|':
c.pa.reply = nil
default:
return fmt.Errorf("processRoutedOriginClusterMsgArgs Bad or Missing Reply Indicator: '%s'", args[3])
}
// Grab header size.
c.pa.hdb = args[len(args)-2]
c.pa.hdr = parseSize(c.pa.hdb)
// Grab size.
c.pa.szb = args[len(args)-1]
c.pa.size = parseSize(c.pa.szb)
// Grab queue names.
if c.pa.reply != nil {
c.pa.queues = args[5 : len(args)-2]
} else {
c.pa.queues = args[4 : len(args)-2]
}
}
if c.pa.hdr < 0 {
return fmt.Errorf("processRoutedOriginClusterMsgArgs Bad or Missing Header Size: '%s'", arg)
}
if c.pa.size < 0 {
return fmt.Errorf("processRoutedOriginClusterMsgArgs Bad or Missing Size: '%s'", args)
}
if c.pa.hdr > c.pa.size {
return fmt.Errorf("processRoutedOriginClusterMsgArgs Header Size larger then TotalSize: '%s'", arg)
}
// Common ones processed after check for arg length
c.pa.origin = args[0]
c.pa.account = args[1]
c.pa.subject = args[2]
if len(an) > 0 {
c.pa.pacache = c.pa.subject
} else {
c.pa.pacache = arg[len(args[0])+1 : len(args[0])+len(args[1])+len(args[2])+2]
}
return nil
}
// Process an inbound HMSG specification from the remote route.
func (c *client) processRoutedHeaderMsgArgs(arg []byte) error {
// Unroll splitArgs to avoid runtime/heap issues
a := [MAX_HMSG_ARGS][]byte{}
args := a[:0]
var an []byte
if c.kind == ROUTER {
if an = c.route.accName; len(an) > 0 {
args = append(args, an)
}
}
start := -1
for i, b := range arg {
switch b {
case ' ', '\t', '\r', '\n':
if start >= 0 {
args = append(args, arg[start:i])
start = -1
}
default:
if start < 0 {
start = i
}
}
}
if start >= 0 {
args = append(args, arg[start:])
}
c.pa.arg = arg
switch len(args) {
case 0, 1, 2, 3:
return fmt.Errorf("processRoutedHeaderMsgArgs Parse Error: '%s'", args)
case 4:
c.pa.reply = nil
c.pa.queues = nil
c.pa.hdb = args[2]
c.pa.hdr = parseSize(args[2])
c.pa.szb = args[3]
c.pa.size = parseSize(args[3])
case 5:
c.pa.reply = args[2]
c.pa.queues = nil
c.pa.hdb = args[3]
c.pa.hdr = parseSize(args[3])
c.pa.szb = args[4]
c.pa.size = parseSize(args[4])
default:
// args[2] is our reply indicator. Should be + or | normally.
if len(args[2]) != 1 {
return fmt.Errorf("processRoutedHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[2])
}
switch args[2][0] {
case '+':
c.pa.reply = args[3]
case '|':
c.pa.reply = nil
default:
return fmt.Errorf("processRoutedHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[2])
}
// Grab header size.
c.pa.hdb = args[len(args)-2]
c.pa.hdr = parseSize(c.pa.hdb)
// Grab size.
c.pa.szb = args[len(args)-1]
c.pa.size = parseSize(c.pa.szb)
// Grab queue names.
if c.pa.reply != nil {
c.pa.queues = args[4 : len(args)-2]
} else {
c.pa.queues = args[3 : len(args)-2]
}
}
if c.pa.hdr < 0 {
return fmt.Errorf("processRoutedHeaderMsgArgs Bad or Missing Header Size: '%s'", arg)
}
if c.pa.size < 0 {
return fmt.Errorf("processRoutedHeaderMsgArgs Bad or Missing Size: '%s'", args)
}
if c.pa.hdr > c.pa.size {
return fmt.Errorf("processRoutedHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg)
}
// Common ones processed after check for arg length
c.pa.account = args[0]
c.pa.subject = args[1]
if len(an) > 0 {
c.pa.pacache = c.pa.subject
} else {
c.pa.pacache = arg[:len(args[0])+len(args[1])+1]
}
return nil
}
// Process an inbound RMSG or LMSG specification from the remote route.
func (c *client) processRoutedMsgArgs(arg []byte) error {
// Unroll splitArgs to avoid runtime/heap issues
a := [MAX_RMSG_ARGS][]byte{}
args := a[:0]
var an []byte
if c.kind == ROUTER {
if an = c.route.accName; len(an) > 0 {
args = append(args, an)
}
}
start := -1
for i, b := range arg {
switch b {
case ' ', '\t', '\r', '\n':
if start >= 0 {
args = append(args, arg[start:i])
start = -1
}
default:
if start < 0 {
start = i
}
}
}
if start >= 0 {
args = append(args, arg[start:])
}
c.pa.arg = arg
switch len(args) {
case 0, 1, 2:
return fmt.Errorf("processRoutedMsgArgs Parse Error: '%s'", args)
case 3:
c.pa.reply = nil
c.pa.queues = nil
c.pa.szb = args[2]
c.pa.size = parseSize(args[2])
case 4:
c.pa.reply = args[2]
c.pa.queues = nil
c.pa.szb = args[3]
c.pa.size = parseSize(args[3])
default:
// args[2] is our reply indicator. Should be + or | normally.
if len(args[2]) != 1 {
return fmt.Errorf("processRoutedMsgArgs Bad or Missing Reply Indicator: '%s'", args[2])
}
switch args[2][0] {
case '+':
c.pa.reply = args[3]
case '|':
c.pa.reply = nil
default:
return fmt.Errorf("processRoutedMsgArgs Bad or Missing Reply Indicator: '%s'", args[2])
}
// Grab size.
c.pa.szb = args[len(args)-1]
c.pa.size = parseSize(c.pa.szb)
// Grab queue names.
if c.pa.reply != nil {
c.pa.queues = args[4 : len(args)-1]
} else {
c.pa.queues = args[3 : len(args)-1]
}
}
if c.pa.size < 0 {
return fmt.Errorf("processRoutedMsgArgs Bad or Missing Size: '%s'", args)
}
// Common ones processed after check for arg length
c.pa.account = args[0]
c.pa.subject = args[1]
if len(an) > 0 {
c.pa.pacache = c.pa.subject
} else {
c.pa.pacache = arg[:len(args[0])+len(args[1])+1]
}
return nil
}
// processInboundRouteMsg is called to process an inbound msg from a route.
func (c *client) processInboundRoutedMsg(msg []byte) {
// Update statistics
c.in.msgs++
// The msg includes the CR_LF, so pull back out for accounting.
c.in.bytes += int32(len(msg) - LEN_CR_LF)
if c.opts.Verbose {
c.sendOK()
}
// Mostly under testing scenarios.
if c.srv == nil {
return
}
// If the subject (c.pa.subject) has the gateway prefix, this function will handle it.
if c.handleGatewayReply(msg) {
// We are done here.
return
}
acc, r := c.getAccAndResultFromCache()
if acc == nil {
c.Debugf("Unknown account %q for routed message on subject: %q", c.pa.account, c.pa.subject)
return
}
// Check for no interest, short circuit if so.
// This is the fanout scale.
if len(r.psubs)+len(r.qsubs) > 0 {
c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, pmrNoFlag)
}
}
// Lock should be held entering here.
func (c *client) sendRouteConnect(clusterName string, tlsRequired bool) error {
var user, pass string
if userInfo := c.route.url.User; userInfo != nil {
user = userInfo.Username()
pass, _ = userInfo.Password()
}
s := c.srv
cinfo := connectInfo{
Echo: true,
Verbose: false,
Pedantic: false,
User: user,
Pass: pass,
TLS: tlsRequired,
Name: s.info.ID,
Headers: s.supportsHeaders(),
Cluster: clusterName,
Dynamic: s.isClusterNameDynamic(),
LNOC: true,
}
b, err := json.Marshal(cinfo)
if err != nil {
c.Errorf("Error marshaling CONNECT to route: %v\n", err)
return err
}
c.enqueueProto([]byte(fmt.Sprintf(ConProto, b)))
return nil
}
// Process the info message if we are a route.
func (c *client) processRouteInfo(info *Info) {
supportsHeaders := c.srv.supportsHeaders()
clusterName := c.srv.ClusterName()
srvName := c.srv.Name()
c.mu.Lock()
// Connection can be closed at any time (by auth timeout, etc).
// Does not make sense to continue here if connection is gone.
if c.route == nil || c.isClosed() {
c.mu.Unlock()
return
}
s := c.srv
// Detect route to self.
if info.ID == s.info.ID {
// Need to set this so that the close does the right thing
c.route.remoteID = info.ID
c.mu.Unlock()
c.closeConnection(DuplicateRoute)
return
}
// Detect if we have a mismatch of cluster names.
if info.Cluster != "" && info.Cluster != clusterName {
c.mu.Unlock()
// If we are dynamic we may update our cluster name.
// Use other if remote is non dynamic or their name is "bigger"
if s.isClusterNameDynamic() && (!info.Dynamic || (strings.Compare(clusterName, info.Cluster) < 0)) {
s.setClusterName(info.Cluster)
s.removeAllRoutesExcept(info.ID)
c.mu.Lock()
} else {
c.closeConnection(ClusterNameConflict)
return
}
}
opts := s.getOpts()
didSolicit := c.route.didSolicit
// If this is an async INFO from an existing route...
if c.flags.isSet(infoReceived) {
remoteID := c.route.remoteID
// Check if this is an INFO about adding a per-account route during
// a configuration reload.
if info.RouteAccReqID != _EMPTY_ {
c.mu.Unlock()
// If there is an account name, then the remote server is telling
// us that this account will now have its dedicated route.
if an := info.RouteAccount; an != _EMPTY_ {
acc, err := s.LookupAccount(an)
if err != nil {
s.Errorf("Error looking up account %q: %v", an, err)
return
}
s.mu.Lock()
if _, ok := s.accRoutes[an]; !ok {
s.accRoutes[an] = make(map[string]*client)
}
acc.mu.Lock()
sl := acc.sl
rpi := acc.routePoolIdx
// Make sure that the account was not already switched.
if rpi >= 0 {
s.setRouteInfo(acc)
// Change the route pool index to indicate that this
// account is actually transitioning. This will be used
// to suppress possible remote subscription interest coming
// in while the transition is happening.
acc.routePoolIdx = accTransitioningToDedicatedRoute
} else if info.RoutePoolSize == s.routesPoolSize {
// Otherwise, and if the other side's pool size matches
// ours, get the route pool index that was handling this
// account.
rpi = s.computeRoutePoolIdx(acc)
}
acc.mu.Unlock()
// Go over each remote's route at pool index `rpi` and remove
// remote subs for this account.
s.forEachRouteIdx(rpi, func(r *client) bool {
r.mu.Lock()
// Exclude routes to servers that don't support pooling.
if !r.route.noPool {
if subs := r.removeRemoteSubsForAcc(an); len(subs) > 0 {
sl.RemoveBatch(subs)
}
}
r.mu.Unlock()
return true
})
// Respond to the remote by clearing the RouteAccount field.
info.RouteAccount = _EMPTY_
proto := generateInfoJSON(info)
c.mu.Lock()
c.enqueueProto(proto)
c.mu.Unlock()
s.mu.Unlock()
} else {
// If no account name is specified, this is a response from the
// remote. Simply send to the communication channel, if the
// request ID matches the current one.
s.mu.Lock()
if info.RouteAccReqID == s.accAddedReqID && s.accAddedCh != nil {
select {
case s.accAddedCh <- struct{}{}:
default:
}
}
s.mu.Unlock()
}
// In both cases, we are done here.
return
}
// Check if this is an INFO for gateways...
if info.Gateway != _EMPTY_ {
c.mu.Unlock()
// If this server has no gateway configured, report error and return.
if !s.gateway.enabled {
// FIXME: Should this be a Fatalf()?
s.Errorf("Received information about gateway %q from %s, but gateway is not configured",
info.Gateway, remoteID)
return
}
s.processGatewayInfoFromRoute(info, remoteID, c)
return
}
// We receive an INFO from a server that informs us about another server,
// so the info.ID in the INFO protocol does not match the ID of this route.
if remoteID != _EMPTY_ && remoteID != info.ID {
c.mu.Unlock()
// Process this implicit route. We will check that it is not an explicit
// route and/or that it has not been connected already.
s.processImplicitRoute(info)
return
}
var connectURLs []string
var wsConnectURLs []string
var updateRoutePerms bool
// If we are notified that the remote is going into LDM mode, capture route's connectURLs.
if info.LameDuckMode {
connectURLs = c.route.connectURLs
wsConnectURLs = c.route.wsConnURLs
} else {
// Update only if we detect a difference
updateRoutePerms = !reflect.DeepEqual(c.opts.Import, info.Import) || !reflect.DeepEqual(c.opts.Export, info.Export)
}
c.mu.Unlock()
if updateRoutePerms {
s.updateRemoteRoutePerms(c, info)
}
// If the remote is going into LDM and there are client connect URLs
// associated with this route and we are allowed to advertise, remove
// those URLs and update our clients.
if (len(connectURLs) > 0 || len(wsConnectURLs) > 0) && !opts.Cluster.NoAdvertise {
s.mu.Lock()
s.removeConnectURLsAndSendINFOToClients(connectURLs, wsConnectURLs)
s.mu.Unlock()
}
return
}
// Check if remote has same server name than this server.
if !didSolicit && info.Name == srvName {
c.mu.Unlock()
// This is now an error and we close the connection. We need unique names for JetStream clustering.
c.Errorf("Remote server has a duplicate name: %q", info.Name)
c.closeConnection(DuplicateServerName)
return
}
// First INFO, check if this server is configured for compression because
// if that is the case, we need to negotiate it with the remote server.
if needsCompression(opts.Cluster.Compression.Mode) {
accName := string(c.route.accName)
// If we did not yet negotiate...
if !c.flags.isSet(compressionNegotiated) {
// Prevent from getting back here.
c.flags.set(compressionNegotiated)
// Release client lock since following function will need server lock.
c.mu.Unlock()
compress, err := s.negotiateRouteCompression(c, didSolicit, accName, info.Compression, opts)
if err != nil {
c.sendErrAndErr(err.Error())
c.closeConnection(ProtocolViolation)
return
}
if compress {
// Done for now, will get back another INFO protocol...
return
}
// No compression because one side does not want/can't, so proceed.
c.mu.Lock()
} else if didSolicit {
// The other side has switched to compression, so we can now set
// the first ping timer and send the delayed INFO for situations
// where it was not already sent.
c.setFirstPingTimer()
if !routeShouldDelayInfo(accName, opts) {
cm := compressionModeForInfoProtocol(&opts.Cluster.Compression, c.route.compression)
// Need to release and then reacquire...
c.mu.Unlock()
s.sendDelayedRouteInfo(c, accName, cm)
c.mu.Lock()
}
}
// Check that the connection did not close if the lock was released.
if c.isClosed() {
c.mu.Unlock()
return
}
} else {
// Coming from an old server, the Compression field would be the empty
// string. For servers that are configured with CompressionNotSupported,
// this makes them behave as old servers.
if info.Compression == _EMPTY_ || opts.Cluster.Compression.Mode == CompressionNotSupported {
c.route.compression = CompressionNotSupported
} else {
c.route.compression = CompressionOff
}
}
// Mark that the INFO protocol has been received, so we can detect updates.
c.flags.set(infoReceived)
// Get the route's proto version
c.opts.Protocol = info.Proto
// Headers
c.headers = supportsHeaders && info.Headers
// Copy over important information.
c.route.remoteID = info.ID
c.route.authRequired = info.AuthRequired
c.route.tlsRequired = info.TLSRequired
c.route.gatewayURL = info.GatewayURL
c.route.remoteName = info.Name
c.route.lnoc = info.LNOC
c.route.jetstream = info.JetStream
// When sent through route INFO, if the field is set, it should be of size 1.
if len(info.LeafNodeURLs) == 1 {
c.route.leafnodeURL = info.LeafNodeURLs[0]
}
// Compute the hash of this route based on remote server name
c.route.hash = getHash(info.Name)
// Same with remote server ID (used for GW mapped replies routing).
// Use getGWHash since we don't use the same hash len for that
// for backward compatibility.
c.route.idHash = string(getGWHash(info.ID))
// Copy over permissions as well.
c.opts.Import = info.Import
c.opts.Export = info.Export
// If we do not know this route's URL, construct one on the fly
// from the information provided.
if c.route.url == nil {
// Add in the URL from host and port
hp := net.JoinHostPort(info.Host, strconv.Itoa(info.Port))
url, err := url.Parse(fmt.Sprintf("nats-route://%s/", hp))
if err != nil {
c.Errorf("Error parsing URL from INFO: %v\n", err)
c.mu.Unlock()
c.closeConnection(ParseError)
return
}
c.route.url = url
}
// The incoming INFO from the route will have IP set
// if it has Cluster.Advertise. In that case, use that
// otherwise construct it from the remote TCP address.
if info.IP == _EMPTY_ {
// Need to get the remote IP address.
switch conn := c.nc.(type) {
case *net.TCPConn, *tls.Conn:
addr := conn.RemoteAddr().(*net.TCPAddr)
info.IP = fmt.Sprintf("nats-route://%s/", net.JoinHostPort(addr.IP.String(),
strconv.Itoa(info.Port)))
default:
info.IP = c.route.url.String()
}
}
// For accounts that are configured to have their own route:
// If this is a solicit route, we already have c.route.accName set in createRoute.
// For non solicited route (the accept side), we will set the account name that
// is present in the INFO protocol.
if !didSolicit {
c.route.accName = []byte(info.RouteAccount)
}
accName := string(c.route.accName)
// Check to see if we have this remote already registered.
// This can happen when both servers have routes to each other.
c.mu.Unlock()
if added := s.addRoute(c, didSolicit, info, accName); added {
if accName != _EMPTY_ {
c.Debugf("Registering remote route %q for account %q", info.ID, accName)
} else {
c.Debugf("Registering remote route %q", info.ID)
}
} else {
c.Debugf("Detected duplicate remote route %q", info.ID)
c.closeConnection(DuplicateRoute)
}
}
func (s *Server) negotiateRouteCompression(c *client, didSolicit bool, accName, infoCompression string, opts *Options) (bool, error) {
// Negotiate the appropriate compression mode (or no compression)
cm, err := selectCompressionMode(opts.Cluster.Compression.Mode, infoCompression)
if err != nil {
return false, err
}
c.mu.Lock()
// For "auto" mode, set the initial compression mode based on RTT
if cm == CompressionS2Auto {
if c.rttStart.IsZero() {
c.rtt = computeRTT(c.start)
}
cm = selectS2AutoModeBasedOnRTT(c.rtt, opts.Cluster.Compression.RTTThresholds)
}
// Keep track of the negotiated compression mode.
c.route.compression = cm
c.mu.Unlock()
// If we end-up doing compression...
if needsCompression(cm) {
// Generate an INFO with the chosen compression mode.
s.mu.Lock()
infoProto := s.generateRouteInitialInfoJSON(accName, cm, 0)
s.mu.Unlock()
// If we solicited, then send this INFO protocol BEFORE switching
// to compression writer. However, if we did not, we send it after.
c.mu.Lock()
if didSolicit {
c.enqueueProto(infoProto)
// Make sure it is completely flushed (the pending bytes goes to
// 0) before proceeding.
for c.out.pb > 0 && !c.isClosed() {
c.flushOutbound()
}
}
// This is to notify the readLoop that it should switch to a
// (de)compression reader.
c.in.flags.set(switchToCompression)
// Create the compress writer before queueing the INFO protocol for
// a route that did not solicit. It will make sure that that proto
// is sent with compression on.
c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...)
if !didSolicit {
c.enqueueProto(infoProto)
}
// We can now set the ping timer.
c.setFirstPingTimer()
c.mu.Unlock()
return true, nil
}
// We are not using compression, set the ping timer.
c.mu.Lock()
c.setFirstPingTimer()
c.mu.Unlock()
// If this is a solicited route, we need to send the INFO if it was not
// done during createRoute() and will not be done in addRoute().
if didSolicit && !routeShouldDelayInfo(accName, opts) {
cm = compressionModeForInfoProtocol(&opts.Cluster.Compression, cm)
s.sendDelayedRouteInfo(c, accName, cm)
}
return false, nil
}
func (s *Server) sendDelayedRouteInfo(c *client, accName, cm string) {
s.mu.Lock()
infoProto := s.generateRouteInitialInfoJSON(accName, cm, 0)
s.mu.Unlock()
c.mu.Lock()
c.enqueueProto(infoProto)
c.mu.Unlock()
}
// Possibly sends local subscriptions interest to this route
// based on changes in the remote's Export permissions.
func (s *Server) updateRemoteRoutePerms(c *client, info *Info) {
c.mu.Lock()
// Interested only on Export permissions for the remote server.
// Create "fake" clients that we will use to check permissions
// using the old permissions...
oldPerms := &RoutePermissions{Export: c.opts.Export}
oldPermsTester := &client{}
oldPermsTester.setRoutePermissions(oldPerms)
// and the new ones.
newPerms := &RoutePermissions{Export: info.Export}
newPermsTester := &client{}
newPermsTester.setRoutePermissions(newPerms)
c.opts.Import = info.Import
c.opts.Export = info.Export
routeAcc, poolIdx, noPool := string(c.route.accName), c.route.poolIdx, c.route.noPool
c.mu.Unlock()
var (
_localSubs [4096]*subscription
_allSubs [4096]*subscription
allSubs = _allSubs[:0]
)
s.accounts.Range(func(_, v interface{}) bool {
acc := v.(*Account)
acc.mu.RLock()
accName, sl, accPoolIdx := acc.Name, acc.sl, acc.routePoolIdx
acc.mu.RUnlock()
// Do this only for accounts handled by this route
if (accPoolIdx >= 0 && accPoolIdx == poolIdx) || (routeAcc == accName) || noPool {
localSubs := _localSubs[:0]
sl.localSubs(&localSubs, false)
if len(localSubs) > 0 {
allSubs = append(allSubs, localSubs...)
}
}
return true
})
if len(allSubs) == 0 {
return
}
c.mu.Lock()
c.sendRouteSubProtos(allSubs, false, func(sub *subscription) bool {
subj := string(sub.subject)
// If the remote can now export but could not before, and this server can import this
// subject, then send SUB protocol.
if newPermsTester.canExport(subj) && !oldPermsTester.canExport(subj) && c.canImport(subj) {
return true
}
return false
})
c.mu.Unlock()
}
// sendAsyncInfoToClients sends an INFO protocol to all
// connected clients that accept async INFO updates.
// The server lock is held on entry.
func (s *Server) sendAsyncInfoToClients(regCli, wsCli bool) {
// If there are no clients supporting async INFO protocols, we are done.
// Also don't send if we are shutting down...
if s.cproto == 0 || s.shutdown {
return
}
info := s.copyInfo()
for _, c := range s.clients {
c.mu.Lock()
// Here, we are going to send only to the clients that are fully
// registered (server has received CONNECT and first PING). For
// clients that are not at this stage, this will happen in the
// processing of the first PING (see client.processPing)
if ((regCli && !c.isWebsocket()) || (wsCli && c.isWebsocket())) &&
c.opts.Protocol >= ClientProtoInfo &&
c.flags.isSet(firstPongSent) {
// sendInfo takes care of checking if the connection is still
// valid or not, so don't duplicate tests here.
c.enqueueProto(c.generateClientInfoJSON(info))
}
c.mu.Unlock()
}
}