Debian Codegraph @

server/monitor.go

raw
1 // Copyright 2013-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 "bytes"
18 "cmp"
19 "crypto/sha256"
20 "crypto/tls"
21 "crypto/x509"
22 "encoding/hex"
23 "encoding/json"
24 "errors"
25 "expvar"
26 "fmt"
27 "maps"
28 "math"
29 "net"
30 "net/http"
31 "net/url"
32 "os"
33 "path/filepath"
34 "runtime"
35 "runtime/debug"
36 "runtime/pprof"
37 "slices"
38 "sort"
39 "strconv"
40 "strings"
41 "sync/atomic"
42 "time"
43
44 "github.com/nats-io/jwt/v2"
45 "github.com/nats-io/nats-server/v2/server/pse"
46 )
47
48 // Connz represents detailed information on current client connections.
49 type Connz struct {
50 ID string `json:"server_id"`
51 Now time.Time `json:"now"`
52 NumConns int `json:"num_connections"`
53 Total int `json:"total"`
54 Offset int `json:"offset"`
55 Limit int `json:"limit"`
56 Conns []*ConnInfo `json:"connections"`
57 }
58
59 // ConnzOptions are the options passed to Connz()
60 type ConnzOptions struct {
61 // Sort indicates how the results will be sorted. Check SortOpt for possible values.
62 // Only the sort by connection ID (ByCid) is ascending, all others are descending.
63 Sort SortOpt `json:"sort"`
64
65 // Username indicates if user names should be included in the results.
66 Username bool `json:"auth"`
67
68 // Subscriptions indicates if subscriptions should be included in the results.
69 Subscriptions bool `json:"subscriptions"`
70
71 // SubscriptionsDetail indicates if subscription details should be included in the results
72 SubscriptionsDetail bool `json:"subscriptions_detail"`
73
74 // Offset is used for pagination. Connz() only returns connections starting at this
75 // offset from the global results.
76 Offset int `json:"offset"`
77
78 // Limit is the maximum number of connections that should be returned by Connz().
79 Limit int `json:"limit"`
80
81 // Filter for this explicit client connection.
82 CID uint64 `json:"cid"`
83
84 // Filter for this explicit client connection based on the MQTT client ID
85 MQTTClient string `json:"mqtt_client"`
86
87 // Filter by connection state.
88 State ConnState `json:"state"`
89
90 // The below options only apply if auth is true.
91
92 // Filter by username.
93 User string `json:"user"`
94
95 // Filter by account.
96 Account string `json:"acc"`
97
98 // Filter by subject interest
99 FilterSubject string `json:"filter_subject"`
100 }
101
102 // ConnState is for filtering states of connections. We will only have two, open and closed.
103 type ConnState int
104
105 const (
106 // ConnOpen filters on open clients.
107 ConnOpen = ConnState(iota)
108 // ConnClosed filters on closed clients.
109 ConnClosed
110 // ConnAll returns all clients.
111 ConnAll
112 )
113
114 // ConnInfo has detailed information on a per connection basis.
115 type ConnInfo struct {
116 Cid uint64 `json:"cid"`
117 Kind string `json:"kind,omitempty"`
118 Type string `json:"type,omitempty"`
119 IP string `json:"ip"`
120 Port int `json:"port"`
121 Start time.Time `json:"start"`
122 LastActivity time.Time `json:"last_activity"`
123 Stop *time.Time `json:"stop,omitempty"`
124 Reason string `json:"reason,omitempty"`
125 RTT string `json:"rtt,omitempty"`
126 Uptime string `json:"uptime"`
127 Idle string `json:"idle"`
128 Pending int `json:"pending_bytes"`
129 InMsgs int64 `json:"in_msgs"`
130 OutMsgs int64 `json:"out_msgs"`
131 InBytes int64 `json:"in_bytes"`
132 OutBytes int64 `json:"out_bytes"`
133 Stalls int64 `json:"stalls,omitempty"`
134 NumSubs uint32 `json:"subscriptions"`
135 Name string `json:"name,omitempty"`
136 Lang string `json:"lang,omitempty"`
137 Version string `json:"version,omitempty"`
138 TLSVersion string `json:"tls_version,omitempty"`
139 TLSCipher string `json:"tls_cipher_suite,omitempty"`
140 TLSPeerCerts []*TLSPeerCert `json:"tls_peer_certs,omitempty"`
141 TLSFirst bool `json:"tls_first,omitempty"`
142 AuthorizedUser string `json:"authorized_user,omitempty"`
143 Account string `json:"account,omitempty"`
144 Subs []string `json:"subscriptions_list,omitempty"`
145 SubsDetail []SubDetail `json:"subscriptions_list_detail,omitempty"`
146 JWT string `json:"jwt,omitempty"`
147 IssuerKey string `json:"issuer_key,omitempty"`
148 NameTag string `json:"name_tag,omitempty"`
149 Tags jwt.TagList `json:"tags,omitempty"`
150 MQTTClient string `json:"mqtt_client,omitempty"` // This is the MQTT client id
151 Proxy *ProxyInfo `json:"proxy,omitempty"`
152
153 // Internal
154 rtt int64 // For fast sorting
155 }
156
157 // ProxyInfo represents the information about this proxied connection.
158 type ProxyInfo struct {
159 Key string `json:"key"`
160 }
161
162 // TLSPeerCert contains basic information about a TLS peer certificate
163 type TLSPeerCert struct {
164 Subject string `json:"subject,omitempty"`
165 SubjectPKISha256 string `json:"spki_sha256,omitempty"`
166 CertSha256 string `json:"cert_sha256,omitempty"`
167 }
168
169 // DefaultConnListSize is the default size of the connection list.
170 const DefaultConnListSize = 1024
171
172 // DefaultSubListSize is the default size of the subscriptions list.
173 const DefaultSubListSize = 1024
174
175 const defaultStackBufSize = 10000
176
177 func newSubsDetailList(client *client) []SubDetail {
178 subsDetail := make([]SubDetail, 0, len(client.subs))
179 for _, sub := range client.subs {
180 subsDetail = append(subsDetail, newClientSubDetail(sub))
181 }
182 return subsDetail
183 }
184
185 func newSubsList(client *client) []string {
186 subs := make([]string, 0, len(client.subs))
187 for _, sub := range client.subs {
188 subs = append(subs, string(sub.subject))
189 }
190 return subs
191 }
192
193 func redactBearerJWT(userJWT string) string {
194 if userJWT == _EMPTY_ {
195 return _EMPTY_
196 }
197 uc, err := jwt.DecodeUserClaims(userJWT)
198 if err == nil && uc != nil && uc.BearerToken {
199 return _EMPTY_
200 }
201 return userJWT
202 }
203
204 // Connz returns a Connz struct containing information about connections.
205 func (s *Server) Connz(opts *ConnzOptions) (*Connz, error) {
206 var (
207 sortOpt = ByCid
208 auth bool
209 subs bool
210 subsDet bool
211 offset int
212 limit = DefaultConnListSize
213 cid = uint64(0)
214 state = ConnOpen
215 user string
216 acc string
217 a *Account
218 filter string
219 mqttCID string
220 )
221
222 if opts != nil {
223 // If no sort option given or sort is by uptime, then sort by cid
224 if opts.Sort != _EMPTY_ {
225 sortOpt = opts.Sort
226 if !sortOpt.IsValid() {
227 return nil, fmt.Errorf("invalid sorting option: %s", sortOpt)
228 }
229 }
230
231 // Auth specifics.
232 auth = opts.Username
233 user = opts.User
234 acc = opts.Account
235 mqttCID = opts.MQTTClient
236
237 subs = opts.Subscriptions
238 subsDet = opts.SubscriptionsDetail
239 offset = opts.Offset
240 if offset < 0 {
241 offset = 0
242 }
243 limit = opts.Limit
244 if limit <= 0 {
245 limit = DefaultConnListSize
246 }
247 // state
248 state = opts.State
249
250 // ByStop only makes sense on closed connections
251 if sortOpt == ByStop && state != ConnClosed {
252 return nil, fmt.Errorf("sort by stop only valid on closed connections")
253 }
254 // ByReason is the same.
255 if sortOpt == ByReason && state != ConnClosed {
256 return nil, fmt.Errorf("sort by reason only valid on closed connections")
257 }
258 // If searching by CID
259 if opts.CID > 0 {
260 cid = opts.CID
261 limit = 1
262 }
263 // If filtering by subject.
264 if opts.FilterSubject != _EMPTY_ && opts.FilterSubject != fwcs {
265 if acc == _EMPTY_ {
266 return nil, fmt.Errorf("filter by subject only valid with account filtering")
267 }
268 filter = opts.FilterSubject
269 }
270 }
271
272 c := &Connz{
273 Offset: offset,
274 Limit: limit,
275 Now: time.Now().UTC(),
276 }
277
278 // Open clients
279 var openClients []*client
280 // Hold for closed clients if requested.
281 var closedClients []*closedClient
282
283 var clist map[uint64]*client
284
285 if acc != _EMPTY_ {
286 var err error
287 a, err = s.lookupAccount(acc)
288 if err != nil {
289 return c, nil
290 }
291 a.mu.RLock()
292 clist = make(map[uint64]*client, a.numLocalConnections())
293 for c := range a.clients {
294 if c.kind == CLIENT || c.kind == LEAF {
295 clist[c.cid] = c
296 }
297 }
298 a.mu.RUnlock()
299 }
300
301 // Walk the open client list with server lock held.
302 s.mu.RLock()
303 // Default to all client unless filled in above.
304 if clist == nil {
305 clist = make(map[uint64]*client, len(s.clients)+len(s.leafs))
306 maps.Copy(clist, s.clients)
307 maps.Copy(clist, s.leafs)
308 }
309
310 // copy the server id for monitoring
311 c.ID = s.info.ID
312
313 // Number of total clients. The resulting ConnInfo array
314 // may be smaller if pagination is used.
315 switch state {
316 case ConnOpen:
317 c.Total = len(clist)
318 case ConnClosed:
319 closedClients = s.closed.closedClients()
320 c.Total = len(closedClients)
321 case ConnAll:
322 c.Total = len(clist)
323 closedClients = s.closed.closedClients()
324 c.Total += len(closedClients)
325 }
326
327 // We may need to filter these connections.
328 if acc != _EMPTY_ && len(closedClients) > 0 {
329 var ccc []*closedClient
330 for _, cc := range closedClients {
331 if cc.acc != acc {
332 continue
333 }
334 ccc = append(ccc, cc)
335 }
336 c.Total -= (len(closedClients) - len(ccc))
337 closedClients = ccc
338 }
339
340 totalClients := c.Total
341 if cid > 0 { // Meaning we only want 1.
342 totalClients = 1
343 }
344 if state == ConnOpen || state == ConnAll {
345 openClients = make([]*client, 0, totalClients)
346 }
347
348 // Data structures for results.
349 var conns []ConnInfo // Limits allocs for actual ConnInfos.
350 var pconns ConnInfos
351
352 switch state {
353 case ConnOpen:
354 conns = make([]ConnInfo, totalClients)
355 pconns = make(ConnInfos, totalClients)
356 case ConnClosed:
357 pconns = make(ConnInfos, totalClients)
358 case ConnAll:
359 conns = make([]ConnInfo, cap(openClients))
360 pconns = make(ConnInfos, totalClients)
361 }
362
363 // Search by individual CID.
364 if cid > 0 {
365 // Let's first check if user also selects on ConnOpen or ConnAll
366 // and look for opened connections.
367 if state == ConnOpen || state == ConnAll {
368 if client := s.clients[cid]; client != nil {
369 openClients = append(openClients, client)
370 closedClients = nil
371 }
372 }
373 // If we did not find, and the user selected for ConnClosed or ConnAll,
374 // look for closed connections.
375 if len(openClients) == 0 && (state == ConnClosed || state == ConnAll) {
376 copyClosed := closedClients
377 closedClients = nil
378 for _, cc := range copyClosed {
379 if cc.Cid == cid {
380 closedClients = []*closedClient{cc}
381 break
382 }
383 }
384 }
385 } else {
386 // Gather all open clients.
387 if state == ConnOpen || state == ConnAll {
388 for _, client := range clist {
389 // Snapshot each under the client lock.
390 client.mu.RLock()
391 var cAccName string
392 if client.acc != nil {
393 cAccName = client.acc.Name
394 }
395 cAuthUser := client.getRawAuthUser()
396 cMQTTID := client.getMQTTClientID()
397 client.mu.RUnlock()
398
399 // If we have an account specified we need to filter.
400 if acc != _EMPTY_ && cAccName != acc {
401 continue
402 }
403 // Do user filtering second
404 if user != _EMPTY_ && cAuthUser != user {
405 continue
406 }
407 // Do mqtt client ID filtering next
408 if mqttCID != _EMPTY_ && cMQTTID != mqttCID {
409 continue
410 }
411 openClients = append(openClients, client)
412 }
413 }
414 }
415 s.mu.RUnlock()
416
417 // Filter by subject now if needed. We do this outside of server lock.
418 if filter != _EMPTY_ {
419 var oc []*client
420 for _, c := range openClients {
421 c.mu.Lock()
422 for _, sub := range c.subs {
423 if SubjectsCollide(filter, string(sub.subject)) {
424 oc = append(oc, c)
425 break
426 }
427 }
428 c.mu.Unlock()
429 openClients = oc
430 }
431 }
432
433 // Just return with empty array if nothing here.
434 if len(openClients) == 0 && len(closedClients) == 0 {
435 c.Conns = ConnInfos{}
436 return c, nil
437 }
438
439 // Now whip through and generate ConnInfo entries
440 // Open Clients
441 i := 0
442 for _, client := range openClients {
443 client.mu.Lock()
444 ci := &conns[i]
445 ci.fill(client, client.nc, c.Now, auth)
446 // Fill in subscription data if requested.
447 if len(client.subs) > 0 {
448 if subsDet {
449 ci.SubsDetail = newSubsDetailList(client)
450 } else if subs {
451 ci.Subs = newSubsList(client)
452 }
453 }
454 // Fill in user if auth requested.
455 if auth {
456 ci.AuthorizedUser = client.getRawAuthUser()
457 if name := client.acc.GetName(); name != globalAccountName {
458 ci.Account = name
459 }
460 ci.JWT = client.opts.JWT
461 ci.IssuerKey = issuerForClient(client)
462 ci.Tags = client.tags
463 ci.NameTag = client.acc.getNameTag()
464 }
465 client.mu.Unlock()
466 ci.JWT = redactBearerJWT(ci.JWT)
467 pconns[i] = ci
468 i++
469 }
470 // Closed Clients
471 var needCopy bool
472 if subs || subsDet || auth {
473 needCopy = true
474 }
475 for _, cc := range closedClients {
476 // If we have an account specified we need to filter.
477 if acc != _EMPTY_ && cc.acc != acc {
478 continue
479 }
480 // Do user filtering second
481 if user != _EMPTY_ && cc.user != user {
482 continue
483 }
484 // Do mqtt client ID filtering next
485 if mqttCID != _EMPTY_ && cc.MQTTClient != mqttCID {
486 continue
487 }
488 // Copy if needed for any changes to the ConnInfo
489 if needCopy {
490 cx := *cc
491 cc = &cx
492 }
493 // Fill in subscription data if requested.
494 if len(cc.subs) > 0 {
495 if subsDet {
496 cc.SubsDetail = cc.subs
497 } else if subs {
498 cc.Subs = make([]string, 0, len(cc.subs))
499 for _, sub := range cc.subs {
500 cc.Subs = append(cc.Subs, sub.Subject)
501 }
502 }
503 }
504 // Fill in user if auth requested.
505 if auth {
506 cc.AuthorizedUser = cc.user
507 if cc.acc != _EMPTY_ && (cc.acc != globalAccountName) {
508 cc.Account = cc.acc
509 if acc, err := s.LookupAccount(cc.acc); err == nil {
510 cc.NameTag = acc.getNameTag()
511 }
512 }
513 cc.JWT = redactBearerJWT(cc.JWT)
514 }
515 pconns[i] = &cc.ConnInfo
516 i++
517 }
518
519 // This will trip if we have filtered out client connections.
520 if len(pconns) != i {
521 pconns = pconns[:i]
522 totalClients = i
523 }
524
525 switch sortOpt {
526 case ByCid, ByStart:
527 sort.Sort(SortByCid{pconns})
528 case BySubs:
529 sort.Sort(sort.Reverse(SortBySubs{pconns}))
530 case ByPending:
531 sort.Sort(sort.Reverse(SortByPending{pconns}))
532 case ByOutMsgs:
533 sort.Sort(sort.Reverse(SortByOutMsgs{pconns}))
534 case ByInMsgs:
535 sort.Sort(sort.Reverse(SortByInMsgs{pconns}))
536 case ByOutBytes:
537 sort.Sort(sort.Reverse(SortByOutBytes{pconns}))
538 case ByInBytes:
539 sort.Sort(sort.Reverse(SortByInBytes{pconns}))
540 case ByLast:
541 sort.Sort(sort.Reverse(SortByLast{pconns}))
542 case ByIdle:
543 sort.Sort(sort.Reverse(SortByIdle{pconns, c.Now}))
544 case ByUptime:
545 sort.Sort(SortByUptime{pconns, time.Now()})
546 case ByStop:
547 sort.Sort(sort.Reverse(SortByStop{pconns}))
548 case ByReason:
549 sort.Sort(SortByReason{pconns})
550 case ByRTT:
551 sort.Sort(sort.Reverse(SortByRTT{pconns}))
552 }
553
554 // Make sure these are sane.
555 maxIndex := totalClients
556 minoff := min(max(c.Offset, 0), maxIndex)
557 maxoff := minoff + min(c.Limit, maxIndex-minoff)
558
559 // Now pare down to the requested size.
560 // TODO(dlc) - for very large number of connections we
561 // could save the whole list in a hash, send hash on first
562 // request and allow users to use has for subsequent pages.
563 // Low TTL, say < 1sec.
564 c.Conns = pconns[minoff:maxoff]
565 c.NumConns = len(c.Conns)
566
567 return c, nil
568 }
569
570 // Fills in the ConnInfo from the client.
571 // client should be locked.
572 func (ci *ConnInfo) fill(client *client, nc net.Conn, now time.Time, auth bool) {
573 // For fast sort if required.
574 rtt := client.getRTT()
575 ci.rtt = int64(rtt)
576
577 ci.Cid = client.cid
578 ci.MQTTClient = client.getMQTTClientID()
579 ci.Kind = client.kindString()
580 ci.Type = client.clientTypeString()
581 ci.Start = client.start
582 ci.LastActivity = client.last
583 ci.Uptime = myUptime(now.Sub(client.start))
584 ci.Idle = myUptime(now.Sub(client.last))
585 ci.RTT = rtt.String()
586 ci.OutMsgs = client.outMsgs
587 ci.OutBytes = client.outBytes
588 ci.NumSubs = uint32(len(client.subs))
589 ci.Pending = int(client.out.pb)
590 ci.Name = client.opts.Name
591 ci.Lang = client.opts.Lang
592 ci.Version = client.opts.Version
593 // inMsgs and inBytes are updated outside of the client's lock, so
594 // we need to use atomic here.
595 ci.InMsgs = atomic.LoadInt64(&client.inMsgs)
596 ci.InBytes = atomic.LoadInt64(&client.inBytes)
597 ci.Stalls = atomic.LoadInt64(&client.stalls)
598 ci.Proxy = createProxyInfo(client)
599
600 // If the connection is gone, too bad, we won't set TLSVersion and TLSCipher.
601 // Exclude clients that are still doing handshake so we don't block in
602 // ConnectionState().
603 if client.flags.isSet(handshakeComplete) && nc != nil {
604 if conn, ok := nc.(*tls.Conn); ok {
605 cs := conn.ConnectionState()
606 ci.TLSVersion = tlsVersion(cs.Version)
607 ci.TLSCipher = tls.CipherSuiteName(cs.CipherSuite)
608 if auth && len(cs.PeerCertificates) > 0 {
609 ci.TLSPeerCerts = makePeerCerts(cs.PeerCertificates)
610 }
611 ci.TLSFirst = client.flags.isSet(didTLSFirst)
612 }
613 }
614
615 if client.port != 0 {
616 ci.Port = int(client.port)
617 ci.IP = client.host
618 }
619 }
620
621 // If this client came from a trusted proxy, this will return a ProxyInfo
622 // to be used in ConnInfo or LeafInfo.
623 //
624 // Client lock must be held on entry.
625 func createProxyInfo(c *client) *ProxyInfo {
626 if c.proxyKey == _EMPTY_ {
627 return nil
628 }
629 return &ProxyInfo{Key: c.proxyKey}
630 }
631
632 func makePeerCerts(pc []*x509.Certificate) []*TLSPeerCert {
633 res := make([]*TLSPeerCert, len(pc))
634 for i, c := range pc {
635 tmp := sha256.Sum256(c.RawSubjectPublicKeyInfo)
636 ssha := hex.EncodeToString(tmp[:])
637 tmp = sha256.Sum256(c.Raw)
638 csha := hex.EncodeToString(tmp[:])
639 res[i] = &TLSPeerCert{Subject: c.Subject.String(), SubjectPKISha256: ssha, CertSha256: csha}
640 }
641 return res
642 }
643
644 // Assume lock is held
645 func (c *client) getRTT() time.Duration {
646 if c.rtt == 0 {
647 // If a real client, go ahead and send ping now to get a value
648 // for RTT. For tests and telnet, or if client is closing, etc skip.
649 if c.opts.Lang != _EMPTY_ {
650 c.sendRTTPingLocked()
651 }
652 return 0
653 }
654 var rtt time.Duration
655 if c.rtt > time.Microsecond && c.rtt < time.Millisecond {
656 rtt = c.rtt.Truncate(time.Microsecond)
657 } else {
658 rtt = c.rtt.Truncate(time.Nanosecond)
659 }
660 return rtt
661 }
662
663 func decodeBool(w http.ResponseWriter, r *http.Request, param string) (bool, error) {
664 str := r.URL.Query().Get(param)
665 if str == _EMPTY_ {
666 return false, nil
667 }
668 val, err := strconv.ParseBool(str)
669 if err != nil {
670 w.WriteHeader(http.StatusBadRequest)
671 w.Write([]byte(fmt.Sprintf("Error decoding boolean for '%s': %v", param, err)))
672 return false, err
673 }
674 return val, nil
675 }
676
677 func decodeUint64(w http.ResponseWriter, r *http.Request, param string) (uint64, error) {
678 str := r.URL.Query().Get(param)
679 if str == _EMPTY_ {
680 return 0, nil
681 }
682 val, err := strconv.ParseUint(str, 10, 64)
683 if err != nil {
684 w.WriteHeader(http.StatusBadRequest)
685 w.Write([]byte(fmt.Sprintf("Error decoding uint64 for '%s': %v", param, err)))
686 return 0, err
687 }
688 return val, nil
689 }
690
691 func decodeInt(w http.ResponseWriter, r *http.Request, param string) (int, error) {
692 str := r.URL.Query().Get(param)
693 if str == _EMPTY_ {
694 return 0, nil
695 }
696 val, err := strconv.Atoi(str)
697 if err != nil {
698 w.WriteHeader(http.StatusBadRequest)
699 w.Write([]byte(fmt.Sprintf("Error decoding int for '%s': %v", param, err)))
700 return 0, err
701 }
702 return val, nil
703 }
704
705 func decodeState(w http.ResponseWriter, r *http.Request) (ConnState, error) {
706 str := r.URL.Query().Get("state")
707 if str == _EMPTY_ {
708 return ConnOpen, nil
709 }
710 switch strings.ToLower(str) {
711 case "open":
712 return ConnOpen, nil
713 case "closed":
714 return ConnClosed, nil
715 case "any", "all":
716 return ConnAll, nil
717 }
718 // We do not understand intended state here.
719 w.WriteHeader(http.StatusBadRequest)
720 err := fmt.Errorf("Error decoding state for %s", str)
721 w.Write([]byte(err.Error()))
722 return 0, err
723 }
724
725 func decodeSubs(w http.ResponseWriter, r *http.Request) (subs bool, subsDet bool, err error) {
726 subsDet = strings.ToLower(r.URL.Query().Get("subs")) == "detail"
727 if !subsDet {
728 subs, err = decodeBool(w, r, "subs")
729 }
730 return
731 }
732
733 // HandleConnz process HTTP requests for connection information.
734 func (s *Server) HandleConnz(w http.ResponseWriter, r *http.Request) {
735 sortOpt := SortOpt(r.URL.Query().Get("sort"))
736 auth, err := decodeBool(w, r, "auth")
737 if err != nil {
738 return
739 }
740 subs, subsDet, err := decodeSubs(w, r)
741 if err != nil {
742 return
743 }
744 offset, err := decodeInt(w, r, "offset")
745 if err != nil {
746 return
747 }
748 limit, err := decodeInt(w, r, "limit")
749 if err != nil {
750 return
751 }
752 cid, err := decodeUint64(w, r, "cid")
753 if err != nil {
754 return
755 }
756 state, err := decodeState(w, r)
757 if err != nil {
758 return
759 }
760
761 user := r.URL.Query().Get("user")
762 acc := r.URL.Query().Get("acc")
763 mqttCID := r.URL.Query().Get("mqtt_client")
764
765 connzOpts := &ConnzOptions{
766 Sort: sortOpt,
767 Username: auth,
768 Subscriptions: subs,
769 SubscriptionsDetail: subsDet,
770 Offset: offset,
771 Limit: limit,
772 CID: cid,
773 MQTTClient: mqttCID,
774 State: state,
775 User: user,
776 Account: acc,
777 }
778
779 s.mu.Lock()
780 s.httpReqStats[ConnzPath]++
781 s.mu.Unlock()
782
783 c, err := s.Connz(connzOpts)
784 if err != nil {
785 w.WriteHeader(http.StatusBadRequest)
786 w.Write([]byte(err.Error()))
787 return
788 }
789 b, err := json.MarshalIndent(c, "", " ")
790 if err != nil {
791 s.Errorf("Error marshaling response to /connz request: %v", err)
792 }
793
794 // Handle response
795 ResponseHandler(w, r, b)
796 }
797
798 // Routez represents detailed information on current client connections.
799 type Routez struct {
800 ID string `json:"server_id"`
801 Name string `json:"server_name"`
802 Now time.Time `json:"now"`
803 Import *SubjectPermission `json:"import,omitempty"`
804 Export *SubjectPermission `json:"export,omitempty"`
805 NumRoutes int `json:"num_routes"`
806 Routes []*RouteInfo `json:"routes"`
807 }
808
809 // RoutezOptions are options passed to Routez
810 type RoutezOptions struct {
811 // Subscriptions indicates that Routez will return a route's subscriptions
812 Subscriptions bool `json:"subscriptions"`
813 // SubscriptionsDetail indicates if subscription details should be included in the results
814 SubscriptionsDetail bool `json:"subscriptions_detail"`
815 }
816
817 // RouteInfo has detailed information on a per connection basis.
818 type RouteInfo struct {
819 Rid uint64 `json:"rid"`
820 RemoteID string `json:"remote_id"`
821 RemoteName string `json:"remote_name"`
822 DidSolicit bool `json:"did_solicit"`
823 IsConfigured bool `json:"is_configured"`
824 IP string `json:"ip"`
825 Port int `json:"port"`
826 Start time.Time `json:"start"`
827 LastActivity time.Time `json:"last_activity"`
828 RTT string `json:"rtt,omitempty"`
829 Uptime string `json:"uptime"`
830 Idle string `json:"idle"`
831 Import *SubjectPermission `json:"import,omitempty"`
832 Export *SubjectPermission `json:"export,omitempty"`
833 Pending int `json:"pending_size"`
834 InMsgs int64 `json:"in_msgs"`
835 OutMsgs int64 `json:"out_msgs"`
836 InBytes int64 `json:"in_bytes"`
837 OutBytes int64 `json:"out_bytes"`
838 NumSubs uint32 `json:"subscriptions"`
839 Subs []string `json:"subscriptions_list,omitempty"`
840 SubsDetail []SubDetail `json:"subscriptions_list_detail,omitempty"`
841 Account string `json:"account,omitempty"`
842 Compression string `json:"compression,omitempty"`
843 }
844
845 // Routez returns a Routez struct containing information about routes.
846 func (s *Server) Routez(routezOpts *RoutezOptions) (*Routez, error) {
847 rs := &Routez{
848 Now: time.Now().UTC(),
849 Routes: []*RouteInfo{},
850 }
851
852 if routezOpts == nil {
853 routezOpts = &RoutezOptions{}
854 }
855
856 s.mu.Lock()
857 rs.NumRoutes = s.numRoutes()
858
859 // copy the server id for monitoring
860 rs.ID = s.info.ID
861
862 // Check for defined permissions for all connected routes.
863 if perms := s.getOpts().Cluster.Permissions; perms != nil {
864 rs.Import = perms.Import
865 rs.Export = perms.Export
866 }
867 rs.Name = s.info.Name
868
869 addRoute := func(r *client) {
870 r.mu.Lock()
871 ri := &RouteInfo{
872 Rid: r.cid,
873 RemoteID: r.route.remoteID,
874 RemoteName: r.route.remoteName,
875 DidSolicit: r.route.didSolicit,
876 IsConfigured: r.route.routeType == Explicit,
877 InMsgs: atomic.LoadInt64(&r.inMsgs),
878 OutMsgs: r.outMsgs,
879 InBytes: atomic.LoadInt64(&r.inBytes),
880 OutBytes: r.outBytes,
881 NumSubs: uint32(len(r.subs)),
882 Import: r.opts.Import,
883 Pending: int(r.out.pb),
884 Export: r.opts.Export,
885 RTT: r.getRTT().String(),
886 Start: r.start,
887 LastActivity: r.last,
888 Uptime: myUptime(rs.Now.Sub(r.start)),
889 Idle: myUptime(rs.Now.Sub(r.last)),
890 Account: string(r.route.accName),
891 Compression: r.route.compression,
892 }
893
894 if len(r.subs) > 0 {
895 if routezOpts.SubscriptionsDetail {
896 ri.SubsDetail = newSubsDetailList(r)
897 } else if routezOpts.Subscriptions {
898 ri.Subs = newSubsList(r)
899 }
900 }
901
902 switch conn := r.nc.(type) {
903 case *net.TCPConn, *tls.Conn:
904 addr := conn.RemoteAddr().(*net.TCPAddr)
905 ri.Port = addr.Port
906 ri.IP = addr.IP.String()
907 }
908 r.mu.Unlock()
909 rs.Routes = append(rs.Routes, ri)
910 }
911
912 // Walk the list
913 s.forEachRoute(func(r *client) {
914 addRoute(r)
915 })
916 s.mu.Unlock()
917 return rs, nil
918 }
919
920 // HandleRoutez process HTTP requests for route information.
921 func (s *Server) HandleRoutez(w http.ResponseWriter, r *http.Request) {
922 subs, subsDetail, err := decodeSubs(w, r)
923 if err != nil {
924 return
925 }
926
927 opts := RoutezOptions{Subscriptions: subs, SubscriptionsDetail: subsDetail}
928
929 s.mu.Lock()
930 s.httpReqStats[RoutezPath]++
931 s.mu.Unlock()
932
933 // As of now, no error is ever returned.
934 rs, _ := s.Routez(&opts)
935 b, err := json.MarshalIndent(rs, "", " ")
936 if err != nil {
937 s.Errorf("Error marshaling response to /routez request: %v", err)
938 }
939
940 // Handle response
941 ResponseHandler(w, r, b)
942 }
943
944 // Subsz represents detail information on current connections.
945 type Subsz struct {
946 ID string `json:"server_id"`
947 Now time.Time `json:"now"`
948 *SublistStats
949 Total int `json:"total"`
950 Offset int `json:"offset"`
951 Limit int `json:"limit"`
952 Subs []SubDetail `json:"subscriptions_list,omitempty"`
953 }
954
955 // SubszOptions are the options passed to Subsz.
956 // As of now, there are no options defined.
957 type SubszOptions struct {
958 // Offset is used for pagination. Subsz() only returns connections starting at this
959 // offset from the global results.
960 Offset int `json:"offset"`
961
962 // Limit is the maximum number of subscriptions that should be returned by Subsz().
963 Limit int `json:"limit"`
964
965 // Subscriptions indicates if subscription details should be included in the results.
966 Subscriptions bool `json:"subscriptions"`
967
968 // Filter based on this account name.
969 Account string `json:"account,omitempty"`
970
971 // Test the list against this subject. Needs to be literal since it signifies a publish subject.
972 // We will only return subscriptions that would match if a message was sent to this subject.
973 Test string `json:"test,omitempty"`
974 }
975
976 // SubDetail is for verbose information for subscriptions.
977 type SubDetail struct {
978 Account string `json:"account,omitempty"`
979 AccountTag string `json:"account_tag,omitempty"`
980 Subject string `json:"subject"`
981 Queue string `json:"qgroup,omitempty"`
982 Sid string `json:"sid"`
983 Msgs int64 `json:"msgs"`
984 Max int64 `json:"max,omitempty"`
985 Cid uint64 `json:"cid"`
986 }
987
988 // Subscription client should be locked and guaranteed to be present.
989 func newSubDetail(sub *subscription) SubDetail {
990 sd := newClientSubDetail(sub)
991 sd.Account = sub.client.acc.GetName()
992 sd.AccountTag = sub.client.acc.getNameTag()
993 return sd
994 }
995
996 // For subs details under clients.
997 func newClientSubDetail(sub *subscription) SubDetail {
998 return SubDetail{
999 Subject: string(sub.subject),
1000 Queue: string(sub.queue),
1001 Sid: string(sub.sid),
1002 Msgs: sub.nm,
1003 Max: sub.max,
1004 Cid: sub.client.cid,
1005 }
1006 }
1007
1008 // Subsz returns a Subsz struct containing subjects statistics
1009 func (s *Server) Subsz(opts *SubszOptions) (*Subsz, error) {
1010 var (
1011 subdetail bool
1012 test bool
1013 offset int
1014 testSub string
1015 filterAcc string
1016 limit = DefaultSubListSize
1017 )
1018
1019 if opts != nil {
1020 subdetail = opts.Subscriptions
1021 offset = opts.Offset
1022 if offset < 0 {
1023 offset = 0
1024 }
1025 limit = opts.Limit
1026 if limit <= 0 {
1027 limit = DefaultSubListSize
1028 }
1029 if opts.Test != _EMPTY_ {
1030 testSub = opts.Test
1031 test = true
1032 if !IsValidLiteralSubject(testSub) {
1033 return nil, fmt.Errorf("invalid test subject, must be valid publish subject: %s", testSub)
1034 }
1035 }
1036 if opts.Account != _EMPTY_ {
1037 filterAcc = opts.Account
1038 }
1039 }
1040
1041 slStats := &SublistStats{}
1042
1043 // FIXME(dlc) - Make account aware.
1044 sz := &Subsz{
1045 ID: s.info.ID,
1046 Now: time.Now().UTC(),
1047 SublistStats: slStats,
1048 Total: 0,
1049 Offset: offset,
1050 Limit: limit,
1051 Subs: nil,
1052 }
1053
1054 if subdetail {
1055 var raw [4096]*subscription
1056 subs := raw[:0]
1057 s.accounts.Range(func(k, v any) bool {
1058 acc := v.(*Account)
1059 if filterAcc != _EMPTY_ && acc.GetName() != filterAcc {
1060 return true
1061 }
1062 slStats.add(acc.sl.Stats())
1063 acc.sl.localSubs(&subs, false)
1064 return true
1065 })
1066
1067 details := make([]SubDetail, 0, len(subs))
1068 i := 0
1069 // TODO(dlc) - may be inefficient and could just do normal match when total subs is large and filtering.
1070 for _, sub := range subs {
1071 // Check for filter
1072 if test && !matchLiteral(testSub, string(sub.subject)) {
1073 continue
1074 }
1075 if sub.client == nil {
1076 continue
1077 }
1078 sub.client.mu.Lock()
1079 details = append(details, newSubDetail(sub))
1080 sub.client.mu.Unlock()
1081 i++
1082 }
1083 // Make sure these are sane.
1084 maxIndex := i
1085 minoff := min(max(sz.Offset, 0), maxIndex)
1086 maxoff := minoff + min(sz.Limit, maxIndex-minoff)
1087 sz.Subs = details[minoff:maxoff]
1088 sz.Total = len(details)
1089 } else {
1090 s.accounts.Range(func(k, v any) bool {
1091 acc := v.(*Account)
1092 if filterAcc != _EMPTY_ && acc.GetName() != filterAcc {
1093 return true
1094 }
1095 slStats.add(acc.sl.Stats())
1096 return true
1097 })
1098 }
1099
1100 return sz, nil
1101 }
1102
1103 // HandleSubsz processes HTTP requests for subjects stats.
1104 func (s *Server) HandleSubsz(w http.ResponseWriter, r *http.Request) {
1105 s.mu.Lock()
1106 s.httpReqStats[SubszPath]++
1107 s.mu.Unlock()
1108
1109 subs, err := decodeBool(w, r, "subs")
1110 if err != nil {
1111 return
1112 }
1113 offset, err := decodeInt(w, r, "offset")
1114 if err != nil {
1115 return
1116 }
1117 limit, err := decodeInt(w, r, "limit")
1118 if err != nil {
1119 return
1120 }
1121 testSub := r.URL.Query().Get("test")
1122 // Filtered account.
1123 filterAcc := r.URL.Query().Get("acc")
1124
1125 subszOpts := &SubszOptions{
1126 Subscriptions: subs,
1127 Offset: offset,
1128 Limit: limit,
1129 Account: filterAcc,
1130 Test: testSub,
1131 }
1132
1133 st, err := s.Subsz(subszOpts)
1134 if err != nil {
1135 w.WriteHeader(http.StatusBadRequest)
1136 w.Write([]byte(err.Error()))
1137 return
1138 }
1139
1140 var b []byte
1141 b, err = json.MarshalIndent(st, "", " ")
1142 if err != nil {
1143 s.Errorf("Error marshaling response to /subscriptionsz request: %v", err)
1144 }
1145
1146 // Handle response
1147 ResponseHandler(w, r, b)
1148 }
1149
1150 // HandleStacksz processes HTTP requests for getting stacks
1151 func (s *Server) HandleStacksz(w http.ResponseWriter, r *http.Request) {
1152 // Do not get any lock here that would prevent getting the stacks
1153 // if we were to have a deadlock somewhere.
1154 var defaultBuf [defaultStackBufSize]byte
1155 size := defaultStackBufSize
1156 buf := defaultBuf[:size]
1157 n := 0
1158 for {
1159 n = runtime.Stack(buf, true)
1160 if n < size {
1161 break
1162 }
1163 size *= 2
1164 buf = make([]byte, size)
1165 }
1166 // Handle response
1167 ResponseHandler(w, r, buf[:n])
1168 }
1169
1170 type IpqueueszStatusIPQ struct {
1171 Pending int `json:"pending"`
1172 InProgress int `json:"in_progress,omitempty"`
1173 }
1174
1175 type IpqueueszStatus map[string]IpqueueszStatusIPQ
1176
1177 func (s *Server) Ipqueuesz(opts *IpqueueszOptions) *IpqueueszStatus {
1178 all, qfilter := opts.All, opts.Filter
1179 queues := IpqueueszStatus{}
1180 s.ipQueues.Range(func(k, v any) bool {
1181 var pending, inProgress int
1182 name := k.(string)
1183 queue, ok := v.(interface {
1184 len() int
1185 inProgress() int64
1186 })
1187 if ok {
1188 pending = queue.len()
1189 inProgress = int(queue.inProgress())
1190 }
1191 if !all && (pending == 0 && inProgress == 0) {
1192 return true
1193 } else if qfilter != _EMPTY_ && !strings.Contains(name, qfilter) {
1194 return true
1195 }
1196 queues[name] = IpqueueszStatusIPQ{Pending: pending, InProgress: inProgress}
1197 return true
1198 })
1199 return &queues
1200 }
1201
1202 func (s *Server) HandleIPQueuesz(w http.ResponseWriter, r *http.Request) {
1203 all, err := decodeBool(w, r, "all")
1204 if err != nil {
1205 return
1206 }
1207 qfilter := r.URL.Query().Get("queues")
1208
1209 queues := s.Ipqueuesz(&IpqueueszOptions{
1210 All: all,
1211 Filter: qfilter,
1212 })
1213
1214 b, _ := json.MarshalIndent(queues, "", " ")
1215 ResponseHandler(w, r, b)
1216 }
1217
1218 // Varz will output server information on the monitoring port at /varz.
1219 type Varz struct {
1220 ID string `json:"server_id"` // ID is the unique server ID generated at start
1221 Name string `json:"server_name"` // Name is the configured server name, equals ID when not set
1222 Version string `json:"version"` // Version is the version of the running server
1223 Proto int `json:"proto"` // Proto is the protocol version this server supports
1224 GitCommit string `json:"git_commit,omitempty"` // GitCommit is the git repository commit hash that the build corresponds with
1225 GoVersion string `json:"go"` // GoVersion is the version of Go used to build this binary
1226 Host string `json:"host"` // Host is the hostname the server runs on
1227 Port int `json:"port"` // Port is the port the server listens on for client connections
1228 AuthRequired bool `json:"auth_required,omitempty"` // AuthRequired indicates if users are required to authenticate to join the server
1229 TLSRequired bool `json:"tls_required,omitempty"` // TLSRequired indicates if connections must use TLS when connecting to this server
1230 TLSVerify bool `json:"tls_verify,omitempty"` // TLSVerify indicates if full TLS verification will be performed
1231 TLSOCSPPeerVerify bool `json:"tls_ocsp_peer_verify,omitempty"` // TLSOCSPPeerVerify indicates if the OCSP protocol will be used to verify peers
1232 IP string `json:"ip,omitempty"` // IP is the IP address the server listens on if set
1233 ClientConnectURLs []string `json:"connect_urls,omitempty"` // ClientConnectURLs is the list of URLs NATS clients can use to connect to this server
1234 WSConnectURLs []string `json:"ws_connect_urls,omitempty"` // WSConnectURLs is the list of URLs websocket clients can use to connect to this server
1235 MaxConn int `json:"max_connections"` // MaxConn is the maximum amount of connections the server can accept
1236 MaxSubs int `json:"max_subscriptions,omitempty"` // MaxSubs is the maximum amount of subscriptions the server can manage
1237 PingInterval time.Duration `json:"ping_interval"` // PingInterval is the interval the server will send PING messages during periods of inactivity on a connection
1238 MaxPingsOut int `json:"ping_max"` // MaxPingsOut is the number of unanswered PINGs after which the connection will be considered stale
1239 HTTPHost string `json:"http_host"` // HTTPHost is the HTTP host monitoring connections are accepted on
1240 HTTPPort int `json:"http_port"` // HTTPPort is the port monitoring connections are accepted on
1241 HTTPBasePath string `json:"http_base_path"` // HTTPBasePath is the path prefix for access to monitor endpoints
1242 HTTPSPort int `json:"https_port"` // HTTPSPort is the HTTPS host monitoring connections are accepted on`
1243 AuthTimeout float64 `json:"auth_timeout"` // AuthTimeout is the amount of seconds connections have to complete authentication
1244 MaxControlLine int32 `json:"max_control_line"` // MaxControlLine is the amount of bytes a signal control message may be
1245 MaxPayload int `json:"max_payload"` // MaxPayload is the maximum amount of bytes a message may have as payload
1246 MaxPending int64 `json:"max_pending"` // MaxPending is the maximum amount of unprocessed bytes a connection may have
1247 Cluster ClusterOptsVarz `json:"cluster,omitempty"` // Cluster is the Cluster state
1248 Gateway GatewayOptsVarz `json:"gateway,omitempty"` // Gateway is the Super Cluster state
1249 LeafNode LeafNodeOptsVarz `json:"leaf,omitempty"` // LeafNode is the Leafnode state
1250 MQTT MQTTOptsVarz `json:"mqtt,omitempty"` // MQTT is the MQTT state
1251 Websocket WebsocketOptsVarz `json:"websocket,omitempty"` // Websocket is the Websocket client state
1252 JetStream JetStreamVarz `json:"jetstream,omitempty"` // JetStream is the JetStream state
1253 TLSTimeout float64 `json:"tls_timeout"` // TLSTimeout is how long TLS operations have to complete
1254 WriteDeadline time.Duration `json:"write_deadline"` // WriteDeadline is the maximum time writes to sockets have to complete
1255 WriteTimeout string `json:"write_timeout,omitempty"` // WriteTimeout is the closure policy for write deadline errors
1256 Start time.Time `json:"start"` // Start is time when the server was started
1257 Now time.Time `json:"now"` // Now is the current time of the server
1258 Uptime string `json:"uptime"` // Uptime is how long the server has been running
1259 Mem int64 `json:"mem"` // Mem is the resident memory allocation
1260 Cores int `json:"cores"` // Cores is the number of cores the process has access to
1261 MaxProcs int `json:"gomaxprocs"` // MaxProcs is the configured GOMAXPROCS value
1262 MemLimit int64 `json:"gomemlimit,omitempty"` // MemLimit is the configured GOMEMLIMIT value
1263 CPU float64 `json:"cpu"` // CPU is the current total CPU usage
1264 Connections int `json:"connections"` // Connections is the current connected connections
1265 TotalConnections uint64 `json:"total_connections"` // TotalConnections is the total connections the server have ever handled
1266 Routes int `json:"routes"` // Routes is the number of connected route servers
1267 Remotes int `json:"remotes"` // Remotes is the configured route remote endpoints
1268 Leafs int `json:"leafnodes"` // Leafs is the number connected leafnode clients
1269 InMsgs int64 `json:"in_msgs"` // InMsgs is the total number of messages this server received. This includes messages from the clients, routers, gateways and leaf nodes
1270 InBytes int64 `json:"in_bytes"` // InBytes is the total number of bytes this server received. This includes messages from the clients, routers, gateways and leaf nodes
1271 InClientMsgs int64 `json:"in_client_msgs"` // InClientMsgs is the number of messages this server received from the clients
1272 InClientBytes int64 `json:"in_client_bytes"` // InClientBytes is the number of bytes this server received from the clients
1273 OutMsgs int64 `json:"out_msgs"` // OutMsgs is the total number of message this server sent. This includes messages sent to the clients, routers, gateways and leaf nodes
1274 OutBytes int64 `json:"out_bytes"` // OutBytes is the total number of bytes this server sent. This includes messages sent to the clients, routers, gateways and leaf nodes
1275 OutClientMsgs int64 `json:"out_client_msgs"` // OutClientMsgs is the number of messages this server sent to the clients
1276 OutClientBytes int64 `json:"out_client_bytes"` // OutClientBytes is the number of bytes this server sent to the clients
1277 SlowConsumers int64 `json:"slow_consumers"` // SlowConsumers is the total count of clients that were disconnected since start due to being slow consumers
1278 StaleConnections int64 `json:"stale_connections"` // StaleConnections is the total count of stale connections that were detected
1279 StalledClients int64 `json:"stalled_clients"` // StalledClients is the total number of times that clients have been stalled.
1280 Subscriptions uint32 `json:"subscriptions"` // Subscriptions is the count of active subscriptions
1281 HTTPReqStats map[string]uint64 `json:"http_req_stats"` // HTTPReqStats is the number of requests each HTTP endpoint received
1282 ConfigLoadTime time.Time `json:"config_load_time"` // ConfigLoadTime is the time the configuration was loaded or reloaded
1283 ConfigDigest string `json:"config_digest"` // ConfigDigest is a calculated hash of the current configuration
1284 Tags jwt.TagList `json:"tags,omitempty"` // Tags are the tags assigned to the server in configuration
1285 Metadata map[string]string `json:"metadata,omitempty"` // Metadata is the metadata assigned to the server in configuration
1286 FeatureFlags map[string]bool `json:"feature_flags,omitempty"` // FeatureFlags is the feature flags enabled/disabled in configuration
1287 TrustedOperatorsJwt []string `json:"trusted_operators_jwt,omitempty"` // TrustedOperatorsJwt is the JWTs for all trusted operators
1288 TrustedOperatorsClaim []*jwt.OperatorClaims `json:"trusted_operators_claim,omitempty"` // TrustedOperatorsClaim is the decoded claims for each trusted operator
1289 SystemAccount string `json:"system_account,omitempty"` // SystemAccount is the name of the System account
1290 PinnedAccountFail uint64 `json:"pinned_account_fails,omitempty"` // PinnedAccountFail is how often user logon fails due to the issuer account not being pinned.
1291 OCSPResponseCache *OCSPResponseCacheVarz `json:"ocsp_peer_cache,omitempty"` // OCSPResponseCache is the state of the OCSP cache
1292 SlowConsumersStats *SlowConsumersStats `json:"slow_consumer_stats"` // SlowConsumersStats are statistics about all detected Slow Consumer
1293 StaleConnectionStats *StaleConnectionStats `json:"stale_connection_stats,omitempty"` // StaleConnectionStats are statistics about all detected Stale Connections
1294 DiskIOWaitStats *DiskIOWaitStats `json:"disk_io_wait_stats"` // DiskIOWaitStats are statistics about disk I/O semaphore contention
1295 Proxies *ProxiesOptsVarz `json:"proxies,omitempty"` // Proxies hold information about network proxy devices
1296 TLSCertNotAfter time.Time `json:"tls_cert_not_after,omitzero"` // TLSCertNotAfter is the expiration date of the TLS certificate of this server
1297 }
1298
1299 // JetStreamVarz contains basic runtime information about jetstream
1300 type JetStreamVarz struct {
1301 Config *JetStreamConfig `json:"config,omitempty"` // Config is the active JetStream configuration
1302 Stats *JetStreamStats `json:"stats,omitempty"` // Stats is the statistics for the JetStream server
1303 Meta *MetaClusterInfo `json:"meta,omitempty"` // Meta is information about the JetStream metalayer
1304 Limits *JSLimitOpts `json:"limits,omitempty"` // Limits are the configured JetStream limits
1305 }
1306
1307 // ClusterOptsVarz contains monitoring cluster information
1308 type ClusterOptsVarz struct {
1309 Name string `json:"name,omitempty"` // Name is the configured cluster name
1310 Host string `json:"addr,omitempty"` // Host is the host the cluster listens on for connections
1311 Port int `json:"cluster_port,omitempty"` // Port is the port the cluster listens on for connections
1312 AuthTimeout float64 `json:"auth_timeout,omitempty"` // AuthTimeout is the time cluster connections have to complete authentication
1313 URLs []string `json:"urls,omitempty"` // URLs is the list of cluster URLs
1314 TLSTimeout float64 `json:"tls_timeout,omitempty"` // TLSTimeout is how long TLS operations have to complete
1315 TLSRequired bool `json:"tls_required,omitempty"` // TLSRequired indicates if TLS is required for connections
1316 TLSVerify bool `json:"tls_verify,omitempty"` // TLSVerify indicates if full verification of TLS connections is performed
1317 PoolSize int `json:"pool_size,omitempty"` // PoolSize is the configured route connection pool size
1318 WriteDeadline time.Duration `json:"write_deadline,omitempty"` // WriteDeadline is the maximum time writes to sockets have to complete
1319 WriteTimeout string `json:"write_timeout,omitempty"` // WriteTimeout is the closure policy for write deadline errors
1320 TLSCertNotAfter time.Time `json:"tls_cert_not_after,omitzero"` // TLSCertNotAfter is the expiration date of the TLS certificate
1321 }
1322
1323 // GatewayOptsVarz contains monitoring gateway information
1324 type GatewayOptsVarz struct {
1325 Name string `json:"name,omitempty"` // Name is the configured cluster name
1326 Host string `json:"host,omitempty"` // Host is the host the gateway listens on for connections
1327 Port int `json:"port,omitempty"` // Port is the post gateway connections listens on
1328 AuthTimeout float64 `json:"auth_timeout,omitempty"` // AuthTimeout is the time cluster connections have to complete authentication
1329 TLSTimeout float64 `json:"tls_timeout,omitempty"` // TLSTimeout is how long TLS operations have to complete
1330 TLSRequired bool `json:"tls_required,omitempty"` // TLSRequired indicates if TLS is required for connections
1331 TLSVerify bool `json:"tls_verify,omitempty"` // TLSVerify indicates if full verification of TLS connections is performed
1332 Advertise string `json:"advertise,omitempty"` // Advertise is the URL advertised to remote gateway clients
1333 ConnectRetries int `json:"connect_retries,omitempty"` // ConnectRetries is how many connection attempts the route will make
1334 Gateways []RemoteGatewayOptsVarz `json:"gateways,omitempty"` // Gateways is state of configured gateway remotes
1335 RejectUnknown bool `json:"reject_unknown,omitempty"` // RejectUnknown indicates if unknown cluster connections will be rejected
1336 WriteDeadline time.Duration `json:"write_deadline,omitempty"` // WriteDeadline is the maximum time writes to sockets have to complete
1337 WriteTimeout string `json:"write_timeout,omitempty"` // WriteTimeout is the closure policy for write deadline errors
1338 TLSCertNotAfter time.Time `json:"tls_cert_not_after,omitzero"` // TLSCertNotAfter is the expiration date of the TLS certificaet
1339 }
1340
1341 // RemoteGatewayOptsVarz contains monitoring remote gateway information
1342 type RemoteGatewayOptsVarz struct {
1343 Name string `json:"name"` // Name is the name of the remote gateway
1344 TLSTimeout float64 `json:"tls_timeout,omitempty"` // TLSTimeout is how long TLS operations have to complete
1345 URLs []string `json:"urls,omitempty"` // URLs is the list of Gateway URLs
1346 }
1347
1348 // LeafNodeOptsVarz contains monitoring leaf node information
1349 type LeafNodeOptsVarz struct {
1350 Host string `json:"host,omitempty"` // Host is the host the server listens on
1351 Port int `json:"port,omitempty"` // Port is the port the server listens on
1352 AuthTimeout float64 `json:"auth_timeout,omitempty"` // AuthTimeout is the time Leafnode connections have to complete authentication
1353 TLSTimeout float64 `json:"tls_timeout,omitempty"` // TLSTimeout is how long TLS operations have to complete
1354 TLSRequired bool `json:"tls_required,omitempty"` // TLSRequired indicates if TLS is required for connections
1355 TLSVerify bool `json:"tls_verify,omitempty"` // TLSVerify indicates if full verification of TLS connections is performed
1356 Remotes []RemoteLeafOptsVarz `json:"remotes,omitempty"` // Remotes is state of configured Leafnode remotes
1357 TLSOCSPPeerVerify bool `json:"tls_ocsp_peer_verify,omitempty"` // TLSOCSPPeerVerify indicates if OCSP verification will be performed
1358 WriteDeadline time.Duration `json:"write_deadline,omitempty"` // WriteDeadline is the maximum time writes to sockets have to complete
1359 WriteTimeout string `json:"write_timeout,omitempty"` // WriteTimeout is the closure policy for write deadline errors
1360 TLSCertNotAfter time.Time `json:"tls_cert_not_after,omitzero"` // TLSCertNotAfter is the expiration date of the TLS certificate
1361 }
1362
1363 // DenyRules Contains lists of subjects not allowed to be imported/exported
1364 type DenyRules struct {
1365 Exports []string `json:"exports,omitempty"` // Exports are denied exports
1366 Imports []string `json:"imports,omitempty"` // Imports are denied imports
1367 }
1368
1369 // RemoteLeafOptsVarz contains monitoring remote leaf node information
1370 type RemoteLeafOptsVarz struct {
1371 LocalAccount string `json:"local_account,omitempty"` // LocalAccount is the local account this leaf is logged into
1372 TLSTimeout float64 `json:"tls_timeout,omitempty"` // TLSTimeout is how long TLS operations have to complete
1373 URLs []string `json:"urls,omitempty"` // URLs is the list of URLs for the remote Leafnode connection
1374 Deny *DenyRules `json:"deny,omitempty"` // Deny is the configured import and exports that the Leafnode may not access
1375 TLSOCSPPeerVerify bool `json:"tls_ocsp_peer_verify,omitempty"` // TLSOCSPPeerVerify indicates if OCSP verification will be done
1376 }
1377
1378 // MQTTOptsVarz contains monitoring MQTT information
1379 type MQTTOptsVarz struct {
1380 Host string `json:"host,omitempty"` // Host is the host the server listens on
1381 Port int `json:"port,omitempty"` // Port is the port the server listens on
1382 NoAuthUser string `json:"no_auth_user,omitempty"` // NoAuthUser is the user that will be used for unauthenticated connections
1383 AuthTimeout float64 `json:"auth_timeout,omitempty"` // AuthTimeout is how long authentication has to complete
1384 TLSMap bool `json:"tls_map,omitempty"` // TLSMap indicates if TLS Mapping is enabled
1385 TLSTimeout float64 `json:"tls_timeout,omitempty"` // TLSTimeout is how long TLS operations have to complete
1386 TLSPinnedCerts []string `json:"tls_pinned_certs,omitempty"` // TLSPinnedCerts is the list of certificates pinned to this connection
1387 JsDomain string `json:"js_domain,omitempty"` // JsDomain is the JetStream domain used for MQTT state
1388 AckWait time.Duration `json:"ack_wait,omitempty"` // AckWait is how long the internal JetStream state store will allow acks to complete
1389 MaxAckPending uint16 `json:"max_ack_pending,omitempty"` // MaxAckPending is how many outstanding acks the internal JetStream state store will allow
1390 TLSOCSPPeerVerify bool `json:"tls_ocsp_peer_verify,omitempty"` // TLSOCSPPeerVerify indicates if OCSP verification will be done
1391 TLSCertNotAfter time.Time `json:"tls_cert_not_after,omitzero"` // TLSCertNotAfter is the expiration date of the TLS certificate
1392 }
1393
1394 // WebsocketOptsVarz contains monitoring websocket information
1395 type WebsocketOptsVarz struct {
1396 Host string `json:"host,omitempty"` // Host is the host the server listens on
1397 Port int `json:"port,omitempty"` // Port is the port the server listens on
1398 Advertise string `json:"advertise,omitempty"` // Advertise is the connection URL the server advertises
1399 NoAuthUser string `json:"no_auth_user,omitempty"` // NoAuthUser is the user that will be used for unauthenticated connections
1400 JWTCookie string `json:"jwt_cookie,omitempty"` // JWTCookie is the name of a cookie the server will read for the connection JWT
1401 HandshakeTimeout time.Duration `json:"handshake_timeout,omitempty"` // HandshakeTimeout is how long the connection has to complete the websocket setup
1402 AuthTimeout float64 `json:"auth_timeout,omitempty"` // AuthTimeout is how long authentication has to complete
1403 NoTLS bool `json:"no_tls,omitempty"` // NoTLS indicates if TLS is disabled
1404 TLSMap bool `json:"tls_map,omitempty"` // TLSMap indicates if TLS Mapping is enabled
1405 TLSPinnedCerts []string `json:"tls_pinned_certs,omitempty"` // TLSPinnedCerts is the list of certificates pinned to this connection
1406 SameOrigin bool `json:"same_origin,omitempty"` // SameOrigin indicates if same origin connections are allowed
1407 AllowedOrigins []string `json:"allowed_origins,omitempty"` // AllowedOrigins list of configured trusted origins
1408 Compression bool `json:"compression,omitempty"` // Compression indicates if compression is supported
1409 TLSOCSPPeerVerify bool `json:"tls_ocsp_peer_verify,omitempty"` // TLSOCSPPeerVerify indicates if OCSP verification will be done
1410 TLSCertNotAfter time.Time `json:"tls_cert_not_after,omitzero"` // TLSCertNotAfter is the expiration date of the TLS certificate
1411 }
1412
1413 // OCSPResponseCacheVarz contains OCSP response cache information
1414 type OCSPResponseCacheVarz struct {
1415 Type string `json:"cache_type,omitempty"` // Type is the kind of cache being used
1416 Hits int64 `json:"cache_hits,omitempty"` // Hits is how many times the cache was able to answer a request
1417 Misses int64 `json:"cache_misses,omitempty"` // Misses is how many times the cache failed to answer a request
1418 Responses int64 `json:"cached_responses,omitempty"` // Responses is how many responses are currently stored in the cache
1419 Revokes int64 `json:"cached_revoked_responses,omitempty"` // Revokes is how many of the stored cache entries are revokes
1420 Goods int64 `json:"cached_good_responses,omitempty"` // Goods is how many of the stored cache entries are good responses
1421 Unknowns int64 `json:"cached_unknown_responses,omitempty"` // Unknowns is how many of the stored cache entries are unknown responses
1422 }
1423
1424 // ProxiesOptsVarz contains proxies information
1425 type ProxiesOptsVarz struct {
1426 Trusted []*ProxyOptsVarz `json:"trusted,omitempty"` // Trusted holds a list of trusted proxies
1427 }
1428
1429 // ProxyOptsVarz contains proxy information
1430 type ProxyOptsVarz struct {
1431 Key string `json:"key"` // Key is the public key of the proxy
1432 }
1433
1434 // VarzOptions are the options passed to Varz().
1435 // Currently, there are no options defined.
1436 type VarzOptions struct{}
1437
1438 // SlowConsumersStats contains information about the slow consumers from different type of connections.
1439 type SlowConsumersStats struct {
1440 Clients uint64 `json:"clients"` // Clients is how many Clients were slow consumers
1441 Routes uint64 `json:"routes"` // Routes is how many Routes were slow consumers
1442 Gateways uint64 `json:"gateways"` // Gateways is how many Gateways were slow consumers
1443 Leafs uint64 `json:"leafs"` // Leafs is how many Leafnodes were slow consumers
1444 }
1445
1446 // StaleConnectionStats contains information about the stale connections from different type of connections.
1447 type StaleConnectionStats struct {
1448 Clients uint64 `json:"clients"` // Clients is how many Client connections became stale connections
1449 Routes uint64 `json:"routes"` // Routes is how many Route connections became stale connections
1450 Gateways uint64 `json:"gateways"` // Gateways is how many Gateway connections became stale connections
1451 Leafs uint64 `json:"leafs"` // Leafs is how many Leafnode connections became stale connections
1452 }
1453
1454 // DiskIOWaitStats contains information about disk I/O semaphore contention.
1455 type DiskIOWaitStats struct {
1456 Waiters int64 `json:"waiters"` // Waiters is the number of goroutines waiting on the dios
1457 Waits uint64 `json:"waits"` // Waits is the number of dios acquires that had to wait
1458 WaitTime uint64 `json:"wait_time"` // WaitTime is the cumulative time spent waiting for dios
1459 MaxWaitTime uint64 `json:"max_wait_time"` // MaxWaitTime is the longest observed wait
1460 }
1461
1462 func myUptime(d time.Duration) string {
1463 // Just use total seconds for uptime, and display days / years
1464 tsecs := d / time.Second
1465 tmins := tsecs / 60
1466 thrs := tmins / 60
1467 tdays := thrs / 24
1468 tyrs := tdays / 365
1469
1470 if tyrs > 0 {
1471 return fmt.Sprintf("%dy%dd%dh%dm%ds", tyrs, tdays%365, thrs%24, tmins%60, tsecs%60)
1472 }
1473 if tdays > 0 {
1474 return fmt.Sprintf("%dd%dh%dm%ds", tdays, thrs%24, tmins%60, tsecs%60)
1475 }
1476 if thrs > 0 {
1477 return fmt.Sprintf("%dh%dm%ds", thrs, tmins%60, tsecs%60)
1478 }
1479 if tmins > 0 {
1480 return fmt.Sprintf("%dm%ds", tmins, tsecs%60)
1481 }
1482 return fmt.Sprintf("%ds", tsecs)
1483 }
1484
1485 func tlsCertNotAfter(config *tls.Config) time.Time {
1486 if config == nil || len(config.Certificates) == 0 {
1487 return time.Time{}
1488 }
1489 cert := config.Certificates[0]
1490 leaf := cert.Leaf
1491 if leaf == nil {
1492 var err error
1493 leaf, err = x509.ParseCertificate(cert.Certificate[0])
1494 if err != nil {
1495 return time.Time{}
1496 }
1497 }
1498 return leaf.NotAfter
1499 }
1500
1501 // HandleRoot will show basic info and links to others handlers.
1502 func (s *Server) HandleRoot(w http.ResponseWriter, r *http.Request) {
1503 // This feels dumb to me, but is required: https://code.google.com/p/go/issues/detail?id=4799
1504 if r.URL.Path != s.httpBasePath {
1505 http.NotFound(w, r)
1506 return
1507 }
1508 s.mu.Lock()
1509 s.httpReqStats[RootPath]++
1510 s.mu.Unlock()
1511
1512 // Calculate source url. If git set go directly to that tag, otherwise just main.
1513 var srcUrl string
1514 if gitCommit == _EMPTY_ {
1515 srcUrl = "https://github.com/nats-io/nats-server"
1516 } else if serverVersion != _EMPTY_ {
1517 srcUrl = fmt.Sprintf("https://github.com/nats-io/nats-server/tree/%s", serverVersion)
1518 } else {
1519 srcUrl = fmt.Sprintf("https://github.com/nats-io/nats-server/tree/%s", gitCommit)
1520 }
1521
1522 fmt.Fprintf(w, `<html lang="en">
1523 <head>
1524 <link rel="shortcut icon" href="https://nats.io/favicon.ico">
1525 <style type="text/css">
1526 body { font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif; font-size: 18; font-weight: light-bold; margin-left: 32px }
1527 a { display:block; margin-left: 7px; padding-bottom: 6px; color: rgb(72 72 92); text-decoration: none }
1528 a:hover { font-weight: 600; color: rgb(59 50 202) }
1529 a.help { display:inline; font-weight: 600; color: rgb(59 50 202); font-size: 20}
1530 a.last { padding-bottom: 16px }
1531 a.version { font-size: 14; font-weight: 400; width: 312px; text-align: right; margin-top: -2rem }
1532 a.version:hover { color: rgb(22 22 32) }
1533 .endpoint { font-size: 12px; color: #999; font-family: monospace; display: none }
1534 a:hover .endpoint { display: inline }
1535
1536 </style>
1537 </head>
1538 <body>
1539 <svg xmlns="http://www.w3.org/2000/svg" role="img" width="325" height="110" viewBox="-4.14 -3.89 436.28 119.03"><style>.st1{fill:#fff}.st2{fill:#34a574}</style><path fill="#27aae1" d="M4.3 84.6h42.2L70.7 107V84.6H103v-80H4.3v80zm15.9-61.3h18.5l35.6 33.2V23.3h11.8v42.9H68.2L32 32.4v33.8H20.2V23.3z"/><path d="M32 32.4l36.2 33.8h17.9V23.3H74.3v33.2L38.7 23.3H20.2v42.9H32z" class="st1"/><path d="M159.8 30.7L147 49h25.6z" class="st2"/><path d="M111.3 84.6H210v-80h-98.7v80zm41-61.5H168l30.8 43.2h-14.1l-5.8-8.3h-38.1l-5.8 8.3h-13.5l30.8-43.2z" class="st2"/><path d="M140.8 57.9h38.1l5.8 8.3h14.1L168 23.1h-15.7l-30.8 43.2H135l5.8-8.4zm19-27.2L172.6 49H147l12.8-18.3z" class="st1"/><path fill="#375c93" d="M218.3 84.6H317v-80h-98.7v80zm15.5-61.3h66.7V33h-27.2v33.2h-12.2V33h-27.3v-9.7z"/><path d="M261.1 66.2h12.2V33h27.2v-9.7h-66.7V33h27.3z" class="st1"/><path fill="#8dc63f" d="M325.3 4.6v80H424v-80h-98.7zm76.5 56.7c-3.2 3.2-10.2 5.7-26.8 5.7-12.3 0-24.1-1.9-30.7-4.7v-10c6.3 2.8 20.1 5.5 30.7 5.5 9.3 0 15.8-.3 17.5-2.1.6-.6.7-1.3.7-2 0-.8-.2-1.3-.7-1.8-1-1-2.6-1.7-17.4-2.1-15.7-.4-23.4-2-27-5.6-1.7-1.7-2.6-4.4-2.6-7.5 0-3.3.6-6.2 3.3-8.9 3.6-3.6 10.7-5.3 25.1-5.3 10.8 0 21.6 1.7 27.3 4v10.1c-6.5-2.8-17.8-4.8-27.2-4.8-10.4 0-14.8.6-16.2 2-.5.5-.8 1.1-.8 1.9 0 .9.2 1.5.7 2 1.3 1.3 6.1 1.7 17.3 1.9 16.4.4 23.5 1.8 27 5.2 1.8 1.8 2.8 4.7 2.8 7.7.1 3.2-.6 6.4-3 8.8z"/><path d="M375.2 39.5c-11.2-.2-16-.6-17.3-1.9-.5-.5-.7-1.1-.7-2 0-.8.3-1.4.8-1.9 1.3-1.3 5.8-2 16.2-2 9.4 0 20.7 2 27.2 4.8v-10c-5.7-2.3-16.6-4-27.3-4-14.5 0-21.6 1.8-25.1 5.3-2.7 2.7-3.3 5.6-3.3 8.9 0 3.1 1 5.8 2.6 7.5 3.6 3.6 11.3 5.2 27 5.6 14.8.4 16.4 1.1 17.4 2.1.5.5.7 1 .7 1.8 0 .7-.1 1.3-.7 2-1.8 1.8-8.3 2.1-17.5 2.1-10.6 0-24.3-2.6-30.7-5.5v10.1c6.6 2.8 18.4 4.7 30.7 4.7 16.6 0 23.6-2.5 26.8-5.7 2.4-2.4 3.1-5.6 3.1-8.9 0-3.1-1-5.9-2.8-7.7-3.6-3.5-10.7-4.9-27.1-5.3z" class="st1"/></svg>
1540
1541 <a href=%s class='version'>v%s</a>
1542
1543 </div>
1544 <br/>
1545 <a href=.%s>General<span class="endpoint"> %s</span></a>
1546 <a href=.%s>JetStream<span class="endpoint"> %s</span></a>
1547 <a href=.%s>Connections<span class="endpoint"> %s</span></a>
1548 <a href=.%s>Accounts<span class="endpoint"> %s</span></a>
1549 <a href=.%s>Account Stats<span class="endpoint"> %s</span></a>
1550 <a href=.%s>Subscriptions<span class="endpoint"> %s</span></a>
1551 <a href=.%s>Routes<span class="endpoint"> %s</span></a>
1552 <a href=.%s>LeafNodes<span class="endpoint"> %s</span></a>
1553 <a href=.%s>Gateways<span class="endpoint"> %s</span></a>
1554 <a href=.%s>Raft Groups<span class="endpoint"> %s</span></a>
1555 <a href=.%s>Health Probe<span class="endpoint"> %s</span></a>
1556 <a href=.%s class=last>Expvar<span class="endpoint"> %s</span></a>
1557 <a href=https://docs.nats.io/running-a-nats-service/nats_admin/monitoring class="help">Help</a>
1558 </body>
1559 </html>`,
1560 srcUrl,
1561 VERSION,
1562 s.basePath(VarzPath), VarzPath,
1563 s.basePath(JszPath), JszPath,
1564 s.basePath(ConnzPath), ConnzPath,
1565 s.basePath(AccountzPath), AccountzPath,
1566 s.basePath(AccountStatzPath), AccountStatzPath,
1567 s.basePath(SubszPath), SubszPath,
1568 s.basePath(RoutezPath), RoutezPath,
1569 s.basePath(LeafzPath), LeafzPath,
1570 s.basePath(GatewayzPath), GatewayzPath,
1571 s.basePath(RaftzPath), RaftzPath,
1572 s.basePath(HealthzPath), HealthzPath,
1573 s.basePath(ExpvarzPath), ExpvarzPath,
1574 )
1575 }
1576
1577 func (s *Server) updateJszVarz(js *jetStream, v *JetStreamVarz, doConfig bool) {
1578 if doConfig {
1579 js.mu.RLock()
1580 // We want to snapshot the config since it will then be available outside
1581 // of the js lock. So make a copy first, then point to this copy.
1582 cfg := js.config
1583 v.Config = &cfg
1584 js.mu.RUnlock()
1585 }
1586 v.Stats = js.usageStats()
1587 v.Limits = &s.getOpts().JetStreamLimits
1588 if mg := js.getMetaGroup(); mg != nil {
1589 if ci := s.raftNodeToClusterInfo(mg); ci != nil {
1590 v.Meta = &MetaClusterInfo{Name: ci.Name, Leader: ci.Leader, Peer: getHash(ci.Leader), Size: mg.ClusterSize()}
1591 if ci.Leader == s.info.Name {
1592 v.Meta.Replicas = ci.Replicas
1593 }
1594 if ipq := s.jsAPIRoutedReqs; ipq != nil {
1595 v.Meta.PendingRequests = ipq.len()
1596 }
1597 if ipq := s.jsAPIRoutedInfoReqs; ipq != nil {
1598 v.Meta.PendingInfos = ipq.len()
1599 }
1600 v.Meta.Pending = v.Meta.PendingRequests + v.Meta.PendingInfos
1601 v.Meta.Snapshot = s.metaClusterSnapshotStats(js, mg)
1602 }
1603 }
1604 }
1605
1606 // Varz returns a Varz struct containing the server information.
1607 func (s *Server) Varz(varzOpts *VarzOptions) (*Varz, error) {
1608 var rss, vss int64
1609 var pcpu float64
1610
1611 // We want to do that outside of the lock.
1612 pse.ProcUsage(&pcpu, &rss, &vss)
1613
1614 s.mu.RLock()
1615 // We need to create a new instance of Varz (with no reference
1616 // whatsoever to anything stored in the server) since the user
1617 // has access to the returned value.
1618 v := s.createVarz(pcpu, rss)
1619 s.mu.RUnlock()
1620
1621 if js := s.getJetStream(); js != nil {
1622 s.updateJszVarz(js, &v.JetStream, true)
1623 }
1624
1625 return v, nil
1626 }
1627
1628 // Returns a Varz instance.
1629 // Server lock is held on entry.
1630 func (s *Server) createVarz(pcpu float64, rss int64) *Varz {
1631 info := s.info
1632 opts := s.getOpts()
1633 c := &opts.Cluster
1634 gw := &opts.Gateway
1635 ln := &opts.LeafNode
1636 mqtt := &opts.MQTT
1637 ws := &opts.Websocket
1638 clustTlsReq := c.TLSConfig != nil
1639 gatewayTlsReq := gw.TLSConfig != nil
1640 leafTlsReq := ln.TLSConfig != nil
1641 leafTlsVerify := leafTlsReq && ln.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert
1642 leafTlsOCSPPeerVerify := s.ocspPeerVerify && leafTlsReq && ln.tlsConfigOpts.OCSPPeerConfig != nil && ln.tlsConfigOpts.OCSPPeerConfig.Verify
1643 mqttTlsOCSPPeerVerify := s.ocspPeerVerify && mqtt.TLSConfig != nil && mqtt.tlsConfigOpts.OCSPPeerConfig != nil && mqtt.tlsConfigOpts.OCSPPeerConfig.Verify
1644 wsTlsOCSPPeerVerify := s.ocspPeerVerify && ws.TLSConfig != nil && ws.tlsConfigOpts.OCSPPeerConfig != nil && ws.tlsConfigOpts.OCSPPeerConfig.Verify
1645 varz := &Varz{
1646 ID: info.ID,
1647 Version: info.Version,
1648 Proto: info.Proto,
1649 GitCommit: info.GitCommit,
1650 GoVersion: info.GoVersion,
1651 Name: info.Name,
1652 Host: info.Host,
1653 Port: info.Port,
1654 IP: info.IP,
1655 HTTPHost: opts.HTTPHost,
1656 HTTPPort: opts.HTTPPort,
1657 HTTPBasePath: opts.HTTPBasePath,
1658 HTTPSPort: opts.HTTPSPort,
1659 Cluster: ClusterOptsVarz{
1660 Name: info.Cluster,
1661 Host: c.Host,
1662 Port: c.Port,
1663 AuthTimeout: c.AuthTimeout,
1664 TLSTimeout: c.TLSTimeout,
1665 TLSRequired: clustTlsReq,
1666 TLSVerify: clustTlsReq,
1667 PoolSize: opts.Cluster.PoolSize,
1668 WriteDeadline: opts.Cluster.WriteDeadline,
1669 WriteTimeout: opts.Cluster.WriteTimeout.String(),
1670 },
1671 Gateway: GatewayOptsVarz{
1672 Name: gw.Name,
1673 Host: gw.Host,
1674 Port: gw.Port,
1675 AuthTimeout: gw.AuthTimeout,
1676 TLSTimeout: gw.TLSTimeout,
1677 TLSRequired: gatewayTlsReq,
1678 TLSVerify: gatewayTlsReq,
1679 Advertise: gw.Advertise,
1680 ConnectRetries: gw.ConnectRetries,
1681 Gateways: []RemoteGatewayOptsVarz{},
1682 RejectUnknown: gw.RejectUnknown,
1683 WriteDeadline: opts.Cluster.WriteDeadline,
1684 WriteTimeout: opts.Cluster.WriteTimeout.String(),
1685 },
1686 LeafNode: LeafNodeOptsVarz{
1687 Host: ln.Host,
1688 Port: ln.Port,
1689 AuthTimeout: ln.AuthTimeout,
1690 TLSTimeout: ln.TLSTimeout,
1691 TLSRequired: leafTlsReq,
1692 TLSVerify: leafTlsVerify,
1693 TLSOCSPPeerVerify: leafTlsOCSPPeerVerify,
1694 Remotes: []RemoteLeafOptsVarz{},
1695 WriteDeadline: opts.Cluster.WriteDeadline,
1696 WriteTimeout: opts.Cluster.WriteTimeout.String(),
1697 },
1698 MQTT: MQTTOptsVarz{
1699 Host: mqtt.Host,
1700 Port: mqtt.Port,
1701 NoAuthUser: mqtt.NoAuthUser,
1702 AuthTimeout: mqtt.AuthTimeout,
1703 TLSMap: mqtt.TLSMap,
1704 TLSTimeout: mqtt.TLSTimeout,
1705 JsDomain: mqtt.JsDomain,
1706 AckWait: mqtt.AckWait,
1707 MaxAckPending: mqtt.MaxAckPending,
1708 TLSOCSPPeerVerify: mqttTlsOCSPPeerVerify,
1709 },
1710 Websocket: WebsocketOptsVarz{
1711 Host: ws.Host,
1712 Port: ws.Port,
1713 Advertise: ws.Advertise,
1714 NoAuthUser: ws.NoAuthUser,
1715 JWTCookie: ws.JWTCookie,
1716 AuthTimeout: ws.AuthTimeout,
1717 NoTLS: ws.NoTLS,
1718 TLSMap: ws.TLSMap,
1719 SameOrigin: ws.SameOrigin,
1720 AllowedOrigins: copyStrings(ws.AllowedOrigins),
1721 Compression: ws.Compression,
1722 HandshakeTimeout: ws.HandshakeTimeout,
1723 TLSOCSPPeerVerify: wsTlsOCSPPeerVerify,
1724 },
1725 Start: s.start.UTC(),
1726 MaxSubs: opts.MaxSubs,
1727 Cores: runtime.NumCPU(),
1728 MaxProcs: runtime.GOMAXPROCS(0),
1729 TrustedOperatorsJwt: opts.operatorJWT,
1730 TrustedOperatorsClaim: opts.TrustedOperators,
1731 }
1732 if mm := debug.SetMemoryLimit(-1); mm < math.MaxInt64 {
1733 varz.MemLimit = mm
1734 }
1735 // If this is a leaf without cluster, reset the cluster name (that is otherwise
1736 // set to the server name).
1737 if s.leafNoCluster {
1738 varz.Cluster.Name = _EMPTY_
1739 }
1740 if len(opts.Routes) > 0 {
1741 varz.Cluster.URLs = urlsToStrings(opts.Routes)
1742 }
1743 if l := len(gw.Gateways); l > 0 {
1744 rgwa := make([]RemoteGatewayOptsVarz, l)
1745 for i, r := range gw.Gateways {
1746 rgwa[i] = RemoteGatewayOptsVarz{
1747 Name: r.Name,
1748 TLSTimeout: r.TLSTimeout,
1749 }
1750 }
1751 varz.Gateway.Gateways = rgwa
1752 }
1753 // Finish setting it up with fields that can be updated during
1754 // configuration reload and runtime.
1755 s.updateVarzConfigReloadableFields(varz)
1756 s.updateVarzRuntimeFields(varz, true, pcpu, rss)
1757 return varz
1758 }
1759
1760 // Builds the list of remote leafnodes for Varz from the given options.
1761 // Server lock is held on entry.
1762 func (s *Server) varzLeafNodeRemotes(opts *Options) []RemoteLeafOptsVarz {
1763 l := len(opts.LeafNode.Remotes)
1764 if l == 0 {
1765 return nil
1766 }
1767 rlna := make([]RemoteLeafOptsVarz, l)
1768 for i, r := range opts.LeafNode.Remotes {
1769 var deny *DenyRules
1770 if len(r.DenyImports) > 0 || len(r.DenyExports) > 0 {
1771 deny = &DenyRules{
1772 Imports: r.DenyImports,
1773 Exports: r.DenyExports,
1774 }
1775 }
1776 remoteTlsOCSPPeerVerify := s.ocspPeerVerify && r.tlsConfigOpts != nil && r.tlsConfigOpts.OCSPPeerConfig != nil && r.tlsConfigOpts.OCSPPeerConfig.Verify
1777
1778 rlna[i] = RemoteLeafOptsVarz{
1779 LocalAccount: r.LocalAccount,
1780 URLs: urlsToStrings(r.URLs),
1781 TLSTimeout: r.TLSTimeout,
1782 Deny: deny,
1783 TLSOCSPPeerVerify: remoteTlsOCSPPeerVerify,
1784 }
1785 }
1786 return rlna
1787 }
1788
1789 func urlsToStrings(urls []*url.URL) []string {
1790 sURLs := make([]string, len(urls))
1791 for i, u := range urls {
1792 sURLs[i] = u.Host
1793 }
1794 return sURLs
1795 }
1796
1797 // Invoked during configuration reload once options have possibly be changed
1798 // and config load time has been set. If s.varz has not been initialized yet
1799 // (because no pooling of /varz has been made), this function does nothing.
1800 // Server lock is held on entry.
1801 func (s *Server) updateVarzConfigReloadableFields(v *Varz) {
1802 if v == nil {
1803 return
1804 }
1805 opts := s.getOpts()
1806 info := &s.info
1807 v.AuthRequired = info.AuthRequired
1808 v.TLSRequired = info.TLSRequired
1809 v.TLSVerify = info.TLSVerify
1810 v.MaxConn = opts.MaxConn
1811 v.PingInterval = opts.PingInterval
1812 v.MaxPingsOut = opts.MaxPingsOut
1813 v.AuthTimeout = opts.AuthTimeout
1814 v.MaxControlLine = opts.MaxControlLine
1815 v.MaxPayload = int(opts.MaxPayload)
1816 v.MaxPending = opts.MaxPending
1817 v.TLSTimeout = opts.TLSTimeout
1818 v.WriteDeadline = opts.WriteDeadline
1819 v.WriteTimeout = opts.WriteTimeout.String()
1820 v.ConfigLoadTime = s.configTime.UTC()
1821 v.ConfigDigest = opts.configDigest
1822 v.Tags = opts.Tags
1823 v.Metadata = opts.Metadata
1824 v.FeatureFlags = opts.getMergedFeatureFlags()
1825 // Update route URLs if applicable
1826 if s.varzUpdateRouteURLs {
1827 v.Cluster.URLs = urlsToStrings(opts.Routes)
1828 s.varzUpdateRouteURLs = false
1829 }
1830 if s.sys != nil && s.sys.account != nil {
1831 v.SystemAccount = s.sys.account.GetName()
1832 }
1833 v.MQTT.TLSPinnedCerts = getPinnedCertsAsSlice(opts.MQTT.TLSPinnedCerts)
1834 v.Websocket.TLSPinnedCerts = getPinnedCertsAsSlice(opts.Websocket.TLSPinnedCerts)
1835
1836 v.TLSOCSPPeerVerify = s.ocspPeerVerify && v.TLSRequired && s.opts.tlsConfigOpts != nil && s.opts.tlsConfigOpts.OCSPPeerConfig != nil && s.opts.tlsConfigOpts.OCSPPeerConfig.Verify
1837
1838 v.TLSCertNotAfter = tlsCertNotAfter(opts.TLSConfig)
1839 v.Cluster.TLSCertNotAfter = tlsCertNotAfter(opts.Cluster.TLSConfig)
1840 v.Gateway.TLSCertNotAfter = tlsCertNotAfter(opts.Gateway.TLSConfig)
1841 v.LeafNode.TLSCertNotAfter = tlsCertNotAfter(opts.LeafNode.TLSConfig)
1842 v.LeafNode.Remotes = s.varzLeafNodeRemotes(opts)
1843 v.MQTT.TLSCertNotAfter = tlsCertNotAfter(opts.MQTT.TLSConfig)
1844 v.Websocket.TLSCertNotAfter = tlsCertNotAfter(opts.Websocket.TLSConfig)
1845
1846 if opts.Proxies != nil {
1847 if v.Proxies == nil {
1848 v.Proxies = &ProxiesOptsVarz{}
1849 }
1850 trusted := make([]*ProxyOptsVarz, 0, len(opts.Proxies.Trusted))
1851 for _, t := range opts.Proxies.Trusted {
1852 trusted = append(trusted, &ProxyOptsVarz{Key: t.Key})
1853 }
1854 v.Proxies.Trusted = trusted
1855 } else {
1856 v.Proxies = nil
1857 }
1858
1859 if cfg := v.JetStream.Config; cfg != nil {
1860 if opts.JetStreamMaxMemory > 0 {
1861 cfg.MaxMemory = opts.JetStreamMaxMemory
1862 }
1863 if opts.JetStreamMaxStore > 0 {
1864 cfg.MaxStore = opts.JetStreamMaxStore
1865 }
1866 }
1867 }
1868
1869 func getPinnedCertsAsSlice(certs PinnedCertSet) []string {
1870 if len(certs) == 0 {
1871 return nil
1872 }
1873 res := make([]string, 0, len(certs))
1874 for cn := range certs {
1875 res = append(res, cn)
1876 }
1877 return res
1878 }
1879
1880 // Updates the runtime Varz fields, that is, fields that change during
1881 // runtime and that should be updated any time Varz() or polling of /varz
1882 // is done.
1883 // Server lock is held on entry.
1884 func (s *Server) updateVarzRuntimeFields(v *Varz, forceUpdate bool, pcpu float64, rss int64) {
1885 v.Now = time.Now().UTC()
1886 v.Uptime = myUptime(time.Since(s.start))
1887 v.Mem = rss
1888 v.CPU = pcpu
1889 if l := len(s.info.ClientConnectURLs); l > 0 {
1890 v.ClientConnectURLs = append([]string(nil), s.info.ClientConnectURLs...)
1891 }
1892 if l := len(s.info.WSConnectURLs); l > 0 {
1893 v.WSConnectURLs = append([]string(nil), s.info.WSConnectURLs...)
1894 }
1895 v.Connections = len(s.clients)
1896 v.TotalConnections = s.totalClients
1897 v.Routes = s.numRoutes()
1898 v.Remotes = s.numRemotes()
1899 v.Leafs = len(s.leafs)
1900 v.InMsgs = atomic.LoadInt64(&s.inMsgs)
1901 v.InBytes = atomic.LoadInt64(&s.inBytes)
1902 v.OutMsgs = atomic.LoadInt64(&s.outMsgs)
1903 v.OutBytes = atomic.LoadInt64(&s.outBytes)
1904 v.InClientMsgs = atomic.LoadInt64(&s.inClientMsgs)
1905 v.InClientBytes = atomic.LoadInt64(&s.inClientBytes)
1906 v.OutClientMsgs = atomic.LoadInt64(&s.outClientMsgs)
1907 v.OutClientBytes = atomic.LoadInt64(&s.outClientBytes)
1908 v.SlowConsumers = atomic.LoadInt64(&s.slowConsumers)
1909 v.StalledClients = atomic.LoadInt64(&s.stalls)
1910 v.SlowConsumersStats = &SlowConsumersStats{
1911 Clients: s.NumSlowConsumersClients(),
1912 Routes: s.NumSlowConsumersRoutes(),
1913 Gateways: s.NumSlowConsumersGateways(),
1914 Leafs: s.NumSlowConsumersLeafs(),
1915 }
1916 v.StaleConnections = atomic.LoadInt64(&s.staleConnections)
1917 v.StaleConnectionStats = &StaleConnectionStats{
1918 Clients: s.NumStaleConnectionsClients(),
1919 Routes: s.NumStaleConnectionsRoutes(),
1920 Gateways: s.NumStaleConnectionsGateways(),
1921 Leafs: s.NumStaleConnectionsLeafs(),
1922 }
1923 v.PinnedAccountFail = atomic.LoadUint64(&s.pinnedAccFail)
1924
1925 // Make sure to reset in case we are re-using.
1926 v.Subscriptions = 0
1927 s.accounts.Range(func(k, val any) bool {
1928 acc := val.(*Account)
1929 v.Subscriptions += acc.sl.Count()
1930 return true
1931 })
1932
1933 v.HTTPReqStats = make(map[string]uint64, len(s.httpReqStats))
1934 for key, val := range s.httpReqStats {
1935 v.HTTPReqStats[key] = val
1936 }
1937
1938 // Update Gateway remote urls if applicable
1939 gw := s.gateway
1940 gw.RLock()
1941 if gw.enabled {
1942 for i := 0; i < len(v.Gateway.Gateways); i++ {
1943 g := &v.Gateway.Gateways[i]
1944 rgw := gw.remotes[g.Name]
1945 if rgw != nil {
1946 rgw.RLock()
1947 // forceUpdate is needed if user calls Varz() programmatically,
1948 // since we need to create a new instance every time and the
1949 // gateway's varzUpdateURLs may have been set to false after
1950 // a web /varz inspection.
1951 if forceUpdate || rgw.varzUpdateURLs {
1952 // Make reuse of backend array
1953 g.URLs = g.URLs[:0]
1954 // rgw.urls is a map[string]*url.URL where the key is
1955 // already in the right format (host:port, without any
1956 // user info present).
1957 for u := range rgw.urls {
1958 g.URLs = append(g.URLs, u)
1959 }
1960 rgw.varzUpdateURLs = false
1961 }
1962 rgw.RUnlock()
1963 } else if g.Name == gw.name && len(gw.ownCfgURLs) > 0 {
1964 // This is a remote that correspond to this very same server.
1965 // We report the URLs that were configured (if any).
1966 // Since we don't support changes to the gateway configuration
1967 // at this time, we could do this only if g.URLs has not been already
1968 // set, but let's do it regardless in case we add support for
1969 // gateway config reload.
1970 g.URLs = g.URLs[:0]
1971 g.URLs = append(g.URLs, gw.ownCfgURLs...)
1972 }
1973 }
1974 }
1975 gw.RUnlock()
1976
1977 if s.ocsprc != nil && s.ocsprc.Type() != "none" {
1978 stats := s.ocsprc.Stats()
1979 if stats != nil {
1980 v.OCSPResponseCache = &OCSPResponseCacheVarz{
1981 s.ocsprc.Type(),
1982 stats.Hits,
1983 stats.Misses,
1984 stats.Responses,
1985 stats.Revokes,
1986 stats.Goods,
1987 stats.Unknowns,
1988 }
1989 }
1990 }
1991 v.DiskIOWaitStats = diskIOWaitStats(s.dios)
1992 }
1993
1994 func diskIOWaitStats(d *diskIOSemaphore) *DiskIOWaitStats {
1995 if d == nil {
1996 return &DiskIOWaitStats{}
1997 }
1998 return &DiskIOWaitStats{
1999 Waiters: d.waiters.Load(),
2000 Waits: d.waits.Load(),
2001 WaitTime: d.waitNanos.Load(),
2002 MaxWaitTime: d.maxWaitNanos.Load(),
2003 }
2004 }
2005
2006 // HandleVarz will process HTTP requests for server information.
2007 func (s *Server) HandleVarz(w http.ResponseWriter, r *http.Request) {
2008 var rss, vss int64
2009 var pcpu float64
2010
2011 // We want to do that outside of the lock.
2012 pse.ProcUsage(&pcpu, &rss, &vss)
2013
2014 // In response to http requests, we want to minimize mem copies
2015 // so we use an object stored in the server. Creating/collecting
2016 // server metrics is done under server lock, but we don't want
2017 // to marshal under that lock. Still, we need to prevent concurrent
2018 // http requests to /varz to update s.varz while marshal is
2019 // happening, so we need a new lock that serialize those http
2020 // requests and include marshaling.
2021 s.varzMu.Lock()
2022
2023 // Use server lock to create/update the server's varz object.
2024 s.mu.Lock()
2025 var created bool
2026 s.httpReqStats[VarzPath]++
2027 if s.varz == nil {
2028 s.varz = s.createVarz(pcpu, rss)
2029 created = true
2030 } else {
2031 s.updateVarzRuntimeFields(s.varz, false, pcpu, rss)
2032 }
2033 s.mu.Unlock()
2034 // Since locking is jetStream -> Server, need to update jetstream
2035 // varz outside of server lock.
2036
2037 if js := s.getJetStream(); js != nil {
2038 var v JetStreamVarz
2039 // Work on stack variable
2040 s.updateJszVarz(js, &v, created)
2041 // Now update server's varz
2042 s.mu.RLock()
2043 sv := &s.varz.JetStream
2044 if created {
2045 sv.Config = v.Config
2046 }
2047 sv.Stats = v.Stats
2048 sv.Meta = v.Meta
2049 sv.Limits = v.Limits
2050 s.mu.RUnlock()
2051 }
2052
2053 // Do the marshaling outside of server lock, but under varzMu lock.
2054 b, err := json.MarshalIndent(s.varz, "", " ")
2055 s.varzMu.Unlock()
2056
2057 if err != nil {
2058 s.Errorf("Error marshaling response to /varz request: %v", err)
2059 }
2060
2061 // Handle response
2062 ResponseHandler(w, r, b)
2063 }
2064
2065 // GatewayzOptions are the options passed to Gatewayz()
2066 type GatewayzOptions struct {
2067 // Name will output only remote gateways with this name
2068 Name string `json:"name"`
2069
2070 // Accounts indicates if accounts with its interest should be included in the results.
2071 Accounts bool `json:"accounts"`
2072
2073 // AccountName will limit the list of accounts to that account name (makes Accounts implicit)
2074 AccountName string `json:"account_name"`
2075
2076 // AccountSubscriptions indicates if subscriptions should be included in the results.
2077 // Note: This is used only if `Accounts` or `AccountName` are specified.
2078 AccountSubscriptions bool `json:"subscriptions"`
2079
2080 // AccountSubscriptionsDetail indicates if subscription details should be included in the results.
2081 // Note: This is used only if `Accounts` or `AccountName` are specified.
2082 AccountSubscriptionsDetail bool `json:"subscriptions_detail"`
2083 }
2084
2085 // Gatewayz represents detailed information on Gateways
2086 type Gatewayz struct {
2087 ID string `json:"server_id"`
2088 Now time.Time `json:"now"`
2089 Name string `json:"name,omitempty"`
2090 Host string `json:"host,omitempty"`
2091 Port int `json:"port,omitempty"`
2092 OutboundGateways map[string]*RemoteGatewayz `json:"outbound_gateways"`
2093 InboundGateways map[string][]*RemoteGatewayz `json:"inbound_gateways"`
2094 }
2095
2096 // RemoteGatewayz represents information about an outbound connection to a gateway
2097 type RemoteGatewayz struct {
2098 IsConfigured bool `json:"configured"`
2099 Connection *ConnInfo `json:"connection,omitempty"`
2100 Accounts []*AccountGatewayz `json:"accounts,omitempty"`
2101 }
2102
2103 // AccountGatewayz represents interest mode for this account
2104 type AccountGatewayz struct {
2105 Name string `json:"name"`
2106 InterestMode string `json:"interest_mode"`
2107 NoInterestCount int `json:"no_interest_count,omitempty"`
2108 InterestOnlyThreshold int `json:"interest_only_threshold,omitempty"`
2109 TotalSubscriptions int `json:"num_subs,omitempty"`
2110 NumQueueSubscriptions int `json:"num_queue_subs,omitempty"`
2111 Subs []string `json:"subscriptions_list,omitempty"`
2112 SubsDetail []SubDetail `json:"subscriptions_list_detail,omitempty"`
2113 }
2114
2115 // Gatewayz returns a Gatewayz struct containing information about gateways.
2116 func (s *Server) Gatewayz(opts *GatewayzOptions) (*Gatewayz, error) {
2117 srvID := s.ID()
2118 now := time.Now().UTC()
2119 gw := s.gateway
2120 gw.RLock()
2121 if !gw.enabled || gw.info == nil {
2122 gw.RUnlock()
2123 gwz := &Gatewayz{
2124 ID: srvID,
2125 Now: now,
2126 OutboundGateways: map[string]*RemoteGatewayz{},
2127 InboundGateways: map[string][]*RemoteGatewayz{},
2128 }
2129 return gwz, nil
2130 }
2131 // Here gateways are enabled, so fill up more.
2132 gwz := &Gatewayz{
2133 ID: srvID,
2134 Now: now,
2135 Name: gw.name,
2136 Host: gw.info.Host,
2137 Port: gw.info.Port,
2138 }
2139 gw.RUnlock()
2140
2141 gwz.OutboundGateways = s.createOutboundsRemoteGatewayz(opts, now)
2142 gwz.InboundGateways = s.createInboundsRemoteGatewayz(opts, now)
2143
2144 return gwz, nil
2145 }
2146
2147 // Based on give options struct, returns if there is a filtered
2148 // Gateway Name and if we should do report Accounts.
2149 // Note that if Accounts is false but AccountName is not empty,
2150 // then Accounts is implicitly set to true.
2151 func getMonitorGWOptions(opts *GatewayzOptions) (string, bool) {
2152 var name string
2153 var accs bool
2154 if opts != nil {
2155 if opts.Name != _EMPTY_ {
2156 name = opts.Name
2157 }
2158 accs = opts.Accounts
2159 if !accs && opts.AccountName != _EMPTY_ {
2160 accs = true
2161 }
2162 }
2163 return name, accs
2164 }
2165
2166 // Returns a map of gateways outbound connections.
2167 // Based on options, will include a single or all gateways,
2168 // with no/single/or all accounts interest information.
2169 func (s *Server) createOutboundsRemoteGatewayz(opts *GatewayzOptions, now time.Time) map[string]*RemoteGatewayz {
2170 targetGWName, doAccs := getMonitorGWOptions(opts)
2171
2172 if targetGWName != _EMPTY_ {
2173 c := s.getOutboundGatewayConnection(targetGWName)
2174 if c == nil {
2175 return nil
2176 }
2177 outbounds := make(map[string]*RemoteGatewayz, 1)
2178 _, rgw := createOutboundRemoteGatewayz(c, opts, now, doAccs)
2179 outbounds[targetGWName] = rgw
2180 return outbounds
2181 }
2182
2183 var connsa [16]*client
2184 var conns = connsa[:0]
2185
2186 s.getOutboundGatewayConnections(&conns)
2187
2188 outbounds := make(map[string]*RemoteGatewayz, len(conns))
2189 for _, c := range conns {
2190 name, rgw := createOutboundRemoteGatewayz(c, opts, now, doAccs)
2191 if rgw != nil {
2192 outbounds[name] = rgw
2193 }
2194 }
2195 return outbounds
2196 }
2197
2198 // Returns a RemoteGatewayz for a given outbound gw connection
2199 func createOutboundRemoteGatewayz(c *client, opts *GatewayzOptions, now time.Time, doAccs bool) (string, *RemoteGatewayz) {
2200 var name string
2201 var rgw *RemoteGatewayz
2202
2203 c.mu.Lock()
2204 if c.gw != nil {
2205 rgw = &RemoteGatewayz{}
2206 if doAccs {
2207 rgw.Accounts = createOutboundAccountsGatewayz(opts, c.gw)
2208 }
2209 if c.gw.cfg != nil {
2210 rgw.IsConfigured = !c.gw.cfg.isImplicit()
2211 }
2212 rgw.Connection = &ConnInfo{}
2213 rgw.Connection.fill(c, c.nc, now, false)
2214 name = c.gw.name
2215 }
2216 c.mu.Unlock()
2217
2218 return name, rgw
2219 }
2220
2221 // Returns the list of accounts for this outbound gateway connection.
2222 // Based on the options, it will be a single or all accounts for
2223 // this outbound.
2224 func createOutboundAccountsGatewayz(opts *GatewayzOptions, gw *gateway) []*AccountGatewayz {
2225 if gw.outsim == nil {
2226 return nil
2227 }
2228
2229 var accName string
2230 if opts != nil {
2231 accName = opts.AccountName
2232 }
2233 if accName != _EMPTY_ {
2234 ei, ok := gw.outsim.Load(accName)
2235 if !ok {
2236 return nil
2237 }
2238 a := createAccountOutboundGatewayz(opts, accName, ei)
2239 return []*AccountGatewayz{a}
2240 }
2241
2242 accs := make([]*AccountGatewayz, 0, 4)
2243 gw.outsim.Range(func(k, v any) bool {
2244 name := k.(string)
2245 a := createAccountOutboundGatewayz(opts, name, v)
2246 accs = append(accs, a)
2247 return true
2248 })
2249 return accs
2250 }
2251
2252 // Returns an AccountGatewayz for this gateway outbound connection
2253 func createAccountOutboundGatewayz(opts *GatewayzOptions, name string, ei any) *AccountGatewayz {
2254 a := &AccountGatewayz{
2255 Name: name,
2256 InterestOnlyThreshold: gatewayMaxRUnsubBeforeSwitch,
2257 }
2258 if ei != nil {
2259 e := ei.(*outsie)
2260 e.RLock()
2261 a.InterestMode = e.mode.String()
2262 a.NoInterestCount = len(e.ni)
2263 a.NumQueueSubscriptions = e.qsubs
2264 a.TotalSubscriptions = int(e.sl.Count())
2265 if opts.AccountSubscriptions || opts.AccountSubscriptionsDetail {
2266 var subsa [4096]*subscription
2267 subs := subsa[:0]
2268 e.sl.All(&subs)
2269 if opts.AccountSubscriptions {
2270 a.Subs = make([]string, 0, len(subs))
2271 } else {
2272 a.SubsDetail = make([]SubDetail, 0, len(subs))
2273 }
2274 for _, sub := range subs {
2275 if opts.AccountSubscriptions {
2276 a.Subs = append(a.Subs, string(sub.subject))
2277 } else {
2278 a.SubsDetail = append(a.SubsDetail, newClientSubDetail(sub))
2279 }
2280 }
2281 }
2282 e.RUnlock()
2283 } else {
2284 a.InterestMode = Optimistic.String()
2285 }
2286 return a
2287 }
2288
2289 // Returns a map of gateways inbound connections.
2290 // Each entry is an array of RemoteGatewayz since a given server
2291 // may have more than one inbound from the same remote gateway.
2292 // Based on options, will include a single or all gateways,
2293 // with no/single/or all accounts interest information.
2294 func (s *Server) createInboundsRemoteGatewayz(opts *GatewayzOptions, now time.Time) map[string][]*RemoteGatewayz {
2295 targetGWName, doAccs := getMonitorGWOptions(opts)
2296
2297 var connsa [16]*client
2298 var conns = connsa[:0]
2299 s.getInboundGatewayConnections(&conns)
2300
2301 m := make(map[string][]*RemoteGatewayz)
2302 for _, c := range conns {
2303 c.mu.Lock()
2304 if c.gw != nil && (targetGWName == _EMPTY_ || targetGWName == c.gw.name) {
2305 igws := m[c.gw.name]
2306 if igws == nil {
2307 igws = make([]*RemoteGatewayz, 0, 2)
2308 }
2309 rgw := &RemoteGatewayz{}
2310 if doAccs {
2311 rgw.Accounts = createInboundAccountsGatewayz(opts, c.gw)
2312 }
2313 rgw.Connection = &ConnInfo{}
2314 rgw.Connection.fill(c, c.nc, now, false)
2315 igws = append(igws, rgw)
2316 m[c.gw.name] = igws
2317 }
2318 c.mu.Unlock()
2319 }
2320 return m
2321 }
2322
2323 // Returns the list of accounts for this inbound gateway connection.
2324 // Based on the options, it will be a single or all accounts for
2325 // this inbound.
2326 func createInboundAccountsGatewayz(opts *GatewayzOptions, gw *gateway) []*AccountGatewayz {
2327 if gw.insim == nil {
2328 return nil
2329 }
2330
2331 var accName string
2332 if opts != nil {
2333 accName = opts.AccountName
2334 }
2335 if accName != _EMPTY_ {
2336 e, ok := gw.insim[accName]
2337 if !ok {
2338 return nil
2339 }
2340 a := createInboundAccountGatewayz(accName, e)
2341 return []*AccountGatewayz{a}
2342 }
2343
2344 accs := make([]*AccountGatewayz, 0, 4)
2345 for name, e := range gw.insim {
2346 a := createInboundAccountGatewayz(name, e)
2347 accs = append(accs, a)
2348 }
2349 return accs
2350 }
2351
2352 // Returns an AccountGatewayz for this gateway inbound connection
2353 func createInboundAccountGatewayz(name string, e *insie) *AccountGatewayz {
2354 a := &AccountGatewayz{
2355 Name: name,
2356 InterestOnlyThreshold: gatewayMaxRUnsubBeforeSwitch,
2357 }
2358 if e != nil {
2359 a.InterestMode = e.mode.String()
2360 a.NoInterestCount = len(e.ni)
2361 } else {
2362 a.InterestMode = Optimistic.String()
2363 }
2364 return a
2365 }
2366
2367 // HandleGatewayz process HTTP requests for route information.
2368 func (s *Server) HandleGatewayz(w http.ResponseWriter, r *http.Request) {
2369 s.mu.Lock()
2370 s.httpReqStats[GatewayzPath]++
2371 s.mu.Unlock()
2372
2373 subs, subsDet, err := decodeSubs(w, r)
2374 if err != nil {
2375 return
2376 }
2377 accs, err := decodeBool(w, r, "accs")
2378 if err != nil {
2379 return
2380 }
2381 gwName := r.URL.Query().Get("gw_name")
2382 accName := r.URL.Query().Get("acc_name")
2383 if accName != _EMPTY_ {
2384 accs = true
2385 }
2386
2387 opts := &GatewayzOptions{
2388 Name: gwName,
2389 Accounts: accs,
2390 AccountName: accName,
2391 AccountSubscriptions: subs,
2392 AccountSubscriptionsDetail: subsDet,
2393 }
2394 gw, err := s.Gatewayz(opts)
2395 if err != nil {
2396 w.WriteHeader(http.StatusBadRequest)
2397 w.Write([]byte(err.Error()))
2398 return
2399 }
2400 b, err := json.MarshalIndent(gw, "", " ")
2401 if err != nil {
2402 s.Errorf("Error marshaling response to /gatewayz request: %v", err)
2403 }
2404
2405 // Handle response
2406 ResponseHandler(w, r, b)
2407 }
2408
2409 // Leafz represents detailed information on Leafnodes.
2410 type Leafz struct {
2411 ID string `json:"server_id"`
2412 Now time.Time `json:"now"`
2413 NumLeafs int `json:"leafnodes"`
2414 Leafs []*LeafInfo `json:"leafs"`
2415 }
2416
2417 // LeafzOptions are options passed to Leafz
2418 type LeafzOptions struct {
2419 // Subscriptions indicates that Leafz will return a leafnode's subscriptions
2420 Subscriptions bool `json:"subscriptions"`
2421 Account string `json:"account"`
2422 }
2423
2424 // LeafInfo has detailed information on each remote leafnode connection.
2425 type LeafInfo struct {
2426 ID uint64 `json:"id"`
2427 Name string `json:"name"`
2428 IsSpoke bool `json:"is_spoke"`
2429 IsIsolated bool `json:"is_isolated,omitempty"`
2430 Account string `json:"account"`
2431 IP string `json:"ip"`
2432 Port int `json:"port"`
2433 RTT string `json:"rtt,omitempty"`
2434 InMsgs int64 `json:"in_msgs"`
2435 OutMsgs int64 `json:"out_msgs"`
2436 InBytes int64 `json:"in_bytes"`
2437 OutBytes int64 `json:"out_bytes"`
2438 NumSubs uint32 `json:"subscriptions"`
2439 Subs []string `json:"subscriptions_list,omitempty"`
2440 Compression string `json:"compression,omitempty"`
2441 Proxy *ProxyInfo `json:"proxy,omitempty"`
2442 }
2443
2444 // Leafz returns a Leafz structure containing information about leafnodes.
2445 func (s *Server) Leafz(opts *LeafzOptions) (*Leafz, error) {
2446 // Grab leafnodes
2447 var lconns []*client
2448 s.mu.Lock()
2449 if len(s.leafs) > 0 {
2450 lconns = make([]*client, 0, len(s.leafs))
2451 for _, ln := range s.leafs {
2452 if opts != nil && opts.Account != _EMPTY_ {
2453 ln.mu.Lock()
2454 ok := ln.acc.Name == opts.Account
2455 ln.mu.Unlock()
2456 if !ok {
2457 continue
2458 }
2459 }
2460 lconns = append(lconns, ln)
2461 }
2462 }
2463 s.mu.Unlock()
2464
2465 leafnodes := make([]*LeafInfo, 0, len(lconns))
2466
2467 if len(lconns) > 0 {
2468 for _, ln := range lconns {
2469 ln.mu.Lock()
2470 lni := &LeafInfo{
2471 ID: ln.cid,
2472 Name: ln.leaf.remoteServer,
2473 IsSpoke: ln.isSpokeLeafNode(),
2474 IsIsolated: ln.leaf.isolated,
2475 Account: ln.acc.Name,
2476 IP: ln.host,
2477 Port: int(ln.port),
2478 RTT: ln.getRTT().String(),
2479 InMsgs: atomic.LoadInt64(&ln.inMsgs),
2480 OutMsgs: ln.outMsgs,
2481 InBytes: atomic.LoadInt64(&ln.inBytes),
2482 OutBytes: ln.outBytes,
2483 NumSubs: uint32(len(ln.subs)),
2484 Compression: ln.leaf.compression,
2485 Proxy: createProxyInfo(ln),
2486 }
2487 if opts != nil && opts.Subscriptions {
2488 lni.Subs = make([]string, 0, len(ln.subs))
2489 for _, sub := range ln.subs {
2490 lni.Subs = append(lni.Subs, string(sub.subject))
2491 }
2492 }
2493 ln.mu.Unlock()
2494 leafnodes = append(leafnodes, lni)
2495 }
2496 }
2497
2498 return &Leafz{
2499 ID: s.ID(),
2500 Now: time.Now().UTC(),
2501 NumLeafs: len(leafnodes),
2502 Leafs: leafnodes,
2503 }, nil
2504 }
2505
2506 // HandleLeafz process HTTP requests for leafnode information.
2507 func (s *Server) HandleLeafz(w http.ResponseWriter, r *http.Request) {
2508 s.mu.Lock()
2509 s.httpReqStats[LeafzPath]++
2510 s.mu.Unlock()
2511
2512 subs, err := decodeBool(w, r, "subs")
2513 if err != nil {
2514 return
2515 }
2516 l, err := s.Leafz(&LeafzOptions{subs, r.URL.Query().Get("acc")})
2517 if err != nil {
2518 w.WriteHeader(http.StatusBadRequest)
2519 w.Write([]byte(err.Error()))
2520 return
2521 }
2522 b, err := json.MarshalIndent(l, "", " ")
2523 if err != nil {
2524 s.Errorf("Error marshaling response to /leafz request: %v", err)
2525 }
2526
2527 // Handle response
2528 ResponseHandler(w, r, b)
2529 }
2530
2531 // Leafz represents detailed information on Leafnodes.
2532 type AccountStatz struct {
2533 ID string `json:"server_id"`
2534 Now time.Time `json:"now"`
2535 Accounts []*AccountStat `json:"account_statz"`
2536 }
2537
2538 // AccountStatzOptions are options passed to account stats requests.
2539 type AccountStatzOptions struct {
2540 Accounts []string `json:"accounts"`
2541 IncludeUnused bool `json:"include_unused"`
2542 }
2543
2544 // Leafz returns a AccountStatz structure containing summary information about accounts.
2545 func (s *Server) AccountStatz(opts *AccountStatzOptions) (*AccountStatz, error) {
2546 stz := &AccountStatz{
2547 ID: s.ID(),
2548 Now: time.Now().UTC(),
2549 Accounts: []*AccountStat{},
2550 }
2551 if opts == nil || len(opts.Accounts) == 0 {
2552 s.accounts.Range(func(key, a any) bool {
2553 acc := a.(*Account)
2554 acc.mu.RLock()
2555 if (opts != nil && opts.IncludeUnused) || acc.numLocalConnections() != 0 || acc.numLocalLeafNodes() != 0 {
2556 stz.Accounts = append(stz.Accounts, acc.statz())
2557 }
2558 acc.mu.RUnlock()
2559 return true
2560 })
2561 } else {
2562 for _, a := range opts.Accounts {
2563 if acc, ok := s.accounts.Load(a); ok {
2564 acc := acc.(*Account)
2565 acc.mu.RLock()
2566 if opts.IncludeUnused || acc.numLocalConnections() != 0 || acc.numLocalLeafNodes() != 0 {
2567 stz.Accounts = append(stz.Accounts, acc.statz())
2568 }
2569 acc.mu.RUnlock()
2570 }
2571 }
2572 }
2573 return stz, nil
2574 }
2575
2576 // HandleAccountStatz process HTTP requests for statz information of all accounts.
2577 func (s *Server) HandleAccountStatz(w http.ResponseWriter, r *http.Request) {
2578 s.mu.Lock()
2579 s.httpReqStats[AccountStatzPath]++
2580 s.mu.Unlock()
2581
2582 unused, err := decodeBool(w, r, "unused")
2583 if err != nil {
2584 return
2585 }
2586
2587 l, err := s.AccountStatz(&AccountStatzOptions{IncludeUnused: unused})
2588 if err != nil {
2589 w.WriteHeader(http.StatusBadRequest)
2590 w.Write([]byte(err.Error()))
2591 return
2592 }
2593 b, err := json.MarshalIndent(l, "", " ")
2594 if err != nil {
2595 s.Errorf("Error marshaling response to %s request: %v", AccountStatzPath, err)
2596 return
2597 }
2598
2599 // Handle response
2600 ResponseHandler(w, r, b)
2601 }
2602
2603 // ResponseHandler handles responses for monitoring routes.
2604 func ResponseHandler(w http.ResponseWriter, r *http.Request, data []byte) {
2605 handleResponse(http.StatusOK, w, r, data)
2606 }
2607
2608 // handleResponse handles responses for monitoring routes with a specific HTTP status code.
2609 func handleResponse(code int, w http.ResponseWriter, _ *http.Request, data []byte) {
2610 w.Header().Set("Content-Type", "application/json")
2611 w.Header().Set("Access-Control-Allow-Origin", "*")
2612 w.WriteHeader(code)
2613 w.Write(data)
2614 }
2615
2616 func (reason ClosedState) String() string {
2617 switch reason {
2618 case ClientClosed:
2619 return "Client Closed"
2620 case AuthenticationTimeout:
2621 return "Authentication Timeout"
2622 case AuthenticationViolation:
2623 return "Authentication Failure"
2624 case TLSHandshakeError:
2625 return "TLS Handshake Failure"
2626 case SlowConsumerPendingBytes:
2627 return "Slow Consumer (Pending Bytes)"
2628 case SlowConsumerWriteDeadline:
2629 return "Slow Consumer (Write Deadline)"
2630 case WriteError:
2631 return "Write Error"
2632 case ReadError:
2633 return "Read Error"
2634 case ParseError:
2635 return "Parse Error"
2636 case StaleConnection:
2637 return "Stale Connection"
2638 case ProtocolViolation:
2639 return "Protocol Violation"
2640 case BadClientProtocolVersion:
2641 return "Bad Client Protocol Version"
2642 case WrongPort:
2643 return "Incorrect Port"
2644 case MaxConnectionsExceeded:
2645 return "Maximum Connections Exceeded"
2646 case MaxAccountConnectionsExceeded:
2647 return "Maximum Account Connections Exceeded"
2648 case MaxPayloadExceeded:
2649 return "Maximum Message Payload Exceeded"
2650 case MaxControlLineExceeded:
2651 return "Maximum Control Line Exceeded"
2652 case MaxSubscriptionsExceeded:
2653 return "Maximum Subscriptions Exceeded"
2654 case DuplicateRoute:
2655 return "Duplicate Route"
2656 case RouteRemoved:
2657 return "Route Removed"
2658 case ServerShutdown:
2659 return "Server Shutdown"
2660 case AuthenticationExpired:
2661 return "Authentication Expired"
2662 case WrongGateway:
2663 return "Wrong Gateway"
2664 case MissingAccount:
2665 return "Missing Account"
2666 case Revocation:
2667 return "Credentials Revoked"
2668 case InternalClient:
2669 return "Internal Client"
2670 case MsgHeaderViolation:
2671 return "Message Header Violation"
2672 case NoRespondersRequiresHeaders:
2673 return "No Responders Requires Headers"
2674 case ClusterNameConflict:
2675 return "Cluster Name Conflict"
2676 case DuplicateRemoteLeafnodeConnection:
2677 return "Duplicate Remote LeafNode Connection"
2678 case DuplicateClientID:
2679 return "Duplicate Client ID"
2680 case DuplicateServerName:
2681 return "Duplicate Server Name"
2682 case MinimumVersionRequired:
2683 return "Minimum Version Required"
2684 case ClusterNamesIdentical:
2685 return "Cluster Names Identical"
2686 case Kicked:
2687 return "Kicked"
2688 case ProxyNotTrusted:
2689 return "Proxy Not Trusted"
2690 case ProxyRequired:
2691 return "Proxy Required"
2692 }
2693
2694 return "Unknown State"
2695 }
2696
2697 // AccountzOptions are options passed to Accountz
2698 type AccountzOptions struct {
2699 // Account indicates that Accountz will return details for the account
2700 Account string `json:"account"`
2701 }
2702
2703 func newExtServiceLatency(l *serviceLatency) *jwt.ServiceLatency {
2704 if l == nil {
2705 return nil
2706 }
2707 return &jwt.ServiceLatency{
2708 Sampling: jwt.SamplingRate(l.sampling),
2709 Results: jwt.Subject(l.subject),
2710 }
2711 }
2712
2713 type ExtImport struct {
2714 jwt.Import
2715 Invalid bool `json:"invalid"`
2716 Share bool `json:"share"`
2717 Tracking bool `json:"tracking"`
2718 TrackingHdr http.Header `json:"tracking_header,omitempty"`
2719 Latency *jwt.ServiceLatency `json:"latency,omitempty"`
2720 M1 *ServiceLatency `json:"m1,omitempty"`
2721 }
2722
2723 type ExtExport struct {
2724 jwt.Export
2725 ApprovedAccounts []string `json:"approved_accounts,omitempty"`
2726 RevokedAct map[string]time.Time `json:"revoked_activations,omitempty"`
2727 }
2728
2729 type ExtVrIssues struct {
2730 Description string `json:"description"`
2731 Blocking bool `json:"blocking"`
2732 Time bool `json:"time_check"`
2733 }
2734
2735 type ExtMap map[string][]*MapDest
2736
2737 type AccountInfo struct {
2738 AccountName string `json:"account_name"`
2739 LastUpdate time.Time `json:"update_time,omitempty"`
2740 IsSystem bool `json:"is_system,omitempty"`
2741 Expired bool `json:"expired"`
2742 Complete bool `json:"complete"`
2743 JetStream bool `json:"jetstream_enabled"`
2744 LeafCnt int `json:"leafnode_connections"`
2745 ClientCnt int `json:"client_connections"`
2746 SubCnt uint32 `json:"subscriptions"`
2747 Mappings ExtMap `json:"mappings,omitempty"`
2748 Exports []ExtExport `json:"exports,omitempty"`
2749 Imports []ExtImport `json:"imports,omitempty"`
2750 Jwt string `json:"jwt,omitempty"`
2751 IssuerKey string `json:"issuer_key,omitempty"`
2752 NameTag string `json:"name_tag,omitempty"`
2753 Tags jwt.TagList `json:"tags,omitempty"`
2754 Claim *jwt.AccountClaims `json:"decoded_jwt,omitempty"`
2755 Vr []ExtVrIssues `json:"validation_result_jwt,omitempty"`
2756 RevokedUser map[string]time.Time `json:"revoked_user,omitempty"`
2757 Sublist *SublistStats `json:"sublist_stats,omitempty"`
2758 Responses map[string]ExtImport `json:"responses,omitempty"`
2759 }
2760
2761 type Accountz struct {
2762 ID string `json:"server_id"`
2763 Now time.Time `json:"now"`
2764 SystemAccount string `json:"system_account,omitempty"`
2765 Accounts []string `json:"accounts,omitempty"`
2766 Account *AccountInfo `json:"account_detail,omitempty"`
2767 }
2768
2769 // HandleAccountz process HTTP requests for account information.
2770 func (s *Server) HandleAccountz(w http.ResponseWriter, r *http.Request) {
2771 s.mu.Lock()
2772 s.httpReqStats[AccountzPath]++
2773 s.mu.Unlock()
2774 if l, err := s.Accountz(&AccountzOptions{r.URL.Query().Get("acc")}); err != nil {
2775 w.WriteHeader(http.StatusBadRequest)
2776 w.Write([]byte(err.Error()))
2777 } else if b, err := json.MarshalIndent(l, "", " "); err != nil {
2778 s.Errorf("Error marshaling response to %s request: %v", AccountzPath, err)
2779 w.WriteHeader(http.StatusBadRequest)
2780 w.Write([]byte(err.Error()))
2781 } else {
2782 ResponseHandler(w, r, b) // Handle response
2783 }
2784 }
2785
2786 func (s *Server) Accountz(optz *AccountzOptions) (*Accountz, error) {
2787 a := &Accountz{
2788 ID: s.ID(),
2789 Now: time.Now().UTC(),
2790 }
2791 if sacc := s.SystemAccount(); sacc != nil {
2792 a.SystemAccount = sacc.GetName()
2793 }
2794 if optz == nil || optz.Account == _EMPTY_ {
2795 a.Accounts = []string{}
2796 s.accounts.Range(func(key, value any) bool {
2797 a.Accounts = append(a.Accounts, key.(string))
2798 return true
2799 })
2800 return a, nil
2801 }
2802 aInfo, err := s.accountInfo(optz.Account)
2803 if err != nil {
2804 return nil, err
2805 }
2806 a.Account = aInfo
2807 return a, nil
2808 }
2809
2810 func newExtImport(v *serviceImport) ExtImport {
2811 imp := ExtImport{
2812 Invalid: true,
2813 Import: jwt.Import{Type: jwt.Service},
2814 }
2815 if v != nil {
2816 imp.Share = v.share
2817 imp.Tracking = v.tracking
2818 imp.Invalid = v.invalid
2819 imp.Import = jwt.Import{
2820 Subject: jwt.Subject(v.to),
2821 Account: v.acc.Name,
2822 Type: jwt.Service,
2823 // Deprecated so we duplicate. Use LocalSubject.
2824 To: jwt.Subject(v.from),
2825 LocalSubject: jwt.RenamingSubject(v.from),
2826 }
2827 imp.TrackingHdr = v.trackingHdr
2828 imp.Latency = newExtServiceLatency(v.latency)
2829 if v.m1 != nil {
2830 m1 := *v.m1
2831 imp.M1 = &m1
2832 }
2833 }
2834 return imp
2835 }
2836
2837 func (s *Server) accountInfo(accName string) (*AccountInfo, error) {
2838 var a *Account
2839 if v, ok := s.accounts.Load(accName); !ok {
2840 return nil, fmt.Errorf("Account %s does not exist", accName)
2841 } else {
2842 a = v.(*Account)
2843 }
2844 isSys := a == s.SystemAccount()
2845 a.mu.RLock()
2846 defer a.mu.RUnlock()
2847 var vrIssues []ExtVrIssues
2848 claim, _ := jwt.DecodeAccountClaims(a.claimJWT) // ignore error
2849 if claim != nil {
2850 vr := jwt.ValidationResults{}
2851 claim.Validate(&vr)
2852 vrIssues = make([]ExtVrIssues, len(vr.Issues))
2853 for i, v := range vr.Issues {
2854 vrIssues[i] = ExtVrIssues{v.Description, v.Blocking, v.TimeCheck}
2855 }
2856 }
2857 collectRevocations := func(revocations map[string]int64) map[string]time.Time {
2858 l := len(revocations)
2859 if l == 0 {
2860 return nil
2861 }
2862 rev := make(map[string]time.Time, l)
2863 for k, v := range revocations {
2864 rev[k] = time.Unix(v, 0)
2865 }
2866 return rev
2867 }
2868 exports := []ExtExport{}
2869 for k, v := range a.exports.services {
2870 e := ExtExport{
2871 Export: jwt.Export{
2872 Subject: jwt.Subject(k),
2873 Type: jwt.Service,
2874 },
2875 ApprovedAccounts: []string{},
2876 }
2877 if v != nil {
2878 e.Latency = newExtServiceLatency(v.latency)
2879 e.TokenReq = v.tokenReq
2880 e.ResponseType = jwt.ResponseType(v.respType.String())
2881 for name := range v.approved {
2882 e.ApprovedAccounts = append(e.ApprovedAccounts, name)
2883 }
2884 e.RevokedAct = collectRevocations(v.actsRevoked)
2885 }
2886 exports = append(exports, e)
2887 }
2888 for k, v := range a.exports.streams {
2889 e := ExtExport{
2890 Export: jwt.Export{
2891 Subject: jwt.Subject(k),
2892 Type: jwt.Stream,
2893 },
2894 ApprovedAccounts: []string{},
2895 }
2896 if v != nil {
2897 e.TokenReq = v.tokenReq
2898 for name := range v.approved {
2899 e.ApprovedAccounts = append(e.ApprovedAccounts, name)
2900 }
2901 e.RevokedAct = collectRevocations(v.actsRevoked)
2902 }
2903 exports = append(exports, e)
2904 }
2905 imports := []ExtImport{}
2906 for _, v := range a.imports.streams {
2907 imp := ExtImport{
2908 Invalid: true,
2909 Import: jwt.Import{Type: jwt.Stream},
2910 }
2911 if v != nil {
2912 imp.Invalid = v.invalid
2913 imp.Import = jwt.Import{
2914 Subject: jwt.Subject(v.from),
2915 Account: v.acc.Name,
2916 Type: jwt.Stream,
2917 LocalSubject: jwt.RenamingSubject(v.to),
2918 }
2919 }
2920 imports = append(imports, imp)
2921 }
2922 for _, sis := range a.imports.services {
2923 for _, v := range sis {
2924 imports = append(imports, newExtImport(v))
2925 }
2926 }
2927 responses := map[string]ExtImport{}
2928 for k, v := range a.exports.responses {
2929 responses[k] = newExtImport(v)
2930 }
2931 mappings := ExtMap{}
2932 for _, m := range a.mappings {
2933 var dests []*MapDest
2934 var src string
2935 if m == nil {
2936 src = "nil"
2937 if _, ok := mappings[src]; ok { // only set if not present (keep orig in case nil is used)
2938 continue
2939 }
2940 dests = append(dests, &MapDest{})
2941 } else {
2942 src = m.src
2943 for _, d := range m.dests {
2944 dests = append(dests, &MapDest{d.tr.dest, d.weight, _EMPTY_})
2945 }
2946 for c, cd := range m.cdests {
2947 for _, d := range cd {
2948 dests = append(dests, &MapDest{d.tr.dest, d.weight, c})
2949 }
2950 }
2951 }
2952 mappings[src] = dests
2953 }
2954 return &AccountInfo{
2955 AccountName: accName,
2956 LastUpdate: a.updated.UTC(),
2957 IsSystem: isSys,
2958 Expired: a.expired.Load(),
2959 Complete: !a.incomplete,
2960 JetStream: a.js != nil,
2961 LeafCnt: a.numLocalLeafNodes(),
2962 ClientCnt: a.numLocalConnections(),
2963 SubCnt: a.sl.Count(),
2964 Mappings: mappings,
2965 Exports: exports,
2966 Imports: imports,
2967 Jwt: a.claimJWT,
2968 IssuerKey: a.Issuer,
2969 NameTag: a.getNameTagLocked(),
2970 Tags: a.tags,
2971 Claim: claim,
2972 Vr: vrIssues,
2973 RevokedUser: collectRevocations(a.usersRevoked),
2974 Sublist: a.sl.Stats(),
2975 Responses: responses,
2976 }, nil
2977 }
2978
2979 // JSzOptions are options passed to Jsz
2980 type JSzOptions struct {
2981 Account string `json:"account,omitempty"`
2982 Accounts bool `json:"accounts,omitempty"`
2983 Streams bool `json:"streams,omitempty"`
2984 Consumer bool `json:"consumer,omitempty"`
2985 DirectConsumer bool `json:"direct_consumer,omitempty"`
2986 Config bool `json:"config,omitempty"`
2987 LeaderOnly bool `json:"leader_only,omitempty"`
2988 Offset int `json:"offset,omitempty"`
2989 Limit int `json:"limit,omitempty"`
2990 RaftGroups bool `json:"raft,omitempty"`
2991 StreamLeaderOnly bool `json:"stream_leader_only,omitempty"`
2992 }
2993
2994 // HealthzOptions are options passed to Healthz
2995 type HealthzOptions struct {
2996 // Deprecated: Use JSEnabledOnly instead
2997 JSEnabled bool `json:"js-enabled,omitempty"`
2998 JSEnabledOnly bool `json:"js-enabled-only,omitempty"`
2999 JSServerOnly bool `json:"js-server-only,omitempty"`
3000 JSMetaOnly bool `json:"js-meta-only,omitempty"`
3001 Account string `json:"account,omitempty"`
3002 Stream string `json:"stream,omitempty"`
3003 Consumer string `json:"consumer,omitempty"`
3004 Details bool `json:"details,omitempty"`
3005 }
3006
3007 // ProfilezOptions are options passed to Profilez
3008 type ProfilezOptions struct {
3009 Name string `json:"name"`
3010 Debug int `json:"debug"`
3011 Duration time.Duration `json:"duration,omitempty"`
3012 }
3013
3014 // IpqueueszOptions are options passed to Ipqueuesz
3015 type IpqueueszOptions struct {
3016 All bool `json:"all"`
3017 Filter string `json:"filter"`
3018 }
3019
3020 // RaftzOptions are options passed to Raftz
3021 type RaftzOptions struct {
3022 AccountFilter string `json:"account"`
3023 GroupFilter string `json:"group"`
3024 }
3025
3026 // StreamDetail shows information about the stream state and its consumers.
3027 type StreamDetail struct {
3028 Name string `json:"name"`
3029 Created time.Time `json:"created"`
3030 Cluster *ClusterInfo `json:"cluster,omitempty"`
3031 Config *StreamConfig `json:"config,omitempty"`
3032 State StreamState `json:"state,omitempty"`
3033 Consumer []*ConsumerInfo `json:"consumer_detail,omitempty"`
3034 DirectConsumer []*ConsumerInfo `json:"direct_consumer_detail,omitempty"`
3035 Mirror *StreamSourceInfo `json:"mirror,omitempty"`
3036 Sources []*StreamSourceInfo `json:"sources,omitempty"`
3037 RaftGroup string `json:"stream_raft_group,omitempty"`
3038 ConsumerRaftGroups []*RaftGroupDetail `json:"consumer_raft_groups,omitempty"`
3039 }
3040
3041 // RaftGroupDetail shows information details about the Raft group.
3042 type RaftGroupDetail struct {
3043 Name string `json:"name"`
3044 RaftGroup string `json:"raft_group,omitempty"`
3045 }
3046
3047 type AccountDetail struct {
3048 Name string `json:"name"`
3049 Id string `json:"id"`
3050 JetStreamStats
3051 Streams []StreamDetail `json:"stream_detail,omitempty"`
3052 }
3053
3054 // MetaSnapshotStats shows information about meta snapshots.
3055 type MetaSnapshotStats struct {
3056 PendingEntries uint64 `json:"pending_entries"` // PendingEntries is the count of pending entries in the meta layer
3057 PendingSize uint64 `json:"pending_size"` // PendingSize is the size in bytes of pending entries in the meta layer
3058 LastTime time.Time `json:"last_time,omitempty"` // LastTime is when the last meta snapshot was taken
3059 LastDuration time.Duration `json:"last_duration,omitempty"` // LastDuration is how long the last meta snapshot took
3060 }
3061
3062 // metaClusterSnapshotStats returns snapshot statistics for the meta group.
3063 func (s *Server) metaClusterSnapshotStats(js *jetStream, mg RaftNode) *MetaSnapshotStats {
3064 entries, bytes := mg.Size()
3065 snap := &MetaSnapshotStats{
3066 PendingEntries: entries,
3067 PendingSize: bytes,
3068 }
3069
3070 js.mu.RLock()
3071 cluster := js.cluster
3072 js.mu.RUnlock()
3073
3074 if cluster != nil {
3075 timeNanos := atomic.LoadInt64(&cluster.lastMetaSnapTime)
3076 durationNanos := atomic.LoadInt64(&cluster.lastMetaSnapDuration)
3077 if timeNanos > 0 {
3078 snap.LastTime = time.Unix(0, timeNanos).UTC()
3079 }
3080 if durationNanos > 0 {
3081 snap.LastDuration = time.Duration(durationNanos)
3082 }
3083 }
3084
3085 return snap
3086 }
3087
3088 // MetaClusterInfo shows information about the meta group.
3089 type MetaClusterInfo struct {
3090 Name string `json:"name,omitempty"` // Name is the name of the cluster
3091 Leader string `json:"leader,omitempty"` // Leader is the server name of the cluster leader
3092 Peer string `json:"peer,omitempty"` // Peer is unique ID of the leader
3093 Replicas []*PeerInfo `json:"replicas,omitempty"` // Replicas is a list of known peers
3094 Size int `json:"cluster_size"` // Size is the known size of the cluster
3095 Pending int `json:"pending"` // Pending is how many RAFT messages are not yet processed
3096 PendingRequests int `json:"pending_requests"` // PendingRequests is how many CRUD operations are queued for processing
3097 PendingInfos int `json:"pending_infos"` // PendingInfos is how many info operations are queued for processing
3098 Snapshot *MetaSnapshotStats `json:"snapshot"` // Snapshot contains meta snapshot statistics
3099 }
3100
3101 // JSInfo has detailed information on JetStream.
3102 type JSInfo struct {
3103 JetStreamStats
3104 ID string `json:"server_id"`
3105 Now time.Time `json:"now"`
3106 Disabled bool `json:"disabled,omitempty"`
3107 Config JetStreamConfig `json:"config,omitempty"`
3108 Limits *JSLimitOpts `json:"limits,omitempty"`
3109 Streams int `json:"streams"`
3110 StreamsLeader int `json:"streams_leader,omitempty"`
3111 Consumers int `json:"consumers"`
3112 ConsumersLeader int `json:"consumers_leader,omitempty"`
3113 Messages uint64 `json:"messages"`
3114 Bytes uint64 `json:"bytes"`
3115 Meta *MetaClusterInfo `json:"meta_cluster,omitempty"`
3116 AccountDetails []*AccountDetail `json:"account_details,omitempty"`
3117 Total int `json:"total"`
3118 }
3119
3120 func (s *Server) accountDetail(jsa *jsAccount, optStreams, optConsumers, optDirectConsumers, optCfg, optRaft, optStreamLeader bool) *AccountDetail {
3121 jsa.mu.RLock()
3122 acc := jsa.account
3123 name := acc.GetName()
3124 id := name
3125 if acc.nameTag != _EMPTY_ {
3126 name = acc.nameTag
3127 }
3128 jsa.usageMu.RLock()
3129 totalMem, totalStore := jsa.storageTotals()
3130 detail := AccountDetail{
3131 Name: name,
3132 Id: id,
3133 JetStreamStats: JetStreamStats{
3134 Memory: totalMem,
3135 Store: totalStore,
3136 API: JetStreamAPIStats{
3137 Total: jsa.apiTotal,
3138 Errors: jsa.apiErrors,
3139 },
3140 },
3141 Streams: make([]StreamDetail, 0, len(jsa.streams)),
3142 }
3143 if reserved, ok := jsa.limits[_EMPTY_]; ok {
3144 detail.JetStreamStats.ReservedMemory = uint64(reserved.MaxMemory)
3145 detail.JetStreamStats.ReservedStore = uint64(reserved.MaxStore)
3146 }
3147 jsa.usageMu.RUnlock()
3148
3149 var streams []*stream
3150 if optStreams {
3151 for _, stream := range jsa.streams {
3152 streams = append(streams, stream)
3153 }
3154 }
3155 jsa.mu.RUnlock()
3156
3157 if js := s.getJetStream(); js != nil && optStreams {
3158 for _, stream := range streams {
3159 rgroup := stream.raftGroup()
3160 ci := js.clusterInfo(rgroup)
3161 var cfg *StreamConfig
3162 if optCfg {
3163 c := stream.config()
3164 cfg = &c
3165 }
3166 // Skip if we are only looking for stream leaders.
3167 if optStreamLeader && ci != nil && ci.Leader != s.Name() {
3168 continue
3169 }
3170 sdet := StreamDetail{
3171 Name: stream.name(),
3172 Created: stream.createdTime(),
3173 State: stream.state(),
3174 Cluster: ci,
3175 Config: cfg,
3176 Mirror: stream.mirrorInfo(),
3177 Sources: stream.sourcesInfo(),
3178 }
3179 if optRaft && rgroup != nil {
3180 sdet.RaftGroup = rgroup.Name
3181 sdet.ConsumerRaftGroups = make([]*RaftGroupDetail, 0)
3182 }
3183 if optConsumers {
3184 for _, consumer := range stream.getPublicConsumers() {
3185 cInfo := consumer.info()
3186 if cInfo == nil {
3187 continue
3188 }
3189 if !optCfg {
3190 cInfo.Config = nil
3191 }
3192 sdet.Consumer = append(sdet.Consumer, cInfo)
3193 if optRaft {
3194 crgroup := consumer.raftGroup()
3195 if crgroup != nil {
3196 sdet.ConsumerRaftGroups = append(sdet.ConsumerRaftGroups,
3197 &RaftGroupDetail{cInfo.Name, crgroup.Name},
3198 )
3199 }
3200 }
3201 }
3202 if optDirectConsumers {
3203 for _, consumer := range stream.getDirectConsumers() {
3204 cInfo := consumer.info()
3205 if cInfo == nil {
3206 continue
3207 }
3208 if !optCfg {
3209 cInfo.Config = nil
3210 }
3211 sdet.DirectConsumer = append(sdet.DirectConsumer, cInfo)
3212 }
3213 }
3214 }
3215 detail.Streams = append(detail.Streams, sdet)
3216 }
3217 }
3218 return &detail
3219 }
3220
3221 func (s *Server) JszAccount(opts *JSzOptions) (*AccountDetail, error) {
3222 js := s.getJetStream()
3223 if js == nil {
3224 return nil, fmt.Errorf("jetstream not enabled")
3225 }
3226 acc := opts.Account
3227 account, ok := s.accounts.Load(acc)
3228 if !ok {
3229 return nil, fmt.Errorf("account %q not found", acc)
3230 }
3231 js.mu.RLock()
3232 jsa, ok := js.accounts[account.(*Account).Name]
3233 js.mu.RUnlock()
3234 if !ok {
3235 return nil, fmt.Errorf("account %q not jetstream enabled", acc)
3236 }
3237 return s.accountDetail(jsa, opts.Streams, opts.Consumer, opts.DirectConsumer, opts.Config, opts.RaftGroups, opts.StreamLeaderOnly), nil
3238 }
3239
3240 // helper to get cluster info from node via dummy group
3241 func (s *Server) raftNodeToClusterInfo(node RaftNode) *ClusterInfo {
3242 if node == nil {
3243 return nil
3244 }
3245 peers := node.Peers()
3246 peerList := make([]string, len(peers))
3247 for i, p := range peers {
3248 peerList[i] = p.ID
3249 }
3250 group := &raftGroup{
3251 Name: _EMPTY_,
3252 Peers: peerList,
3253 node: node,
3254 }
3255 return s.getJetStream().clusterInfo(group)
3256 }
3257
3258 // Jsz returns a Jsz structure containing information about JetStream.
3259 func (s *Server) Jsz(opts *JSzOptions) (*JSInfo, error) {
3260 // set option defaults
3261 if opts == nil {
3262 opts = &JSzOptions{}
3263 }
3264 if opts.Offset < 0 {
3265 opts.Offset = 0
3266 }
3267 if opts.Limit == 0 {
3268 opts.Limit = 1024
3269 }
3270 if opts.Consumer {
3271 opts.Streams = true
3272 }
3273 if opts.Streams && opts.Account == _EMPTY_ {
3274 opts.Accounts = true
3275 }
3276
3277 jsi := &JSInfo{
3278 ID: s.ID(),
3279 Now: time.Now().UTC(),
3280 }
3281
3282 js := s.getJetStream()
3283 if js == nil || !js.isEnabled() {
3284 if opts.LeaderOnly {
3285 return nil, fmt.Errorf("%w: not leader", errSkipZreq)
3286 }
3287
3288 jsi.Disabled = true
3289 return jsi, nil
3290 }
3291
3292 jsi.Limits = &s.getOpts().JetStreamLimits
3293
3294 js.mu.RLock()
3295 isLeader := js.cluster == nil || js.cluster.isLeader()
3296 js.mu.RUnlock()
3297
3298 if opts.LeaderOnly && !isLeader {
3299 return nil, fmt.Errorf("%w: not leader", errSkipZreq)
3300 }
3301
3302 var accounts []*jsAccount
3303
3304 js.mu.RLock()
3305 jsi.Config = js.config
3306 for _, info := range js.accounts {
3307 accounts = append(accounts, info)
3308 }
3309 js.mu.RUnlock()
3310
3311 jsi.Total = len(accounts)
3312
3313 if mg := js.getMetaGroup(); mg != nil {
3314 if ci := s.raftNodeToClusterInfo(mg); ci != nil {
3315 jsi.Meta = &MetaClusterInfo{Name: ci.Name, Leader: ci.Leader, Peer: getHash(ci.Leader), Size: mg.ClusterSize()}
3316 if isLeader {
3317 jsi.Meta.Replicas = ci.Replicas
3318 }
3319 if ipq := s.jsAPIRoutedReqs; ipq != nil {
3320 jsi.Meta.PendingRequests = ipq.len()
3321 }
3322 if ipq := s.jsAPIRoutedInfoReqs; ipq != nil {
3323 jsi.Meta.PendingInfos = ipq.len()
3324 }
3325 jsi.Meta.Pending = jsi.Meta.PendingRequests + jsi.Meta.PendingInfos
3326 jsi.Meta.Snapshot = s.metaClusterSnapshotStats(js, mg)
3327 }
3328 }
3329
3330 jsi.JetStreamStats = *js.usageStats()
3331
3332 // If a specific account is requested, track the index.
3333 filterIdx := -1
3334
3335 // Calculate the stats of all accounts and streams regardless of the filtering.
3336 for i, jsa := range accounts {
3337 if jsa.acc().GetName() == opts.Account {
3338 filterIdx = i
3339 }
3340
3341 jsa.mu.RLock()
3342 streams := make([]*stream, 0, len(jsa.streams))
3343 for _, stream := range jsa.streams {
3344 streams = append(streams, stream)
3345 }
3346 jsa.mu.RUnlock()
3347
3348 jsi.Streams += len(streams)
3349 for _, stream := range streams {
3350 streamState := stream.state()
3351 jsi.Messages += streamState.Msgs
3352 jsi.Bytes += streamState.Bytes
3353 jsi.Consumers += streamState.Consumers
3354 if opts.RaftGroups {
3355 if node := stream.raftNode(); node == nil || node.Leader() {
3356 jsi.StreamsLeader++
3357 }
3358 for _, consumer := range stream.getPublicConsumers() {
3359 if node := consumer.raftNode(); node == nil || node.Leader() {
3360 jsi.ConsumersLeader++
3361 }
3362 }
3363 }
3364 }
3365 }
3366
3367 // Targeted account takes precedence.
3368 if filterIdx >= 0 {
3369 accounts = accounts[filterIdx : filterIdx+1]
3370 } else if opts.Accounts {
3371
3372 if opts.Limit > 0 {
3373 // Sort by name for a consistent read (barring any concurrent changes)
3374 slices.SortFunc(accounts, func(i, j *jsAccount) int { return cmp.Compare(i.acc().Name, j.acc().Name) })
3375
3376 // Offset larger than the number of accounts.
3377 offset := min(opts.Offset, len(accounts))
3378 accounts = accounts[offset:]
3379
3380 limit := min(opts.Limit, len(accounts))
3381 accounts = accounts[:limit]
3382 }
3383 } else {
3384 accounts = nil
3385 }
3386
3387 if len(accounts) > 0 {
3388 jsi.AccountDetails = make([]*AccountDetail, 0, len(accounts))
3389
3390 for _, jsa := range accounts {
3391 detail := s.accountDetail(jsa, opts.Streams, opts.Consumer, opts.DirectConsumer, opts.Config, opts.RaftGroups, opts.StreamLeaderOnly)
3392 jsi.AccountDetails = append(jsi.AccountDetails, detail)
3393 }
3394 }
3395
3396 return jsi, nil
3397 }
3398
3399 // HandleJsz process HTTP requests for jetstream information.
3400 func (s *Server) HandleJsz(w http.ResponseWriter, r *http.Request) {
3401 s.mu.Lock()
3402 s.httpReqStats[JszPath]++
3403 s.mu.Unlock()
3404 accounts, err := decodeBool(w, r, "accounts")
3405 if err != nil {
3406 return
3407 }
3408 streams, err := decodeBool(w, r, "streams")
3409 if err != nil {
3410 return
3411 }
3412 consumers, err := decodeBool(w, r, "consumers")
3413 if err != nil {
3414 return
3415 }
3416 directConsumers, err := decodeBool(w, r, "direct-consumers")
3417 if err != nil {
3418 return
3419 }
3420 config, err := decodeBool(w, r, "config")
3421 if err != nil {
3422 return
3423 }
3424 offset, err := decodeInt(w, r, "offset")
3425 if err != nil {
3426 return
3427 }
3428 limit, err := decodeInt(w, r, "limit")
3429 if err != nil {
3430 return
3431 }
3432 leader, err := decodeBool(w, r, "leader-only")
3433 if err != nil {
3434 return
3435 }
3436 rgroups, err := decodeBool(w, r, "raft")
3437 if err != nil {
3438 return
3439 }
3440
3441 sleader, err := decodeBool(w, r, "stream-leader-only")
3442 if err != nil {
3443 return
3444 }
3445
3446 l, err := s.Jsz(&JSzOptions{
3447 Account: r.URL.Query().Get("acc"),
3448 Accounts: accounts,
3449 Streams: streams,
3450 Consumer: consumers,
3451 DirectConsumer: directConsumers,
3452 Config: config,
3453 LeaderOnly: leader,
3454 Offset: offset,
3455 Limit: limit,
3456 RaftGroups: rgroups,
3457 StreamLeaderOnly: sleader,
3458 })
3459 if err != nil {
3460 w.WriteHeader(http.StatusBadRequest)
3461 w.Write([]byte(err.Error()))
3462 return
3463 }
3464 b, err := json.MarshalIndent(l, "", " ")
3465 if err != nil {
3466 s.Errorf("Error marshaling response to /jsz request: %v", err)
3467 }
3468
3469 // Handle response
3470 ResponseHandler(w, r, b)
3471 }
3472
3473 type HealthStatus struct {
3474 Status string `json:"status"`
3475 StatusCode int `json:"status_code,omitempty"`
3476 Error string `json:"error,omitempty"`
3477 Errors []HealthzError `json:"errors,omitempty"`
3478 }
3479
3480 type HealthzError struct {
3481 Type HealthZErrorType `json:"type"`
3482 Account string `json:"account,omitempty"`
3483 Stream string `json:"stream,omitempty"`
3484 Consumer string `json:"consumer,omitempty"`
3485 Error string `json:"error,omitempty"`
3486 }
3487
3488 type HealthZErrorType int
3489
3490 const (
3491 HealthzErrorConn HealthZErrorType = iota
3492 HealthzErrorBadRequest
3493 HealthzErrorJetStream
3494 HealthzErrorAccount
3495 HealthzErrorStream
3496 HealthzErrorConsumer
3497 )
3498
3499 func (t HealthZErrorType) String() string {
3500 switch t {
3501 case HealthzErrorConn:
3502 return "CONNECTION"
3503 case HealthzErrorBadRequest:
3504 return "BAD_REQUEST"
3505 case HealthzErrorJetStream:
3506 return "JETSTREAM"
3507 case HealthzErrorAccount:
3508 return "ACCOUNT"
3509 case HealthzErrorStream:
3510 return "STREAM"
3511 case HealthzErrorConsumer:
3512 return "CONSUMER"
3513 default:
3514 return "unknown"
3515 }
3516 }
3517
3518 func (t HealthZErrorType) MarshalJSON() ([]byte, error) {
3519 return json.Marshal(t.String())
3520 }
3521
3522 func (t *HealthZErrorType) UnmarshalJSON(data []byte) error {
3523 switch string(data) {
3524 case `"CONNECTION"`:
3525 *t = HealthzErrorConn
3526 case `"BAD_REQUEST"`:
3527 *t = HealthzErrorBadRequest
3528 case `"JETSTREAM"`:
3529 *t = HealthzErrorJetStream
3530 case `"ACCOUNT"`:
3531 *t = HealthzErrorAccount
3532 case `"STREAM"`:
3533 *t = HealthzErrorStream
3534 case `"CONSUMER"`:
3535 *t = HealthzErrorConsumer
3536 default:
3537 return fmt.Errorf("unknown healthz error type %q", data)
3538 }
3539 return nil
3540 }
3541
3542 // https://datatracker.ietf.org/doc/html/draft-inadarei-api-health-check
3543 func (s *Server) HandleHealthz(w http.ResponseWriter, r *http.Request) {
3544 s.mu.Lock()
3545 s.httpReqStats[HealthzPath]++
3546 s.mu.Unlock()
3547
3548 jsEnabled, err := decodeBool(w, r, "js-enabled")
3549 if err != nil {
3550 return
3551 }
3552 if jsEnabled {
3553 s.Warnf("Healthcheck: js-enabled deprecated, use js-enabled-only instead")
3554 }
3555 jsEnabledOnly, err := decodeBool(w, r, "js-enabled-only")
3556 if err != nil {
3557 return
3558 }
3559 jsServerOnly, err := decodeBool(w, r, "js-server-only")
3560 if err != nil {
3561 return
3562 }
3563 jsMetaOnly, err := decodeBool(w, r, "js-meta-only")
3564 if err != nil {
3565 return
3566 }
3567
3568 includeDetails, err := decodeBool(w, r, "details")
3569 if err != nil {
3570 return
3571 }
3572
3573 hs := s.healthz(&HealthzOptions{
3574 JSEnabled: jsEnabled,
3575 JSEnabledOnly: jsEnabledOnly,
3576 JSServerOnly: jsServerOnly,
3577 JSMetaOnly: jsMetaOnly,
3578 Account: r.URL.Query().Get("account"),
3579 Stream: r.URL.Query().Get("stream"),
3580 Consumer: r.URL.Query().Get("consumer"),
3581 Details: includeDetails,
3582 })
3583
3584 code := hs.StatusCode
3585 if hs.Error != _EMPTY_ {
3586 s.Warnf("Healthcheck failed: %q", hs.Error)
3587 } else if len(hs.Errors) != 0 {
3588 s.Warnf("Healthcheck failed: %d errors", len(hs.Errors))
3589 }
3590 // Remove StatusCode from JSON representation when responding via HTTP
3591 // since this is already in the response.
3592 hs.StatusCode = 0
3593 b, err := json.Marshal(hs)
3594 if err != nil {
3595 s.Errorf("Error marshaling response to /healthz request: %v", err)
3596 }
3597
3598 handleResponse(code, w, r, b)
3599 }
3600
3601 // Generate health status.
3602 func (s *Server) healthz(opts *HealthzOptions) *HealthStatus {
3603 var health = &HealthStatus{Status: "ok"}
3604
3605 // set option defaults
3606 if opts == nil {
3607 opts = &HealthzOptions{}
3608 }
3609 details := opts.Details
3610 defer func() {
3611 // for response with details enabled, set status to either "error" or "ok"
3612 if details {
3613 if len(health.Errors) != 0 {
3614 health.Status = "error"
3615 } else {
3616 health.Status = "ok"
3617 }
3618 }
3619 // if no specific status code was set, set it based on the presence of errors
3620 if health.StatusCode == 0 {
3621 if health.Error != _EMPTY_ || len(health.Errors) != 0 {
3622 health.StatusCode = http.StatusServiceUnavailable
3623 } else {
3624 health.StatusCode = http.StatusOK
3625 }
3626 }
3627 }()
3628
3629 if opts.Account == _EMPTY_ && opts.Stream != _EMPTY_ {
3630 health.StatusCode = http.StatusBadRequest
3631 if !details {
3632 health.Status = "error"
3633 health.Error = fmt.Sprintf("%q must not be empty when checking stream health", "account")
3634 } else {
3635 health.Errors = append(health.Errors, HealthzError{
3636 Type: HealthzErrorBadRequest,
3637 Error: fmt.Sprintf("%q must not be empty when checking stream health", "account"),
3638 })
3639 }
3640 return health
3641 }
3642
3643 if opts.Stream == _EMPTY_ && opts.Consumer != _EMPTY_ {
3644 health.StatusCode = http.StatusBadRequest
3645 if !details {
3646 health.Status = "error"
3647 health.Error = fmt.Sprintf("%q must not be empty when checking consumer health", "stream")
3648 } else {
3649 health.Errors = append(health.Errors, HealthzError{
3650 Type: HealthzErrorBadRequest,
3651 Error: fmt.Sprintf("%q must not be empty when checking consumer health", "stream"),
3652 })
3653 }
3654 return health
3655 }
3656
3657 if err := s.readyForConnections(time.Millisecond); err != nil {
3658 health.StatusCode = http.StatusInternalServerError
3659 health.Status = "error"
3660 if !details {
3661 health.Error = err.Error()
3662 } else {
3663 health.Errors = append(health.Errors, HealthzError{
3664 Type: HealthzErrorConn,
3665 Error: err.Error(),
3666 })
3667 }
3668 return health
3669 }
3670
3671 // If JSServerOnly is true, then do not check further accounts, streams and consumers.
3672 if opts.JSServerOnly {
3673 return health
3674 }
3675
3676 sopts := s.getOpts()
3677
3678 // If JS is not enabled in the config, we stop.
3679 if !sopts.JetStream {
3680 return health
3681 }
3682
3683 // Access the Jetstream state to perform additional checks.
3684 js := s.getJetStream()
3685 const na = "unavailable"
3686 if !js.isEnabled() {
3687 health.StatusCode = http.StatusServiceUnavailable
3688 health.Status = na
3689 if !details {
3690 health.Error = NewJSNotEnabledError().Error()
3691 } else {
3692 health.Errors = append(health.Errors, HealthzError{
3693 Type: HealthzErrorJetStream,
3694 Error: NewJSNotEnabledError().Error(),
3695 })
3696 }
3697 return health
3698 }
3699 // Only check if JS is enabled, skip meta and asset check.
3700 if opts.JSEnabledOnly || opts.JSEnabled {
3701 return health
3702 }
3703
3704 // Clustered JetStream
3705 js.mu.RLock()
3706 cc := js.cluster
3707 js.mu.RUnlock()
3708
3709 // Currently single server we make sure the streams were recovered.
3710 if cc == nil {
3711 sdir := js.config.StoreDir
3712 // Whip through account folders and pull each stream name.
3713 fis, _ := os.ReadDir(sdir)
3714 var accFound, streamFound, consumerFound bool
3715 for _, fi := range fis {
3716 if fi.Name() == snapStagingDir {
3717 continue
3718 }
3719 if opts.Account != _EMPTY_ {
3720 if fi.Name() != opts.Account {
3721 continue
3722 }
3723 accFound = true
3724 }
3725 acc, err := s.LookupAccount(fi.Name())
3726 // Expired accounts are not a JetStream health problem; skip them when
3727 // scanning all accounts. Still surface an error if this account was
3728 // explicitly requested — including the err==nil + IsExpired() case.
3729 expired := (err != nil && errors.Is(err, ErrAccountExpired)) || (err == nil && acc.IsExpired())
3730 if expired {
3731 if opts.Account == _EMPTY_ {
3732 continue
3733 }
3734 msg := fmt.Sprintf("JetStream account '%s' is expired", fi.Name())
3735 if !details {
3736 health.Status = na
3737 health.Error = msg
3738 return health
3739 }
3740 health.Errors = append(health.Errors, HealthzError{
3741 Type: HealthzErrorAccount,
3742 Account: fi.Name(),
3743 Error: msg,
3744 })
3745 // Return so later stream/consumer not-found checks do not
3746 // replace this with a misleading 404 for assets we skipped.
3747 return health
3748 }
3749 if err != nil {
3750 if !details {
3751 health.Status = na
3752 health.Error = fmt.Sprintf("JetStream account '%s' could not be resolved", fi.Name())
3753 return health
3754 }
3755 health.Errors = append(health.Errors, HealthzError{
3756 Type: HealthzErrorAccount,
3757 Account: fi.Name(),
3758 Error: fmt.Sprintf("JetStream account '%s' could not be resolved", fi.Name()),
3759 })
3760 continue
3761 }
3762 sfis, _ := os.ReadDir(filepath.Join(sdir, fi.Name(), "streams"))
3763 for _, sfi := range sfis {
3764 if opts.Stream != _EMPTY_ {
3765 if sfi.Name() != opts.Stream {
3766 continue
3767 }
3768 streamFound = true
3769 }
3770 stream := sfi.Name()
3771 s, err := acc.lookupStream(stream)
3772 if err != nil {
3773 if !details {
3774 health.Status = na
3775 health.Error = fmt.Sprintf("JetStream stream '%s > %s' could not be recovered", acc, stream)
3776 return health
3777 }
3778 health.Errors = append(health.Errors, HealthzError{
3779 Type: HealthzErrorStream,
3780 Account: acc.Name,
3781 Stream: stream,
3782 Error: fmt.Sprintf("JetStream stream '%s > %s' could not be recovered", acc, stream),
3783 })
3784 continue
3785 }
3786 if streamWerr := s.getWriteErr(); streamWerr != nil {
3787 if !details {
3788 health.Status = na
3789 health.Error = fmt.Sprintf("JetStream stream '%s > %s' write error: %v", acc, stream, streamWerr)
3790 return health
3791 }
3792 health.Errors = append(health.Errors, HealthzError{
3793 Type: HealthzErrorStream,
3794 Account: acc.Name,
3795 Stream: stream,
3796 Error: fmt.Sprintf("JetStream stream '%s > %s' write error: %v", acc, stream, streamWerr),
3797 })
3798 continue
3799 }
3800 if streamFound {
3801 // if consumer option is passed, verify that the consumer exists on stream
3802 if opts.Consumer != _EMPTY_ {
3803 if s.lookupConsumer(opts.Consumer) != nil {
3804 consumerFound = true
3805 }
3806 }
3807 break
3808 }
3809 }
3810 if accFound {
3811 break
3812 }
3813 }
3814 if opts.Account != _EMPTY_ && !accFound {
3815 health.StatusCode = http.StatusNotFound
3816 if !details {
3817 health.Status = na
3818 health.Error = fmt.Sprintf("JetStream account %q not found", opts.Account)
3819 } else {
3820 health.Errors = []HealthzError{
3821 {
3822 Type: HealthzErrorAccount,
3823 Account: opts.Account,
3824 Error: fmt.Sprintf("JetStream account %q not found", opts.Account),
3825 },
3826 }
3827 }
3828 return health
3829 }
3830 if opts.Stream != _EMPTY_ && !streamFound {
3831 health.StatusCode = http.StatusNotFound
3832 if !details {
3833 health.Status = na
3834 health.Error = fmt.Sprintf("JetStream stream %q not found on account %q", opts.Stream, opts.Account)
3835 } else {
3836 health.Errors = []HealthzError{
3837 {
3838 Type: HealthzErrorStream,
3839 Account: opts.Account,
3840 Stream: opts.Stream,
3841 Error: fmt.Sprintf("JetStream stream %q not found on account %q", opts.Stream, opts.Account),
3842 },
3843 }
3844 }
3845 return health
3846 }
3847 if opts.Consumer != _EMPTY_ && !consumerFound {
3848 health.StatusCode = http.StatusNotFound
3849 if !details {
3850 health.Status = na
3851 health.Error = fmt.Sprintf("JetStream consumer %q not found for stream %q on account %q", opts.Consumer, opts.Stream, opts.Account)
3852 } else {
3853 health.Errors = []HealthzError{
3854 {
3855 Type: HealthzErrorConsumer,
3856 Account: opts.Account,
3857 Stream: opts.Stream,
3858 Consumer: opts.Consumer,
3859 Error: fmt.Sprintf("JetStream consumer %q not found for stream %q on account %q", opts.Consumer, opts.Stream, opts.Account),
3860 },
3861 }
3862 }
3863 }
3864 return health
3865 }
3866
3867 // If we are here we want to check for any assets assigned to us.
3868 var meta RaftNode
3869 js.mu.RLock()
3870 meta = cc.meta
3871 js.mu.RUnlock()
3872
3873 // Check meta layer health.
3874 var metaNoLeader, metaClosed, metaUnhealthy bool
3875 var metaWerr error
3876 if meta != nil {
3877 metaNoLeader = meta.GroupLeader() == _EMPTY_
3878 metaClosed = meta.State() == Closed
3879 metaUnhealthy = !meta.Healthy()
3880 metaWerr = meta.GetWriteErr()
3881 }
3882 metaRecovering := js.isMetaRecovering()
3883 if meta == nil || metaNoLeader || metaClosed || metaUnhealthy || metaWerr != nil || metaRecovering {
3884 var desc string
3885 if metaWerr != nil {
3886 desc = fmt.Sprintf("JetStream meta layer write error: %v", metaWerr)
3887 } else if metaClosed {
3888 desc = "JetStream meta layer is not running"
3889 } else if meta != nil && metaRecovering {
3890 desc = "JetStream is still recovering meta layer"
3891 } else if meta == nil || metaNoLeader {
3892 desc = "JetStream has not established contact with a meta leader"
3893 } else {
3894 desc = "JetStream is not current with the meta leader"
3895 }
3896 if !details {
3897 health.Status = na
3898 health.Error = desc
3899 } else {
3900 health.Errors = []HealthzError{
3901 {
3902 Type: HealthzErrorJetStream,
3903 Error: desc,
3904 },
3905 }
3906 }
3907 return health
3908 }
3909
3910 // Skips doing full healthz and only checks the meta leader.
3911 if opts.JSMetaOnly {
3912 return health
3913 }
3914
3915 // Range across all accounts, the streams assigned to them, and the consumers.
3916 // If they are assigned to this server check their status.
3917 ourID := meta.ID()
3918
3919 // Copy the meta layer so we do not need to hold the js read lock for an extended period of time.
3920 var streams map[string]map[string]*streamAssignment
3921 js.mu.RLock()
3922 if opts.Account == _EMPTY_ {
3923 // Collect all relevant streams and consumers.
3924 streams = make(map[string]map[string]*streamAssignment, len(cc.streams))
3925 for acc, asa := range cc.streams {
3926 nasa := make(map[string]*streamAssignment)
3927 for stream, sa := range asa {
3928 // If we are a member and we are not being restored, select for check.
3929 if sa.Group.isMember(ourID) && sa.Restore == nil {
3930 csa := sa.copyGroup()
3931 csa.consumers = make(map[string]*consumerAssignment)
3932 for consumer, ca := range sa.consumers {
3933 if ca.Group.isMember(ourID) {
3934 // Use original here. Not a copy.
3935 csa.consumers[consumer] = ca
3936 }
3937 }
3938 nasa[stream] = csa
3939 }
3940 }
3941 streams[acc] = nasa
3942 }
3943 } else {
3944 streams = make(map[string]map[string]*streamAssignment, 1)
3945 asa, ok := cc.streams[opts.Account]
3946 if !ok {
3947 health.StatusCode = http.StatusNotFound
3948 if !details {
3949 health.Status = na
3950 health.Error = fmt.Sprintf("JetStream account %q not found", opts.Account)
3951 } else {
3952 health.Errors = []HealthzError{
3953 {
3954 Type: HealthzErrorAccount,
3955 Account: opts.Account,
3956 Error: fmt.Sprintf("JetStream account %q not found", opts.Account),
3957 },
3958 }
3959 }
3960 js.mu.RUnlock()
3961 return health
3962 }
3963 nasa := make(map[string]*streamAssignment)
3964 if opts.Stream != _EMPTY_ {
3965 sa, ok := asa[opts.Stream]
3966 if !ok || !sa.Group.isMember(ourID) {
3967 health.StatusCode = http.StatusNotFound
3968 if !details {
3969 health.Status = na
3970 health.Error = fmt.Sprintf("JetStream stream %q not found on account %q", opts.Stream, opts.Account)
3971 } else {
3972 health.Errors = []HealthzError{
3973 {
3974 Type: HealthzErrorStream,
3975 Account: opts.Account,
3976 Stream: opts.Stream,
3977 Error: fmt.Sprintf("JetStream stream %q not found on account %q", opts.Stream, opts.Account),
3978 },
3979 }
3980 }
3981 js.mu.RUnlock()
3982 return health
3983 }
3984 csa := sa.copyGroup()
3985 csa.consumers = make(map[string]*consumerAssignment)
3986 var consumerFound bool
3987 for consumer, ca := range sa.consumers {
3988 if opts.Consumer != _EMPTY_ {
3989 if consumer != opts.Consumer || !ca.Group.isMember(ourID) {
3990 continue
3991 }
3992 consumerFound = true
3993 }
3994 // If we are a member and we are not being restored, select for check.
3995 if sa.Group.isMember(ourID) && sa.Restore == nil {
3996 csa.consumers[consumer] = ca
3997 }
3998 if consumerFound {
3999 break
4000 }
4001 }
4002 if opts.Consumer != _EMPTY_ && !consumerFound {
4003 health.StatusCode = http.StatusNotFound
4004 if !details {
4005 health.Status = na
4006 health.Error = fmt.Sprintf("JetStream consumer %q not found for stream %q on account %q", opts.Consumer, opts.Stream, opts.Account)
4007 } else {
4008 health.Errors = []HealthzError{
4009 {
4010 Type: HealthzErrorConsumer,
4011 Account: opts.Account,
4012 Stream: opts.Stream,
4013 Consumer: opts.Consumer,
4014 Error: fmt.Sprintf("JetStream consumer %q not found for stream %q on account %q", opts.Consumer, opts.Stream, opts.Account),
4015 },
4016 }
4017 }
4018 js.mu.RUnlock()
4019 return health
4020 }
4021 nasa[opts.Stream] = csa
4022 } else {
4023 for stream, sa := range asa {
4024 // If we are a member and we are not being restored, select for check.
4025 if sa.Group.isMember(ourID) && sa.Restore == nil {
4026 csa := sa.copyGroup()
4027 csa.consumers = make(map[string]*consumerAssignment)
4028 for consumer, ca := range sa.consumers {
4029 if ca.Group.isMember(ourID) {
4030 csa.consumers[consumer] = ca
4031 }
4032 }
4033 nasa[stream] = csa
4034 }
4035 }
4036 }
4037 streams[opts.Account] = nasa
4038 }
4039 js.mu.RUnlock()
4040
4041 // Use our copy to traverse so we do not need to hold the js lock.
4042 for accName, asa := range streams {
4043 acc, err := s.LookupAccount(accName)
4044 // Expired accounts are not a JetStream health problem; skip them when
4045 // scanning all accounts. Still surface an error if this account was
4046 // explicitly requested — including the err==nil + IsExpired() case.
4047 expired := (err != nil && errors.Is(err, ErrAccountExpired)) || (err == nil && acc.IsExpired())
4048 if expired {
4049 if opts.Account == _EMPTY_ {
4050 continue
4051 }
4052 msg := fmt.Sprintf("JetStream account %q is expired", accName)
4053 if !details {
4054 health.Status = na
4055 health.Error = msg
4056 return health
4057 }
4058 health.Errors = append(health.Errors, HealthzError{
4059 Type: HealthzErrorAccount,
4060 Account: accName,
4061 Error: msg,
4062 })
4063 // Return so later health checks do not obscure the expired account.
4064 return health
4065 }
4066 if err != nil && len(asa) > 0 {
4067 if !details {
4068 health.Status = na
4069 health.Error = fmt.Sprintf("JetStream can not lookup account %q: %v", accName, err)
4070 return health
4071 }
4072 health.Errors = append(health.Errors, HealthzError{
4073 Type: HealthzErrorAccount,
4074 Account: accName,
4075 Error: fmt.Sprintf("JetStream can not lookup account %q: %v", accName, err),
4076 })
4077 continue
4078 }
4079
4080 for stream, sa := range asa {
4081 if sa != nil && sa.unsupported != nil {
4082 continue
4083 }
4084 // Make sure we can look up
4085 if err := js.isStreamHealthy(acc, sa); err != nil {
4086 if !details {
4087 health.Status = na
4088 health.Error = fmt.Sprintf("JetStream stream '%s > %s' is not current: %s", accName, stream, err)
4089 return health
4090 }
4091 health.Errors = append(health.Errors, HealthzError{
4092 Type: HealthzErrorStream,
4093 Account: accName,
4094 Stream: stream,
4095 Error: fmt.Sprintf("JetStream stream '%s > %s' is not current: %s", accName, stream, err),
4096 })
4097 continue
4098 }
4099 mset, _ := acc.lookupStream(stream)
4100 // Now check consumers.
4101 for consumer, ca := range sa.consumers {
4102 if err := js.isConsumerHealthy(mset, consumer, ca); err != nil {
4103 if !details {
4104 health.Status = na
4105 health.Error = fmt.Sprintf("JetStream consumer '%s > %s > %s' is not current: %s", acc, stream, consumer, err)
4106 return health
4107 }
4108 health.Errors = append(health.Errors, HealthzError{
4109 Type: HealthzErrorConsumer,
4110 Account: accName,
4111 Stream: stream,
4112 Consumer: consumer,
4113 Error: fmt.Sprintf("JetStream consumer '%s > %s > %s' is not current: %s", acc, stream, consumer, err),
4114 })
4115 }
4116 }
4117 }
4118 }
4119 // Success.
4120 return health
4121 }
4122
4123 // Healthz returns the health status of the server.
4124 func (s *Server) Healthz(opts *HealthzOptions) *HealthStatus {
4125 return s.healthz(opts)
4126 }
4127
4128 type ExpvarzStatus struct {
4129 Memstats json.RawMessage `json:"memstats"`
4130 Cmdline json.RawMessage `json:"cmdline"`
4131 }
4132
4133 func (s *Server) expvarz(_ *ExpvarzEventOptions) *ExpvarzStatus {
4134 var stat ExpvarzStatus
4135
4136 const memStatsKey = "memstats"
4137 const cmdLineKey = "cmdline"
4138
4139 expvar.Do(func(v expvar.KeyValue) {
4140 switch v.Key {
4141 case memStatsKey:
4142 stat.Memstats = json.RawMessage(v.Value.String())
4143
4144 case cmdLineKey:
4145 stat.Cmdline = json.RawMessage(v.Value.String())
4146 }
4147 })
4148
4149 return &stat
4150 }
4151
4152 type ProfilezStatus struct {
4153 Profile []byte `json:"profile"`
4154 Error string `json:"error"`
4155 }
4156
4157 func (s *Server) profilez(opts *ProfilezOptions) *ProfilezStatus {
4158 var buffer bytes.Buffer
4159 switch opts.Name {
4160 case _EMPTY_:
4161 return &ProfilezStatus{
4162 Error: "Profile name not specified",
4163 }
4164 case "cpu":
4165 if opts.Duration <= 0 || opts.Duration > 15*time.Second {
4166 return &ProfilezStatus{
4167 Error: fmt.Sprintf("Duration %s should be between 0s and 15s", opts.Duration),
4168 }
4169 }
4170 if err := pprof.StartCPUProfile(&buffer); err != nil {
4171 return &ProfilezStatus{
4172 Error: fmt.Sprintf("Failed to start CPU profile: %s", err),
4173 }
4174 }
4175 time.Sleep(opts.Duration)
4176 pprof.StopCPUProfile()
4177 default:
4178 profile := pprof.Lookup(opts.Name)
4179 if profile == nil {
4180 return &ProfilezStatus{
4181 Error: fmt.Sprintf("Profile %q not found", opts.Name),
4182 }
4183 }
4184 if err := profile.WriteTo(&buffer, opts.Debug); err != nil {
4185 return &ProfilezStatus{
4186 Error: fmt.Sprintf("Profile %q error: %s", opts.Name, err),
4187 }
4188 }
4189 }
4190 return &ProfilezStatus{
4191 Profile: buffer.Bytes(),
4192 }
4193 }
4194
4195 type RaftzGroup struct {
4196 ID string `json:"id"`
4197 State string `json:"state"`
4198 Size int `json:"size"`
4199 QuorumNeeded int `json:"quorum_needed"`
4200 Observer bool `json:"observer,omitempty"`
4201 Paused bool `json:"paused,omitempty"`
4202 Overrun bool `json:"overrun,omitempty"`
4203 OverrunCount uint64 `json:"overrun_count,omitempty"`
4204 Committed uint64 `json:"committed"`
4205 Applied uint64 `json:"applied"`
4206 CatchingUp bool `json:"catching_up,omitempty"`
4207 Leader string `json:"leader,omitempty"`
4208 LeaderSince *time.Time `json:"leader_since,omitempty"`
4209 EverHadLeader bool `json:"ever_had_leader"`
4210 Term uint64 `json:"term"`
4211 Vote string `json:"voted_for,omitempty"`
4212 PTerm uint64 `json:"pterm"`
4213 PIndex uint64 `json:"pindex"`
4214 SystemAcc bool `json:"system_account"`
4215 TrafficAcc string `json:"traffic_account"`
4216 IPQPropLen int `json:"ipq_proposal_len"`
4217 IPQEntryLen int `json:"ipq_entry_len"`
4218 IPQRespLen int `json:"ipq_resp_len"`
4219 IPQApplyLen int `json:"ipq_apply_len"`
4220 WAL StreamState `json:"wal"`
4221 WALError error `json:"wal_error,omitempty"`
4222 Peers map[string]RaftzGroupPeer `json:"peers"`
4223 }
4224
4225 type RaftzGroupPeer struct {
4226 Name string `json:"name"`
4227 Known bool `json:"known"`
4228 LastReplicatedIndex uint64 `json:"last_replicated_index,omitempty"`
4229 LastSeen string `json:"last_seen,omitempty"`
4230 }
4231
4232 type RaftzStatus map[string]map[string]RaftzGroup
4233
4234 func (s *Server) HandleRaftz(w http.ResponseWriter, r *http.Request) {
4235 if s.raftNodes == nil {
4236 w.WriteHeader(404)
4237 w.Write([]byte("No Raft nodes registered"))
4238 return
4239 }
4240
4241 groups := s.Raftz(&RaftzOptions{
4242 AccountFilter: r.URL.Query().Get("acc"),
4243 GroupFilter: r.URL.Query().Get("group"),
4244 })
4245
4246 if groups == nil {
4247 w.WriteHeader(404)
4248 w.Write([]byte("No Raft nodes returned, check supplied filters"))
4249 return
4250 }
4251
4252 b, _ := json.MarshalIndent(groups, "", " ")
4253 ResponseHandler(w, r, b)
4254 }
4255
4256 func (s *Server) Raftz(opts *RaftzOptions) *RaftzStatus {
4257 afilter, gfilter := opts.AccountFilter, opts.GroupFilter
4258
4259 if afilter == _EMPTY_ {
4260 if sys := s.SystemAccount(); sys != nil {
4261 afilter = sys.Name
4262 } else {
4263 return nil
4264 }
4265 }
4266
4267 groups := map[string]RaftNode{}
4268 infos := RaftzStatus{} // account -> group ID
4269
4270 s.rnMu.RLock()
4271 if gfilter != _EMPTY_ {
4272 if rg, ok := s.raftNodes[gfilter]; ok && rg != nil {
4273 if n, ok := rg.(*raft); ok {
4274 if n.accName == afilter {
4275 groups[gfilter] = rg
4276 }
4277 }
4278 }
4279 } else {
4280 for name, rg := range s.raftNodes {
4281 if rg == nil {
4282 continue
4283 }
4284 if n, ok := rg.(*raft); ok {
4285 if n.accName != afilter {
4286 continue
4287 }
4288 groups[name] = rg
4289 }
4290 }
4291 }
4292 s.rnMu.RUnlock()
4293
4294 for name, rg := range groups {
4295 n, ok := rg.(*raft)
4296 if n == nil || !ok {
4297 continue
4298 }
4299 if _, ok := infos[n.accName]; !ok {
4300 infos[n.accName] = map[string]RaftzGroup{}
4301 }
4302 // Only take the lock once, using the public RaftNode functions would
4303 // cause us to take and release the locks over and over again.
4304 n.RLock()
4305 info := RaftzGroup{
4306 ID: n.id,
4307 State: RaftState(n.state.Load()).String(),
4308 Size: n.csz,
4309 QuorumNeeded: n.qn,
4310 Observer: n.observer,
4311 Paused: n.paused,
4312 Overrun: n.quorumPaused || n.isLeaderOverrun(),
4313 OverrunCount: n.overrunCount,
4314 Committed: n.commit,
4315 Applied: n.applied,
4316 CatchingUp: n.catchup != nil,
4317 Leader: n.leader,
4318 LeaderSince: n.leaderSince.Load(),
4319 EverHadLeader: n.pleader.Load(),
4320 Term: n.term,
4321 Vote: n.vote,
4322 PTerm: n.pterm,
4323 PIndex: n.pindex,
4324 SystemAcc: n.IsSystemAccount(),
4325 TrafficAcc: n.t.Account().GetName(),
4326 IPQPropLen: n.prop.len(),
4327 IPQEntryLen: n.entry.len(),
4328 IPQRespLen: n.resp.len(),
4329 IPQApplyLen: n.apply.len(),
4330 WALError: n.werr,
4331 Peers: map[string]RaftzGroupPeer{},
4332 }
4333 n.wal.FastState(&info.WAL)
4334 for id, p := range n.peers {
4335 if id == n.id {
4336 continue
4337 }
4338 kp := n.membChange == nil || n.membChange.peer != id
4339 peer := RaftzGroupPeer{
4340 Name: s.serverNameForNode(id),
4341 Known: kp,
4342 LastReplicatedIndex: p.li,
4343 }
4344 if !p.ts.IsZero() {
4345 peer.LastSeen = time.Since(p.ts).String()
4346 }
4347 info.Peers[id] = peer
4348 }
4349 n.RUnlock()
4350 infos[n.accName][name] = info
4351 }
4352
4353 return &infos
4354 }