Debian Codegraph @

server/reload.go

raw
1 // Copyright 2017-2026 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 "cmp"
18 "crypto/tls"
19 "errors"
20 "fmt"
21 "net/url"
22 "reflect"
23 "slices"
24 "strings"
25 "sync/atomic"
26 "time"
27
28 "github.com/klauspost/compress/s2"
29
30 "github.com/nats-io/jwt/v2"
31 "github.com/nats-io/nuid"
32 )
33
34 // FlagSnapshot captures the server options as specified by CLI flags at
35 // startup. This should not be modified once the server has started.
36 var FlagSnapshot *Options
37
38 type reloadContext struct {
39 oldClusterPerms *RoutePermissions
40 }
41
42 // option is a hot-swappable configuration setting.
43 type option interface {
44 // Apply the server option.
45 Apply(server *Server)
46
47 // IsLoggingChange indicates if this option requires reloading the logger.
48 IsLoggingChange() bool
49
50 // IsTraceLevelChange indicates if this option requires reloading cached trace level.
51 // Clients store trace level separately.
52 IsTraceLevelChange() bool
53
54 // IsAuthChange indicates if this option requires reloading authorization.
55 IsAuthChange() bool
56
57 // IsTLSChange indicates if this option requires reloading TLS.
58 IsTLSChange() bool
59
60 // IsClusterPermsChange indicates if this option requires reloading
61 // cluster permissions.
62 IsClusterPermsChange() bool
63
64 // IsClusterPoolSizeOrAccountsChange indicates if this option requires
65 // special handling for changes in cluster's pool size or accounts list.
66 IsClusterPoolSizeOrAccountsChange() bool
67
68 // IsJetStreamChange inidicates a change in the servers config for JetStream.
69 // Account changes will be handled separately in reloadAuthorization.
70 IsJetStreamChange() bool
71
72 // Indicates a change in the server that requires publishing the server's statz
73 IsStatszChange() bool
74 }
75
76 // noopOption is a base struct that provides default no-op behaviors.
77 type noopOption struct{}
78
79 func (n noopOption) IsLoggingChange() bool {
80 return false
81 }
82
83 func (n noopOption) IsTraceLevelChange() bool {
84 return false
85 }
86
87 func (n noopOption) IsAuthChange() bool {
88 return false
89 }
90
91 func (n noopOption) IsTLSChange() bool {
92 return false
93 }
94
95 func (n noopOption) IsClusterPermsChange() bool {
96 return false
97 }
98
99 func (n noopOption) IsClusterPoolSizeOrAccountsChange() bool {
100 return false
101 }
102
103 func (n noopOption) IsJetStreamChange() bool {
104 return false
105 }
106
107 func (n noopOption) IsStatszChange() bool {
108 return false
109 }
110
111 // loggingOption is a base struct that provides default option behaviors for
112 // logging-related options.
113 type loggingOption struct {
114 noopOption
115 }
116
117 func (l loggingOption) IsLoggingChange() bool {
118 return true
119 }
120
121 // traceLevelOption is a base struct that provides default option behaviors for
122 // tracelevel-related options.
123 type traceLevelOption struct {
124 loggingOption
125 }
126
127 func (l traceLevelOption) IsTraceLevelChange() bool {
128 return true
129 }
130
131 // traceOption implements the option interface for the `trace` setting.
132 type traceOption struct {
133 traceLevelOption
134 newValue bool
135 }
136
137 // Apply is a no-op because logging will be reloaded after options are applied.
138 func (t *traceOption) Apply(server *Server) {
139 server.Noticef("Reloaded: trace = %v", t.newValue)
140 }
141
142 // traceVersboseOption implements the option interface for the `trace_verbose` setting.
143 type traceVerboseOption struct {
144 traceLevelOption
145 newValue bool
146 }
147
148 // Apply is a no-op because logging will be reloaded after options are applied.
149 func (t *traceVerboseOption) Apply(server *Server) {
150 server.Noticef("Reloaded: trace_verbose = %v", t.newValue)
151 }
152
153 // traceHeadersOption implements the option interface for the `trace_headers` setting.
154 type traceHeadersOption struct {
155 traceLevelOption
156 newValue bool
157 }
158
159 // Apply is a no-op because logging will be reloaded after options are applied.
160 func (t *traceHeadersOption) Apply(server *Server) {
161 server.Noticef("Reloaded: trace_headers = %v", t.newValue)
162 }
163
164 // debugOption implements the option interface for the `debug` setting.
165 type debugOption struct {
166 loggingOption
167 newValue bool
168 }
169
170 // Apply is mostly a no-op because logging will be reloaded after options are applied.
171 // However we will kick the raft nodes if they exist to reload.
172 func (d *debugOption) Apply(server *Server) {
173 server.Noticef("Reloaded: debug = %v", d.newValue)
174 server.reloadDebugRaftNodes(d.newValue)
175 }
176
177 // logtimeOption implements the option interface for the `logtime` setting.
178 type logtimeOption struct {
179 loggingOption
180 newValue bool
181 }
182
183 // Apply is a no-op because logging will be reloaded after options are applied.
184 func (l *logtimeOption) Apply(server *Server) {
185 server.Noticef("Reloaded: logtime = %v", l.newValue)
186 }
187
188 // logtimeUTCOption implements the option interface for the `logtime_utc` setting.
189 type logtimeUTCOption struct {
190 loggingOption
191 newValue bool
192 }
193
194 // Apply is a no-op because logging will be reloaded after options are applied.
195 func (l *logtimeUTCOption) Apply(server *Server) {
196 server.Noticef("Reloaded: logtime_utc = %v", l.newValue)
197 }
198
199 // logfileOption implements the option interface for the `log_file` setting.
200 type logfileOption struct {
201 loggingOption
202 newValue string
203 }
204
205 // Apply is a no-op because logging will be reloaded after options are applied.
206 func (l *logfileOption) Apply(server *Server) {
207 server.Noticef("Reloaded: log_file = %v", l.newValue)
208 }
209
210 // syslogOption implements the option interface for the `syslog` setting.
211 type syslogOption struct {
212 loggingOption
213 newValue bool
214 }
215
216 // Apply is a no-op because logging will be reloaded after options are applied.
217 func (s *syslogOption) Apply(server *Server) {
218 server.Noticef("Reloaded: syslog = %v", s.newValue)
219 }
220
221 // remoteSyslogOption implements the option interface for the `remote_syslog`
222 // setting.
223 type remoteSyslogOption struct {
224 loggingOption
225 newValue string
226 }
227
228 // Apply is a no-op because logging will be reloaded after options are applied.
229 func (r *remoteSyslogOption) Apply(server *Server) {
230 server.Noticef("Reloaded: remote_syslog = %v", r.newValue)
231 }
232
233 // tlsOption implements the option interface for the `tls` setting.
234 type tlsOption struct {
235 noopOption
236 newValue *tls.Config
237 }
238
239 // Apply the tls change.
240 func (t *tlsOption) Apply(server *Server) {
241 server.mu.Lock()
242 tlsRequired := t.newValue != nil
243 server.info.TLSRequired = tlsRequired && !server.getOpts().AllowNonTLS
244 message := "disabled"
245 if tlsRequired {
246 server.info.TLSVerify = (t.newValue.ClientAuth == tls.RequireAndVerifyClientCert)
247 message = "enabled"
248 }
249 server.mu.Unlock()
250 server.Noticef("Reloaded: tls = %s", message)
251 }
252
253 func (t *tlsOption) IsTLSChange() bool {
254 return true
255 }
256
257 // tlsTimeoutOption implements the option interface for the tls `timeout`
258 // setting.
259 type tlsTimeoutOption struct {
260 noopOption
261 newValue float64
262 }
263
264 // Apply is a no-op because the timeout will be reloaded after options are
265 // applied.
266 func (t *tlsTimeoutOption) Apply(server *Server) {
267 server.Noticef("Reloaded: tls timeout = %v", t.newValue)
268 }
269
270 // tlsPinnedCertOption implements the option interface for the tls `pinned_certs` setting.
271 type tlsPinnedCertOption struct {
272 noopOption
273 newValue PinnedCertSet
274 }
275
276 // Apply is a no-op because the pinned certs will be reloaded after options are applied.
277 func (t *tlsPinnedCertOption) Apply(server *Server) {
278 server.Noticef("Reloaded: %d pinned_certs", len(t.newValue))
279 }
280
281 // tlsHandshakeFirst implements the option interface for the tls `handshake first` setting.
282 type tlsHandshakeFirst struct {
283 noopOption
284 newValue bool
285 }
286
287 // Apply is a no-op because the timeout will be reloaded after options are applied.
288 func (t *tlsHandshakeFirst) Apply(server *Server) {
289 server.Noticef("Reloaded: Client TLS handshake first: %v", t.newValue)
290 }
291
292 // tlsHandshakeFirstFallback implements the option interface for the tls `handshake first fallback delay` setting.
293 type tlsHandshakeFirstFallback struct {
294 noopOption
295 newValue time.Duration
296 }
297
298 // Apply is a no-op because the timeout will be reloaded after options are applied.
299 func (t *tlsHandshakeFirstFallback) Apply(server *Server) {
300 server.Noticef("Reloaded: Client TLS handshake first fallback delay: %v", t.newValue)
301 }
302
303 // authOption is a base struct that provides default option behaviors.
304 type authOption struct {
305 noopOption
306 }
307
308 func (o authOption) IsAuthChange() bool {
309 return true
310 }
311
312 // usernameOption implements the option interface for the `username` setting.
313 type usernameOption struct {
314 authOption
315 }
316
317 // Apply is a no-op because authorization will be reloaded after options are
318 // applied.
319 func (u *usernameOption) Apply(server *Server) {
320 server.Noticef("Reloaded: authorization username")
321 }
322
323 // passwordOption implements the option interface for the `password` setting.
324 type passwordOption struct {
325 authOption
326 }
327
328 // Apply is a no-op because authorization will be reloaded after options are
329 // applied.
330 func (p *passwordOption) Apply(server *Server) {
331 server.Noticef("Reloaded: authorization password")
332 }
333
334 // authorizationOption implements the option interface for the `token`
335 // authorization setting.
336 type authorizationOption struct {
337 authOption
338 }
339
340 // Apply is a no-op because authorization will be reloaded after options are
341 // applied.
342 func (a *authorizationOption) Apply(server *Server) {
343 server.Noticef("Reloaded: authorization token")
344 }
345
346 // authTimeoutOption implements the option interface for the authorization
347 // `timeout` setting.
348 type authTimeoutOption struct {
349 noopOption // Not authOption because this is a no-op; will be reloaded with options.
350 newValue float64
351 }
352
353 // Apply is a no-op because the timeout will be reloaded after options are
354 // applied.
355 func (a *authTimeoutOption) Apply(server *Server) {
356 server.Noticef("Reloaded: authorization timeout = %v", a.newValue)
357 }
358
359 // tagsOption implements the option interface for the `tags` setting.
360 type tagsOption struct {
361 noopOption // Not authOption because this is a no-op; will be reloaded with options.
362 }
363
364 func (u *tagsOption) Apply(server *Server) {
365 server.Noticef("Reloaded: tags")
366 }
367
368 func (u *tagsOption) IsStatszChange() bool {
369 return true
370 }
371
372 // metadataOption implements the option interface for the `metadata` setting.
373 type metadataOption struct {
374 noopOption // Not authOption because this is a no-op; will be reloaded with options.
375 }
376
377 func (u *metadataOption) Apply(server *Server) {
378 server.Noticef("Reloaded: metadata")
379 }
380
381 func (u *metadataOption) IsStatszChange() bool {
382 return true
383 }
384
385 // usersOption implements the option interface for the authorization `users`
386 // setting.
387 type usersOption struct {
388 authOption
389 }
390
391 func (u *usersOption) Apply(server *Server) {
392 server.Noticef("Reloaded: authorization users")
393 }
394
395 // nkeysOption implements the option interface for the authorization `users`
396 // setting.
397 type nkeysOption struct {
398 authOption
399 }
400
401 func (u *nkeysOption) Apply(server *Server) {
402 server.Noticef("Reloaded: authorization nkey users")
403 }
404
405 // clusterOption implements the option interface for the `cluster` setting.
406 type clusterOption struct {
407 authOption
408 newValue ClusterOpts
409 permsChanged bool
410 accsAdded []string
411 accsRemoved []string
412 poolSizeChanged bool
413 compressChanged bool
414 }
415
416 // Apply the cluster change.
417 func (c *clusterOption) Apply(s *Server) {
418 // TODO: support enabling/disabling clustering.
419 s.mu.Lock()
420 tlsRequired := c.newValue.TLSConfig != nil
421 s.routeInfo.TLSRequired = tlsRequired
422 s.routeInfo.TLSVerify = tlsRequired
423 s.routeInfo.AuthRequired = c.newValue.Username != ""
424 if c.newValue.NoAdvertise {
425 s.routeInfo.ClientConnectURLs = nil
426 s.routeInfo.WSConnectURLs = nil
427 } else {
428 s.routeInfo.ClientConnectURLs = s.clientConnectURLs
429 s.routeInfo.WSConnectURLs = s.websocket.connectURLs
430 }
431 s.setRouteInfoHostPortAndIP()
432 var routes []*client
433 if c.compressChanged {
434 co := &s.getOpts().Cluster.Compression
435 newMode := co.Mode
436 s.forEachRoute(func(r *client) {
437 r.mu.Lock()
438 // Skip routes that are "not supported" (because they will never do
439 // compression) or the routes that have already the new compression
440 // mode.
441 if r.route.compression == CompressionNotSupported || r.route.compression == newMode {
442 r.mu.Unlock()
443 return
444 }
445 // We need to close the route if it had compression "off" or the new
446 // mode is compression "off", or if the new mode is "accept", because
447 // these require negotiation.
448 if r.route.compression == CompressionOff || newMode == CompressionOff || newMode == CompressionAccept {
449 routes = append(routes, r)
450 } else if newMode == CompressionS2Auto {
451 // If the mode is "s2_auto", we need to check if there is really
452 // need to change, and at any rate, we want to save the actual
453 // compression level here, not s2_auto.
454 r.updateS2AutoCompressionLevel(co, &r.route.compression)
455 } else {
456 // Simply change the compression writer
457 r.out.cw = s2.NewWriter(nil, s2WriterOptions(newMode)...)
458 r.route.compression = newMode
459 }
460 r.mu.Unlock()
461 })
462 }
463 s.mu.Unlock()
464 if c.newValue.Name != "" && c.newValue.Name != s.ClusterName() {
465 s.setClusterName(c.newValue.Name)
466 }
467 for _, r := range routes {
468 r.closeConnection(ClientClosed)
469 }
470 s.Noticef("Reloaded: cluster")
471 if tlsRequired && c.newValue.TLSConfig.InsecureSkipVerify {
472 s.Warnf(clusterTLSInsecureWarning)
473 }
474 }
475
476 func (c *clusterOption) IsClusterPermsChange() bool {
477 return c.permsChanged
478 }
479
480 func (c *clusterOption) IsClusterPoolSizeOrAccountsChange() bool {
481 return c.poolSizeChanged || len(c.accsAdded) > 0 || len(c.accsRemoved) > 0
482 }
483
484 func (c *clusterOption) diffPoolAndAccounts(old *ClusterOpts) {
485 c.poolSizeChanged = c.newValue.PoolSize != old.PoolSize
486 addLoop:
487 for _, na := range c.newValue.PinnedAccounts {
488 for _, oa := range old.PinnedAccounts {
489 if na == oa {
490 continue addLoop
491 }
492 }
493 c.accsAdded = append(c.accsAdded, na)
494 }
495 removeLoop:
496 for _, oa := range old.PinnedAccounts {
497 for _, na := range c.newValue.PinnedAccounts {
498 if oa == na {
499 continue removeLoop
500 }
501 }
502 c.accsRemoved = append(c.accsRemoved, oa)
503 }
504 }
505
506 // routesOption implements the option interface for the cluster `routes`
507 // setting.
508 type routesOption struct {
509 noopOption
510 add []*url.URL
511 remove []*url.URL
512 }
513
514 // Apply the route changes by adding and removing the necessary routes.
515 func (r *routesOption) Apply(server *Server) {
516 server.mu.Lock()
517 routes := make([]*client, server.numRoutes())
518 i := 0
519 server.forEachRoute(func(r *client) {
520 routes[i] = r
521 i++
522 })
523 // If there was a change, notify monitoring code that it should
524 // update the route URLs if /varz endpoint is inspected.
525 if len(r.add)+len(r.remove) > 0 {
526 server.varzUpdateRouteURLs = true
527 }
528 server.mu.Unlock()
529
530 // Remove routes.
531 for _, remove := range r.remove {
532 for _, client := range routes {
533 var url *url.URL
534 client.mu.Lock()
535 if client.route != nil {
536 url = client.route.url
537 }
538 client.mu.Unlock()
539 if url != nil && urlsAreEqual(url, remove) {
540 // Do not attempt to reconnect when route is removed.
541 client.setNoReconnect()
542 client.closeConnection(RouteRemoved)
543 server.Noticef("Removed route %v", remove)
544 }
545 }
546 }
547
548 // Add routes.
549 server.mu.Lock()
550 server.solicitRoutes(r.add, server.getOpts().Cluster.PinnedAccounts)
551 server.mu.Unlock()
552
553 server.Noticef("Reloaded: cluster routes")
554 }
555
556 // maxConnOption implements the option interface for the `max_connections`
557 // setting.
558 type maxConnOption struct {
559 noopOption
560 newValue int
561 }
562
563 // Apply the max connections change by closing random connections til we are
564 // below the limit if necessary.
565 func (m *maxConnOption) Apply(server *Server) {
566 server.mu.Lock()
567 clients := make([]*client, 0, len(server.clients))
568 // Map iteration is random, which allows us to close random connections.
569 for _, client := range server.clients {
570 if isInternalClient(client.kind) {
571 continue
572 }
573 clients = append(clients, client)
574 }
575 server.mu.Unlock()
576
577 if newc := max(0, m.newValue); len(clients) > newc {
578 // Close connections til we are within the limit.
579 var (
580 numClose = len(clients) - newc
581 closed = 0
582 )
583 for _, client := range clients {
584 client.maxConnExceeded()
585 closed++
586 if closed >= numClose {
587 break
588 }
589 }
590 server.Noticef("Closed %d connections to fall within max_connections", closed)
591 }
592 server.Noticef("Reloaded: max_connections = %v", m.newValue)
593 }
594
595 // pidFileOption implements the option interface for the `pid_file` setting.
596 type pidFileOption struct {
597 noopOption
598 newValue string
599 }
600
601 // Apply the setting by logging the pid to the new file.
602 func (p *pidFileOption) Apply(server *Server) {
603 if p.newValue == "" {
604 return
605 }
606 if err := server.logPid(); err != nil {
607 server.Errorf("Failed to write pidfile: %v", err)
608 }
609 server.Noticef("Reloaded: pid_file = %v", p.newValue)
610 }
611
612 // portsFileDirOption implements the option interface for the `portFileDir` setting.
613 type portsFileDirOption struct {
614 noopOption
615 oldValue string
616 newValue string
617 }
618
619 func (p *portsFileDirOption) Apply(server *Server) {
620 server.deletePortsFile(p.oldValue)
621 server.logPorts()
622 server.Noticef("Reloaded: ports_file_dir = %v", p.newValue)
623 }
624
625 // maxControlLineOption implements the option interface for the
626 // `max_control_line` setting.
627 type maxControlLineOption struct {
628 noopOption
629 newValue int32
630 }
631
632 // Apply the setting by updating each client.
633 func (m *maxControlLineOption) Apply(server *Server) {
634 mcl := int32(m.newValue)
635 server.mu.Lock()
636 for _, client := range server.clients {
637 atomic.StoreInt32(&client.mcl, mcl)
638 }
639 server.mu.Unlock()
640 server.Noticef("Reloaded: max_control_line = %d", mcl)
641 }
642
643 // maxPayloadOption implements the option interface for the `max_payload`
644 // setting.
645 type maxPayloadOption struct {
646 noopOption
647 newValue int32
648 }
649
650 // Apply the setting by updating the server info and each client.
651 func (m *maxPayloadOption) Apply(server *Server) {
652 server.mu.Lock()
653 server.info.MaxPayload = m.newValue
654 for _, client := range server.clients {
655 atomic.StoreInt32(&client.mpay, int32(m.newValue))
656 }
657 server.mu.Unlock()
658 server.Noticef("Reloaded: max_payload = %d", m.newValue)
659 }
660
661 // pingIntervalOption implements the option interface for the `ping_interval`
662 // setting.
663 type pingIntervalOption struct {
664 noopOption
665 newValue time.Duration
666 }
667
668 // Apply is a no-op because the ping interval will be reloaded after options
669 // are applied.
670 func (p *pingIntervalOption) Apply(server *Server) {
671 server.Noticef("Reloaded: ping_interval = %s", p.newValue)
672 }
673
674 // maxPingsOutOption implements the option interface for the `ping_max`
675 // setting.
676 type maxPingsOutOption struct {
677 noopOption
678 newValue int
679 }
680
681 // Apply is a no-op because the ping interval will be reloaded after options
682 // are applied.
683 func (m *maxPingsOutOption) Apply(server *Server) {
684 server.Noticef("Reloaded: ping_max = %d", m.newValue)
685 }
686
687 // writeDeadlineOption implements the option interface for the `write_deadline`
688 // setting.
689 type writeDeadlineOption struct {
690 noopOption
691 newValue time.Duration
692 }
693
694 // Apply is a no-op because the write deadline will be reloaded after options
695 // are applied.
696 func (w *writeDeadlineOption) Apply(server *Server) {
697 server.Noticef("Reloaded: write_deadline = %s", w.newValue)
698 }
699
700 // clientAdvertiseOption implements the option interface for the `client_advertise` setting.
701 type clientAdvertiseOption struct {
702 noopOption
703 newValue string
704 }
705
706 // Apply the setting by updating the server info and regenerate the infoJSON byte array.
707 func (c *clientAdvertiseOption) Apply(server *Server) {
708 server.mu.Lock()
709 server.setInfoHostPort()
710 server.mu.Unlock()
711 server.Noticef("Reload: client_advertise = %s", c.newValue)
712 }
713
714 // accountsOption implements the option interface.
715 // Ensure that authorization code is executed if any change in accounts
716 type accountsOption struct {
717 authOption
718 }
719
720 // Apply is a no-op. Changes will be applied in reloadAuthorization
721 func (a *accountsOption) Apply(s *Server) {
722 s.Noticef("Reloaded: accounts")
723 }
724
725 // For changes to a server's config.
726 type jetStreamOption struct {
727 noopOption
728 newValue bool
729 }
730
731 func (a *jetStreamOption) Apply(s *Server) {
732 s.Noticef("Reloaded: JetStream")
733 }
734
735 func (jso jetStreamOption) IsJetStreamChange() bool {
736 return true
737 }
738
739 func (jso jetStreamOption) IsStatszChange() bool {
740 return true
741 }
742
743 type jetStreamLimitsOption struct {
744 noopOption
745 newMaxMemory int64
746 newMaxStore int64
747 }
748
749 func (jso *jetStreamLimitsOption) Apply(s *Server) {
750 js := s.getJetStream()
751 if js == nil {
752 return
753 }
754 js.mu.Lock()
755 if jso.newMaxMemory > 0 {
756 js.config.MaxMemory = jso.newMaxMemory
757 atomic.StoreInt64(&js.memMax, js.config.MaxMemory)
758 s.Noticef("Reloaded: JetStream max_mem_store = %s", friendlyBytes(jso.newMaxMemory))
759 }
760 if jso.newMaxStore > 0 {
761 js.config.MaxStore = jso.newMaxStore
762 atomic.StoreInt64(&js.storeMax, js.config.MaxStore)
763 s.Noticef("Reloaded: JetStream max_file_store = %s", friendlyBytes(jso.newMaxStore))
764 }
765 js.mu.Unlock()
766 }
767
768 func (jso *jetStreamLimitsOption) IsStatszChange() bool {
769 return true
770 }
771
772 type defaultSentinelOption struct {
773 noopOption
774 newValue string
775 }
776
777 func (so *defaultSentinelOption) Apply(s *Server) {
778 s.Noticef("Reloaded: default_sentinel = %s", so.newValue)
779 }
780
781 type ocspOption struct {
782 tlsOption
783 newValue *OCSPConfig
784 }
785
786 func (a *ocspOption) Apply(s *Server) {
787 s.Noticef("Reloaded: OCSP")
788 }
789
790 type ocspResponseCacheOption struct {
791 tlsOption
792 newValue *OCSPResponseCacheConfig
793 }
794
795 func (a *ocspResponseCacheOption) Apply(s *Server) {
796 s.Noticef("Reloaded OCSP peer cache")
797 }
798
799 // connectErrorReports implements the option interface for the `connect_error_reports`
800 // setting.
801 type connectErrorReports struct {
802 noopOption
803 newValue int
804 }
805
806 // Apply is a no-op because the value will be reloaded after options are applied.
807 func (c *connectErrorReports) Apply(s *Server) {
808 s.Noticef("Reloaded: connect_error_reports = %v", c.newValue)
809 }
810
811 // connectErrorReports implements the option interface for the `connect_error_reports`
812 // setting.
813 type reconnectErrorReports struct {
814 noopOption
815 newValue int
816 }
817
818 // Apply is a no-op because the value will be reloaded after options are applied.
819 func (r *reconnectErrorReports) Apply(s *Server) {
820 s.Noticef("Reloaded: reconnect_error_reports = %v", r.newValue)
821 }
822
823 // maxTracedMsgLenOption implements the option interface for the `max_traced_msg_len` setting.
824 type maxTracedMsgLenOption struct {
825 noopOption
826 newValue int
827 }
828
829 // Apply the setting by updating the maximum traced message length.
830 func (m *maxTracedMsgLenOption) Apply(server *Server) {
831 server.mu.Lock()
832 defer server.mu.Unlock()
833 server.opts.MaxTracedMsgLen = m.newValue
834 server.Noticef("Reloaded: max_traced_msg_len = %d", m.newValue)
835 }
836
837 type mqttAckWaitReload struct {
838 noopOption
839 newValue time.Duration
840 }
841
842 func (o *mqttAckWaitReload) Apply(s *Server) {
843 s.Noticef("Reloaded: MQTT ack_wait = %v", o.newValue)
844 }
845
846 type mqttMaxAckPendingReload struct {
847 noopOption
848 newValue uint16
849 }
850
851 func (o *mqttMaxAckPendingReload) Apply(s *Server) {
852 s.mqttUpdateMaxAckPending(o.newValue)
853 s.Noticef("Reloaded: MQTT max_ack_pending = %v", o.newValue)
854 }
855
856 type mqttStreamReplicasReload struct {
857 noopOption
858 newValue int
859 }
860
861 func (o *mqttStreamReplicasReload) Apply(s *Server) {
862 s.Noticef("Reloaded: MQTT stream_replicas = %v", o.newValue)
863 }
864
865 type mqttConsumerReplicasReload struct {
866 noopOption
867 newValue int
868 }
869
870 func (o *mqttConsumerReplicasReload) Apply(s *Server) {
871 s.Noticef("Reloaded: MQTT consumer_replicas = %v", o.newValue)
872 }
873
874 type mqttConsumerMemoryStorageReload struct {
875 noopOption
876 newValue bool
877 }
878
879 func (o *mqttConsumerMemoryStorageReload) Apply(s *Server) {
880 s.Noticef("Reloaded: MQTT consumer_memory_storage = %v", o.newValue)
881 }
882
883 type mqttInactiveThresholdReload struct {
884 noopOption
885 newValue time.Duration
886 }
887
888 func (o *mqttInactiveThresholdReload) Apply(s *Server) {
889 s.Noticef("Reloaded: MQTT consumer_inactive_threshold = %v", o.newValue)
890 }
891
892 type profBlockRateReload struct {
893 noopOption
894 newValue int
895 }
896
897 func (o *profBlockRateReload) Apply(s *Server) {
898 s.setBlockProfileRate(o.newValue)
899 s.Noticef("Reloaded: prof_block_rate = %v", o.newValue)
900 }
901
902 type leafNodeOption struct {
903 noopOption
904 tlsFirstChanged bool
905 compressionChanged bool
906 // These are for the remotes
907 added []*RemoteLeafOpts
908 changed map[*leafNodeCfg]*remoteLeafOption
909 }
910
911 type remoteLeafOption struct {
912 tlsFirstChanged bool
913 compressionChanged bool
914 disabledChanged bool
915 opts *RemoteLeafOpts
916 }
917
918 // Given `old` and `new` Leafnode options, this function will return the structure
919 // used for applying the configuration, or an error is there are changes that
920 // are not supported.
921 func getLeafNodeOptionsChanges(s *Server, old, new *LeafNodeOpts) (*leafNodeOption, error) {
922
923 // We can't use DeepEqual for `Users` field, so do custom check.
924 if usersHaveChanged(old.Users, new.Users) {
925 return nil, fmt.Errorf("field \"Users\": old=%v, new=%v", old.Users, new.Users)
926 }
927
928 // Check the main leafnodes{} block to see if there are any changes that are
929 // not supported. We provide a list of fields to ignore (we already checked,
930 // allow them to be modified or will check later).
931 if err := checkConfigsEqual(old, new, []string{
932 "Compression",
933 "Remotes",
934 "TLSHandshakeFirst",
935 "TLSHandshakeFirstFallback",
936 "TLSConfig",
937 "Users",
938 }); err != nil {
939 return nil, err
940 }
941
942 const (
943 remoteErrFormat = "remote %s: %s"
944 maxAttempts = 20
945 )
946 var (
947 nlo *leafNodeOption
948 // Track whether any existing remote was not found (i.e. removed).
949 removed bool
950 )
951
952 forLoop:
953 for failed := range maxAttempts {
954 removed = false
955 if failed > 0 {
956 // If we failed once, we will wait a bit before trying again the remotes.
957 // This could give enough time for connections that were in progress to complete.
958 select {
959 case <-time.After(50 * time.Millisecond):
960 case <-s.quitCh:
961 return nil, ErrServerNotRunning
962 }
963 }
964 nlo = &leafNodeOption{
965 tlsFirstChanged: (old.TLSHandshakeFirst != new.TLSHandshakeFirst || old.TLSHandshakeFirstFallback != new.TLSHandshakeFirstFallback),
966 compressionChanged: !old.Compression.equals(&new.Compression),
967 // Start with all, will update when processing existing ones.
968 // Since the list will be modified, we need to clone it.
969 added: slices.Clone(new.Remotes),
970 }
971
972 s.mu.RLock()
973 // Go through the list of existing remote configurations.
974 for lrc := range s.leafRemoteCfgs {
975 var rlo *RemoteLeafOpts
976 // Look for the corresponding `*RemoteLeafOpts` in the `nlo.added`
977 // list. If it is found, that function returns an updated list
978 // with the element removed from it.
979 lrc.RLock()
980 rlo, nlo.added = getRemoteLeafOpts(lrc.name(), nlo.added)
981 if rlo == nil {
982 // Not found, will be removed in leafNodeOption.Apply().
983 removed = true
984 lrc.RUnlock()
985 continue
986 }
987 // Now we need to make sure that there are no changes that we don't
988 // support for a RemoteLeafOpts.
989 err := checkConfigsEqual(lrc.RemoteLeafOpts, rlo, []string{
990 "Compression",
991 "Disabled",
992 "TLS",
993 "TLSHandshakeFirst",
994 "TLSConfig",
995 })
996 if err != nil {
997 lrc.RUnlock()
998 s.mu.RUnlock()
999 return nil, fmt.Errorf(remoteErrFormat, rlo.safeName(), err)
1000 }
1001 disabledChanged := lrc.Disabled != rlo.Disabled
1002 // If this remote was disabled and is now enabled, we need to make sure
1003 // that there is no connect in progress. If that is the case, either
1004 // try again (if it is the first failure) or return an error.
1005 if disabledChanged && lrc.Disabled && lrc.connInProgress {
1006 lrc.RUnlock()
1007 s.mu.RUnlock()
1008 if failed < maxAttempts-1 {
1009 continue forLoop
1010 }
1011 return nil, fmt.Errorf(remoteErrFormat, rlo.safeName(),
1012 "cannot be enabled at the moment, try again")
1013 }
1014 // Since we will use the new `rlo.TLSConfig` later on, consider all
1015 // existing remote configs as "changed" and store them in the
1016 // `nlo.changed` map.
1017 if nlo.changed == nil {
1018 nlo.changed = make(map[*leafNodeCfg]*remoteLeafOption)
1019 }
1020 lnro := &remoteLeafOption{
1021 tlsFirstChanged: lrc.TLSHandshakeFirst != rlo.TLSHandshakeFirst,
1022 compressionChanged: !lrc.Compression.equals(&rlo.Compression),
1023 disabledChanged: disabledChanged,
1024 opts: rlo,
1025 }
1026 lrc.RUnlock()
1027 nlo.changed[lrc] = lnro
1028 }
1029 if len(nlo.added) > 0 {
1030 // Go through the added list and check if an added was recently removed and,
1031 // if that is the case, is it still in the `s.rmLeafRemoteCfgs` map, which
1032 // may mean that there was a connect-in-progress that did not complete yet.
1033 // Either try again (if it is the first failure) or return an error.
1034 for _, rlo := range nlo.added {
1035 if _, cip := s.rmLeafRemoteCfgs[rlo.name()]; cip {
1036 s.mu.RUnlock()
1037 if failed < maxAttempts-1 {
1038 continue forLoop
1039 }
1040 return nil, fmt.Errorf(remoteErrFormat, rlo.safeName(),
1041 "cannot be added at the moment, try again")
1042 }
1043 }
1044 }
1045 s.mu.RUnlock()
1046 break
1047 }
1048
1049 // Now we want to make sure that there were actual changes, so that we don't
1050 // cause a reload of leafnodes for nothing. However, if one has (or all have)
1051 // been removed we still need to invoke leafNodeOption.Apply().
1052 if !nlo.tlsFirstChanged && !nlo.compressionChanged && !removed && len(nlo.added) == 0 && len(nlo.changed) == 0 {
1053 return nil, nil
1054 }
1055
1056 return nlo, nil
1057 }
1058
1059 func usersHaveChanged(ousers, nusers []*User) bool {
1060 if len(ousers) != len(nusers) {
1061 return true
1062 }
1063 // We did not do a strict list order check in the past, so maintain this to
1064 // avoid possible breaking changes.
1065 oua := make(map[string]*User, len(ousers))
1066 nua := make(map[string]*User, len(nusers))
1067 for _, u := range ousers {
1068 oua[u.Username] = u
1069 }
1070 for _, u := range nusers {
1071 nua[u.Username] = u
1072 }
1073 for uname, u := range oua {
1074 // If we can not find new one with same name, consider that they have changed.
1075 nu, ok := nua[uname]
1076 if !ok {
1077 return true
1078 }
1079 // Same if password or account has changed.
1080 if u.Password != nu.Password || u.Account.GetName() != nu.Account.GetName() {
1081 return true
1082 }
1083 }
1084 return false
1085 }
1086
1087 // Given the `search` remote leafnode options name, searches for a match in the `list`.
1088 // If found, returns the `*RemoteLeafOpts` from the list, and the updated list
1089 // without the element in it. If not found, returns `nil` and the unmodified list.
1090 func getRemoteLeafOpts(search string, list []*RemoteLeafOpts) (*RemoteLeafOpts, []*RemoteLeafOpts) {
1091 for i, rlo := range list {
1092 if search == rlo.name() {
1093 lastIdx := len(list) - 1
1094 if lastIdx == 0 {
1095 return rlo, nil
1096 }
1097 if i < lastIdx {
1098 list[i] = list[lastIdx]
1099 }
1100 list = list[:lastIdx]
1101 return rlo, list
1102 }
1103 }
1104 return nil, list
1105 }
1106
1107 func (l *leafNodeOption) Apply(s *Server) {
1108 opts := s.getOpts()
1109 if l.tlsFirstChanged {
1110 s.Noticef("Reloaded: LeafNode TLS HandshakeFirst value is: %v", opts.LeafNode.TLSHandshakeFirst)
1111 s.Noticef("Reloaded: LeafNode TLS HandshakeFirstFallback value is: %v", opts.LeafNode.TLSHandshakeFirstFallback)
1112 }
1113 if l.compressionChanged {
1114 s.Noticef("Reloaded: LeafNode Compression value is: %v", opts.LeafNode.Compression)
1115 }
1116
1117 var close []*client
1118 var enable []*leafNodeCfg
1119 var removed bool
1120
1121 s.mu.Lock()
1122 acceptSideCompOpts := &opts.LeafNode.Compression
1123 // First go over existing leafnode remote configurations and
1124 // either remove if no longer present, or update the config.
1125 for lrc := range s.leafRemoteCfgs {
1126 rlo := l.changed[lrc]
1127 if rlo == nil {
1128 delete(s.leafRemoteCfgs, lrc)
1129 removed = true
1130 if s.rmLeafRemoteCfgs == nil {
1131 s.rmLeafRemoteCfgs = make(map[string]*leafNodeCfg)
1132 }
1133 s.rmLeafRemoteCfgs[lrc.name()] = lrc
1134 lrc.markAsRemoved()
1135 s.Noticef("Reloaded: LeafNode Remote %s removed", lrc.RemoteLeafOpts.safeName())
1136 // We will close the existing connection in the next for-loop.
1137 continue
1138 }
1139 lrc.Lock()
1140 // TLSConfig is always applied.
1141 lrc.TLSConfig = rlo.opts.TLSConfig.Clone()
1142 // Now update what has been detected has changed.
1143 if rlo.tlsFirstChanged {
1144 lrc.TLSHandshakeFirst = rlo.opts.TLSHandshakeFirst
1145 s.Noticef("Reloaded: LeafNode Remote %s TLS HandshakeFirst value is: %v",
1146 lrc.RemoteLeafOpts.safeName(), rlo.opts.TLSHandshakeFirst)
1147 }
1148 if rlo.compressionChanged {
1149 lrc.Compression = rlo.opts.Compression
1150 s.Noticef("Reloaded: LeafNode Remote %s Compression value is: %v",
1151 lrc.RemoteLeafOpts.safeName(), rlo.opts.Compression)
1152 }
1153 if rlo.disabledChanged {
1154 // Change to new value.
1155 lrc.Disabled = rlo.opts.Disabled
1156 if lrc.Disabled {
1157 lrc.notifyQuitChannel()
1158 } else {
1159 enable = append(enable, lrc)
1160 }
1161 s.Noticef("Reloaded: LeafNode Remote %s Disabled value is: %v",
1162 lrc.RemoteLeafOpts.safeName(), rlo.opts.Disabled)
1163 }
1164 lrc.Unlock()
1165 }
1166 // Second, go over existing leaf connections and apply compression
1167 // changes (if applicable) and collect connections that need to be
1168 // closed and/or disabled.
1169 for _, c := range s.leafs {
1170 var co *CompressionOpts
1171
1172 c.mu.Lock()
1173 if r := c.leaf.remote; r != nil {
1174 rlo := l.changed[r]
1175 // If the config is not in the `changed` map, or the new config says that
1176 // the connection is disabled, collect so we can close it after the server
1177 // lock is released.
1178 if rlo == nil || (rlo.disabledChanged && rlo.opts.Disabled) {
1179 c.flags.set(noReconnect)
1180 close = append(close, c)
1181 c.mu.Unlock()
1182 continue
1183 }
1184 if rlo.compressionChanged {
1185 co = &r.Compression
1186 }
1187 } else if l.compressionChanged {
1188 co = acceptSideCompOpts
1189 }
1190 if co != nil && applyCompressionChanges(c, co) {
1191 close = append(close, c)
1192 }
1193 c.mu.Unlock()
1194 }
1195 s.mu.Unlock()
1196
1197 // Close the connections for which negotiation is required, have been disabled
1198 // or simply removed.
1199 for _, c := range close {
1200 c.closeConnection(ClientClosed)
1201 }
1202 // Start the ones that have been enabled.
1203 for _, r := range enable {
1204 s.connectToRemoteLeafNodeAsynchronously(r, true)
1205 }
1206 // Finally, deal with the ones that have been added.
1207 if len(l.added) > 0 {
1208 s.solicitLeafNodeRemotes(l.added)
1209 }
1210 // Deal with removed configs. Make sure there are no connect-in-progress.
1211 // If there are still some, have a go routine to check in the background.
1212 if removed {
1213 if checkAgain := checkRemovedLeafNodeCfgs(s); checkAgain {
1214 checkRemovedLeafNodeCfgsAsync(s)
1215 }
1216 }
1217 }
1218
1219 // Go through the removed remote leafnode configs map to check if the
1220 // connect-in-progress flag is set. If not, remove from the map.
1221 // Returns `true` if there are still some that are in progress.
1222 func checkRemovedLeafNodeCfgs(s *Server) bool {
1223 var inProgress int
1224 s.mu.Lock()
1225 for rn, r := range s.rmLeafRemoteCfgs {
1226 if r.isConnectInProgress() {
1227 inProgress++
1228 } else {
1229 delete(s.rmLeafRemoteCfgs, rn)
1230 }
1231 }
1232 s.mu.Unlock()
1233 // Needs to be called again if inProgress > 0
1234 return inProgress > 0
1235 }
1236
1237 // Will start a go routine that will periodically call `checkRemovedLeafNodeCfgs`.
1238 // When the removed map has been emptied, the go routine will end. It is ok for
1239 // this function to be invoked multiple times and have multiple instances running
1240 // concurrently.
1241 func checkRemovedLeafNodeCfgsAsync(s *Server) {
1242 s.startGoRoutine(func() {
1243 defer s.grWG.Done()
1244 tick := time.NewTicker(50 * time.Millisecond)
1245 defer tick.Stop()
1246 for {
1247 select {
1248 case <-tick.C:
1249 if checkAgain := checkRemovedLeafNodeCfgs(s); !checkAgain {
1250 return
1251 }
1252 case <-s.quitCh:
1253 return
1254 }
1255 }
1256 })
1257 }
1258
1259 // The `co` compression options are applied to the given leaf connection `c`.
1260 // If a "restart" of the connection is needed, will return true, false otherwise.
1261 func applyCompressionChanges(c *client, co *CompressionOpts) bool {
1262 newMode := co.Mode
1263 // Skip leaf connections that are "not supported" (because they
1264 // will never do compression) or the ones that have already the
1265 // new compression mode.
1266 if c.leaf.compression == CompressionNotSupported || c.leaf.compression == newMode {
1267 return false
1268 }
1269 // We need to close the connections if it had compression "off" or the new
1270 // mode is compression "off", or if the new mode is "accept", because
1271 // these require negotiation.
1272 if c.leaf.compression == CompressionOff || newMode == CompressionOff || newMode == CompressionAccept {
1273 return true
1274 } else if newMode == CompressionS2Auto {
1275 // If the mode is "s2_auto", we need to check if there is really
1276 // need to change, and at any rate, we want to save the actual
1277 // compression level here, not s2_auto.
1278 c.updateS2AutoCompressionLevel(co, &c.leaf.compression)
1279 } else {
1280 // Simply change the compression writer
1281 c.out.cw = s2.NewWriter(nil, s2WriterOptions(newMode)...)
1282 c.leaf.compression = newMode
1283 }
1284 return false
1285 }
1286
1287 type noFastProdStallReload struct {
1288 noopOption
1289 noStall bool
1290 }
1291
1292 func (l *noFastProdStallReload) Apply(s *Server) {
1293 var not string
1294 if l.noStall {
1295 not = "not "
1296 }
1297 s.Noticef("Reloaded: fast producers will %sbe stalled", not)
1298 }
1299
1300 // Compares options and disconnects clients that are no longer listed in pinned certs. Lock must not be held.
1301 func (s *Server) recheckPinnedCerts(curOpts *Options, newOpts *Options) {
1302 s.mu.Lock()
1303 disconnectClients := []*client{}
1304 protoToPinned := map[int]PinnedCertSet{}
1305 if !reflect.DeepEqual(newOpts.TLSPinnedCerts, curOpts.TLSPinnedCerts) {
1306 protoToPinned[NATS] = curOpts.TLSPinnedCerts
1307 }
1308 if !reflect.DeepEqual(newOpts.MQTT.TLSPinnedCerts, curOpts.MQTT.TLSPinnedCerts) {
1309 protoToPinned[MQTT] = curOpts.MQTT.TLSPinnedCerts
1310 }
1311 if !reflect.DeepEqual(newOpts.Websocket.TLSPinnedCerts, curOpts.Websocket.TLSPinnedCerts) {
1312 protoToPinned[WS] = curOpts.Websocket.TLSPinnedCerts
1313 }
1314 for _, c := range s.clients {
1315 if c.kind != CLIENT {
1316 continue
1317 }
1318 if pinned, ok := protoToPinned[c.clientType()]; ok {
1319 if !c.matchesPinnedCert(pinned) {
1320 disconnectClients = append(disconnectClients, c)
1321 }
1322 }
1323 }
1324 checkClients := func(kind int, clients map[uint64]*client, set PinnedCertSet) {
1325 for _, c := range clients {
1326 if c.kind == kind && !c.matchesPinnedCert(set) {
1327 disconnectClients = append(disconnectClients, c)
1328 }
1329 }
1330 }
1331 if !reflect.DeepEqual(newOpts.LeafNode.TLSPinnedCerts, curOpts.LeafNode.TLSPinnedCerts) {
1332 checkClients(LEAF, s.leafs, newOpts.LeafNode.TLSPinnedCerts)
1333 }
1334 if !reflect.DeepEqual(newOpts.Cluster.TLSPinnedCerts, curOpts.Cluster.TLSPinnedCerts) {
1335 s.forEachRoute(func(c *client) {
1336 if !c.matchesPinnedCert(newOpts.Cluster.TLSPinnedCerts) {
1337 disconnectClients = append(disconnectClients, c)
1338 }
1339 })
1340 }
1341 if s.gateway.enabled && !reflect.DeepEqual(newOpts.Gateway.TLSPinnedCerts, curOpts.Gateway.TLSPinnedCerts) {
1342 gw := s.gateway
1343 gw.RLock()
1344 for _, c := range gw.out {
1345 if !c.matchesPinnedCert(newOpts.Gateway.TLSPinnedCerts) {
1346 disconnectClients = append(disconnectClients, c)
1347 }
1348 }
1349 checkClients(GATEWAY, gw.in, newOpts.Gateway.TLSPinnedCerts)
1350 gw.RUnlock()
1351 }
1352 s.mu.Unlock()
1353 if len(disconnectClients) > 0 {
1354 s.Noticef("Disconnect %d clients due to pinned certs reload", len(disconnectClients))
1355 for _, c := range disconnectClients {
1356 c.closeConnection(TLSHandshakeError)
1357 }
1358 }
1359 }
1360
1361 type proxiesReload struct {
1362 noopOption
1363 add []string
1364 del []string
1365 }
1366
1367 func (p *proxiesReload) Apply(s *Server) {
1368 var clients []*client
1369 s.mu.Lock()
1370 for _, k := range p.del {
1371 cc := s.proxiedConns[k]
1372 delete(s.proxiedConns, k)
1373 if len(cc) > 0 {
1374 for _, c := range cc {
1375 clients = append(clients, c)
1376 }
1377 }
1378 }
1379 s.processProxiesTrustedKeys()
1380 s.mu.Unlock()
1381 if len(p.del) > 0 {
1382 for _, c := range clients {
1383 c.setAuthError(ErrAuthProxyNotTrusted)
1384 c.authViolation()
1385 }
1386 s.Noticef("Reloaded: proxies trusted keys %q were removed", p.del)
1387 }
1388 if len(p.add) > 0 {
1389 s.Noticef("Reloaded: proxies trusted keys %q were added", p.add)
1390 }
1391 }
1392
1393 // Reload reads the current configuration file and calls out to ReloadOptions
1394 // to apply the changes. This returns an error if the server was not started
1395 // with a config file or an option which doesn't support hot-swapping was changed.
1396 func (s *Server) Reload() error {
1397 s.mu.Lock()
1398 configFile := s.configFile
1399 s.mu.Unlock()
1400 if configFile == "" {
1401 return errors.New("can only reload config when a file is provided using -c or --config")
1402 }
1403
1404 newOpts, err := ProcessConfigFile(configFile)
1405 if err != nil {
1406 // TODO: Dump previous good config to a .bak file?
1407 return err
1408 }
1409 return s.ReloadOptions(newOpts)
1410 }
1411
1412 // ReloadOptions applies any supported options from the provided Options
1413 // type. This returns an error if an option which doesn't support
1414 // hot-swapping was changed.
1415 // The provided Options type should not be re-used afterwards.
1416 // Either use Options.Clone() to pass a copy, or make a new one.
1417 func (s *Server) ReloadOptions(newOpts *Options) error {
1418 s.reloadMu.Lock()
1419 defer s.reloadMu.Unlock()
1420
1421 s.mu.Lock()
1422
1423 curOpts := s.getOpts()
1424
1425 clientOrgPort := curOpts.Port
1426 clusterOrgPort := curOpts.Cluster.Port
1427 gatewayOrgPort := curOpts.Gateway.Port
1428 leafnodesOrgPort := curOpts.LeafNode.Port
1429 websocketOrgPort := curOpts.Websocket.Port
1430 mqttOrgPort := curOpts.MQTT.Port
1431
1432 s.mu.Unlock()
1433
1434 // In case "-cluster ..." was provided through the command line, this will
1435 // properly set the Cluster.Host/Port etc...
1436 if l := curOpts.Cluster.ListenStr; l != _EMPTY_ {
1437 newOpts.Cluster.ListenStr = l
1438 overrideCluster(newOpts)
1439 }
1440
1441 // Apply flags over config file settings.
1442 newOpts = MergeOptions(newOpts, FlagSnapshot)
1443
1444 // Need more processing for boolean flags...
1445 if FlagSnapshot != nil {
1446 applyBoolFlags(newOpts, FlagSnapshot)
1447 }
1448
1449 setBaselineOptions(newOpts)
1450
1451 // setBaselineOptions sets Port to 0 if set to -1 (RANDOM port)
1452 // If that's the case, set it to the saved value when the accept loop was
1453 // created.
1454 if newOpts.Port == 0 {
1455 newOpts.Port = clientOrgPort
1456 }
1457 // We don't do that for cluster, so check against -1.
1458 if newOpts.Cluster.Port == -1 {
1459 newOpts.Cluster.Port = clusterOrgPort
1460 }
1461 if newOpts.Gateway.Port == -1 {
1462 newOpts.Gateway.Port = gatewayOrgPort
1463 }
1464 if newOpts.LeafNode.Port == -1 {
1465 newOpts.LeafNode.Port = leafnodesOrgPort
1466 }
1467 if newOpts.Websocket.Port == -1 {
1468 newOpts.Websocket.Port = websocketOrgPort
1469 }
1470 if newOpts.MQTT.Port == -1 {
1471 newOpts.MQTT.Port = mqttOrgPort
1472 }
1473
1474 if err := s.reloadOptions(curOpts, newOpts); err != nil {
1475 return err
1476 }
1477
1478 s.recheckPinnedCerts(curOpts, newOpts)
1479
1480 s.varzMu.Lock()
1481 s.mu.Lock()
1482 s.configTime = time.Now().UTC()
1483 s.updateVarzConfigReloadableFields(s.varz)
1484 s.mu.Unlock()
1485 s.varzMu.Unlock()
1486 return nil
1487 }
1488 func applyBoolFlags(newOpts, flagOpts *Options) {
1489 // Reset fields that may have been set to `true` in
1490 // MergeOptions() when some of the flags default to `true`
1491 // but have not been explicitly set and therefore value
1492 // from config file should take precedence.
1493 for name, val := range newOpts.inConfig {
1494 f := reflect.ValueOf(newOpts).Elem()
1495 names := strings.Split(name, ".")
1496 for _, name := range names {
1497 f = f.FieldByName(name)
1498 }
1499 f.SetBool(val)
1500 }
1501 // Now apply value (true or false) from flags that have
1502 // been explicitly set in command line
1503 for name, val := range flagOpts.inCmdLine {
1504 f := reflect.ValueOf(newOpts).Elem()
1505 names := strings.Split(name, ".")
1506 for _, name := range names {
1507 f = f.FieldByName(name)
1508 }
1509 f.SetBool(val)
1510 }
1511 }
1512
1513 // reloadOptions reloads the server config with the provided options. If an
1514 // option that doesn't support hot-swapping is changed, this returns an error.
1515 func (s *Server) reloadOptions(curOpts, newOpts *Options) error {
1516 // Apply to the new options some of the options that may have been set
1517 // that can't be configured in the config file (this can happen in
1518 // applications starting NATS Server programmatically).
1519 newOpts.CustomClientAuthentication = curOpts.CustomClientAuthentication
1520 newOpts.CustomRouterAuthentication = curOpts.CustomRouterAuthentication
1521
1522 // Do the validation before checking for differences. We need to ensure
1523 // that the new options are valid. Note that there are possible side
1524 // effects of calling validateOptions(), in that some default values
1525 // may be set, etc... but that should be ok since the current options
1526 // went through the same process on startup/previous reload.
1527 if err := validateOptions(newOpts); err != nil {
1528 return err
1529 }
1530
1531 changed, err := s.diffOptions(newOpts)
1532 if err != nil {
1533 return err
1534 }
1535
1536 // Create a context that is used to pass special info that we may need
1537 // while applying the new options.
1538 ctx := reloadContext{oldClusterPerms: curOpts.Cluster.Permissions}
1539 s.setOpts(newOpts)
1540 s.applyOptions(&ctx, changed)
1541 return nil
1542 }
1543
1544 // For the purpose of comparing, impose a order on slice data types where order does not matter
1545 func imposeOrder(value any) error {
1546 switch value := value.(type) {
1547 case []*Account:
1548 slices.SortFunc(value, func(i, j *Account) int { return cmp.Compare(i.Name, j.Name) })
1549 for _, a := range value {
1550 slices.SortFunc(a.imports.streams, func(i, j *streamImport) int { return cmp.Compare(i.acc.Name, j.acc.Name) })
1551 }
1552 case []*User:
1553 slices.SortFunc(value, func(i, j *User) int { return cmp.Compare(i.Username, j.Username) })
1554 case []*NkeyUser:
1555 slices.SortFunc(value, func(i, j *NkeyUser) int { return cmp.Compare(i.Nkey, j.Nkey) })
1556 case []*url.URL:
1557 slices.SortFunc(value, func(i, j *url.URL) int { return cmp.Compare(i.String(), j.String()) })
1558 case []string:
1559 slices.Sort(value)
1560 case []*jwt.OperatorClaims:
1561 slices.SortFunc(value, func(i, j *jwt.OperatorClaims) int { return cmp.Compare(i.Issuer, j.Issuer) })
1562 case GatewayOpts:
1563 slices.SortFunc(value.Gateways, func(i, j *RemoteGatewayOpts) int { return cmp.Compare(i.Name, j.Name) })
1564 case WebsocketOpts:
1565 slices.Sort(value.AllowedOrigins)
1566 case string, bool, uint8, uint16, uint64, int, int32, int64, time.Duration, float64, nil, LeafNodeOpts, ClusterOpts, *tls.Config, PinnedCertSet,
1567 *URLAccResolver, *MemAccResolver, *DirAccResolver, *CacheDirAccResolver, Authentication, MQTTOpts, jwt.TagList,
1568 *OCSPConfig, map[string]string, map[string]bool, JSLimitOpts, StoreCipher, *OCSPResponseCacheConfig, *ProxiesConfig, WriteTimeoutPolicy:
1569 // explicitly skipped types
1570 case *AuthCallout:
1571 case JSTpmOpts:
1572 default:
1573 // this will fail during unit tests
1574 return fmt.Errorf("OnReload, sort or explicitly skip type: %s",
1575 reflect.TypeOf(value))
1576 }
1577 return nil
1578 }
1579
1580 // diffOptions returns a slice containing options which have been changed. If
1581 // an option that doesn't support hot-swapping is changed, this returns an
1582 // error.
1583 func (s *Server) diffOptions(newOpts *Options) ([]option, error) {
1584 var (
1585 oldOpts = s.getOpts()
1586 oldConfig = reflect.ValueOf(oldOpts).Elem()
1587 newConfig = reflect.ValueOf(newOpts).Elem()
1588 diffOpts = []option{}
1589 skipTKeys = len(oldOpts.TrustedOperators) > 0 && len(oldOpts.TrustedKeys) > 0
1590
1591 // Need to keep track of whether JS is being disabled
1592 // to prevent changing limits at runtime.
1593 jsEnabled = s.JetStreamEnabled()
1594 disableJS bool
1595 jsMemLimitsChanged bool
1596 jsFileLimitsChanged bool
1597 jsStoreDirChanged bool
1598 jsLimitsUpdate *jetStreamLimitsOption
1599 )
1600 for i := 0; i < oldConfig.NumField(); i++ {
1601 field := oldConfig.Type().Field(i)
1602 // field.PkgPath is empty for exported fields, and is not for unexported ones.
1603 // We skip the unexported fields.
1604 if field.PkgPath != _EMPTY_ {
1605 continue
1606 }
1607 optName := strings.ToLower(field.Name)
1608 if skipTKeys && optName == "trustedkeys" {
1609 // TrustedOperators and TrustedKeys change is not supported. During options
1610 // validation, if they are both specified, a conflict error is returned.
1611 // If only TrustedOperators is specified, the TrustedKeys is filled with
1612 // the operators' signing keys. So here, if we detect that the current
1613 // options have operators, we don't do the trusted keys comparison, so
1614 // we can fail with the "not supported for TrustedOperators" config reload
1615 // error instead of TrustedKeys (that the user would not have set).
1616 continue
1617 }
1618 var (
1619 oldValue = oldConfig.Field(i).Interface()
1620 newValue = newConfig.Field(i).Interface()
1621 )
1622 if err := imposeOrder(oldValue); err != nil {
1623 return nil, err
1624 }
1625 if err := imposeOrder(newValue); err != nil {
1626 return nil, err
1627 }
1628
1629 // accounts and users (referencing accounts) will always differ as accounts
1630 // contain internal state, say locks etc..., so we don't bother here.
1631 // This also avoids races with atomic stats counters
1632 if optName != "accounts" && optName != "users" {
1633 if changed := !reflect.DeepEqual(oldValue, newValue); !changed {
1634 // Check to make sure we are running JetStream if we think we should be.
1635 if optName == "jetstream" && newValue.(bool) {
1636 if !jsEnabled {
1637 diffOpts = append(diffOpts, &jetStreamOption{newValue: true})
1638 }
1639 }
1640 continue
1641 }
1642 }
1643 switch optName {
1644 case "traceverbose":
1645 diffOpts = append(diffOpts, &traceVerboseOption{newValue: newValue.(bool)})
1646 case "traceheaders":
1647 diffOpts = append(diffOpts, &traceHeadersOption{newValue: newValue.(bool)})
1648 case "trace":
1649 diffOpts = append(diffOpts, &traceOption{newValue: newValue.(bool)})
1650 case "debug":
1651 diffOpts = append(diffOpts, &debugOption{newValue: newValue.(bool)})
1652 case "logtime":
1653 diffOpts = append(diffOpts, &logtimeOption{newValue: newValue.(bool)})
1654 case "logtimeutc":
1655 diffOpts = append(diffOpts, &logtimeUTCOption{newValue: newValue.(bool)})
1656 case "logfile":
1657 diffOpts = append(diffOpts, &logfileOption{newValue: newValue.(string)})
1658 case "syslog":
1659 diffOpts = append(diffOpts, &syslogOption{newValue: newValue.(bool)})
1660 case "remotesyslog":
1661 diffOpts = append(diffOpts, &remoteSyslogOption{newValue: newValue.(string)})
1662 case "tlsconfig":
1663 diffOpts = append(diffOpts, &tlsOption{newValue: newValue.(*tls.Config)})
1664 case "tlstimeout":
1665 diffOpts = append(diffOpts, &tlsTimeoutOption{newValue: newValue.(float64)})
1666 case "tlspinnedcerts":
1667 diffOpts = append(diffOpts, &tlsPinnedCertOption{newValue: newValue.(PinnedCertSet)})
1668 case "tlshandshakefirst":
1669 diffOpts = append(diffOpts, &tlsHandshakeFirst{newValue: newValue.(bool)})
1670 case "tlshandshakefirstfallback":
1671 diffOpts = append(diffOpts, &tlsHandshakeFirstFallback{newValue: newValue.(time.Duration)})
1672 case "username":
1673 diffOpts = append(diffOpts, &usernameOption{})
1674 case "password":
1675 diffOpts = append(diffOpts, &passwordOption{})
1676 case "tags":
1677 diffOpts = append(diffOpts, &tagsOption{})
1678 case "metadata":
1679 diffOpts = append(diffOpts, &metadataOption{})
1680 case "authorization":
1681 diffOpts = append(diffOpts, &authorizationOption{})
1682 case "authtimeout":
1683 diffOpts = append(diffOpts, &authTimeoutOption{newValue: newValue.(float64)})
1684 case "users":
1685 diffOpts = append(diffOpts, &usersOption{})
1686 case "nkeys":
1687 diffOpts = append(diffOpts, &nkeysOption{})
1688 case "cluster":
1689 newClusterOpts := newValue.(ClusterOpts)
1690 oldClusterOpts := oldValue.(ClusterOpts)
1691 if err := validateClusterOpts(oldClusterOpts, newClusterOpts); err != nil {
1692 return nil, err
1693 }
1694 co := &clusterOption{
1695 newValue: newClusterOpts,
1696 permsChanged: !reflect.DeepEqual(newClusterOpts.Permissions, oldClusterOpts.Permissions),
1697 compressChanged: !oldClusterOpts.Compression.equals(&newClusterOpts.Compression),
1698 }
1699 co.diffPoolAndAccounts(&oldClusterOpts)
1700 // If there are added accounts, first make sure that we can look them up.
1701 // If we can't let's fail the reload.
1702 for _, acc := range co.accsAdded {
1703 if _, err := s.LookupAccount(acc); err != nil {
1704 return nil, fmt.Errorf("unable to add account %q to the list of dedicated routes: %v", acc, err)
1705 }
1706 }
1707 // If pool_size has been set to negative (but was not before), then let's
1708 // add the system account to the list of removed accounts (we don't have
1709 // to check if already there, duplicates are ok in that case).
1710 if newClusterOpts.PoolSize < 0 && oldClusterOpts.PoolSize >= 0 {
1711 if sys := s.SystemAccount(); sys != nil {
1712 co.accsRemoved = append(co.accsRemoved, sys.GetName())
1713 }
1714 }
1715 diffOpts = append(diffOpts, co)
1716 case "routes":
1717 add, remove := diffRoutes(oldValue.([]*url.URL), newValue.([]*url.URL))
1718 diffOpts = append(diffOpts, &routesOption{add: add, remove: remove})
1719 case "maxconn":
1720 diffOpts = append(diffOpts, &maxConnOption{newValue: newValue.(int)})
1721 case "pidfile":
1722 diffOpts = append(diffOpts, &pidFileOption{newValue: newValue.(string)})
1723 case "portsfiledir":
1724 diffOpts = append(diffOpts, &portsFileDirOption{newValue: newValue.(string), oldValue: oldValue.(string)})
1725 case "maxcontrolline":
1726 diffOpts = append(diffOpts, &maxControlLineOption{newValue: newValue.(int32)})
1727 case "maxpayload":
1728 diffOpts = append(diffOpts, &maxPayloadOption{newValue: newValue.(int32)})
1729 case "pinginterval":
1730 diffOpts = append(diffOpts, &pingIntervalOption{newValue: newValue.(time.Duration)})
1731 case "maxpingsout":
1732 diffOpts = append(diffOpts, &maxPingsOutOption{newValue: newValue.(int)})
1733 case "writedeadline":
1734 diffOpts = append(diffOpts, &writeDeadlineOption{newValue: newValue.(time.Duration)})
1735 case "clientadvertise":
1736 cliAdv := newValue.(string)
1737 if cliAdv != "" {
1738 // Validate ClientAdvertise syntax
1739 if _, _, err := parseHostPort(cliAdv, 0); err != nil {
1740 return nil, fmt.Errorf("invalid ClientAdvertise value of %s, err=%v", cliAdv, err)
1741 }
1742 }
1743 diffOpts = append(diffOpts, &clientAdvertiseOption{newValue: cliAdv})
1744 case "accounts":
1745 diffOpts = append(diffOpts, &accountsOption{})
1746 case "resolver", "accountresolver", "accountsresolver":
1747 // We can't move from no resolver to one. So check for that.
1748 if (oldValue == nil && newValue != nil) ||
1749 (oldValue != nil && newValue == nil) {
1750 return nil, fmt.Errorf("config reload does not support moving to or from an account resolver")
1751 }
1752 diffOpts = append(diffOpts, &accountsOption{})
1753 case "accountresolvertlsconfig":
1754 diffOpts = append(diffOpts, &accountsOption{})
1755 case "gateway":
1756 // Not supported for now, but report warning if configuration of gateway
1757 // is actually changed so that user knows that it won't take effect.
1758
1759 // Any deep-equal is likely to fail for when there is a TLSConfig. so
1760 // remove for the test.
1761 tmpOld := oldValue.(GatewayOpts)
1762 tmpNew := newValue.(GatewayOpts)
1763 tmpOld.TLSConfig = nil
1764 tmpNew.TLSConfig = nil
1765 tmpOld.tlsConfigOpts = nil
1766 tmpNew.tlsConfigOpts = nil
1767
1768 // Allow TLSPinnedCerts through reload, existing connections
1769 // are checked in recheckPinnedCerts
1770 tmpOld.TLSPinnedCerts = nil
1771 tmpNew.TLSPinnedCerts = nil
1772
1773 // Need to do the same for remote gateways' TLS configs.
1774 // But we can't just set remotes' TLSConfig to nil otherwise this
1775 // would lose the real TLS configuration.
1776 tmpOld.Gateways = copyRemoteGWConfigsWithoutTLSConfig(tmpOld.Gateways)
1777 tmpNew.Gateways = copyRemoteGWConfigsWithoutTLSConfig(tmpNew.Gateways)
1778
1779 // If there is really a change prevents reload.
1780 if !reflect.DeepEqual(tmpOld, tmpNew) {
1781 // See TODO(ik) note below about printing old/new values.
1782 return nil, fmt.Errorf("config reload not supported for %s: old=%v, new=%v",
1783 field.Name, oldValue, newValue)
1784 }
1785 case "leafnode":
1786 tmpOld := oldValue.(LeafNodeOpts)
1787 tmpNew := newValue.(LeafNodeOpts)
1788
1789 lno, err := getLeafNodeOptionsChanges(s, &tmpOld, &tmpNew)
1790 // If there was an unsupported change, we will get an error with the name
1791 // of the (first) field and its old and new value.
1792 if err != nil {
1793 return nil, fmt.Errorf("config reload not supported for %s: %v", field.Name, err)
1794 }
1795 // If there was an actual change...
1796 if lno != nil {
1797 diffOpts = append(diffOpts, lno)
1798 }
1799 case "jetstream":
1800 new := newValue.(bool)
1801 old := oldValue.(bool)
1802 if new != old {
1803 diffOpts = append(diffOpts, &jetStreamOption{newValue: new})
1804 }
1805
1806 // Mark whether JS will be disabled.
1807 disableJS = !new
1808 case "storedir":
1809 new := newValue.(string)
1810 old := oldValue.(string)
1811 modified := new != old
1812
1813 // Check whether JS is being disabled and/or storage dir attempted to change.
1814 if jsEnabled && modified {
1815 if new == _EMPTY_ {
1816 // This means that either JS is being disabled or it is using an temp dir.
1817 // Allow the change but error in case JS was not disabled.
1818 jsStoreDirChanged = true
1819 } else {
1820 return nil, fmt.Errorf("config reload not supported for jetstream storage directory")
1821 }
1822 }
1823 case "jetstreammaxmemory", "jetstreammaxstore":
1824 old := oldValue.(int64)
1825 new := newValue.(int64)
1826
1827 // Check whether JS is being disabled and/or limits are being changed.
1828 var (
1829 modified = new != old
1830 fromUnset = old == -1
1831 fromSet = !fromUnset
1832 toUnset = new == -1
1833 toSet = !toUnset
1834 increased = fromSet && toSet && new > old
1835 )
1836 if jsEnabled && modified {
1837 // Cannot change limits from dynamic storage at runtime.
1838 switch {
1839 case increased:
1840 // Allowed to increase, but not decrease.
1841 if jsLimitsUpdate == nil {
1842 jsLimitsUpdate = &jetStreamLimitsOption{}
1843 diffOpts = append(diffOpts, jsLimitsUpdate)
1844 }
1845 if optName == "jetstreammaxmemory" {
1846 jsLimitsUpdate.newMaxMemory = new
1847 } else {
1848 jsLimitsUpdate.newMaxStore = new
1849 }
1850 case fromSet && toUnset:
1851 // Limits changed but it may mean that JS is being disabled,
1852 // keep track of the change and error in case it is not.
1853 if optName == "jetstreammaxmemory" {
1854 jsMemLimitsChanged = true
1855 } else {
1856 jsFileLimitsChanged = true
1857 }
1858 case fromUnset && toSet:
1859 // Prevent changing from dynamic max memory / file at runtime.
1860 return nil, fmt.Errorf("config reload not supported for jetstream dynamic max memory and store")
1861 default:
1862 return nil, fmt.Errorf("config reload not supported for decreasing jetstream max memory and store")
1863 }
1864 }
1865 case "jetstreammetacompact", "jetstreammetacompactsize", "jetstreammetacompactsync":
1866 // Allowed at runtime but monitorCluster looks at s.opts directly, so no further work needed here.
1867 case "jetstreamconcurrentios":
1868 // Not reloadable at runtime; preserve the current value while JetStream is disabled,
1869 // e.g. the entire jetstream{} block was deleted.
1870 if newOpts.JetStream {
1871 return nil, fmt.Errorf("config reload not supported for %s: old=%v, new=%v",
1872 field.Name, oldValue, newValue)
1873 } else {
1874 newOpts.JetStreamConcurrentIOs = oldValue.(int)
1875 }
1876 case "websocket":
1877 // Similar to gateways
1878 tmpOld := oldValue.(WebsocketOpts)
1879 tmpNew := newValue.(WebsocketOpts)
1880 tmpOld.TLSConfig, tmpOld.tlsConfigOpts = nil, nil
1881 tmpNew.TLSConfig, tmpNew.tlsConfigOpts = nil, nil
1882 // If there is really a change prevents reload.
1883 if !reflect.DeepEqual(tmpOld, tmpNew) {
1884 // See TODO(ik) note below about printing old/new values.
1885 return nil, fmt.Errorf("config reload not supported for %s: old=%v, new=%v",
1886 field.Name, oldValue, newValue)
1887 }
1888 case "mqtt":
1889 diffOpts = append(diffOpts, &mqttAckWaitReload{newValue: newValue.(MQTTOpts).AckWait})
1890 diffOpts = append(diffOpts, &mqttMaxAckPendingReload{newValue: newValue.(MQTTOpts).MaxAckPending})
1891 diffOpts = append(diffOpts, &mqttStreamReplicasReload{newValue: newValue.(MQTTOpts).StreamReplicas})
1892 diffOpts = append(diffOpts, &mqttConsumerReplicasReload{newValue: newValue.(MQTTOpts).ConsumerReplicas})
1893 diffOpts = append(diffOpts, &mqttConsumerMemoryStorageReload{newValue: newValue.(MQTTOpts).ConsumerMemoryStorage})
1894 diffOpts = append(diffOpts, &mqttInactiveThresholdReload{newValue: newValue.(MQTTOpts).ConsumerInactiveThreshold})
1895
1896 // Nil out/set to 0 the options that we allow to be reloaded so that
1897 // we only fail reload if some that we don't support are changed.
1898 tmpOld := oldValue.(MQTTOpts)
1899 tmpNew := newValue.(MQTTOpts)
1900 tmpOld.TLSConfig, tmpOld.tlsConfigOpts, tmpOld.AckWait, tmpOld.MaxAckPending, tmpOld.StreamReplicas, tmpOld.ConsumerReplicas, tmpOld.ConsumerMemoryStorage = nil, nil, 0, 0, 0, 0, false
1901 tmpOld.ConsumerInactiveThreshold = 0
1902 tmpNew.TLSConfig, tmpNew.tlsConfigOpts, tmpNew.AckWait, tmpNew.MaxAckPending, tmpNew.StreamReplicas, tmpNew.ConsumerReplicas, tmpNew.ConsumerMemoryStorage = nil, nil, 0, 0, 0, 0, false
1903 tmpNew.ConsumerInactiveThreshold = 0
1904
1905 if !reflect.DeepEqual(tmpOld, tmpNew) {
1906 // See TODO(ik) note below about printing old/new values.
1907 return nil, fmt.Errorf("config reload not supported for %s: old=%v, new=%v",
1908 field.Name, oldValue, newValue)
1909 }
1910 tmpNew.AckWait = newValue.(MQTTOpts).AckWait
1911 tmpNew.MaxAckPending = newValue.(MQTTOpts).MaxAckPending
1912 tmpNew.StreamReplicas = newValue.(MQTTOpts).StreamReplicas
1913 tmpNew.ConsumerReplicas = newValue.(MQTTOpts).ConsumerReplicas
1914 tmpNew.ConsumerMemoryStorage = newValue.(MQTTOpts).ConsumerMemoryStorage
1915 tmpNew.ConsumerInactiveThreshold = newValue.(MQTTOpts).ConsumerInactiveThreshold
1916 case "connecterrorreports":
1917 diffOpts = append(diffOpts, &connectErrorReports{newValue: newValue.(int)})
1918 case "reconnecterrorreports":
1919 diffOpts = append(diffOpts, &reconnectErrorReports{newValue: newValue.(int)})
1920 case "nolog", "nosigs":
1921 // Ignore NoLog and NoSigs options since they are not parsed and only used in
1922 // testing.
1923 continue
1924 case "disableshortfirstping":
1925 newOpts.DisableShortFirstPing = oldValue.(bool)
1926 continue
1927 case "maxtracedmsglen":
1928 diffOpts = append(diffOpts, &maxTracedMsgLenOption{newValue: newValue.(int)})
1929 case "port":
1930 // check to see if newValue == 0 and continue if so.
1931 if newValue == 0 {
1932 // ignore RANDOM_PORT
1933 continue
1934 }
1935 fallthrough
1936 case "noauthuser":
1937 if oldValue != _EMPTY_ && newValue == _EMPTY_ {
1938 for _, user := range newOpts.Users {
1939 if user.Username == oldValue {
1940 return nil, fmt.Errorf("config reload not supported for %s: old=%v, new=%v",
1941 field.Name, oldValue, newValue)
1942 }
1943 }
1944 } else {
1945 return nil, fmt.Errorf("config reload not supported for %s: old=%v, new=%v",
1946 field.Name, oldValue, newValue)
1947 }
1948 case "defaultsentinel":
1949 diffOpts = append(diffOpts, &defaultSentinelOption{newValue: newValue.(string)})
1950 case "systemaccount":
1951 if oldValue != DEFAULT_SYSTEM_ACCOUNT || newValue != _EMPTY_ {
1952 return nil, fmt.Errorf("config reload not supported for %s: old=%v, new=%v",
1953 field.Name, oldValue, newValue)
1954 }
1955 case "ocspconfig":
1956 diffOpts = append(diffOpts, &ocspOption{newValue: newValue.(*OCSPConfig)})
1957 case "ocspcacheconfig":
1958 diffOpts = append(diffOpts, &ocspResponseCacheOption{newValue: newValue.(*OCSPResponseCacheConfig)})
1959 case "profblockrate":
1960 new := newValue.(int)
1961 old := oldValue.(int)
1962 if new != old {
1963 diffOpts = append(diffOpts, &profBlockRateReload{newValue: new})
1964 }
1965 case "configdigest":
1966 // skip changes in config digest, this is handled already while
1967 // processing the config.
1968 continue
1969 case "nofastproducerstall":
1970 diffOpts = append(diffOpts, &noFastProdStallReload{noStall: newValue.(bool)})
1971 case "proxies":
1972 new := newValue.(*ProxiesConfig)
1973 old := oldValue.(*ProxiesConfig)
1974 if add, del := diffProxiesTrustedKeys(old.Trusted, new.Trusted); len(add) > 0 || len(del) > 0 {
1975 diffOpts = append(diffOpts, &proxiesReload{add: add, del: del})
1976 }
1977 default:
1978 // TODO(ik): Implement String() on those options to have a nice print.
1979 // %v is difficult to figure what's what, %+v print private fields and
1980 // would print passwords. Tried json.Marshal but it is too verbose for
1981 // the URL array.
1982
1983 // Bail out if attempting to reload any unsupported options.
1984 return nil, fmt.Errorf("config reload not supported for %s: old=%v, new=%v",
1985 field.Name, oldValue, newValue)
1986 }
1987 }
1988
1989 // If not disabling JS but limits have changed then it is an error.
1990 if !disableJS {
1991 if jsMemLimitsChanged || jsFileLimitsChanged {
1992 return nil, fmt.Errorf("config reload not supported for jetstream max memory and max store")
1993 }
1994 if jsStoreDirChanged {
1995 return nil, fmt.Errorf("config reload not supported for jetstream storage dir")
1996 }
1997 }
1998
1999 return diffOpts, nil
2000 }
2001
2002 func copyRemoteGWConfigsWithoutTLSConfig(current []*RemoteGatewayOpts) []*RemoteGatewayOpts {
2003 l := len(current)
2004 if l == 0 {
2005 return nil
2006 }
2007 rgws := make([]*RemoteGatewayOpts, 0, l)
2008 for _, rcfg := range current {
2009 cp := *rcfg
2010 cp.TLSConfig = nil
2011 cp.tlsConfigOpts = nil
2012 rgws = append(rgws, &cp)
2013 }
2014 return rgws
2015 }
2016
2017 func (s *Server) applyOptions(ctx *reloadContext, opts []option) {
2018 var (
2019 reloadLogging = false
2020 reloadAuth = false
2021 reloadClusterPerms = false
2022 reloadClientTrcLvl = false
2023 reloadJetstream = false
2024 jsEnabled = false
2025 isStatszChange = false
2026 co *clusterOption
2027 )
2028 for _, opt := range opts {
2029 opt.Apply(s)
2030 if opt.IsLoggingChange() {
2031 reloadLogging = true
2032 }
2033 if opt.IsTraceLevelChange() {
2034 reloadClientTrcLvl = true
2035 }
2036 if opt.IsAuthChange() {
2037 reloadAuth = true
2038 }
2039 if opt.IsClusterPoolSizeOrAccountsChange() {
2040 co = opt.(*clusterOption)
2041 }
2042 if opt.IsClusterPermsChange() {
2043 reloadClusterPerms = true
2044 }
2045 if opt.IsJetStreamChange() {
2046 reloadJetstream = true
2047 jsEnabled = opt.(*jetStreamOption).newValue
2048 }
2049 if opt.IsStatszChange() {
2050 isStatszChange = true
2051 }
2052 }
2053
2054 if reloadLogging {
2055 s.ConfigureLogger()
2056 }
2057 if reloadClientTrcLvl {
2058 s.reloadClientTraceLevel()
2059 }
2060 if reloadAuth {
2061 s.reloadAuthorization()
2062 }
2063 if reloadClusterPerms {
2064 s.reloadClusterPermissions(ctx.oldClusterPerms)
2065 }
2066 newOpts := s.getOpts()
2067 // If we need to reload cluster pool/per-account, then co will be not nil
2068 if co != nil {
2069 s.reloadClusterPoolAndAccounts(co, newOpts)
2070 }
2071 if reloadJetstream {
2072 if !jsEnabled {
2073 s.DisableJetStream()
2074 } else if !s.JetStreamEnabled() {
2075 if err := s.restartJetStream(); err != nil {
2076 s.Warnf("Can't start JetStream: %v", err)
2077 }
2078 }
2079 // Make sure to reset the internal loop's version of JS.
2080 s.resetInternalLoopInfo()
2081 }
2082 if isStatszChange {
2083 s.sendStatszUpdate()
2084 }
2085
2086 // For remote gateways, make sure that their TLS configuration
2087 // is updated (since the config is "captured" early and changes would otherwise
2088 // not be visible).
2089 if s.gateway.enabled {
2090 s.gateway.updateRemotesTLSConfig(newOpts)
2091 }
2092
2093 // Always restart OCSP monitoring on reload.
2094 if err := s.reloadOCSP(); err != nil {
2095 s.Warnf("Can't restart OCSP features: %v", err)
2096 }
2097 var cd string
2098 if newOpts.configDigest != "" {
2099 cd = fmt.Sprintf("(%s)", newOpts.configDigest)
2100 }
2101 s.Noticef("Reloaded server configuration %s", cd)
2102 }
2103
2104 // This will send a reset to the internal send loop.
2105 func (s *Server) resetInternalLoopInfo() {
2106 var resetCh chan struct{}
2107 s.mu.Lock()
2108 if s.sys != nil {
2109 // can't hold the lock as go routine reading it may be waiting for lock as well
2110 resetCh = s.sys.resetCh
2111 }
2112 s.mu.Unlock()
2113
2114 if resetCh != nil {
2115 select {
2116 case resetCh <- struct{}{}:
2117 case <-s.quitCh:
2118 }
2119 }
2120 }
2121
2122 // Update all cached debug and trace settings for every client
2123 func (s *Server) reloadClientTraceLevel() {
2124 opts := s.getOpts()
2125
2126 if opts.NoLog {
2127 return
2128 }
2129
2130 // Create a list of all clients.
2131 // Update their trace level when not holding server or gateway lock
2132
2133 s.mu.Lock()
2134 clientCnt := 1 + len(s.clients) + len(s.grTmpClients) + s.numRoutes() + len(s.leafs)
2135 s.mu.Unlock()
2136
2137 s.gateway.RLock()
2138 clientCnt += len(s.gateway.in) + len(s.gateway.outo)
2139 s.gateway.RUnlock()
2140
2141 clients := make([]*client, 0, clientCnt)
2142
2143 s.mu.Lock()
2144 if s.eventsEnabled() {
2145 clients = append(clients, s.sys.client)
2146 }
2147
2148 cMaps := []map[uint64]*client{s.clients, s.grTmpClients, s.leafs}
2149 for _, m := range cMaps {
2150 for _, c := range m {
2151 clients = append(clients, c)
2152 }
2153 }
2154 s.forEachRoute(func(c *client) {
2155 clients = append(clients, c)
2156 })
2157 s.mu.Unlock()
2158
2159 s.gateway.RLock()
2160 for _, c := range s.gateway.in {
2161 clients = append(clients, c)
2162 }
2163 clients = append(clients, s.gateway.outo...)
2164 s.gateway.RUnlock()
2165
2166 for _, c := range clients {
2167 // client.trace is commonly read while holding the lock
2168 c.mu.Lock()
2169 c.setTraceLevel()
2170 c.mu.Unlock()
2171 }
2172 }
2173
2174 // reloadAuthorization reconfigures the server authorization settings,
2175 // disconnects any clients who are no longer authorized, and removes any
2176 // unauthorized subscriptions.
2177 func (s *Server) reloadAuthorization() {
2178 // This map will contain the names of accounts that have their streams
2179 // import configuration changed.
2180 var awcsti map[string]struct{}
2181 checkJetStream := false
2182 opts := s.getOpts()
2183 s.mu.Lock()
2184
2185 deletedAccounts := make(map[string]*Account)
2186
2187 // This can not be changed for now so ok to check server's trustedKeys unlocked.
2188 // If plain configured accounts, process here.
2189 if s.trustedKeys == nil {
2190 // Make a map of the configured account names so we figure out the accounts
2191 // that should be removed later on.
2192 configAccs := make(map[string]struct{}, len(opts.Accounts))
2193 for _, acc := range opts.Accounts {
2194 configAccs[acc.GetName()] = struct{}{}
2195 }
2196 // Now range over existing accounts and keep track of the ones deleted
2197 // so some cleanup can be made after releasing the server lock.
2198 s.accounts.Range(func(k, v any) bool {
2199 an, acc := k.(string), v.(*Account)
2200 // Exclude default and system account from this test since those
2201 // may not actually be in opts.Accounts.
2202 if an == DEFAULT_GLOBAL_ACCOUNT || an == DEFAULT_SYSTEM_ACCOUNT {
2203 return true
2204 }
2205 // Check check if existing account is still in opts.Accounts.
2206 if _, ok := configAccs[an]; !ok {
2207 deletedAccounts[an] = acc
2208 s.accounts.Delete(k)
2209 }
2210 return true
2211 })
2212 // This will update existing and add new ones.
2213 awcsti, _ = s.configureAccounts(true)
2214 s.configureAuthorization()
2215 // Double check any JetStream configs.
2216 checkJetStream = s.getJetStream() != nil
2217 } else if opts.AccountResolver != nil {
2218 s.configureResolver()
2219 if _, ok := s.accResolver.(*MemAccResolver); ok {
2220 // Check preloads so we can issue warnings etc if needed.
2221 s.checkResolvePreloads()
2222 // With a memory resolver we want to do something similar to configured accounts.
2223 // We will walk the accounts and delete them if they are no longer present via fetch.
2224 // If they are present we will force a claim update to process changes.
2225 s.accounts.Range(func(k, v any) bool {
2226 acc := v.(*Account)
2227 // Skip global account.
2228 if acc == s.gacc {
2229 return true
2230 }
2231 accName := acc.GetName()
2232 // Release server lock for following actions
2233 s.mu.Unlock()
2234 accClaims, claimJWT, _ := s.fetchAccountClaims(accName)
2235 if accClaims != nil {
2236 if err := s.updateAccountWithClaimJWT(acc, claimJWT); err != nil {
2237 s.Noticef("Reloaded: deleting account [bad claims]: %q", accName)
2238 s.accounts.Delete(k)
2239 }
2240 } else {
2241 s.Noticef("Reloaded: deleting account [removed]: %q", accName)
2242 s.accounts.Delete(k)
2243 }
2244 // Regrab server lock.
2245 s.mu.Lock()
2246 return true
2247 })
2248 }
2249 }
2250
2251 var (
2252 cclientsa [64]*client
2253 cclients = cclientsa[:0]
2254 clientsa [64]*client
2255 clients = clientsa[:0]
2256 routesa [64]*client
2257 routes = routesa[:0]
2258 )
2259
2260 // Gather clients that changed accounts. We will close them and they
2261 // will reconnect, doing the right thing.
2262 for _, client := range s.clients {
2263 if s.clientHasMovedToDifferentAccount(client) {
2264 cclients = append(cclients, client)
2265 } else {
2266 clients = append(clients, client)
2267 }
2268 }
2269 s.forEachRoute(func(route *client) {
2270 routes = append(routes, route)
2271 })
2272 // Check here for any system/internal clients which will not be in the servers map of normal clients.
2273 if s.sys != nil && s.sys.account != nil && !opts.NoSystemAccount {
2274 s.accounts.Store(s.sys.account.Name, s.sys.account)
2275 }
2276
2277 s.accounts.Range(func(k, v any) bool {
2278 acc := v.(*Account)
2279 acc.mu.RLock()
2280 // Check for sysclients accounting, ignore the system account.
2281 if acc.sysclients > 0 && (s.sys == nil || s.sys.account != acc) {
2282 for c := range acc.clients {
2283 if c.kind != CLIENT && c.kind != LEAF {
2284 clients = append(clients, c)
2285 }
2286 }
2287 }
2288 acc.mu.RUnlock()
2289 return true
2290 })
2291
2292 var resetCh chan struct{}
2293 if s.sys != nil {
2294 // can't hold the lock as go routine reading it may be waiting for lock as well
2295 resetCh = s.sys.resetCh
2296 }
2297 s.mu.Unlock()
2298
2299 // Clear some timers and remove service import subs for deleted accounts.
2300 for _, acc := range deletedAccounts {
2301 acc.mu.Lock()
2302 clearTimer(&acc.etmr)
2303 clearTimer(&acc.ctmr)
2304 for _, se := range acc.exports.services {
2305 se.clearResponseThresholdTimer()
2306 }
2307 acc.mu.Unlock()
2308 acc.removeAllServiceImportSubs()
2309 }
2310
2311 if resetCh != nil {
2312 select {
2313 case resetCh <- struct{}{}:
2314 case <-s.quitCh:
2315 }
2316 }
2317
2318 // Close clients that have moved accounts
2319 for _, client := range cclients {
2320 client.closeConnection(ClientClosed)
2321 }
2322
2323 for _, c := range clients {
2324 // Disconnect any unauthorized clients.
2325 // Ignore internal clients.
2326 if (c.kind == CLIENT || c.kind == LEAF) && !s.isClientAuthorized(c) {
2327 c.authViolation()
2328 continue
2329 }
2330 // Check to make sure account is correct.
2331 c.swapAccountAfterReload()
2332 // Remove any unauthorized subscriptions and check for account imports.
2333 c.processSubsOnConfigReload(awcsti)
2334 }
2335
2336 for _, route := range routes {
2337 // Disconnect any unauthorized routes.
2338 // Do this only for routes that were accepted, not initiated
2339 // because in the later case, we don't have the user name/password
2340 // of the remote server.
2341 if !route.isSolicitedRoute() && !s.isRouterAuthorized(route) {
2342 route.setNoReconnect()
2343 route.authViolation()
2344 }
2345 }
2346
2347 if res := s.AccountResolver(); res != nil {
2348 res.Reload()
2349 }
2350
2351 // We will double check all JetStream configs on a reload.
2352 if checkJetStream {
2353 if err := s.enableJetStreamAccounts(); err != nil {
2354 s.Errorf(err.Error())
2355 }
2356 }
2357
2358 // Check that publish retained messages sources are still allowed to publish.
2359 // Do this after dealing with JetStream.
2360 s.mqttCheckPubRetainedPerms()
2361 }
2362
2363 // Returns true if given client current account has changed (or user
2364 // no longer exist) in the new config, false if the user did not
2365 // change accounts.
2366 // Server lock is held on entry.
2367 func (s *Server) clientHasMovedToDifferentAccount(c *client) bool {
2368 var (
2369 nu *NkeyUser
2370 u *User
2371 )
2372 c.mu.Lock()
2373 defer c.mu.Unlock()
2374 if c.opts.Nkey != _EMPTY_ {
2375 if s.nkeys != nil {
2376 nu = s.nkeys[c.opts.Nkey]
2377 }
2378 } else if c.opts.Username != _EMPTY_ {
2379 if s.users != nil {
2380 u = s.users[c.opts.Username]
2381 }
2382 } else {
2383 return false
2384 }
2385 // Get the current account name
2386 var curAccName string
2387 if c.acc != nil {
2388 curAccName = c.acc.Name
2389 }
2390 if nu != nil && nu.Account != nil {
2391 return curAccName != nu.Account.Name
2392 } else if u != nil && u.Account != nil {
2393 return curAccName != u.Account.Name
2394 }
2395 // user/nkey no longer exists.
2396 return true
2397 }
2398
2399 // reloadClusterPermissions reconfigures the cluster's permssions
2400 // and set the permissions to all existing routes, sending an
2401 // update INFO protocol so that remote can resend their local
2402 // subs if needed, and sending local subs matching cluster's
2403 // import subjects.
2404 func (s *Server) reloadClusterPermissions(oldPerms *RoutePermissions) {
2405 s.mu.Lock()
2406 newPerms := s.getOpts().Cluster.Permissions
2407 routes := make(map[uint64]*client, s.numRoutes())
2408 // Get all connected routes
2409 s.forEachRoute(func(route *client) {
2410 route.mu.Lock()
2411 routes[route.cid] = route
2412 route.mu.Unlock()
2413 })
2414 // If new permissions is nil, then clear routeInfo import/export
2415 if newPerms == nil {
2416 s.routeInfo.Import = nil
2417 s.routeInfo.Export = nil
2418 } else {
2419 s.routeInfo.Import = newPerms.Import
2420 s.routeInfo.Export = newPerms.Export
2421 }
2422 infoJSON := generateInfoJSON(&s.routeInfo)
2423 s.mu.Unlock()
2424
2425 // Close connections for routes that don't understand async INFO.
2426 for _, route := range routes {
2427 route.mu.Lock()
2428 close := route.opts.Protocol < RouteProtoInfo
2429 cid := route.cid
2430 route.mu.Unlock()
2431 if close {
2432 route.closeConnection(RouteRemoved)
2433 delete(routes, cid)
2434 }
2435 }
2436
2437 // If there are no route left, we are done
2438 if len(routes) == 0 {
2439 return
2440 }
2441
2442 // Fake clients to test cluster permissions
2443 oldPermsTester := &client{}
2444 oldPermsTester.setRoutePermissions(oldPerms)
2445 newPermsTester := &client{}
2446 newPermsTester.setRoutePermissions(newPerms)
2447
2448 var (
2449 _localSubs [4096]*subscription
2450 subsNeedSUB = map[*client][]*subscription{}
2451 subsNeedUNSUB = map[*client][]*subscription{}
2452 deleteRoutedSubs []*subscription
2453 )
2454
2455 getRouteForAccount := func(accName string, poolIdx int) *client {
2456 for _, r := range routes {
2457 r.mu.Lock()
2458 ok := (poolIdx >= 0 && poolIdx == r.route.poolIdx) || (string(r.route.accName) == accName) || r.route.noPool
2459 r.mu.Unlock()
2460 if ok {
2461 return r
2462 }
2463 }
2464 return nil
2465 }
2466
2467 // First set the new permissions on all routes.
2468 for _, route := range routes {
2469 route.mu.Lock()
2470 route.setRoutePermissions(newPerms)
2471 route.mu.Unlock()
2472 }
2473
2474 // Then, go over all accounts and gather local subscriptions that need to be
2475 // sent over as SUB or removed as UNSUB, and routed subscriptions that need
2476 // to be dropped due to export permissions.
2477 s.accounts.Range(func(_, v any) bool {
2478 acc := v.(*Account)
2479 acc.mu.RLock()
2480 accName, sl, poolIdx := acc.Name, acc.sl, acc.routePoolIdx
2481 acc.mu.RUnlock()
2482 // Get the route handling this account. If no route or sublist, bail out.
2483 route := getRouteForAccount(accName, poolIdx)
2484 if route == nil || sl == nil {
2485 return true
2486 }
2487 localSubs := _localSubs[:0]
2488 sl.localSubs(&localSubs, false)
2489
2490 // Go through all local subscriptions
2491 for _, sub := range localSubs {
2492 // Get all subs that can now be imported
2493 subj := string(sub.subject)
2494 couldImportThen := oldPermsTester.canImport(subj)
2495 canImportNow := newPermsTester.canImport(subj)
2496 if canImportNow {
2497 // If we could not before, then will need to send a SUB protocol.
2498 if !couldImportThen {
2499 subsNeedSUB[route] = append(subsNeedSUB[route], sub)
2500 }
2501 } else if couldImportThen {
2502 // We were previously able to import this sub, but now
2503 // we can't so we need to send an UNSUB protocol
2504 subsNeedUNSUB[route] = append(subsNeedUNSUB[route], sub)
2505 }
2506 }
2507 deleteRoutedSubs = deleteRoutedSubs[:0]
2508 route.mu.Lock()
2509 pa, _, hasSubType := route.getRoutedSubKeyInfo()
2510 for key, sub := range route.subs {
2511 // If this is not a pinned-account route, we need to get the
2512 // account name from the key to see if we collect this sub.
2513 if !pa {
2514 if an := getAccNameFromRoutedSubKey(sub, key, hasSubType); an != accName {
2515 continue
2516 }
2517 }
2518 // If we can't export, we need to drop the subscriptions that
2519 // we have on behalf of this route.
2520 // Need to make a string cast here since canExport call sl.Match()
2521 subj := string(sub.subject)
2522 if !route.canExport(subj) {
2523 // We can use bytesToString() here.
2524 delete(route.subs, bytesToString(sub.sid))
2525 deleteRoutedSubs = append(deleteRoutedSubs, sub)
2526 }
2527 }
2528 route.mu.Unlock()
2529 // Remove as a batch all the subs that we have removed from each route.
2530 sl.RemoveBatch(deleteRoutedSubs)
2531 return true
2532 })
2533
2534 // Send an update INFO, which will allow remote server to show
2535 // our current route config in monitoring and resend subscriptions
2536 // that we now possibly allow with a change of Export permissions.
2537 for _, route := range routes {
2538 route.mu.Lock()
2539 route.enqueueProto(infoJSON)
2540 // Now send SUB and UNSUB protocols as needed.
2541 if subs, ok := subsNeedSUB[route]; ok && len(subs) > 0 {
2542 route.sendRouteSubProtos(subs, false, nil)
2543 }
2544 if unsubs, ok := subsNeedUNSUB[route]; ok && len(unsubs) > 0 {
2545 route.sendRouteUnSubProtos(unsubs, false, nil)
2546 }
2547 route.mu.Unlock()
2548 }
2549 }
2550
2551 func (s *Server) reloadClusterPoolAndAccounts(co *clusterOption, opts *Options) {
2552 s.mu.Lock()
2553 // Prevent adding new routes until we are ready to do so.
2554 s.routesReject = true
2555 var ch chan struct{}
2556 // Number of per-account route INFO protocols sent that we expect a
2557 // confirmation for. Declared here so the wait below can block on it.
2558 protosSent := 0
2559 // For accounts that have been added to the list of dedicated routes,
2560 // send a protocol to their current assigned routes to allow the
2561 // other side to prepare for the changes.
2562 if len(co.accsAdded) > 0 {
2563 s.accAddedReqID = nuid.Next()
2564 for _, an := range co.accsAdded {
2565 if s.accRoutes == nil {
2566 s.accRoutes = make(map[string]map[string]*client)
2567 }
2568 // In case a config reload was first done on another server,
2569 // we may have already switched this account to a dedicated route.
2570 // But we still want to send the protocol over the routes that
2571 // would have otherwise handled it.
2572 if _, ok := s.accRoutes[an]; !ok {
2573 s.accRoutes[an] = make(map[string]*client)
2574 }
2575 if a, ok := s.accounts.Load(an); ok {
2576 acc := a.(*Account)
2577 acc.mu.Lock()
2578 sl := acc.sl
2579 // Get the current route pool index before calling setRouteInfo.
2580 rpi := acc.routePoolIdx
2581 // Switch to per-account route if not already done.
2582 if rpi >= 0 {
2583 s.setRouteInfo(acc)
2584 } else {
2585 // If it was transitioning, make sure we set it to the state
2586 // that indicates that it has a dedicated route
2587 if rpi == accTransitioningToDedicatedRoute {
2588 acc.routePoolIdx = accDedicatedRoute
2589 }
2590 // Otherwise get the route pool index it would have been before
2591 // the move so we can send the protocol to those routes.
2592 rpi = computeRoutePoolIdx(s.routesPoolSize, acc.Name)
2593 }
2594 acc.mu.Unlock()
2595 // Generate the INFO protocol to send indicating that this account
2596 // is being moved to a dedicated route.
2597 ri := Info{
2598 RoutePoolSize: s.routesPoolSize,
2599 RouteAccount: an,
2600 RouteAccReqID: s.accAddedReqID,
2601 }
2602 proto := generateInfoJSON(&ri)
2603 // Since v2.11.0, we support remotes with a different pool size
2604 // (for rolling upgrades), so we need to use the remote route
2605 // pool index (based on the remote configured pool size) since
2606 // the remote subscriptions will be attached to the route at
2607 // that index, not at our account's route pool index. However,
2608 // we are going to send the protocol through the route that
2609 // handles this account from our pool size perspective (that
2610 // would be the route at index `rpi`).
2611 removeSubsAndSendProto := func(r *client, doSubs, doProto bool) {
2612 r.mu.Lock()
2613 defer r.mu.Unlock()
2614 // Exclude routes to servers that don't support pooling.
2615 if r.route.noPool {
2616 return
2617 }
2618 if doSubs {
2619 if subs := r.removeRemoteSubsForAcc(an); len(subs) > 0 {
2620 sl.RemoveBatch(subs)
2621 }
2622 }
2623 if doProto {
2624 r.enqueueProto(proto)
2625 protosSent++
2626 }
2627 }
2628 for remote, conns := range s.routes {
2629 r := conns[rpi]
2630 // The route connection at this index is currently not up,
2631 // so we won't be able to send the protocol, so move to the
2632 // next remote.
2633 if r == nil {
2634 continue
2635 }
2636 doSubs := true
2637 // Check the remote's route pool size and if different than
2638 // ours, remove the subs on that other route.
2639 remotePoolSize, ok := s.remoteRoutePoolSize[remote]
2640 if ok && remotePoolSize != s.routesPoolSize {
2641 // This is the remote's route pool index for this account
2642 rrpi := computeRoutePoolIdx(remotePoolSize, an)
2643 if rr := conns[rrpi]; rr != nil {
2644 removeSubsAndSendProto(rr, true, false)
2645 // Indicate that we have already remove the subs.
2646 doSubs = false
2647 }
2648 }
2649 // Now send the protocol from the route that handles the
2650 // account from this server perspective.
2651 removeSubsAndSendProto(r, doSubs, true)
2652 }
2653 }
2654 }
2655 if protosSent > 0 {
2656 s.accAddedCh = make(chan struct{}, protosSent)
2657 ch = s.accAddedCh
2658 }
2659 }
2660 // Collect routes that need to be closed.
2661 routes := make(map[*client]struct{})
2662 // Collect the per-account routes that need to be closed.
2663 if len(co.accsRemoved) > 0 {
2664 for _, an := range co.accsRemoved {
2665 if remotes, ok := s.accRoutes[an]; ok && remotes != nil {
2666 for _, r := range remotes {
2667 if r != nil {
2668 r.setNoReconnect()
2669 routes[r] = struct{}{}
2670 }
2671 }
2672 }
2673 }
2674 }
2675 // If the pool size has changed, we need to close all pooled routes.
2676 if co.poolSizeChanged {
2677 s.forEachNonPerAccountRoute(func(r *client) {
2678 routes[r] = struct{}{}
2679 })
2680 }
2681 // If there are routes to close, we need to release the server lock.
2682 // Same if we need to wait on responses from the remotes when
2683 // processing new per-account routes.
2684 if len(routes) > 0 || protosSent > 0 {
2685 s.mu.Unlock()
2686
2687 // Wait for the expected number of confirmations from the remotes.
2688 for received := 0; received < protosSent; {
2689 select {
2690 case <-ch:
2691 received++
2692 case <-time.After(2 * time.Second):
2693 s.Warnf("Timed out waiting for confirmation from all routes regarding per-account routes changes")
2694 received = protosSent
2695 }
2696 }
2697
2698 for r := range routes {
2699 r.closeConnection(RouteRemoved)
2700 }
2701
2702 s.mu.Lock()
2703 }
2704 // Clear the accAddedCh/ReqID fields in case they were set.
2705 s.accAddedReqID, s.accAddedCh = _EMPTY_, nil
2706 // Now that per-account routes that needed to be closed are closed,
2707 // remove them from s.accRoutes. Doing so before would prevent
2708 // removeRoute() to do proper cleanup because the route would not
2709 // be found in s.accRoutes.
2710 for _, an := range co.accsRemoved {
2711 delete(s.accRoutes, an)
2712 // Do not lookup and call setRouteInfo() on the accounts here.
2713 // We need first to set the new s.routesPoolSize value and
2714 // anyway, there is no need to do here if the pool size has
2715 // changed (since it will be called for all accounts).
2716 }
2717 // We have already added the accounts to s.accRoutes that needed to
2718 // be added.
2719
2720 // We should always have at least the system account with a dedicated route,
2721 // but in case we have a configuration that disables pooling and without
2722 // a system account, possibly set the accRoutes to nil.
2723 if len(opts.Cluster.PinnedAccounts) == 0 {
2724 s.accRoutes = nil
2725 }
2726 // Now deal with pool size updates.
2727 if ps := opts.Cluster.PoolSize; ps > 0 {
2728 s.routesPoolSize = ps
2729 s.routeInfo.RoutePoolSize = ps
2730 } else {
2731 s.routesPoolSize = 1
2732 s.routeInfo.RoutePoolSize = 0
2733 }
2734 // If the pool size has changed, we need to recompute all accounts' route
2735 // pool index. Note that the added/removed accounts will be reset there
2736 // too, but that's ok (we could use a map to exclude them, but not worth it).
2737 if co.poolSizeChanged {
2738 s.accounts.Range(func(_, v any) bool {
2739 acc := v.(*Account)
2740 acc.mu.Lock()
2741 s.setRouteInfo(acc)
2742 acc.mu.Unlock()
2743 return true
2744 })
2745 } else if len(co.accsRemoved) > 0 {
2746 // For accounts that no longer have a dedicated route, we need to send
2747 // the subsriptions on the existing pooled routes for those accounts.
2748 for _, an := range co.accsRemoved {
2749 if a, ok := s.accounts.Load(an); ok {
2750 acc := a.(*Account)
2751 acc.mu.Lock()
2752 // First call this which will assign a new route pool index.
2753 s.setRouteInfo(acc)
2754 // Get the value so we can send the subscriptions interest
2755 // on all routes with this pool index.
2756 rpi := acc.routePoolIdx
2757 acc.mu.Unlock()
2758 s.forEachRouteIdx(rpi, func(r *client) bool {
2759 // We have the guarantee that if the route exists, it
2760 // is not a new one that would have been created when
2761 // we released the server lock if some routes needed
2762 // to be closed, because we have set s.routesReject
2763 // to `true` at the top of this function.
2764 s.sendSubsToRoute(r, rpi, an)
2765 return true
2766 })
2767 }
2768 }
2769 }
2770 // Allow routes to be accepted now.
2771 s.routesReject = false
2772 // If there is a pool size change or added accounts, solicit routes now.
2773 if co.poolSizeChanged || len(co.accsAdded) > 0 {
2774 s.solicitRoutes(opts.Routes, co.accsAdded)
2775 }
2776 s.mu.Unlock()
2777 }
2778
2779 // validateClusterOpts ensures the new ClusterOpts does not change some of the
2780 // fields that do not support reload.
2781 func validateClusterOpts(old, new ClusterOpts) error {
2782 if old.Host != new.Host {
2783 return fmt.Errorf("config reload not supported for cluster host: old=%s, new=%s",
2784 old.Host, new.Host)
2785 }
2786 if old.Port != new.Port {
2787 return fmt.Errorf("config reload not supported for cluster port: old=%d, new=%d",
2788 old.Port, new.Port)
2789 }
2790 // Validate Cluster.Advertise syntax
2791 if new.Advertise != "" {
2792 if _, _, err := parseHostPort(new.Advertise, 0); err != nil {
2793 return fmt.Errorf("invalid Cluster.Advertise value of %s, err=%v", new.Advertise, err)
2794 }
2795 }
2796 return nil
2797 }
2798
2799 // diffRoutes diffs the old routes and the new routes and returns the ones that
2800 // should be added and removed from the server.
2801 func diffRoutes(old, new []*url.URL) (add, remove []*url.URL) {
2802 // Find routes to remove.
2803 removeLoop:
2804 for _, oldRoute := range old {
2805 for _, newRoute := range new {
2806 if urlsAreEqual(oldRoute, newRoute) {
2807 continue removeLoop
2808 }
2809 }
2810 remove = append(remove, oldRoute)
2811 }
2812
2813 // Find routes to add.
2814 addLoop:
2815 for _, newRoute := range new {
2816 for _, oldRoute := range old {
2817 if urlsAreEqual(oldRoute, newRoute) {
2818 continue addLoop
2819 }
2820 }
2821 add = append(add, newRoute)
2822 }
2823
2824 return add, remove
2825 }
2826
2827 func diffProxiesTrustedKeys(old, new []*ProxyConfig) ([]string, []string) {
2828 var add []string
2829 var del []string
2830 // Both "old" and "new" lists should be small...
2831 for _, op := range old {
2832 if !slices.ContainsFunc(new, func(pc *ProxyConfig) bool {
2833 return pc.Key == op.Key
2834 }) {
2835 del = append(del, op.Key)
2836 }
2837 }
2838 for _, np := range new {
2839 if !slices.ContainsFunc(old, func(pc *ProxyConfig) bool {
2840 return pc.Key == np.Key
2841 }) {
2842 add = append(add, np.Key)
2843 }
2844 }
2845 return add, del
2846 }
2847
2848 // This function calls `reflect.DeepEqual` on all public fields that are
2849 // not part of the `ignoreFields` list. If they are all equal, returns nil,
2850 // otherwise returns an error that will contain the name of the first field
2851 // that fails the comparison, along with its old and new values.
2852 func checkConfigsEqual(c1, c2 any, ignoreFields []string) error {
2853 oldConfig := reflect.ValueOf(c1).Elem()
2854 newConfig := reflect.ValueOf(c2).Elem()
2855 for i := 0; i < oldConfig.NumField(); i++ {
2856 field := oldConfig.Type().Field(i)
2857 // field.PkgPath is empty for exported fields, and is not for unexported ones.
2858 // We skip the unexported fields.
2859 if field.PkgPath != _EMPTY_ {
2860 continue
2861 }
2862 // If it is in the set of fields to ignore, move to the next.
2863 // We expect the number of ignore fields to be small.
2864 var ignored bool
2865 for _, f := range ignoreFields {
2866 if f == field.Name {
2867 ignored = true
2868 break
2869 }
2870 }
2871 if ignored {
2872 continue
2873 }
2874 oldValue := oldConfig.Field(i).Interface()
2875 newValue := newConfig.Field(i).Interface()
2876 if !reflect.DeepEqual(oldValue, newValue) {
2877 return fmt.Errorf("field %q: old=%v, new=%v", field.Name, oldValue, newValue)
2878 }
2879 }
2880 return nil
2881 }