| 1 |
// Copyright 2018-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 |
"compress/gzip" |
| 19 |
"crypto/sha256" |
| 20 |
"crypto/x509" |
| 21 |
"encoding/json" |
| 22 |
"errors" |
| 23 |
"fmt" |
| 24 |
"math" |
| 25 |
"math/rand" |
| 26 |
"net/http" |
| 27 |
"runtime" |
| 28 |
"runtime/debug" |
| 29 |
"strconv" |
| 30 |
"strings" |
| 31 |
"sync" |
| 32 |
"sync/atomic" |
| 33 |
"time" |
| 34 |
|
| 35 |
"github.com/klauspost/compress/s2" |
| 36 |
"github.com/nats-io/jwt/v2" |
| 37 |
"github.com/nats-io/nats-server/v2/server/certidp" |
| 38 |
"github.com/nats-io/nats-server/v2/server/pse" |
| 39 |
) |
| 40 |
|
| 41 |
const ( |
| 42 |
accLookupReqTokens = 6 |
| 43 |
accLookupReqSubj = "$SYS.REQ.ACCOUNT.%s.CLAIMS.LOOKUP" |
| 44 |
accPackReqSubj = "$SYS.REQ.CLAIMS.PACK" |
| 45 |
accListReqSubj = "$SYS.REQ.CLAIMS.LIST" |
| 46 |
accClaimsReqSubj = "$SYS.REQ.CLAIMS.UPDATE" |
| 47 |
accDeleteReqSubj = "$SYS.REQ.CLAIMS.DELETE" |
| 48 |
|
| 49 |
connectEventSubj = "$SYS.ACCOUNT.%s.CONNECT" |
| 50 |
disconnectEventSubj = "$SYS.ACCOUNT.%s.DISCONNECT" |
| 51 |
accDirectReqSubj = "$SYS.REQ.ACCOUNT.%s.%s" |
| 52 |
accPingReqSubj = "$SYS.REQ.ACCOUNT.PING.%s" // atm. only used for STATZ and CONNZ import from system account |
| 53 |
// kept for backward compatibility when using http resolver |
| 54 |
// this overlaps with the names for events but you'd have to have the operator private key in order to succeed. |
| 55 |
accUpdateEventSubjOld = "$SYS.ACCOUNT.%s.CLAIMS.UPDATE" |
| 56 |
accUpdateEventSubjNew = "$SYS.REQ.ACCOUNT.%s.CLAIMS.UPDATE" |
| 57 |
connsRespSubj = "$SYS._INBOX_.%s" |
| 58 |
accConnsEventSubjNew = "$SYS.ACCOUNT.%s.SERVER.CONNS" |
| 59 |
accConnsEventSubjOld = "$SYS.SERVER.ACCOUNT.%s.CONNS" // kept for backward compatibility |
| 60 |
lameDuckEventSubj = "$SYS.SERVER.%s.LAMEDUCK" |
| 61 |
shutdownEventSubj = "$SYS.SERVER.%s.SHUTDOWN" |
| 62 |
clientKickReqSubj = "$SYS.REQ.SERVER.%s.KICK" |
| 63 |
clientLDMReqSubj = "$SYS.REQ.SERVER.%s.LDM" |
| 64 |
authErrorEventSubj = "$SYS.SERVER.%s.CLIENT.AUTH.ERR" |
| 65 |
authErrorAccountEventSubj = "$SYS.ACCOUNT.CLIENT.AUTH.ERR" |
| 66 |
serverStatsSubj = "$SYS.SERVER.%s.STATSZ" |
| 67 |
serverDirectReqSubj = "$SYS.REQ.SERVER.%s.%s" |
| 68 |
serverPingReqSubj = "$SYS.REQ.SERVER.PING.%s" |
| 69 |
serverStatsPingReqSubj = "$SYS.REQ.SERVER.PING" // use $SYS.REQ.SERVER.PING.STATSZ instead |
| 70 |
serverReloadReqSubj = "$SYS.REQ.SERVER.%s.RELOAD" // with server ID |
| 71 |
leafNodeConnectEventSubj = "$SYS.ACCOUNT.%s.LEAFNODE.CONNECT" // for internal use only |
| 72 |
remoteLatencyEventSubj = "$SYS.LATENCY.M2.%s" |
| 73 |
inboxRespSubj = "$SYS._INBOX.%s.%s" |
| 74 |
|
| 75 |
// Used to return information to a user on bound account and user permissions. |
| 76 |
userDirectInfoSubj = "$SYS.REQ.USER.INFO" |
| 77 |
userDirectReqSubj = "$SYS.REQ.USER.%s.INFO" |
| 78 |
|
| 79 |
// FIXME(dlc) - Should account scope, even with wc for now, but later on |
| 80 |
// we can then shard as needed. |
| 81 |
accNumSubsReqSubj = "$SYS.REQ.ACCOUNT.NSUBS" |
| 82 |
|
| 83 |
// These are for exported debug services. These are local to this server only. |
| 84 |
accSubsSubj = "$SYS.DEBUG.SUBSCRIBERS" |
| 85 |
|
| 86 |
shutdownEventTokens = 4 |
| 87 |
serverSubjectIndex = 2 |
| 88 |
accUpdateTokensNew = 6 |
| 89 |
accUpdateTokensOld = 5 |
| 90 |
accUpdateAccIdxOld = 2 |
| 91 |
|
| 92 |
accReqTokens = 5 |
| 93 |
accReqAccIndex = 3 |
| 94 |
|
| 95 |
ocspPeerRejectEventSubj = "$SYS.SERVER.%s.OCSP.PEER.CONN.REJECT" |
| 96 |
ocspPeerChainlinkInvalidEventSubj = "$SYS.SERVER.%s.OCSP.PEER.LINK.INVALID" |
| 97 |
) |
| 98 |
|
| 99 |
// FIXME(dlc) - make configurable. |
| 100 |
var eventsHBInterval = 30 * time.Second |
| 101 |
var statsHBInterval = 10 * time.Second |
| 102 |
|
| 103 |
// Default minimum wait time for sending statsz |
| 104 |
const defaultStatszRateLimit = 1 * time.Second |
| 105 |
|
| 106 |
// Variable version so we can set in tests. |
| 107 |
var statszRateLimit = defaultStatszRateLimit |
| 108 |
|
| 109 |
type sysMsgHandler func(sub *subscription, client *client, acc *Account, subject, reply string, hdr, msg []byte) |
| 110 |
|
| 111 |
// Used if we have to queue things internally to avoid the route/gw path. |
| 112 |
type inSysMsg struct { |
| 113 |
sub *subscription |
| 114 |
c *client |
| 115 |
acc *Account |
| 116 |
subj string |
| 117 |
rply string |
| 118 |
hdr []byte |
| 119 |
msg []byte |
| 120 |
cb sysMsgHandler |
| 121 |
} |
| 122 |
|
| 123 |
// Used to send and receive messages from inside the server. |
| 124 |
type internal struct { |
| 125 |
account *Account |
| 126 |
client *client |
| 127 |
seq uint64 |
| 128 |
sid int |
| 129 |
servers map[string]*serverUpdate |
| 130 |
sweeper *time.Timer |
| 131 |
stmr *time.Timer |
| 132 |
replies map[string]msgHandler |
| 133 |
sendq *ipQueue[*pubMsg] |
| 134 |
recvq *ipQueue[*inSysMsg] |
| 135 |
recvqp *ipQueue[*inSysMsg] // For STATSZ/Pings |
| 136 |
resetCh chan struct{} |
| 137 |
wg sync.WaitGroup |
| 138 |
sq *sendq |
| 139 |
orphMax time.Duration |
| 140 |
chkOrph time.Duration |
| 141 |
statsz time.Duration |
| 142 |
cstatsz time.Duration |
| 143 |
shash string |
| 144 |
inboxPre string |
| 145 |
remoteStatsSub *subscription |
| 146 |
lastStatsz time.Time |
| 147 |
} |
| 148 |
|
| 149 |
// ServerStatsMsg is sent periodically with stats updates. |
| 150 |
type ServerStatsMsg struct { |
| 151 |
Server ServerInfo `json:"server"` |
| 152 |
Stats ServerStats `json:"statsz"` |
| 153 |
} |
| 154 |
|
| 155 |
// ConnectEventMsg is sent when a new connection is made that is part of an account. |
| 156 |
type ConnectEventMsg struct { |
| 157 |
TypedEvent |
| 158 |
Server ServerInfo `json:"server"` |
| 159 |
Client ClientInfo `json:"client"` |
| 160 |
} |
| 161 |
|
| 162 |
// ConnectEventMsgType is the schema type for ConnectEventMsg |
| 163 |
const ConnectEventMsgType = "io.nats.server.advisory.v1.client_connect" |
| 164 |
|
| 165 |
// DisconnectEventMsg is sent when a new connection previously defined from a |
| 166 |
// ConnectEventMsg is closed. |
| 167 |
type DisconnectEventMsg struct { |
| 168 |
TypedEvent |
| 169 |
Server ServerInfo `json:"server"` |
| 170 |
Client ClientInfo `json:"client"` |
| 171 |
Sent DataStats `json:"sent"` |
| 172 |
Received DataStats `json:"received"` |
| 173 |
Reason string `json:"reason"` |
| 174 |
} |
| 175 |
|
| 176 |
// DisconnectEventMsgType is the schema type for DisconnectEventMsg |
| 177 |
const DisconnectEventMsgType = "io.nats.server.advisory.v1.client_disconnect" |
| 178 |
|
| 179 |
// OCSPPeerRejectEventMsg is sent when a peer TLS handshake is ultimately rejected due to OCSP invalidation. |
| 180 |
// A "peer" can be an inbound client connection or a leaf connection to a remote server. Peer in event payload |
| 181 |
// is always the peer's (TLS) leaf cert, which may or may be the invalid cert (See also OCSPPeerChainlinkInvalidEventMsg) |
| 182 |
type OCSPPeerRejectEventMsg struct { |
| 183 |
TypedEvent |
| 184 |
Kind string `json:"kind"` |
| 185 |
Peer certidp.CertInfo `json:"peer"` |
| 186 |
Server ServerInfo `json:"server"` |
| 187 |
Reason string `json:"reason"` |
| 188 |
} |
| 189 |
|
| 190 |
// OCSPPeerRejectEventMsgType is the schema type for OCSPPeerRejectEventMsg |
| 191 |
const OCSPPeerRejectEventMsgType = "io.nats.server.advisory.v1.ocsp_peer_reject" |
| 192 |
|
| 193 |
// OCSPPeerChainlinkInvalidEventMsg is sent when a certificate (link) in a valid TLS chain is found to be OCSP invalid |
| 194 |
// during a peer TLS handshake. A "peer" can be an inbound client connection or a leaf connection to a remote server. |
| 195 |
// Peer and Link may be the same if the invalid cert was the peer's leaf cert |
| 196 |
type OCSPPeerChainlinkInvalidEventMsg struct { |
| 197 |
TypedEvent |
| 198 |
Link certidp.CertInfo `json:"link"` |
| 199 |
Peer certidp.CertInfo `json:"peer"` |
| 200 |
Server ServerInfo `json:"server"` |
| 201 |
Reason string `json:"reason"` |
| 202 |
} |
| 203 |
|
| 204 |
// OCSPPeerChainlinkInvalidEventMsgType is the schema type for OCSPPeerChainlinkInvalidEventMsg |
| 205 |
const OCSPPeerChainlinkInvalidEventMsgType = "io.nats.server.advisory.v1.ocsp_peer_link_invalid" |
| 206 |
|
| 207 |
// AccountNumConns is an event that will be sent from a server that is tracking |
| 208 |
// a given account when the number of connections changes. It will also HB |
| 209 |
// updates in the absence of any changes. |
| 210 |
type AccountNumConns struct { |
| 211 |
TypedEvent |
| 212 |
Server ServerInfo `json:"server"` |
| 213 |
AccountStat |
| 214 |
} |
| 215 |
|
| 216 |
// AccountStat contains the data common between AccountNumConns and AccountStatz |
| 217 |
type AccountStat struct { |
| 218 |
Account string `json:"acc"` |
| 219 |
Name string `json:"name"` |
| 220 |
Conns int `json:"conns"` |
| 221 |
LeafNodes int `json:"leafnodes"` |
| 222 |
TotalConns int `json:"total_conns"` |
| 223 |
NumSubs uint32 `json:"num_subscriptions"` |
| 224 |
Sent DataStats `json:"sent"` |
| 225 |
Received DataStats `json:"received"` |
| 226 |
SlowConsumers int64 `json:"slow_consumers"` |
| 227 |
} |
| 228 |
|
| 229 |
const AccountNumConnsMsgType = "io.nats.server.advisory.v1.account_connections" |
| 230 |
|
| 231 |
// accNumConnsReq is sent when we are starting to track an account for the first |
| 232 |
// time. We will request others send info to us about their local state. |
| 233 |
type accNumConnsReq struct { |
| 234 |
Server ServerInfo `json:"server"` |
| 235 |
Account string `json:"acc"` |
| 236 |
} |
| 237 |
|
| 238 |
// ServerID is basic static info for a server. |
| 239 |
type ServerID struct { |
| 240 |
Name string `json:"name"` |
| 241 |
Host string `json:"host"` |
| 242 |
ID string `json:"id"` |
| 243 |
} |
| 244 |
|
| 245 |
// Type for our server capabilities. |
| 246 |
type ServerCapability uint64 |
| 247 |
|
| 248 |
// ServerInfo identifies remote servers. |
| 249 |
type ServerInfo struct { |
| 250 |
Name string `json:"name"` |
| 251 |
Host string `json:"host"` |
| 252 |
ID string `json:"id"` |
| 253 |
Cluster string `json:"cluster,omitempty"` |
| 254 |
Domain string `json:"domain,omitempty"` |
| 255 |
Version string `json:"ver"` |
| 256 |
Tags []string `json:"tags,omitempty"` |
| 257 |
Metadata map[string]string `json:"metadata,omitempty"` |
| 258 |
FeatureFlags map[string]bool `json:"feature_flags,omitempty"` |
| 259 |
// Whether JetStream is enabled (deprecated in favor of the `ServerCapability`). |
| 260 |
JetStream bool `json:"jetstream"` |
| 261 |
// Generic capability flags |
| 262 |
Flags ServerCapability `json:"flags"` |
| 263 |
// Sequence and Time from the remote server for this message. |
| 264 |
Seq uint64 `json:"seq"` |
| 265 |
Time time.Time `json:"time"` |
| 266 |
} |
| 267 |
|
| 268 |
const ( |
| 269 |
JetStreamEnabled ServerCapability = 1 << iota // Server had JetStream enabled. |
| 270 |
BinaryStreamSnapshot // New stream snapshot capability. |
| 271 |
AccountNRG // Move NRG traffic out of system account. |
| 272 |
) |
| 273 |
|
| 274 |
// Set JetStream capability. |
| 275 |
func (si *ServerInfo) SetJetStreamEnabled() { |
| 276 |
si.Flags |= JetStreamEnabled |
| 277 |
// Still set old version. |
| 278 |
si.JetStream = true |
| 279 |
} |
| 280 |
|
| 281 |
// JetStreamEnabled indicates whether or not we have JetStream enabled. |
| 282 |
func (si *ServerInfo) JetStreamEnabled() bool { |
| 283 |
// Take into account old version. |
| 284 |
return si.Flags&JetStreamEnabled != 0 || si.JetStream |
| 285 |
} |
| 286 |
|
| 287 |
// Set binary stream snapshot capability. |
| 288 |
func (si *ServerInfo) SetBinaryStreamSnapshot() { |
| 289 |
si.Flags |= BinaryStreamSnapshot |
| 290 |
} |
| 291 |
|
| 292 |
// JetStreamEnabled indicates whether or not we have binary stream snapshot capbilities. |
| 293 |
func (si *ServerInfo) BinaryStreamSnapshot() bool { |
| 294 |
return si.Flags&BinaryStreamSnapshot != 0 |
| 295 |
} |
| 296 |
|
| 297 |
// Set account NRG capability. |
| 298 |
func (si *ServerInfo) SetAccountNRG() { |
| 299 |
si.Flags |= AccountNRG |
| 300 |
} |
| 301 |
|
| 302 |
// AccountNRG indicates whether or not we support moving the NRG traffic out of the |
| 303 |
// system account and into the asset account. |
| 304 |
func (si *ServerInfo) AccountNRG() bool { |
| 305 |
return si.Flags&AccountNRG != 0 |
| 306 |
} |
| 307 |
|
| 308 |
// ClientInfo is detailed information about the client forming a connection. |
| 309 |
type ClientInfo struct { |
| 310 |
Start *time.Time `json:"start,omitempty"` |
| 311 |
Host string `json:"host,omitempty"` |
| 312 |
ID uint64 `json:"id,omitempty"` |
| 313 |
Account string `json:"acc,omitempty"` |
| 314 |
Service string `json:"svc,omitempty"` |
| 315 |
User string `json:"user,omitempty"` |
| 316 |
Name string `json:"name,omitempty"` |
| 317 |
Lang string `json:"lang,omitempty"` |
| 318 |
Version string `json:"ver,omitempty"` |
| 319 |
RTT time.Duration `json:"rtt,omitempty"` |
| 320 |
Server string `json:"server,omitempty"` |
| 321 |
Cluster string `json:"cluster,omitempty"` |
| 322 |
Alternates []string `json:"alts,omitempty"` |
| 323 |
Stop *time.Time `json:"stop,omitempty"` |
| 324 |
Jwt string `json:"jwt,omitempty"` |
| 325 |
IssuerKey string `json:"issuer_key,omitempty"` |
| 326 |
NameTag string `json:"name_tag,omitempty"` |
| 327 |
Tags jwt.TagList `json:"tags,omitempty"` |
| 328 |
Kind string `json:"kind,omitempty"` |
| 329 |
ClientType string `json:"client_type,omitempty"` |
| 330 |
MQTTClient string `json:"client_id,omitempty"` // This is the MQTT client ID |
| 331 |
Nonce string `json:"nonce,omitempty"` |
| 332 |
Reply string `json:"reply,omitempty"` // Original reply subject after a service import (only when needed). |
| 333 |
} |
| 334 |
|
| 335 |
// forAssignmentSnap returns the minimum amount of ClientInfo we need for assignment snapshots. |
| 336 |
func (ci *ClientInfo) forAssignmentSnap() *ClientInfo { |
| 337 |
return &ClientInfo{ |
| 338 |
Account: ci.Account, |
| 339 |
Service: ci.Service, |
| 340 |
Cluster: ci.Cluster, |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
// forProposal returns the minimum amount of ClientInfo we need for assignment proposals. |
| 345 |
func (ci *ClientInfo) forProposal() *ClientInfo { |
| 346 |
if ci == nil { |
| 347 |
return nil |
| 348 |
} |
| 349 |
cci := *ci |
| 350 |
cci.Jwt = _EMPTY_ |
| 351 |
cci.IssuerKey = _EMPTY_ |
| 352 |
return &cci |
| 353 |
} |
| 354 |
|
| 355 |
// forAdvisory returns the minimum amount of ClientInfo we need for JS advisory events. |
| 356 |
func (ci *ClientInfo) forAdvisory() *ClientInfo { |
| 357 |
if ci == nil { |
| 358 |
return nil |
| 359 |
} |
| 360 |
cci := *ci |
| 361 |
cci.Jwt = _EMPTY_ |
| 362 |
cci.Alternates = nil |
| 363 |
return &cci |
| 364 |
} |
| 365 |
|
| 366 |
// ServerStats hold various statistics that we will periodically send out. |
| 367 |
type ServerStats struct { |
| 368 |
Start time.Time `json:"start"` |
| 369 |
Mem int64 `json:"mem"` |
| 370 |
Cores int `json:"cores"` |
| 371 |
CPU float64 `json:"cpu"` |
| 372 |
Connections int `json:"connections"` |
| 373 |
TotalConnections uint64 `json:"total_connections"` |
| 374 |
ActiveAccounts int `json:"active_accounts"` |
| 375 |
NumSubs uint32 `json:"subscriptions"` |
| 376 |
Sent DataStats `json:"sent"` |
| 377 |
SentToClients DataStats `json:"sent_to_clients"` |
| 378 |
Received DataStats `json:"received"` |
| 379 |
ReceivedFromClients DataStats `json:"received_from_clients"` |
| 380 |
SlowConsumers int64 `json:"slow_consumers"` |
| 381 |
SlowConsumersStats *SlowConsumersStats `json:"slow_consumer_stats,omitempty"` |
| 382 |
StaleConnections int64 `json:"stale_connections,omitempty"` |
| 383 |
StaleConnectionStats *StaleConnectionStats `json:"stale_connection_stats,omitempty"` |
| 384 |
StalledClients int64 `json:"stalled_clients,omitempty"` |
| 385 |
Routes []*RouteStat `json:"routes,omitempty"` |
| 386 |
Gateways []*GatewayStat `json:"gateways,omitempty"` |
| 387 |
ActiveServers int `json:"active_servers,omitempty"` |
| 388 |
JetStream *JetStreamVarz `json:"jetstream,omitempty"` |
| 389 |
MemLimit int64 `json:"gomemlimit,omitempty"` |
| 390 |
MaxProcs int `json:"gomaxprocs,omitempty"` |
| 391 |
} |
| 392 |
|
| 393 |
// RouteStat holds route statistics. |
| 394 |
type RouteStat struct { |
| 395 |
ID uint64 `json:"rid"` |
| 396 |
Name string `json:"name,omitempty"` |
| 397 |
Sent DataStats `json:"sent"` |
| 398 |
Received DataStats `json:"received"` |
| 399 |
Pending int `json:"pending"` |
| 400 |
} |
| 401 |
|
| 402 |
// GatewayStat holds gateway statistics. |
| 403 |
type GatewayStat struct { |
| 404 |
ID uint64 `json:"gwid"` |
| 405 |
Name string `json:"name"` |
| 406 |
Sent DataStats `json:"sent"` |
| 407 |
Received DataStats `json:"received"` |
| 408 |
NumInbound int `json:"inbound_connections"` |
| 409 |
} |
| 410 |
|
| 411 |
type MsgBytes struct { |
| 412 |
Msgs int64 `json:"msgs"` |
| 413 |
Bytes int64 `json:"bytes"` |
| 414 |
} |
| 415 |
|
| 416 |
// DataStats reports how may msg and bytes. Applicable for both sent and received. |
| 417 |
type DataStats struct { |
| 418 |
MsgBytes |
| 419 |
Gateways *MsgBytes `json:"gateways,omitempty"` |
| 420 |
Routes *MsgBytes `json:"routes,omitempty"` |
| 421 |
Leafs *MsgBytes `json:"leafs,omitempty"` |
| 422 |
} |
| 423 |
|
| 424 |
// Used for internally queueing up messages that the server wants to send. |
| 425 |
type pubMsg struct { |
| 426 |
c *client |
| 427 |
sub string |
| 428 |
rply string |
| 429 |
si *ServerInfo |
| 430 |
hdr []byte |
| 431 |
msg any |
| 432 |
oct compressionType |
| 433 |
echo bool |
| 434 |
last bool |
| 435 |
} |
| 436 |
|
| 437 |
var pubMsgPool sync.Pool |
| 438 |
|
| 439 |
func newPubMsg(c *client, sub, rply string, si *ServerInfo, hdr []byte, |
| 440 |
msg any, oct compressionType, echo, last bool) *pubMsg { |
| 441 |
|
| 442 |
var m *pubMsg |
| 443 |
pm := pubMsgPool.Get() |
| 444 |
if pm != nil { |
| 445 |
m = pm.(*pubMsg) |
| 446 |
} else { |
| 447 |
m = &pubMsg{} |
| 448 |
} |
| 449 |
// When getting something from a pool it is critical that all fields are |
| 450 |
// initialized. Doing this way guarantees that if someone adds a field to |
| 451 |
// the structure, the compiler will fail the build if this line is not updated. |
| 452 |
(*m) = pubMsg{c, sub, rply, si, hdr, msg, oct, echo, last} |
| 453 |
return m |
| 454 |
} |
| 455 |
|
| 456 |
func (pm *pubMsg) returnToPool() { |
| 457 |
if pm == nil { |
| 458 |
return |
| 459 |
} |
| 460 |
pm.c, pm.sub, pm.rply, pm.si, pm.hdr, pm.msg = nil, _EMPTY_, _EMPTY_, nil, nil, nil |
| 461 |
pubMsgPool.Put(pm) |
| 462 |
} |
| 463 |
|
| 464 |
// Used to track server updates. |
| 465 |
type serverUpdate struct { |
| 466 |
seq uint64 |
| 467 |
ltime time.Time |
| 468 |
} |
| 469 |
|
| 470 |
// TypedEvent is a event or advisory sent by the server that has nats type hints |
| 471 |
// typically used for events that might be consumed by 3rd party event systems |
| 472 |
type TypedEvent struct { |
| 473 |
Type string `json:"type"` |
| 474 |
ID string `json:"id"` |
| 475 |
Time time.Time `json:"timestamp"` |
| 476 |
} |
| 477 |
|
| 478 |
// internalReceiveLoop will be responsible for dispatching all messages that |
| 479 |
// a server receives and needs to internally process, e.g. internal subs. |
| 480 |
func (s *Server) internalReceiveLoop(recvq *ipQueue[*inSysMsg]) { |
| 481 |
for s.eventsRunning() { |
| 482 |
select { |
| 483 |
case <-recvq.ch: |
| 484 |
msgs := recvq.pop() |
| 485 |
for _, m := range msgs { |
| 486 |
if m.cb != nil { |
| 487 |
m.cb(m.sub, m.c, m.acc, m.subj, m.rply, m.hdr, m.msg) |
| 488 |
} |
| 489 |
} |
| 490 |
recvq.recycle(&msgs) |
| 491 |
case <-s.quitCh: |
| 492 |
return |
| 493 |
} |
| 494 |
} |
| 495 |
} |
| 496 |
|
| 497 |
// internalSendLoop will be responsible for serializing all messages that |
| 498 |
// a server wants to send. |
| 499 |
func (s *Server) internalSendLoop(wg *sync.WaitGroup) { |
| 500 |
defer wg.Done() |
| 501 |
|
| 502 |
RESET: |
| 503 |
s.mu.RLock() |
| 504 |
if s.sys == nil || s.sys.sendq == nil { |
| 505 |
s.mu.RUnlock() |
| 506 |
return |
| 507 |
} |
| 508 |
sysc := s.sys.client |
| 509 |
resetCh := s.sys.resetCh |
| 510 |
sendq := s.sys.sendq |
| 511 |
id := s.info.ID |
| 512 |
host := s.info.Host |
| 513 |
servername := s.info.Name |
| 514 |
domain := s.info.Domain |
| 515 |
seqp := &s.sys.seq |
| 516 |
js := s.info.JetStream |
| 517 |
cluster := s.info.Cluster |
| 518 |
if s.gateway.enabled { |
| 519 |
cluster = s.getGatewayName() |
| 520 |
} |
| 521 |
s.mu.RUnlock() |
| 522 |
|
| 523 |
// Grab tags and metadata. |
| 524 |
opts := s.getOpts() |
| 525 |
tags, metadata, featureFlags := opts.Tags, opts.Metadata, opts.getMergedFeatureFlags() |
| 526 |
|
| 527 |
for s.eventsRunning() { |
| 528 |
select { |
| 529 |
case <-sendq.ch: |
| 530 |
msgs := sendq.pop() |
| 531 |
for _, pm := range msgs { |
| 532 |
if si := pm.si; si != nil { |
| 533 |
si.Name = servername |
| 534 |
si.Domain = domain |
| 535 |
si.Host = host |
| 536 |
si.Cluster = cluster |
| 537 |
si.ID = id |
| 538 |
si.Seq = atomic.AddUint64(seqp, 1) |
| 539 |
si.Version = VERSION |
| 540 |
si.Time = time.Now().UTC() |
| 541 |
si.Tags = tags |
| 542 |
si.Metadata = metadata |
| 543 |
si.FeatureFlags = featureFlags |
| 544 |
si.Flags = 0 |
| 545 |
if js { |
| 546 |
// New capability based flags. |
| 547 |
si.SetJetStreamEnabled() |
| 548 |
si.SetBinaryStreamSnapshot() |
| 549 |
if s.accountNRGAllowed.Load() { |
| 550 |
si.SetAccountNRG() |
| 551 |
} |
| 552 |
} |
| 553 |
} |
| 554 |
var b []byte |
| 555 |
if pm.msg != nil { |
| 556 |
switch v := pm.msg.(type) { |
| 557 |
case string: |
| 558 |
b = []byte(v) |
| 559 |
case []byte: |
| 560 |
b = v |
| 561 |
default: |
| 562 |
b, _ = json.Marshal(pm.msg) |
| 563 |
} |
| 564 |
} |
| 565 |
// Setup our client. If the user wants to use a non-system account use our internal |
| 566 |
// account scoped here so that we are not changing out accounts for the system client. |
| 567 |
var c *client |
| 568 |
if pm.c != nil { |
| 569 |
c = pm.c |
| 570 |
} else { |
| 571 |
c = sysc |
| 572 |
} |
| 573 |
|
| 574 |
// Grab client lock. |
| 575 |
c.mu.Lock() |
| 576 |
|
| 577 |
// Prep internal structures needed to send message. |
| 578 |
c.pa.subject, c.pa.reply = []byte(pm.sub), []byte(pm.rply) |
| 579 |
c.pa.size, c.pa.szb = len(b), []byte(strconv.FormatInt(int64(len(b)), 10)) |
| 580 |
c.pa.hdr, c.pa.hdb = -1, nil |
| 581 |
trace := c.trace |
| 582 |
|
| 583 |
// Now check for optional compression. |
| 584 |
var contentHeader string |
| 585 |
var bb bytes.Buffer |
| 586 |
|
| 587 |
if len(b) > 0 { |
| 588 |
switch pm.oct { |
| 589 |
case gzipCompression: |
| 590 |
zw := gzip.NewWriter(&bb) |
| 591 |
zw.Write(b) |
| 592 |
zw.Close() |
| 593 |
b = bb.Bytes() |
| 594 |
contentHeader = "gzip" |
| 595 |
case snappyCompression: |
| 596 |
sw := s2.NewWriter(&bb, s2.WriterSnappyCompat()) |
| 597 |
sw.Write(b) |
| 598 |
sw.Close() |
| 599 |
b = bb.Bytes() |
| 600 |
contentHeader = "snappy" |
| 601 |
case unsupportedCompression: |
| 602 |
contentHeader = "identity" |
| 603 |
} |
| 604 |
} |
| 605 |
// Optional Echo |
| 606 |
replaceEcho := c.echo != pm.echo |
| 607 |
if replaceEcho { |
| 608 |
c.echo = !c.echo |
| 609 |
} |
| 610 |
c.mu.Unlock() |
| 611 |
|
| 612 |
// Add in NL |
| 613 |
b = append(b, _CRLF_...) |
| 614 |
|
| 615 |
// Optional raw header addition. |
| 616 |
if pm.hdr != nil { |
| 617 |
b = append(pm.hdr[:len(pm.hdr):len(pm.hdr)], b...) |
| 618 |
nhdr := len(pm.hdr) |
| 619 |
nsize := len(b) - LEN_CR_LF |
| 620 |
// MQTT producers don't have CRLF, so add it back. |
| 621 |
if c.isMqtt() { |
| 622 |
nsize += LEN_CR_LF |
| 623 |
} |
| 624 |
// Update pubArgs |
| 625 |
// If others will use this later we need to save and restore original. |
| 626 |
c.pa.hdr = nhdr |
| 627 |
c.pa.size = nsize |
| 628 |
c.pa.hdb = []byte(strconv.Itoa(nhdr)) |
| 629 |
c.pa.szb = []byte(strconv.Itoa(nsize)) |
| 630 |
} |
| 631 |
|
| 632 |
// Check if we should set content-encoding |
| 633 |
if contentHeader != _EMPTY_ { |
| 634 |
b = c.setHeader(contentEncodingHeader, contentHeader, b) |
| 635 |
} |
| 636 |
|
| 637 |
// Tracing |
| 638 |
if trace { |
| 639 |
c.traceInOp(fmt.Sprintf("PUB %s %s %d", c.pa.subject, c.pa.reply, c.pa.size), nil) |
| 640 |
c.traceMsg(b) |
| 641 |
} |
| 642 |
|
| 643 |
// Process like a normal inbound msg. |
| 644 |
c.processInboundClientMsg(b) |
| 645 |
|
| 646 |
// Put echo back if needed. |
| 647 |
if replaceEcho { |
| 648 |
c.mu.Lock() |
| 649 |
c.echo = !c.echo |
| 650 |
c.mu.Unlock() |
| 651 |
} |
| 652 |
|
| 653 |
// See if we are doing graceful shutdown. |
| 654 |
if !pm.last { |
| 655 |
c.flushClients(0) // Never spend time in place. |
| 656 |
} else { |
| 657 |
// For the Shutdown event, we need to send in place otherwise |
| 658 |
// there is a chance that the process will exit before the |
| 659 |
// writeLoop has a chance to send it. |
| 660 |
c.flushClients(time.Second) |
| 661 |
sendq.recycle(&msgs) |
| 662 |
return |
| 663 |
} |
| 664 |
pm.returnToPool() |
| 665 |
} |
| 666 |
sendq.recycle(&msgs) |
| 667 |
case <-resetCh: |
| 668 |
goto RESET |
| 669 |
case <-s.quitCh: |
| 670 |
return |
| 671 |
} |
| 672 |
} |
| 673 |
} |
| 674 |
|
| 675 |
// Will send a shutdown message for lame-duck. Unlike sendShutdownEvent, this will |
| 676 |
// not close off the send queue or reply handler, as we may still have a workload |
| 677 |
// that needs migrating off. |
| 678 |
// Lock should be held. |
| 679 |
func (s *Server) sendLDMShutdownEventLocked() { |
| 680 |
if s.sys == nil || s.sys.sendq == nil { |
| 681 |
return |
| 682 |
} |
| 683 |
subj := fmt.Sprintf(lameDuckEventSubj, s.info.ID) |
| 684 |
si := &ServerInfo{} |
| 685 |
s.sys.sendq.push(newPubMsg(nil, subj, _EMPTY_, si, nil, si, noCompression, false, true)) |
| 686 |
} |
| 687 |
|
| 688 |
// Will send a shutdown message. |
| 689 |
func (s *Server) sendShutdownEvent() { |
| 690 |
s.mu.Lock() |
| 691 |
if s.sys == nil || s.sys.sendq == nil { |
| 692 |
s.mu.Unlock() |
| 693 |
return |
| 694 |
} |
| 695 |
subj := fmt.Sprintf(shutdownEventSubj, s.info.ID) |
| 696 |
sendq := s.sys.sendq |
| 697 |
// Stop any more messages from queueing up. |
| 698 |
s.sys.sendq = nil |
| 699 |
// Unhook all msgHandlers. Normal client cleanup will deal with subs, etc. |
| 700 |
s.sys.replies = nil |
| 701 |
// Send to the internal queue and mark as last. |
| 702 |
si := &ServerInfo{} |
| 703 |
sendq.push(newPubMsg(nil, subj, _EMPTY_, si, nil, si, noCompression, false, true)) |
| 704 |
s.mu.Unlock() |
| 705 |
} |
| 706 |
|
| 707 |
// Used to send an internal message to an arbitrary account. |
| 708 |
func (s *Server) sendInternalAccountMsg(a *Account, subject string, msg any) error { |
| 709 |
return s.sendInternalAccountMsgWithReply(a, subject, _EMPTY_, nil, msg, false) |
| 710 |
} |
| 711 |
|
| 712 |
// Used to send an internal message with an optional reply to an arbitrary account. |
| 713 |
func (s *Server) sendInternalAccountMsgWithReply(a *Account, subject, reply string, hdr []byte, msg any, echo bool) error { |
| 714 |
s.mu.RLock() |
| 715 |
if s.sys == nil || s.sys.sendq == nil { |
| 716 |
s.mu.RUnlock() |
| 717 |
if s.isShuttingDown() { |
| 718 |
// Skip in case this was called at the end phase during shut down |
| 719 |
// to avoid too many entries in the logs. |
| 720 |
return nil |
| 721 |
} |
| 722 |
return ErrNoSysAccount |
| 723 |
} |
| 724 |
c := s.sys.client |
| 725 |
// Replace our client with the account's internal client. |
| 726 |
if a != nil { |
| 727 |
a.mu.Lock() |
| 728 |
c = a.internalClient() |
| 729 |
a.mu.Unlock() |
| 730 |
} |
| 731 |
s.sys.sendq.push(newPubMsg(c, subject, reply, nil, hdr, msg, noCompression, echo, false)) |
| 732 |
s.mu.RUnlock() |
| 733 |
return nil |
| 734 |
} |
| 735 |
|
| 736 |
// Send system style message to an account scope. |
| 737 |
func (s *Server) sendInternalAccountSysMsg(a *Account, subj string, si *ServerInfo, msg any, ct compressionType) { |
| 738 |
s.mu.RLock() |
| 739 |
if s.sys == nil || s.sys.sendq == nil || a == nil { |
| 740 |
s.mu.RUnlock() |
| 741 |
return |
| 742 |
} |
| 743 |
sendq := s.sys.sendq |
| 744 |
s.mu.RUnlock() |
| 745 |
|
| 746 |
a.mu.Lock() |
| 747 |
c := a.internalClient() |
| 748 |
a.mu.Unlock() |
| 749 |
|
| 750 |
sendq.push(newPubMsg(c, subj, _EMPTY_, si, nil, msg, ct, false, false)) |
| 751 |
} |
| 752 |
|
| 753 |
// This will queue up a message to be sent. |
| 754 |
// Lock should not be held. |
| 755 |
func (s *Server) sendInternalMsgLocked(subj, rply string, si *ServerInfo, msg any) { |
| 756 |
s.mu.RLock() |
| 757 |
s.sendInternalMsg(subj, rply, si, msg) |
| 758 |
s.mu.RUnlock() |
| 759 |
} |
| 760 |
|
| 761 |
// This will queue up a message to be sent. |
| 762 |
// Assumes lock is held on entry. |
| 763 |
func (s *Server) sendInternalMsg(subj, rply string, si *ServerInfo, msg any) { |
| 764 |
if s.sys == nil || s.sys.sendq == nil { |
| 765 |
return |
| 766 |
} |
| 767 |
s.sys.sendq.push(newPubMsg(nil, subj, rply, si, nil, msg, noCompression, false, false)) |
| 768 |
} |
| 769 |
|
| 770 |
// Will send an api response. |
| 771 |
func (s *Server) sendInternalResponse(subj string, response *ServerAPIResponse) { |
| 772 |
s.mu.RLock() |
| 773 |
if s.sys == nil || s.sys.sendq == nil { |
| 774 |
s.mu.RUnlock() |
| 775 |
return |
| 776 |
} |
| 777 |
s.sys.sendq.push(newPubMsg(nil, subj, _EMPTY_, response.Server, nil, response, response.compress, false, false)) |
| 778 |
s.mu.RUnlock() |
| 779 |
} |
| 780 |
|
| 781 |
// Used to send internal messages from other system clients to avoid no echo issues. |
| 782 |
func (c *client) sendInternalMsg(subj, rply string, si *ServerInfo, msg any) { |
| 783 |
if c == nil { |
| 784 |
return |
| 785 |
} |
| 786 |
s := c.srv |
| 787 |
if s == nil { |
| 788 |
return |
| 789 |
} |
| 790 |
s.mu.RLock() |
| 791 |
if s.sys == nil || s.sys.sendq == nil { |
| 792 |
s.mu.RUnlock() |
| 793 |
return |
| 794 |
} |
| 795 |
s.sys.sendq.push(newPubMsg(c, subj, rply, si, nil, msg, noCompression, false, false)) |
| 796 |
s.mu.RUnlock() |
| 797 |
} |
| 798 |
|
| 799 |
// Locked version of checking if events system running. Also checks server. |
| 800 |
func (s *Server) eventsRunning() bool { |
| 801 |
if s == nil { |
| 802 |
return false |
| 803 |
} |
| 804 |
s.mu.RLock() |
| 805 |
er := s.isRunning() && s.eventsEnabled() |
| 806 |
s.mu.RUnlock() |
| 807 |
return er |
| 808 |
} |
| 809 |
|
| 810 |
// EventsEnabled will report if the server has internal events enabled via |
| 811 |
// a defined system account. |
| 812 |
func (s *Server) EventsEnabled() bool { |
| 813 |
s.mu.RLock() |
| 814 |
defer s.mu.RUnlock() |
| 815 |
return s.eventsEnabled() |
| 816 |
} |
| 817 |
|
| 818 |
// eventsEnabled will report if events are enabled. |
| 819 |
// Lock should be held. |
| 820 |
func (s *Server) eventsEnabled() bool { |
| 821 |
return s.sys != nil && s.sys.client != nil && s.sys.account != nil |
| 822 |
} |
| 823 |
|
| 824 |
// TrackedRemoteServers returns how many remote servers we are tracking |
| 825 |
// from a system events perspective. |
| 826 |
func (s *Server) TrackedRemoteServers() int { |
| 827 |
s.mu.RLock() |
| 828 |
defer s.mu.RUnlock() |
| 829 |
if !s.isRunning() || !s.eventsEnabled() { |
| 830 |
return -1 |
| 831 |
} |
| 832 |
return len(s.sys.servers) |
| 833 |
} |
| 834 |
|
| 835 |
// Check for orphan servers who may have gone away without notification. |
| 836 |
// This should be wrapChk() to setup common locking. |
| 837 |
func (s *Server) checkRemoteServers() { |
| 838 |
now := time.Now() |
| 839 |
for sid, su := range s.sys.servers { |
| 840 |
if now.Sub(su.ltime) > s.sys.orphMax { |
| 841 |
s.Debugf("Detected orphan remote server: %q", sid) |
| 842 |
// Simulate it going away. |
| 843 |
s.processRemoteServerShutdown(sid) |
| 844 |
} |
| 845 |
} |
| 846 |
if s.sys.sweeper != nil { |
| 847 |
s.sys.sweeper.Reset(s.sys.chkOrph) |
| 848 |
} |
| 849 |
} |
| 850 |
|
| 851 |
// Grab RSS and PCPU |
| 852 |
// Server lock will be held but released. |
| 853 |
func (s *Server) updateServerUsage(v *ServerStats) { |
| 854 |
var vss int64 |
| 855 |
pse.ProcUsage(&v.CPU, &v.Mem, &vss) |
| 856 |
v.Cores = runtime.NumCPU() |
| 857 |
v.MaxProcs = runtime.GOMAXPROCS(-1) |
| 858 |
if mm := debug.SetMemoryLimit(-1); mm < math.MaxInt64 { |
| 859 |
v.MemLimit = mm |
| 860 |
} |
| 861 |
} |
| 862 |
|
| 863 |
// Generate a route stat for our statz update. |
| 864 |
func routeStat(r *client) *RouteStat { |
| 865 |
if r == nil { |
| 866 |
return nil |
| 867 |
} |
| 868 |
r.mu.Lock() |
| 869 |
// Note: *client.out[Msgs|Bytes] are not set using atomics, |
| 870 |
// unlike in[Msgs|Bytes]. |
| 871 |
rs := &RouteStat{ |
| 872 |
ID: r.cid, |
| 873 |
Sent: DataStats{ |
| 874 |
MsgBytes: MsgBytes{ |
| 875 |
Msgs: r.outMsgs, |
| 876 |
Bytes: r.outBytes, |
| 877 |
}, |
| 878 |
}, |
| 879 |
Received: DataStats{ |
| 880 |
MsgBytes: MsgBytes{ |
| 881 |
Msgs: atomic.LoadInt64(&r.inMsgs), |
| 882 |
Bytes: atomic.LoadInt64(&r.inBytes), |
| 883 |
}, |
| 884 |
}, |
| 885 |
Pending: int(r.out.pb), |
| 886 |
} |
| 887 |
if r.route != nil { |
| 888 |
rs.Name = r.route.remoteName |
| 889 |
} |
| 890 |
r.mu.Unlock() |
| 891 |
return rs |
| 892 |
} |
| 893 |
|
| 894 |
// Actual send method for statz updates. |
| 895 |
// Lock should be held. |
| 896 |
func (s *Server) sendStatsz(subj string) { |
| 897 |
var m ServerStatsMsg |
| 898 |
s.updateServerUsage(&m.Stats) |
| 899 |
|
| 900 |
if s.limitStatsz(subj) { |
| 901 |
return |
| 902 |
} |
| 903 |
|
| 904 |
s.mu.RLock() |
| 905 |
defer s.mu.RUnlock() |
| 906 |
|
| 907 |
// Check that we have a system account, etc. |
| 908 |
if s.sys == nil || s.sys.account == nil { |
| 909 |
return |
| 910 |
} |
| 911 |
|
| 912 |
shouldCheckInterest := func() bool { |
| 913 |
opts := s.getOpts() |
| 914 |
if opts.Cluster.Port != 0 || opts.Gateway.Port != 0 || opts.LeafNode.Port != 0 { |
| 915 |
return false |
| 916 |
} |
| 917 |
// If we are here we have no clustering or gateways and are not a leafnode hub. |
| 918 |
// Check for leafnode remotes that connect the system account. |
| 919 |
if len(opts.LeafNode.Remotes) > 0 { |
| 920 |
sysAcc := s.sys.account.GetName() |
| 921 |
for _, r := range opts.LeafNode.Remotes { |
| 922 |
if r.LocalAccount == sysAcc { |
| 923 |
return false |
| 924 |
} |
| 925 |
} |
| 926 |
} |
| 927 |
return true |
| 928 |
} |
| 929 |
|
| 930 |
// if we are running standalone, check for interest. |
| 931 |
if shouldCheckInterest() { |
| 932 |
// Check if we even have interest in this subject. |
| 933 |
sacc := s.sys.account |
| 934 |
rr := sacc.sl.Match(subj) |
| 935 |
totalSubs := len(rr.psubs) + len(rr.qsubs) |
| 936 |
if totalSubs == 0 { |
| 937 |
return |
| 938 |
} else if totalSubs == 1 && len(rr.psubs) == 1 { |
| 939 |
// For the broadcast subject we listen to that ourselves with no echo for remote updates. |
| 940 |
// If we are the only ones listening do not send either. |
| 941 |
if rr.psubs[0] == s.sys.remoteStatsSub { |
| 942 |
return |
| 943 |
} |
| 944 |
} |
| 945 |
} |
| 946 |
|
| 947 |
m.Stats.Start = s.start |
| 948 |
m.Stats.Connections = len(s.clients) |
| 949 |
m.Stats.TotalConnections = s.totalClients |
| 950 |
m.Stats.ActiveAccounts = int(atomic.LoadInt32(&s.activeAccounts)) |
| 951 |
m.Stats.Received.Msgs = atomic.LoadInt64(&s.inMsgs) |
| 952 |
m.Stats.Received.Bytes = atomic.LoadInt64(&s.inBytes) |
| 953 |
m.Stats.ReceivedFromClients.Msgs = atomic.LoadInt64(&s.inClientMsgs) |
| 954 |
m.Stats.ReceivedFromClients.Bytes = atomic.LoadInt64(&s.inClientBytes) |
| 955 |
m.Stats.Sent.Msgs = atomic.LoadInt64(&s.outMsgs) |
| 956 |
m.Stats.Sent.Bytes = atomic.LoadInt64(&s.outBytes) |
| 957 |
m.Stats.SentToClients.Msgs = atomic.LoadInt64(&s.outClientMsgs) |
| 958 |
m.Stats.SentToClients.Bytes = atomic.LoadInt64(&s.outClientBytes) |
| 959 |
m.Stats.SlowConsumers = atomic.LoadInt64(&s.slowConsumers) |
| 960 |
// Evaluate the slow consumer stats, but set it only if one of the value is not 0. |
| 961 |
scs := &SlowConsumersStats{ |
| 962 |
Clients: s.NumSlowConsumersClients(), |
| 963 |
Routes: s.NumSlowConsumersRoutes(), |
| 964 |
Gateways: s.NumSlowConsumersGateways(), |
| 965 |
Leafs: s.NumSlowConsumersLeafs(), |
| 966 |
} |
| 967 |
if scs.Clients != 0 || scs.Routes != 0 || scs.Gateways != 0 || scs.Leafs != 0 { |
| 968 |
m.Stats.SlowConsumersStats = scs |
| 969 |
} |
| 970 |
m.Stats.StaleConnections = atomic.LoadInt64(&s.staleConnections) |
| 971 |
m.Stats.StalledClients = atomic.LoadInt64(&s.stalls) |
| 972 |
stcs := &StaleConnectionStats{ |
| 973 |
Clients: s.NumStaleConnectionsClients(), |
| 974 |
Routes: s.NumStaleConnectionsRoutes(), |
| 975 |
Gateways: s.NumStaleConnectionsGateways(), |
| 976 |
Leafs: s.NumStaleConnectionsLeafs(), |
| 977 |
} |
| 978 |
if stcs.Clients != 0 || stcs.Routes != 0 || stcs.Gateways != 0 || stcs.Leafs != 0 { |
| 979 |
m.Stats.StaleConnectionStats = stcs |
| 980 |
} |
| 981 |
m.Stats.NumSubs = s.numSubscriptions() |
| 982 |
// Routes |
| 983 |
s.forEachRoute(func(r *client) { |
| 984 |
m.Stats.Routes = append(m.Stats.Routes, routeStat(r)) |
| 985 |
}) |
| 986 |
// Gateways |
| 987 |
if s.gateway.enabled { |
| 988 |
gw := s.gateway |
| 989 |
gw.RLock() |
| 990 |
for name, c := range gw.out { |
| 991 |
gs := &GatewayStat{Name: name} |
| 992 |
c.mu.Lock() |
| 993 |
gs.ID = c.cid |
| 994 |
// Note that *client.out[Msgs|Bytes] are not set using atomic, |
| 995 |
// unlike the in[Msgs|bytes]. |
| 996 |
gs.Sent = DataStats{ |
| 997 |
MsgBytes: MsgBytes{ |
| 998 |
Msgs: c.outMsgs, |
| 999 |
Bytes: c.outBytes, |
| 1000 |
}, |
| 1001 |
} |
| 1002 |
c.mu.Unlock() |
| 1003 |
// Gather matching inbound connections |
| 1004 |
gs.Received = DataStats{} |
| 1005 |
for _, c := range gw.in { |
| 1006 |
c.mu.Lock() |
| 1007 |
if c.gw.name == name { |
| 1008 |
gs.Received.Msgs += atomic.LoadInt64(&c.inMsgs) |
| 1009 |
gs.Received.Bytes += atomic.LoadInt64(&c.inBytes) |
| 1010 |
gs.NumInbound++ |
| 1011 |
} |
| 1012 |
c.mu.Unlock() |
| 1013 |
} |
| 1014 |
m.Stats.Gateways = append(m.Stats.Gateways, gs) |
| 1015 |
} |
| 1016 |
gw.RUnlock() |
| 1017 |
} |
| 1018 |
// Active Servers |
| 1019 |
m.Stats.ActiveServers = len(s.sys.servers) + 1 |
| 1020 |
|
| 1021 |
// JetStream |
| 1022 |
if js := s.js.Load(); js != nil { |
| 1023 |
jStat := &JetStreamVarz{} |
| 1024 |
s.mu.RUnlock() |
| 1025 |
js.mu.RLock() |
| 1026 |
c := js.config |
| 1027 |
c.StoreDir = _EMPTY_ |
| 1028 |
jStat.Config = &c |
| 1029 |
js.mu.RUnlock() |
| 1030 |
jStat.Stats = js.usageStats() |
| 1031 |
// Update our own usage since we do not echo so we will not hear ourselves. |
| 1032 |
ourNode := getHash(s.serverName()) |
| 1033 |
if v, ok := s.nodeToInfo.Load(ourNode); ok && v != nil { |
| 1034 |
ni := v.(nodeInfo) |
| 1035 |
ni.stats = jStat.Stats |
| 1036 |
ni.cfg = jStat.Config |
| 1037 |
s.optsMu.RLock() |
| 1038 |
ni.tags = copyStrings(s.opts.Tags) |
| 1039 |
s.optsMu.RUnlock() |
| 1040 |
s.nodeToInfo.Store(ourNode, ni) |
| 1041 |
} |
| 1042 |
// Metagroup info. |
| 1043 |
if mg := js.getMetaGroup(); mg != nil { |
| 1044 |
if mg.Leader() { |
| 1045 |
if ci := s.raftNodeToClusterInfo(mg); ci != nil { |
| 1046 |
jStat.Meta = &MetaClusterInfo{ |
| 1047 |
Name: ci.Name, |
| 1048 |
Leader: ci.Leader, |
| 1049 |
Peer: getHash(ci.Leader), |
| 1050 |
Replicas: ci.Replicas, |
| 1051 |
Size: mg.ClusterSize(), |
| 1052 |
} |
| 1053 |
} |
| 1054 |
} else { |
| 1055 |
// non leader only include a shortened version without peers |
| 1056 |
leader := s.serverNameForNode(mg.GroupLeader()) |
| 1057 |
jStat.Meta = &MetaClusterInfo{ |
| 1058 |
Name: mg.Group(), |
| 1059 |
Leader: leader, |
| 1060 |
Peer: getHash(leader), |
| 1061 |
Size: mg.ClusterSize(), |
| 1062 |
} |
| 1063 |
} |
| 1064 |
if jStat.Meta != nil { |
| 1065 |
if ipq := s.jsAPIRoutedReqs; ipq != nil { |
| 1066 |
jStat.Meta.PendingRequests = ipq.len() |
| 1067 |
} |
| 1068 |
if ipq := s.jsAPIRoutedInfoReqs; ipq != nil { |
| 1069 |
jStat.Meta.PendingInfos = ipq.len() |
| 1070 |
} |
| 1071 |
jStat.Meta.Pending = jStat.Meta.PendingRequests + jStat.Meta.PendingInfos |
| 1072 |
jStat.Meta.Snapshot = s.metaClusterSnapshotStats(js, mg) |
| 1073 |
} |
| 1074 |
} |
| 1075 |
jStat.Limits = &s.getOpts().JetStreamLimits |
| 1076 |
m.Stats.JetStream = jStat |
| 1077 |
s.mu.RLock() |
| 1078 |
} |
| 1079 |
// Send message. |
| 1080 |
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m) |
| 1081 |
} |
| 1082 |
|
| 1083 |
// Limit updates to the heartbeat interval, max one second by default. |
| 1084 |
func (s *Server) limitStatsz(subj string) bool { |
| 1085 |
s.mu.Lock() |
| 1086 |
defer s.mu.Unlock() |
| 1087 |
|
| 1088 |
if s.sys == nil { |
| 1089 |
return true |
| 1090 |
} |
| 1091 |
|
| 1092 |
// Only limit the normal broadcast subject. |
| 1093 |
if subj != fmt.Sprintf(serverStatsSubj, s.ID()) { |
| 1094 |
return false |
| 1095 |
} |
| 1096 |
|
| 1097 |
interval := statszRateLimit |
| 1098 |
if s.sys.cstatsz < interval { |
| 1099 |
interval = s.sys.cstatsz |
| 1100 |
} |
| 1101 |
if time.Since(s.sys.lastStatsz) < interval { |
| 1102 |
// Reschedule heartbeat for the next interval. |
| 1103 |
if s.sys.stmr != nil { |
| 1104 |
s.sys.stmr.Reset(time.Until(s.sys.lastStatsz.Add(interval))) |
| 1105 |
} |
| 1106 |
return true |
| 1107 |
} |
| 1108 |
s.sys.lastStatsz = time.Now() |
| 1109 |
return false |
| 1110 |
} |
| 1111 |
|
| 1112 |
// Send out our statz update. |
| 1113 |
// This should be wrapChk() to setup common locking. |
| 1114 |
func (s *Server) heartbeatStatsz() { |
| 1115 |
if s.sys.stmr != nil { |
| 1116 |
// Increase after startup to our max. |
| 1117 |
if s.sys.cstatsz < s.sys.statsz { |
| 1118 |
s.sys.cstatsz *= 2 |
| 1119 |
if s.sys.cstatsz > s.sys.statsz { |
| 1120 |
s.sys.cstatsz = s.sys.statsz |
| 1121 |
} |
| 1122 |
} |
| 1123 |
s.sys.stmr.Reset(s.sys.cstatsz) |
| 1124 |
} |
| 1125 |
// Do in separate Go routine. |
| 1126 |
go s.sendStatszUpdate() |
| 1127 |
} |
| 1128 |
|
| 1129 |
// Reset statsz rate limit for the next broadcast. |
| 1130 |
// This should be wrapChk() to setup common locking. |
| 1131 |
func (s *Server) resetLastStatsz() { |
| 1132 |
s.sys.lastStatsz = time.Time{} |
| 1133 |
} |
| 1134 |
|
| 1135 |
func (s *Server) sendStatszUpdate() { |
| 1136 |
s.sendStatsz(fmt.Sprintf(serverStatsSubj, s.ID())) |
| 1137 |
} |
| 1138 |
|
| 1139 |
// This should be wrapChk() to setup common locking. |
| 1140 |
func (s *Server) startStatszTimer() { |
| 1141 |
// We will start by sending out more of these and trail off to the statsz being the max. |
| 1142 |
s.sys.cstatsz = 250 * time.Millisecond |
| 1143 |
// Send out the first one quickly, we will slowly back off. |
| 1144 |
s.sys.stmr = time.AfterFunc(s.sys.cstatsz, s.wrapChk(s.heartbeatStatsz)) |
| 1145 |
} |
| 1146 |
|
| 1147 |
// Start a ticker that will fire periodically and check for orphaned servers. |
| 1148 |
// This should be wrapChk() to setup common locking. |
| 1149 |
func (s *Server) startRemoteServerSweepTimer() { |
| 1150 |
s.sys.sweeper = time.AfterFunc(s.sys.chkOrph, s.wrapChk(s.checkRemoteServers)) |
| 1151 |
} |
| 1152 |
|
| 1153 |
// Length of our system hash used for server targeted messages. |
| 1154 |
const sysHashLen = 8 |
| 1155 |
|
| 1156 |
// Computes a hash of 8 characters for the name. |
| 1157 |
func getHash(name string) string { |
| 1158 |
return getHashSize(name, sysHashLen) |
| 1159 |
} |
| 1160 |
|
| 1161 |
// Computes a hash for the given `name`. The result will be `size` characters long. |
| 1162 |
func getHashSize(name string, size int) string { |
| 1163 |
sha := sha256.New() |
| 1164 |
sha.Write([]byte(name)) |
| 1165 |
b := sha.Sum(nil) |
| 1166 |
for i := 0; i < size; i++ { |
| 1167 |
b[i] = digits[int(b[i]%base)] |
| 1168 |
} |
| 1169 |
return string(b[:size]) |
| 1170 |
} |
| 1171 |
|
| 1172 |
// Returns the node name for this server which is a hash of the server name. |
| 1173 |
func (s *Server) Node() string { |
| 1174 |
s.mu.RLock() |
| 1175 |
defer s.mu.RUnlock() |
| 1176 |
if s.sys != nil { |
| 1177 |
return s.sys.shash |
| 1178 |
} |
| 1179 |
return _EMPTY_ |
| 1180 |
} |
| 1181 |
|
| 1182 |
// This will setup our system wide tracking subs. |
| 1183 |
// For now we will setup one wildcard subscription to |
| 1184 |
// monitor all accounts for changes in number of connections. |
| 1185 |
// We can make this on a per account tracking basis if needed. |
| 1186 |
// Tradeoff is subscription and interest graph events vs connect and |
| 1187 |
// disconnect events, etc. |
| 1188 |
func (s *Server) initEventTracking() { |
| 1189 |
// Capture sys in case we are shutdown while setting up. |
| 1190 |
s.mu.RLock() |
| 1191 |
sys := s.sys |
| 1192 |
s.mu.RUnlock() |
| 1193 |
|
| 1194 |
if sys == nil || sys.client == nil || sys.account == nil { |
| 1195 |
return |
| 1196 |
} |
| 1197 |
// Create a system hash which we use for other servers to target us specifically. |
| 1198 |
sys.shash = getHash(s.info.Name) |
| 1199 |
|
| 1200 |
// This will be for all inbox responses. |
| 1201 |
subject := fmt.Sprintf(inboxRespSubj, sys.shash, "*") |
| 1202 |
if _, err := s.sysSubscribe(subject, s.inboxReply); err != nil { |
| 1203 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1204 |
return |
| 1205 |
} |
| 1206 |
sys.inboxPre = subject |
| 1207 |
// This is for remote updates for connection accounting. |
| 1208 |
subject = fmt.Sprintf(accConnsEventSubjOld, "*") |
| 1209 |
if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.remoteConnsUpdate)); err != nil { |
| 1210 |
s.Errorf("Error setting up internal tracking for %s: %v", subject, err) |
| 1211 |
return |
| 1212 |
} |
| 1213 |
// This will be for responses for account info that we send out. |
| 1214 |
subject = fmt.Sprintf(connsRespSubj, s.info.ID) |
| 1215 |
if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.remoteConnsUpdate)); err != nil { |
| 1216 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1217 |
return |
| 1218 |
} |
| 1219 |
// Listen for broad requests to respond with number of subscriptions for a given subject. |
| 1220 |
if _, err := s.sysSubscribe(accNumSubsReqSubj, s.noInlineCallback(s.nsubsRequest)); err != nil { |
| 1221 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1222 |
return |
| 1223 |
} |
| 1224 |
// Listen for statsz from others. |
| 1225 |
subject = fmt.Sprintf(serverStatsSubj, "*") |
| 1226 |
if sub, err := s.sysSubscribe(subject, s.noInlineCallback(s.remoteServerUpdate)); err != nil { |
| 1227 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1228 |
return |
| 1229 |
} else { |
| 1230 |
// Keep track of this one. |
| 1231 |
sys.remoteStatsSub = sub |
| 1232 |
} |
| 1233 |
|
| 1234 |
// Listen for all server shutdowns. |
| 1235 |
subject = fmt.Sprintf(shutdownEventSubj, "*") |
| 1236 |
if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.remoteServerShutdown)); err != nil { |
| 1237 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1238 |
return |
| 1239 |
} |
| 1240 |
// Listen for servers entering lame-duck mode. |
| 1241 |
// NOTE: This currently is handled in the same way as a server shutdown, but has |
| 1242 |
// a different subject in case we need to handle differently in future. |
| 1243 |
subject = fmt.Sprintf(lameDuckEventSubj, "*") |
| 1244 |
if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.remoteServerShutdown)); err != nil { |
| 1245 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1246 |
return |
| 1247 |
} |
| 1248 |
// Listen for account claims updates. |
| 1249 |
subscribeToUpdate := true |
| 1250 |
if s.accResolver != nil { |
| 1251 |
subscribeToUpdate = !s.accResolver.IsTrackingUpdate() |
| 1252 |
} |
| 1253 |
if subscribeToUpdate { |
| 1254 |
for _, sub := range []string{accUpdateEventSubjOld, accUpdateEventSubjNew} { |
| 1255 |
if _, err := s.sysSubscribe(fmt.Sprintf(sub, "*"), s.noInlineCallback(s.accountClaimUpdate)); err != nil { |
| 1256 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1257 |
return |
| 1258 |
} |
| 1259 |
} |
| 1260 |
} |
| 1261 |
// Listen for ping messages that will be sent to all servers for statsz. |
| 1262 |
// This subscription is kept for backwards compatibility. Got replaced by ...PING.STATZ from below |
| 1263 |
if _, err := s.sysSubscribe(serverStatsPingReqSubj, s.noInlineCallbackStatsz(s.statszReq)); err != nil { |
| 1264 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1265 |
return |
| 1266 |
} |
| 1267 |
monSrvc := map[string]sysMsgHandler{ |
| 1268 |
"IDZ": s.idzReq, |
| 1269 |
"STATSZ": s.statszReq, |
| 1270 |
"VARZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1271 |
optz := &VarzEventOptions{} |
| 1272 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Varz(&optz.VarzOptions) }) |
| 1273 |
}, |
| 1274 |
"SUBSZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1275 |
optz := &SubszEventOptions{} |
| 1276 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Subsz(&optz.SubszOptions) }) |
| 1277 |
}, |
| 1278 |
"CONNZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1279 |
optz := &ConnzEventOptions{} |
| 1280 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Connz(&optz.ConnzOptions) }) |
| 1281 |
}, |
| 1282 |
"ROUTEZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1283 |
optz := &RoutezEventOptions{} |
| 1284 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Routez(&optz.RoutezOptions) }) |
| 1285 |
}, |
| 1286 |
"GATEWAYZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1287 |
optz := &GatewayzEventOptions{} |
| 1288 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Gatewayz(&optz.GatewayzOptions) }) |
| 1289 |
}, |
| 1290 |
"LEAFZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1291 |
optz := &LeafzEventOptions{} |
| 1292 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Leafz(&optz.LeafzOptions) }) |
| 1293 |
}, |
| 1294 |
"ACCOUNTZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1295 |
optz := &AccountzEventOptions{} |
| 1296 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Accountz(&optz.AccountzOptions) }) |
| 1297 |
}, |
| 1298 |
"JSZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1299 |
optz := &JszEventOptions{} |
| 1300 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Jsz(&optz.JSzOptions) }) |
| 1301 |
}, |
| 1302 |
"HEALTHZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1303 |
optz := &HealthzEventOptions{} |
| 1304 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.healthz(&optz.HealthzOptions), nil }) |
| 1305 |
}, |
| 1306 |
"PROFILEZ": nil, // Special case, see below |
| 1307 |
"EXPVARZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1308 |
optz := &ExpvarzEventOptions{} |
| 1309 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.expvarz(optz), nil }) |
| 1310 |
}, |
| 1311 |
"IPQUEUESZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1312 |
optz := &IpqueueszEventOptions{} |
| 1313 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Ipqueuesz(&optz.IpqueueszOptions), nil }) |
| 1314 |
}, |
| 1315 |
"RAFTZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1316 |
optz := &RaftzEventOptions{} |
| 1317 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Raftz(&optz.RaftzOptions), nil }) |
| 1318 |
}, |
| 1319 |
} |
| 1320 |
profilez := func(_ *subscription, c *client, _ *Account, _, rply string, rmsg []byte) { |
| 1321 |
hdr, msg := c.msgParts(rmsg) |
| 1322 |
// Need to copy since we are passing those to the go routine below. |
| 1323 |
hdr, msg = copyBytes(hdr), copyBytes(msg) |
| 1324 |
// Execute in its own go routine because CPU profiling, for instance, |
| 1325 |
// could take several seconds to complete. |
| 1326 |
go func() { |
| 1327 |
optz := &ProfilezEventOptions{} |
| 1328 |
s.zReq(c, rply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { |
| 1329 |
return s.profilez(&optz.ProfilezOptions), nil |
| 1330 |
}) |
| 1331 |
}() |
| 1332 |
} |
| 1333 |
for name, req := range monSrvc { |
| 1334 |
var h msgHandler |
| 1335 |
switch name { |
| 1336 |
case "PROFILEZ": |
| 1337 |
h = profilez |
| 1338 |
case "STATSZ": |
| 1339 |
h = s.noInlineCallbackStatsz(req) |
| 1340 |
default: |
| 1341 |
h = s.noInlineCallback(req) |
| 1342 |
} |
| 1343 |
subject = fmt.Sprintf(serverDirectReqSubj, s.info.ID, name) |
| 1344 |
if _, err := s.sysSubscribe(subject, h); err != nil { |
| 1345 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1346 |
return |
| 1347 |
} |
| 1348 |
subject = fmt.Sprintf(serverPingReqSubj, name) |
| 1349 |
if _, err := s.sysSubscribe(subject, h); err != nil { |
| 1350 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1351 |
return |
| 1352 |
} |
| 1353 |
} |
| 1354 |
extractAccount := func(subject string) (string, error) { |
| 1355 |
if tk := strings.Split(subject, tsep); len(tk) != accReqTokens { |
| 1356 |
return _EMPTY_, fmt.Errorf("subject %q is malformed", subject) |
| 1357 |
} else { |
| 1358 |
return tk[accReqAccIndex], nil |
| 1359 |
} |
| 1360 |
} |
| 1361 |
monAccSrvc := map[string]sysMsgHandler{ |
| 1362 |
"SUBSZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1363 |
optz := &SubszEventOptions{} |
| 1364 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { |
| 1365 |
if acc, err := extractAccount(subject); err != nil { |
| 1366 |
return nil, err |
| 1367 |
} else { |
| 1368 |
optz.SubszOptions.Subscriptions = true |
| 1369 |
optz.SubszOptions.Account = acc |
| 1370 |
return s.Subsz(&optz.SubszOptions) |
| 1371 |
} |
| 1372 |
}) |
| 1373 |
}, |
| 1374 |
"CONNZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1375 |
optz := &ConnzEventOptions{} |
| 1376 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { |
| 1377 |
if acc, err := extractAccount(subject); err != nil { |
| 1378 |
return nil, err |
| 1379 |
} else { |
| 1380 |
optz.ConnzOptions.Account = acc |
| 1381 |
return s.Connz(&optz.ConnzOptions) |
| 1382 |
} |
| 1383 |
}) |
| 1384 |
}, |
| 1385 |
"LEAFZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1386 |
optz := &LeafzEventOptions{} |
| 1387 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { |
| 1388 |
if acc, err := extractAccount(subject); err != nil { |
| 1389 |
return nil, err |
| 1390 |
} else { |
| 1391 |
optz.LeafzOptions.Account = acc |
| 1392 |
return s.Leafz(&optz.LeafzOptions) |
| 1393 |
} |
| 1394 |
}) |
| 1395 |
}, |
| 1396 |
"JSZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1397 |
optz := &JszEventOptions{} |
| 1398 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { |
| 1399 |
if acc, err := extractAccount(subject); err != nil { |
| 1400 |
return nil, err |
| 1401 |
} else { |
| 1402 |
optz.Account = acc |
| 1403 |
return s.JszAccount(&optz.JSzOptions) |
| 1404 |
} |
| 1405 |
}) |
| 1406 |
}, |
| 1407 |
"INFO": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1408 |
optz := &AccInfoEventOptions{} |
| 1409 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { |
| 1410 |
if acc, err := extractAccount(subject); err != nil { |
| 1411 |
return nil, err |
| 1412 |
} else { |
| 1413 |
return s.accountInfo(acc) |
| 1414 |
} |
| 1415 |
}) |
| 1416 |
}, |
| 1417 |
// STATZ is essentially a duplicate of CONNS with an envelope identical to the others. |
| 1418 |
// For historical reasons CONNS is the odd one out. |
| 1419 |
// STATZ is also less heavy weight than INFO |
| 1420 |
"STATZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1421 |
optz := &AccountStatzEventOptions{} |
| 1422 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { |
| 1423 |
if acc, err := extractAccount(subject); err != nil { |
| 1424 |
return nil, err |
| 1425 |
} else if acc == "PING" { // Filter PING subject. Happens for server as well. But wildcards are not used |
| 1426 |
return nil, errSkipZreq |
| 1427 |
} else { |
| 1428 |
optz.Accounts = []string{acc} |
| 1429 |
if stz, err := s.AccountStatz(&optz.AccountStatzOptions); err != nil { |
| 1430 |
return nil, err |
| 1431 |
} else if len(stz.Accounts) == 0 && !optz.IncludeUnused { |
| 1432 |
return nil, errSkipZreq |
| 1433 |
} else { |
| 1434 |
return stz, nil |
| 1435 |
} |
| 1436 |
} |
| 1437 |
}) |
| 1438 |
}, |
| 1439 |
"CONNS": s.connsRequest, |
| 1440 |
} |
| 1441 |
for name, req := range monAccSrvc { |
| 1442 |
if _, err := s.sysSubscribe(fmt.Sprintf(accDirectReqSubj, "*", name), s.noInlineCallback(req)); err != nil { |
| 1443 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1444 |
return |
| 1445 |
} |
| 1446 |
} |
| 1447 |
|
| 1448 |
// User info. Do not propagate interest so that we know the local server to the connection |
| 1449 |
// is the only one that will answer the requests. |
| 1450 |
if _, err := s.sysSubscribeInternal(fmt.Sprintf(userDirectReqSubj, "*"), s.userInfoReq); err != nil { |
| 1451 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1452 |
return |
| 1453 |
} |
| 1454 |
|
| 1455 |
// For now only the STATZ subject has an account specific ping equivalent. |
| 1456 |
if _, err := s.sysSubscribe(fmt.Sprintf(accPingReqSubj, "STATZ"), |
| 1457 |
s.noInlineCallback(func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1458 |
optz := &AccountStatzEventOptions{} |
| 1459 |
s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { |
| 1460 |
if stz, err := s.AccountStatz(&optz.AccountStatzOptions); err != nil { |
| 1461 |
return nil, err |
| 1462 |
} else if len(stz.Accounts) == 0 && !optz.IncludeUnused { |
| 1463 |
return nil, errSkipZreq |
| 1464 |
} else { |
| 1465 |
return stz, nil |
| 1466 |
} |
| 1467 |
}) |
| 1468 |
})); err != nil { |
| 1469 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1470 |
return |
| 1471 |
} |
| 1472 |
|
| 1473 |
// Listen for updates when leaf nodes connect for a given account. This will |
| 1474 |
// force any gateway connections to move to `modeInterestOnly` |
| 1475 |
subject = fmt.Sprintf(leafNodeConnectEventSubj, "*") |
| 1476 |
if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.leafNodeConnected)); err != nil { |
| 1477 |
s.Errorf("Error setting up internal tracking: %v", err) |
| 1478 |
return |
| 1479 |
} |
| 1480 |
// For tracking remote latency measurements. |
| 1481 |
subject = fmt.Sprintf(remoteLatencyEventSubj, sys.shash) |
| 1482 |
if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.remoteLatencyUpdate)); err != nil { |
| 1483 |
s.Errorf("Error setting up internal latency tracking: %v", err) |
| 1484 |
return |
| 1485 |
} |
| 1486 |
// This is for simple debugging of number of subscribers that exist in the system. |
| 1487 |
if _, err := s.sysSubscribeInternal(accSubsSubj, s.noInlineCallback(s.debugSubscribers)); err != nil { |
| 1488 |
s.Errorf("Error setting up internal debug service for subscribers: %v", err) |
| 1489 |
return |
| 1490 |
} |
| 1491 |
|
| 1492 |
// Listen for requests to reload the server configuration. |
| 1493 |
subject = fmt.Sprintf(serverReloadReqSubj, s.info.ID) |
| 1494 |
if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.reloadConfig)); err != nil { |
| 1495 |
s.Errorf("Error setting up server reload handler: %v", err) |
| 1496 |
return |
| 1497 |
} |
| 1498 |
|
| 1499 |
// Client connection kick |
| 1500 |
subject = fmt.Sprintf(clientKickReqSubj, s.info.ID) |
| 1501 |
if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.kickClient)); err != nil { |
| 1502 |
s.Errorf("Error setting up client kick service: %v", err) |
| 1503 |
return |
| 1504 |
} |
| 1505 |
// Client connection LDM |
| 1506 |
subject = fmt.Sprintf(clientLDMReqSubj, s.info.ID) |
| 1507 |
if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.ldmClient)); err != nil { |
| 1508 |
s.Errorf("Error setting up client LDM service: %v", err) |
| 1509 |
return |
| 1510 |
} |
| 1511 |
} |
| 1512 |
|
| 1513 |
// UserInfo returns basic information to a user about bound account and user permissions. |
| 1514 |
// For account information they will need to ping that separately, and this allows security |
| 1515 |
// controls on each subsystem if desired, e.g. account info, jetstream account info, etc. |
| 1516 |
type UserInfo struct { |
| 1517 |
UserID string `json:"user"` |
| 1518 |
Account string `json:"account"` |
| 1519 |
AccountName string `json:"account_name,omitempty"` |
| 1520 |
UserName string `json:"user_name,omitempty"` |
| 1521 |
Permissions *Permissions `json:"permissions,omitempty"` |
| 1522 |
Expires time.Duration `json:"expires,omitempty"` |
| 1523 |
} |
| 1524 |
|
| 1525 |
// Process a user info request. |
| 1526 |
func (s *Server) userInfoReq(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) { |
| 1527 |
if !s.EventsEnabled() || reply == _EMPTY_ { |
| 1528 |
return |
| 1529 |
} |
| 1530 |
|
| 1531 |
response := &ServerAPIResponse{Server: &ServerInfo{}} |
| 1532 |
|
| 1533 |
ci, _, _, _, err := s.getRequestInfo(c, msg) |
| 1534 |
if err != nil { |
| 1535 |
response.Error = &ApiError{Code: http.StatusBadRequest} |
| 1536 |
s.sendInternalResponse(reply, response) |
| 1537 |
return |
| 1538 |
} |
| 1539 |
|
| 1540 |
// Look up the requester's account directly from ci.Account rather than |
| 1541 |
// using the acc returned by getRequestInfo, which may resolve to the |
| 1542 |
// service account (ci.Service) when the request arrives via a chained |
| 1543 |
// service import. |
| 1544 |
var accountName string |
| 1545 |
if ci.Account != _EMPTY_ { |
| 1546 |
if reqAcc, _ := s.LookupAccount(ci.Account); reqAcc != nil { |
| 1547 |
accountName = reqAcc.getNameTag() |
| 1548 |
} |
| 1549 |
} |
| 1550 |
|
| 1551 |
response.Data = &UserInfo{ |
| 1552 |
UserID: ci.User, |
| 1553 |
Account: ci.Account, |
| 1554 |
AccountName: accountName, |
| 1555 |
UserName: ci.NameTag, |
| 1556 |
Permissions: c.publicPermissions(), |
| 1557 |
Expires: c.claimExpiration(), |
| 1558 |
} |
| 1559 |
s.sendInternalResponse(reply, response) |
| 1560 |
} |
| 1561 |
|
| 1562 |
// register existing accounts with any system exports. |
| 1563 |
func (s *Server) registerSystemImportsForExisting() { |
| 1564 |
var accounts []*Account |
| 1565 |
|
| 1566 |
s.mu.RLock() |
| 1567 |
if s.sys == nil { |
| 1568 |
s.mu.RUnlock() |
| 1569 |
return |
| 1570 |
} |
| 1571 |
sacc := s.sys.account |
| 1572 |
s.accounts.Range(func(k, v any) bool { |
| 1573 |
a := v.(*Account) |
| 1574 |
if a != sacc { |
| 1575 |
accounts = append(accounts, a) |
| 1576 |
} |
| 1577 |
return true |
| 1578 |
}) |
| 1579 |
s.mu.RUnlock() |
| 1580 |
|
| 1581 |
for _, a := range accounts { |
| 1582 |
s.registerSystemImports(a) |
| 1583 |
} |
| 1584 |
} |
| 1585 |
|
| 1586 |
// add all exports a system account will need |
| 1587 |
func (s *Server) addSystemAccountExports(sacc *Account) { |
| 1588 |
if !s.EventsEnabled() { |
| 1589 |
return |
| 1590 |
} |
| 1591 |
accConnzSubj := fmt.Sprintf(accDirectReqSubj, "*", "CONNZ") |
| 1592 |
// prioritize not automatically added exports |
| 1593 |
if !sacc.hasServiceExportMatching(accConnzSubj) { |
| 1594 |
// pick export type that clamps importing account id into subject |
| 1595 |
if err := sacc.addServiceExportWithResponseAndAccountPos(accConnzSubj, Streamed, nil, 4); err != nil { |
| 1596 |
//if err := sacc.AddServiceExportWithResponse(accConnzSubj, Streamed, nil); err != nil { |
| 1597 |
s.Errorf("Error adding system service export for %q: %v", accConnzSubj, err) |
| 1598 |
} |
| 1599 |
} |
| 1600 |
// prioritize not automatically added exports |
| 1601 |
accStatzSubj := fmt.Sprintf(accDirectReqSubj, "*", "STATZ") |
| 1602 |
if !sacc.hasServiceExportMatching(accStatzSubj) { |
| 1603 |
// pick export type that clamps importing account id into subject |
| 1604 |
if err := sacc.addServiceExportWithResponseAndAccountPos(accStatzSubj, Streamed, nil, 4); err != nil { |
| 1605 |
s.Errorf("Error adding system service export for %q: %v", accStatzSubj, err) |
| 1606 |
} |
| 1607 |
} |
| 1608 |
// FIXME(dlc) - Old experiment, Remove? |
| 1609 |
if !sacc.hasServiceExportMatching(accSubsSubj) { |
| 1610 |
if err := sacc.AddServiceExport(accSubsSubj, nil); err != nil { |
| 1611 |
s.Errorf("Error adding system service export for %q: %v", accSubsSubj, err) |
| 1612 |
} |
| 1613 |
} |
| 1614 |
|
| 1615 |
// User info export. |
| 1616 |
userInfoSubj := fmt.Sprintf(userDirectReqSubj, "*") |
| 1617 |
if !sacc.hasServiceExportMatching(userInfoSubj) { |
| 1618 |
if err := sacc.AddServiceExport(userInfoSubj, nil); err != nil { |
| 1619 |
s.Errorf("Error adding system service export for %q: %v", userInfoSubj, err) |
| 1620 |
} |
| 1621 |
mappedSubj := fmt.Sprintf(userDirectReqSubj, sacc.GetName()) |
| 1622 |
if err := sacc.AddServiceImport(sacc, userDirectInfoSubj, mappedSubj); err != nil { |
| 1623 |
s.Errorf("Error setting up system service import %s: %v", mappedSubj, err) |
| 1624 |
} |
| 1625 |
// Make sure to share details. |
| 1626 |
sacc.setServiceImportSharing(sacc, mappedSubj, false, true) |
| 1627 |
} |
| 1628 |
|
| 1629 |
// Register any accounts that existed prior. |
| 1630 |
s.registerSystemImportsForExisting() |
| 1631 |
|
| 1632 |
// in case of a mixed mode setup, enable js exports anyway |
| 1633 |
if s.JetStreamEnabled() || !s.standAloneMode() { |
| 1634 |
s.checkJetStreamExports() |
| 1635 |
} |
| 1636 |
} |
| 1637 |
|
| 1638 |
// accountClaimUpdate will receive claim updates for accounts. |
| 1639 |
func (s *Server) accountClaimUpdate(sub *subscription, c *client, _ *Account, subject, resp string, hdr, msg []byte) { |
| 1640 |
if !s.EventsEnabled() { |
| 1641 |
return |
| 1642 |
} |
| 1643 |
var pubKey string |
| 1644 |
toks := strings.Split(subject, tsep) |
| 1645 |
if len(toks) == accUpdateTokensNew { |
| 1646 |
pubKey = toks[accReqAccIndex] |
| 1647 |
} else if len(toks) == accUpdateTokensOld { |
| 1648 |
pubKey = toks[accUpdateAccIdxOld] |
| 1649 |
} else { |
| 1650 |
s.Debugf("Received account claims update on bad subject %q", subject) |
| 1651 |
return |
| 1652 |
} |
| 1653 |
if len(msg) == 0 { |
| 1654 |
err := errors.New("request body is empty") |
| 1655 |
respondToUpdate(s, resp, pubKey, "jwt update error", err) |
| 1656 |
} else if claim, err := jwt.DecodeAccountClaims(string(msg)); err != nil { |
| 1657 |
respondToUpdate(s, resp, pubKey, "jwt update resulted in error", err) |
| 1658 |
} else if claim.Subject != pubKey { |
| 1659 |
err := errors.New("subject does not match jwt content") |
| 1660 |
respondToUpdate(s, resp, pubKey, "jwt update resulted in error", err) |
| 1661 |
} else if v, ok := s.accounts.Load(pubKey); !ok { |
| 1662 |
respondToUpdate(s, resp, pubKey, "jwt update skipped", nil) |
| 1663 |
} else if err := s.updateAccountWithClaimJWT(v.(*Account), string(msg)); err != nil { |
| 1664 |
respondToUpdate(s, resp, pubKey, "jwt update resulted in error", err) |
| 1665 |
} else { |
| 1666 |
respondToUpdate(s, resp, pubKey, "jwt updated", nil) |
| 1667 |
} |
| 1668 |
} |
| 1669 |
|
| 1670 |
// processRemoteServerShutdown will update any affected accounts. |
| 1671 |
// Will update the remote count for clients. |
| 1672 |
// Lock assume held. |
| 1673 |
func (s *Server) processRemoteServerShutdown(sid string) { |
| 1674 |
s.accounts.Range(func(k, v any) bool { |
| 1675 |
v.(*Account).removeRemoteServer(sid) |
| 1676 |
return true |
| 1677 |
}) |
| 1678 |
// Update any state in nodeInfo. |
| 1679 |
s.nodeToInfo.Range(func(k, v any) bool { |
| 1680 |
ni := v.(nodeInfo) |
| 1681 |
if ni.id == sid { |
| 1682 |
ni.offline = true |
| 1683 |
s.nodeToInfo.Store(k, ni) |
| 1684 |
return false |
| 1685 |
} |
| 1686 |
return true |
| 1687 |
}) |
| 1688 |
delete(s.sys.servers, sid) |
| 1689 |
} |
| 1690 |
|
| 1691 |
func (s *Server) sameDomain(domain string) bool { |
| 1692 |
return domain == _EMPTY_ || s.info.Domain == _EMPTY_ || domain == s.info.Domain |
| 1693 |
} |
| 1694 |
|
| 1695 |
// remoteServerShutdown is called when we get an event from another server shutting down. |
| 1696 |
func (s *Server) remoteServerShutdown(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1697 |
s.mu.Lock() |
| 1698 |
defer s.mu.Unlock() |
| 1699 |
if !s.eventsEnabled() { |
| 1700 |
return |
| 1701 |
} |
| 1702 |
toks := strings.Split(subject, tsep) |
| 1703 |
if len(toks) < shutdownEventTokens { |
| 1704 |
s.Debugf("Received remote server shutdown on bad subject %q", subject) |
| 1705 |
return |
| 1706 |
} |
| 1707 |
|
| 1708 |
if len(msg) == 0 { |
| 1709 |
s.Errorf("Remote server sent invalid (empty) shutdown message to %q", subject) |
| 1710 |
return |
| 1711 |
} |
| 1712 |
|
| 1713 |
// We have an optional serverInfo here, remove from nodeToX lookups. |
| 1714 |
var si ServerInfo |
| 1715 |
if err := json.Unmarshal(msg, &si); err != nil { |
| 1716 |
s.Debugf("Received bad server info for remote server shutdown") |
| 1717 |
return |
| 1718 |
} |
| 1719 |
|
| 1720 |
// JetStream node updates if applicable. |
| 1721 |
node := getHash(si.Name) |
| 1722 |
if v, ok := s.nodeToInfo.Load(node); ok && v != nil { |
| 1723 |
ni := v.(nodeInfo) |
| 1724 |
ni.offline = true |
| 1725 |
s.nodeToInfo.Store(node, ni) |
| 1726 |
} |
| 1727 |
|
| 1728 |
sid := toks[serverSubjectIndex] |
| 1729 |
if su := s.sys.servers[sid]; su != nil { |
| 1730 |
s.processRemoteServerShutdown(sid) |
| 1731 |
} |
| 1732 |
} |
| 1733 |
|
| 1734 |
// remoteServerUpdate listens for statsz updates from other servers. |
| 1735 |
func (s *Server) remoteServerUpdate(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1736 |
var ssm ServerStatsMsg |
| 1737 |
if len(msg) == 0 { |
| 1738 |
s.Debugf("Received empty server info for remote server update") |
| 1739 |
return |
| 1740 |
} else if err := json.Unmarshal(msg, &ssm); err != nil { |
| 1741 |
s.Debugf("Received bad server info for remote server update") |
| 1742 |
return |
| 1743 |
} |
| 1744 |
si := ssm.Server |
| 1745 |
|
| 1746 |
// Should do normal updates before bailing if wrong domain. |
| 1747 |
s.mu.Lock() |
| 1748 |
if s.isRunning() && s.eventsEnabled() && ssm.Server.ID != s.info.ID { |
| 1749 |
s.updateRemoteServer(&si) |
| 1750 |
} |
| 1751 |
s.mu.Unlock() |
| 1752 |
|
| 1753 |
// JetStream node updates. |
| 1754 |
if !s.sameDomain(si.Domain) { |
| 1755 |
return |
| 1756 |
} |
| 1757 |
|
| 1758 |
var cfg *JetStreamConfig |
| 1759 |
var stats *JetStreamStats |
| 1760 |
|
| 1761 |
if ssm.Stats.JetStream != nil { |
| 1762 |
cfg = ssm.Stats.JetStream.Config |
| 1763 |
stats = ssm.Stats.JetStream.Stats |
| 1764 |
} |
| 1765 |
|
| 1766 |
node := getHash(si.Name) |
| 1767 |
accountNRG := si.AccountNRG() |
| 1768 |
oldInfo, _ := s.nodeToInfo.Swap(node, nodeInfo{ |
| 1769 |
name: si.Name, |
| 1770 |
version: si.Version, |
| 1771 |
cluster: si.Cluster, |
| 1772 |
domain: si.Domain, |
| 1773 |
id: si.ID, |
| 1774 |
tags: si.Tags, |
| 1775 |
cfg: cfg, |
| 1776 |
stats: stats, |
| 1777 |
offline: false, |
| 1778 |
js: si.JetStreamEnabled(), |
| 1779 |
binarySnapshots: si.BinaryStreamSnapshot(), |
| 1780 |
accountNRG: accountNRG, |
| 1781 |
}) |
| 1782 |
if oldInfo == nil || accountNRG != oldInfo.(nodeInfo).accountNRG { |
| 1783 |
// One of the servers we received statsz from changed its mind about |
| 1784 |
// whether or not it supports in-account NRG, so update the groups |
| 1785 |
// with this information. |
| 1786 |
s.updateNRGAccountStatus() |
| 1787 |
} |
| 1788 |
} |
| 1789 |
|
| 1790 |
// updateRemoteServer is called when we have an update from a remote server. |
| 1791 |
// This allows us to track remote servers, respond to shutdown messages properly, |
| 1792 |
// make sure that messages are ordered, and allow us to prune dead servers. |
| 1793 |
// Lock should be held upon entry. |
| 1794 |
func (s *Server) updateRemoteServer(si *ServerInfo) { |
| 1795 |
su := s.sys.servers[si.ID] |
| 1796 |
if su == nil { |
| 1797 |
s.sys.servers[si.ID] = &serverUpdate{si.Seq, time.Now()} |
| 1798 |
s.processNewServer(si) |
| 1799 |
} else { |
| 1800 |
// Should always be going up. |
| 1801 |
if si.Seq <= su.seq { |
| 1802 |
s.Errorf("Received out of order remote server update from: %q", si.ID) |
| 1803 |
return |
| 1804 |
} |
| 1805 |
su.seq = si.Seq |
| 1806 |
su.ltime = time.Now() |
| 1807 |
} |
| 1808 |
} |
| 1809 |
|
| 1810 |
// processNewServer will hold any logic we want to use when we discover a new server. |
| 1811 |
// Lock should be held upon entry. |
| 1812 |
func (s *Server) processNewServer(si *ServerInfo) { |
| 1813 |
// Right now we only check if we have leafnode servers and if so send another |
| 1814 |
// connect update to make sure they switch this account to interest only mode. |
| 1815 |
s.ensureGWsInterestOnlyForLeafNodes() |
| 1816 |
|
| 1817 |
// Add to our nodeToName |
| 1818 |
if s.sameDomain(si.Domain) { |
| 1819 |
node := getHash(si.Name) |
| 1820 |
// Only update if non-existent |
| 1821 |
if _, ok := s.nodeToInfo.Load(node); !ok { |
| 1822 |
s.nodeToInfo.Store(node, nodeInfo{ |
| 1823 |
name: si.Name, |
| 1824 |
version: si.Version, |
| 1825 |
cluster: si.Cluster, |
| 1826 |
domain: si.Domain, |
| 1827 |
id: si.ID, |
| 1828 |
tags: si.Tags, |
| 1829 |
cfg: nil, |
| 1830 |
stats: nil, |
| 1831 |
offline: false, |
| 1832 |
js: si.JetStreamEnabled(), |
| 1833 |
binarySnapshots: si.BinaryStreamSnapshot(), |
| 1834 |
accountNRG: si.AccountNRG(), |
| 1835 |
}) |
| 1836 |
} |
| 1837 |
} |
| 1838 |
go s.updateNRGAccountStatus() |
| 1839 |
// Announce ourselves.. |
| 1840 |
// Do this in a separate Go routine. |
| 1841 |
go s.sendStatszUpdate() |
| 1842 |
} |
| 1843 |
|
| 1844 |
// Works out whether all nodes support moving the NRG traffic into |
| 1845 |
// the account and moves it appropriately. |
| 1846 |
// Server lock MUST NOT be held on entry. |
| 1847 |
func (s *Server) updateNRGAccountStatus() { |
| 1848 |
s.rnMu.RLock() |
| 1849 |
raftNodes := make([]RaftNode, 0, len(s.raftNodes)) |
| 1850 |
for _, n := range s.raftNodes { |
| 1851 |
raftNodes = append(raftNodes, n) |
| 1852 |
} |
| 1853 |
s.rnMu.RUnlock() |
| 1854 |
for _, n := range raftNodes { |
| 1855 |
// In the event that the node is happy that all nodes that |
| 1856 |
// it cares about haven't changed, this will be a no-op. |
| 1857 |
if err := n.RecreateInternalSubs(); err != nil { |
| 1858 |
n.Stop() |
| 1859 |
} |
| 1860 |
} |
| 1861 |
} |
| 1862 |
|
| 1863 |
// If GW is enabled on this server and there are any leaf node connections, |
| 1864 |
// this function will send a LeafNode connect system event to the super cluster |
| 1865 |
// to ensure that the GWs are in interest-only mode for this account. |
| 1866 |
// Lock should be held upon entry. |
| 1867 |
// TODO(dlc) - this will cause this account to be loaded on all servers. Need a better |
| 1868 |
// way with GW2. |
| 1869 |
func (s *Server) ensureGWsInterestOnlyForLeafNodes() { |
| 1870 |
if !s.gateway.enabled || len(s.leafs) == 0 { |
| 1871 |
return |
| 1872 |
} |
| 1873 |
sent := make(map[*Account]bool, len(s.leafs)) |
| 1874 |
for _, c := range s.leafs { |
| 1875 |
if !sent[c.acc] { |
| 1876 |
s.sendLeafNodeConnectMsg(c.acc.Name) |
| 1877 |
sent[c.acc] = true |
| 1878 |
} |
| 1879 |
} |
| 1880 |
} |
| 1881 |
|
| 1882 |
// shutdownEventing will clean up all eventing state. |
| 1883 |
func (s *Server) shutdownEventing() { |
| 1884 |
if !s.eventsRunning() { |
| 1885 |
return |
| 1886 |
} |
| 1887 |
|
| 1888 |
s.mu.Lock() |
| 1889 |
if s.sys == nil || s.sys.resetCh == nil { |
| 1890 |
s.mu.Unlock() |
| 1891 |
return |
| 1892 |
} |
| 1893 |
clearTimer(&s.sys.sweeper) |
| 1894 |
clearTimer(&s.sys.stmr) |
| 1895 |
// We intentionally do not close resetCh. A sender that captured the channel |
| 1896 |
// may still attempt to send after the internal send loop has exited. |
| 1897 |
s.sys.resetCh = nil |
| 1898 |
wg := &s.sys.wg |
| 1899 |
s.mu.Unlock() |
| 1900 |
|
| 1901 |
// We will queue up a shutdown event and wait for the |
| 1902 |
// internal send loop to exit. |
| 1903 |
s.sendShutdownEvent() |
| 1904 |
wg.Wait() |
| 1905 |
|
| 1906 |
s.mu.Lock() |
| 1907 |
defer s.mu.Unlock() |
| 1908 |
|
| 1909 |
// Whip through all accounts. |
| 1910 |
s.accounts.Range(func(k, v any) bool { |
| 1911 |
v.(*Account).clearEventing() |
| 1912 |
return true |
| 1913 |
}) |
| 1914 |
// Turn everything off here. |
| 1915 |
s.sys = nil |
| 1916 |
} |
| 1917 |
|
| 1918 |
// Request for our local connection count. |
| 1919 |
func (s *Server) connsRequest(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1920 |
if !s.eventsRunning() { |
| 1921 |
return |
| 1922 |
} |
| 1923 |
tk := strings.Split(subject, tsep) |
| 1924 |
if len(tk) != accReqTokens { |
| 1925 |
s.sys.client.Errorf("Bad subject account connections request message") |
| 1926 |
return |
| 1927 |
} |
| 1928 |
a := tk[accReqAccIndex] |
| 1929 |
m := accNumConnsReq{Account: a} |
| 1930 |
if len(msg) > 0 { |
| 1931 |
if err := json.Unmarshal(msg, &m); err != nil { |
| 1932 |
s.sys.client.Errorf("Error unmarshalling account connections request message: %v", err) |
| 1933 |
return |
| 1934 |
} |
| 1935 |
} |
| 1936 |
if m.Account != a { |
| 1937 |
s.sys.client.Errorf("Error unmarshalled account does not match subject") |
| 1938 |
return |
| 1939 |
} |
| 1940 |
// Here we really only want to lookup the account if its local. We do not want to fetch this |
| 1941 |
// account if we have no interest in it. |
| 1942 |
var acc *Account |
| 1943 |
if v, ok := s.accounts.Load(m.Account); ok { |
| 1944 |
acc = v.(*Account) |
| 1945 |
} |
| 1946 |
if acc == nil { |
| 1947 |
return |
| 1948 |
} |
| 1949 |
// We know this is a local connection. |
| 1950 |
if nlc := acc.NumLocalConnections(); nlc > 0 { |
| 1951 |
s.mu.Lock() |
| 1952 |
s.sendAccConnsUpdate(acc, reply) |
| 1953 |
s.mu.Unlock() |
| 1954 |
} |
| 1955 |
} |
| 1956 |
|
| 1957 |
// leafNodeConnected is an event we will receive when a leaf node for a given account connects. |
| 1958 |
func (s *Server) leafNodeConnected(sub *subscription, _ *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 1959 |
m := accNumConnsReq{} |
| 1960 |
if err := json.Unmarshal(msg, &m); err != nil { |
| 1961 |
s.sys.client.Errorf("Error unmarshalling account connections request message: %v", err) |
| 1962 |
return |
| 1963 |
} |
| 1964 |
|
| 1965 |
s.mu.RLock() |
| 1966 |
na := m.Account == _EMPTY_ || !s.eventsEnabled() || !s.gateway.enabled |
| 1967 |
s.mu.RUnlock() |
| 1968 |
|
| 1969 |
if na { |
| 1970 |
return |
| 1971 |
} |
| 1972 |
|
| 1973 |
if acc, _ := s.lookupAccount(m.Account); acc != nil { |
| 1974 |
s.switchAccountToInterestMode(acc.Name) |
| 1975 |
} |
| 1976 |
} |
| 1977 |
|
| 1978 |
// Common filter options for system requests STATSZ VARZ SUBSZ CONNZ ROUTEZ GATEWAYZ LEAFZ |
| 1979 |
type EventFilterOptions struct { |
| 1980 |
Name string `json:"server_name,omitempty"` // filter by server name |
| 1981 |
Cluster string `json:"cluster,omitempty"` // filter by cluster name |
| 1982 |
Host string `json:"host,omitempty"` // filter by host name |
| 1983 |
ExactMatch bool `json:"exact_match,omitempty"` // if the above filters should use exact matching or only "contains" |
| 1984 |
Tags []string `json:"tags,omitempty"` // filter by tags (must match all tags) |
| 1985 |
Domain string `json:"domain,omitempty"` // filter by JS domain |
| 1986 |
} |
| 1987 |
|
| 1988 |
// StatszEventOptions are options passed to Statsz |
| 1989 |
type StatszEventOptions struct { |
| 1990 |
// No actual options yet |
| 1991 |
EventFilterOptions |
| 1992 |
} |
| 1993 |
|
| 1994 |
// Options for account Info |
| 1995 |
type AccInfoEventOptions struct { |
| 1996 |
// No actual options yet |
| 1997 |
EventFilterOptions |
| 1998 |
} |
| 1999 |
|
| 2000 |
// In the context of system events, ConnzEventOptions are options passed to Connz |
| 2001 |
type ConnzEventOptions struct { |
| 2002 |
ConnzOptions |
| 2003 |
EventFilterOptions |
| 2004 |
} |
| 2005 |
|
| 2006 |
// In the context of system events, RoutezEventOptions are options passed to Routez |
| 2007 |
type RoutezEventOptions struct { |
| 2008 |
RoutezOptions |
| 2009 |
EventFilterOptions |
| 2010 |
} |
| 2011 |
|
| 2012 |
// In the context of system events, SubzEventOptions are options passed to Subz |
| 2013 |
type SubszEventOptions struct { |
| 2014 |
SubszOptions |
| 2015 |
EventFilterOptions |
| 2016 |
} |
| 2017 |
|
| 2018 |
// In the context of system events, VarzEventOptions are options passed to Varz |
| 2019 |
type VarzEventOptions struct { |
| 2020 |
VarzOptions |
| 2021 |
EventFilterOptions |
| 2022 |
} |
| 2023 |
|
| 2024 |
// In the context of system events, GatewayzEventOptions are options passed to Gatewayz |
| 2025 |
type GatewayzEventOptions struct { |
| 2026 |
GatewayzOptions |
| 2027 |
EventFilterOptions |
| 2028 |
} |
| 2029 |
|
| 2030 |
// In the context of system events, LeafzEventOptions are options passed to Leafz |
| 2031 |
type LeafzEventOptions struct { |
| 2032 |
LeafzOptions |
| 2033 |
EventFilterOptions |
| 2034 |
} |
| 2035 |
|
| 2036 |
// In the context of system events, AccountzEventOptions are options passed to Accountz |
| 2037 |
type AccountzEventOptions struct { |
| 2038 |
AccountzOptions |
| 2039 |
EventFilterOptions |
| 2040 |
} |
| 2041 |
|
| 2042 |
// In the context of system events, AccountzEventOptions are options passed to Accountz |
| 2043 |
type AccountStatzEventOptions struct { |
| 2044 |
AccountStatzOptions |
| 2045 |
EventFilterOptions |
| 2046 |
} |
| 2047 |
|
| 2048 |
// In the context of system events, JszEventOptions are options passed to Jsz |
| 2049 |
type JszEventOptions struct { |
| 2050 |
JSzOptions |
| 2051 |
EventFilterOptions |
| 2052 |
} |
| 2053 |
|
| 2054 |
// In the context of system events, HealthzEventOptions are options passed to Healthz |
| 2055 |
type HealthzEventOptions struct { |
| 2056 |
HealthzOptions |
| 2057 |
EventFilterOptions |
| 2058 |
} |
| 2059 |
|
| 2060 |
// In the context of system events, ProfilezEventOptions are options passed to Profilez |
| 2061 |
type ProfilezEventOptions struct { |
| 2062 |
ProfilezOptions |
| 2063 |
EventFilterOptions |
| 2064 |
} |
| 2065 |
|
| 2066 |
// In the context of system events, ExpvarzEventOptions are options passed to Expvarz |
| 2067 |
type ExpvarzEventOptions struct { |
| 2068 |
EventFilterOptions |
| 2069 |
} |
| 2070 |
|
| 2071 |
// In the context of system events, IpqueueszEventOptions are options passed to Ipqueuesz |
| 2072 |
type IpqueueszEventOptions struct { |
| 2073 |
EventFilterOptions |
| 2074 |
IpqueueszOptions |
| 2075 |
} |
| 2076 |
|
| 2077 |
// In the context of system events, RaftzEventOptions are options passed to Raftz |
| 2078 |
type RaftzEventOptions struct { |
| 2079 |
EventFilterOptions |
| 2080 |
RaftzOptions |
| 2081 |
} |
| 2082 |
|
| 2083 |
// returns true if the request does NOT apply to this server and can be ignored. |
| 2084 |
// DO NOT hold the server lock when calling this. |
| 2085 |
func (s *Server) filterRequest(fOpts *EventFilterOptions) bool { |
| 2086 |
if fOpts == nil { |
| 2087 |
return false |
| 2088 |
} |
| 2089 |
if fOpts.ExactMatch { |
| 2090 |
if (fOpts.Name != _EMPTY_ && fOpts.Name != s.info.Name) || |
| 2091 |
(fOpts.Host != _EMPTY_ && fOpts.Host != s.info.Host) || |
| 2092 |
(fOpts.Cluster != _EMPTY_ && fOpts.Cluster != s.ClusterName()) { |
| 2093 |
return true |
| 2094 |
} |
| 2095 |
} else if (fOpts.Name != _EMPTY_ && !strings.Contains(s.info.Name, fOpts.Name)) || |
| 2096 |
(fOpts.Host != _EMPTY_ && !strings.Contains(s.info.Host, fOpts.Host)) || |
| 2097 |
(fOpts.Cluster != _EMPTY_ && !strings.Contains(s.ClusterName(), fOpts.Cluster)) { |
| 2098 |
return true |
| 2099 |
} |
| 2100 |
if len(fOpts.Tags) > 0 { |
| 2101 |
opts := s.getOpts() |
| 2102 |
for _, t := range fOpts.Tags { |
| 2103 |
if !opts.Tags.Contains(t) { |
| 2104 |
return true |
| 2105 |
} |
| 2106 |
} |
| 2107 |
} |
| 2108 |
if fOpts.Domain != _EMPTY_ && s.getOpts().JetStreamDomain != fOpts.Domain { |
| 2109 |
return true |
| 2110 |
} |
| 2111 |
return false |
| 2112 |
} |
| 2113 |
|
| 2114 |
// Encoding support (compression) |
| 2115 |
type compressionType int8 |
| 2116 |
|
| 2117 |
const ( |
| 2118 |
noCompression = compressionType(iota) |
| 2119 |
gzipCompression |
| 2120 |
snappyCompression |
| 2121 |
unsupportedCompression |
| 2122 |
) |
| 2123 |
|
| 2124 |
// ServerAPIResponse is the response type for the server API like varz, connz etc. |
| 2125 |
type ServerAPIResponse struct { |
| 2126 |
Server *ServerInfo `json:"server"` |
| 2127 |
Data any `json:"data,omitempty"` |
| 2128 |
Error *ApiError `json:"error,omitempty"` |
| 2129 |
|
| 2130 |
// Private to indicate compression if any. |
| 2131 |
compress compressionType |
| 2132 |
} |
| 2133 |
|
| 2134 |
// Specialized response types for unmarshalling. These structures are not |
| 2135 |
// used in the server code and only there for users of the Z endpoints to |
| 2136 |
// unmarshal the data without having to create these structs in their code |
| 2137 |
|
| 2138 |
// ServerAPIConnzResponse is the response type connz |
| 2139 |
type ServerAPIConnzResponse struct { |
| 2140 |
Server *ServerInfo `json:"server"` |
| 2141 |
Data *Connz `json:"data,omitempty"` |
| 2142 |
Error *ApiError `json:"error,omitempty"` |
| 2143 |
} |
| 2144 |
|
| 2145 |
// ServerAPIRoutezResponse is the response type for routez |
| 2146 |
type ServerAPIRoutezResponse struct { |
| 2147 |
Server *ServerInfo `json:"server"` |
| 2148 |
Data *Routez `json:"data,omitempty"` |
| 2149 |
Error *ApiError `json:"error,omitempty"` |
| 2150 |
} |
| 2151 |
|
| 2152 |
// ServerAPIGatewayzResponse is the response type for gatewayz |
| 2153 |
type ServerAPIGatewayzResponse struct { |
| 2154 |
Server *ServerInfo `json:"server"` |
| 2155 |
Data *Gatewayz `json:"data,omitempty"` |
| 2156 |
Error *ApiError `json:"error,omitempty"` |
| 2157 |
} |
| 2158 |
|
| 2159 |
// ServerAPIJszResponse is the response type for jsz |
| 2160 |
type ServerAPIJszResponse struct { |
| 2161 |
Server *ServerInfo `json:"server"` |
| 2162 |
Data *JSInfo `json:"data,omitempty"` |
| 2163 |
Error *ApiError `json:"error,omitempty"` |
| 2164 |
} |
| 2165 |
|
| 2166 |
// ServerAPIHealthzResponse is the response type for healthz |
| 2167 |
type ServerAPIHealthzResponse struct { |
| 2168 |
Server *ServerInfo `json:"server"` |
| 2169 |
Data *HealthStatus `json:"data,omitempty"` |
| 2170 |
Error *ApiError `json:"error,omitempty"` |
| 2171 |
} |
| 2172 |
|
| 2173 |
// ServerAPIVarzResponse is the response type for varz |
| 2174 |
type ServerAPIVarzResponse struct { |
| 2175 |
Server *ServerInfo `json:"server"` |
| 2176 |
Data *Varz `json:"data,omitempty"` |
| 2177 |
Error *ApiError `json:"error,omitempty"` |
| 2178 |
} |
| 2179 |
|
| 2180 |
// ServerAPISubszResponse is the response type for subsz |
| 2181 |
type ServerAPISubszResponse struct { |
| 2182 |
Server *ServerInfo `json:"server"` |
| 2183 |
Data *Subsz `json:"data,omitempty"` |
| 2184 |
Error *ApiError `json:"error,omitempty"` |
| 2185 |
} |
| 2186 |
|
| 2187 |
// ServerAPILeafzResponse is the response type for leafz |
| 2188 |
type ServerAPILeafzResponse struct { |
| 2189 |
Server *ServerInfo `json:"server"` |
| 2190 |
Data *Leafz `json:"data,omitempty"` |
| 2191 |
Error *ApiError `json:"error,omitempty"` |
| 2192 |
} |
| 2193 |
|
| 2194 |
// ServerAPIAccountzResponse is the response type for accountz |
| 2195 |
type ServerAPIAccountzResponse struct { |
| 2196 |
Server *ServerInfo `json:"server"` |
| 2197 |
Data *Accountz `json:"data,omitempty"` |
| 2198 |
Error *ApiError `json:"error,omitempty"` |
| 2199 |
} |
| 2200 |
|
| 2201 |
// ServerAPIExpvarzResponse is the response type for expvarz |
| 2202 |
type ServerAPIExpvarzResponse struct { |
| 2203 |
Server *ServerInfo `json:"server"` |
| 2204 |
Data *ExpvarzStatus `json:"data,omitempty"` |
| 2205 |
Error *ApiError `json:"error,omitempty"` |
| 2206 |
} |
| 2207 |
|
| 2208 |
// ServerAPIpqueueszResponse is the response type for ipqueuesz |
| 2209 |
type ServerAPIpqueueszResponse struct { |
| 2210 |
Server *ServerInfo `json:"server"` |
| 2211 |
Data *IpqueueszStatus `json:"data,omitempty"` |
| 2212 |
Error *ApiError `json:"error,omitempty"` |
| 2213 |
} |
| 2214 |
|
| 2215 |
// ServerAPIRaftzResponse is the response type for raftz |
| 2216 |
type ServerAPIRaftzResponse struct { |
| 2217 |
Server *ServerInfo `json:"server"` |
| 2218 |
Data *RaftzStatus `json:"data,omitempty"` |
| 2219 |
Error *ApiError `json:"error,omitempty"` |
| 2220 |
} |
| 2221 |
|
| 2222 |
// statszReq is a request for us to respond with current statsz. |
| 2223 |
func (s *Server) statszReq(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 2224 |
if !s.EventsEnabled() { |
| 2225 |
return |
| 2226 |
} |
| 2227 |
|
| 2228 |
// No reply is a signal that we should use our normal broadcast subject. |
| 2229 |
if reply == _EMPTY_ { |
| 2230 |
reply = fmt.Sprintf(serverStatsSubj, s.info.ID) |
| 2231 |
s.wrapChk(s.resetLastStatsz)() |
| 2232 |
} |
| 2233 |
|
| 2234 |
opts := StatszEventOptions{} |
| 2235 |
if len(msg) != 0 { |
| 2236 |
if err := json.Unmarshal(msg, &opts); err != nil { |
| 2237 |
response := &ServerAPIResponse{ |
| 2238 |
Server: &ServerInfo{}, |
| 2239 |
Error: &ApiError{Code: http.StatusBadRequest, Description: err.Error()}, |
| 2240 |
} |
| 2241 |
s.sendInternalMsgLocked(reply, _EMPTY_, response.Server, response) |
| 2242 |
return |
| 2243 |
} else if ignore := s.filterRequest(&opts.EventFilterOptions); ignore { |
| 2244 |
return |
| 2245 |
} |
| 2246 |
} |
| 2247 |
s.sendStatsz(reply) |
| 2248 |
} |
| 2249 |
|
| 2250 |
// idzReq is for a request for basic static server info. |
| 2251 |
// Try to not hold the write lock or dynamically create data. |
| 2252 |
func (s *Server) idzReq(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 2253 |
s.mu.RLock() |
| 2254 |
defer s.mu.RUnlock() |
| 2255 |
id := &ServerID{ |
| 2256 |
Name: s.info.Name, |
| 2257 |
Host: s.info.Host, |
| 2258 |
ID: s.info.ID, |
| 2259 |
} |
| 2260 |
s.sendInternalMsg(reply, _EMPTY_, nil, &id) |
| 2261 |
} |
| 2262 |
|
| 2263 |
var errSkipZreq = errors.New("filtered response") |
| 2264 |
|
| 2265 |
const ( |
| 2266 |
acceptEncodingHeader = "Accept-Encoding" |
| 2267 |
contentEncodingHeader = "Content-Encoding" |
| 2268 |
) |
| 2269 |
|
| 2270 |
// This is not as formal as it could be. We see if anything has s2 or snappy first, then gzip. |
| 2271 |
func getAcceptEncoding(hdr []byte) compressionType { |
| 2272 |
ae := strings.ToLower(string(getHeader(acceptEncodingHeader, hdr))) |
| 2273 |
if ae == _EMPTY_ { |
| 2274 |
return noCompression |
| 2275 |
} |
| 2276 |
if strings.Contains(ae, "snappy") || strings.Contains(ae, "s2") { |
| 2277 |
return snappyCompression |
| 2278 |
} |
| 2279 |
if strings.Contains(ae, "gzip") { |
| 2280 |
return gzipCompression |
| 2281 |
} |
| 2282 |
return unsupportedCompression |
| 2283 |
} |
| 2284 |
|
| 2285 |
func (s *Server) zReq(_ *client, reply string, hdr, msg []byte, fOpts *EventFilterOptions, optz any, respf func() (any, error)) { |
| 2286 |
if !s.EventsEnabled() || reply == _EMPTY_ { |
| 2287 |
return |
| 2288 |
} |
| 2289 |
response := &ServerAPIResponse{Server: &ServerInfo{}} |
| 2290 |
var err error |
| 2291 |
status := 0 |
| 2292 |
if len(msg) != 0 { |
| 2293 |
if err = json.Unmarshal(msg, optz); err != nil { |
| 2294 |
status = http.StatusBadRequest // status is only included on error, so record how far execution got |
| 2295 |
} else if s.filterRequest(fOpts) { |
| 2296 |
return |
| 2297 |
} |
| 2298 |
} |
| 2299 |
if err == nil { |
| 2300 |
response.Data, err = respf() |
| 2301 |
if errors.Is(err, errSkipZreq) { |
| 2302 |
return |
| 2303 |
} else if err != nil { |
| 2304 |
status = http.StatusInternalServerError |
| 2305 |
} |
| 2306 |
} |
| 2307 |
if err != nil { |
| 2308 |
response.Error = &ApiError{Code: status, Description: err.Error()} |
| 2309 |
} else if len(hdr) > 0 { |
| 2310 |
response.compress = getAcceptEncoding(hdr) |
| 2311 |
} |
| 2312 |
s.sendInternalResponse(reply, response) |
| 2313 |
} |
| 2314 |
|
| 2315 |
// remoteConnsUpdate gets called when we receive a remote update from another server. |
| 2316 |
func (s *Server) remoteConnsUpdate(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 2317 |
if !s.eventsRunning() { |
| 2318 |
return |
| 2319 |
} |
| 2320 |
var m AccountNumConns |
| 2321 |
if len(msg) == 0 { |
| 2322 |
s.sys.client.Errorf("No message body provided") |
| 2323 |
return |
| 2324 |
} else if err := json.Unmarshal(msg, &m); err != nil { |
| 2325 |
s.sys.client.Errorf("Error unmarshalling account connection event message: %v", err) |
| 2326 |
return |
| 2327 |
} |
| 2328 |
|
| 2329 |
// See if we have the account registered, if not drop it. |
| 2330 |
// Make sure this does not force us to load this account here. |
| 2331 |
var acc *Account |
| 2332 |
if v, ok := s.accounts.Load(m.Account); ok { |
| 2333 |
acc = v.(*Account) |
| 2334 |
} |
| 2335 |
// Silently ignore these if we do not have local interest in the account. |
| 2336 |
if acc == nil { |
| 2337 |
return |
| 2338 |
} |
| 2339 |
|
| 2340 |
s.mu.Lock() |
| 2341 |
|
| 2342 |
// check again here if we have been shutdown. |
| 2343 |
if !s.isRunning() || !s.eventsEnabled() { |
| 2344 |
s.mu.Unlock() |
| 2345 |
return |
| 2346 |
} |
| 2347 |
// Double check that this is not us, should never happen, so error if it does. |
| 2348 |
if m.Server.ID == s.info.ID { |
| 2349 |
s.sys.client.Errorf("Processing our own account connection event message: ignored") |
| 2350 |
s.mu.Unlock() |
| 2351 |
return |
| 2352 |
} |
| 2353 |
// If we are here we have interest in tracking this account. Update our accounting. |
| 2354 |
clients := acc.updateRemoteServer(&m) |
| 2355 |
s.updateRemoteServer(&m.Server) |
| 2356 |
s.mu.Unlock() |
| 2357 |
// Need to close clients outside of server lock |
| 2358 |
for _, c := range clients { |
| 2359 |
c.maxAccountConnExceeded() |
| 2360 |
} |
| 2361 |
} |
| 2362 |
|
| 2363 |
// This will import any system level exports. |
| 2364 |
func (s *Server) registerSystemImports(a *Account) { |
| 2365 |
if a == nil || !s.EventsEnabled() { |
| 2366 |
return |
| 2367 |
} |
| 2368 |
sacc := s.SystemAccount() |
| 2369 |
if sacc == nil || sacc == a { |
| 2370 |
return |
| 2371 |
} |
| 2372 |
dstAccName := sacc.Name |
| 2373 |
// FIXME(dlc) - make a shared list between sys exports etc. |
| 2374 |
|
| 2375 |
importSrvc := func(subj, mappedSubj string) { |
| 2376 |
if !a.serviceImportExists(dstAccName, subj) { |
| 2377 |
if err := a.addServiceImportWithClaim(sacc, subj, mappedSubj, nil, true); err != nil { |
| 2378 |
s.Errorf("Error setting up system service import %s -> %s for account: %v", |
| 2379 |
subj, mappedSubj, err) |
| 2380 |
} |
| 2381 |
} |
| 2382 |
} |
| 2383 |
// Add in this to the account in 2 places. |
| 2384 |
// "$SYS.REQ.SERVER.PING.CONNZ" and "$SYS.REQ.ACCOUNT.PING.CONNZ" |
| 2385 |
mappedConnzSubj := fmt.Sprintf(accDirectReqSubj, a.Name, "CONNZ") |
| 2386 |
importSrvc(fmt.Sprintf(accPingReqSubj, "CONNZ"), mappedConnzSubj) |
| 2387 |
importSrvc(fmt.Sprintf(serverPingReqSubj, "CONNZ"), mappedConnzSubj) |
| 2388 |
importSrvc(fmt.Sprintf(accPingReqSubj, "STATZ"), fmt.Sprintf(accDirectReqSubj, a.Name, "STATZ")) |
| 2389 |
|
| 2390 |
// This is for user's looking up their own info. |
| 2391 |
mappedSubject := fmt.Sprintf(userDirectReqSubj, a.Name) |
| 2392 |
importSrvc(userDirectInfoSubj, mappedSubject) |
| 2393 |
// Make sure to share details. |
| 2394 |
a.setServiceImportSharing(sacc, mappedSubject, false, true) |
| 2395 |
} |
| 2396 |
|
| 2397 |
// Setup tracking for this account. This allows us to track global account activity. |
| 2398 |
// Lock should be held on entry. |
| 2399 |
func (s *Server) enableAccountTracking(a *Account) { |
| 2400 |
if a == nil || !s.eventsEnabled() { |
| 2401 |
return |
| 2402 |
} |
| 2403 |
|
| 2404 |
// TODO(ik): Generate payload although message may not be sent. |
| 2405 |
// May need to ensure we do so only if there is a known interest. |
| 2406 |
// This can get complicated with gateways. |
| 2407 |
|
| 2408 |
subj := fmt.Sprintf(accDirectReqSubj, a.Name, "CONNS") |
| 2409 |
reply := fmt.Sprintf(connsRespSubj, s.info.ID) |
| 2410 |
m := accNumConnsReq{Account: a.Name} |
| 2411 |
s.sendInternalMsg(subj, reply, &m.Server, &m) |
| 2412 |
} |
| 2413 |
|
| 2414 |
// Event on leaf node connect. |
| 2415 |
// Lock should NOT be held on entry. |
| 2416 |
func (s *Server) sendLeafNodeConnect(a *Account) { |
| 2417 |
s.mu.Lock() |
| 2418 |
// If we are not in operator mode, or do not have any gateways defined, this should also be a no-op. |
| 2419 |
if a == nil || !s.eventsEnabled() || !s.gateway.enabled { |
| 2420 |
s.mu.Unlock() |
| 2421 |
return |
| 2422 |
} |
| 2423 |
s.sendLeafNodeConnectMsg(a.Name) |
| 2424 |
s.mu.Unlock() |
| 2425 |
|
| 2426 |
s.switchAccountToInterestMode(a.Name) |
| 2427 |
} |
| 2428 |
|
| 2429 |
// Send the leafnode connect message. |
| 2430 |
// Lock should be held. |
| 2431 |
func (s *Server) sendLeafNodeConnectMsg(accName string) { |
| 2432 |
subj := fmt.Sprintf(leafNodeConnectEventSubj, accName) |
| 2433 |
m := accNumConnsReq{Account: accName} |
| 2434 |
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m) |
| 2435 |
} |
| 2436 |
|
| 2437 |
// sendAccConnsUpdate is called to send out our information on the |
| 2438 |
// account's local connections. |
| 2439 |
// Lock should be held on entry. |
| 2440 |
func (s *Server) sendAccConnsUpdate(a *Account, subj ...string) { |
| 2441 |
if !s.eventsEnabled() || a == nil { |
| 2442 |
return |
| 2443 |
} |
| 2444 |
sendQ := s.sys.sendq |
| 2445 |
if sendQ == nil { |
| 2446 |
return |
| 2447 |
} |
| 2448 |
// Build event with account name and number of local clients and leafnodes. |
| 2449 |
eid := s.nextEventID() |
| 2450 |
a.mu.Lock() |
| 2451 |
stat := a.statz() |
| 2452 |
m := AccountNumConns{ |
| 2453 |
TypedEvent: TypedEvent{ |
| 2454 |
Type: AccountNumConnsMsgType, |
| 2455 |
ID: eid, |
| 2456 |
Time: time.Now().UTC(), |
| 2457 |
}, |
| 2458 |
AccountStat: *stat, |
| 2459 |
} |
| 2460 |
// Set timer to fire again unless we are at zero. |
| 2461 |
if m.TotalConns == 0 { |
| 2462 |
clearTimer(&a.ctmr) |
| 2463 |
} else { |
| 2464 |
// Check to see if we have an HB running and update. |
| 2465 |
if a.ctmr == nil { |
| 2466 |
a.ctmr = time.AfterFunc(eventsHBInterval, func() { s.accConnsUpdate(a) }) |
| 2467 |
} else { |
| 2468 |
a.ctmr.Reset(eventsHBInterval) |
| 2469 |
} |
| 2470 |
} |
| 2471 |
for _, sub := range subj { |
| 2472 |
msg := newPubMsg(nil, sub, _EMPTY_, &m.Server, nil, &m, noCompression, false, false) |
| 2473 |
sendQ.push(msg) |
| 2474 |
} |
| 2475 |
a.mu.Unlock() |
| 2476 |
} |
| 2477 |
|
| 2478 |
// Lock should be held on entry. |
| 2479 |
func (a *Account) statz() *AccountStat { |
| 2480 |
localConns := a.numLocalConnections() |
| 2481 |
leafConns := a.numLocalLeafNodes() |
| 2482 |
|
| 2483 |
a.stats.Lock() |
| 2484 |
received := DataStats{ |
| 2485 |
MsgBytes: MsgBytes{ |
| 2486 |
Msgs: a.stats.inMsgs, |
| 2487 |
Bytes: a.stats.inBytes, |
| 2488 |
}, |
| 2489 |
Gateways: &MsgBytes{ |
| 2490 |
Msgs: a.stats.gw.inMsgs, |
| 2491 |
Bytes: a.stats.gw.inBytes, |
| 2492 |
}, |
| 2493 |
Routes: &MsgBytes{ |
| 2494 |
Msgs: a.stats.rt.inMsgs, |
| 2495 |
Bytes: a.stats.rt.inBytes, |
| 2496 |
}, |
| 2497 |
Leafs: &MsgBytes{ |
| 2498 |
Msgs: a.stats.ln.inMsgs, |
| 2499 |
Bytes: a.stats.ln.inBytes, |
| 2500 |
}, |
| 2501 |
} |
| 2502 |
sent := DataStats{ |
| 2503 |
MsgBytes: MsgBytes{ |
| 2504 |
Msgs: a.stats.outMsgs, |
| 2505 |
Bytes: a.stats.outBytes, |
| 2506 |
}, |
| 2507 |
Gateways: &MsgBytes{ |
| 2508 |
Msgs: a.stats.gw.outMsgs, |
| 2509 |
Bytes: a.stats.gw.outBytes, |
| 2510 |
}, |
| 2511 |
Routes: &MsgBytes{ |
| 2512 |
Msgs: a.stats.rt.outMsgs, |
| 2513 |
Bytes: a.stats.rt.outBytes, |
| 2514 |
}, |
| 2515 |
Leafs: &MsgBytes{ |
| 2516 |
Msgs: a.stats.ln.outMsgs, |
| 2517 |
Bytes: a.stats.ln.outBytes, |
| 2518 |
}, |
| 2519 |
} |
| 2520 |
slowConsumers := a.stats.slowConsumers |
| 2521 |
a.stats.Unlock() |
| 2522 |
|
| 2523 |
return &AccountStat{ |
| 2524 |
Account: a.Name, |
| 2525 |
Name: a.getNameTagLocked(), |
| 2526 |
Conns: localConns, |
| 2527 |
LeafNodes: leafConns, |
| 2528 |
TotalConns: localConns + leafConns, |
| 2529 |
NumSubs: a.sl.Count(), |
| 2530 |
Received: received, |
| 2531 |
Sent: sent, |
| 2532 |
SlowConsumers: slowConsumers, |
| 2533 |
} |
| 2534 |
} |
| 2535 |
|
| 2536 |
// accConnsUpdate is called whenever there is a change to the account's |
| 2537 |
// number of active connections, or during a heartbeat. |
| 2538 |
// We will not send for $G. |
| 2539 |
func (s *Server) accConnsUpdate(a *Account) { |
| 2540 |
s.mu.Lock() |
| 2541 |
defer s.mu.Unlock() |
| 2542 |
if !s.eventsEnabled() || a == nil || a == s.gacc { |
| 2543 |
return |
| 2544 |
} |
| 2545 |
s.sendAccConnsUpdate(a, fmt.Sprintf(accConnsEventSubjOld, a.Name), fmt.Sprintf(accConnsEventSubjNew, a.Name)) |
| 2546 |
} |
| 2547 |
|
| 2548 |
// server lock should be held |
| 2549 |
func (s *Server) nextEventID() string { |
| 2550 |
return s.eventIds.Next() |
| 2551 |
} |
| 2552 |
|
| 2553 |
// accountConnectEvent will send an account client connect event if there is interest. |
| 2554 |
// This is a billing event. |
| 2555 |
func (s *Server) accountConnectEvent(c *client) { |
| 2556 |
s.mu.Lock() |
| 2557 |
if !s.eventsEnabled() { |
| 2558 |
s.mu.Unlock() |
| 2559 |
return |
| 2560 |
} |
| 2561 |
eid := s.nextEventID() |
| 2562 |
s.mu.Unlock() |
| 2563 |
|
| 2564 |
c.mu.Lock() |
| 2565 |
if c.acc == nil { |
| 2566 |
c.mu.Unlock() |
| 2567 |
return |
| 2568 |
} |
| 2569 |
|
| 2570 |
m := ConnectEventMsg{ |
| 2571 |
TypedEvent: TypedEvent{ |
| 2572 |
Type: ConnectEventMsgType, |
| 2573 |
ID: eid, |
| 2574 |
Time: time.Now().UTC(), |
| 2575 |
}, |
| 2576 |
Client: ClientInfo{ |
| 2577 |
Start: &c.start, |
| 2578 |
Host: c.host, |
| 2579 |
ID: c.cid, |
| 2580 |
Account: accForClient(c), |
| 2581 |
User: c.getRawAuthUser(), |
| 2582 |
Name: c.opts.Name, |
| 2583 |
Lang: c.opts.Lang, |
| 2584 |
Version: c.opts.Version, |
| 2585 |
Jwt: c.opts.JWT, |
| 2586 |
IssuerKey: issuerForClient(c), |
| 2587 |
Tags: c.tags, |
| 2588 |
NameTag: c.acc.getNameTag(), |
| 2589 |
Kind: c.kindString(), |
| 2590 |
ClientType: c.clientTypeString(), |
| 2591 |
MQTTClient: c.getMQTTClientID(), |
| 2592 |
}, |
| 2593 |
} |
| 2594 |
subj := fmt.Sprintf(connectEventSubj, c.acc.Name) |
| 2595 |
c.mu.Unlock() |
| 2596 |
|
| 2597 |
s.sendInternalMsgLocked(subj, _EMPTY_, &m.Server, &m) |
| 2598 |
} |
| 2599 |
|
| 2600 |
// accountDisconnectEvent will send an account client disconnect event if there is interest. |
| 2601 |
// This is a billing event. |
| 2602 |
func (s *Server) accountDisconnectEvent(c *client, now time.Time, reason string) { |
| 2603 |
s.mu.Lock() |
| 2604 |
if !s.eventsEnabled() { |
| 2605 |
s.mu.Unlock() |
| 2606 |
return |
| 2607 |
} |
| 2608 |
eid := s.nextEventID() |
| 2609 |
s.mu.Unlock() |
| 2610 |
|
| 2611 |
c.mu.Lock() |
| 2612 |
|
| 2613 |
if c.acc == nil { |
| 2614 |
c.mu.Unlock() |
| 2615 |
return |
| 2616 |
} |
| 2617 |
m := DisconnectEventMsg{ |
| 2618 |
TypedEvent: TypedEvent{ |
| 2619 |
Type: DisconnectEventMsgType, |
| 2620 |
ID: eid, |
| 2621 |
Time: now, |
| 2622 |
}, |
| 2623 |
Client: ClientInfo{ |
| 2624 |
Start: &c.start, |
| 2625 |
Stop: &now, |
| 2626 |
Host: c.host, |
| 2627 |
ID: c.cid, |
| 2628 |
Account: accForClient(c), |
| 2629 |
User: c.getRawAuthUser(), |
| 2630 |
Name: c.opts.Name, |
| 2631 |
Lang: c.opts.Lang, |
| 2632 |
Version: c.opts.Version, |
| 2633 |
RTT: c.getRTT(), |
| 2634 |
Jwt: c.opts.JWT, |
| 2635 |
IssuerKey: issuerForClient(c), |
| 2636 |
Tags: c.tags, |
| 2637 |
NameTag: c.acc.getNameTag(), |
| 2638 |
Kind: c.kindString(), |
| 2639 |
ClientType: c.clientTypeString(), |
| 2640 |
MQTTClient: c.getMQTTClientID(), |
| 2641 |
}, |
| 2642 |
Sent: DataStats{ |
| 2643 |
MsgBytes: MsgBytes{ |
| 2644 |
Msgs: atomic.LoadInt64(&c.inMsgs), |
| 2645 |
Bytes: atomic.LoadInt64(&c.inBytes), |
| 2646 |
}, |
| 2647 |
}, |
| 2648 |
Received: DataStats{ |
| 2649 |
MsgBytes: MsgBytes{ |
| 2650 |
Msgs: c.outMsgs, |
| 2651 |
Bytes: c.outBytes, |
| 2652 |
}, |
| 2653 |
}, |
| 2654 |
Reason: reason, |
| 2655 |
} |
| 2656 |
accName := c.acc.Name |
| 2657 |
c.mu.Unlock() |
| 2658 |
|
| 2659 |
subj := fmt.Sprintf(disconnectEventSubj, accName) |
| 2660 |
s.sendInternalMsgLocked(subj, _EMPTY_, &m.Server, &m) |
| 2661 |
} |
| 2662 |
|
| 2663 |
// This is the system level event sent to the system account for operators. |
| 2664 |
func (s *Server) sendAuthErrorEvent(c *client, reason string) { |
| 2665 |
s.mu.Lock() |
| 2666 |
if !s.eventsEnabled() { |
| 2667 |
s.mu.Unlock() |
| 2668 |
return |
| 2669 |
} |
| 2670 |
eid := s.nextEventID() |
| 2671 |
s.mu.Unlock() |
| 2672 |
|
| 2673 |
now := time.Now().UTC() |
| 2674 |
c.mu.Lock() |
| 2675 |
m := DisconnectEventMsg{ |
| 2676 |
TypedEvent: TypedEvent{ |
| 2677 |
Type: DisconnectEventMsgType, |
| 2678 |
ID: eid, |
| 2679 |
Time: now, |
| 2680 |
}, |
| 2681 |
Client: ClientInfo{ |
| 2682 |
Start: &c.start, |
| 2683 |
Stop: &now, |
| 2684 |
Host: c.host, |
| 2685 |
ID: c.cid, |
| 2686 |
Account: accForClient(c), |
| 2687 |
User: c.getRawAuthUser(), |
| 2688 |
Name: c.opts.Name, |
| 2689 |
Lang: c.opts.Lang, |
| 2690 |
Version: c.opts.Version, |
| 2691 |
RTT: c.getRTT(), |
| 2692 |
Jwt: c.opts.JWT, |
| 2693 |
IssuerKey: issuerForClient(c), |
| 2694 |
Tags: c.tags, |
| 2695 |
NameTag: c.acc.getNameTag(), |
| 2696 |
Kind: c.kindString(), |
| 2697 |
ClientType: c.clientTypeString(), |
| 2698 |
MQTTClient: c.getMQTTClientID(), |
| 2699 |
}, |
| 2700 |
Sent: DataStats{ |
| 2701 |
MsgBytes: MsgBytes{ |
| 2702 |
Msgs: c.inMsgs, |
| 2703 |
Bytes: c.inBytes, |
| 2704 |
}, |
| 2705 |
}, |
| 2706 |
Received: DataStats{ |
| 2707 |
MsgBytes: MsgBytes{ |
| 2708 |
Msgs: c.outMsgs, |
| 2709 |
Bytes: c.outBytes, |
| 2710 |
}, |
| 2711 |
}, |
| 2712 |
Reason: reason, |
| 2713 |
} |
| 2714 |
c.mu.Unlock() |
| 2715 |
|
| 2716 |
s.mu.Lock() |
| 2717 |
subj := fmt.Sprintf(authErrorEventSubj, s.info.ID) |
| 2718 |
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m) |
| 2719 |
s.mu.Unlock() |
| 2720 |
} |
| 2721 |
|
| 2722 |
// This is the account level event sent to the origin account for account owners. |
| 2723 |
func (s *Server) sendAccountAuthErrorEvent(c *client, acc *Account, reason string) { |
| 2724 |
if acc == nil { |
| 2725 |
return |
| 2726 |
} |
| 2727 |
s.mu.Lock() |
| 2728 |
if !s.eventsEnabled() { |
| 2729 |
s.mu.Unlock() |
| 2730 |
return |
| 2731 |
} |
| 2732 |
eid := s.nextEventID() |
| 2733 |
s.mu.Unlock() |
| 2734 |
|
| 2735 |
now := time.Now().UTC() |
| 2736 |
c.mu.Lock() |
| 2737 |
m := DisconnectEventMsg{ |
| 2738 |
TypedEvent: TypedEvent{ |
| 2739 |
Type: DisconnectEventMsgType, |
| 2740 |
ID: eid, |
| 2741 |
Time: now, |
| 2742 |
}, |
| 2743 |
Client: ClientInfo{ |
| 2744 |
Start: &c.start, |
| 2745 |
Stop: &now, |
| 2746 |
Host: c.host, |
| 2747 |
ID: c.cid, |
| 2748 |
Account: acc.Name, |
| 2749 |
User: c.getRawAuthUser(), |
| 2750 |
Name: c.opts.Name, |
| 2751 |
Lang: c.opts.Lang, |
| 2752 |
Version: c.opts.Version, |
| 2753 |
RTT: c.getRTT(), |
| 2754 |
Jwt: c.opts.JWT, |
| 2755 |
IssuerKey: issuerForClient(c), |
| 2756 |
Tags: c.tags, |
| 2757 |
NameTag: c.acc.getNameTag(), |
| 2758 |
Kind: c.kindString(), |
| 2759 |
ClientType: c.clientTypeString(), |
| 2760 |
MQTTClient: c.getMQTTClientID(), |
| 2761 |
}, |
| 2762 |
Sent: DataStats{ |
| 2763 |
MsgBytes: MsgBytes{ |
| 2764 |
Msgs: c.inMsgs, |
| 2765 |
Bytes: c.inBytes, |
| 2766 |
}, |
| 2767 |
}, |
| 2768 |
Received: DataStats{ |
| 2769 |
MsgBytes: MsgBytes{ |
| 2770 |
Msgs: c.outMsgs, |
| 2771 |
Bytes: c.outBytes, |
| 2772 |
}, |
| 2773 |
}, |
| 2774 |
Reason: reason, |
| 2775 |
} |
| 2776 |
c.mu.Unlock() |
| 2777 |
|
| 2778 |
s.sendInternalAccountSysMsg(acc, authErrorAccountEventSubj, &m.Server, &m, noCompression) |
| 2779 |
} |
| 2780 |
|
| 2781 |
// Internal message callback. |
| 2782 |
// If the msg is needed past the callback it is required to be copied. |
| 2783 |
// rmsg contains header and the message. use client.msgParts(rmsg) to split them apart |
| 2784 |
type msgHandler func(sub *subscription, client *client, acc *Account, subject, reply string, rmsg []byte) |
| 2785 |
|
| 2786 |
const ( |
| 2787 |
recvQMuxed = 1 |
| 2788 |
recvQStatsz = 2 |
| 2789 |
) |
| 2790 |
|
| 2791 |
// Create a wrapped callback handler for the subscription that will move it to an |
| 2792 |
// internal recvQ for processing not inline with routes etc. |
| 2793 |
func (s *Server) noInlineCallback(cb sysMsgHandler) msgHandler { |
| 2794 |
return s.noInlineCallbackRecvQSelect(cb, recvQMuxed) |
| 2795 |
} |
| 2796 |
|
| 2797 |
// Create a wrapped callback handler for the subscription that will move it to an |
| 2798 |
// internal recvQ for Statsz/Pings for processing not inline with routes etc. |
| 2799 |
func (s *Server) noInlineCallbackStatsz(cb sysMsgHandler) msgHandler { |
| 2800 |
return s.noInlineCallbackRecvQSelect(cb, recvQStatsz) |
| 2801 |
} |
| 2802 |
|
| 2803 |
// Create a wrapped callback handler for the subscription that will move it to an |
| 2804 |
// internal IPQueue for processing not inline with routes etc. |
| 2805 |
func (s *Server) noInlineCallbackRecvQSelect(cb sysMsgHandler, recvQSelect int) msgHandler { |
| 2806 |
s.mu.RLock() |
| 2807 |
if !s.eventsEnabled() { |
| 2808 |
s.mu.RUnlock() |
| 2809 |
return nil |
| 2810 |
} |
| 2811 |
// Capture here for direct reference to avoid any unnecessary blocking inline with routes, gateways etc. |
| 2812 |
var recvq *ipQueue[*inSysMsg] |
| 2813 |
switch recvQSelect { |
| 2814 |
case recvQStatsz: |
| 2815 |
recvq = s.sys.recvqp |
| 2816 |
default: |
| 2817 |
recvq = s.sys.recvq |
| 2818 |
} |
| 2819 |
s.mu.RUnlock() |
| 2820 |
|
| 2821 |
return func(sub *subscription, c *client, acc *Account, subj, rply string, rmsg []byte) { |
| 2822 |
// Need to copy and split here. |
| 2823 |
hdr, msg := c.msgParts(rmsg) |
| 2824 |
recvq.push(&inSysMsg{sub, c, acc, subj, rply, copyBytes(hdr), copyBytes(msg), cb}) |
| 2825 |
} |
| 2826 |
} |
| 2827 |
|
| 2828 |
// Create an internal subscription. sysSubscribeQ for queue groups. |
| 2829 |
func (s *Server) sysSubscribe(subject string, cb msgHandler) (*subscription, error) { |
| 2830 |
return s.systemSubscribe(subject, _EMPTY_, false, nil, cb) |
| 2831 |
} |
| 2832 |
|
| 2833 |
// Create an internal subscription with queue |
| 2834 |
func (s *Server) sysSubscribeQ(subject, queue string, cb msgHandler) (*subscription, error) { |
| 2835 |
return s.systemSubscribe(subject, queue, false, nil, cb) |
| 2836 |
} |
| 2837 |
|
| 2838 |
// Create an internal subscription but do not forward interest. |
| 2839 |
func (s *Server) sysSubscribeInternal(subject string, cb msgHandler) (*subscription, error) { |
| 2840 |
return s.systemSubscribe(subject, _EMPTY_, true, nil, cb) |
| 2841 |
} |
| 2842 |
|
| 2843 |
func (s *Server) systemSubscribe(subject, queue string, internalOnly bool, c *client, cb msgHandler) (*subscription, error) { |
| 2844 |
s.mu.Lock() |
| 2845 |
if !s.eventsEnabled() { |
| 2846 |
s.mu.Unlock() |
| 2847 |
return nil, ErrNoSysAccount |
| 2848 |
} |
| 2849 |
if cb == nil { |
| 2850 |
s.mu.Unlock() |
| 2851 |
return nil, fmt.Errorf("undefined message handler") |
| 2852 |
} |
| 2853 |
if c == nil { |
| 2854 |
c = s.sys.client |
| 2855 |
} |
| 2856 |
trace := c.trace |
| 2857 |
s.sys.sid++ |
| 2858 |
sid := strconv.Itoa(s.sys.sid) |
| 2859 |
s.mu.Unlock() |
| 2860 |
|
| 2861 |
// Now create the subscription |
| 2862 |
if trace { |
| 2863 |
c.traceInOp("SUB", []byte(subject+" "+queue+" "+sid)) |
| 2864 |
} |
| 2865 |
|
| 2866 |
var q []byte |
| 2867 |
if queue != _EMPTY_ { |
| 2868 |
q = []byte(queue) |
| 2869 |
} |
| 2870 |
|
| 2871 |
// Now create the subscription |
| 2872 |
return c.processSub([]byte(subject), q, []byte(sid), cb, internalOnly) |
| 2873 |
} |
| 2874 |
|
| 2875 |
func (s *Server) sysUnsubscribe(sub *subscription) { |
| 2876 |
if sub == nil { |
| 2877 |
return |
| 2878 |
} |
| 2879 |
s.mu.RLock() |
| 2880 |
if !s.eventsEnabled() { |
| 2881 |
s.mu.RUnlock() |
| 2882 |
return |
| 2883 |
} |
| 2884 |
c := sub.client |
| 2885 |
s.mu.RUnlock() |
| 2886 |
|
| 2887 |
if c != nil { |
| 2888 |
c.processUnsub(sub.sid) |
| 2889 |
} |
| 2890 |
} |
| 2891 |
|
| 2892 |
// This will generate the tracking subject for remote latency from the response subject. |
| 2893 |
func remoteLatencySubjectForResponse(subject []byte) string { |
| 2894 |
if !isTrackedReply(subject) { |
| 2895 |
return "" |
| 2896 |
} |
| 2897 |
toks := bytes.Split(subject, []byte(tsep)) |
| 2898 |
// FIXME(dlc) - Sprintf may become a performance concern at some point. |
| 2899 |
return fmt.Sprintf(remoteLatencyEventSubj, toks[len(toks)-2]) |
| 2900 |
} |
| 2901 |
|
| 2902 |
// remoteLatencyUpdate is used to track remote latency measurements for tracking on exported services. |
| 2903 |
func (s *Server) remoteLatencyUpdate(sub *subscription, _ *client, _ *Account, subject, _ string, hdr, msg []byte) { |
| 2904 |
if !s.eventsRunning() { |
| 2905 |
return |
| 2906 |
} |
| 2907 |
var rl remoteLatency |
| 2908 |
if err := json.Unmarshal(msg, &rl); err != nil { |
| 2909 |
s.Errorf("Error unmarshalling remote latency measurement: %v", err) |
| 2910 |
return |
| 2911 |
} |
| 2912 |
// Now we need to look up the responseServiceImport associated with this measurement. |
| 2913 |
acc, err := s.LookupAccount(rl.Account) |
| 2914 |
if err != nil { |
| 2915 |
s.Warnf("Could not lookup account %q for latency measurement", rl.Account) |
| 2916 |
return |
| 2917 |
} |
| 2918 |
// Now get the request id / reply. We need to see if we have a GW prefix and if so strip that off. |
| 2919 |
reply := rl.ReqId |
| 2920 |
if gwPrefix, old := isGWRoutedSubjectAndIsOldPrefix([]byte(reply)); gwPrefix { |
| 2921 |
reply = string(getSubjectFromGWRoutedReply([]byte(reply), old)) |
| 2922 |
} |
| 2923 |
acc.mu.RLock() |
| 2924 |
si := acc.exports.responses[reply] |
| 2925 |
if si == nil || si.latency == nil { |
| 2926 |
acc.mu.RUnlock() |
| 2927 |
return |
| 2928 |
} |
| 2929 |
lsub := si.latency.subject |
| 2930 |
acc.mu.RUnlock() |
| 2931 |
|
| 2932 |
si.acc.mu.Lock() |
| 2933 |
m1 := si.m1 |
| 2934 |
m2 := rl.M2 |
| 2935 |
|
| 2936 |
// So we have not processed the response tracking measurement yet. |
| 2937 |
if m1 == nil { |
| 2938 |
// Store our value there for them to pick up. |
| 2939 |
si.m1 = &m2 |
| 2940 |
} |
| 2941 |
si.acc.mu.Unlock() |
| 2942 |
|
| 2943 |
if m1 == nil { |
| 2944 |
return |
| 2945 |
} |
| 2946 |
|
| 2947 |
// Calculate the correct latencies given M1 and M2. |
| 2948 |
m1.merge(&m2) |
| 2949 |
|
| 2950 |
// Clear the requesting client since we send the result here. |
| 2951 |
acc.mu.Lock() |
| 2952 |
si.rc = nil |
| 2953 |
acc.mu.Unlock() |
| 2954 |
|
| 2955 |
// Send the metrics |
| 2956 |
s.sendInternalAccountMsg(acc, lsub, m1) |
| 2957 |
} |
| 2958 |
|
| 2959 |
// This is used for all inbox replies so that we do not send supercluster wide interest |
| 2960 |
// updates for every request. Same trick used in modern NATS clients. |
| 2961 |
func (s *Server) inboxReply(sub *subscription, c *client, acc *Account, subject, reply string, msg []byte) { |
| 2962 |
s.mu.RLock() |
| 2963 |
if !s.eventsEnabled() || s.sys.replies == nil { |
| 2964 |
s.mu.RUnlock() |
| 2965 |
return |
| 2966 |
} |
| 2967 |
cb, ok := s.sys.replies[subject] |
| 2968 |
s.mu.RUnlock() |
| 2969 |
|
| 2970 |
if ok && cb != nil { |
| 2971 |
cb(sub, c, acc, subject, reply, msg) |
| 2972 |
} |
| 2973 |
} |
| 2974 |
|
| 2975 |
// Copied from go client. |
| 2976 |
// We could use serviceReply here instead to save some code. |
| 2977 |
// I prefer these semantics for the moment, when tracing you know what this is. |
| 2978 |
const ( |
| 2979 |
InboxPrefix = "$SYS._INBOX." |
| 2980 |
inboxPrefixLen = len(InboxPrefix) |
| 2981 |
respInboxPrefixLen = inboxPrefixLen + sysHashLen + 1 |
| 2982 |
replySuffixLen = 8 // Gives us 62^8 |
| 2983 |
) |
| 2984 |
|
| 2985 |
// Creates an internal inbox used for replies that will be processed by the global wc handler. |
| 2986 |
func (s *Server) newRespInbox() string { |
| 2987 |
var b [respInboxPrefixLen + replySuffixLen]byte |
| 2988 |
pres := b[:respInboxPrefixLen] |
| 2989 |
copy(pres, s.sys.inboxPre) |
| 2990 |
rn := rand.Int63() |
| 2991 |
for i, l := respInboxPrefixLen, rn; i < len(b); i++ { |
| 2992 |
b[i] = digits[l%base] |
| 2993 |
l /= base |
| 2994 |
} |
| 2995 |
return string(b[:]) |
| 2996 |
} |
| 2997 |
|
| 2998 |
// accNumSubsReq is sent when we need to gather remote info on subs. |
| 2999 |
type accNumSubsReq struct { |
| 3000 |
Account string `json:"acc"` |
| 3001 |
Subject string `json:"subject"` |
| 3002 |
Queue []byte `json:"queue,omitempty"` |
| 3003 |
} |
| 3004 |
|
| 3005 |
// helper function to total information from results to count subs. |
| 3006 |
func totalSubs(rr *SublistResult, qg []byte) (nsubs int32) { |
| 3007 |
if rr == nil { |
| 3008 |
return |
| 3009 |
} |
| 3010 |
checkSub := func(sub *subscription) { |
| 3011 |
// TODO(dlc) - This could be smarter. |
| 3012 |
if qg != nil && !bytes.Equal(qg, sub.queue) { |
| 3013 |
return |
| 3014 |
} |
| 3015 |
if sub.client.kind == CLIENT || sub.client.isHubLeafNode() { |
| 3016 |
nsubs++ |
| 3017 |
} |
| 3018 |
} |
| 3019 |
if qg == nil { |
| 3020 |
for _, sub := range rr.psubs { |
| 3021 |
checkSub(sub) |
| 3022 |
} |
| 3023 |
} |
| 3024 |
for _, qsub := range rr.qsubs { |
| 3025 |
for _, sub := range qsub { |
| 3026 |
checkSub(sub) |
| 3027 |
} |
| 3028 |
} |
| 3029 |
return |
| 3030 |
} |
| 3031 |
|
| 3032 |
// Allows users of large systems to debug active subscribers for a given subject. |
| 3033 |
// Payload should be the subject of interest. |
| 3034 |
func (s *Server) debugSubscribers(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 3035 |
// Even though this is an internal only subscription, meaning interest was not forwarded, we could |
| 3036 |
// get one here from a GW in optimistic mode. Ignore for now. |
| 3037 |
// FIXME(dlc) - Should we send no interest here back to the GW? |
| 3038 |
if c.kind != CLIENT { |
| 3039 |
return |
| 3040 |
} |
| 3041 |
|
| 3042 |
var ci ClientInfo |
| 3043 |
if len(hdr) > 0 { |
| 3044 |
if err := json.Unmarshal(getHeader(ClientInfoHdr, hdr), &ci); err != nil { |
| 3045 |
return |
| 3046 |
} |
| 3047 |
} |
| 3048 |
|
| 3049 |
var acc *Account |
| 3050 |
if ci.Service != _EMPTY_ { |
| 3051 |
acc, _ = s.LookupAccount(ci.Service) |
| 3052 |
} else if ci.Account != _EMPTY_ { |
| 3053 |
acc, _ = s.LookupAccount(ci.Account) |
| 3054 |
} else { |
| 3055 |
// Direct $SYS access. |
| 3056 |
acc = c.acc |
| 3057 |
if acc == nil { |
| 3058 |
acc = s.SystemAccount() |
| 3059 |
} |
| 3060 |
} |
| 3061 |
if acc == nil { |
| 3062 |
return |
| 3063 |
} |
| 3064 |
|
| 3065 |
// We could have a single subject or we could have a subject and a wildcard separated by whitespace. |
| 3066 |
args := strings.Split(strings.TrimSpace(string(msg)), " ") |
| 3067 |
if len(args) == 0 { |
| 3068 |
s.sendInternalAccountMsg(acc, reply, 0) |
| 3069 |
return |
| 3070 |
} |
| 3071 |
|
| 3072 |
tsubj := args[0] |
| 3073 |
var qgroup []byte |
| 3074 |
if len(args) > 1 { |
| 3075 |
qgroup = []byte(args[1]) |
| 3076 |
} |
| 3077 |
|
| 3078 |
var nsubs int32 |
| 3079 |
|
| 3080 |
if subjectIsLiteral(tsubj) { |
| 3081 |
// We will look up subscribers locally first then determine if we need to solicit other servers. |
| 3082 |
rr := acc.sl.Match(tsubj) |
| 3083 |
nsubs = totalSubs(rr, qgroup) |
| 3084 |
} else { |
| 3085 |
// We have a wildcard, so this is a bit slower path. |
| 3086 |
var _subs [32]*subscription |
| 3087 |
subs := _subs[:0] |
| 3088 |
acc.sl.All(&subs) |
| 3089 |
for _, sub := range subs { |
| 3090 |
if subjectIsSubsetMatch(string(sub.subject), tsubj) { |
| 3091 |
if qgroup != nil && !bytes.Equal(qgroup, sub.queue) { |
| 3092 |
continue |
| 3093 |
} |
| 3094 |
if sub.client.kind == CLIENT || sub.client.isHubLeafNode() { |
| 3095 |
nsubs++ |
| 3096 |
} |
| 3097 |
} |
| 3098 |
} |
| 3099 |
} |
| 3100 |
|
| 3101 |
// We should have an idea of how many responses to expect from remote servers. |
| 3102 |
var expected = acc.expectedRemoteResponses() |
| 3103 |
|
| 3104 |
// If we are only local, go ahead and return. |
| 3105 |
if expected == 0 { |
| 3106 |
s.sendInternalAccountMsg(nil, reply, nsubs) |
| 3107 |
return |
| 3108 |
} |
| 3109 |
|
| 3110 |
// We need to solicit from others. |
| 3111 |
// To track status. |
| 3112 |
responses := int32(0) |
| 3113 |
done := make(chan (bool)) |
| 3114 |
|
| 3115 |
s.mu.Lock() |
| 3116 |
// Create direct reply inbox that we multiplex under the WC replies. |
| 3117 |
replySubj := s.newRespInbox() |
| 3118 |
// Store our handler. |
| 3119 |
s.sys.replies[replySubj] = func(sub *subscription, _ *client, _ *Account, subject, _ string, msg []byte) { |
| 3120 |
if n, err := strconv.ParseInt(string(msg), 10, 32); err == nil { |
| 3121 |
atomic.AddInt32(&nsubs, int32(n)) |
| 3122 |
} |
| 3123 |
if atomic.AddInt32(&responses, 1) >= expected { |
| 3124 |
select { |
| 3125 |
case done <- true: |
| 3126 |
default: |
| 3127 |
} |
| 3128 |
} |
| 3129 |
} |
| 3130 |
// Send the request to the other servers. |
| 3131 |
request := &accNumSubsReq{ |
| 3132 |
Account: acc.Name, |
| 3133 |
Subject: tsubj, |
| 3134 |
Queue: qgroup, |
| 3135 |
} |
| 3136 |
s.sendInternalMsg(accNumSubsReqSubj, replySubj, nil, request) |
| 3137 |
s.mu.Unlock() |
| 3138 |
|
| 3139 |
// FIXME(dlc) - We should rate limit here instead of blind Go routine. |
| 3140 |
go func() { |
| 3141 |
select { |
| 3142 |
case <-done: |
| 3143 |
case <-time.After(500 * time.Millisecond): |
| 3144 |
} |
| 3145 |
// Cleanup the WC entry. |
| 3146 |
var sendResponse bool |
| 3147 |
s.mu.Lock() |
| 3148 |
if s.sys != nil && s.sys.replies != nil { |
| 3149 |
delete(s.sys.replies, replySubj) |
| 3150 |
sendResponse = true |
| 3151 |
} |
| 3152 |
s.mu.Unlock() |
| 3153 |
if sendResponse { |
| 3154 |
// Send the response. |
| 3155 |
s.sendInternalAccountMsg(nil, reply, atomic.LoadInt32(&nsubs)) |
| 3156 |
} |
| 3157 |
}() |
| 3158 |
} |
| 3159 |
|
| 3160 |
// Request for our local subscription count. This will come from a remote origin server |
| 3161 |
// that received the initial request. |
| 3162 |
func (s *Server) nsubsRequest(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 3163 |
if !s.eventsRunning() { |
| 3164 |
return |
| 3165 |
} |
| 3166 |
m := accNumSubsReq{} |
| 3167 |
if len(msg) == 0 { |
| 3168 |
s.sys.client.Errorf("request requires a body") |
| 3169 |
return |
| 3170 |
} else if err := json.Unmarshal(msg, &m); err != nil { |
| 3171 |
s.sys.client.Errorf("Error unmarshalling account nsubs request message: %v", err) |
| 3172 |
return |
| 3173 |
} |
| 3174 |
// Grab account. |
| 3175 |
acc, _ := s.lookupAccount(m.Account) |
| 3176 |
if acc == nil || acc.numLocalAndLeafConnections() == 0 { |
| 3177 |
return |
| 3178 |
} |
| 3179 |
// We will look up subscribers locally first then determine if we need to solicit other servers. |
| 3180 |
var nsubs int32 |
| 3181 |
if subjectIsLiteral(m.Subject) { |
| 3182 |
rr := acc.sl.Match(m.Subject) |
| 3183 |
nsubs = totalSubs(rr, m.Queue) |
| 3184 |
} else { |
| 3185 |
// We have a wildcard, so this is a bit slower path. |
| 3186 |
var _subs [32]*subscription |
| 3187 |
subs := _subs[:0] |
| 3188 |
acc.sl.All(&subs) |
| 3189 |
for _, sub := range subs { |
| 3190 |
if (sub.client.kind == CLIENT || sub.client.isHubLeafNode()) && subjectIsSubsetMatch(string(sub.subject), m.Subject) { |
| 3191 |
if m.Queue != nil && !bytes.Equal(m.Queue, sub.queue) { |
| 3192 |
continue |
| 3193 |
} |
| 3194 |
nsubs++ |
| 3195 |
} |
| 3196 |
} |
| 3197 |
} |
| 3198 |
s.sendInternalMsgLocked(reply, _EMPTY_, nil, nsubs) |
| 3199 |
} |
| 3200 |
|
| 3201 |
func (s *Server) reloadConfig(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 3202 |
if !s.eventsRunning() { |
| 3203 |
return |
| 3204 |
} |
| 3205 |
|
| 3206 |
optz := &EventFilterOptions{} |
| 3207 |
s.zReq(c, reply, hdr, msg, optz, optz, func() (any, error) { |
| 3208 |
// Reload the server config, as requested. |
| 3209 |
return nil, s.Reload() |
| 3210 |
}) |
| 3211 |
} |
| 3212 |
|
| 3213 |
type KickClientReq struct { |
| 3214 |
CID uint64 `json:"cid"` |
| 3215 |
} |
| 3216 |
|
| 3217 |
type LDMClientReq struct { |
| 3218 |
CID uint64 `json:"cid"` |
| 3219 |
} |
| 3220 |
|
| 3221 |
func (s *Server) kickClient(_ *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 3222 |
if !s.eventsRunning() { |
| 3223 |
return |
| 3224 |
} |
| 3225 |
|
| 3226 |
var req KickClientReq |
| 3227 |
if err := json.Unmarshal(msg, &req); err != nil { |
| 3228 |
s.sys.client.Errorf("Error unmarshalling kick client request: %v", err) |
| 3229 |
return |
| 3230 |
} |
| 3231 |
|
| 3232 |
optz := &EventFilterOptions{} |
| 3233 |
s.zReq(c, reply, hdr, msg, optz, optz, func() (any, error) { |
| 3234 |
return nil, s.DisconnectClientByID(req.CID) |
| 3235 |
}) |
| 3236 |
|
| 3237 |
} |
| 3238 |
|
| 3239 |
func (s *Server) ldmClient(_ *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) { |
| 3240 |
if !s.eventsRunning() { |
| 3241 |
return |
| 3242 |
} |
| 3243 |
|
| 3244 |
var req LDMClientReq |
| 3245 |
if err := json.Unmarshal(msg, &req); err != nil { |
| 3246 |
s.sys.client.Errorf("Error unmarshalling kick client request: %v", err) |
| 3247 |
return |
| 3248 |
} |
| 3249 |
|
| 3250 |
optz := &EventFilterOptions{} |
| 3251 |
s.zReq(c, reply, hdr, msg, optz, optz, func() (any, error) { |
| 3252 |
return nil, s.LDMClientByID(req.CID) |
| 3253 |
}) |
| 3254 |
} |
| 3255 |
|
| 3256 |
// Helper to grab account name for a client. |
| 3257 |
func accForClient(c *client) string { |
| 3258 |
if c.acc != nil { |
| 3259 |
return c.acc.Name |
| 3260 |
} |
| 3261 |
return "N/A" |
| 3262 |
} |
| 3263 |
|
| 3264 |
// Helper to grab issuer for a client. |
| 3265 |
func issuerForClient(c *client) (issuerKey string) { |
| 3266 |
if c == nil || c.user == nil { |
| 3267 |
return |
| 3268 |
} |
| 3269 |
issuerKey = c.user.SigningKey |
| 3270 |
if issuerKey == _EMPTY_ && c.user.Account != nil { |
| 3271 |
issuerKey = c.user.Account.Name |
| 3272 |
} |
| 3273 |
return |
| 3274 |
} |
| 3275 |
|
| 3276 |
// Helper to clear timers. |
| 3277 |
func clearTimer(tp **time.Timer) { |
| 3278 |
if t := *tp; t != nil { |
| 3279 |
t.Stop() |
| 3280 |
*tp = nil |
| 3281 |
} |
| 3282 |
} |
| 3283 |
|
| 3284 |
// Helper function to wrap functions with common test |
| 3285 |
// to lock server and return if events not enabled. |
| 3286 |
func (s *Server) wrapChk(f func()) func() { |
| 3287 |
return func() { |
| 3288 |
s.mu.Lock() |
| 3289 |
if !s.eventsEnabled() { |
| 3290 |
s.mu.Unlock() |
| 3291 |
return |
| 3292 |
} |
| 3293 |
f() |
| 3294 |
s.mu.Unlock() |
| 3295 |
} |
| 3296 |
} |
| 3297 |
|
| 3298 |
// sendOCSPPeerRejectEvent sends a system level event to system account when a peer connection is |
| 3299 |
// rejected due to OCSP invalid status of its trust chain(s). |
| 3300 |
func (s *Server) sendOCSPPeerRejectEvent(kind string, peer *x509.Certificate, reason string) { |
| 3301 |
s.mu.Lock() |
| 3302 |
defer s.mu.Unlock() |
| 3303 |
if !s.eventsEnabled() { |
| 3304 |
return |
| 3305 |
} |
| 3306 |
if peer == nil { |
| 3307 |
s.Errorf(certidp.ErrPeerEmptyNoEvent) |
| 3308 |
return |
| 3309 |
} |
| 3310 |
eid := s.nextEventID() |
| 3311 |
now := time.Now().UTC() |
| 3312 |
m := OCSPPeerRejectEventMsg{ |
| 3313 |
TypedEvent: TypedEvent{ |
| 3314 |
Type: OCSPPeerRejectEventMsgType, |
| 3315 |
ID: eid, |
| 3316 |
Time: now, |
| 3317 |
}, |
| 3318 |
Kind: kind, |
| 3319 |
Peer: certidp.CertInfo{ |
| 3320 |
Subject: certidp.GetSubjectDNForm(peer), |
| 3321 |
Issuer: certidp.GetIssuerDNForm(peer), |
| 3322 |
Fingerprint: certidp.GenerateFingerprint(peer), |
| 3323 |
Raw: peer.Raw, |
| 3324 |
}, |
| 3325 |
Reason: reason, |
| 3326 |
} |
| 3327 |
subj := fmt.Sprintf(ocspPeerRejectEventSubj, s.info.ID) |
| 3328 |
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m) |
| 3329 |
} |
| 3330 |
|
| 3331 |
// sendOCSPPeerChainlinkInvalidEvent sends a system level event to system account when a link in a peer's trust chain |
| 3332 |
// is OCSP invalid. |
| 3333 |
func (s *Server) sendOCSPPeerChainlinkInvalidEvent(peer *x509.Certificate, link *x509.Certificate, reason string) { |
| 3334 |
s.mu.Lock() |
| 3335 |
defer s.mu.Unlock() |
| 3336 |
if !s.eventsEnabled() { |
| 3337 |
return |
| 3338 |
} |
| 3339 |
if peer == nil || link == nil { |
| 3340 |
s.Errorf(certidp.ErrPeerEmptyNoEvent) |
| 3341 |
return |
| 3342 |
} |
| 3343 |
eid := s.nextEventID() |
| 3344 |
now := time.Now().UTC() |
| 3345 |
m := OCSPPeerChainlinkInvalidEventMsg{ |
| 3346 |
TypedEvent: TypedEvent{ |
| 3347 |
Type: OCSPPeerChainlinkInvalidEventMsgType, |
| 3348 |
ID: eid, |
| 3349 |
Time: now, |
| 3350 |
}, |
| 3351 |
Link: certidp.CertInfo{ |
| 3352 |
Subject: certidp.GetSubjectDNForm(link), |
| 3353 |
Issuer: certidp.GetIssuerDNForm(link), |
| 3354 |
Fingerprint: certidp.GenerateFingerprint(link), |
| 3355 |
Raw: link.Raw, |
| 3356 |
}, |
| 3357 |
Peer: certidp.CertInfo{ |
| 3358 |
Subject: certidp.GetSubjectDNForm(peer), |
| 3359 |
Issuer: certidp.GetIssuerDNForm(peer), |
| 3360 |
Fingerprint: certidp.GenerateFingerprint(peer), |
| 3361 |
Raw: peer.Raw, |
| 3362 |
}, |
| 3363 |
Reason: reason, |
| 3364 |
} |
| 3365 |
subj := fmt.Sprintf(ocspPeerChainlinkInvalidEventSubj, s.info.ID) |
| 3366 |
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m) |
| 3367 |
} |