| 1 |
// Copyright 2013-2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"crypto/tls" |
| 19 |
"encoding/json" |
| 20 |
"fmt" |
| 21 |
"hash/fnv" |
| 22 |
"math/rand" |
| 23 |
"net" |
| 24 |
"net/url" |
| 25 |
"reflect" |
| 26 |
"runtime" |
| 27 |
"strconv" |
| 28 |
"strings" |
| 29 |
"sync/atomic" |
| 30 |
"time" |
| 31 |
|
| 32 |
"github.com/klauspost/compress/s2" |
| 33 |
) |
| 34 |
|
| 35 |
// RouteType designates the router type |
| 36 |
type RouteType int |
| 37 |
|
| 38 |
// Type of Route |
| 39 |
const ( |
| 40 |
// This route we learned from speaking to other routes. |
| 41 |
Implicit RouteType = iota |
| 42 |
// This route was explicitly configured. |
| 43 |
Explicit |
| 44 |
) |
| 45 |
|
| 46 |
// Include the space for the proto |
| 47 |
var ( |
| 48 |
aSubBytes = []byte{'A', '+', ' '} |
| 49 |
aUnsubBytes = []byte{'A', '-', ' '} |
| 50 |
rSubBytes = []byte{'R', 'S', '+', ' '} |
| 51 |
rUnsubBytes = []byte{'R', 'S', '-', ' '} |
| 52 |
lSubBytes = []byte{'L', 'S', '+', ' '} |
| 53 |
lUnsubBytes = []byte{'L', 'S', '-', ' '} |
| 54 |
) |
| 55 |
|
| 56 |
type route struct { |
| 57 |
remoteID string |
| 58 |
remoteName string |
| 59 |
didSolicit bool |
| 60 |
retry bool |
| 61 |
lnoc bool |
| 62 |
lnocu bool |
| 63 |
routeType RouteType |
| 64 |
url *url.URL |
| 65 |
authRequired bool |
| 66 |
tlsRequired bool |
| 67 |
jetstream bool |
| 68 |
connectURLs []string |
| 69 |
wsConnURLs []string |
| 70 |
gatewayURL string |
| 71 |
leafnodeURL string |
| 72 |
hash string |
| 73 |
idHash string |
| 74 |
// Location of the route in the slice: s.routes[remoteID][]*client. |
| 75 |
// Initialized to -1 on creation, as to indicate that it is not |
| 76 |
// added to the list. |
| 77 |
poolIdx int |
| 78 |
// If this is set, it means that the route is dedicated for this |
| 79 |
// account and the account name will not be included in protocols. |
| 80 |
accName []byte |
| 81 |
// This is set to true if this is a route connection to an old |
| 82 |
// server or a server that has pooling completely disabled. |
| 83 |
noPool bool |
| 84 |
// Selected compression mode, which may be different from the |
| 85 |
// server configured mode. |
| 86 |
compression string |
| 87 |
// Transient value used to set the Info.GossipMode when initiating |
| 88 |
// an implicit route and sending to the remote. |
| 89 |
gossipMode byte |
| 90 |
// This will be set in case of pooling so that a route can trigger |
| 91 |
// the creation of the next after receiving a PONG, ensuring |
| 92 |
// that authentication did not fail. |
| 93 |
startNewRoute *routeInfo |
| 94 |
} |
| 95 |
|
| 96 |
// This contains the information required to create a new route. |
| 97 |
type routeInfo struct { |
| 98 |
url *url.URL |
| 99 |
rtype RouteType |
| 100 |
gossipMode byte |
| 101 |
} |
| 102 |
|
| 103 |
// Do not change the values/order since they are exchanged between servers. |
| 104 |
const ( |
| 105 |
gossipDefault = byte(iota) |
| 106 |
gossipDisabled |
| 107 |
gossipOverride |
| 108 |
) |
| 109 |
|
| 110 |
type connectInfo struct { |
| 111 |
Echo bool `json:"echo"` |
| 112 |
Verbose bool `json:"verbose"` |
| 113 |
Pedantic bool `json:"pedantic"` |
| 114 |
User string `json:"user,omitempty"` |
| 115 |
Pass string `json:"pass,omitempty"` |
| 116 |
TLS bool `json:"tls_required"` |
| 117 |
Headers bool `json:"headers"` |
| 118 |
Name string `json:"name"` |
| 119 |
Cluster string `json:"cluster"` |
| 120 |
Dynamic bool `json:"cluster_dynamic,omitempty"` |
| 121 |
LNOC bool `json:"lnoc,omitempty"` |
| 122 |
LNOCU bool `json:"lnocu,omitempty"` // Support for LS- with origin cluster name |
| 123 |
Gateway string `json:"gateway,omitempty"` |
| 124 |
} |
| 125 |
|
| 126 |
// Route protocol constants |
| 127 |
const ( |
| 128 |
ConProto = "CONNECT %s" + _CRLF_ |
| 129 |
InfoProto = "INFO %s" + _CRLF_ |
| 130 |
) |
| 131 |
|
| 132 |
const ( |
| 133 |
// Warning when user configures cluster TLS insecure |
| 134 |
clusterTLSInsecureWarning = "TLS certificate chain and hostname of solicited routes will not be verified. DO NOT USE IN PRODUCTION!" |
| 135 |
|
| 136 |
// The default ping interval is set to 2 minutes, which is fine for client |
| 137 |
// connections, etc.. but for route compression, the CompressionS2Auto |
| 138 |
// mode uses RTT measurements (ping/pong) to decide which compression level |
| 139 |
// to use, we want the interval to not be that high. |
| 140 |
defaultRouteMaxPingInterval = 30 * time.Second |
| 141 |
) |
| 142 |
|
| 143 |
// Can be changed for tests |
| 144 |
var ( |
| 145 |
routeConnectDelay = DEFAULT_ROUTE_CONNECT |
| 146 |
routeConnectMaxDelay = DEFAULT_ROUTE_CONNECT_MAX |
| 147 |
routeMaxPingInterval = defaultRouteMaxPingInterval |
| 148 |
) |
| 149 |
|
| 150 |
// removeReplySub is called when we trip the max on remoteReply subs. |
| 151 |
func (c *client) removeReplySub(sub *subscription) { |
| 152 |
if sub == nil { |
| 153 |
return |
| 154 |
} |
| 155 |
// Lookup the account based on sub.sid. |
| 156 |
if i := bytes.Index(sub.sid, []byte(" ")); i > 0 { |
| 157 |
// First part of SID for route is account name. |
| 158 |
if v, ok := c.srv.accounts.Load(bytesToString(sub.sid[:i])); ok { |
| 159 |
(v.(*Account)).sl.Remove(sub) |
| 160 |
} |
| 161 |
c.mu.Lock() |
| 162 |
delete(c.subs, bytesToString(sub.sid)) |
| 163 |
c.mu.Unlock() |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
func (c *client) processAccountSub(arg []byte) error { |
| 168 |
if c.kind == GATEWAY { |
| 169 |
return c.processGatewayAccountSub(string(arg)) |
| 170 |
} |
| 171 |
return nil |
| 172 |
} |
| 173 |
|
| 174 |
func (c *client) processAccountUnsub(arg []byte) { |
| 175 |
if c.kind == GATEWAY { |
| 176 |
c.processGatewayAccountUnsub(string(arg)) |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
// Process an inbound LMSG specification from the remote route. This means |
| 181 |
// we have an origin cluster and we force header semantics. |
| 182 |
func (c *client) processRoutedOriginClusterMsgArgs(arg []byte) error { |
| 183 |
// Unroll splitArgs to avoid runtime/heap issues |
| 184 |
args := c.argsa[:0] |
| 185 |
start := -1 |
| 186 |
for i, b := range arg { |
| 187 |
switch b { |
| 188 |
case ' ', '\t', '\r', '\n': |
| 189 |
if start >= 0 { |
| 190 |
args = append(args, arg[start:i]) |
| 191 |
start = -1 |
| 192 |
} |
| 193 |
default: |
| 194 |
if start < 0 { |
| 195 |
start = i |
| 196 |
} |
| 197 |
} |
| 198 |
} |
| 199 |
if start >= 0 { |
| 200 |
args = append(args, arg[start:]) |
| 201 |
} |
| 202 |
|
| 203 |
var an []byte |
| 204 |
if c.kind == ROUTER { |
| 205 |
if an = c.route.accName; len(an) > 0 && len(args) > 2 { |
| 206 |
args = append(args[:2], args[1:]...) |
| 207 |
args[1] = an |
| 208 |
} |
| 209 |
} |
| 210 |
c.pa.arg = arg |
| 211 |
switch len(args) { |
| 212 |
case 0, 1, 2, 3, 4: |
| 213 |
return fmt.Errorf("processRoutedOriginClusterMsgArgs Parse Error: '%s'", args) |
| 214 |
case 5: |
| 215 |
c.pa.reply = nil |
| 216 |
c.pa.queues = nil |
| 217 |
c.pa.hdb = args[3] |
| 218 |
c.pa.hdr = parseSize(args[3]) |
| 219 |
c.pa.szb = args[4] |
| 220 |
c.pa.size = parseSize(args[4]) |
| 221 |
case 6: |
| 222 |
c.pa.reply = args[3] |
| 223 |
c.pa.queues = nil |
| 224 |
c.pa.hdb = args[4] |
| 225 |
c.pa.hdr = parseSize(args[4]) |
| 226 |
c.pa.szb = args[5] |
| 227 |
c.pa.size = parseSize(args[5]) |
| 228 |
default: |
| 229 |
// args[2] is our reply indicator. Should be + or | normally. |
| 230 |
if len(args[3]) != 1 { |
| 231 |
return fmt.Errorf("processRoutedOriginClusterMsgArgs Bad or Missing Reply Indicator: '%s'", args[3]) |
| 232 |
} |
| 233 |
switch args[3][0] { |
| 234 |
case '+': |
| 235 |
c.pa.reply = args[4] |
| 236 |
case '|': |
| 237 |
c.pa.reply = nil |
| 238 |
default: |
| 239 |
return fmt.Errorf("processRoutedOriginClusterMsgArgs Bad or Missing Reply Indicator: '%s'", args[3]) |
| 240 |
} |
| 241 |
|
| 242 |
// Grab header size. |
| 243 |
c.pa.hdb = args[len(args)-2] |
| 244 |
c.pa.hdr = parseSize(c.pa.hdb) |
| 245 |
|
| 246 |
// Grab size. |
| 247 |
c.pa.szb = args[len(args)-1] |
| 248 |
c.pa.size = parseSize(c.pa.szb) |
| 249 |
|
| 250 |
// Grab queue names. |
| 251 |
if c.pa.reply != nil { |
| 252 |
c.pa.queues = args[5 : len(args)-2] |
| 253 |
} else { |
| 254 |
c.pa.queues = args[4 : len(args)-2] |
| 255 |
} |
| 256 |
} |
| 257 |
if c.pa.hdr < 0 { |
| 258 |
return fmt.Errorf("processRoutedOriginClusterMsgArgs Bad or Missing Header Size: '%s'", arg) |
| 259 |
} |
| 260 |
if c.pa.size < 0 { |
| 261 |
return fmt.Errorf("processRoutedOriginClusterMsgArgs Bad or Missing Size: '%s'", args) |
| 262 |
} |
| 263 |
if c.pa.hdr > c.pa.size { |
| 264 |
return fmt.Errorf("processRoutedOriginClusterMsgArgs Header Size larger then TotalSize: '%s'", arg) |
| 265 |
} |
| 266 |
|
| 267 |
// Common ones processed after check for arg length |
| 268 |
c.pa.origin = args[0] |
| 269 |
c.pa.account = args[1] |
| 270 |
c.pa.subject = args[2] |
| 271 |
if len(an) > 0 { |
| 272 |
c.pa.pacache = c.pa.subject |
| 273 |
} else { |
| 274 |
c.pa.pacache = arg[len(args[0])+1 : len(args[0])+len(args[1])+len(args[2])+2] |
| 275 |
} |
| 276 |
return nil |
| 277 |
} |
| 278 |
|
| 279 |
// Process an inbound HMSG specification from the remote route. |
| 280 |
func (c *client) processRoutedHeaderMsgArgs(arg []byte) error { |
| 281 |
// Unroll splitArgs to avoid runtime/heap issues |
| 282 |
args := c.argsa[:0] |
| 283 |
var an []byte |
| 284 |
if c.kind == ROUTER { |
| 285 |
if an = c.route.accName; len(an) > 0 { |
| 286 |
args = append(args, an) |
| 287 |
} |
| 288 |
} |
| 289 |
start := -1 |
| 290 |
for i, b := range arg { |
| 291 |
switch b { |
| 292 |
case ' ', '\t', '\r', '\n': |
| 293 |
if start >= 0 { |
| 294 |
args = append(args, arg[start:i]) |
| 295 |
start = -1 |
| 296 |
} |
| 297 |
default: |
| 298 |
if start < 0 { |
| 299 |
start = i |
| 300 |
} |
| 301 |
} |
| 302 |
} |
| 303 |
if start >= 0 { |
| 304 |
args = append(args, arg[start:]) |
| 305 |
} |
| 306 |
|
| 307 |
c.pa.arg = arg |
| 308 |
switch len(args) { |
| 309 |
case 0, 1, 2, 3: |
| 310 |
return fmt.Errorf("processRoutedHeaderMsgArgs Parse Error: '%s'", args) |
| 311 |
case 4: |
| 312 |
c.pa.reply = nil |
| 313 |
c.pa.queues = nil |
| 314 |
c.pa.hdb = args[2] |
| 315 |
c.pa.hdr = parseSize(args[2]) |
| 316 |
c.pa.szb = args[3] |
| 317 |
c.pa.size = parseSize(args[3]) |
| 318 |
case 5: |
| 319 |
c.pa.reply = args[2] |
| 320 |
c.pa.queues = nil |
| 321 |
c.pa.hdb = args[3] |
| 322 |
c.pa.hdr = parseSize(args[3]) |
| 323 |
c.pa.szb = args[4] |
| 324 |
c.pa.size = parseSize(args[4]) |
| 325 |
default: |
| 326 |
// args[2] is our reply indicator. Should be + or | normally. |
| 327 |
if len(args[2]) != 1 { |
| 328 |
return fmt.Errorf("processRoutedHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[2]) |
| 329 |
} |
| 330 |
switch args[2][0] { |
| 331 |
case '+': |
| 332 |
c.pa.reply = args[3] |
| 333 |
case '|': |
| 334 |
c.pa.reply = nil |
| 335 |
default: |
| 336 |
return fmt.Errorf("processRoutedHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[2]) |
| 337 |
} |
| 338 |
|
| 339 |
// Grab header size. |
| 340 |
c.pa.hdb = args[len(args)-2] |
| 341 |
c.pa.hdr = parseSize(c.pa.hdb) |
| 342 |
|
| 343 |
// Grab size. |
| 344 |
c.pa.szb = args[len(args)-1] |
| 345 |
c.pa.size = parseSize(c.pa.szb) |
| 346 |
|
| 347 |
// Grab queue names. |
| 348 |
if c.pa.reply != nil { |
| 349 |
c.pa.queues = args[4 : len(args)-2] |
| 350 |
} else { |
| 351 |
c.pa.queues = args[3 : len(args)-2] |
| 352 |
} |
| 353 |
} |
| 354 |
if c.pa.hdr < 0 { |
| 355 |
return fmt.Errorf("processRoutedHeaderMsgArgs Bad or Missing Header Size: '%s'", arg) |
| 356 |
} |
| 357 |
if c.pa.size < 0 { |
| 358 |
return fmt.Errorf("processRoutedHeaderMsgArgs Bad or Missing Size: '%s'", args) |
| 359 |
} |
| 360 |
if c.pa.hdr > c.pa.size { |
| 361 |
return fmt.Errorf("processRoutedHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg) |
| 362 |
} |
| 363 |
|
| 364 |
// Common ones processed after check for arg length |
| 365 |
c.pa.account = args[0] |
| 366 |
c.pa.subject = args[1] |
| 367 |
if len(an) > 0 { |
| 368 |
c.pa.pacache = c.pa.subject |
| 369 |
} else { |
| 370 |
c.pa.pacache = arg[:len(args[0])+len(args[1])+1] |
| 371 |
} |
| 372 |
return nil |
| 373 |
} |
| 374 |
|
| 375 |
// Process an inbound RMSG or LMSG specification from the remote route. |
| 376 |
func (c *client) processRoutedMsgArgs(arg []byte) error { |
| 377 |
// Unroll splitArgs to avoid runtime/heap issues |
| 378 |
args := c.argsa[:0] |
| 379 |
var an []byte |
| 380 |
if c.kind == ROUTER { |
| 381 |
if an = c.route.accName; len(an) > 0 { |
| 382 |
args = append(args, an) |
| 383 |
} |
| 384 |
} |
| 385 |
start := -1 |
| 386 |
for i, b := range arg { |
| 387 |
switch b { |
| 388 |
case ' ', '\t', '\r', '\n': |
| 389 |
if start >= 0 { |
| 390 |
args = append(args, arg[start:i]) |
| 391 |
start = -1 |
| 392 |
} |
| 393 |
default: |
| 394 |
if start < 0 { |
| 395 |
start = i |
| 396 |
} |
| 397 |
} |
| 398 |
} |
| 399 |
if start >= 0 { |
| 400 |
args = append(args, arg[start:]) |
| 401 |
} |
| 402 |
|
| 403 |
c.pa.arg = arg |
| 404 |
switch len(args) { |
| 405 |
case 0, 1, 2: |
| 406 |
return fmt.Errorf("processRoutedMsgArgs Parse Error: '%s'", args) |
| 407 |
case 3: |
| 408 |
c.pa.reply = nil |
| 409 |
c.pa.queues = nil |
| 410 |
c.pa.szb = args[2] |
| 411 |
c.pa.size = parseSize(args[2]) |
| 412 |
case 4: |
| 413 |
c.pa.reply = args[2] |
| 414 |
c.pa.queues = nil |
| 415 |
c.pa.szb = args[3] |
| 416 |
c.pa.size = parseSize(args[3]) |
| 417 |
default: |
| 418 |
// args[2] is our reply indicator. Should be + or | normally. |
| 419 |
if len(args[2]) != 1 { |
| 420 |
return fmt.Errorf("processRoutedMsgArgs Bad or Missing Reply Indicator: '%s'", args[2]) |
| 421 |
} |
| 422 |
switch args[2][0] { |
| 423 |
case '+': |
| 424 |
c.pa.reply = args[3] |
| 425 |
case '|': |
| 426 |
c.pa.reply = nil |
| 427 |
default: |
| 428 |
return fmt.Errorf("processRoutedMsgArgs Bad or Missing Reply Indicator: '%s'", args[2]) |
| 429 |
} |
| 430 |
// Grab size. |
| 431 |
c.pa.szb = args[len(args)-1] |
| 432 |
c.pa.size = parseSize(c.pa.szb) |
| 433 |
|
| 434 |
// Grab queue names. |
| 435 |
if c.pa.reply != nil { |
| 436 |
c.pa.queues = args[4 : len(args)-1] |
| 437 |
} else { |
| 438 |
c.pa.queues = args[3 : len(args)-1] |
| 439 |
} |
| 440 |
} |
| 441 |
if c.pa.size < 0 { |
| 442 |
return fmt.Errorf("processRoutedMsgArgs Bad or Missing Size: '%s'", args) |
| 443 |
} |
| 444 |
|
| 445 |
// Common ones processed after check for arg length |
| 446 |
c.pa.account = args[0] |
| 447 |
c.pa.subject = args[1] |
| 448 |
if len(an) > 0 { |
| 449 |
c.pa.pacache = c.pa.subject |
| 450 |
} else { |
| 451 |
c.pa.pacache = arg[:len(args[0])+len(args[1])+1] |
| 452 |
} |
| 453 |
return nil |
| 454 |
} |
| 455 |
|
| 456 |
// processInboundRoutedMsg is called to process an inbound msg from a route. |
| 457 |
func (c *client) processInboundRoutedMsg(msg []byte) { |
| 458 |
// Update statistics |
| 459 |
c.in.msgs++ |
| 460 |
// The msg includes the CR_LF, so pull back out for accounting. |
| 461 |
size := len(msg) - LEN_CR_LF |
| 462 |
c.in.bytes += int32(size) |
| 463 |
|
| 464 |
if c.opts.Verbose { |
| 465 |
c.sendOK() |
| 466 |
} |
| 467 |
|
| 468 |
// Mostly under testing scenarios. |
| 469 |
if c.srv == nil { |
| 470 |
return |
| 471 |
} |
| 472 |
|
| 473 |
// If the subject (c.pa.subject) has the gateway prefix, this function will handle it. |
| 474 |
if c.handleGatewayReply(msg) { |
| 475 |
// We are done here. |
| 476 |
return |
| 477 |
} |
| 478 |
|
| 479 |
acc, r := c.getAccAndResultFromCache() |
| 480 |
if acc == nil { |
| 481 |
c.Debugf("Unknown account %q for routed message on subject: %q", c.pa.account, c.pa.subject) |
| 482 |
return |
| 483 |
} |
| 484 |
|
| 485 |
acc.stats.Lock() |
| 486 |
acc.stats.inMsgs++ |
| 487 |
acc.stats.inBytes += int64(size) |
| 488 |
acc.stats.rt.inMsgs++ |
| 489 |
acc.stats.rt.inBytes += int64(size) |
| 490 |
acc.stats.Unlock() |
| 491 |
|
| 492 |
// Check for no interest, short circuit if so. |
| 493 |
// This is the fanout scale. |
| 494 |
if len(r.psubs)+len(r.qsubs) > 0 { |
| 495 |
c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, pmrNoFlag) |
| 496 |
} |
| 497 |
} |
| 498 |
|
| 499 |
// Lock should be held entering here. |
| 500 |
func (c *client) sendRouteConnect(clusterName string, tlsRequired bool) error { |
| 501 |
var user, pass string |
| 502 |
if userInfo := c.route.url.User; userInfo != nil { |
| 503 |
user = userInfo.Username() |
| 504 |
pass, _ = userInfo.Password() |
| 505 |
} |
| 506 |
s := c.srv |
| 507 |
cinfo := connectInfo{ |
| 508 |
Echo: true, |
| 509 |
Verbose: false, |
| 510 |
Pedantic: false, |
| 511 |
User: user, |
| 512 |
Pass: pass, |
| 513 |
TLS: tlsRequired, |
| 514 |
Name: s.info.ID, |
| 515 |
Headers: s.supportsHeaders(), |
| 516 |
Cluster: clusterName, |
| 517 |
Dynamic: s.isClusterNameDynamic(), |
| 518 |
LNOC: true, |
| 519 |
} |
| 520 |
|
| 521 |
b, err := json.Marshal(cinfo) |
| 522 |
if err != nil { |
| 523 |
c.Errorf("Error marshaling CONNECT to route: %v\n", err) |
| 524 |
return err |
| 525 |
} |
| 526 |
c.enqueueProto([]byte(fmt.Sprintf(ConProto, b))) |
| 527 |
return nil |
| 528 |
} |
| 529 |
|
| 530 |
// Returns a route pool index for this account based on the given pool size. |
| 531 |
// If `poolSize` is smaller or equal to 1, the returned value will always |
| 532 |
// be 0, regardless of the account name. If not, the returned value will |
| 533 |
// be in the range [0..poolSize-1]. The value for a given account name |
| 534 |
// is constant and same on all servers (given the same `poolSize` value). |
| 535 |
func computeRoutePoolIdx(poolSize int, an string) int { |
| 536 |
if poolSize <= 1 { |
| 537 |
return 0 |
| 538 |
} |
| 539 |
h := fnv.New32a() |
| 540 |
h.Write([]byte(an)) |
| 541 |
sum32 := h.Sum32() |
| 542 |
return int((sum32 % uint32(poolSize))) |
| 543 |
} |
| 544 |
|
| 545 |
// Process the info message if we are a route. |
| 546 |
func (c *client) processRouteInfo(info *Info) { |
| 547 |
|
| 548 |
supportsHeaders := c.srv.supportsHeaders() |
| 549 |
clusterName := c.srv.ClusterName() |
| 550 |
srvName := c.srv.Name() |
| 551 |
|
| 552 |
c.mu.Lock() |
| 553 |
// Connection can be closed at any time (by auth timeout, etc). |
| 554 |
// Does not make sense to continue here if connection is gone. |
| 555 |
if c.route == nil || c.isClosed() { |
| 556 |
c.mu.Unlock() |
| 557 |
return |
| 558 |
} |
| 559 |
|
| 560 |
s := c.srv |
| 561 |
|
| 562 |
// Detect route to self. |
| 563 |
if info.ID == s.info.ID { |
| 564 |
// Need to set this so that the close does the right thing |
| 565 |
c.route.remoteID = info.ID |
| 566 |
c.mu.Unlock() |
| 567 |
c.closeConnection(DuplicateRoute) |
| 568 |
return |
| 569 |
} |
| 570 |
|
| 571 |
// Detect if we have a mismatch of cluster names. |
| 572 |
if info.Cluster != "" && info.Cluster != clusterName { |
| 573 |
c.mu.Unlock() |
| 574 |
// If we are dynamic we may update our cluster name. |
| 575 |
// Use other if remote is non dynamic or their name is "bigger" |
| 576 |
if s.isClusterNameDynamic() && (!info.Dynamic || (strings.Compare(clusterName, info.Cluster) < 0)) { |
| 577 |
s.setClusterName(info.Cluster) |
| 578 |
s.removeAllRoutesExcept(info.ID) |
| 579 |
c.mu.Lock() |
| 580 |
} else { |
| 581 |
c.closeConnection(ClusterNameConflict) |
| 582 |
return |
| 583 |
} |
| 584 |
} |
| 585 |
|
| 586 |
opts := s.getOpts() |
| 587 |
|
| 588 |
didSolicit := c.route.didSolicit |
| 589 |
|
| 590 |
// If this is an async INFO from an existing route... |
| 591 |
if c.flags.isSet(infoReceived) { |
| 592 |
remoteID := c.route.remoteID |
| 593 |
|
| 594 |
// Check if this is an INFO about adding a per-account route during |
| 595 |
// a configuration reload. |
| 596 |
if info.RouteAccReqID != _EMPTY_ { |
| 597 |
c.mu.Unlock() |
| 598 |
|
| 599 |
// If there is an account name, then the remote server is telling |
| 600 |
// us that this account will now have its dedicated route. |
| 601 |
if an := info.RouteAccount; an != _EMPTY_ { |
| 602 |
acc, err := s.LookupAccount(an) |
| 603 |
if err != nil { |
| 604 |
s.Errorf("Error looking up account %q: %v", an, err) |
| 605 |
return |
| 606 |
} |
| 607 |
s.mu.Lock() |
| 608 |
// If running without system account and adding a dedicated |
| 609 |
// route for an account for the first time, it could be that |
| 610 |
// the map is nil. If so, create it. |
| 611 |
if s.accRoutes == nil { |
| 612 |
s.accRoutes = make(map[string]map[string]*client) |
| 613 |
} |
| 614 |
if _, ok := s.accRoutes[an]; !ok { |
| 615 |
s.accRoutes[an] = make(map[string]*client) |
| 616 |
} |
| 617 |
acc.mu.Lock() |
| 618 |
sl := acc.sl |
| 619 |
rpi := acc.routePoolIdx |
| 620 |
// Make sure that the account was not already switched. |
| 621 |
if rpi >= 0 { |
| 622 |
s.setRouteInfo(acc) |
| 623 |
// Change the route pool index to indicate that this |
| 624 |
// account is actually transitioning. This will be used |
| 625 |
// to suppress possible remote subscription interest coming |
| 626 |
// in while the transition is happening. |
| 627 |
acc.routePoolIdx = accTransitioningToDedicatedRoute |
| 628 |
} |
| 629 |
acc.mu.Unlock() |
| 630 |
// Since v2.11.0, we support remotes with a different pool size |
| 631 |
// (for rolling upgrades), so we need to use the remote route |
| 632 |
// pool index (based on the remote configured pool size) since |
| 633 |
// the remote subscriptions will be attached to the route at |
| 634 |
// that index, not at our account's route pool index. But we |
| 635 |
// need to compute only if rpi is negative or the pool sizes |
| 636 |
// are different. |
| 637 |
if rpi <= 0 || info.RoutePoolSize != s.routesPoolSize { |
| 638 |
rpi = computeRoutePoolIdx(info.RoutePoolSize, an) |
| 639 |
} |
| 640 |
// Go over each remote's route at pool index `rpi` and remove |
| 641 |
// remote subs for this account. |
| 642 |
s.forEachRouteIdx(rpi, func(r *client) bool { |
| 643 |
r.mu.Lock() |
| 644 |
// Exclude routes to servers that don't support pooling. |
| 645 |
if !r.route.noPool { |
| 646 |
if subs := r.removeRemoteSubsForAcc(an); len(subs) > 0 { |
| 647 |
sl.RemoveBatch(subs) |
| 648 |
} |
| 649 |
} |
| 650 |
r.mu.Unlock() |
| 651 |
return true |
| 652 |
}) |
| 653 |
// Respond to the remote by clearing the RouteAccount field. |
| 654 |
info.RouteAccount = _EMPTY_ |
| 655 |
proto := generateInfoJSON(info) |
| 656 |
c.mu.Lock() |
| 657 |
c.enqueueProto(proto) |
| 658 |
c.mu.Unlock() |
| 659 |
s.mu.Unlock() |
| 660 |
} else { |
| 661 |
// If no account name is specified, this is a response from the |
| 662 |
// remote. Simply send to the communication channel, if the |
| 663 |
// request ID matches the current one. |
| 664 |
s.mu.Lock() |
| 665 |
if info.RouteAccReqID == s.accAddedReqID && s.accAddedCh != nil { |
| 666 |
select { |
| 667 |
case s.accAddedCh <- struct{}{}: |
| 668 |
default: |
| 669 |
} |
| 670 |
} |
| 671 |
s.mu.Unlock() |
| 672 |
} |
| 673 |
// In both cases, we are done here. |
| 674 |
return |
| 675 |
} |
| 676 |
|
| 677 |
// Check if this is an INFO for gateways... |
| 678 |
if info.Gateway != _EMPTY_ { |
| 679 |
c.mu.Unlock() |
| 680 |
// If this server has no gateway configured, report error and return. |
| 681 |
if !s.gateway.enabled { |
| 682 |
// FIXME: Should this be a Fatalf()? |
| 683 |
s.Errorf("Received information about gateway %q from %s, but gateway is not configured", |
| 684 |
info.Gateway, remoteID) |
| 685 |
return |
| 686 |
} |
| 687 |
s.processGatewayInfoFromRoute(info, remoteID) |
| 688 |
return |
| 689 |
} |
| 690 |
|
| 691 |
// We receive an INFO from a server that informs us about another server, |
| 692 |
// so the info.ID in the INFO protocol does not match the ID of this route. |
| 693 |
if remoteID != _EMPTY_ && remoteID != info.ID { |
| 694 |
// We want to know if the existing route supports pooling/pinned-account |
| 695 |
// or not when processing the implicit route. |
| 696 |
noPool := c.route.noPool |
| 697 |
c.mu.Unlock() |
| 698 |
|
| 699 |
// Process this implicit route. We will check that it is not an explicit |
| 700 |
// route and/or that it has not been connected already. |
| 701 |
s.processImplicitRoute(info, noPool) |
| 702 |
return |
| 703 |
} |
| 704 |
|
| 705 |
var connectURLs []string |
| 706 |
var wsConnectURLs []string |
| 707 |
var updateRoutePerms bool |
| 708 |
|
| 709 |
// If we are notified that the remote is going into LDM mode, capture route's connectURLs. |
| 710 |
if info.LameDuckMode { |
| 711 |
connectURLs = c.route.connectURLs |
| 712 |
wsConnectURLs = c.route.wsConnURLs |
| 713 |
} else { |
| 714 |
// Update only if we detect a difference |
| 715 |
updateRoutePerms = !reflect.DeepEqual(c.opts.Import, info.Import) || !reflect.DeepEqual(c.opts.Export, info.Export) |
| 716 |
} |
| 717 |
c.mu.Unlock() |
| 718 |
|
| 719 |
if updateRoutePerms { |
| 720 |
s.updateRemoteRoutePerms(c, info) |
| 721 |
} |
| 722 |
|
| 723 |
// If the remote is going into LDM and there are client connect URLs |
| 724 |
// associated with this route and we are allowed to advertise, remove |
| 725 |
// those URLs and update our clients. |
| 726 |
if (len(connectURLs) > 0 || len(wsConnectURLs) > 0) && !opts.Cluster.NoAdvertise { |
| 727 |
s.mu.Lock() |
| 728 |
s.removeConnectURLsAndSendINFOToClients(connectURLs, wsConnectURLs) |
| 729 |
s.mu.Unlock() |
| 730 |
} |
| 731 |
return |
| 732 |
} |
| 733 |
|
| 734 |
// Check if remote has same server name than this server. |
| 735 |
if !didSolicit && info.Name == srvName { |
| 736 |
c.mu.Unlock() |
| 737 |
// This is now an error and we close the connection. We need unique names for JetStream clustering. |
| 738 |
c.Errorf("Remote server has a duplicate name: %q", info.Name) |
| 739 |
c.closeConnection(DuplicateServerName) |
| 740 |
return |
| 741 |
} |
| 742 |
|
| 743 |
var sendDelayedInfo bool |
| 744 |
|
| 745 |
// First INFO, check if this server is configured for compression because |
| 746 |
// if that is the case, we need to negotiate it with the remote server. |
| 747 |
if needsCompression(opts.Cluster.Compression.Mode) { |
| 748 |
accName := bytesToString(c.route.accName) |
| 749 |
// If we did not yet negotiate... |
| 750 |
compNeg := c.flags.isSet(compressionNegotiated) |
| 751 |
if !compNeg { |
| 752 |
// Prevent from getting back here. |
| 753 |
c.flags.set(compressionNegotiated) |
| 754 |
// Release client lock since following function will need server lock. |
| 755 |
c.mu.Unlock() |
| 756 |
compress, err := s.negotiateRouteCompression(c, didSolicit, accName, info.Compression, opts) |
| 757 |
if err != nil { |
| 758 |
c.sendErrAndErr(err.Error()) |
| 759 |
c.closeConnection(ProtocolViolation) |
| 760 |
return |
| 761 |
} |
| 762 |
if compress { |
| 763 |
// Done for now, will get back another INFO protocol... |
| 764 |
return |
| 765 |
} |
| 766 |
// No compression because one side does not want/can't, so proceed. |
| 767 |
c.mu.Lock() |
| 768 |
// Check that the connection did not close if the lock was released. |
| 769 |
if c.isClosed() { |
| 770 |
c.mu.Unlock() |
| 771 |
return |
| 772 |
} |
| 773 |
} |
| 774 |
// We can set the ping timer after we just negotiated compression above, |
| 775 |
// or for solicited routes if we already negotiated. |
| 776 |
if !compNeg || didSolicit { |
| 777 |
c.setFirstPingTimer() |
| 778 |
} |
| 779 |
// When compression is configured, we delay the initial INFO for any |
| 780 |
// solicited route. So we need to send the delayed INFO simply based |
| 781 |
// on the didSolicit boolean. |
| 782 |
sendDelayedInfo = didSolicit |
| 783 |
} else { |
| 784 |
// Coming from an old server, the Compression field would be the empty |
| 785 |
// string. For servers that are configured with CompressionNotSupported, |
| 786 |
// this makes them behave as old servers. |
| 787 |
if info.Compression == _EMPTY_ || opts.Cluster.Compression.Mode == CompressionNotSupported { |
| 788 |
c.route.compression = CompressionNotSupported |
| 789 |
} else { |
| 790 |
c.route.compression = CompressionOff |
| 791 |
} |
| 792 |
// When compression is not configured, we delay the initial INFO only |
| 793 |
// for solicited pooled routes, so use the same check that we did when |
| 794 |
// we decided to delay in createRoute(). |
| 795 |
sendDelayedInfo = didSolicit && routeShouldDelayInfo(bytesToString(c.route.accName), opts) |
| 796 |
} |
| 797 |
|
| 798 |
// Mark that the INFO protocol has been received, so we can detect updates. |
| 799 |
c.flags.set(infoReceived) |
| 800 |
|
| 801 |
// Get the route's proto version. It will be used to check if the connection |
| 802 |
// supports certain features, such as message tracing. |
| 803 |
c.opts.Protocol = info.Proto |
| 804 |
|
| 805 |
// Headers |
| 806 |
c.headers = supportsHeaders && info.Headers |
| 807 |
|
| 808 |
// Copy over important information. |
| 809 |
c.route.remoteID = info.ID |
| 810 |
c.route.authRequired = info.AuthRequired |
| 811 |
c.route.tlsRequired = info.TLSRequired |
| 812 |
c.route.gatewayURL = info.GatewayURL |
| 813 |
c.route.remoteName = info.Name |
| 814 |
c.route.lnoc = info.LNOC |
| 815 |
c.route.lnocu = info.LNOCU |
| 816 |
c.route.jetstream = info.JetStream |
| 817 |
|
| 818 |
// When sent through route INFO, if the field is set, it should be of size 1. |
| 819 |
if len(info.LeafNodeURLs) == 1 { |
| 820 |
c.route.leafnodeURL = info.LeafNodeURLs[0] |
| 821 |
} |
| 822 |
// Compute the hash of this route based on remote server name |
| 823 |
c.route.hash = getHash(info.Name) |
| 824 |
// Same with remote server ID (used for GW mapped replies routing). |
| 825 |
// Use getGWHash since we don't use the same hash len for that |
| 826 |
// for backward compatibility. |
| 827 |
c.route.idHash = string(getGWHash(info.ID)) |
| 828 |
|
| 829 |
// Copy over permissions as well. |
| 830 |
c.opts.Import = info.Import |
| 831 |
c.opts.Export = info.Export |
| 832 |
|
| 833 |
// If we do not know this route's URL, construct one on the fly |
| 834 |
// from the information provided. |
| 835 |
if c.route.url == nil { |
| 836 |
// Add in the URL from host and port |
| 837 |
hp := net.JoinHostPort(info.Host, strconv.Itoa(info.Port)) |
| 838 |
url, err := url.Parse(fmt.Sprintf("nats-route://%s/", hp)) |
| 839 |
if err != nil { |
| 840 |
c.Errorf("Error parsing URL from INFO: %v\n", err) |
| 841 |
c.mu.Unlock() |
| 842 |
c.closeConnection(ParseError) |
| 843 |
return |
| 844 |
} |
| 845 |
c.route.url = url |
| 846 |
} |
| 847 |
// The incoming INFO from the route will have IP set |
| 848 |
// if it has Cluster.Advertise. In that case, use that |
| 849 |
// otherwise construct it from the remote TCP address. |
| 850 |
if info.IP == _EMPTY_ { |
| 851 |
// Need to get the remote IP address. |
| 852 |
switch conn := c.nc.(type) { |
| 853 |
case *net.TCPConn, *tls.Conn: |
| 854 |
addr := conn.RemoteAddr().(*net.TCPAddr) |
| 855 |
info.IP = fmt.Sprintf("nats-route://%s/", net.JoinHostPort(addr.IP.String(), |
| 856 |
strconv.Itoa(info.Port))) |
| 857 |
default: |
| 858 |
info.IP = c.route.url.String() |
| 859 |
} |
| 860 |
} |
| 861 |
// For accounts that are configured to have their own route: |
| 862 |
// If this is a solicited route, we already have c.route.accName set in createRoute. |
| 863 |
// For non solicited route (the accept side), we will set the account name that |
| 864 |
// is present in the INFO protocol. |
| 865 |
if didSolicit && len(c.route.accName) > 0 { |
| 866 |
// Set it in the info.RouteAccount so that addRoute can use that |
| 867 |
// and we properly gossip that this is a route for an account. |
| 868 |
info.RouteAccount = string(c.route.accName) |
| 869 |
} else if !didSolicit && info.RouteAccount != _EMPTY_ { |
| 870 |
c.route.accName = []byte(info.RouteAccount) |
| 871 |
} |
| 872 |
accName := string(c.route.accName) |
| 873 |
|
| 874 |
// Capture the noGossip value and reset it here. |
| 875 |
gossipMode := c.route.gossipMode |
| 876 |
c.route.gossipMode = 0 |
| 877 |
|
| 878 |
// Check to see if we have this remote already registered. |
| 879 |
// This can happen when both servers have routes to each other. |
| 880 |
c.mu.Unlock() |
| 881 |
|
| 882 |
if added := s.addRoute(c, didSolicit, sendDelayedInfo, gossipMode, info, accName); added { |
| 883 |
if accName != _EMPTY_ { |
| 884 |
c.Debugf("Registering remote route %q for account %q", info.ID, accName) |
| 885 |
} else { |
| 886 |
c.Debugf("Registering remote route %q", info.ID) |
| 887 |
} |
| 888 |
} else { |
| 889 |
c.Debugf("Detected duplicate remote route %q", info.ID) |
| 890 |
c.closeConnection(DuplicateRoute) |
| 891 |
} |
| 892 |
} |
| 893 |
|
| 894 |
func (s *Server) negotiateRouteCompression(c *client, didSolicit bool, accName, infoCompression string, opts *Options) (bool, error) { |
| 895 |
// Negotiate the appropriate compression mode (or no compression) |
| 896 |
cm, err := selectCompressionMode(opts.Cluster.Compression.Mode, infoCompression) |
| 897 |
if err != nil { |
| 898 |
return false, err |
| 899 |
} |
| 900 |
c.mu.Lock() |
| 901 |
// For "auto" mode, set the initial compression mode based on RTT |
| 902 |
if cm == CompressionS2Auto { |
| 903 |
if c.rttStart.IsZero() { |
| 904 |
c.rtt = computeRTT(c.start) |
| 905 |
} |
| 906 |
cm = selectS2AutoModeBasedOnRTT(c.rtt, opts.Cluster.Compression.RTTThresholds) |
| 907 |
} |
| 908 |
// Keep track of the negotiated compression mode. |
| 909 |
c.route.compression = cm |
| 910 |
c.mu.Unlock() |
| 911 |
|
| 912 |
// If we end-up doing compression... |
| 913 |
if needsCompression(cm) { |
| 914 |
// Generate an INFO with the chosen compression mode. |
| 915 |
s.mu.Lock() |
| 916 |
infoProto := s.generateRouteInitialInfoJSON(accName, cm, 0, gossipDefault) |
| 917 |
s.mu.Unlock() |
| 918 |
|
| 919 |
// If we solicited, then send this INFO protocol BEFORE switching |
| 920 |
// to compression writer. However, if we did not, we send it after. |
| 921 |
c.mu.Lock() |
| 922 |
if didSolicit { |
| 923 |
c.enqueueProto(infoProto) |
| 924 |
// Make sure it is completely flushed (the pending bytes goes to |
| 925 |
// 0) before proceeding. |
| 926 |
for c.out.pb > 0 && !c.isClosed() { |
| 927 |
c.flushOutbound() |
| 928 |
} |
| 929 |
} |
| 930 |
// This is to notify the readLoop that it should switch to a |
| 931 |
// (de)compression reader. |
| 932 |
c.in.flags.set(switchToCompression) |
| 933 |
// Create the compress writer before queueing the INFO protocol for |
| 934 |
// a route that did not solicit. It will make sure that that proto |
| 935 |
// is sent with compression on. |
| 936 |
c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...) |
| 937 |
if !didSolicit { |
| 938 |
c.enqueueProto(infoProto) |
| 939 |
} |
| 940 |
// We can now set the ping timer. |
| 941 |
c.setFirstPingTimer() |
| 942 |
c.mu.Unlock() |
| 943 |
return true, nil |
| 944 |
} |
| 945 |
return false, nil |
| 946 |
} |
| 947 |
|
| 948 |
// Possibly sends local subscriptions interest to this route |
| 949 |
// based on changes in the remote's Export permissions. |
| 950 |
func (s *Server) updateRemoteRoutePerms(c *client, info *Info) { |
| 951 |
c.mu.Lock() |
| 952 |
// Interested only on Export permissions for the remote server. |
| 953 |
// Create "fake" clients that we will use to check permissions |
| 954 |
// using the old permissions... |
| 955 |
oldPerms := &RoutePermissions{Export: c.opts.Export} |
| 956 |
oldPermsTester := &client{} |
| 957 |
oldPermsTester.setRoutePermissions(oldPerms) |
| 958 |
// and the new ones. |
| 959 |
newPerms := &RoutePermissions{Export: info.Export} |
| 960 |
newPermsTester := &client{} |
| 961 |
newPermsTester.setRoutePermissions(newPerms) |
| 962 |
|
| 963 |
c.opts.Import = info.Import |
| 964 |
c.opts.Export = info.Export |
| 965 |
|
| 966 |
routeAcc, poolIdx, noPool := bytesToString(c.route.accName), c.route.poolIdx, c.route.noPool |
| 967 |
c.mu.Unlock() |
| 968 |
|
| 969 |
var ( |
| 970 |
_localSubs [4096]*subscription |
| 971 |
_allSubs [4096]*subscription |
| 972 |
allSubs = _allSubs[:0] |
| 973 |
) |
| 974 |
|
| 975 |
s.accounts.Range(func(_, v any) bool { |
| 976 |
acc := v.(*Account) |
| 977 |
acc.mu.RLock() |
| 978 |
accName, sl, accPoolIdx := acc.Name, acc.sl, acc.routePoolIdx |
| 979 |
acc.mu.RUnlock() |
| 980 |
|
| 981 |
// Do this only for accounts handled by this route |
| 982 |
if (accPoolIdx >= 0 && accPoolIdx == poolIdx) || (routeAcc == accName) || noPool { |
| 983 |
localSubs := _localSubs[:0] |
| 984 |
sl.localSubs(&localSubs, false) |
| 985 |
if len(localSubs) > 0 { |
| 986 |
allSubs = append(allSubs, localSubs...) |
| 987 |
} |
| 988 |
} |
| 989 |
return true |
| 990 |
}) |
| 991 |
|
| 992 |
if len(allSubs) == 0 { |
| 993 |
return |
| 994 |
} |
| 995 |
|
| 996 |
c.mu.Lock() |
| 997 |
c.sendRouteSubProtos(allSubs, false, func(sub *subscription) bool { |
| 998 |
subj := string(sub.subject) |
| 999 |
// If the remote can now export but could not before, and this server can import this |
| 1000 |
// subject, then send SUB protocol. |
| 1001 |
if newPermsTester.canExport(subj) && !oldPermsTester.canExport(subj) && c.canImport(subj) { |
| 1002 |
return true |
| 1003 |
} |
| 1004 |
return false |
| 1005 |
}) |
| 1006 |
c.mu.Unlock() |
| 1007 |
} |
| 1008 |
|
| 1009 |
// sendAsyncInfoToClients sends an INFO protocol to all |
| 1010 |
// connected clients that accept async INFO updates. |
| 1011 |
// The server lock is held on entry. |
| 1012 |
func (s *Server) sendAsyncInfoToClients(regCli, wsCli bool) { |
| 1013 |
// If there are no clients supporting async INFO protocols, we are done. |
| 1014 |
// Also don't send if we are shutting down... |
| 1015 |
if s.cproto == 0 || s.isShuttingDown() { |
| 1016 |
return |
| 1017 |
} |
| 1018 |
info := s.copyInfo() |
| 1019 |
|
| 1020 |
for _, c := range s.clients { |
| 1021 |
c.mu.Lock() |
| 1022 |
// Here, we are going to send only to the clients that are fully |
| 1023 |
// registered (server has received CONNECT and first PING). For |
| 1024 |
// clients that are not at this stage, this will happen in the |
| 1025 |
// processing of the first PING (see client.processPing) |
| 1026 |
if ((regCli && !c.isWebsocket()) || (wsCli && c.isWebsocket())) && |
| 1027 |
c.opts.Protocol >= ClientProtoInfo && |
| 1028 |
c.flags.isSet(firstPongSent) { |
| 1029 |
// sendInfo takes care of checking if the connection is still |
| 1030 |
// valid or not, so don't duplicate tests here. |
| 1031 |
c.enqueueProto(c.generateClientInfoJSON(info, true)) |
| 1032 |
} |
| 1033 |
c.mu.Unlock() |
| 1034 |
} |
| 1035 |
} |
| 1036 |
|
| 1037 |
// This will process implicit route information received from another server. |
| 1038 |
// We will check to see if we have configured or are already connected, |
| 1039 |
// and if so we will ignore. Otherwise we will attempt to connect. |
| 1040 |
func (s *Server) processImplicitRoute(info *Info, routeNoPool bool) { |
| 1041 |
remoteID := info.ID |
| 1042 |
|
| 1043 |
s.mu.Lock() |
| 1044 |
defer s.mu.Unlock() |
| 1045 |
|
| 1046 |
// Don't connect to ourself |
| 1047 |
if remoteID == s.info.ID { |
| 1048 |
return |
| 1049 |
} |
| 1050 |
|
| 1051 |
// Snapshot server options. |
| 1052 |
opts := s.getOpts() |
| 1053 |
|
| 1054 |
// Check if this route already exists |
| 1055 |
if accName := info.RouteAccount; accName != _EMPTY_ { |
| 1056 |
// If we don't support pooling/pinned account, bail. |
| 1057 |
if opts.Cluster.PoolSize <= 0 { |
| 1058 |
return |
| 1059 |
} |
| 1060 |
if remotes, ok := s.accRoutes[accName]; ok { |
| 1061 |
if r := remotes[remoteID]; r != nil { |
| 1062 |
return |
| 1063 |
} |
| 1064 |
} |
| 1065 |
} else if _, exists := s.routes[remoteID]; exists { |
| 1066 |
return |
| 1067 |
} |
| 1068 |
// Check if we have this route as a configured route |
| 1069 |
if s.hasThisRouteConfigured(info) { |
| 1070 |
return |
| 1071 |
} |
| 1072 |
|
| 1073 |
// Initiate the connection, using info.IP instead of info.URL here... |
| 1074 |
r, err := url.Parse(info.IP) |
| 1075 |
if err != nil { |
| 1076 |
s.Errorf("Error parsing URL from INFO: %v\n", err) |
| 1077 |
return |
| 1078 |
} |
| 1079 |
|
| 1080 |
if info.AuthRequired { |
| 1081 |
r.User = url.UserPassword(opts.Cluster.Username, opts.Cluster.Password) |
| 1082 |
} |
| 1083 |
s.startGoRoutine(func() { s.connectToRoute(r, Implicit, true, info.GossipMode, info.RouteAccount) }) |
| 1084 |
// If we are processing an implicit route from a route that does not |
| 1085 |
// support pooling/pinned-accounts, we won't receive an INFO for each of |
| 1086 |
// the pinned-accounts that we would normally receive. In that case, just |
| 1087 |
// initiate routes for all our configured pinned accounts. |
| 1088 |
if routeNoPool && info.RouteAccount == _EMPTY_ && len(opts.Cluster.PinnedAccounts) > 0 { |
| 1089 |
// Copy since we are going to pass as closure to a go routine. |
| 1090 |
rURL := r |
| 1091 |
for _, an := range opts.Cluster.PinnedAccounts { |
| 1092 |
accName := an |
| 1093 |
s.startGoRoutine(func() { s.connectToRoute(rURL, Implicit, true, info.GossipMode, accName) }) |
| 1094 |
} |
| 1095 |
} |
| 1096 |
} |
| 1097 |
|
| 1098 |
// hasThisRouteConfigured returns true if info.Host:info.Port is present |
| 1099 |
// in the server's opts.Routes, false otherwise. |
| 1100 |
// Server lock is assumed to be held by caller. |
| 1101 |
func (s *Server) hasThisRouteConfigured(info *Info) bool { |
| 1102 |
routes := s.getOpts().Routes |
| 1103 |
if len(routes) == 0 { |
| 1104 |
return false |
| 1105 |
} |
| 1106 |
// This could possibly be a 0.0.0.0 host so we will also construct a second |
| 1107 |
// url with the host section of the `info.IP` (if present). |
| 1108 |
sPort := strconv.Itoa(info.Port) |
| 1109 |
urlOne := strings.ToLower(net.JoinHostPort(info.Host, sPort)) |
| 1110 |
var urlTwo string |
| 1111 |
if info.IP != _EMPTY_ { |
| 1112 |
if u, _ := url.Parse(info.IP); u != nil { |
| 1113 |
urlTwo = strings.ToLower(net.JoinHostPort(u.Hostname(), sPort)) |
| 1114 |
// Ignore if same than the first |
| 1115 |
if urlTwo == urlOne { |
| 1116 |
urlTwo = _EMPTY_ |
| 1117 |
} |
| 1118 |
} |
| 1119 |
} |
| 1120 |
for _, ri := range routes { |
| 1121 |
rHost := strings.ToLower(ri.Host) |
| 1122 |
if rHost == urlOne { |
| 1123 |
return true |
| 1124 |
} |
| 1125 |
if urlTwo != _EMPTY_ && rHost == urlTwo { |
| 1126 |
return true |
| 1127 |
} |
| 1128 |
} |
| 1129 |
return false |
| 1130 |
} |
| 1131 |
|
| 1132 |
// forwardNewRouteInfoToKnownServers possibly sends the INFO protocol of the |
| 1133 |
// new route to all routes known by this server. In turn, each server will |
| 1134 |
// contact this new route. |
| 1135 |
// Server lock held on entry. |
| 1136 |
func (s *Server) forwardNewRouteInfoToKnownServers(info *Info, rtype RouteType, didSolicit bool, localGossipMode byte) { |
| 1137 |
// Determine if this connection is resulting from a gossip notification. |
| 1138 |
fromGossip := didSolicit && rtype == Implicit |
| 1139 |
// If from gossip (but we are not overriding it) or if the remote disabled gossip, bail out. |
| 1140 |
if (fromGossip && localGossipMode != gossipOverride) || info.GossipMode == gossipDisabled { |
| 1141 |
return |
| 1142 |
} |
| 1143 |
|
| 1144 |
// Note: nonce is not used in routes. |
| 1145 |
// That being said, the info we get is the initial INFO which |
| 1146 |
// contains a nonce, but we now forward this to existing routes, |
| 1147 |
// so clear it now. |
| 1148 |
info.Nonce = _EMPTY_ |
| 1149 |
|
| 1150 |
var ( |
| 1151 |
infoGMDefault []byte |
| 1152 |
infoGMDisabled []byte |
| 1153 |
infoGMOverride []byte |
| 1154 |
) |
| 1155 |
|
| 1156 |
generateJSON := func(gm byte) []byte { |
| 1157 |
info.GossipMode = gm |
| 1158 |
b, _ := json.Marshal(info) |
| 1159 |
return []byte(fmt.Sprintf(InfoProto, b)) |
| 1160 |
} |
| 1161 |
|
| 1162 |
getJSON := func(r *client) []byte { |
| 1163 |
if (!didSolicit && r.route.routeType == Explicit) || (didSolicit && rtype == Explicit) { |
| 1164 |
if infoGMOverride == nil { |
| 1165 |
infoGMOverride = generateJSON(gossipOverride) |
| 1166 |
} |
| 1167 |
return infoGMOverride |
| 1168 |
} else if !didSolicit { |
| 1169 |
if infoGMDisabled == nil { |
| 1170 |
infoGMDisabled = generateJSON(gossipDisabled) |
| 1171 |
} |
| 1172 |
return infoGMDisabled |
| 1173 |
} |
| 1174 |
if infoGMDefault == nil { |
| 1175 |
infoGMDefault = generateJSON(0) |
| 1176 |
} |
| 1177 |
return infoGMDefault |
| 1178 |
} |
| 1179 |
|
| 1180 |
var accRemotes map[string]*client |
| 1181 |
pinnedAccount := info.RouteAccount != _EMPTY_ |
| 1182 |
// If this is for a pinned account, we will try to send the gossip |
| 1183 |
// through our pinned account routes, but fall back to the other |
| 1184 |
// routes in case we don't have one for a given remote. |
| 1185 |
if pinnedAccount { |
| 1186 |
var ok bool |
| 1187 |
if accRemotes, ok = s.accRoutes[info.RouteAccount]; ok { |
| 1188 |
for remoteID, r := range accRemotes { |
| 1189 |
if r == nil { |
| 1190 |
continue |
| 1191 |
} |
| 1192 |
r.mu.Lock() |
| 1193 |
// Do not send to a remote that does not support pooling/pinned-accounts. |
| 1194 |
if remoteID != info.ID && !r.route.noPool { |
| 1195 |
r.enqueueProto(getJSON(r)) |
| 1196 |
} |
| 1197 |
r.mu.Unlock() |
| 1198 |
} |
| 1199 |
} |
| 1200 |
} |
| 1201 |
|
| 1202 |
s.forEachRemote(func(r *client) { |
| 1203 |
r.mu.Lock() |
| 1204 |
remoteID := r.route.remoteID |
| 1205 |
if pinnedAccount { |
| 1206 |
if _, processed := accRemotes[remoteID]; processed { |
| 1207 |
r.mu.Unlock() |
| 1208 |
return |
| 1209 |
} |
| 1210 |
} |
| 1211 |
// If this is a new route for a given account, do not send to a server |
| 1212 |
// that does not support pooling/pinned-accounts. |
| 1213 |
if remoteID != info.ID && (!pinnedAccount || !r.route.noPool) { |
| 1214 |
r.enqueueProto(getJSON(r)) |
| 1215 |
} |
| 1216 |
r.mu.Unlock() |
| 1217 |
}) |
| 1218 |
} |
| 1219 |
|
| 1220 |
// canImport is whether or not we will send a SUB for interest to the other side. |
| 1221 |
// This is for ROUTER connections only. |
| 1222 |
// Lock is held on entry. |
| 1223 |
func (c *client) canImport(subject string) bool { |
| 1224 |
// Use pubAllowed() since this checks Publish permissions which |
| 1225 |
// is what Import maps to. |
| 1226 |
return c.pubAllowedFullCheck(subject, false, true) |
| 1227 |
} |
| 1228 |
|
| 1229 |
// canExport is whether or not we will accept a SUB from the remote for a given subject. |
| 1230 |
// This is for ROUTER connections only. |
| 1231 |
// Lock is held on entry |
| 1232 |
func (c *client) canExport(subject string) bool { |
| 1233 |
// Use canSubscribe() since this checks Subscribe permissions which |
| 1234 |
// is what Export maps to. |
| 1235 |
return c.canSubscribe(subject) |
| 1236 |
} |
| 1237 |
|
| 1238 |
// Initialize or reset cluster's permissions. |
| 1239 |
// This is for ROUTER connections only. |
| 1240 |
// Client lock is held on entry |
| 1241 |
func (c *client) setRoutePermissions(perms *RoutePermissions) { |
| 1242 |
// Reset if some were set |
| 1243 |
if perms == nil { |
| 1244 |
c.perms = nil |
| 1245 |
c.mperms = nil |
| 1246 |
return |
| 1247 |
} |
| 1248 |
// Convert route permissions to user permissions. |
| 1249 |
// The Import permission is mapped to Publish |
| 1250 |
// and Export permission is mapped to Subscribe. |
| 1251 |
// For meaning of Import/Export, see canImport and canExport. |
| 1252 |
p := &Permissions{ |
| 1253 |
Publish: perms.Import, |
| 1254 |
Subscribe: perms.Export, |
| 1255 |
} |
| 1256 |
c.setPermissions(p) |
| 1257 |
} |
| 1258 |
|
| 1259 |
// Type used to hold a list of subs on a per account basis. |
| 1260 |
type asubs struct { |
| 1261 |
acc *Account |
| 1262 |
subs []*subscription |
| 1263 |
} |
| 1264 |
|
| 1265 |
// Returns the account name from the subscription's key. |
| 1266 |
// This is invoked knowing that the key contains an account name, so for a sub |
| 1267 |
// that is not from a pinned-account route. |
| 1268 |
// The `keyHasSubType` boolean indicates that the key starts with the indicator |
| 1269 |
// for leaf or regular routed subscriptions. |
| 1270 |
func getAccNameFromRoutedSubKey(sub *subscription, key string, keyHasSubType bool) string { |
| 1271 |
var accIdx int |
| 1272 |
if keyHasSubType { |
| 1273 |
// Start after the sub type indicator. |
| 1274 |
accIdx = 1 |
| 1275 |
// But if there is an origin, bump its index. |
| 1276 |
if len(sub.origin) > 0 { |
| 1277 |
accIdx = 2 |
| 1278 |
} |
| 1279 |
} |
| 1280 |
return strings.Fields(key)[accIdx] |
| 1281 |
} |
| 1282 |
|
| 1283 |
// Returns if the route is dedicated to an account, its name, and a boolean |
| 1284 |
// that indicates if this route uses the routed subscription indicator at |
| 1285 |
// the beginning of the subscription key. |
| 1286 |
// Lock held on entry. |
| 1287 |
func (c *client) getRoutedSubKeyInfo() (bool, string, bool) { |
| 1288 |
var accName string |
| 1289 |
if an := c.route.accName; len(an) > 0 { |
| 1290 |
accName = string(an) |
| 1291 |
} |
| 1292 |
return accName != _EMPTY_, accName, c.route.lnocu |
| 1293 |
} |
| 1294 |
|
| 1295 |
// removeRemoteSubs will walk the subs and remove them from the appropriate account. |
| 1296 |
func (c *client) removeRemoteSubs() { |
| 1297 |
// We need to gather these on a per account basis. |
| 1298 |
// FIXME(dlc) - We should be smarter about this.. |
| 1299 |
as := map[string]*asubs{} |
| 1300 |
c.mu.Lock() |
| 1301 |
srv := c.srv |
| 1302 |
subs := c.subs |
| 1303 |
c.subs = nil |
| 1304 |
pa, accountName, hasSubType := c.getRoutedSubKeyInfo() |
| 1305 |
c.mu.Unlock() |
| 1306 |
|
| 1307 |
for key, sub := range subs { |
| 1308 |
c.mu.Lock() |
| 1309 |
sub.max = 0 |
| 1310 |
c.mu.Unlock() |
| 1311 |
// If not a pinned-account route, we need to find the account |
| 1312 |
// name from the sub's key. |
| 1313 |
if !pa { |
| 1314 |
accountName = getAccNameFromRoutedSubKey(sub, key, hasSubType) |
| 1315 |
} |
| 1316 |
ase := as[accountName] |
| 1317 |
if ase == nil { |
| 1318 |
if v, ok := srv.accounts.Load(accountName); ok { |
| 1319 |
ase = &asubs{acc: v.(*Account), subs: []*subscription{sub}} |
| 1320 |
as[accountName] = ase |
| 1321 |
} else { |
| 1322 |
continue |
| 1323 |
} |
| 1324 |
} else { |
| 1325 |
ase.subs = append(ase.subs, sub) |
| 1326 |
} |
| 1327 |
delta := int32(1) |
| 1328 |
if len(sub.queue) > 0 { |
| 1329 |
delta = sub.qw |
| 1330 |
} |
| 1331 |
if srv.gateway.enabled { |
| 1332 |
srv.gatewayUpdateSubInterest(accountName, sub, -delta) |
| 1333 |
} |
| 1334 |
ase.acc.updateLeafNodes(sub, -delta) |
| 1335 |
} |
| 1336 |
|
| 1337 |
// Now remove the subs by batch for each account sublist. |
| 1338 |
for _, ase := range as { |
| 1339 |
c.Debugf("Removing %d subscriptions for account %q", len(ase.subs), ase.acc.Name) |
| 1340 |
ase.acc.mu.Lock() |
| 1341 |
ase.acc.sl.RemoveBatch(ase.subs) |
| 1342 |
ase.acc.mu.Unlock() |
| 1343 |
} |
| 1344 |
} |
| 1345 |
|
| 1346 |
// Removes (and returns) the subscriptions from this route's subscriptions map |
| 1347 |
// that belong to the given account. |
| 1348 |
// Lock is held on entry |
| 1349 |
func (c *client) removeRemoteSubsForAcc(name string) []*subscription { |
| 1350 |
var subs []*subscription |
| 1351 |
_, _, hasSubType := c.getRoutedSubKeyInfo() |
| 1352 |
for key, sub := range c.subs { |
| 1353 |
an := getAccNameFromRoutedSubKey(sub, key, hasSubType) |
| 1354 |
if an == name { |
| 1355 |
sub.max = 0 |
| 1356 |
subs = append(subs, sub) |
| 1357 |
delete(c.subs, key) |
| 1358 |
} |
| 1359 |
} |
| 1360 |
return subs |
| 1361 |
} |
| 1362 |
|
| 1363 |
func (c *client) parseUnsubProto(arg []byte, accInProto, hasOrigin bool) ([]byte, string, []byte, []byte, error) { |
| 1364 |
// Indicate any activity, so pub and sub or unsubs. |
| 1365 |
c.in.subs++ |
| 1366 |
|
| 1367 |
args := splitArg(arg) |
| 1368 |
|
| 1369 |
var ( |
| 1370 |
origin []byte |
| 1371 |
accountName string |
| 1372 |
queue []byte |
| 1373 |
subjIdx int |
| 1374 |
) |
| 1375 |
// If `hasOrigin` is true, then it means this is a LS- with origin in proto. |
| 1376 |
if hasOrigin { |
| 1377 |
// We would not be here if there was not at least 1 field. |
| 1378 |
origin = args[0] |
| 1379 |
subjIdx = 1 |
| 1380 |
} |
| 1381 |
// If there is an account in the protocol, bump the subject index. |
| 1382 |
if accInProto { |
| 1383 |
subjIdx++ |
| 1384 |
} |
| 1385 |
|
| 1386 |
switch len(args) { |
| 1387 |
case subjIdx + 1: |
| 1388 |
case subjIdx + 2: |
| 1389 |
queue = args[subjIdx+1] |
| 1390 |
default: |
| 1391 |
return nil, _EMPTY_, nil, nil, fmt.Errorf("parse error: '%s'", arg) |
| 1392 |
} |
| 1393 |
if accInProto { |
| 1394 |
// If there is an account in the protocol, it is before the subject. |
| 1395 |
accountName = string(args[subjIdx-1]) |
| 1396 |
} |
| 1397 |
return origin, accountName, args[subjIdx], queue, nil |
| 1398 |
} |
| 1399 |
|
| 1400 |
// Indicates no more interest in the given account/subject for the remote side. |
| 1401 |
func (c *client) processRemoteUnsub(arg []byte, leafUnsub bool) (err error) { |
| 1402 |
srv := c.srv |
| 1403 |
if srv == nil { |
| 1404 |
return nil |
| 1405 |
} |
| 1406 |
|
| 1407 |
var accountName string |
| 1408 |
// Assume the account will be in the protocol. |
| 1409 |
accInProto := true |
| 1410 |
|
| 1411 |
c.mu.Lock() |
| 1412 |
originSupport := c.route.lnocu |
| 1413 |
if c.route != nil && len(c.route.accName) > 0 { |
| 1414 |
accountName, accInProto = string(c.route.accName), false |
| 1415 |
} |
| 1416 |
c.mu.Unlock() |
| 1417 |
|
| 1418 |
hasOrigin := leafUnsub && originSupport |
| 1419 |
_, accNameFromProto, subject, _, err := c.parseUnsubProto(arg, accInProto, hasOrigin) |
| 1420 |
if err != nil { |
| 1421 |
return fmt.Errorf("processRemoteUnsub %s", err.Error()) |
| 1422 |
} |
| 1423 |
if accInProto { |
| 1424 |
accountName = accNameFromProto |
| 1425 |
} |
| 1426 |
// Lookup the account |
| 1427 |
var acc *Account |
| 1428 |
if v, ok := srv.accounts.Load(accountName); ok { |
| 1429 |
acc = v.(*Account) |
| 1430 |
} else { |
| 1431 |
c.Debugf("Unknown account %q for subject %q", accountName, subject) |
| 1432 |
return nil |
| 1433 |
} |
| 1434 |
|
| 1435 |
c.mu.Lock() |
| 1436 |
if c.isClosed() { |
| 1437 |
c.mu.Unlock() |
| 1438 |
return nil |
| 1439 |
} |
| 1440 |
|
| 1441 |
_keya := [128]byte{} |
| 1442 |
_key := _keya[:0] |
| 1443 |
|
| 1444 |
var key string |
| 1445 |
if !originSupport { |
| 1446 |
// If it is an LS- or RS-, we use the protocol as-is as the key. |
| 1447 |
key = bytesToString(arg) |
| 1448 |
} else { |
| 1449 |
// We need to prefix with the sub type. |
| 1450 |
if leafUnsub { |
| 1451 |
_key = append(_key, keyRoutedLeafSubByte) |
| 1452 |
} else { |
| 1453 |
_key = append(_key, keyRoutedSubByte) |
| 1454 |
} |
| 1455 |
_key = append(_key, ' ') |
| 1456 |
_key = append(_key, arg...) |
| 1457 |
key = bytesToString(_key) |
| 1458 |
} |
| 1459 |
delta := int32(1) |
| 1460 |
sub, ok := c.subs[key] |
| 1461 |
if ok { |
| 1462 |
delete(c.subs, key) |
| 1463 |
acc.sl.Remove(sub) |
| 1464 |
if len(sub.queue) > 0 { |
| 1465 |
delta = sub.qw |
| 1466 |
} |
| 1467 |
} |
| 1468 |
c.mu.Unlock() |
| 1469 |
|
| 1470 |
// Update gateways and leaf nodes only if the subscription was found. |
| 1471 |
if ok { |
| 1472 |
if srv.gateway.enabled { |
| 1473 |
srv.gatewayUpdateSubInterest(accountName, sub, -delta) |
| 1474 |
} |
| 1475 |
|
| 1476 |
// Now check on leafnode updates. |
| 1477 |
acc.updateLeafNodes(sub, -delta) |
| 1478 |
} |
| 1479 |
|
| 1480 |
if c.opts.Verbose { |
| 1481 |
c.sendOK() |
| 1482 |
} |
| 1483 |
return nil |
| 1484 |
} |
| 1485 |
|
| 1486 |
func (c *client) processRemoteSub(argo []byte, hasOrigin bool) (err error) { |
| 1487 |
// Indicate activity. |
| 1488 |
c.in.subs++ |
| 1489 |
|
| 1490 |
srv := c.srv |
| 1491 |
if srv == nil { |
| 1492 |
return nil |
| 1493 |
} |
| 1494 |
|
| 1495 |
// We copy `argo` to not reference the read buffer. However, we will |
| 1496 |
// prefix with a code that says if the remote sub is for a leaf |
| 1497 |
// (hasOrigin == true) or not to prevent key collisions. Imagine: |
| 1498 |
// "RS+ foo bar baz 1\r\n" => "foo bar baz" (a routed queue sub) |
| 1499 |
// "LS+ foo bar baz\r\n" => "foo bar baz" (a route leaf sub on "baz", |
| 1500 |
// for account "bar" with origin "foo"). |
| 1501 |
// |
| 1502 |
// The sub.sid/key will be set respectively to "R foo bar baz" and |
| 1503 |
// "L foo bar baz". |
| 1504 |
// |
| 1505 |
// We also no longer add the account if it was not present (due to |
| 1506 |
// pinned-account route) since there is no need really. |
| 1507 |
// |
| 1508 |
// For routes to older server, we will still create the "arg" with |
| 1509 |
// the above layout, but we will create the sub.sid/key as before, |
| 1510 |
// that is, not including the origin for LS+ because older server |
| 1511 |
// only send LS- without origin, so we would not be able to find |
| 1512 |
// the sub in the map. |
| 1513 |
c.mu.Lock() |
| 1514 |
accountName := string(c.route.accName) |
| 1515 |
oldStyle := !c.route.lnocu |
| 1516 |
c.mu.Unlock() |
| 1517 |
|
| 1518 |
// Indicate if the account name should be in the protocol. It would be the |
| 1519 |
// case if accountName is empty. |
| 1520 |
accInProto := accountName == _EMPTY_ |
| 1521 |
|
| 1522 |
// Copy so we do not reference a potentially large buffer. |
| 1523 |
// Add 2 more bytes for the routed sub type. |
| 1524 |
arg := make([]byte, 0, 2+len(argo)) |
| 1525 |
if hasOrigin { |
| 1526 |
arg = append(arg, keyRoutedLeafSubByte) |
| 1527 |
} else { |
| 1528 |
arg = append(arg, keyRoutedSubByte) |
| 1529 |
} |
| 1530 |
arg = append(arg, ' ') |
| 1531 |
arg = append(arg, argo...) |
| 1532 |
|
| 1533 |
// Now split to get all fields. Unroll splitArgs to avoid runtime/heap issues. |
| 1534 |
a := [MAX_RSUB_ARGS][]byte{} |
| 1535 |
args := a[:0] |
| 1536 |
start := -1 |
| 1537 |
for i, b := range arg { |
| 1538 |
switch b { |
| 1539 |
case ' ', '\t', '\r', '\n': |
| 1540 |
if start >= 0 { |
| 1541 |
args = append(args, arg[start:i]) |
| 1542 |
start = -1 |
| 1543 |
} |
| 1544 |
default: |
| 1545 |
if start < 0 { |
| 1546 |
start = i |
| 1547 |
} |
| 1548 |
} |
| 1549 |
} |
| 1550 |
if start >= 0 { |
| 1551 |
args = append(args, arg[start:]) |
| 1552 |
} |
| 1553 |
|
| 1554 |
delta := int32(1) |
| 1555 |
sub := &subscription{client: c} |
| 1556 |
|
| 1557 |
// There will always be at least a subject, but its location will depend |
| 1558 |
// on if there is an origin, an account name, etc.. Since we know that |
| 1559 |
// we have added the sub type indicator as the first field, the subject |
| 1560 |
// position will be at minimum at index 1. |
| 1561 |
subjIdx := 1 |
| 1562 |
if hasOrigin { |
| 1563 |
subjIdx++ |
| 1564 |
} |
| 1565 |
if accInProto { |
| 1566 |
subjIdx++ |
| 1567 |
} |
| 1568 |
switch len(args) { |
| 1569 |
case subjIdx + 1: |
| 1570 |
sub.queue = nil |
| 1571 |
case subjIdx + 3: |
| 1572 |
sub.queue = args[subjIdx+1] |
| 1573 |
sub.qw = int32(parseSize(args[subjIdx+2])) |
| 1574 |
// TODO: (ik) We should have a non empty queue name and a queue |
| 1575 |
// weight >= 1. For 2.11, we may want to return an error if that |
| 1576 |
// is not the case, but for now just overwrite `delta` if queue |
| 1577 |
// weight is greater than 1 (it is possible after a reconnect/ |
| 1578 |
// server restart to receive a queue weight > 1 for a new sub). |
| 1579 |
if sub.qw > 1 { |
| 1580 |
delta = sub.qw |
| 1581 |
} |
| 1582 |
default: |
| 1583 |
return fmt.Errorf("processRemoteSub Parse Error: '%s'", arg) |
| 1584 |
} |
| 1585 |
// We know that the number of fields is correct. So we can access args[] based |
| 1586 |
// on where we expect the fields to be. |
| 1587 |
|
| 1588 |
// If there is an origin, it will be at index 1. |
| 1589 |
if hasOrigin { |
| 1590 |
sub.origin = args[1] |
| 1591 |
} |
| 1592 |
// For subject, use subjIdx. |
| 1593 |
sub.subject = args[subjIdx] |
| 1594 |
// If the account name is in the protocol, it will be before the subject. |
| 1595 |
if accInProto { |
| 1596 |
accountName = bytesToString(args[subjIdx-1]) |
| 1597 |
} |
| 1598 |
// Now set the sub.sid from the arg slice. However, we will have a different |
| 1599 |
// one if we use the origin or not. |
| 1600 |
start = 0 |
| 1601 |
end := len(arg) |
| 1602 |
if sub.queue != nil { |
| 1603 |
// Remove the ' <weight>' from the arg length. |
| 1604 |
end -= 1 + len(args[subjIdx+2]) |
| 1605 |
} |
| 1606 |
if oldStyle { |
| 1607 |
// We will start at the account (if present) or at the subject. |
| 1608 |
// We first skip the "R " or "L " |
| 1609 |
start = 2 |
| 1610 |
// And if there is an origin skip that. |
| 1611 |
if hasOrigin { |
| 1612 |
start += len(sub.origin) + 1 |
| 1613 |
} |
| 1614 |
// Here we are pointing at the account (if present), or at the subject. |
| 1615 |
} |
| 1616 |
sub.sid = arg[start:end] |
| 1617 |
|
| 1618 |
// Lookup account while avoiding fetch. |
| 1619 |
// A slow fetch delays subsequent remote messages. It also avoids the expired check (see below). |
| 1620 |
// With all but memory resolver lookup can be delayed or fail. |
| 1621 |
// It is also possible that the account can't be resolved yet. |
| 1622 |
// This does not apply to the memory resolver. |
| 1623 |
// When used, perform the fetch. |
| 1624 |
staticResolver := true |
| 1625 |
if res := srv.AccountResolver(); res != nil { |
| 1626 |
if _, ok := res.(*MemAccResolver); !ok { |
| 1627 |
staticResolver = false |
| 1628 |
} |
| 1629 |
} |
| 1630 |
var acc *Account |
| 1631 |
if staticResolver { |
| 1632 |
acc, _ = srv.LookupAccount(accountName) |
| 1633 |
} else if v, ok := srv.accounts.Load(accountName); ok { |
| 1634 |
acc = v.(*Account) |
| 1635 |
} |
| 1636 |
if acc == nil { |
| 1637 |
// if the option of retrieving accounts later exists, create an expired one. |
| 1638 |
// When a client comes along, expiration will prevent it from being used, |
| 1639 |
// cause a fetch and update the account to what is should be. |
| 1640 |
if staticResolver { |
| 1641 |
c.Errorf("Unknown account %q for remote subject %q", accountName, sub.subject) |
| 1642 |
return |
| 1643 |
} |
| 1644 |
c.Debugf("Unknown account %q for remote subject %q", accountName, sub.subject) |
| 1645 |
|
| 1646 |
var isNew bool |
| 1647 |
if acc, isNew = srv.LookupOrRegisterAccount(accountName); isNew { |
| 1648 |
acc.mu.Lock() |
| 1649 |
acc.expired.Store(true) |
| 1650 |
acc.incomplete = true |
| 1651 |
acc.mu.Unlock() |
| 1652 |
} |
| 1653 |
} |
| 1654 |
|
| 1655 |
c.mu.Lock() |
| 1656 |
if c.isClosed() { |
| 1657 |
c.mu.Unlock() |
| 1658 |
return nil |
| 1659 |
} |
| 1660 |
|
| 1661 |
// Check permissions if applicable. |
| 1662 |
if c.perms != nil && !c.canExport(string(sub.subject)) { |
| 1663 |
c.mu.Unlock() |
| 1664 |
c.Debugf("Can not export %q, ignoring remote subscription request", sub.subject) |
| 1665 |
return nil |
| 1666 |
} |
| 1667 |
|
| 1668 |
// Check if we have a maximum on the number of subscriptions. |
| 1669 |
if c.subsAtLimit() { |
| 1670 |
c.mu.Unlock() |
| 1671 |
c.maxSubsExceeded() |
| 1672 |
return nil |
| 1673 |
} |
| 1674 |
|
| 1675 |
acc.mu.RLock() |
| 1676 |
// For routes (this can be called by leafnodes), check if the account is |
| 1677 |
// transitioning (from pool to dedicated route) and this route is not a |
| 1678 |
// per-account route (route.poolIdx >= 0). If so, ignore this subscription. |
| 1679 |
// Exclude "no pool" routes from this check. |
| 1680 |
if c.kind == ROUTER && !c.route.noPool && |
| 1681 |
acc.routePoolIdx == accTransitioningToDedicatedRoute && c.route.poolIdx >= 0 { |
| 1682 |
acc.mu.RUnlock() |
| 1683 |
c.mu.Unlock() |
| 1684 |
// Do not return an error, which would cause the connection to be closed. |
| 1685 |
return nil |
| 1686 |
} |
| 1687 |
sl := acc.sl |
| 1688 |
acc.mu.RUnlock() |
| 1689 |
|
| 1690 |
// We use the sub.sid for the key of the c.subs map. |
| 1691 |
key := bytesToString(sub.sid) |
| 1692 |
osub := c.subs[key] |
| 1693 |
if osub == nil { |
| 1694 |
c.subs[key] = sub |
| 1695 |
// Now place into the account sl. |
| 1696 |
if err = sl.Insert(sub); err != nil { |
| 1697 |
delete(c.subs, key) |
| 1698 |
c.mu.Unlock() |
| 1699 |
c.Errorf("Could not insert subscription: %v", err) |
| 1700 |
c.sendErr("Invalid Subscription") |
| 1701 |
return nil |
| 1702 |
} |
| 1703 |
} else if sub.queue != nil { |
| 1704 |
// For a queue we need to update the weight. |
| 1705 |
delta = sub.qw - atomic.LoadInt32(&osub.qw) |
| 1706 |
atomic.StoreInt32(&osub.qw, sub.qw) |
| 1707 |
sl.UpdateRemoteQSub(osub) |
| 1708 |
} |
| 1709 |
c.mu.Unlock() |
| 1710 |
|
| 1711 |
if srv.gateway.enabled { |
| 1712 |
srv.gatewayUpdateSubInterest(acc.Name, sub, delta) |
| 1713 |
} |
| 1714 |
|
| 1715 |
// Now check on leafnode updates. |
| 1716 |
acc.updateLeafNodes(sub, delta) |
| 1717 |
|
| 1718 |
if c.opts.Verbose { |
| 1719 |
c.sendOK() |
| 1720 |
} |
| 1721 |
|
| 1722 |
return nil |
| 1723 |
} |
| 1724 |
|
| 1725 |
// Lock is held on entry |
| 1726 |
func (c *client) addRouteSubOrUnsubProtoToBuf(buf []byte, accName string, sub *subscription, isSubProto bool) []byte { |
| 1727 |
// If we have an origin cluster and the other side supports leafnode origin clusters |
| 1728 |
// send an LS+/LS- version instead. |
| 1729 |
if len(sub.origin) > 0 && c.route.lnoc { |
| 1730 |
if isSubProto { |
| 1731 |
buf = append(buf, lSubBytes...) |
| 1732 |
buf = append(buf, sub.origin...) |
| 1733 |
buf = append(buf, ' ') |
| 1734 |
} else { |
| 1735 |
buf = append(buf, lUnsubBytes...) |
| 1736 |
if c.route.lnocu { |
| 1737 |
buf = append(buf, sub.origin...) |
| 1738 |
buf = append(buf, ' ') |
| 1739 |
} |
| 1740 |
} |
| 1741 |
} else { |
| 1742 |
if isSubProto { |
| 1743 |
buf = append(buf, rSubBytes...) |
| 1744 |
} else { |
| 1745 |
buf = append(buf, rUnsubBytes...) |
| 1746 |
} |
| 1747 |
} |
| 1748 |
if len(c.route.accName) == 0 { |
| 1749 |
buf = append(buf, accName...) |
| 1750 |
buf = append(buf, ' ') |
| 1751 |
} |
| 1752 |
buf = append(buf, sub.subject...) |
| 1753 |
if len(sub.queue) > 0 { |
| 1754 |
buf = append(buf, ' ') |
| 1755 |
buf = append(buf, sub.queue...) |
| 1756 |
// Send our weight if we are a sub proto |
| 1757 |
if isSubProto { |
| 1758 |
buf = append(buf, ' ') |
| 1759 |
var b [12]byte |
| 1760 |
var i = len(b) |
| 1761 |
for l := sub.qw; l > 0; l /= 10 { |
| 1762 |
i-- |
| 1763 |
b[i] = digits[l%10] |
| 1764 |
} |
| 1765 |
buf = append(buf, b[i:]...) |
| 1766 |
} |
| 1767 |
} |
| 1768 |
buf = append(buf, CR_LF...) |
| 1769 |
return buf |
| 1770 |
} |
| 1771 |
|
| 1772 |
// sendSubsToRoute will send over our subject interest to |
| 1773 |
// the remote side. For each account we will send the |
| 1774 |
// complete interest for all subjects, both normal as a binary |
| 1775 |
// and queue group weights. |
| 1776 |
// |
| 1777 |
// Server lock held on entry. |
| 1778 |
func (s *Server) sendSubsToRoute(route *client, idx int, account string) { |
| 1779 |
var noPool bool |
| 1780 |
if idx >= 0 { |
| 1781 |
// We need to check if this route is "no_pool" in which case we |
| 1782 |
// need to select all accounts. |
| 1783 |
route.mu.Lock() |
| 1784 |
noPool = route.route.noPool |
| 1785 |
route.mu.Unlock() |
| 1786 |
} |
| 1787 |
// Estimated size of all protocols. It does not have to be accurate at all. |
| 1788 |
var eSize int |
| 1789 |
estimateProtosSize := func(a *Account, addAccountName bool) { |
| 1790 |
if ns := len(a.rm); ns > 0 { |
| 1791 |
var accSize int |
| 1792 |
if addAccountName { |
| 1793 |
accSize = len(a.Name) + 1 |
| 1794 |
} |
| 1795 |
// Proto looks like: "RS+ [<account name> ]<subject>[ <queue> <weight>]\r\n" |
| 1796 |
eSize += ns * (len(rSubBytes) + 1 + accSize) |
| 1797 |
for key := range a.rm { |
| 1798 |
// Key contains "<subject>[ <queue>]" |
| 1799 |
eSize += len(key) |
| 1800 |
// In case this is a queue, just add some bytes for the queue weight. |
| 1801 |
// If we want to be accurate, would have to check if "key" has a space, |
| 1802 |
// if so, then figure out how many bytes we need to represent the weight. |
| 1803 |
eSize += 5 |
| 1804 |
} |
| 1805 |
} |
| 1806 |
} |
| 1807 |
// Send over our account subscriptions. |
| 1808 |
accs := make([]*Account, 0, 1024) |
| 1809 |
if idx < 0 || account != _EMPTY_ { |
| 1810 |
if ai, ok := s.accounts.Load(account); ok { |
| 1811 |
a := ai.(*Account) |
| 1812 |
a.mu.RLock() |
| 1813 |
// Estimate size and add account name in protocol if idx is not -1 |
| 1814 |
estimateProtosSize(a, idx >= 0) |
| 1815 |
accs = append(accs, a) |
| 1816 |
a.mu.RUnlock() |
| 1817 |
} |
| 1818 |
} else { |
| 1819 |
s.accounts.Range(func(k, v any) bool { |
| 1820 |
a := v.(*Account) |
| 1821 |
a.mu.RLock() |
| 1822 |
// We are here for regular or pooled routes (not per-account). |
| 1823 |
// So we collect all accounts whose routePoolIdx matches the |
| 1824 |
// one for this route, or only the account provided, or all |
| 1825 |
// accounts if dealing with a "no pool" route. |
| 1826 |
if a.routePoolIdx == idx || noPool { |
| 1827 |
estimateProtosSize(a, true) |
| 1828 |
accs = append(accs, a) |
| 1829 |
} |
| 1830 |
a.mu.RUnlock() |
| 1831 |
return true |
| 1832 |
}) |
| 1833 |
} |
| 1834 |
|
| 1835 |
buf := make([]byte, 0, eSize) |
| 1836 |
|
| 1837 |
route.mu.Lock() |
| 1838 |
for _, a := range accs { |
| 1839 |
a.mu.RLock() |
| 1840 |
for key, n := range a.rm { |
| 1841 |
var origin, qn []byte |
| 1842 |
s := strings.Fields(key) |
| 1843 |
// Subject will always be the second field (index 1). |
| 1844 |
subj := stringToBytes(s[1]) |
| 1845 |
// Check if the key is for a leaf (will be field 0). |
| 1846 |
forLeaf := s[0] == keyRoutedLeafSub |
| 1847 |
// For queue, if not for a leaf, we need 3 fields "R foo bar", |
| 1848 |
// but if for a leaf, we need 4 fields "L foo bar leaf_origin". |
| 1849 |
if l := len(s); (!forLeaf && l == 3) || (forLeaf && l == 4) { |
| 1850 |
qn = stringToBytes(s[2]) |
| 1851 |
} |
| 1852 |
if forLeaf { |
| 1853 |
// The leaf origin will be the last field. |
| 1854 |
origin = stringToBytes(s[len(s)-1]) |
| 1855 |
} |
| 1856 |
// s[1] is the subject and already as a string, so use that |
| 1857 |
// instead of converting back `subj` to a string. |
| 1858 |
if !route.canImport(s[1]) { |
| 1859 |
continue |
| 1860 |
} |
| 1861 |
sub := subscription{origin: origin, subject: subj, queue: qn, qw: n} |
| 1862 |
buf = route.addRouteSubOrUnsubProtoToBuf(buf, a.Name, &sub, true) |
| 1863 |
} |
| 1864 |
a.mu.RUnlock() |
| 1865 |
} |
| 1866 |
if len(buf) > 0 { |
| 1867 |
route.enqueueProto(buf) |
| 1868 |
route.Debugf("Sent local subscriptions to route") |
| 1869 |
} |
| 1870 |
route.mu.Unlock() |
| 1871 |
} |
| 1872 |
|
| 1873 |
// Sends SUBs protocols for the given subscriptions. If a filter is specified, it is |
| 1874 |
// invoked for each subscription. If the filter returns false, the subscription is skipped. |
| 1875 |
// This function may release the route's lock due to flushing of outbound data. A boolean |
| 1876 |
// is returned to indicate if the connection has been closed during this call. |
| 1877 |
// Lock is held on entry. |
| 1878 |
func (c *client) sendRouteSubProtos(subs []*subscription, trace bool, filter func(sub *subscription) bool) { |
| 1879 |
c.sendRouteSubOrUnSubProtos(subs, true, trace, filter) |
| 1880 |
} |
| 1881 |
|
| 1882 |
// Sends UNSUBs protocols for the given subscriptions. If a filter is specified, it is |
| 1883 |
// invoked for each subscription. If the filter returns false, the subscription is skipped. |
| 1884 |
// This function may release the route's lock due to flushing of outbound data. A boolean |
| 1885 |
// is returned to indicate if the connection has been closed during this call. |
| 1886 |
// Lock is held on entry. |
| 1887 |
func (c *client) sendRouteUnSubProtos(subs []*subscription, trace bool, filter func(sub *subscription) bool) { |
| 1888 |
c.sendRouteSubOrUnSubProtos(subs, false, trace, filter) |
| 1889 |
} |
| 1890 |
|
| 1891 |
// Low-level function that sends RS+ or RS- protocols for the given subscriptions. |
| 1892 |
// This can now also send LS+ and LS- for origin cluster based leafnode subscriptions for cluster no-echo. |
| 1893 |
// Use sendRouteSubProtos or sendRouteUnSubProtos instead for clarity. |
| 1894 |
// Lock is held on entry. |
| 1895 |
func (c *client) sendRouteSubOrUnSubProtos(subs []*subscription, isSubProto, trace bool, filter func(sub *subscription) bool) { |
| 1896 |
var ( |
| 1897 |
_buf [1024]byte |
| 1898 |
buf = _buf[:0] |
| 1899 |
) |
| 1900 |
|
| 1901 |
for _, sub := range subs { |
| 1902 |
if filter != nil && !filter(sub) { |
| 1903 |
continue |
| 1904 |
} |
| 1905 |
// Determine the account. If sub has an ImportMap entry, use that, otherwise scoped to |
| 1906 |
// client. Default to global if all else fails. |
| 1907 |
var accName string |
| 1908 |
if sub.client != nil && sub.client != c { |
| 1909 |
sub.client.mu.Lock() |
| 1910 |
} |
| 1911 |
if sub.im != nil { |
| 1912 |
accName = sub.im.acc.Name |
| 1913 |
} else if sub.client != nil && sub.client.acc != nil { |
| 1914 |
accName = sub.client.acc.Name |
| 1915 |
} else { |
| 1916 |
c.Debugf("Falling back to default account for sending subs") |
| 1917 |
accName = globalAccountName |
| 1918 |
} |
| 1919 |
if sub.client != nil && sub.client != c { |
| 1920 |
sub.client.mu.Unlock() |
| 1921 |
} |
| 1922 |
|
| 1923 |
as := len(buf) |
| 1924 |
buf = c.addRouteSubOrUnsubProtoToBuf(buf, accName, sub, isSubProto) |
| 1925 |
if trace { |
| 1926 |
c.traceOutOp("", buf[as:len(buf)-LEN_CR_LF]) |
| 1927 |
} |
| 1928 |
} |
| 1929 |
c.enqueueProto(buf) |
| 1930 |
} |
| 1931 |
|
| 1932 |
func (s *Server) createRoute(conn net.Conn, rURL *url.URL, rtype RouteType, gossipMode byte, accName string) *client { |
| 1933 |
// Snapshot server options. |
| 1934 |
opts := s.getOpts() |
| 1935 |
|
| 1936 |
didSolicit := rURL != nil |
| 1937 |
r := &route{routeType: rtype, didSolicit: didSolicit, poolIdx: -1, gossipMode: gossipMode} |
| 1938 |
|
| 1939 |
c := &client{srv: s, nc: conn, opts: ClientOpts{}, kind: ROUTER, msubs: -1, mpay: -1, route: r, start: time.Now()} |
| 1940 |
|
| 1941 |
// Is the server configured for compression? |
| 1942 |
compressionConfigured := needsCompression(opts.Cluster.Compression.Mode) |
| 1943 |
|
| 1944 |
var infoJSON []byte |
| 1945 |
// Grab server variables and generates route INFO Json. Note that we set |
| 1946 |
// and reset some of s.routeInfo fields when that happens, so we need |
| 1947 |
// the server write lock. |
| 1948 |
s.mu.Lock() |
| 1949 |
// If we are creating a pooled connection and this is the server soliciting |
| 1950 |
// the connection, we will delay sending the INFO after we have processed |
| 1951 |
// the incoming INFO from the remote. Also delay if configured for compression. |
| 1952 |
delayInfo := didSolicit && (compressionConfigured || routeShouldDelayInfo(accName, opts)) |
| 1953 |
if !delayInfo { |
| 1954 |
infoJSON = s.generateRouteInitialInfoJSON(accName, opts.Cluster.Compression.Mode, 0, gossipMode) |
| 1955 |
} |
| 1956 |
authRequired := s.routeInfo.AuthRequired |
| 1957 |
tlsRequired := s.routeInfo.TLSRequired |
| 1958 |
clusterName := s.info.Cluster |
| 1959 |
tlsName := s.routeTLSName |
| 1960 |
s.mu.Unlock() |
| 1961 |
|
| 1962 |
// Grab lock |
| 1963 |
c.mu.Lock() |
| 1964 |
|
| 1965 |
// Initialize |
| 1966 |
c.initClient() |
| 1967 |
|
| 1968 |
if didSolicit { |
| 1969 |
// Do this before the TLS code, otherwise, in case of failure |
| 1970 |
// and if route is explicit, it would try to reconnect to 'nil'... |
| 1971 |
r.url = rURL |
| 1972 |
r.accName = []byte(accName) |
| 1973 |
} else { |
| 1974 |
c.flags.set(expectConnect) |
| 1975 |
} |
| 1976 |
|
| 1977 |
// Check for TLS |
| 1978 |
if tlsRequired { |
| 1979 |
tlsConfig := opts.Cluster.TLSConfig |
| 1980 |
if didSolicit { |
| 1981 |
// Copy off the config to add in ServerName if we need to. |
| 1982 |
tlsConfig = tlsConfig.Clone() |
| 1983 |
} |
| 1984 |
// Perform (server or client side) TLS handshake. |
| 1985 |
if resetTLSName, err := c.doTLSHandshake("route", didSolicit, rURL, tlsConfig, tlsName, opts.Cluster.TLSTimeout, opts.Cluster.TLSPinnedCerts); err != nil { |
| 1986 |
c.mu.Unlock() |
| 1987 |
if resetTLSName { |
| 1988 |
s.mu.Lock() |
| 1989 |
s.routeTLSName = _EMPTY_ |
| 1990 |
s.mu.Unlock() |
| 1991 |
} |
| 1992 |
return nil |
| 1993 |
} |
| 1994 |
} |
| 1995 |
|
| 1996 |
// Do final client initialization |
| 1997 |
|
| 1998 |
// Initialize the per-account cache. |
| 1999 |
c.in.pacache = make(map[string]*perAccountCache) |
| 2000 |
if didSolicit { |
| 2001 |
// Set permissions associated with the route user (if applicable). |
| 2002 |
// No lock needed since we are already under client lock. |
| 2003 |
c.setRoutePermissions(opts.Cluster.Permissions) |
| 2004 |
} |
| 2005 |
|
| 2006 |
// We can't safely send the pings until we have negotiated compression |
| 2007 |
// with the remote, but we want to protect against a connection that |
| 2008 |
// does not perform the handshake. We will start a timer that will close |
| 2009 |
// the connection as stale based on the ping interval and max out values, |
| 2010 |
// but without actually sending pings. |
| 2011 |
if compressionConfigured { |
| 2012 |
pingInterval := opts.PingInterval |
| 2013 |
pingMax := opts.MaxPingsOut |
| 2014 |
if opts.Cluster.PingInterval > 0 { |
| 2015 |
pingInterval = opts.Cluster.PingInterval |
| 2016 |
} |
| 2017 |
if opts.Cluster.MaxPingsOut > 0 { |
| 2018 |
pingMax = opts.Cluster.MaxPingsOut |
| 2019 |
} |
| 2020 |
c.watchForStaleConnection(adjustPingInterval(ROUTER, pingInterval), pingMax) |
| 2021 |
} else { |
| 2022 |
// Set the Ping timer |
| 2023 |
c.setFirstPingTimer() |
| 2024 |
} |
| 2025 |
|
| 2026 |
// For routes, the "client" is added to s.routes only when processing |
| 2027 |
// the INFO protocol, that is much later. |
| 2028 |
// In the meantime, if the server shutsdown, there would be no reference |
| 2029 |
// to the client (connection) to be closed, leaving this readLoop |
| 2030 |
// uinterrupted, causing the Shutdown() to wait indefinitively. |
| 2031 |
// We need to store the client in a special map, under a special lock. |
| 2032 |
if !s.addToTempClients(c.cid, c) { |
| 2033 |
c.mu.Unlock() |
| 2034 |
c.setNoReconnect() |
| 2035 |
c.closeConnection(ServerShutdown) |
| 2036 |
return nil |
| 2037 |
} |
| 2038 |
|
| 2039 |
// Check for Auth required state for incoming connections. |
| 2040 |
// Make sure to do this before spinning up readLoop. |
| 2041 |
if authRequired && !didSolicit { |
| 2042 |
ttl := secondsToDuration(opts.Cluster.AuthTimeout) |
| 2043 |
c.setAuthTimer(ttl) |
| 2044 |
} |
| 2045 |
|
| 2046 |
// Spin up the read loop. |
| 2047 |
s.startGoRoutine(func() { c.readLoop(nil) }) |
| 2048 |
|
| 2049 |
// Spin up the write loop. |
| 2050 |
s.startGoRoutine(func() { c.writeLoop() }) |
| 2051 |
|
| 2052 |
if tlsRequired { |
| 2053 |
c.Debugf("TLS handshake complete") |
| 2054 |
cs := c.nc.(*tls.Conn).ConnectionState() |
| 2055 |
c.Debugf("TLS version %s, cipher suite %s", tlsVersion(cs.Version), tls.CipherSuiteName(cs.CipherSuite)) |
| 2056 |
} |
| 2057 |
|
| 2058 |
// Queue Connect proto if we solicited the connection. |
| 2059 |
if didSolicit { |
| 2060 |
c.Debugf("Route connect msg sent") |
| 2061 |
if err := c.sendRouteConnect(clusterName, tlsRequired); err != nil { |
| 2062 |
c.mu.Unlock() |
| 2063 |
c.closeConnection(ProtocolViolation) |
| 2064 |
return nil |
| 2065 |
} |
| 2066 |
} |
| 2067 |
|
| 2068 |
if !delayInfo { |
| 2069 |
// Send our info to the other side. |
| 2070 |
// Our new version requires dynamic information for accounts and a nonce. |
| 2071 |
c.enqueueProto(infoJSON) |
| 2072 |
} |
| 2073 |
c.mu.Unlock() |
| 2074 |
|
| 2075 |
c.Noticef("Route connection created") |
| 2076 |
return c |
| 2077 |
} |
| 2078 |
|
| 2079 |
func routeShouldDelayInfo(accName string, opts *Options) bool { |
| 2080 |
return accName == _EMPTY_ && opts.Cluster.PoolSize >= 1 |
| 2081 |
} |
| 2082 |
|
| 2083 |
// Generates a nonce and set some route info's fields before marshal'ing into JSON. |
| 2084 |
// To be used only when a route is created (to send the initial INFO protocol). |
| 2085 |
// |
| 2086 |
// Server lock held on entry. |
| 2087 |
func (s *Server) generateRouteInitialInfoJSON(accName, compression string, poolIdx int, gossipMode byte) []byte { |
| 2088 |
// New proto wants a nonce (although not used in routes, that is, not signed in CONNECT) |
| 2089 |
var raw [nonceLen]byte |
| 2090 |
nonce := raw[:] |
| 2091 |
s.generateNonce(nonce) |
| 2092 |
ri := &s.routeInfo |
| 2093 |
// Override compression with s2_auto instead of actual compression level. |
| 2094 |
if s.getOpts().Cluster.Compression.Mode == CompressionS2Auto { |
| 2095 |
compression = CompressionS2Auto |
| 2096 |
} |
| 2097 |
ri.Nonce, ri.RouteAccount, ri.RoutePoolIdx, ri.Compression, ri.GossipMode = string(nonce), accName, poolIdx, compression, gossipMode |
| 2098 |
infoJSON := generateInfoJSON(&s.routeInfo) |
| 2099 |
// Clear now that it has been serialized. Will prevent nonce to be included in async INFO that we may send. |
| 2100 |
// Same for some other fields. |
| 2101 |
ri.Nonce, ri.RouteAccount, ri.RoutePoolIdx, ri.Compression, ri.GossipMode = _EMPTY_, _EMPTY_, 0, _EMPTY_, 0 |
| 2102 |
return infoJSON |
| 2103 |
} |
| 2104 |
|
| 2105 |
const ( |
| 2106 |
_CRLF_ = "\r\n" |
| 2107 |
_EMPTY_ = "" |
| 2108 |
) |
| 2109 |
|
| 2110 |
func (s *Server) addRoute(c *client, didSolicit, sendDelayedInfo bool, gossipMode byte, info *Info, accName string) bool { |
| 2111 |
id := info.ID |
| 2112 |
|
| 2113 |
var acc *Account |
| 2114 |
if accName != _EMPTY_ { |
| 2115 |
var err error |
| 2116 |
acc, err = s.LookupAccount(accName) |
| 2117 |
if err != nil { |
| 2118 |
c.sendErrAndErr(fmt.Sprintf("Unable to lookup account %q: %v", accName, err)) |
| 2119 |
c.closeConnection(MissingAccount) |
| 2120 |
return false |
| 2121 |
} |
| 2122 |
} |
| 2123 |
|
| 2124 |
s.mu.Lock() |
| 2125 |
if !s.isRunning() || s.routesReject { |
| 2126 |
s.mu.Unlock() |
| 2127 |
return false |
| 2128 |
} |
| 2129 |
var invProtoErr string |
| 2130 |
|
| 2131 |
opts := s.getOpts() |
| 2132 |
|
| 2133 |
// Assume we are in pool mode if info.RoutePoolSize is set. We may disable |
| 2134 |
// in some cases. |
| 2135 |
pool := info.RoutePoolSize > 0 |
| 2136 |
// This is used to prevent a server with pooling to constantly trying |
| 2137 |
// to connect to a server with no pooling (for instance old server) after |
| 2138 |
// the first connection is established. |
| 2139 |
var noReconnectForOldServer bool |
| 2140 |
|
| 2141 |
// To allow rolling updates, we now allow servers with different pool sizes |
| 2142 |
// so we will use as the effective pool size here, the max between our |
| 2143 |
// configured size and the size we receive in the info protocol. |
| 2144 |
effectivePoolSize := max(s.routesPoolSize, info.RoutePoolSize) |
| 2145 |
|
| 2146 |
// If the remote is an old server, info.RoutePoolSize will be 0, or if |
| 2147 |
// this server's Cluster.PoolSize is negative, we will behave as an old |
| 2148 |
// server and need to handle things differently. |
| 2149 |
if info.RoutePoolSize <= 0 || opts.Cluster.PoolSize < 0 { |
| 2150 |
if accName != _EMPTY_ { |
| 2151 |
invProtoErr = fmt.Sprintf("Not possible to have a dedicated route for account %q between those servers", accName) |
| 2152 |
// In this case, make sure this route does not attempt to reconnect |
| 2153 |
c.setNoReconnect() |
| 2154 |
} else { |
| 2155 |
// We will accept, but treat this remote has "no pool" |
| 2156 |
pool, noReconnectForOldServer = false, true |
| 2157 |
c.mu.Lock() |
| 2158 |
c.route.poolIdx = 0 |
| 2159 |
c.route.noPool = true |
| 2160 |
c.mu.Unlock() |
| 2161 |
// Keep track of number of routes like that. We will use that when |
| 2162 |
// sending subscriptions over routes. |
| 2163 |
s.routesNoPool++ |
| 2164 |
} |
| 2165 |
} else if didSolicit { |
| 2166 |
// For solicited route, the incoming's RoutePoolIdx should not be set. |
| 2167 |
if info.RoutePoolIdx != 0 { |
| 2168 |
invProtoErr = fmt.Sprintf("Route pool index should not be set but is set to %v", info.RoutePoolIdx) |
| 2169 |
} |
| 2170 |
} else if info.RoutePoolIdx < 0 || info.RoutePoolIdx >= effectivePoolSize { |
| 2171 |
// For non solicited routes, if the remote sends a RoutePoolIdx, make |
| 2172 |
// sure it is a valid one (in range of the pool size). |
| 2173 |
invProtoErr = fmt.Sprintf("Invalid route pool index: %v - pool size is %v", info.RoutePoolIdx, info.RoutePoolSize) |
| 2174 |
} |
| 2175 |
if invProtoErr != _EMPTY_ { |
| 2176 |
s.mu.Unlock() |
| 2177 |
c.sendErrAndErr(invProtoErr) |
| 2178 |
c.closeConnection(ProtocolViolation) |
| 2179 |
return false |
| 2180 |
} |
| 2181 |
// If accName is set, we are dealing with a per-account connection. |
| 2182 |
if accName != _EMPTY_ { |
| 2183 |
// When an account has its own route, it will be an error if the given |
| 2184 |
// account name is not found in s.accRoutes map. |
| 2185 |
conns, exists := s.accRoutes[accName] |
| 2186 |
if !exists { |
| 2187 |
s.mu.Unlock() |
| 2188 |
c.sendErrAndErr(fmt.Sprintf("No route for account %q", accName)) |
| 2189 |
c.closeConnection(ProtocolViolation) |
| 2190 |
return false |
| 2191 |
} |
| 2192 |
remote, exists := conns[id] |
| 2193 |
if !exists { |
| 2194 |
conns[id] = c |
| 2195 |
c.mu.Lock() |
| 2196 |
idHash := c.route.idHash |
| 2197 |
cid := c.cid |
| 2198 |
rtype := c.route.routeType |
| 2199 |
if sendDelayedInfo { |
| 2200 |
cm := compressionModeForInfoProtocol(&opts.Cluster.Compression, c.route.compression) |
| 2201 |
c.enqueueProto(s.generateRouteInitialInfoJSON(accName, cm, 0, gossipMode)) |
| 2202 |
} |
| 2203 |
if c.last.IsZero() { |
| 2204 |
c.last = time.Now() |
| 2205 |
} |
| 2206 |
if acc != nil { |
| 2207 |
c.acc = acc |
| 2208 |
} |
| 2209 |
c.mu.Unlock() |
| 2210 |
|
| 2211 |
// Store this route with key being the route id hash + account name |
| 2212 |
s.storeRouteByHash(idHash+accName, c) |
| 2213 |
|
| 2214 |
// Now that we have registered the route, we can remove from the temp map. |
| 2215 |
s.removeFromTempClients(cid) |
| 2216 |
|
| 2217 |
// We don't need to send if the only route is the one we just accepted. |
| 2218 |
if len(conns) > 1 { |
| 2219 |
s.forwardNewRouteInfoToKnownServers(info, rtype, didSolicit, gossipMode) |
| 2220 |
} |
| 2221 |
|
| 2222 |
// Send subscription interest |
| 2223 |
s.sendSubsToRoute(c, -1, accName) |
| 2224 |
} else { |
| 2225 |
handleDuplicateRoute(remote, c, true) |
| 2226 |
} |
| 2227 |
s.mu.Unlock() |
| 2228 |
return !exists |
| 2229 |
} |
| 2230 |
var remote *client |
| 2231 |
// That will be the position of the connection in the slice, we initialize |
| 2232 |
// to -1 to indicate that no space was found. |
| 2233 |
idx := -1 |
| 2234 |
// This will be the size (or number of connections) in a given slice. |
| 2235 |
sz := 0 |
| 2236 |
// Check if we know about the remote server |
| 2237 |
conns, exists := s.routes[id] |
| 2238 |
if !exists { |
| 2239 |
// Now, create a slice for route connections of the size of the pool |
| 2240 |
// or 1 when not in pool mode. |
| 2241 |
conns = make([]*client, effectivePoolSize) |
| 2242 |
// Track this slice for this remote server. |
| 2243 |
s.routes[id] = conns |
| 2244 |
// Set the index to info.RoutePoolIdx because if this is a solicited |
| 2245 |
// route, this value will be 0, which is what we want, otherwise, we |
| 2246 |
// will use whatever index the remote has chosen. |
| 2247 |
idx = info.RoutePoolIdx |
| 2248 |
} else if pool { |
| 2249 |
// The remote could have done a config reload and increased the pool size. |
| 2250 |
// It will close the connections before soliciting again, however, if |
| 2251 |
// on this side, one of the route is not yet fully removed, but the |
| 2252 |
// first one is, it would accept the new connection (with a greater pool |
| 2253 |
// size) and we would not go through the phase of `!exists` above creating |
| 2254 |
// the slice with the right size. So we need to check here and add new empty |
| 2255 |
// entries to complete the effective pool size. |
| 2256 |
if n := effectivePoolSize - len(conns); n > 0 { |
| 2257 |
for range n { |
| 2258 |
conns = append(conns, nil) |
| 2259 |
} |
| 2260 |
s.routes[id] = conns |
| 2261 |
} |
| 2262 |
// The remote was found. If this is a non solicited route, we will place |
| 2263 |
// the connection in the pool at the index given by info.RoutePoolIdx. |
| 2264 |
// But if there is already one, close this incoming connection as a |
| 2265 |
// duplicate. |
| 2266 |
if !didSolicit { |
| 2267 |
idx = info.RoutePoolIdx |
| 2268 |
if remote = conns[idx]; remote != nil { |
| 2269 |
handleDuplicateRoute(remote, c, false) |
| 2270 |
s.mu.Unlock() |
| 2271 |
return false |
| 2272 |
} |
| 2273 |
// Look if there is a solicited route in the pool. If there is one, |
| 2274 |
// they should all be, so stop at the first. |
| 2275 |
if url, rtype, hasSolicited := hasSolicitedRoute(conns); hasSolicited { |
| 2276 |
upgradeRouteToSolicited(c, url, rtype) |
| 2277 |
} |
| 2278 |
} else { |
| 2279 |
// If we solicit, upgrade to solicited all non-solicited routes that |
| 2280 |
// we may have registered. |
| 2281 |
c.mu.Lock() |
| 2282 |
url := c.route.url |
| 2283 |
rtype := c.route.routeType |
| 2284 |
c.mu.Unlock() |
| 2285 |
for _, r := range conns { |
| 2286 |
upgradeRouteToSolicited(r, url, rtype) |
| 2287 |
} |
| 2288 |
} |
| 2289 |
// For all cases (solicited and not) we need to count how many connections |
| 2290 |
// we already have, and for solicited route, we will find a free spot in |
| 2291 |
// the slice. |
| 2292 |
for i, r := range conns { |
| 2293 |
if idx == -1 && r == nil { |
| 2294 |
idx = i |
| 2295 |
} else if r != nil { |
| 2296 |
sz++ |
| 2297 |
} |
| 2298 |
} |
| 2299 |
} else { |
| 2300 |
remote = conns[0] |
| 2301 |
} |
| 2302 |
// If there is a spot, idx will be greater or equal to 0. |
| 2303 |
if idx >= 0 { |
| 2304 |
c.mu.Lock() |
| 2305 |
c.route.connectURLs = info.ClientConnectURLs |
| 2306 |
c.route.wsConnURLs = info.WSConnectURLs |
| 2307 |
c.route.poolIdx = idx |
| 2308 |
rtype := c.route.routeType |
| 2309 |
cid := c.cid |
| 2310 |
idHash := c.route.idHash |
| 2311 |
rHash := c.route.hash |
| 2312 |
rn := c.route.remoteName |
| 2313 |
url := c.route.url |
| 2314 |
if sendDelayedInfo { |
| 2315 |
cm := compressionModeForInfoProtocol(&opts.Cluster.Compression, c.route.compression) |
| 2316 |
c.enqueueProto(s.generateRouteInitialInfoJSON(_EMPTY_, cm, idx, gossipMode)) |
| 2317 |
} |
| 2318 |
if c.last.IsZero() { |
| 2319 |
c.last = time.Now() |
| 2320 |
} |
| 2321 |
c.mu.Unlock() |
| 2322 |
|
| 2323 |
// With pooling, we keep track of the remote's configured route pool size. |
| 2324 |
// We do so when adding the connection in the first slot, not when `sz == 1` |
| 2325 |
// because there could be situations where we have old connections that have |
| 2326 |
// not yet been removed and so we would not have `sz == `. However, we will |
| 2327 |
// always have the condition where we are adding the new connection at `idx==0` |
| 2328 |
// so use that as the condition to store the remote pool size. |
| 2329 |
if pool && idx == 0 { |
| 2330 |
if s.remoteRoutePoolSize == nil { |
| 2331 |
s.remoteRoutePoolSize = make(map[string]int) |
| 2332 |
} |
| 2333 |
s.remoteRoutePoolSize[id] = info.RoutePoolSize |
| 2334 |
} |
| 2335 |
|
| 2336 |
// Add to the slice and bump the count of connections for this remote |
| 2337 |
conns[idx] = c |
| 2338 |
sz++ |
| 2339 |
// This boolean will indicate that we are registering the only |
| 2340 |
// connection in non pooled situation or we stored the very first |
| 2341 |
// connection for a given remote server. |
| 2342 |
doOnce := !pool || sz == 1 |
| 2343 |
if doOnce { |
| 2344 |
// check to be consistent and future proof. but will be same domain |
| 2345 |
if s.sameDomain(info.Domain) { |
| 2346 |
s.nodeToInfo.Store(rHash, nodeInfo{ |
| 2347 |
name: rn, |
| 2348 |
version: s.info.Version, |
| 2349 |
cluster: s.info.Cluster, |
| 2350 |
domain: info.Domain, |
| 2351 |
id: id, |
| 2352 |
tags: nil, |
| 2353 |
cfg: nil, |
| 2354 |
stats: nil, |
| 2355 |
offline: false, |
| 2356 |
js: info.JetStream, |
| 2357 |
binarySnapshots: true, // Updated default to true. Versions 2.10.0+ support it. |
| 2358 |
accountNRG: false, |
| 2359 |
}) |
| 2360 |
} |
| 2361 |
} |
| 2362 |
|
| 2363 |
// Store this route using the hash as the key |
| 2364 |
if pool { |
| 2365 |
idHash += strconv.Itoa(idx) |
| 2366 |
} |
| 2367 |
s.storeRouteByHash(idHash, c) |
| 2368 |
|
| 2369 |
// Now that we have registered the route, we can remove from the temp map. |
| 2370 |
s.removeFromTempClients(cid) |
| 2371 |
|
| 2372 |
if doOnce { |
| 2373 |
// If the INFO contains a Gateway URL, add it to the list for our cluster. |
| 2374 |
if info.GatewayURL != _EMPTY_ && s.addGatewayURL(info.GatewayURL) { |
| 2375 |
s.sendAsyncGatewayInfo() |
| 2376 |
} |
| 2377 |
|
| 2378 |
// We don't need to send if the only route is the one we just accepted. |
| 2379 |
if len(s.routes) > 1 { |
| 2380 |
s.forwardNewRouteInfoToKnownServers(info, rtype, didSolicit, gossipMode) |
| 2381 |
} |
| 2382 |
|
| 2383 |
// Send info about the known gateways to this route. |
| 2384 |
s.sendGatewayConfigsToRoute(c) |
| 2385 |
|
| 2386 |
// Unless disabled, possibly update the server's INFO protocol |
| 2387 |
// and send to clients that know how to handle async INFOs. |
| 2388 |
if !opts.Cluster.NoAdvertise { |
| 2389 |
s.addConnectURLsAndSendINFOToClients(info.ClientConnectURLs, info.WSConnectURLs) |
| 2390 |
} |
| 2391 |
|
| 2392 |
// Add the remote's leafnodeURL to our list of URLs and send the update |
| 2393 |
// to all LN connections. (Note that when coming from a route, LeafNodeURLs |
| 2394 |
// is an array of size 1 max). |
| 2395 |
if len(info.LeafNodeURLs) == 1 && s.addLeafNodeURL(info.LeafNodeURLs[0]) { |
| 2396 |
s.sendAsyncLeafNodeInfo() |
| 2397 |
} |
| 2398 |
} |
| 2399 |
|
| 2400 |
// Send the subscriptions interest. |
| 2401 |
s.sendSubsToRoute(c, idx, _EMPTY_) |
| 2402 |
|
| 2403 |
// In pool mode, if we did not yet reach the cap, try to connect a new connection, |
| 2404 |
// but do so only after receiving the first PONG to our PING, which will ensure |
| 2405 |
// that we have proper authentication. |
| 2406 |
if pool && didSolicit && sz != effectivePoolSize { |
| 2407 |
c.mu.Lock() |
| 2408 |
c.route.startNewRoute = &routeInfo{ |
| 2409 |
url: url, |
| 2410 |
rtype: rtype, |
| 2411 |
gossipMode: gossipMode, |
| 2412 |
} |
| 2413 |
c.sendPing() |
| 2414 |
c.mu.Unlock() |
| 2415 |
} |
| 2416 |
} |
| 2417 |
s.mu.Unlock() |
| 2418 |
if pool { |
| 2419 |
if idx == -1 { |
| 2420 |
// Was full, so need to close connection |
| 2421 |
c.Debugf("Route pool size reached, closing extra connection to %q", id) |
| 2422 |
handleDuplicateRoute(nil, c, true) |
| 2423 |
return false |
| 2424 |
} |
| 2425 |
return true |
| 2426 |
} |
| 2427 |
// This is for non-pool mode at this point. |
| 2428 |
if exists { |
| 2429 |
handleDuplicateRoute(remote, c, noReconnectForOldServer) |
| 2430 |
} |
| 2431 |
|
| 2432 |
return !exists |
| 2433 |
} |
| 2434 |
|
| 2435 |
func hasSolicitedRoute(conns []*client) (*url.URL, RouteType, bool) { |
| 2436 |
var url *url.URL |
| 2437 |
var rtype RouteType |
| 2438 |
for _, r := range conns { |
| 2439 |
if r == nil { |
| 2440 |
continue |
| 2441 |
} |
| 2442 |
r.mu.Lock() |
| 2443 |
if r.route.didSolicit { |
| 2444 |
url = r.route.url |
| 2445 |
rtype = r.route.routeType |
| 2446 |
} |
| 2447 |
r.mu.Unlock() |
| 2448 |
if url != nil { |
| 2449 |
return url, rtype, true |
| 2450 |
} |
| 2451 |
} |
| 2452 |
return nil, 0, false |
| 2453 |
} |
| 2454 |
|
| 2455 |
func upgradeRouteToSolicited(r *client, url *url.URL, rtype RouteType) { |
| 2456 |
if r == nil { |
| 2457 |
return |
| 2458 |
} |
| 2459 |
r.mu.Lock() |
| 2460 |
// On disconnect, an explicit route only reconnects if the connection's |
| 2461 |
// URL matches a configured route. So adopt the given URL rather than |
| 2462 |
// keeping a gossiped one, which may not match any configured route. |
| 2463 |
if !r.route.didSolicit || (rtype == Explicit && r.route.routeType != Explicit) { |
| 2464 |
r.route.url = url |
| 2465 |
} |
| 2466 |
r.route.didSolicit = true |
| 2467 |
if rtype == Explicit { |
| 2468 |
r.route.routeType = Explicit |
| 2469 |
} |
| 2470 |
r.mu.Unlock() |
| 2471 |
} |
| 2472 |
|
| 2473 |
func handleDuplicateRoute(remote, c *client, setNoReconnect bool) { |
| 2474 |
// We used to clear some fields when closing a duplicate connection |
| 2475 |
// to prevent sending INFO protocols for the remotes to update |
| 2476 |
// their leafnode/gateway URLs. This is no longer needed since |
| 2477 |
// removeRoute() now does the right thing of doing that only when |
| 2478 |
// the closed connection was an added route connection. |
| 2479 |
c.mu.Lock() |
| 2480 |
didSolicit := c.route.didSolicit |
| 2481 |
url := c.route.url |
| 2482 |
rtype := c.route.routeType |
| 2483 |
if setNoReconnect { |
| 2484 |
c.flags.set(noReconnect) |
| 2485 |
} |
| 2486 |
c.mu.Unlock() |
| 2487 |
|
| 2488 |
if remote == nil { |
| 2489 |
return |
| 2490 |
} |
| 2491 |
|
| 2492 |
remote.mu.Lock() |
| 2493 |
if didSolicit { |
| 2494 |
// On disconnect, an explicit route only reconnects if the connection's |
| 2495 |
// URL matches a configured route. So adopt the given URL rather than |
| 2496 |
// keeping a gossiped one, which may not match any configured route. |
| 2497 |
if !remote.route.didSolicit || (rtype == Explicit && remote.route.routeType != Explicit) { |
| 2498 |
remote.route.url = url |
| 2499 |
} |
| 2500 |
remote.route.didSolicit = true |
| 2501 |
} |
| 2502 |
// The extra route might be an configured explicit route |
| 2503 |
// so keep the state that the remote was configured. |
| 2504 |
if rtype == Explicit { |
| 2505 |
remote.route.routeType = rtype |
| 2506 |
} |
| 2507 |
// This is to mitigate the issue where both sides add the route |
| 2508 |
// on the opposite connection, and therefore end-up with both |
| 2509 |
// connections being dropped. |
| 2510 |
remote.route.retry = true |
| 2511 |
remote.mu.Unlock() |
| 2512 |
} |
| 2513 |
|
| 2514 |
// Import filter check. |
| 2515 |
func (c *client) importFilter(sub *subscription) bool { |
| 2516 |
if c.perms == nil { |
| 2517 |
return true |
| 2518 |
} |
| 2519 |
return c.canImport(string(sub.subject)) |
| 2520 |
} |
| 2521 |
|
| 2522 |
// updateRouteSubscriptionMap will make sure to update the route map for the subscription. Will |
| 2523 |
// also forward to all routes if needed. |
| 2524 |
func (s *Server) updateRouteSubscriptionMap(acc *Account, sub *subscription, delta int32) { |
| 2525 |
if acc == nil || sub == nil { |
| 2526 |
return |
| 2527 |
} |
| 2528 |
|
| 2529 |
// We only store state on local subs for transmission across all other routes. |
| 2530 |
if sub.client == nil || sub.client.kind == ROUTER || sub.client.kind == GATEWAY { |
| 2531 |
return |
| 2532 |
} |
| 2533 |
|
| 2534 |
if sub.si { |
| 2535 |
return |
| 2536 |
} |
| 2537 |
|
| 2538 |
// Copy to hold outside acc lock. |
| 2539 |
var n int32 |
| 2540 |
var ok bool |
| 2541 |
|
| 2542 |
isq := len(sub.queue) > 0 |
| 2543 |
|
| 2544 |
accLock := func() { |
| 2545 |
// Not required for code correctness, but helps reduce the number of |
| 2546 |
// updates sent to the routes when processing high number of concurrent |
| 2547 |
// queue subscriptions updates (sub/unsub). |
| 2548 |
// See https://github.com/nats-io/nats-server/pull/1126 for more details. |
| 2549 |
if isq { |
| 2550 |
acc.smu.Lock() |
| 2551 |
} |
| 2552 |
acc.mu.Lock() |
| 2553 |
} |
| 2554 |
accUnlock := func() { |
| 2555 |
acc.mu.Unlock() |
| 2556 |
if isq { |
| 2557 |
acc.smu.Unlock() |
| 2558 |
} |
| 2559 |
} |
| 2560 |
|
| 2561 |
accLock() |
| 2562 |
|
| 2563 |
// This is non-nil when we know we are in cluster mode. |
| 2564 |
rm, lws := acc.rm, acc.lws |
| 2565 |
if rm == nil { |
| 2566 |
accUnlock() |
| 2567 |
return |
| 2568 |
} |
| 2569 |
|
| 2570 |
// Create the subscription key which will prevent collisions between regular |
| 2571 |
// and leaf routed subscriptions. See keyFromSubWithOrigin() for details. |
| 2572 |
key := keyFromSubWithOrigin(sub) |
| 2573 |
|
| 2574 |
// Decide whether we need to send an update out to all the routes. |
| 2575 |
update := isq |
| 2576 |
|
| 2577 |
// This is where we do update to account. For queues we need to take |
| 2578 |
// special care that this order of updates is same as what is sent out |
| 2579 |
// over routes. |
| 2580 |
if n, ok = rm[key]; ok { |
| 2581 |
n += delta |
| 2582 |
if n <= 0 { |
| 2583 |
delete(rm, key) |
| 2584 |
delete(lws, key) |
| 2585 |
update = true // Update for deleting (N->0) |
| 2586 |
} else { |
| 2587 |
rm[key] = n |
| 2588 |
} |
| 2589 |
} else if delta > 0 { |
| 2590 |
n = delta |
| 2591 |
rm[key] = delta |
| 2592 |
update = true // Adding a new entry for normal sub means update (0->1) |
| 2593 |
} |
| 2594 |
|
| 2595 |
accUnlock() |
| 2596 |
|
| 2597 |
if !update { |
| 2598 |
return |
| 2599 |
} |
| 2600 |
|
| 2601 |
// If we are sending a queue sub, make a copy and place in the queue weight. |
| 2602 |
// FIXME(dlc) - We can be smarter here and avoid copying and acquiring the lock. |
| 2603 |
if isq { |
| 2604 |
sub.client.mu.Lock() |
| 2605 |
nsub := *sub |
| 2606 |
sub.client.mu.Unlock() |
| 2607 |
nsub.qw = n |
| 2608 |
sub = &nsub |
| 2609 |
} |
| 2610 |
|
| 2611 |
// We need to send out this update. Gather routes |
| 2612 |
var _routes [32]*client |
| 2613 |
routes := _routes[:0] |
| 2614 |
|
| 2615 |
s.mu.RLock() |
| 2616 |
// The account's routePoolIdx field is set/updated under the server lock |
| 2617 |
// (but also the account's lock). So we don't need to acquire the account's |
| 2618 |
// lock here to get the value. |
| 2619 |
if poolIdx := acc.routePoolIdx; poolIdx < 0 { |
| 2620 |
if conns, ok := s.accRoutes[acc.Name]; ok { |
| 2621 |
for _, r := range conns { |
| 2622 |
routes = append(routes, r) |
| 2623 |
} |
| 2624 |
} |
| 2625 |
if s.routesNoPool > 0 { |
| 2626 |
// We also need to look for "no pool" remotes (that is, routes to older |
| 2627 |
// servers or servers that have explicitly disabled pooling). |
| 2628 |
s.forEachRemote(func(r *client) { |
| 2629 |
r.mu.Lock() |
| 2630 |
if r.route.noPool { |
| 2631 |
routes = append(routes, r) |
| 2632 |
} |
| 2633 |
r.mu.Unlock() |
| 2634 |
}) |
| 2635 |
} |
| 2636 |
} else { |
| 2637 |
// We can't use s.forEachRouteIdx here since we want to check/get the |
| 2638 |
// "no pool" route ONLY if we don't find a route at the given `poolIdx`. |
| 2639 |
for _, conns := range s.routes { |
| 2640 |
if r := conns[poolIdx]; r != nil { |
| 2641 |
routes = append(routes, r) |
| 2642 |
} else if s.routesNoPool > 0 { |
| 2643 |
// Check if we have a "no pool" route at index 0, and if so, it |
| 2644 |
// means that for this remote, we have a single connection because |
| 2645 |
// that server does not have pooling. |
| 2646 |
if r := conns[0]; r != nil { |
| 2647 |
r.mu.Lock() |
| 2648 |
if r.route.noPool { |
| 2649 |
routes = append(routes, r) |
| 2650 |
} |
| 2651 |
r.mu.Unlock() |
| 2652 |
} |
| 2653 |
} |
| 2654 |
} |
| 2655 |
} |
| 2656 |
trace := atomic.LoadInt32(&s.logging.trace) == 1 |
| 2657 |
s.mu.RUnlock() |
| 2658 |
|
| 2659 |
// We need to make sure our updates are serialized from potential multiple connections. We want |
| 2660 |
// to make sure that the order above is preserved here but not necessarily all updates need to |
| 2661 |
// be sent. We need to block and recheck the n count with the lock held through sending here. |
| 2662 |
// |
| 2663 |
// However, we can't hold the acc.mu lock since we allow client.mu.Lock -> acc.mu.Lock |
| 2664 |
// but not the opposite. So use a dedicated lock while holding the route's lock. |
| 2665 |
acc.smu.Lock() |
| 2666 |
defer acc.smu.Unlock() |
| 2667 |
|
| 2668 |
acc.mu.Lock() |
| 2669 |
n = rm[key] |
| 2670 |
if isq { |
| 2671 |
sub.qw = n |
| 2672 |
} |
| 2673 |
// Check the last sent value here. If same, then someone beat us to it and |
| 2674 |
// we can just return here. Otherwise update. |
| 2675 |
if ls, ok := lws[key]; ok && ls == n { |
| 2676 |
acc.mu.Unlock() |
| 2677 |
return |
| 2678 |
} else if n > 0 { |
| 2679 |
lws[key] = n |
| 2680 |
} |
| 2681 |
acc.mu.Unlock() |
| 2682 |
|
| 2683 |
// Snapshot into array |
| 2684 |
subs := []*subscription{sub} |
| 2685 |
|
| 2686 |
// Deliver to all routes. |
| 2687 |
for _, route := range routes { |
| 2688 |
route.mu.Lock() |
| 2689 |
// Note that queue unsubs where n > 0 are still |
| 2690 |
// subscribes with a smaller weight. |
| 2691 |
route.sendRouteSubOrUnSubProtos(subs, n > 0, trace, route.importFilter) |
| 2692 |
route.mu.Unlock() |
| 2693 |
} |
| 2694 |
} |
| 2695 |
|
| 2696 |
// This starts the route accept loop in a go routine, unless it |
| 2697 |
// is detected that the server has already been shutdown. |
| 2698 |
// It will also start soliciting explicit routes. |
| 2699 |
func (s *Server) startRouteAcceptLoop() { |
| 2700 |
if s.isShuttingDown() { |
| 2701 |
return |
| 2702 |
} |
| 2703 |
|
| 2704 |
// Snapshot server options. |
| 2705 |
opts := s.getOpts() |
| 2706 |
|
| 2707 |
// Snapshot server options. |
| 2708 |
port := opts.Cluster.Port |
| 2709 |
|
| 2710 |
if port == -1 { |
| 2711 |
port = 0 |
| 2712 |
} |
| 2713 |
|
| 2714 |
// This requires lock, so do this outside of may block. |
| 2715 |
clusterName := s.ClusterName() |
| 2716 |
|
| 2717 |
s.mu.Lock() |
| 2718 |
s.Noticef("Cluster name is %s", clusterName) |
| 2719 |
if s.isClusterNameDynamic() { |
| 2720 |
s.Warnf("Cluster name was dynamically generated, consider setting one") |
| 2721 |
} |
| 2722 |
|
| 2723 |
hp := net.JoinHostPort(opts.Cluster.Host, strconv.Itoa(port)) |
| 2724 |
l, e := natsListen("tcp", hp) |
| 2725 |
s.routeListenerErr = e |
| 2726 |
if e != nil { |
| 2727 |
s.mu.Unlock() |
| 2728 |
s.Fatalf("Error listening on router port: %d - %v", opts.Cluster.Port, e) |
| 2729 |
return |
| 2730 |
} |
| 2731 |
s.Noticef("Listening for route connections on %s", |
| 2732 |
net.JoinHostPort(opts.Cluster.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port))) |
| 2733 |
|
| 2734 |
// Check for TLSConfig |
| 2735 |
tlsReq := opts.Cluster.TLSConfig != nil |
| 2736 |
info := Info{ |
| 2737 |
ID: s.info.ID, |
| 2738 |
Name: s.info.Name, |
| 2739 |
Version: s.info.Version, |
| 2740 |
GoVersion: runtime.Version(), |
| 2741 |
AuthRequired: false, |
| 2742 |
TLSRequired: tlsReq, |
| 2743 |
TLSVerify: tlsReq, |
| 2744 |
MaxPayload: s.info.MaxPayload, |
| 2745 |
JetStream: s.info.JetStream, |
| 2746 |
Proto: s.getServerProto(), |
| 2747 |
GatewayURL: s.getGatewayURL(), |
| 2748 |
Headers: s.supportsHeaders(), |
| 2749 |
Cluster: s.info.Cluster, |
| 2750 |
Domain: s.info.Domain, |
| 2751 |
Dynamic: s.isClusterNameDynamic(), |
| 2752 |
LNOC: true, |
| 2753 |
LNOCU: true, |
| 2754 |
} |
| 2755 |
// For tests that want to simulate old servers, do not set the compression |
| 2756 |
// on the INFO protocol if configured with CompressionNotSupported. |
| 2757 |
if cm := opts.Cluster.Compression.Mode; cm != CompressionNotSupported { |
| 2758 |
info.Compression = cm |
| 2759 |
} |
| 2760 |
if ps := opts.Cluster.PoolSize; ps > 0 { |
| 2761 |
info.RoutePoolSize = ps |
| 2762 |
} |
| 2763 |
// Set this if only if advertise is not disabled |
| 2764 |
if !opts.Cluster.NoAdvertise { |
| 2765 |
info.ClientConnectURLs = s.clientConnectURLs |
| 2766 |
info.WSConnectURLs = s.websocket.connectURLs |
| 2767 |
} |
| 2768 |
// If we have selected a random port... |
| 2769 |
if port == 0 { |
| 2770 |
// Write resolved port back to options. |
| 2771 |
opts.Cluster.Port = l.Addr().(*net.TCPAddr).Port |
| 2772 |
} |
| 2773 |
// Check for Auth items |
| 2774 |
if opts.Cluster.Username != "" { |
| 2775 |
info.AuthRequired = true |
| 2776 |
} |
| 2777 |
// Check for permissions. |
| 2778 |
if opts.Cluster.Permissions != nil { |
| 2779 |
info.Import = opts.Cluster.Permissions.Import |
| 2780 |
info.Export = opts.Cluster.Permissions.Export |
| 2781 |
} |
| 2782 |
// If this server has a LeafNode accept loop, s.leafNodeInfo.IP is, |
| 2783 |
// at this point, set to the host:port for the leafnode accept URL, |
| 2784 |
// taking into account possible advertise setting. Use the LeafNodeURLs |
| 2785 |
// and set this server's leafnode accept URL. This will be sent to |
| 2786 |
// routed servers. |
| 2787 |
if !opts.LeafNode.NoAdvertise && s.leafNodeInfo.IP != _EMPTY_ { |
| 2788 |
info.LeafNodeURLs = []string{s.leafNodeInfo.IP} |
| 2789 |
} |
| 2790 |
s.routeInfo = info |
| 2791 |
// Possibly override Host/Port and set IP based on Cluster.Advertise |
| 2792 |
if err := s.setRouteInfoHostPortAndIP(); err != nil { |
| 2793 |
s.Fatalf("Error setting route INFO with Cluster.Advertise value of %s, err=%v", opts.Cluster.Advertise, err) |
| 2794 |
l.Close() |
| 2795 |
s.mu.Unlock() |
| 2796 |
return |
| 2797 |
} |
| 2798 |
// Setup state that can enable shutdown |
| 2799 |
s.routeListener = l |
| 2800 |
// Warn if using Cluster.Insecure |
| 2801 |
if tlsReq && opts.Cluster.TLSConfig.InsecureSkipVerify { |
| 2802 |
s.Warnf(clusterTLSInsecureWarning) |
| 2803 |
} |
| 2804 |
|
| 2805 |
// Now that we have the port, keep track of all ip:port that resolve to this server. |
| 2806 |
if interfaceAddr, err := net.InterfaceAddrs(); err == nil { |
| 2807 |
var localIPs []string |
| 2808 |
for i := 0; i < len(interfaceAddr); i++ { |
| 2809 |
interfaceIP, _, _ := net.ParseCIDR(interfaceAddr[i].String()) |
| 2810 |
ipStr := interfaceIP.String() |
| 2811 |
if net.ParseIP(ipStr) != nil { |
| 2812 |
localIPs = append(localIPs, ipStr) |
| 2813 |
} |
| 2814 |
} |
| 2815 |
var portStr = strconv.FormatInt(int64(s.routeInfo.Port), 10) |
| 2816 |
for _, ip := range localIPs { |
| 2817 |
ipPort := net.JoinHostPort(ip, portStr) |
| 2818 |
s.routesToSelf[ipPort] = struct{}{} |
| 2819 |
} |
| 2820 |
} |
| 2821 |
|
| 2822 |
// Start the accept loop in a different go routine. |
| 2823 |
go s.acceptConnections(l, "Route", func(conn net.Conn) { s.createRoute(conn, nil, Implicit, gossipDefault, _EMPTY_) }, nil) |
| 2824 |
|
| 2825 |
// Solicit Routes if applicable. This will not block. |
| 2826 |
s.solicitRoutes(opts.Routes, opts.Cluster.PinnedAccounts) |
| 2827 |
|
| 2828 |
s.mu.Unlock() |
| 2829 |
} |
| 2830 |
|
| 2831 |
// Similar to setInfoHostPortAndGenerateJSON, but for routeInfo. |
| 2832 |
func (s *Server) setRouteInfoHostPortAndIP() error { |
| 2833 |
opts := s.getOpts() |
| 2834 |
if opts.Cluster.Advertise != _EMPTY_ { |
| 2835 |
advHost, advPort, err := parseHostPort(opts.Cluster.Advertise, opts.Cluster.Port) |
| 2836 |
if err != nil { |
| 2837 |
return err |
| 2838 |
} |
| 2839 |
s.routeInfo.Host = advHost |
| 2840 |
s.routeInfo.Port = advPort |
| 2841 |
s.routeInfo.IP = fmt.Sprintf("nats-route://%s/", net.JoinHostPort(advHost, strconv.Itoa(advPort))) |
| 2842 |
} else { |
| 2843 |
s.routeInfo.Host = opts.Cluster.Host |
| 2844 |
s.routeInfo.Port = opts.Cluster.Port |
| 2845 |
s.routeInfo.IP = "" |
| 2846 |
} |
| 2847 |
return nil |
| 2848 |
} |
| 2849 |
|
| 2850 |
// StartRouting will start the accept loop on the cluster host:port |
| 2851 |
// and will actively try to connect to listed routes. |
| 2852 |
func (s *Server) StartRouting(clientListenReady chan struct{}) { |
| 2853 |
defer s.grWG.Done() |
| 2854 |
|
| 2855 |
// Wait for the client and leafnode listen ports to be opened, |
| 2856 |
// and the possible ephemeral ports to be selected. |
| 2857 |
<-clientListenReady |
| 2858 |
|
| 2859 |
// Start the accept loop and solicitation of explicit routes (if applicable) |
| 2860 |
s.startRouteAcceptLoop() |
| 2861 |
|
| 2862 |
} |
| 2863 |
|
| 2864 |
func (s *Server) reConnectToRoute(rURL *url.URL, rtype RouteType, accName string) { |
| 2865 |
// If A connects to B, and B to A (regardless if explicit or |
| 2866 |
// implicit - due to auto-discovery), and if each server first |
| 2867 |
// registers the route on the opposite TCP connection, the |
| 2868 |
// two connections will end-up being closed. |
| 2869 |
// Add some random delay to reduce risk of repeated failures. |
| 2870 |
delay := time.Duration(rand.Intn(100)) * time.Millisecond |
| 2871 |
if rtype == Explicit { |
| 2872 |
delay += DEFAULT_ROUTE_RECONNECT |
| 2873 |
} |
| 2874 |
select { |
| 2875 |
case <-time.After(delay): |
| 2876 |
case <-s.quitCh: |
| 2877 |
s.grWG.Done() |
| 2878 |
return |
| 2879 |
} |
| 2880 |
s.connectToRoute(rURL, rtype, false, gossipDefault, accName) |
| 2881 |
} |
| 2882 |
|
| 2883 |
// Checks to make sure the route is still valid. |
| 2884 |
func (s *Server) routeStillValid(rURL *url.URL) bool { |
| 2885 |
for _, ri := range s.getOpts().Routes { |
| 2886 |
if urlsAreEqual(ri, rURL) { |
| 2887 |
return true |
| 2888 |
} |
| 2889 |
} |
| 2890 |
return false |
| 2891 |
} |
| 2892 |
|
| 2893 |
func (s *Server) connectToRoute(rURL *url.URL, rtype RouteType, firstConnect bool, gossipMode byte, accName string) { |
| 2894 |
defer s.grWG.Done() |
| 2895 |
if rURL == nil { |
| 2896 |
return |
| 2897 |
} |
| 2898 |
// For explicit routes, we will try to connect until we succeed. For implicit |
| 2899 |
// we will try only based on the number of ConnectRetries optin. |
| 2900 |
tryForEver := rtype == Explicit |
| 2901 |
|
| 2902 |
// Snapshot server options. |
| 2903 |
opts := s.getOpts() |
| 2904 |
|
| 2905 |
const connErrFmt = "Error trying to connect to route (attempt %v): %v" |
| 2906 |
|
| 2907 |
s.mu.RLock() |
| 2908 |
resolver := s.routeResolver |
| 2909 |
excludedAddresses := s.routesToSelf |
| 2910 |
s.mu.RUnlock() |
| 2911 |
|
| 2912 |
attemptDelay := routeConnectDelay |
| 2913 |
reconnectTimer := time.NewTimer(attemptDelay) |
| 2914 |
reconnectTimer.Stop() |
| 2915 |
defer stopAndClearTimer(&reconnectTimer) |
| 2916 |
|
| 2917 |
for attempts := 0; s.isRunning(); { |
| 2918 |
if tryForEver { |
| 2919 |
if !s.routeStillValid(rURL) { |
| 2920 |
s.Debugf("Not attempting to connect to explicit route %q, no longer part of configured routes", rURL.Redacted()) |
| 2921 |
return |
| 2922 |
} |
| 2923 |
if accName != _EMPTY_ { |
| 2924 |
s.mu.RLock() |
| 2925 |
_, valid := s.accRoutes[accName] |
| 2926 |
s.mu.RUnlock() |
| 2927 |
if !valid { |
| 2928 |
s.Debugf("Not attempting to connect to route %q for account %q, no longer a per-account route", rURL.Redacted(), accName) |
| 2929 |
return |
| 2930 |
} |
| 2931 |
} |
| 2932 |
} |
| 2933 |
var conn net.Conn |
| 2934 |
address, err := s.getRandomIP(resolver, rURL.Host, excludedAddresses) |
| 2935 |
if err == errNoIPAvail { |
| 2936 |
// This is ok, we are done. |
| 2937 |
return |
| 2938 |
} |
| 2939 |
if err == nil { |
| 2940 |
s.Debugf("Trying to connect to route on %s (%s)", rURL.Host, address) |
| 2941 |
conn, err = natsDialTimeout("tcp", address, DEFAULT_ROUTE_DIAL) |
| 2942 |
} |
| 2943 |
if err != nil { |
| 2944 |
attempts++ |
| 2945 |
if s.shouldReportConnectErr(firstConnect, attempts) { |
| 2946 |
s.Errorf(connErrFmt, attempts, err) |
| 2947 |
} else { |
| 2948 |
s.Debugf(connErrFmt, attempts, err) |
| 2949 |
} |
| 2950 |
if !tryForEver { |
| 2951 |
if opts.Cluster.ConnectRetries <= 0 { |
| 2952 |
return |
| 2953 |
} |
| 2954 |
if attempts > opts.Cluster.ConnectRetries { |
| 2955 |
return |
| 2956 |
} |
| 2957 |
} |
| 2958 |
reconnectTimer.Reset(attemptDelay) |
| 2959 |
select { |
| 2960 |
case <-s.quitCh: |
| 2961 |
return |
| 2962 |
case <-reconnectTimer.C: |
| 2963 |
if opts.Cluster.ConnectBackoff { |
| 2964 |
// Use exponential backoff for connection attempts. |
| 2965 |
attemptDelay *= 2 |
| 2966 |
if attemptDelay > routeConnectMaxDelay { |
| 2967 |
attemptDelay = routeConnectMaxDelay |
| 2968 |
} |
| 2969 |
} |
| 2970 |
continue |
| 2971 |
} |
| 2972 |
} |
| 2973 |
|
| 2974 |
if tryForEver && !s.routeStillValid(rURL) { |
| 2975 |
conn.Close() |
| 2976 |
return |
| 2977 |
} |
| 2978 |
|
| 2979 |
// We have a route connection here. |
| 2980 |
// Go ahead and create it and exit this func. |
| 2981 |
s.createRoute(conn, rURL, rtype, gossipMode, accName) |
| 2982 |
return |
| 2983 |
} |
| 2984 |
} |
| 2985 |
|
| 2986 |
func (c *client) isSolicitedRoute() bool { |
| 2987 |
c.mu.Lock() |
| 2988 |
defer c.mu.Unlock() |
| 2989 |
return c.kind == ROUTER && c.route != nil && c.route.didSolicit |
| 2990 |
} |
| 2991 |
|
| 2992 |
// Save the first hostname found in route URLs. This will be used in gossip mode |
| 2993 |
// when trying to create a TLS connection by setting the tlsConfig.ServerName. |
| 2994 |
// Lock is held on entry |
| 2995 |
func (s *Server) saveRouteTLSName(routes []*url.URL) { |
| 2996 |
for _, u := range routes { |
| 2997 |
if s.routeTLSName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil { |
| 2998 |
s.routeTLSName = u.Hostname() |
| 2999 |
} |
| 3000 |
} |
| 3001 |
} |
| 3002 |
|
| 3003 |
// Start connection process to provided routes. Each route connection will |
| 3004 |
// be started in a dedicated go routine. |
| 3005 |
// Lock is held on entry |
| 3006 |
func (s *Server) solicitRoutes(routes []*url.URL, accounts []string) { |
| 3007 |
s.saveRouteTLSName(routes) |
| 3008 |
for _, r := range routes { |
| 3009 |
route := r |
| 3010 |
s.startGoRoutine(func() { s.connectToRoute(route, Explicit, true, gossipDefault, _EMPTY_) }) |
| 3011 |
} |
| 3012 |
// Now go over possible per-account routes and create them. |
| 3013 |
for _, an := range accounts { |
| 3014 |
for _, r := range routes { |
| 3015 |
route, accName := r, an |
| 3016 |
s.startGoRoutine(func() { s.connectToRoute(route, Explicit, true, gossipDefault, accName) }) |
| 3017 |
} |
| 3018 |
} |
| 3019 |
} |
| 3020 |
|
| 3021 |
func (c *client) processRouteConnect(srv *Server, arg []byte, lang string) error { |
| 3022 |
// Way to detect clients that incorrectly connect to the route listen |
| 3023 |
// port. Client provide Lang in the CONNECT protocol while ROUTEs don't. |
| 3024 |
if lang != "" { |
| 3025 |
c.sendErrAndErr(ErrClientConnectedToRoutePort.Error()) |
| 3026 |
c.closeConnection(WrongPort) |
| 3027 |
return ErrClientConnectedToRoutePort |
| 3028 |
} |
| 3029 |
// Unmarshal as a route connect protocol |
| 3030 |
proto := &connectInfo{} |
| 3031 |
|
| 3032 |
if err := json.Unmarshal(arg, proto); err != nil { |
| 3033 |
return err |
| 3034 |
} |
| 3035 |
// Reject if this has Gateway which means that it would be from a gateway |
| 3036 |
// connection that incorrectly connects to the Route port. |
| 3037 |
if proto.Gateway != "" { |
| 3038 |
errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the Route port", proto.Gateway) |
| 3039 |
c.Errorf(errTxt) |
| 3040 |
c.sendErr(errTxt) |
| 3041 |
c.closeConnection(WrongGateway) |
| 3042 |
return ErrWrongGateway |
| 3043 |
} |
| 3044 |
|
| 3045 |
if srv == nil { |
| 3046 |
return ErrServerNotRunning |
| 3047 |
} |
| 3048 |
|
| 3049 |
perms := srv.getOpts().Cluster.Permissions |
| 3050 |
clusterName := srv.ClusterName() |
| 3051 |
|
| 3052 |
// If we have a cluster name set, make sure it matches ours. |
| 3053 |
if proto.Cluster != clusterName { |
| 3054 |
shouldReject := true |
| 3055 |
// If we have a dynamic name we will do additional checks. |
| 3056 |
if srv.isClusterNameDynamic() { |
| 3057 |
if !proto.Dynamic || strings.Compare(clusterName, proto.Cluster) < 0 { |
| 3058 |
// We will take on their name since theirs is configured or higher then ours. |
| 3059 |
srv.setClusterName(proto.Cluster) |
| 3060 |
if !proto.Dynamic { |
| 3061 |
srv.optsMu.Lock() |
| 3062 |
srv.opts.Cluster.Name = proto.Cluster |
| 3063 |
srv.optsMu.Unlock() |
| 3064 |
} |
| 3065 |
c.mu.Lock() |
| 3066 |
remoteID := c.opts.Name |
| 3067 |
c.mu.Unlock() |
| 3068 |
srv.removeAllRoutesExcept(remoteID) |
| 3069 |
shouldReject = false |
| 3070 |
} |
| 3071 |
} |
| 3072 |
if shouldReject { |
| 3073 |
errTxt := fmt.Sprintf("Rejecting connection, cluster name %q does not match %q", proto.Cluster, clusterName) |
| 3074 |
c.Errorf(errTxt) |
| 3075 |
c.sendErr(errTxt) |
| 3076 |
c.closeConnection(ClusterNameConflict) |
| 3077 |
return ErrClusterNameRemoteConflict |
| 3078 |
} |
| 3079 |
} |
| 3080 |
|
| 3081 |
supportsHeaders := c.srv.supportsHeaders() |
| 3082 |
|
| 3083 |
// Grab connection name of remote route. |
| 3084 |
c.mu.Lock() |
| 3085 |
c.route.remoteID = c.opts.Name |
| 3086 |
c.route.lnoc = proto.LNOC |
| 3087 |
c.route.lnocu = proto.LNOCU |
| 3088 |
c.setRoutePermissions(perms) |
| 3089 |
c.headers = supportsHeaders && proto.Headers |
| 3090 |
c.mu.Unlock() |
| 3091 |
return nil |
| 3092 |
} |
| 3093 |
|
| 3094 |
// Called when we update our cluster name during negotiations with remotes. |
| 3095 |
func (s *Server) removeAllRoutesExcept(remoteID string) { |
| 3096 |
s.mu.Lock() |
| 3097 |
routes := make([]*client, 0, s.numRoutes()) |
| 3098 |
for rID, conns := range s.routes { |
| 3099 |
if rID == remoteID { |
| 3100 |
continue |
| 3101 |
} |
| 3102 |
for _, r := range conns { |
| 3103 |
if r != nil { |
| 3104 |
routes = append(routes, r) |
| 3105 |
} |
| 3106 |
} |
| 3107 |
} |
| 3108 |
for _, conns := range s.accRoutes { |
| 3109 |
for rID, r := range conns { |
| 3110 |
if rID == remoteID { |
| 3111 |
continue |
| 3112 |
} |
| 3113 |
routes = append(routes, r) |
| 3114 |
} |
| 3115 |
} |
| 3116 |
s.mu.Unlock() |
| 3117 |
|
| 3118 |
for _, r := range routes { |
| 3119 |
r.closeConnection(ClusterNameConflict) |
| 3120 |
} |
| 3121 |
} |
| 3122 |
|
| 3123 |
func (s *Server) removeRoute(c *client) { |
| 3124 |
s.mu.Lock() |
| 3125 |
defer s.mu.Unlock() |
| 3126 |
|
| 3127 |
var ( |
| 3128 |
rID string |
| 3129 |
lnURL string |
| 3130 |
gwURL string |
| 3131 |
idHash string |
| 3132 |
accName string |
| 3133 |
poolIdx = -1 |
| 3134 |
connectURLs []string |
| 3135 |
wsConnectURLs []string |
| 3136 |
opts = s.getOpts() |
| 3137 |
rURL *url.URL |
| 3138 |
noPool bool |
| 3139 |
rtype RouteType |
| 3140 |
) |
| 3141 |
c.mu.Lock() |
| 3142 |
cid := c.cid |
| 3143 |
r := c.route |
| 3144 |
if r != nil { |
| 3145 |
rID = r.remoteID |
| 3146 |
lnURL = r.leafnodeURL |
| 3147 |
idHash = r.idHash |
| 3148 |
gwURL = r.gatewayURL |
| 3149 |
poolIdx = r.poolIdx |
| 3150 |
accName = bytesToString(r.accName) |
| 3151 |
if r.noPool { |
| 3152 |
s.routesNoPool-- |
| 3153 |
noPool = true |
| 3154 |
} |
| 3155 |
connectURLs = r.connectURLs |
| 3156 |
wsConnectURLs = r.wsConnURLs |
| 3157 |
rURL = r.url |
| 3158 |
rtype = r.routeType |
| 3159 |
} |
| 3160 |
c.mu.Unlock() |
| 3161 |
if accName != _EMPTY_ { |
| 3162 |
if conns, ok := s.accRoutes[accName]; ok { |
| 3163 |
if r := conns[rID]; r == c { |
| 3164 |
s.removeRouteByHash(idHash + accName) |
| 3165 |
delete(conns, rID) |
| 3166 |
// Do not remove or set to nil when all remotes have been |
| 3167 |
// removed from the map. The configured accounts must always |
| 3168 |
// be in the accRoutes map and addRoute expects "conns" map |
| 3169 |
// to be created. |
| 3170 |
} |
| 3171 |
} |
| 3172 |
} |
| 3173 |
// If this is still -1, it means that it was not added to the routes |
| 3174 |
// so simply remove from temp clients and we are done. |
| 3175 |
if poolIdx == -1 || accName != _EMPTY_ { |
| 3176 |
s.removeFromTempClients(cid) |
| 3177 |
return |
| 3178 |
} |
| 3179 |
if conns, ok := s.routes[rID]; ok { |
| 3180 |
// If this route was not the one stored, simply remove from the |
| 3181 |
// temporary map and be done. |
| 3182 |
if conns[poolIdx] != c { |
| 3183 |
s.removeFromTempClients(cid) |
| 3184 |
return |
| 3185 |
} |
| 3186 |
conns[poolIdx] = nil |
| 3187 |
// Now check if this was the last connection to be removed. |
| 3188 |
empty := true |
| 3189 |
for _, c := range conns { |
| 3190 |
if c != nil { |
| 3191 |
empty = false |
| 3192 |
break |
| 3193 |
} |
| 3194 |
} |
| 3195 |
// This was the last route for this remote. Remove the remote entry |
| 3196 |
// and possibly send some async INFO protocols regarding gateway |
| 3197 |
// and leafnode URLs. |
| 3198 |
if empty { |
| 3199 |
delete(s.routes, rID) |
| 3200 |
|
| 3201 |
// Since this is the last route for this remote, possibly update |
| 3202 |
// the client connect URLs and send an update to connected |
| 3203 |
// clients. |
| 3204 |
if (len(connectURLs) > 0 || len(wsConnectURLs) > 0) && !opts.Cluster.NoAdvertise { |
| 3205 |
s.removeConnectURLsAndSendINFOToClients(connectURLs, wsConnectURLs) |
| 3206 |
} |
| 3207 |
// Remove the remote's gateway URL from our list and |
| 3208 |
// send update to inbound Gateway connections. |
| 3209 |
if gwURL != _EMPTY_ && s.removeGatewayURL(gwURL) { |
| 3210 |
s.sendAsyncGatewayInfo() |
| 3211 |
} |
| 3212 |
// Remove the remote's leafNode URL from |
| 3213 |
// our list and send update to LN connections. |
| 3214 |
if lnURL != _EMPTY_ && s.removeLeafNodeURL(lnURL) { |
| 3215 |
s.sendAsyncLeafNodeInfo() |
| 3216 |
} |
| 3217 |
// We can remove the configured route pool size of this remote. |
| 3218 |
delete(s.remoteRoutePoolSize, rID) |
| 3219 |
// If this server has pooling/pinned accounts and the route for |
| 3220 |
// this remote was a "no pool" route, attempt to reconnect. |
| 3221 |
if noPool { |
| 3222 |
if s.routesPoolSize > 1 { |
| 3223 |
s.startGoRoutine(func() { s.connectToRoute(rURL, rtype, true, gossipDefault, _EMPTY_) }) |
| 3224 |
} |
| 3225 |
if len(opts.Cluster.PinnedAccounts) > 0 { |
| 3226 |
for _, an := range opts.Cluster.PinnedAccounts { |
| 3227 |
accName := an |
| 3228 |
s.startGoRoutine(func() { s.connectToRoute(rURL, rtype, true, gossipDefault, accName) }) |
| 3229 |
} |
| 3230 |
} |
| 3231 |
} |
| 3232 |
} |
| 3233 |
// This is for gateway code. Remove this route from a map that uses |
| 3234 |
// the route hash in combination with the pool index as the key. |
| 3235 |
if s.routesPoolSize > 1 { |
| 3236 |
idHash += strconv.Itoa(poolIdx) |
| 3237 |
} |
| 3238 |
s.removeRouteByHash(idHash) |
| 3239 |
} |
| 3240 |
s.removeFromTempClients(cid) |
| 3241 |
} |
| 3242 |
|
| 3243 |
func (s *Server) isDuplicateServerName(name string) bool { |
| 3244 |
if name == _EMPTY_ { |
| 3245 |
return false |
| 3246 |
} |
| 3247 |
s.mu.RLock() |
| 3248 |
defer s.mu.RUnlock() |
| 3249 |
|
| 3250 |
if s.info.Name == name { |
| 3251 |
return true |
| 3252 |
} |
| 3253 |
for _, conns := range s.routes { |
| 3254 |
for _, r := range conns { |
| 3255 |
if r != nil { |
| 3256 |
r.mu.Lock() |
| 3257 |
duplicate := r.route.remoteName == name |
| 3258 |
r.mu.Unlock() |
| 3259 |
if duplicate { |
| 3260 |
return true |
| 3261 |
} |
| 3262 |
break |
| 3263 |
} |
| 3264 |
} |
| 3265 |
} |
| 3266 |
return false |
| 3267 |
} |
| 3268 |
|
| 3269 |
// Goes over each non-nil route connection for all remote servers |
| 3270 |
// and invokes the function `f`. It does not go over per-account |
| 3271 |
// routes. |
| 3272 |
// Server lock is held on entry. |
| 3273 |
func (s *Server) forEachNonPerAccountRoute(f func(r *client)) { |
| 3274 |
for _, conns := range s.routes { |
| 3275 |
for _, r := range conns { |
| 3276 |
if r != nil { |
| 3277 |
f(r) |
| 3278 |
} |
| 3279 |
} |
| 3280 |
} |
| 3281 |
} |
| 3282 |
|
| 3283 |
// Goes over each non-nil route connection for all remote servers |
| 3284 |
// and invokes the function `f`. This also includes the per-account |
| 3285 |
// routes. |
| 3286 |
// Server lock is held on entry. |
| 3287 |
func (s *Server) forEachRoute(f func(r *client)) { |
| 3288 |
s.forEachNonPerAccountRoute(f) |
| 3289 |
for _, conns := range s.accRoutes { |
| 3290 |
for _, r := range conns { |
| 3291 |
f(r) |
| 3292 |
} |
| 3293 |
} |
| 3294 |
} |
| 3295 |
|
| 3296 |
// Goes over each non-nil route connection at the given pool index |
| 3297 |
// location in the slice and invokes the function `f`. If the |
| 3298 |
// callback returns `true`, this function moves to the next remote. |
| 3299 |
// Otherwise, the iteration over removes stops. |
| 3300 |
// This does not include per-account routes. |
| 3301 |
// Server lock is held on entry. |
| 3302 |
func (s *Server) forEachRouteIdx(idx int, f func(r *client) bool) { |
| 3303 |
for _, conns := range s.routes { |
| 3304 |
if r := conns[idx]; r != nil { |
| 3305 |
if !f(r) { |
| 3306 |
return |
| 3307 |
} |
| 3308 |
} |
| 3309 |
} |
| 3310 |
} |
| 3311 |
|
| 3312 |
// Goes over each remote and for the first non nil route connection, |
| 3313 |
// invokes the function `f`. |
| 3314 |
// Server lock is held on entry. |
| 3315 |
func (s *Server) forEachRemote(f func(r *client)) { |
| 3316 |
for _, conns := range s.routes { |
| 3317 |
for _, r := range conns { |
| 3318 |
if r != nil { |
| 3319 |
f(r) |
| 3320 |
break |
| 3321 |
} |
| 3322 |
} |
| 3323 |
} |
| 3324 |
} |