Debian Codegraph @

server/monitor_test.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 package server
14
15 import (
16 "bufio"
17 "bytes"
18 "crypto/tls"
19 "encoding/base64"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "io"
24 "math"
25 "math/rand"
26 "net"
27 "net/http"
28 "net/url"
29 "os"
30 "path/filepath"
31 "reflect"
32 "runtime"
33 "slices"
34 "sort"
35 "strings"
36 "sync"
37 "testing"
38 "time"
39 "unicode"
40
41 "github.com/nats-io/jwt/v2"
42 "github.com/nats-io/nats.go"
43 "github.com/nats-io/nkeys"
44 )
45
46 const CLIENT_PORT = -1
47 const MONITOR_PORT = -1
48 const CLUSTER_PORT = -1
49
50 func DefaultMonitorOptions() *Options {
51 return &Options{
52 Host: "127.0.0.1",
53 Port: CLIENT_PORT,
54 HTTPHost: "127.0.0.1",
55 HTTPPort: MONITOR_PORT,
56 HTTPBasePath: "/",
57 ServerName: "monitor_server",
58 NoLog: true,
59 NoSigs: true,
60 Tags: []string{"tag"},
61 Metadata: map[string]string{"key1": "value1", "key2": "value2"},
62 FeatureFlags: map[string]bool{"feature": false, "fix": true, "revert_fix": true},
63 }
64 }
65
66 func runMonitorJSServer(t *testing.T, clientPort int, monitorPort int, clusterPort int, routePort int) (*Server, *Options) {
67 resetPreviousHTTPConnections()
68 tmpDir := t.TempDir()
69 cf := createConfFile(t, []byte(fmt.Sprintf(`
70 listen: 127.0.0.1:%d
71 http: 127.0.0.1:%d
72 system_account: SYS
73 accounts {
74 SYS {
75 users [{user: sys, password: pwd}]
76 }
77 ACC {
78 users [{user: usr, password: pwd}]
79 // In clustered mode, these reservations will not impact any one server.
80 jetstream: {max_store: 4Mb, max_memory: 5Mb}
81 }
82 BCC_TO_HAVE_ONE_EXTRA {
83 users [{user: usr2, password: pwd}]
84 jetstream: enabled
85 }
86 }
87 jetstream: {
88 max_mem_store: 10Mb
89 max_file_store: 10Mb
90 store_dir: '%s'
91 unique_tag: az
92 limits: {
93 max_ha_assets: 1000
94 }
95 }
96 cluster {
97 name: cluster_name
98 listen: 127.0.0.1:%d
99 routes: [nats-route://127.0.0.1:%d]
100 }
101 server_name: server_%d
102 server_tags: [ "az:%d", "tag" ] `, clientPort, monitorPort, tmpDir, clusterPort, routePort, clientPort, clientPort)))
103
104 return RunServerWithConfig(cf)
105 }
106
107 func runMonitorServer() *Server {
108 resetPreviousHTTPConnections()
109 opts := DefaultMonitorOptions()
110 opts.NoSystemAccount = true
111 return RunServer(opts)
112 }
113
114 func runMonitorServerWithAccounts() *Server {
115 resetPreviousHTTPConnections()
116 opts := DefaultMonitorOptions()
117 opts.NoSystemAccount = true
118 aA := NewAccount("A")
119 aB := NewAccount("B")
120 opts.Accounts = append(opts.Accounts, aA, aB)
121 opts.Users = append(opts.Users,
122 &User{Username: "a", Password: "a", Account: aA},
123 &User{Username: "b", Password: "b", Account: aB})
124 return RunServer(opts)
125 }
126
127 func runMonitorServerNoHTTPPort() *Server {
128 resetPreviousHTTPConnections()
129 opts := DefaultMonitorOptions()
130 opts.NoSystemAccount = true
131 opts.HTTPPort = 0
132 return RunServer(opts)
133 }
134
135 func resetPreviousHTTPConnections() {
136 http.DefaultTransport.(*http.Transport).CloseIdleConnections()
137 }
138
139 func TestMyUptime(t *testing.T) {
140 // Make sure we print this stuff right.
141 var d time.Duration
142 var s string
143
144 d = 22 * time.Second
145 s = myUptime(d)
146 if s != "22s" {
147 t.Fatalf("Expected `22s`, go ``%s`", s)
148 }
149 d = 4*time.Minute + d
150 s = myUptime(d)
151 if s != "4m22s" {
152 t.Fatalf("Expected `4m22s`, go ``%s`", s)
153 }
154 d = 4*time.Hour + d
155 s = myUptime(d)
156 if s != "4h4m22s" {
157 t.Fatalf("Expected `4h4m22s`, go ``%s`", s)
158 }
159 d = 32*24*time.Hour + d
160 s = myUptime(d)
161 if s != "32d4h4m22s" {
162 t.Fatalf("Expected `32d4h4m22s`, go ``%s`", s)
163 }
164 d = 22*365*24*time.Hour + d
165 s = myUptime(d)
166 if s != "22y32d4h4m22s" {
167 t.Fatalf("Expected `22y32d4h4m22s`, go ``%s`", s)
168 }
169 }
170
171 // Make sure that we do not run the http server for monitoring unless asked.
172 func TestMonitorNoPort(t *testing.T) {
173 s := runMonitorServerNoHTTPPort()
174 defer s.Shutdown()
175
176 // this test might be meaningless now that we're testing with random ports?
177 url := fmt.Sprintf("http://127.0.0.1:%d/", 11245)
178 if resp, err := http.Get(url + "varz"); err == nil {
179 t.Fatalf("Expected error: Got %+v\n", resp)
180 }
181 if resp, err := http.Get(url + "healthz"); err == nil {
182 t.Fatalf("Expected error: Got %+v\n", resp)
183 }
184 if resp, err := http.Get(url + "connz"); err == nil {
185 t.Fatalf("Expected error: Got %+v\n", resp)
186 }
187 }
188
189 var (
190 appJSONContent = "application/json"
191 textPlain = "text/plain; charset=utf-8"
192 textHTML = "text/html; charset=utf-8"
193 )
194
195 func readBodyEx(t *testing.T, url string, status int, content string) []byte {
196 t.Helper()
197 resp, err := http.Get(url)
198 if err != nil {
199 t.Fatalf("Expected no error: Got %v\n", err)
200 }
201 defer resp.Body.Close()
202 body, err := io.ReadAll(resp.Body)
203 if err != nil {
204 t.Fatalf("Got an error reading the body: %v\n", err)
205 }
206 if resp.StatusCode != status {
207 t.Fatalf("Expected a %d response, got %d\n%s", status, resp.StatusCode, string(body))
208 }
209 ct := resp.Header.Get("Content-Type")
210 if ct != content {
211 t.Fatalf("Expected %q content-type, got %q\n", content, ct)
212 }
213 // Check the CORS header for "application/json" requests only.
214 if ct == appJSONContent {
215 acao := resp.Header.Get("Access-Control-Allow-Origin")
216 if acao != "*" {
217 t.Fatalf("Expected with %q Content-Type an Access-Control-Allow-Origin header with value %q, got %q\n", appJSONContent, "*", acao)
218 }
219 }
220 return body
221 }
222
223 func TestMonitorHTTPBasePath(t *testing.T) {
224 resetPreviousHTTPConnections()
225 opts := DefaultMonitorOptions()
226 opts.NoSystemAccount = true
227 opts.HTTPBasePath = "/nats"
228
229 s := RunServer(opts)
230 defer s.Shutdown()
231
232 url := fmt.Sprintf("http://127.0.0.1:%d/nats", s.MonitorAddr().Port)
233 readBodyEx(t, url, http.StatusOK, textHTML)
234 }
235
236 func readBody(t *testing.T, url string) []byte {
237 t.Helper()
238 return readBodyEx(t, url, http.StatusOK, appJSONContent)
239 }
240
241 func pollVarz(t *testing.T, s *Server, mode int, url string, opts *VarzOptions) *Varz {
242 t.Helper()
243 if mode == 0 {
244 v := &Varz{}
245 body := readBody(t, url)
246 if err := json.Unmarshal(body, v); err != nil {
247 t.Fatalf("Got an error unmarshalling the body: %v\n", err)
248 }
249 return v
250 }
251 v, err := s.Varz(opts)
252 if err != nil {
253 t.Fatalf("Error on Varz: %v", err)
254 }
255 return v
256 }
257
258 // https://github.com/nats-io/nats-server/issues/2170
259 // Just the ever increasing subs part.
260 func TestMonitorVarzSubscriptionsResetProperly(t *testing.T) {
261 // Run with JS to create a bunch of subs to start.
262 resetPreviousHTTPConnections()
263 opts := DefaultMonitorOptions()
264 opts.JetStream = true
265 s := RunServer(opts)
266 defer s.Shutdown()
267
268 // This bug seems to only happen via the http endpoint, not direct calls.
269 // Every time you call it doubles.
270 url := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
271 osubs := pollVarz(t, s, 0, url, nil).Subscriptions
272 // Make sure we get same number back.
273 if v := pollVarz(t, s, 0, url, nil); v.Subscriptions != osubs {
274 t.Fatalf("Expected subs to stay the same, %d vs %d", osubs, v.Subscriptions)
275 }
276 }
277
278 // Must be run with -race.
279 func TestMonitorVarzReloadRace(t *testing.T) {
280 resetPreviousHTTPConnections()
281 opts := DefaultMonitorOptions()
282 opts.NoSystemAccount = true
283 s := RunServer(opts)
284 defer s.Shutdown()
285
286 url := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
287
288 // Ensure s.varz is populated so the marshal path reads the shared object.
289 _, err := http.Get(url)
290 require_NoError(t, err)
291
292 var wg sync.WaitGroup
293 stop := make(chan struct{})
294
295 // Reader: hit /varz, which marshals s.varz under s.varzMu.
296 wg.Add(1)
297 go func() {
298 defer wg.Done()
299 for {
300 select {
301 case <-stop:
302 return
303 default:
304 resp, err := http.Get(url)
305 if err == nil {
306 io.Copy(io.Discard, resp.Body)
307 resp.Body.Close()
308 }
309 }
310 }
311 }()
312
313 // Writer: reload, which mutates s.varz via updateVarzConfigReloadableFields.
314 wg.Add(1)
315 go func() {
316 defer wg.Done()
317 for {
318 select {
319 case <-stop:
320 return
321 default:
322 if err := s.ReloadOptions(s.getOpts().Clone()); err != nil {
323 t.Errorf("Error on reload: %v", err)
324 return
325 }
326 }
327 }
328 }()
329
330 time.Sleep(500 * time.Millisecond)
331 close(stop)
332 wg.Wait()
333 }
334
335 func TestMonitorHandleVarz(t *testing.T) {
336 s, _ := runMonitorJSServer(t, -1, -1, 0, 0)
337 defer s.Shutdown()
338
339 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
340
341 for mode := 0; mode < 2; mode++ {
342 v := pollVarz(t, s, mode, url+"varz", nil)
343
344 // Do some sanity checks on values
345 if time.Since(v.Start) > 10*time.Second {
346 t.Fatal("Expected start time to be within 10 seconds.")
347 }
348 }
349
350 time.Sleep(100 * time.Millisecond)
351
352 nc := createClientConnWithUserSubscribeAndPublish(t, s, "sys", "pwd")
353 defer nc.Close()
354
355 for mode := 0; mode < 2; mode++ {
356 v := pollVarz(t, s, mode, url+"varz", nil)
357
358 if v.Connections != 1 {
359 t.Fatalf("Expected Connections of 1, got %v\n", v.Connections)
360 }
361 if v.TotalConnections < 1 {
362 t.Fatalf("Expected Total Connections of at least 1, got %v\n", v.TotalConnections)
363 }
364 if v.InMsgs != 1 {
365 t.Fatalf("Expected InMsgs of 1, got %v\n", v.InMsgs)
366 }
367 if v.InBytes != 5 {
368 t.Fatalf("Expected InBytes of 5, got %v\n", v.InBytes)
369 }
370 if v.OutMsgs != 1 {
371 t.Fatalf("Expected OutMsgs of 1, got %v\n", v.OutMsgs)
372 }
373 if v.OutBytes != 5 {
374 t.Fatalf("Expected OutBytes of 5, got %v\n", v.OutBytes)
375 }
376 if v.InClientMsgs != 1 {
377 t.Fatalf("Expected InClientMsgs of 1, got %v\n", v.InClientMsgs)
378 }
379 if v.InClientBytes != 5 {
380 t.Fatalf("Expected InClientBytes of 5, got %v\n", v.InClientBytes)
381 }
382 if v.OutClientMsgs != 1 {
383 t.Fatalf("Expected OutClientMsgs of 1, got %v\n", v.OutClientMsgs)
384 }
385 if v.OutClientBytes != 5 {
386 t.Fatalf("Expected OutClientBytes of 5, got %v\n", v.OutClientBytes)
387 }
388 if v.Subscriptions <= 10 {
389 t.Fatalf("Expected Subscriptions of at least 10, got %v\n", v.Subscriptions)
390 }
391 if v.Name != "server_-1" {
392 t.Fatalf("Expected ServerName to be 'monitor_server' got %q", v.Name)
393 }
394 if !v.Tags.Contains("tag") {
395 t.Fatalf("Expected tags to be 'tag' got %v", v.Tags)
396 }
397 if v.JetStream.Config == nil {
398 t.Fatalf("JS Config not set")
399 }
400 sd := filepath.Join(s.opts.StoreDir, "jetstream")
401 if v.JetStream.Config.StoreDir != sd {
402 t.Fatalf("JS Config is invalid expected %q got %q", sd, v.JetStream.Config.StoreDir)
403 }
404 if v.JetStream.Stats == nil {
405 t.Fatalf("JS Stats not set")
406 }
407 if v.JetStream.Stats.Accounts != 2 {
408 t.Fatalf("Invalid stats expected 2 accounts got %d", v.JetStream.Stats.Accounts)
409 }
410 if v.JetStream.Limits == nil {
411 t.Fatalf("JS limits not set")
412 }
413 if v.JetStream.Limits.MaxHAAssets != 1000 {
414 t.Fatalf("Expected 1000 max_ha_assets got %v", v.JetStream.Limits.MaxHAAssets)
415 }
416 }
417 }
418
419 func pollConnz(t *testing.T, s *Server, mode int, url string, opts *ConnzOptions) *Connz {
420 t.Helper()
421 if mode == 0 {
422 body := readBody(t, url)
423 c := &Connz{}
424 if err := json.Unmarshal(body, &c); err != nil {
425 t.Fatalf("Got an error unmarshalling the body: %v\n", err)
426 }
427 return c
428 }
429 c, err := s.Connz(opts)
430 if err != nil {
431 t.Fatalf("Error on Connz(): %v", err)
432 }
433 return c
434 }
435
436 func TestMonitorConnz(t *testing.T) {
437 s := runMonitorServerWithAccounts()
438 defer s.Shutdown()
439
440 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
441
442 testConnz := func(mode int) {
443 c := pollConnz(t, s, mode, url+"connz", nil)
444
445 // Test contents..
446 require_Equal(t, c.NumConns, 0)
447 require_Equal(t, c.Total, 0)
448 require_Equal(t, len(c.Conns), 0)
449
450 // Test with connections.
451 nc := createClientConnWithUserSubscribeAndPublish(t, s, "a", "a")
452 defer nc.Close()
453
454 time.Sleep(50 * time.Millisecond)
455
456 c = pollConnz(t, s, mode, url+"connz?auth=1", &ConnzOptions{Username: true})
457
458 require_Equal(t, c.NumConns, 1)
459 require_Equal(t, c.Total, 1)
460 require_Equal(t, len(c.Conns), 1)
461 require_Equal(t, c.Limit, DefaultConnListSize)
462 require_Equal(t, c.Offset, 0)
463
464 // Test inside details of each connection
465 ci := c.Conns[0]
466
467 require_NotEqual(t, ci.Cid, 0)
468 require_Equal(t, ci.IP, "127.0.0.1")
469 require_NotEqual(t, ci.Port, 0)
470 require_Equal(t, ci.NumSubs, 0)
471 require_Equal(t, len(ci.Subs), 0)
472 require_Equal(t, len(ci.SubsDetail), 0)
473 require_Equal(t, ci.InMsgs, 1)
474 require_Equal(t, ci.OutMsgs, 1)
475 require_Equal(t, ci.InBytes, 5)
476 require_Equal(t, ci.OutBytes, 5)
477 require_False(t, ci.Start.IsZero())
478 require_NotEqual(t, ci.Uptime, "")
479 require_False(t, ci.LastActivity.IsZero())
480 require_False(t, ci.LastActivity.UnixNano() < ci.Start.UnixNano())
481 require_NotEqual(t, ci.Idle, "")
482 // This is a change, we now expect them to be set for connections when the
483 // client sends a connect.
484 require_NotEqual(t, ci.RTT, "")
485
486 require_Equal(t, ci.Account, "A")
487 require_Equal(t, ci.NameTag, "A")
488 }
489
490 for mode := 0; mode < 2; mode++ {
491 testConnz(mode)
492 checkClientsCount(t, s, 0)
493 }
494 }
495
496 func TestMonitorConnzBadParams(t *testing.T) {
497 s := runMonitorServer()
498 defer s.Shutdown()
499
500 url := fmt.Sprintf("http://127.0.0.1:%d/connz?", s.MonitorAddr().Port)
501 readBodyEx(t, url+"auth=xxx", http.StatusBadRequest, textPlain)
502 readBodyEx(t, url+"subs=xxx", http.StatusBadRequest, textPlain)
503 readBodyEx(t, url+"offset=xxx", http.StatusBadRequest, textPlain)
504 readBodyEx(t, url+"limit=xxx", http.StatusBadRequest, textPlain)
505 readBodyEx(t, url+"state=xxx", http.StatusBadRequest, textPlain)
506 }
507
508 func TestMonitorConnzWithSubs(t *testing.T) {
509 s := runMonitorServer()
510 defer s.Shutdown()
511
512 nc := createClientConnSubscribeAndPublish(t, s)
513 defer nc.Close()
514
515 nc.Subscribe("hello.foo", func(m *nats.Msg) {})
516 ensureServerActivityRecorded(t, nc)
517
518 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
519 for mode := 0; mode < 2; mode++ {
520 c := pollConnz(t, s, mode, url+"connz?subs=1", &ConnzOptions{Subscriptions: true})
521 // Test inside details of each connection
522 ci := c.Conns[0]
523 if len(ci.Subs) != 1 || ci.Subs[0] != "hello.foo" {
524 t.Fatalf("Expected subs of 1, got %v\n", ci.Subs)
525 }
526 }
527 }
528
529 func TestMonitorConnzWithSubsDetail(t *testing.T) {
530 s := runMonitorServer()
531 defer s.Shutdown()
532
533 nc := createClientConnSubscribeAndPublish(t, s)
534 defer nc.Close()
535
536 nc.Subscribe("hello.foo", func(m *nats.Msg) {})
537 ensureServerActivityRecorded(t, nc)
538
539 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
540 for mode := 0; mode < 2; mode++ {
541 c := pollConnz(t, s, mode, url+"connz?subs=detail", &ConnzOptions{SubscriptionsDetail: true})
542 // Test inside details of each connection
543 ci := c.Conns[0]
544 if len(ci.SubsDetail) != 1 || ci.SubsDetail[0].Subject != "hello.foo" {
545 t.Fatalf("Expected subsdetail of 1, got %v\n", ci.Subs)
546 }
547 }
548 }
549
550 func TestMonitorClosedConnzWithSubsDetail(t *testing.T) {
551 s := runMonitorServer()
552 defer s.Shutdown()
553
554 nc := createClientConnSubscribeAndPublish(t, s)
555
556 nc.Subscribe("hello.foo", func(m *nats.Msg) {})
557 ensureServerActivityRecorded(t, nc)
558 nc.Close()
559
560 s.mu.Lock()
561 for len(s.clients) != 0 {
562 s.mu.Unlock()
563 <-time.After(100 * time.Millisecond)
564 s.mu.Lock()
565 }
566 s.mu.Unlock()
567
568 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
569 for mode := 0; mode < 2; mode++ {
570 c := pollConnz(t, s, mode, url+"connz?state=closed&subs=detail", &ConnzOptions{State: ConnClosed,
571 SubscriptionsDetail: true})
572 // Test inside details of each connection
573 ci := c.Conns[0]
574 if len(ci.SubsDetail) != 1 || ci.SubsDetail[0].Subject != "hello.foo" {
575 t.Fatalf("Expected subsdetail of 1, got %v\n", ci.Subs)
576 }
577 }
578 }
579
580 func TestMonitorConnzWithCID(t *testing.T) {
581 s := runMonitorServer()
582 defer s.Shutdown()
583
584 // The one we will request
585 cid := 5
586 total := 10
587
588 // Create 10
589 for i := 1; i <= total; i++ {
590 nc := createClientConnSubscribeAndPublish(t, s)
591 defer nc.Close()
592 if i == cid {
593 nc.Subscribe("hello.foo", func(m *nats.Msg) {})
594 nc.Subscribe("hello.bar", func(m *nats.Msg) {})
595 ensureServerActivityRecorded(t, nc)
596 }
597 }
598
599 url := fmt.Sprintf("http://127.0.0.1:%d/connz?cid=%d", s.MonitorAddr().Port, cid)
600 for mode := 0; mode < 2; mode++ {
601 c := pollConnz(t, s, mode, url, &ConnzOptions{CID: uint64(cid)})
602 // Test inside details of each connection
603 if len(c.Conns) != 1 {
604 t.Fatalf("Expected only one connection, but got %d\n", len(c.Conns))
605 }
606 if c.NumConns != 1 {
607 t.Fatalf("Expected NumConns to be 1, but got %d\n", c.NumConns)
608 }
609 ci := c.Conns[0]
610 if ci.Cid != uint64(cid) {
611 t.Fatalf("Expected to receive connection %v, but received %v\n", cid, ci.Cid)
612 }
613 if ci.NumSubs != 2 {
614 t.Fatalf("Expected to receive connection with %d subs, but received %d\n", 2, ci.NumSubs)
615 }
616 // Now test a miss
617 badUrl := fmt.Sprintf("http://127.0.0.1:%d/connz?cid=%d", s.MonitorAddr().Port, 100)
618 c = pollConnz(t, s, mode, badUrl, &ConnzOptions{CID: uint64(100)})
619 if len(c.Conns) != 0 {
620 t.Fatalf("Expected no connections, got %d\n", len(c.Conns))
621 }
622 if c.NumConns != 0 {
623 t.Fatalf("Expected NumConns of 0, got %d\n", c.NumConns)
624 }
625 }
626 }
627
628 // Helper to map to connection name
629 func createConnMap(cz *Connz) map[string]*ConnInfo {
630 cm := make(map[string]*ConnInfo)
631 for _, c := range cz.Conns {
632 cm[c.Name] = c
633 }
634 return cm
635 }
636
637 func getFooAndBar(cm map[string]*ConnInfo) (*ConnInfo, *ConnInfo) {
638 return cm["foo"], cm["bar"]
639 }
640
641 func ensureServerActivityRecorded(t *testing.T, nc *nats.Conn) {
642 nc.Flush()
643 err := nc.Flush()
644 if err != nil {
645 t.Fatalf("Error flushing: %v\n", err)
646 }
647 }
648
649 func TestMonitorConnzRTT(t *testing.T) {
650 s := runMonitorServer()
651 defer s.Shutdown()
652
653 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
654
655 testRTT := func(mode int) {
656 // Test with connections.
657 nc := createClientConnSubscribeAndPublish(t, s)
658 defer nc.Close()
659
660 c := pollConnz(t, s, mode, url+"connz", nil)
661
662 if c.NumConns != 1 {
663 t.Fatalf("Expected 1 connection, got %d\n", c.NumConns)
664 }
665
666 // Send a server side PING to record RTT
667 s.mu.Lock()
668 ci := c.Conns[0]
669 sc := s.clients[ci.Cid]
670 if sc == nil {
671 t.Fatalf("Error looking up client %v\n", ci.Cid)
672 }
673 s.mu.Unlock()
674 sc.mu.Lock()
675 sc.sendPing()
676 sc.mu.Unlock()
677
678 // Wait for client to respond with PONG
679 time.Sleep(20 * time.Millisecond)
680
681 // Repoll for updated information.
682 c = pollConnz(t, s, mode, url+"connz", nil)
683 ci = c.Conns[0]
684
685 rtt, err := time.ParseDuration(ci.RTT)
686 if err != nil {
687 t.Fatalf("Could not parse RTT properly, %v (ci.RTT=%v)", err, ci.RTT)
688 }
689 if rtt <= 0 {
690 t.Fatal("Expected RTT to be valid and non-zero\n")
691 }
692 if (runtime.GOOS == "windows" && rtt > 20*time.Millisecond) ||
693 rtt > 20*time.Millisecond || rtt < 100*time.Nanosecond {
694 t.Fatalf("Invalid RTT of %s\n", ci.RTT)
695 }
696 }
697
698 for mode := 0; mode < 2; mode++ {
699 testRTT(mode)
700 checkClientsCount(t, s, 0)
701 }
702 }
703
704 func TestMonitorConnzLastActivity(t *testing.T) {
705 s := runMonitorServer()
706 defer s.Shutdown()
707
708 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
709 url += "connz?subs=1"
710 opts := &ConnzOptions{Subscriptions: true}
711
712 var sleepTime time.Duration
713 if runtime.GOOS == "windows" {
714 sleepTime = 10 * time.Millisecond
715 }
716
717 testActivity := func(mode int) {
718 ncFoo := createClientConnWithName(t, "foo", s)
719 defer ncFoo.Close()
720
721 ncBar := createClientConnWithName(t, "bar", s)
722 defer ncBar.Close()
723
724 // Test inside details of each connection
725 ciFoo, ciBar := getFooAndBar(createConnMap(pollConnz(t, s, mode, url, opts)))
726
727 // Test that LastActivity is non-zero
728 if ciFoo.LastActivity.IsZero() {
729 t.Fatalf("Expected LastActivity for connection '%s'to be valid\n", ciFoo.Name)
730 }
731 if ciBar.LastActivity.IsZero() {
732 t.Fatalf("Expected LastActivity for connection '%s'to be valid\n", ciBar.Name)
733 }
734 // Foo should be older than Bar
735 if ciFoo.LastActivity.After(ciBar.LastActivity) {
736 t.Fatal("Expected connection 'foo' to be older than 'bar'\n")
737 }
738
739 fooLA := ciFoo.LastActivity
740 barLA := ciBar.LastActivity
741
742 ensureServerActivityRecorded(t, ncFoo)
743 ensureServerActivityRecorded(t, ncBar)
744
745 time.Sleep(sleepTime)
746
747 // Sub should trigger update.
748 sub, _ := ncFoo.Subscribe("hello.world", func(m *nats.Msg) {})
749 ensureServerActivityRecorded(t, ncFoo)
750
751 ciFoo, _ = getFooAndBar(createConnMap(pollConnz(t, s, mode, url, opts)))
752 nextLA := ciFoo.LastActivity
753 if fooLA.Equal(nextLA) {
754 t.Fatalf("Subscribe should have triggered update to LastActivity %+v\n", ciFoo)
755 }
756 fooLA = nextLA
757
758 time.Sleep(sleepTime)
759
760 // Publish and Message Delivery should trigger as well. So both connections
761 // should have updates.
762 ncBar.Publish("hello.world", []byte("Hello"))
763
764 ensureServerActivityRecorded(t, ncFoo)
765 ensureServerActivityRecorded(t, ncBar)
766
767 ciFoo, ciBar = getFooAndBar(createConnMap(pollConnz(t, s, mode, url, opts)))
768 nextLA = ciBar.LastActivity
769 if barLA.Equal(nextLA) {
770 t.Fatalf("Publish should have triggered update to LastActivity\n")
771 }
772
773 // Message delivery on ncFoo should have triggered as well.
774 nextLA = ciFoo.LastActivity
775 if fooLA.Equal(nextLA) {
776 t.Fatalf("Message delivery should have triggered update to LastActivity\n")
777 }
778 fooLA = nextLA
779
780 time.Sleep(sleepTime)
781
782 // Unsub should trigger as well
783 sub.Unsubscribe()
784 ensureServerActivityRecorded(t, ncFoo)
785
786 ciFoo, _ = getFooAndBar(createConnMap(pollConnz(t, s, mode, url, opts)))
787 nextLA = ciFoo.LastActivity
788 if fooLA.Equal(nextLA) {
789 t.Fatalf("Message delivery should have triggered update to LastActivity\n")
790 }
791 }
792
793 for mode := 0; mode < 2; mode++ {
794 testActivity(mode)
795 }
796 }
797
798 func TestMonitorConnzWithOffsetAndLimit(t *testing.T) {
799 s := runMonitorServer()
800 defer s.Shutdown()
801
802 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
803
804 for mode := 0; mode < 2; mode++ {
805 c := pollConnz(t, s, mode, url+"connz?offset=1&limit=1", &ConnzOptions{Offset: 1, Limit: 1})
806 if c.Conns == nil || len(c.Conns) != 0 {
807 t.Fatalf("Expected 0 connections in array, got %p\n", c.Conns)
808 }
809
810 // Test that when given negative values, 0 or default is used
811 c = pollConnz(t, s, mode, url+"connz?offset=-1&limit=-1", &ConnzOptions{Offset: -11, Limit: -11})
812 if c.Conns == nil || len(c.Conns) != 0 {
813 t.Fatalf("Expected 0 connections in array, got %p\n", c.Conns)
814 }
815 if c.Offset != 0 {
816 t.Fatalf("Expected offset to be 0, and limit to be %v, got %v and %v",
817 DefaultConnListSize, c.Offset, c.Limit)
818 }
819 }
820
821 cl1 := createClientConnSubscribeAndPublish(t, s)
822 defer cl1.Close()
823
824 cl2 := createClientConnSubscribeAndPublish(t, s)
825 defer cl2.Close()
826
827 for mode := 0; mode < 2; mode++ {
828 c := pollConnz(t, s, mode, url+"connz?offset=1&limit=1", &ConnzOptions{Offset: 1, Limit: 1})
829 if c.Limit != 1 {
830 t.Fatalf("Expected limit of 1, got %v\n", c.Limit)
831 }
832
833 if c.Offset != 1 {
834 t.Fatalf("Expected offset of 1, got %v\n", c.Offset)
835 }
836
837 if len(c.Conns) != 1 {
838 t.Fatalf("Expected conns of 1, got %v\n", len(c.Conns))
839 }
840
841 if c.NumConns != 1 {
842 t.Fatalf("Expected NumConns to be 1, got %v\n", c.NumConns)
843 }
844
845 if c.Total != 2 {
846 t.Fatalf("Expected Total to be at least 2, got %v", c.Total)
847 }
848
849 c = pollConnz(t, s, mode, url+"connz?offset=2&limit=1", &ConnzOptions{Offset: 2, Limit: 1})
850 if c.Limit != 1 {
851 t.Fatalf("Expected limit of 1, got %v\n", c.Limit)
852 }
853
854 if c.Offset != 2 {
855 t.Fatalf("Expected offset of 2, got %v\n", c.Offset)
856 }
857
858 if len(c.Conns) != 0 {
859 t.Fatalf("Expected conns of 0, got %v\n", len(c.Conns))
860 }
861
862 if c.NumConns != 0 {
863 t.Fatalf("Expected NumConns to be 0, got %v\n", c.NumConns)
864 }
865
866 if c.Total != 2 {
867 t.Fatalf("Expected Total to be 2, got %v", c.Total)
868 }
869 }
870 }
871
872 func TestMonitorConnzOffsetOverflow(t *testing.T) {
873 s := runMonitorServer()
874 defer s.Shutdown()
875
876 // Need at least one open connection so we get past the empty-result early
877 // return and reach the pagination slicing.
878 cl := createClientConnSubscribeAndPublish(t, s)
879 defer cl.Close()
880
881 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
882
883 for mode := 0; mode < 2; mode++ {
884 // Offset = math.MaxInt64, Limit = 1 makes Offset+Limit overflow to math.MinInt64.
885 c := pollConnz(t, s, mode, url+fmt.Sprintf("connz?offset=%d&limit=1", math.MaxInt64),
886 &ConnzOptions{Offset: math.MaxInt64, Limit: 1})
887 if c.Conns == nil || len(c.Conns) != 0 {
888 t.Fatalf("Expected 0 connections in array, got %v\n", len(c.Conns))
889 }
890 if c.NumConns != 0 {
891 t.Fatalf("Expected NumConns to be 0, got %v", c.NumConns)
892 }
893 }
894
895 // Both Offset and Limit at the max also overflows the sum.
896 _, err := s.Connz(&ConnzOptions{Offset: math.MaxInt64, Limit: math.MaxInt64})
897 require_NoError(t, err)
898 }
899
900 func TestMonitorConnzDefaultSorted(t *testing.T) {
901 s := runMonitorServer()
902 defer s.Shutdown()
903
904 clients := make([]*nats.Conn, 4)
905 for i := range clients {
906 clients[i] = createClientConnSubscribeAndPublish(t, s)
907 defer clients[i].Close()
908 }
909
910 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
911 for mode := 0; mode < 2; mode++ {
912 c := pollConnz(t, s, mode, url+"connz", nil)
913 if c.Conns[0].Cid > c.Conns[1].Cid ||
914 c.Conns[1].Cid > c.Conns[2].Cid ||
915 c.Conns[2].Cid > c.Conns[3].Cid {
916 t.Fatalf("Expected conns sorted in ascending order by cid, got %v < %v\n", c.Conns[0].Cid, c.Conns[3].Cid)
917 }
918 }
919 }
920
921 func TestMonitorConnzSortedByCid(t *testing.T) {
922 s := runMonitorServer()
923 defer s.Shutdown()
924
925 clients := make([]*nats.Conn, 4)
926 for i := range clients {
927 clients[i] = createClientConnSubscribeAndPublish(t, s)
928 defer clients[i].Close()
929 }
930
931 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
932 for mode := 0; mode < 2; mode++ {
933 c := pollConnz(t, s, mode, url+"connz?sort=cid", &ConnzOptions{Sort: ByCid})
934 if c.Conns[0].Cid > c.Conns[1].Cid ||
935 c.Conns[1].Cid > c.Conns[2].Cid ||
936 c.Conns[2].Cid > c.Conns[3].Cid {
937 t.Fatalf("Expected conns sorted in ascending order by cid, got [%v, %v, %v, %v]\n",
938 c.Conns[0].Cid, c.Conns[1].Cid, c.Conns[2].Cid, c.Conns[3].Cid)
939 }
940 }
941 }
942
943 func TestMonitorConnzSortedByStart(t *testing.T) {
944 s := runMonitorServer()
945 defer s.Shutdown()
946
947 clients := make([]*nats.Conn, 4)
948 for i := range clients {
949 clients[i] = createClientConnSubscribeAndPublish(t, s)
950 defer clients[i].Close()
951 }
952
953 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
954 for mode := 0; mode < 2; mode++ {
955 c := pollConnz(t, s, mode, url+"connz?sort=start", &ConnzOptions{Sort: ByStart})
956 if c.Conns[0].Start.After(c.Conns[1].Start) ||
957 c.Conns[1].Start.After(c.Conns[2].Start) ||
958 c.Conns[2].Start.After(c.Conns[3].Start) {
959 t.Fatalf("Expected conns sorted in ascending order by startime, got [%v, %v, %v, %v]\n",
960 c.Conns[0].Start, c.Conns[1].Start, c.Conns[2].Start, c.Conns[3].Start)
961 }
962 }
963 }
964
965 func TestMonitorConnzSortedByBytesAndMsgs(t *testing.T) {
966 s := runMonitorServer()
967 defer s.Shutdown()
968
969 // Create a connection and make it send more messages than others
970 firstClient := createClientConnSubscribeAndPublish(t, s)
971 for i := 0; i < 100; i++ {
972 firstClient.Publish("foo", []byte("Hello World"))
973 }
974 defer firstClient.Close()
975 firstClient.Flush()
976
977 clients := make([]*nats.Conn, 3)
978 for i := range clients {
979 clients[i] = createClientConnSubscribeAndPublish(t, s)
980 defer clients[i].Close()
981 }
982
983 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
984 for mode := 0; mode < 2; mode++ {
985 c := pollConnz(t, s, mode, url+"connz?sort=bytes_to", &ConnzOptions{Sort: ByOutBytes})
986 if c.Conns[0].OutBytes < c.Conns[1].OutBytes ||
987 c.Conns[0].OutBytes < c.Conns[2].OutBytes ||
988 c.Conns[0].OutBytes < c.Conns[3].OutBytes {
989 t.Fatalf("Expected conns sorted in descending order by bytes to, got %v < one of [%v, %v, %v]\n",
990 c.Conns[0].OutBytes, c.Conns[1].OutBytes, c.Conns[2].OutBytes, c.Conns[3].OutBytes)
991 }
992
993 c = pollConnz(t, s, mode, url+"connz?sort=msgs_to", &ConnzOptions{Sort: ByOutMsgs})
994 if c.Conns[0].OutMsgs < c.Conns[1].OutMsgs ||
995 c.Conns[0].OutMsgs < c.Conns[2].OutMsgs ||
996 c.Conns[0].OutMsgs < c.Conns[3].OutMsgs {
997 t.Fatalf("Expected conns sorted in descending order by msgs from, got %v < one of [%v, %v, %v]\n",
998 c.Conns[0].OutMsgs, c.Conns[1].OutMsgs, c.Conns[2].OutMsgs, c.Conns[3].OutMsgs)
999 }
1000
1001 c = pollConnz(t, s, mode, url+"connz?sort=bytes_from", &ConnzOptions{Sort: ByInBytes})
1002 if c.Conns[0].InBytes < c.Conns[1].InBytes ||
1003 c.Conns[0].InBytes < c.Conns[2].InBytes ||
1004 c.Conns[0].InBytes < c.Conns[3].InBytes {
1005 t.Fatalf("Expected conns sorted in descending order by bytes from, got %v < one of [%v, %v, %v]\n",
1006 c.Conns[0].InBytes, c.Conns[1].InBytes, c.Conns[2].InBytes, c.Conns[3].InBytes)
1007 }
1008
1009 c = pollConnz(t, s, mode, url+"connz?sort=msgs_from", &ConnzOptions{Sort: ByInMsgs})
1010 if c.Conns[0].InMsgs < c.Conns[1].InMsgs ||
1011 c.Conns[0].InMsgs < c.Conns[2].InMsgs ||
1012 c.Conns[0].InMsgs < c.Conns[3].InMsgs {
1013 t.Fatalf("Expected conns sorted in descending order by msgs from, got %v < one of [%v, %v, %v]\n",
1014 c.Conns[0].InMsgs, c.Conns[1].InMsgs, c.Conns[2].InMsgs, c.Conns[3].InMsgs)
1015 }
1016 }
1017 }
1018
1019 func TestMonitorConnzSortedByPending(t *testing.T) {
1020 s := runMonitorServer()
1021 defer s.Shutdown()
1022
1023 firstClient := createClientConnSubscribeAndPublish(t, s)
1024 firstClient.Subscribe("hello.world", func(m *nats.Msg) {})
1025 clients := make([]*nats.Conn, 3)
1026 for i := range clients {
1027 clients[i] = createClientConnSubscribeAndPublish(t, s)
1028 defer clients[i].Close()
1029 }
1030 defer firstClient.Close()
1031
1032 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1033 for mode := 0; mode < 2; mode++ {
1034 c := pollConnz(t, s, mode, url+"connz?sort=pending", &ConnzOptions{Sort: ByPending})
1035 if c.Conns[0].Pending < c.Conns[1].Pending ||
1036 c.Conns[0].Pending < c.Conns[2].Pending ||
1037 c.Conns[0].Pending < c.Conns[3].Pending {
1038 t.Fatalf("Expected conns sorted in descending order by number of pending, got %v < one of [%v, %v, %v]\n",
1039 c.Conns[0].Pending, c.Conns[1].Pending, c.Conns[2].Pending, c.Conns[3].Pending)
1040 }
1041 }
1042 }
1043
1044 func TestMonitorConnzSortedBySubs(t *testing.T) {
1045 s := runMonitorServer()
1046 defer s.Shutdown()
1047
1048 firstClient := createClientConnSubscribeAndPublish(t, s)
1049 firstClient.Subscribe("hello.world", func(m *nats.Msg) {})
1050 defer firstClient.Close()
1051
1052 clients := make([]*nats.Conn, 3)
1053 for i := range clients {
1054 clients[i] = createClientConnSubscribeAndPublish(t, s)
1055 defer clients[i].Close()
1056 }
1057
1058 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1059 for mode := 0; mode < 2; mode++ {
1060 c := pollConnz(t, s, mode, url+"connz?sort=subs", &ConnzOptions{Sort: BySubs})
1061 if c.Conns[0].NumSubs < c.Conns[1].NumSubs ||
1062 c.Conns[0].NumSubs < c.Conns[2].NumSubs ||
1063 c.Conns[0].NumSubs < c.Conns[3].NumSubs {
1064 t.Fatalf("Expected conns sorted in descending order by number of subs, got %v < one of [%v, %v, %v]\n",
1065 c.Conns[0].NumSubs, c.Conns[1].NumSubs, c.Conns[2].NumSubs, c.Conns[3].NumSubs)
1066 }
1067 }
1068 }
1069
1070 func TestMonitorConnzSortedByLast(t *testing.T) {
1071 resetPreviousHTTPConnections()
1072 opts := DefaultMonitorOptions()
1073 opts.NoSystemAccount = true
1074 s := RunServer(opts)
1075 defer s.Shutdown()
1076
1077 firstClient := createClientConnSubscribeAndPublish(t, s)
1078 defer firstClient.Close()
1079 firstClient.Subscribe("hello.world", func(m *nats.Msg) {})
1080 firstClient.Flush()
1081
1082 clients := make([]*nats.Conn, 3)
1083 for i := range clients {
1084 clients[i] = createClientConnSubscribeAndPublish(t, s)
1085 defer clients[i].Close()
1086 clients[i].Flush()
1087 }
1088
1089 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1090 for mode := 0; mode < 2; mode++ {
1091 c := pollConnz(t, s, mode, url+"connz?sort=last", &ConnzOptions{Sort: ByLast})
1092 if c.Conns[0].LastActivity.UnixNano() < c.Conns[1].LastActivity.UnixNano() ||
1093 c.Conns[1].LastActivity.UnixNano() < c.Conns[2].LastActivity.UnixNano() ||
1094 c.Conns[2].LastActivity.UnixNano() < c.Conns[3].LastActivity.UnixNano() {
1095 t.Fatalf("Expected conns sorted in descending order by lastActivity, got %v < one of [%v, %v, %v]\n",
1096 c.Conns[0].LastActivity, c.Conns[1].LastActivity, c.Conns[2].LastActivity, c.Conns[3].LastActivity)
1097 }
1098 }
1099 }
1100
1101 func TestMonitorConnzSortedByUptime(t *testing.T) {
1102 s := runMonitorServer()
1103 defer s.Shutdown()
1104
1105 for i := 0; i < 4; i++ {
1106 client := createClientConnSubscribeAndPublish(t, s)
1107 defer client.Close()
1108 // Since we check times (now-start) does not have to be big.
1109 time.Sleep(50 * time.Millisecond)
1110 }
1111
1112 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1113 for mode := 0; mode < 2; mode++ {
1114 c := pollConnz(t, s, mode, url+"connz?sort=uptime", &ConnzOptions{Sort: ByUptime})
1115 now := time.Now()
1116 ups := make([]int, 4)
1117 for i := 0; i < 4; i++ {
1118 ups[i] = int(now.Sub(c.Conns[i].Start))
1119 }
1120 if !sort.IntsAreSorted(ups) {
1121 d := make([]time.Duration, 4)
1122 for i := 0; i < 4; i++ {
1123 d[i] = time.Duration(ups[i])
1124 }
1125 t.Fatalf("Expected conns sorted in ascending order by uptime (now-Start), got %+v\n", d)
1126 }
1127 }
1128 }
1129
1130 func TestMonitorConnzSortedByUptimeClosedConn(t *testing.T) {
1131 s := runMonitorServer()
1132 defer s.Shutdown()
1133
1134 for i := time.Duration(1); i <= 4; i++ {
1135 c := createClientConnSubscribeAndPublish(t, s)
1136
1137 // Grab client and asjust start time such that
1138 client := s.getClient(uint64(i))
1139 if client == nil {
1140 t.Fatalf("Could nopt retrieve client for %d\n", i)
1141 }
1142 client.mu.Lock()
1143 client.start = client.start.Add(-10 * (4 - i) * time.Second)
1144 client.mu.Unlock()
1145
1146 c.Close()
1147 }
1148
1149 checkClosedConns(t, s, 4, time.Second)
1150
1151 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1152 for mode := 0; mode < 2; mode++ {
1153 c := pollConnz(t, s, mode, url+"connz?state=closed&sort=uptime", &ConnzOptions{State: ConnClosed, Sort: ByUptime})
1154 ups := make([]int, 4)
1155 for i := 0; i < 4; i++ {
1156 ups[i] = int(c.Conns[i].Stop.Sub(c.Conns[i].Start))
1157 }
1158 if !sort.IntsAreSorted(ups) {
1159 d := make([]time.Duration, 4)
1160 for i := 0; i < 4; i++ {
1161 d[i] = time.Duration(ups[i])
1162 }
1163 t.Fatalf("Expected conns sorted in ascending order by uptime, got %+v\n", d)
1164 }
1165 }
1166 }
1167
1168 func TestMonitorConnzSortedByStopOnOpen(t *testing.T) {
1169 s := runMonitorServer()
1170 defer s.Shutdown()
1171
1172 opts := s.getOpts()
1173 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1174
1175 // 4 clients
1176 for i := 0; i < 4; i++ {
1177 c, err := nats.Connect(url)
1178 if err != nil {
1179 t.Fatalf("Could not create client: %v\n", err)
1180 }
1181 defer c.Close()
1182 }
1183
1184 c, err := s.Connz(&ConnzOptions{Sort: ByStop})
1185 if err == nil {
1186 t.Fatalf("Expected err to be non-nil, got %+v\n", c)
1187 }
1188 }
1189
1190 func TestMonitorConnzSortedByStopTimeClosedConn(t *testing.T) {
1191 s := runMonitorServer()
1192 defer s.Shutdown()
1193
1194 opts := s.getOpts()
1195 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1196
1197 // 4 clients
1198 for i := 0; i < 4; i++ {
1199 c, err := nats.Connect(url)
1200 if err != nil {
1201 t.Fatalf("Could not create client: %v\n", err)
1202 }
1203 c.Close()
1204 }
1205 checkClosedConns(t, s, 4, time.Second)
1206
1207 // Now adjust the Stop times for these with some random values.
1208 s.mu.Lock()
1209 now := time.Now().UTC()
1210 ccs := s.closed.closedClients()
1211 for _, cc := range ccs {
1212 newStop := now.Add(time.Duration(rand.Int()%120) * -time.Minute)
1213 cc.Stop = &newStop
1214 }
1215 s.mu.Unlock()
1216
1217 url = fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1218 for mode := 0; mode < 2; mode++ {
1219 c := pollConnz(t, s, mode, url+"connz?state=closed&sort=stop", &ConnzOptions{State: ConnClosed, Sort: ByStop})
1220 ups := make([]int, 4)
1221 nowU := time.Now().UnixNano()
1222 for i := 0; i < 4; i++ {
1223 ups[i] = int(nowU - c.Conns[i].Stop.UnixNano())
1224 }
1225 if !sort.IntsAreSorted(ups) {
1226 d := make([]time.Duration, 4)
1227 for i := 0; i < 4; i++ {
1228 d[i] = time.Duration(ups[i])
1229 }
1230 t.Fatalf("Expected conns sorted in ascending order by stop time, got %+v\n", d)
1231 }
1232 }
1233 }
1234
1235 func TestMonitorConnzSortedByReason(t *testing.T) {
1236 s := runMonitorServer()
1237 defer s.Shutdown()
1238
1239 opts := s.getOpts()
1240 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1241
1242 // 20 clients
1243 for i := 0; i < 20; i++ {
1244 c, err := nats.Connect(url)
1245 if err != nil {
1246 t.Fatalf("Could not create client: %v\n", err)
1247 }
1248 c.Close()
1249 }
1250 checkClosedConns(t, s, 20, time.Second)
1251
1252 // Now adjust the Reasons for these with some random values.
1253 s.mu.Lock()
1254 ccs := s.closed.closedClients()
1255 max := int(ServerShutdown)
1256 for _, cc := range ccs {
1257 cc.Reason = ClosedState(rand.Int() % max).String()
1258 }
1259 s.mu.Unlock()
1260
1261 url = fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1262 for mode := 0; mode < 2; mode++ {
1263 c := pollConnz(t, s, mode, url+"connz?state=closed&sort=reason", &ConnzOptions{State: ConnClosed, Sort: ByReason})
1264 rs := make([]string, 20)
1265 for i := 0; i < 20; i++ {
1266 rs[i] = c.Conns[i].Reason
1267 }
1268 if !sort.StringsAreSorted(rs) {
1269 t.Fatalf("Expected conns sorted in order by stop reason, got %#v\n", rs)
1270 }
1271 }
1272 }
1273
1274 func TestMonitorConnzSortedByReasonOnOpen(t *testing.T) {
1275 s := runMonitorServer()
1276 defer s.Shutdown()
1277
1278 opts := s.getOpts()
1279 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1280
1281 // 4 clients
1282 for i := 0; i < 4; i++ {
1283 c, err := nats.Connect(url)
1284 if err != nil {
1285 t.Fatalf("Could not create client: %v\n", err)
1286 }
1287 defer c.Close()
1288 }
1289
1290 c, err := s.Connz(&ConnzOptions{Sort: ByReason})
1291 if err == nil {
1292 t.Fatalf("Expected err to be non-nil, got %+v\n", c)
1293 }
1294 }
1295
1296 func TestMonitorConnzSortedByIdle(t *testing.T) {
1297 s := runMonitorServer()
1298 defer s.Shutdown()
1299
1300 url := fmt.Sprintf("http://%s/connz?sort=idle", s.MonitorAddr())
1301 now := time.Now()
1302
1303 clients := []struct {
1304 start time.Time // Client start time.
1305 last time.Time // Client last activity time.
1306 }{
1307 {start: now.Add(-10 * time.Second), last: now.Add(-5 * time.Second)},
1308 {start: now.Add(-20 * time.Second), last: now.Add(-10 * time.Second)},
1309 {start: now.Add(-3 * time.Second), last: now.Add(-2 * time.Second)},
1310 {start: now.Add(-30 * time.Second), last: now.Add(-20 * time.Second)},
1311 }
1312
1313 testIdle := func(mode int) {
1314 // Connect the specified number of clients.
1315 for _, c := range clients {
1316 clientConn := createClientConnSubscribeAndPublish(t, s)
1317 defer clientConn.Close()
1318
1319 cid, err := clientConn.GetClientID()
1320 if err != nil {
1321 t.Fatalf("error getting the client CID: %v", err)
1322 }
1323
1324 client := s.getClient(cid)
1325 if client == nil {
1326 t.Fatalf("error looking up client %d", cid)
1327 }
1328
1329 // Change the client's start and last activity times.
1330 client.mu.Lock()
1331 client.start = c.start
1332 client.last = c.last
1333 client.mu.Unlock()
1334 }
1335
1336 connz := pollConnz(t, s, mode, url, &ConnzOptions{Sort: ByIdle})
1337
1338 wantConns := len(clients)
1339 gotConns := len(connz.Conns)
1340
1341 if gotConns != wantConns {
1342 t.Fatalf("want %d connections, got %d", wantConns, gotConns)
1343 }
1344
1345 idleDurations := getConnsIdleDurations(t, connz.Conns)
1346
1347 if !sortedDurationsDesc(idleDurations) {
1348 t.Errorf("want durations sorted in descending order, got %v", idleDurations)
1349 }
1350 }
1351
1352 for mode := 0; mode < 2; mode++ {
1353 testIdle(mode)
1354 }
1355 }
1356
1357 // getConnsIdleDurations returns a slice of parsed idle durations from a connection info slice.
1358 func getConnsIdleDurations(t *testing.T, conns []*ConnInfo) []time.Duration {
1359 t.Helper()
1360
1361 durations := make([]time.Duration, 0, len(conns))
1362
1363 for _, conn := range conns {
1364 idle, err := time.ParseDuration(conn.Idle)
1365 if err != nil {
1366 t.Fatalf("error parsing duration %q: %v", conn.Idle, err)
1367 }
1368 durations = append(durations, idle)
1369 }
1370
1371 return durations
1372 }
1373
1374 // sortedDurationsDesc checks if a time.Duration slice is sorted in descending order.
1375 func sortedDurationsDesc(durations []time.Duration) bool {
1376 return sort.SliceIsSorted(durations, func(i, j int) bool {
1377 // Must be longer than the next duration.
1378 return durations[i] > durations[j]
1379 })
1380 }
1381
1382 func TestMonitorConnzSortByIdleTime(t *testing.T) {
1383 now := time.Now().UTC()
1384
1385 cases := map[string]ConnInfos{
1386 "zero values": {{}, {}, {}, {}},
1387 "equal last activity times": {
1388 {Start: now.Add(-50 * time.Minute), LastActivity: now.Add(-time.Minute)},
1389 {Start: now.Add(-30 * time.Minute), LastActivity: now.Add(-time.Minute)},
1390 {Start: now.Add(-10 * time.Second), LastActivity: now.Add(-time.Minute)},
1391 {Start: now.Add(-2 * time.Hour), LastActivity: now.Add(-time.Minute)},
1392 },
1393 "last activity in the future": {
1394 {Start: now.Add(-50 * time.Minute), LastActivity: now.Add(10 * time.Minute)}, // +10m
1395 {Start: now.Add(-30 * time.Minute), LastActivity: now.Add(5 * time.Minute)}, // +5m
1396 {Start: now.Add(-24 * time.Hour), LastActivity: now.Add(2 * time.Second)}, // +2s
1397 {Start: now.Add(-10 * time.Second), LastActivity: now.Add(15 * time.Minute)}, // +15m
1398 {Start: now.Add(-2 * time.Hour), LastActivity: now.Add(time.Minute)}, // +1m
1399 },
1400 "unsorted": {
1401 {Start: now.Add(-50 * time.Minute), LastActivity: now.Add(-10 * time.Minute)}, // 10m ago
1402 {Start: now.Add(-30 * time.Minute), LastActivity: now.Add(-5 * time.Minute)}, // 5m ago
1403 {Start: now.Add(-24 * time.Hour), LastActivity: now.Add(-2 * time.Second)}, // 2s ago
1404 {Start: now.Add(-10 * time.Second), LastActivity: now.Add(-15 * time.Minute)}, // 15m ago
1405 {Start: now.Add(-2 * time.Hour), LastActivity: now.Add(-time.Minute)}, // 1m ago
1406 },
1407 "unsorted with zero value start time": {
1408 {LastActivity: now.Add(-10 * time.Minute)}, // 10m ago
1409 {LastActivity: now.Add(-5 * time.Minute)}, // 5m ago
1410 {LastActivity: now.Add(-2 * time.Second)}, // 2s ago
1411 {LastActivity: now.Add(-15 * time.Minute)}, // 15m ago
1412 {LastActivity: now.Add(-time.Minute)}, // 1m ago
1413 },
1414 "sorted": {
1415 {Start: now.Add(-24 * time.Hour), LastActivity: now.Add(-2 * time.Second)}, // 2s ago
1416 {Start: now.Add(-2 * time.Hour), LastActivity: now.Add(-time.Minute)}, // 1m ago
1417 {Start: now.Add(-30 * time.Minute), LastActivity: now.Add(-5 * time.Minute)}, // 5m ago
1418 {Start: now.Add(-50 * time.Minute), LastActivity: now.Add(-10 * time.Minute)}, // 10m ago
1419 {Start: now.Add(-10 * time.Second), LastActivity: now.Add(-15 * time.Minute)}, // 15m ago
1420 },
1421 "sorted with zero value start time": {
1422 {LastActivity: now.Add(-2 * time.Second)}, // 2s ago
1423 {LastActivity: now.Add(-time.Minute)}, // 1m ago
1424 {LastActivity: now.Add(-5 * time.Minute)}, // 5m ago
1425 {LastActivity: now.Add(-10 * time.Minute)}, // 10m ago
1426 {LastActivity: now.Add(-15 * time.Minute)}, // 15m ago
1427 },
1428 }
1429
1430 for name, conns := range cases {
1431 t.Run(name, func(t *testing.T) {
1432 sort.Sort(SortByIdle{conns, now})
1433
1434 idleDurations := getIdleDurations(conns, now)
1435
1436 if !sortedDurationsAsc(idleDurations) {
1437 t.Errorf("want durations sorted in ascending order, got %v", idleDurations)
1438 }
1439 })
1440 }
1441 }
1442
1443 // getIdleDurations returns a slice of idle durations from a connection info list up until now time.
1444 func getIdleDurations(conns ConnInfos, now time.Time) []time.Duration {
1445 durations := make([]time.Duration, 0, len(conns))
1446
1447 for _, conn := range conns {
1448 durations = append(durations, now.Sub(conn.LastActivity))
1449 }
1450
1451 return durations
1452 }
1453
1454 // sortedDurationsAsc checks if a time.Duration slice is sorted in ascending order.
1455 func sortedDurationsAsc(durations []time.Duration) bool {
1456 return sort.SliceIsSorted(durations, func(i, j int) bool {
1457 return durations[i] < durations[j]
1458 })
1459 }
1460
1461 func TestMonitorConnzSortBadRequest(t *testing.T) {
1462 s := runMonitorServer()
1463 defer s.Shutdown()
1464
1465 firstClient := createClientConnSubscribeAndPublish(t, s)
1466 firstClient.Subscribe("hello.world", func(m *nats.Msg) {})
1467 clients := make([]*nats.Conn, 3)
1468 for i := range clients {
1469 clients[i] = createClientConnSubscribeAndPublish(t, s)
1470 defer clients[i].Close()
1471 }
1472 defer firstClient.Close()
1473
1474 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1475 readBodyEx(t, url+"connz?sort=foo", http.StatusBadRequest, textPlain)
1476
1477 if _, err := s.Connz(&ConnzOptions{Sort: "foo"}); err == nil {
1478 t.Fatal("Expected error, got none")
1479 }
1480 }
1481
1482 func pollRoutez(t *testing.T, s *Server, mode int, url string, opts *RoutezOptions) *Routez {
1483 t.Helper()
1484 if mode == 0 {
1485 rz := &Routez{}
1486 body := readBody(t, url)
1487 if err := json.Unmarshal(body, rz); err != nil {
1488 t.Fatalf("Got an error unmarshalling the body: %v\n", err)
1489 }
1490 return rz
1491 }
1492 rz, err := s.Routez(opts)
1493 if err != nil {
1494 t.Fatalf("Error on Routez: %v", err)
1495 }
1496 return rz
1497 }
1498
1499 func TestMonitorConnzWithRoutes(t *testing.T) {
1500 resetPreviousHTTPConnections()
1501 opts := DefaultMonitorOptions()
1502 opts.NoSystemAccount = true
1503 opts.Cluster.Name = "A"
1504 opts.Cluster.Host = "127.0.0.1"
1505 opts.Cluster.Port = CLUSTER_PORT
1506
1507 s := RunServer(opts)
1508 defer s.Shutdown()
1509
1510 opts = &Options{
1511 Host: "127.0.0.1",
1512 Port: -1,
1513 Cluster: ClusterOpts{
1514 Name: "A",
1515 Host: "127.0.0.1",
1516 Port: -1,
1517 },
1518 NoLog: true,
1519 NoSigs: true,
1520 NoSystemAccount: true,
1521 }
1522 routeURL, _ := url.Parse(fmt.Sprintf("nats-route://127.0.0.1:%d", s.ClusterAddr().Port))
1523 opts.Routes = []*url.URL{routeURL}
1524
1525 start := time.Now()
1526 sc := RunServer(opts)
1527 defer sc.Shutdown()
1528
1529 checkClusterFormed(t, s, sc)
1530
1531 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1532 for mode := 0; mode < 2; mode++ {
1533 c := pollConnz(t, s, mode, url+"connz", nil)
1534 // Test contents..
1535 // Make sure routes don't show up under connz, but do under routez
1536 if c.NumConns != 0 {
1537 t.Fatalf("Expected 0 connections, got %d", c.NumConns)
1538 }
1539 if c.Conns == nil || len(c.Conns) != 0 {
1540 t.Fatalf("Expected 0 connections in array, got %p", c.Conns)
1541 }
1542 }
1543
1544 nc := createClientConnSubscribeAndPublish(t, sc)
1545 defer nc.Close()
1546
1547 nc.Subscribe("hello.bar", func(m *nats.Msg) {})
1548 nc.Flush()
1549 checkExpectedSubs(t, 1, s, sc)
1550
1551 // Now check routez
1552 urls := []string{"routez", "routez?subs=1", "routez?subs=detail"}
1553 for subs, urlSuffix := range urls {
1554 for mode := 0; mode < 2; mode++ {
1555 rz := pollRoutez(t, s, mode, url+urlSuffix, &RoutezOptions{Subscriptions: subs == 1, SubscriptionsDetail: subs == 2})
1556
1557 if rz.NumRoutes != DEFAULT_ROUTE_POOL_SIZE {
1558 t.Fatalf("Expected %d route, got %d", DEFAULT_ROUTE_POOL_SIZE, rz.NumRoutes)
1559 }
1560
1561 if len(rz.Routes) != DEFAULT_ROUTE_POOL_SIZE {
1562 t.Fatalf("Expected route array of %d, got %v", DEFAULT_ROUTE_POOL_SIZE, len(rz.Routes))
1563 }
1564
1565 route := rz.Routes[0]
1566
1567 if route.DidSolicit {
1568 t.Fatalf("Expected unsolicited route, got %v", route.DidSolicit)
1569 }
1570
1571 if route.Start.IsZero() {
1572 t.Fatalf("Expected Start to be set, got %+v", route)
1573 } else if route.Start.Before(start) {
1574 t.Fatalf("Unexpected start time: route was started around %v, got %v", start, route.Start)
1575 }
1576 if route.LastActivity.IsZero() {
1577 t.Fatalf("Expected LastActivity to be set, got %+v", route)
1578 }
1579 if route.Uptime == _EMPTY_ {
1580 t.Fatalf("Expected Uptime to be set, it was not")
1581 }
1582 if route.Idle == _EMPTY_ {
1583 t.Fatalf("Expected Idle to be set, it was not")
1584 }
1585
1586 // Don't ask for subs, so there should not be any
1587 if subs == 0 {
1588 if len(route.Subs) != 0 {
1589 t.Fatalf("There should not be subs, got %v", len(route.Subs))
1590 }
1591 } else if subs == 1 {
1592 if len(route.Subs) != 1 && len(route.SubsDetail) != 0 {
1593 t.Fatalf("There should be 1 sub, got %v", len(route.Subs))
1594 }
1595 } else if subs == 2 {
1596 if len(route.SubsDetail) != 1 && len(route.Subs) != 0 {
1597 t.Fatalf("There should be 1 sub, got %v", len(route.SubsDetail))
1598 }
1599 }
1600 }
1601 }
1602 }
1603
1604 func TestMonitorRoutezWithBadParams(t *testing.T) {
1605 s := runMonitorServer()
1606 defer s.Shutdown()
1607
1608 url := fmt.Sprintf("http://127.0.0.1:%d/routez?", s.MonitorAddr().Port)
1609 readBodyEx(t, url+"subs=xxx", http.StatusBadRequest, textPlain)
1610 }
1611
1612 func pollSubsz(t *testing.T, s *Server, mode int, url string, opts *SubszOptions) *Subsz {
1613 t.Helper()
1614 if mode == 0 {
1615 body := readBody(t, url)
1616 sz := &Subsz{}
1617 if err := json.Unmarshal(body, sz); err != nil {
1618 t.Fatalf("Got an error unmarshalling the body: %v\n", err)
1619 }
1620 return sz
1621 }
1622 sz, err := s.Subsz(opts)
1623 if err != nil {
1624 t.Fatalf("Error on Subsz: %v", err)
1625 }
1626 return sz
1627 }
1628
1629 func TestSubsz(t *testing.T) {
1630 s := runMonitorServer()
1631 defer s.Shutdown()
1632
1633 nc := createClientConnSubscribeAndPublish(t, s)
1634 defer nc.Close()
1635
1636 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1637
1638 for mode := 0; mode < 2; mode++ {
1639 sl := pollSubsz(t, s, mode, url+"subsz", nil)
1640
1641 require_Equal(t, sl.NumSubs, 0)
1642 require_Equal(t, sl.NumInserts, 1)
1643 require_Equal(t, sl.NumMatches, 1)
1644
1645 for _, s := range sl.Subs {
1646 switch s.Account {
1647 case DEFAULT_GLOBAL_ACCOUNT:
1648 require_Equal(t, s.AccountTag, DEFAULT_GLOBAL_ACCOUNT)
1649 case DEFAULT_SYSTEM_ACCOUNT:
1650 require_Equal(t, s.AccountTag, DEFAULT_SYSTEM_ACCOUNT)
1651 default:
1652 t.Fatalf("Unknown account: %q", s.Account)
1653 }
1654 }
1655 }
1656 }
1657
1658 func TestSubszOperatorMode(t *testing.T) {
1659 sysName := "SYS"
1660 accName := "APP"
1661
1662 srvs, sysKp, accKp := runMonitorServerWithOperator(t, sysName, accName)
1663 for _, s := range srvs {
1664 defer s.Shutdown()
1665 }
1666 s := srvs[0]
1667
1668 sysPub, _ := sysKp.PublicKey()
1669 accPub, _ := accKp.PublicKey()
1670
1671 _, aCreds := createUser(t, accKp)
1672
1673 nc, err := nats.Connect(s.ClientURL(), nats.UserCredentials(aCreds))
1674 require_NoError(t, err)
1675 defer nc.Close()
1676
1677 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1678
1679 for mode := 0; mode < 2; mode++ {
1680 sl := pollSubsz(t, s, mode, url+"subsz", nil)
1681
1682 for _, s := range sl.Subs {
1683 switch s.Account {
1684 case DEFAULT_GLOBAL_ACCOUNT:
1685 require_Equal(t, s.AccountTag, DEFAULT_GLOBAL_ACCOUNT)
1686 case sysPub:
1687 require_Equal(t, s.AccountTag, sysName)
1688 case accPub:
1689 require_Equal(t, s.AccountTag, accName)
1690 default:
1691 t.Fatalf("Unknown account: %q", s.Account)
1692 }
1693 }
1694 }
1695 }
1696
1697 func TestMonitorSubszDetails(t *testing.T) {
1698 s := runMonitorServer()
1699 defer s.Shutdown()
1700
1701 nc := createClientConnSubscribeAndPublish(t, s)
1702 defer nc.Close()
1703
1704 nc.Subscribe("foo.*", func(m *nats.Msg) {})
1705 nc.Subscribe("foo.bar", func(m *nats.Msg) {})
1706 nc.Subscribe("foo.foo", func(m *nats.Msg) {})
1707
1708 nc.Publish("foo.bar", []byte("Hello"))
1709 nc.Publish("foo.baz", []byte("Hello"))
1710 nc.Publish("foo.foo", []byte("Hello"))
1711
1712 nc.Flush()
1713
1714 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1715
1716 for mode := 0; mode < 2; mode++ {
1717 sl := pollSubsz(t, s, mode, url+"subsz?subs=1", &SubszOptions{Subscriptions: true})
1718 if sl.NumSubs != 3 {
1719 t.Fatalf("Expected NumSubs of 3, got %d\n", sl.NumSubs)
1720 }
1721 if sl.Total != 3 {
1722 t.Fatalf("Expected Total of 3, got %d\n", sl.Total)
1723 }
1724 if len(sl.Subs) != 3 {
1725 t.Fatalf("Expected subscription details for 3 subs, got %d\n", len(sl.Subs))
1726 }
1727 }
1728 }
1729
1730 func TestMonitorSubszWithOffsetAndLimit(t *testing.T) {
1731 s := runMonitorServer()
1732 defer s.Shutdown()
1733
1734 nc := createClientConnSubscribeAndPublish(t, s)
1735 defer nc.Close()
1736
1737 for i := 0; i < 200; i++ {
1738 nc.Subscribe(fmt.Sprintf("foo.%d", i), func(m *nats.Msg) {})
1739 }
1740 nc.Flush()
1741
1742 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1743 for mode := 0; mode < 2; mode++ {
1744 sl := pollSubsz(t, s, mode, url+"subsz?subs=1&offset=10&limit=100", &SubszOptions{Subscriptions: true, Offset: 10, Limit: 100})
1745 if sl.NumSubs != 200 {
1746 t.Fatalf("Expected NumSubs of 200, got %d\n", sl.NumSubs)
1747 }
1748 if sl.Total != 200 {
1749 t.Fatalf("Expected Total of 200, got %d\n", sl.Total)
1750 }
1751 if sl.Offset != 10 {
1752 t.Fatalf("Expected Offset of 10, got %d\n", sl.Offset)
1753 }
1754 if sl.Limit != 100 {
1755 t.Fatalf("Expected Total of 100, got %d\n", sl.Limit)
1756 }
1757 if len(sl.Subs) != 100 {
1758 t.Fatalf("Expected subscription details for 100 subs, got %d\n", len(sl.Subs))
1759 }
1760 }
1761 }
1762
1763 func TestMonitorSubszOffsetOverflow(t *testing.T) {
1764 s := runMonitorServer()
1765 defer s.Shutdown()
1766
1767 nc := createClientConnSubscribeAndPublish(t, s)
1768 defer nc.Close()
1769
1770 _, err := nc.Subscribe("foo.*", func(m *nats.Msg) {})
1771 require_NoError(t, err)
1772 _, err = nc.Subscribe("foo.bar", func(m *nats.Msg) {})
1773 require_NoError(t, err)
1774 _, err = nc.Subscribe("foo.foo", func(m *nats.Msg) {})
1775 require_NoError(t, err)
1776 require_NoError(t, nc.Flush())
1777
1778 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1779
1780 for mode := 0; mode < 2; mode++ {
1781 // Offset = math.MaxInt64, Limit = 1 makes Offset+Limit overflow to math.MinInt64.
1782 sl := pollSubsz(t, s, mode, url+fmt.Sprintf("subsz?subs=1&offset=%d&limit=1", math.MaxInt64),
1783 &SubszOptions{Subscriptions: true, Offset: math.MaxInt64, Limit: 1})
1784 if len(sl.Subs) != 0 {
1785 t.Fatalf("Expected 0 subscription details, got %d", len(sl.Subs))
1786 }
1787 }
1788
1789 // Both Offset and Limit at the max also overflows the sum.
1790 _, err = s.Subsz(&SubszOptions{Subscriptions: true, Offset: math.MaxInt64, Limit: math.MaxInt64})
1791 require_NoError(t, err)
1792 }
1793
1794 func TestMonitorSubszTestPubSubject(t *testing.T) {
1795 s := runMonitorServer()
1796 defer s.Shutdown()
1797
1798 nc := createClientConnSubscribeAndPublish(t, s)
1799 defer nc.Close()
1800
1801 nc.Subscribe("foo.*", func(m *nats.Msg) {})
1802 nc.Subscribe("foo.bar", func(m *nats.Msg) {})
1803 nc.Subscribe("foo.foo", func(m *nats.Msg) {})
1804 nc.Flush()
1805
1806 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1807 for mode := 0; mode < 2; mode++ {
1808 sl := pollSubsz(t, s, mode, url+"subsz?subs=1&test=foo.foo", &SubszOptions{Subscriptions: true, Test: "foo.foo"})
1809 if sl.Total != 2 {
1810 t.Fatalf("Expected Total of 2 match, got %d\n", sl.Total)
1811 }
1812 if len(sl.Subs) != 2 {
1813 t.Fatalf("Expected subscription details for 2 matching subs, got %d\n", len(sl.Subs))
1814 }
1815 sl = pollSubsz(t, s, mode, url+"subsz?subs=1&test=foo", &SubszOptions{Subscriptions: true, Test: "foo"})
1816 if len(sl.Subs) != 0 {
1817 t.Fatalf("Expected no matching subs, got %d\n", len(sl.Subs))
1818 }
1819 }
1820 // Make sure we get an error with invalid test subject.
1821 testUrl := url + "subsz?subs=1&"
1822 readBodyEx(t, testUrl+"test=*", http.StatusBadRequest, textPlain)
1823 readBodyEx(t, testUrl+"test=foo.*", http.StatusBadRequest, textPlain)
1824 readBodyEx(t, testUrl+"test=foo.>", http.StatusBadRequest, textPlain)
1825 readBodyEx(t, testUrl+"test=foo..bar", http.StatusBadRequest, textPlain)
1826 }
1827
1828 func TestMonitorSubszMultiAccount(t *testing.T) {
1829 s := runMonitorServerWithAccounts()
1830 defer s.Shutdown()
1831
1832 ncA := createClientConnWithUserSubscribeAndPublish(t, s, "a", "a")
1833 defer ncA.Close()
1834
1835 ncA.Subscribe("foo.*", func(m *nats.Msg) {})
1836 ncA.Subscribe("foo.bar", func(m *nats.Msg) {})
1837 ncA.Subscribe("foo.foo", func(m *nats.Msg) {})
1838
1839 ncA.Publish("foo.bar", []byte("Hello"))
1840 ncA.Publish("foo.baz", []byte("Hello"))
1841 ncA.Publish("foo.foo", []byte("Hello"))
1842
1843 ncA.Flush()
1844
1845 ncB := createClientConnWithUserSubscribeAndPublish(t, s, "b", "b")
1846 defer ncB.Close()
1847
1848 ncB.Subscribe("foo.*", func(m *nats.Msg) {})
1849 ncB.Subscribe("foo.bar", func(m *nats.Msg) {})
1850 ncB.Subscribe("foo.foo", func(m *nats.Msg) {})
1851
1852 ncB.Publish("foo.bar", []byte("Hello"))
1853 ncB.Publish("foo.baz", []byte("Hello"))
1854 ncB.Publish("foo.foo", []byte("Hello"))
1855
1856 ncB.Flush()
1857
1858 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1859
1860 for mode := 0; mode < 2; mode++ {
1861 sl := pollSubsz(t, s, mode, url+"subsz?subs=1", &SubszOptions{Subscriptions: true})
1862 if sl.NumSubs != 6 {
1863 t.Fatalf("Expected NumSubs of 6, got %d\n", sl.NumSubs)
1864 }
1865 if sl.Total != 6 {
1866 t.Fatalf("Expected Total of 6, got %d\n", sl.Total)
1867 }
1868 if len(sl.Subs) != 6 {
1869 t.Fatalf("Expected subscription details for 6 subs, got %d\n", len(sl.Subs))
1870 }
1871 for _, sd := range sl.Subs {
1872 if sd.Account != "A" && sd.Account != "B" {
1873 t.Fatalf("Expected account information to be present and be 'A' or 'B', got %q", sd.Account)
1874 }
1875 }
1876
1877 // Now make sure we can filter on account.
1878 sl = pollSubsz(t, s, mode, url+"subsz?subs=1&acc=A", &SubszOptions{Account: "A", Subscriptions: true})
1879 if sl.NumSubs != 3 {
1880 t.Fatalf("Expected NumSubs of 3, got %d\n", sl.NumSubs)
1881 }
1882 if sl.Total != 3 {
1883 t.Fatalf("Expected Total of 6, got %d\n", sl.Total)
1884 }
1885 if len(sl.Subs) != 3 {
1886 t.Fatalf("Expected subscription details for 6 subs, got %d\n", len(sl.Subs))
1887 }
1888 for _, sd := range sl.Subs {
1889 if sd.Account != "A" {
1890 t.Fatalf("Expected account information to be present and be 'A', got %q", sd.Account)
1891 }
1892 }
1893 }
1894 }
1895
1896 func TestMonitorSubszMultiAccountWithOffsetAndLimit(t *testing.T) {
1897 s := runMonitorServer()
1898 defer s.Shutdown()
1899
1900 ncA := createClientConnWithUserSubscribeAndPublish(t, s, "a", "a")
1901 defer ncA.Close()
1902
1903 for i := 0; i < 200; i++ {
1904 ncA.Subscribe(fmt.Sprintf("foo.%d", i), func(m *nats.Msg) {})
1905 }
1906 ncA.Flush()
1907
1908 ncB := createClientConnWithUserSubscribeAndPublish(t, s, "b", "b")
1909 defer ncB.Close()
1910
1911 for i := 0; i < 200; i++ {
1912 ncB.Subscribe(fmt.Sprintf("foo.%d", i), func(m *nats.Msg) {})
1913 }
1914 ncB.Flush()
1915
1916 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1917 for mode := 0; mode < 2; mode++ {
1918 sl := pollSubsz(t, s, mode, url+"subsz?subs=1&offset=10&limit=100", &SubszOptions{Subscriptions: true, Offset: 10, Limit: 100})
1919 if sl.NumSubs != 400 {
1920 t.Fatalf("Expected NumSubs of 200, got %d\n", sl.NumSubs)
1921 }
1922 if sl.Total != 400 {
1923 t.Fatalf("Expected Total of 400, got %d\n", sl.Total)
1924 }
1925 if sl.Offset != 10 {
1926 t.Fatalf("Expected Offset of 10, got %d\n", sl.Offset)
1927 }
1928 if sl.Limit != 100 {
1929 t.Fatalf("Expected Total of 100, got %d\n", sl.Limit)
1930 }
1931 if len(sl.Subs) != 100 {
1932 t.Fatalf("Expected subscription details for 100 subs, got %d\n", len(sl.Subs))
1933 }
1934 }
1935 }
1936
1937 // Tests handle root
1938 func TestMonitorHandleRoot(t *testing.T) {
1939 s := runMonitorServer()
1940 defer s.Shutdown()
1941
1942 nc := createClientConnSubscribeAndPublish(t, s)
1943 defer nc.Close()
1944
1945 resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port))
1946 if err != nil {
1947 t.Fatalf("Expected no error: Got %v\n", err)
1948 }
1949 defer resp.Body.Close()
1950 if resp.StatusCode != http.StatusOK {
1951 t.Fatalf("Expected a %d response, got %d\n", http.StatusOK, resp.StatusCode)
1952 }
1953
1954 body, err := io.ReadAll(resp.Body)
1955 if err != nil {
1956 t.Fatalf("Expected no error reading body: Got %v\n", err)
1957 }
1958 for _, b := range body {
1959 if b > unicode.MaxASCII {
1960 t.Fatalf("Expected body to contain only ASCII characters, but got %v\n", b)
1961 }
1962 }
1963
1964 ct := resp.Header.Get("Content-Type")
1965 if !strings.Contains(ct, "text/html") {
1966 t.Fatalf("Expected text/html response, got %s\n", ct)
1967 }
1968 }
1969
1970 func TestMonitorConnzWithNamedClient(t *testing.T) {
1971 s := runMonitorServer()
1972 defer s.Shutdown()
1973
1974 clientName := "test-client"
1975 nc := createClientConnWithName(t, clientName, s)
1976 defer nc.Close()
1977
1978 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
1979 for mode := 0; mode < 2; mode++ {
1980 // Confirm server is exposing client name in monitoring endpoint.
1981 c := pollConnz(t, s, mode, url+"connz", nil)
1982 got := len(c.Conns)
1983 expected := 1
1984 if got != expected {
1985 t.Fatalf("Expected %d connection in array, got %d\n", expected, got)
1986 }
1987
1988 conn := c.Conns[0]
1989 if conn.Name != clientName {
1990 t.Fatalf("Expected client to have name %q. got %q", clientName, conn.Name)
1991 }
1992 }
1993 }
1994
1995 func TestMonitorConnzWithStateForClosedConns(t *testing.T) {
1996 s := runMonitorServer()
1997 defer s.Shutdown()
1998
1999 numEach := 10
2000 // Create 10 closed, and 10 to leave open.
2001 for i := 0; i < numEach; i++ {
2002 nc := createClientConnSubscribeAndPublish(t, s)
2003 nc.Subscribe("hello.closed.conns", func(m *nats.Msg) {})
2004 nc.Close()
2005 nc = createClientConnSubscribeAndPublish(t, s)
2006 nc.Subscribe("hello.open.conns", func(m *nats.Msg) {})
2007 defer nc.Close()
2008 }
2009
2010 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
2011
2012 for mode := 0; mode < 2; mode++ {
2013 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
2014 // Look at all open
2015 c := pollConnz(t, s, mode, url+"connz?state=open", &ConnzOptions{State: ConnOpen})
2016 if lc := len(c.Conns); lc != numEach {
2017 return fmt.Errorf("Expected %d connections in array, got %d", numEach, lc)
2018 }
2019 // Look at all closed
2020 c = pollConnz(t, s, mode, url+"connz?state=closed", &ConnzOptions{State: ConnClosed})
2021 if lc := len(c.Conns); lc != numEach {
2022 return fmt.Errorf("Expected %d connections in array, got %d", numEach, lc)
2023 }
2024 // Look at all
2025 c = pollConnz(t, s, mode, url+"connz?state=ALL", &ConnzOptions{State: ConnAll})
2026 if lc := len(c.Conns); lc != numEach*2 {
2027 return fmt.Errorf("Expected %d connections in array, got %d", 2*numEach, lc)
2028 }
2029 // Look at CID #1, which is in closed.
2030 c = pollConnz(t, s, mode, url+"connz?cid=1&state=open", &ConnzOptions{CID: 1, State: ConnOpen})
2031 if lc := len(c.Conns); lc != 0 {
2032 return fmt.Errorf("Expected no connections in open array, got %d", lc)
2033 }
2034 c = pollConnz(t, s, mode, url+"connz?cid=1&state=closed", &ConnzOptions{CID: 1, State: ConnClosed})
2035 if lc := len(c.Conns); lc != 1 {
2036 return fmt.Errorf("Expected a connection in closed array, got %d", lc)
2037 }
2038 c = pollConnz(t, s, mode, url+"connz?cid=1&state=ALL", &ConnzOptions{CID: 1, State: ConnAll})
2039 if lc := len(c.Conns); lc != 1 {
2040 return fmt.Errorf("Expected a connection in closed array, got %d", lc)
2041 }
2042 c = pollConnz(t, s, mode, url+"connz?cid=1&state=closed&subs=true",
2043 &ConnzOptions{CID: 1, State: ConnClosed, Subscriptions: true})
2044 if lc := len(c.Conns); lc != 1 {
2045 return fmt.Errorf("Expected a connection in closed array, got %d", lc)
2046 }
2047 ci := c.Conns[0]
2048 if ci.NumSubs != 1 {
2049 return fmt.Errorf("Expected NumSubs to be 1, got %d", ci.NumSubs)
2050 }
2051 if len(ci.Subs) != 1 {
2052 return fmt.Errorf("Expected len(ci.Subs) to be 1 also, got %d", len(ci.Subs))
2053 }
2054 // Now ask for same thing without subs and make sure they are not returned.
2055 c = pollConnz(t, s, mode, url+"connz?cid=1&state=closed&subs=false",
2056 &ConnzOptions{CID: 1, State: ConnClosed, Subscriptions: false})
2057 if lc := len(c.Conns); lc != 1 {
2058 return fmt.Errorf("Expected a connection in closed array, got %d", lc)
2059 }
2060 ci = c.Conns[0]
2061 if ci.NumSubs != 1 {
2062 return fmt.Errorf("Expected NumSubs to be 1, got %d", ci.NumSubs)
2063 }
2064 if len(ci.Subs) != 0 {
2065 return fmt.Errorf("Expected len(ci.Subs) to be 0 since subs=false, got %d", len(ci.Subs))
2066 }
2067
2068 // CID #2 is in open
2069 c = pollConnz(t, s, mode, url+"connz?cid=2&state=open", &ConnzOptions{CID: 2, State: ConnOpen})
2070 if lc := len(c.Conns); lc != 1 {
2071 return fmt.Errorf("Expected a connection in open array, got %d", lc)
2072 }
2073 // It should also work if we ask for "state=all"
2074 c = pollConnz(t, s, mode, url+"connz?cid=2&state=all", &ConnzOptions{CID: 2, State: ConnAll})
2075 if lc := len(c.Conns); lc != 1 {
2076 return fmt.Errorf("Expected a connection in open array, got %d", lc)
2077 }
2078 // But not for "state=closed"
2079 c = pollConnz(t, s, mode, url+"connz?cid=2&state=closed", &ConnzOptions{CID: 2, State: ConnClosed})
2080 if lc := len(c.Conns); lc != 0 {
2081 return fmt.Errorf("Expected no connections in closed array, got %d", lc)
2082 }
2083 return nil
2084 })
2085 }
2086 }
2087
2088 // Make sure options for ConnInfo like subs=1, authuser, etc do not cause a race.
2089 func TestMonitorConnzClosedConnsRace(t *testing.T) {
2090 s := runMonitorServer()
2091 defer s.Shutdown()
2092
2093 // Create 100 closed connections.
2094 for i := 0; i < 100; i++ {
2095 nc := createClientConnSubscribeAndPublish(t, s)
2096 nc.Close()
2097 }
2098
2099 urlWithoutSubs := fmt.Sprintf("http://127.0.0.1:%d/connz?state=closed", s.MonitorAddr().Port)
2100 urlWithSubs := urlWithoutSubs + "&subs=true"
2101
2102 checkClosedConns(t, s, 100, 2*time.Second)
2103
2104 wg := &sync.WaitGroup{}
2105
2106 fn := func(url string) {
2107 deadline := time.Now().Add(1 * time.Second)
2108 for time.Now().Before(deadline) {
2109 c := pollConnz(t, s, 0, url, nil)
2110 if len(c.Conns) != 100 {
2111 t.Errorf("Incorrect Results: %+v\n", c)
2112 }
2113 }
2114 wg.Done()
2115 }
2116
2117 wg.Add(2)
2118 go fn(urlWithSubs)
2119 go fn(urlWithoutSubs)
2120 wg.Wait()
2121 }
2122
2123 // Make sure a bad client that is disconnected right away has proper values.
2124 func TestMonitorConnzClosedConnsBadClient(t *testing.T) {
2125 s := runMonitorServer()
2126 defer s.Shutdown()
2127
2128 opts := s.getOpts()
2129
2130 rc, err := net.Dial("tcp", net.JoinHostPort(opts.Host, fmt.Sprintf("%d", opts.Port)))
2131 if err != nil {
2132 t.Fatalf("Error on dial: %v", err)
2133 }
2134 rc.Close()
2135
2136 checkClosedConns(t, s, 1, 2*time.Second)
2137
2138 c := pollConnz(t, s, 1, "", &ConnzOptions{State: ConnClosed})
2139 if len(c.Conns) != 1 {
2140 t.Errorf("Incorrect Results: %+v\n", c)
2141 }
2142 ci := c.Conns[0]
2143
2144 uptime := ci.Stop.Sub(ci.Start)
2145 idle, err := time.ParseDuration(ci.Idle)
2146 if err != nil {
2147 t.Fatalf("Could not parse Idle: %v\n", err)
2148 }
2149 if idle > uptime {
2150 t.Fatalf("Idle can't be larger then uptime, %v vs %v\n", idle, uptime)
2151 }
2152 if ci.LastActivity.IsZero() {
2153 t.Fatalf("LastActivity should not be Zero\n")
2154 }
2155 }
2156
2157 // Make sure a bad client that tries to connect plain to TLS has proper values.
2158 func TestMonitorConnzClosedConnsBadTLSClient(t *testing.T) {
2159 resetPreviousHTTPConnections()
2160
2161 tc := &TLSConfigOpts{}
2162 tc.CertFile = "configs/certs/server.pem"
2163 tc.KeyFile = "configs/certs/key.pem"
2164
2165 var err error
2166 opts := DefaultMonitorOptions()
2167 opts.NoSystemAccount = true
2168 opts.TLSTimeout = 1.5 // 1.5 seconds
2169 opts.TLSConfig, err = GenTLSConfig(tc)
2170 if err != nil {
2171 t.Fatalf("Error creating TSL config: %v", err)
2172 }
2173
2174 s := RunServer(opts)
2175 defer s.Shutdown()
2176
2177 opts = s.getOpts()
2178
2179 rc, err := net.Dial("tcp", net.JoinHostPort(opts.Host, fmt.Sprintf("%d", opts.Port)))
2180 if err != nil {
2181 t.Fatalf("Error on dial: %v", err)
2182 }
2183 rc.Write([]byte("CONNECT {}\r\n"))
2184 rc.Close()
2185
2186 checkClosedConns(t, s, 1, 2*time.Second)
2187
2188 c := pollConnz(t, s, 1, "", &ConnzOptions{State: ConnClosed})
2189 if len(c.Conns) != 1 {
2190 t.Errorf("Incorrect Results: %+v\n", c)
2191 }
2192 ci := c.Conns[0]
2193
2194 uptime := ci.Stop.Sub(ci.Start)
2195 idle, err := time.ParseDuration(ci.Idle)
2196 if err != nil {
2197 t.Fatalf("Could not parse Idle: %v\n", err)
2198 }
2199 if idle > uptime {
2200 t.Fatalf("Idle can't be larger then uptime, %v vs %v\n", idle, uptime)
2201 }
2202 if ci.LastActivity.IsZero() {
2203 t.Fatalf("LastActivity should not be Zero\n")
2204 }
2205 }
2206
2207 // Create a connection to test ConnInfo
2208 func createClientConnWithUserSubscribeAndPublish(t *testing.T, s *Server, user, pwd string) *nats.Conn {
2209 natsURL := ""
2210 if user == "" {
2211 natsURL = fmt.Sprintf("nats://127.0.0.1:%d", s.Addr().(*net.TCPAddr).Port)
2212 } else {
2213 natsURL = fmt.Sprintf("nats://%s:%[email protected]:%d", user, pwd, s.Addr().(*net.TCPAddr).Port)
2214 }
2215 client := nats.GetDefaultOptions()
2216 client.Servers = []string{natsURL}
2217 nc, err := client.Connect()
2218 if err != nil {
2219 t.Fatalf("Error creating client: %v to: %s\n", err, natsURL)
2220 }
2221
2222 ch := make(chan bool)
2223 inbox := nats.NewInbox()
2224 sub, err := nc.Subscribe(inbox, func(m *nats.Msg) { ch <- true })
2225 if err != nil {
2226 t.Fatalf("Error subscribing to `%s`: %v\n", inbox, err)
2227 }
2228 nc.Publish(inbox, []byte("Hello"))
2229 // Wait for message
2230 <-ch
2231 sub.Unsubscribe()
2232 close(ch)
2233 nc.Flush()
2234 return nc
2235 }
2236
2237 func createClientConnSubscribeAndPublish(t *testing.T, s *Server) *nats.Conn {
2238 return createClientConnWithUserSubscribeAndPublish(t, s, "", "")
2239 }
2240
2241 func createClientConnWithName(t *testing.T, name string, s *Server) *nats.Conn {
2242 natsURI := fmt.Sprintf("nats://127.0.0.1:%d", s.Addr().(*net.TCPAddr).Port)
2243
2244 client := nats.GetDefaultOptions()
2245 client.Servers = []string{natsURI}
2246 client.Name = name
2247 nc, err := client.Connect()
2248 if err != nil {
2249 t.Fatalf("Error creating client: %v\n", err)
2250 }
2251 return nc
2252 }
2253
2254 func TestMonitorStacksz(t *testing.T) {
2255 s := runMonitorServer()
2256 defer s.Shutdown()
2257
2258 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
2259 body := readBody(t, url+"stacksz")
2260 // Check content
2261 str := string(body)
2262 if !strings.Contains(str, "HandleStacksz") {
2263 t.Fatalf("Result does not seem to contain server's stacks:\n%v", str)
2264 }
2265 }
2266
2267 func TestMonitorConcurrentMonitoring(t *testing.T) {
2268 s := runMonitorServer()
2269 defer s.Shutdown()
2270
2271 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
2272 // Get some endpoints. Make sure we have at least varz,
2273 // and the more the merrier.
2274 endpoints := []string{"varz", "varz", "varz", "connz", "connz", "subsz", "subsz", "routez", "routez"}
2275 wg := &sync.WaitGroup{}
2276 wg.Add(len(endpoints))
2277 ech := make(chan string, len(endpoints))
2278
2279 for _, e := range endpoints {
2280 go func(endpoint string) {
2281 defer wg.Done()
2282 for i := 0; i < 50; i++ {
2283 resp, err := http.Get(url + endpoint)
2284 if err != nil {
2285 ech <- fmt.Sprintf("Expected no error: Got %v\n", err)
2286 return
2287 }
2288 defer resp.Body.Close()
2289 if resp.StatusCode != http.StatusOK {
2290 ech <- fmt.Sprintf("Expected a %v response, got %d\n", http.StatusOK, resp.StatusCode)
2291 return
2292 }
2293 ct := resp.Header.Get("Content-Type")
2294 if ct != "application/json" {
2295 ech <- fmt.Sprintf("Expected application/json content-type, got %s\n", ct)
2296 return
2297 }
2298 if _, err := io.ReadAll(resp.Body); err != nil {
2299 ech <- fmt.Sprintf("Got an error reading the body: %v\n", err)
2300 return
2301 }
2302 resp.Body.Close()
2303 }
2304 }(e)
2305 }
2306 wg.Wait()
2307 // Check for any errors
2308 select {
2309 case err := <-ech:
2310 t.Fatal(err)
2311 default:
2312 }
2313 }
2314
2315 func TestMonitorHandler(t *testing.T) {
2316 s := runMonitorServer()
2317 defer s.Shutdown()
2318 handler := s.HTTPHandler()
2319 if handler == nil {
2320 t.Fatal("HTTP Handler should be set")
2321 }
2322 s.Shutdown()
2323 handler = s.HTTPHandler()
2324 if handler != nil {
2325 t.Fatal("HTTP Handler should be nil")
2326 }
2327 }
2328
2329 func TestMonitorRoutezRace(t *testing.T) {
2330 resetPreviousHTTPConnections()
2331 srvAOpts := DefaultMonitorOptions()
2332 srvAOpts.NoSystemAccount = true
2333 srvAOpts.Cluster.Name = "B"
2334 srvAOpts.Cluster.Port = -1
2335 srvA := RunServer(srvAOpts)
2336 defer srvA.Shutdown()
2337
2338 srvBOpts := nextServerOpts(srvAOpts)
2339 srvBOpts.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srvA.ClusterAddr().Port))
2340
2341 doneCh := make(chan struct{})
2342 go func() {
2343 defer func() {
2344 doneCh <- struct{}{}
2345 }()
2346 for i := 0; i < 10; i++ {
2347 time.Sleep(10 * time.Millisecond)
2348 // Reset ports
2349 srvBOpts.Port = -1
2350 srvBOpts.Cluster.Port = -1
2351 srvB := RunServer(srvBOpts)
2352 time.Sleep(20 * time.Millisecond)
2353 srvB.Shutdown()
2354 }
2355 }()
2356 done := false
2357 for !done {
2358 if _, err := srvA.Routez(nil); err != nil {
2359 time.Sleep(10 * time.Millisecond)
2360 }
2361 select {
2362 case <-doneCh:
2363 done = true
2364 default:
2365 }
2366 }
2367 }
2368
2369 func TestMonitorConnzTLSInHandshake(t *testing.T) {
2370 resetPreviousHTTPConnections()
2371
2372 tc := &TLSConfigOpts{}
2373 tc.CertFile = "configs/certs/server.pem"
2374 tc.KeyFile = "configs/certs/key.pem"
2375
2376 var err error
2377 opts := DefaultMonitorOptions()
2378 opts.NoSystemAccount = true
2379 opts.TLSTimeout = 1.5 // 1.5 seconds
2380 opts.TLSConfig, err = GenTLSConfig(tc)
2381 if err != nil {
2382 t.Fatalf("Error creating TSL config: %v", err)
2383 }
2384
2385 s := RunServer(opts)
2386 defer s.Shutdown()
2387
2388 // Create bare TCP connection to delay client TLS handshake
2389 c, err := net.Dial("tcp", net.JoinHostPort(opts.Host, fmt.Sprintf("%d", opts.Port)))
2390 if err != nil {
2391 t.Fatalf("Error on dial: %v", err)
2392 }
2393 defer c.Close()
2394
2395 // Wait for the connection to be registered
2396 checkClientsCount(t, s, 1)
2397
2398 start := time.Now()
2399 endpoint := fmt.Sprintf("http://%s:%d/connz", opts.HTTPHost, s.MonitorAddr().Port)
2400 for mode := 0; mode < 2; mode++ {
2401 connz := pollConnz(t, s, mode, endpoint, nil)
2402 duration := time.Since(start)
2403 if duration >= 1500*time.Millisecond {
2404 t.Fatalf("Looks like connz blocked on handshake, took %v", duration)
2405 }
2406 if len(connz.Conns) != 1 {
2407 t.Fatalf("Expected 1 conn, got %v", len(connz.Conns))
2408 }
2409 conn := connz.Conns[0]
2410 // TLS fields should be not set
2411 if conn.TLSVersion != "" || conn.TLSCipher != "" {
2412 t.Fatalf("Expected TLS fields to not be set, got version:%v cipher:%v", conn.TLSVersion, conn.TLSCipher)
2413 }
2414 }
2415 }
2416
2417 func TestMonitorConnzTLSCfg(t *testing.T) {
2418 resetPreviousHTTPConnections()
2419
2420 tc := &TLSConfigOpts{}
2421 tc.CertFile = "configs/certs/server.pem"
2422 tc.KeyFile = "configs/certs/key.pem"
2423
2424 var err error
2425 opts := DefaultMonitorOptions()
2426 opts.NoSystemAccount = true
2427 opts.TLSTimeout = 1.5 // 1.5 seconds
2428 opts.TLSConfig, err = GenTLSConfig(tc)
2429 require_NoError(t, err)
2430 opts.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
2431 opts.Gateway.TLSConfig, err = GenTLSConfig(tc)
2432 require_NoError(t, err)
2433 opts.Gateway.TLSTimeout = 1.5
2434 opts.LeafNode.TLSConfig, err = GenTLSConfig(tc)
2435 require_NoError(t, err)
2436 opts.LeafNode.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
2437 opts.LeafNode.TLSTimeout = 1.5
2438 opts.Cluster.TLSConfig, err = GenTLSConfig(tc)
2439 require_NoError(t, err)
2440 opts.Cluster.TLSTimeout = 1.5
2441
2442 s := RunServer(opts)
2443 defer s.Shutdown()
2444
2445 check := func(verify, required bool, timeout float64) {
2446 t.Helper()
2447 if !verify {
2448 t.Fatalf("Expected tls_verify to be true")
2449 }
2450 if !required {
2451 t.Fatalf("Expected tls_required to be true")
2452 }
2453 if timeout != 1.5 {
2454 t.Fatalf("Expected tls_timeout to be 1.5")
2455 }
2456 }
2457
2458 start := time.Now()
2459 endpoint := fmt.Sprintf("http://%s:%d/varz", opts.HTTPHost, s.MonitorAddr().Port)
2460 for mode := 0; mode < 2; mode++ {
2461 varz := pollVarz(t, s, mode, endpoint, nil)
2462 duration := time.Since(start)
2463 if duration >= 1500*time.Millisecond {
2464 t.Fatalf("Looks like varz blocked on handshake, took %v", duration)
2465 }
2466 check(varz.TLSVerify, varz.TLSRequired, varz.TLSTimeout)
2467 check(varz.Cluster.TLSVerify, varz.Cluster.TLSRequired, varz.Cluster.TLSTimeout)
2468 check(varz.Gateway.TLSVerify, varz.Gateway.TLSRequired, varz.Gateway.TLSTimeout)
2469 check(varz.LeafNode.TLSVerify, varz.LeafNode.TLSRequired, varz.LeafNode.TLSTimeout)
2470 }
2471 }
2472
2473 func TestMonitorConnzTLSPeerCerts(t *testing.T) {
2474 resetPreviousHTTPConnections()
2475
2476 tc := &TLSConfigOpts{}
2477 tc.CertFile = "../test/configs/certs/server-cert.pem"
2478 tc.KeyFile = "../test/configs/certs/server-key.pem"
2479 tc.CaFile = "../test/configs/certs/ca.pem"
2480 tc.Verify = true
2481 tc.Timeout = 2.0
2482
2483 var err error
2484 opts := DefaultMonitorOptions()
2485 opts.TLSConfig, err = GenTLSConfig(tc)
2486 require_NoError(t, err)
2487
2488 s := RunServer(opts)
2489 defer s.Shutdown()
2490
2491 nc := natsConnect(t, s.ClientURL(),
2492 nats.ClientCert("../test/configs/certs/client-cert.pem", "../test/configs/certs/client-key.pem"),
2493 nats.RootCAs("../test/configs/certs/ca.pem"))
2494 defer nc.Close()
2495
2496 endpoint := fmt.Sprintf("http://%s:%d/connz", opts.HTTPHost, s.MonitorAddr().Port)
2497 for mode := 0; mode < 2; mode++ {
2498 // Without "auth" option, we should not get the details
2499 connz := pollConnz(t, s, mode, endpoint, nil)
2500 require_True(t, len(connz.Conns) == 1)
2501 c := connz.Conns[0]
2502 if c.TLSPeerCerts != nil {
2503 t.Fatalf("Did not expect TLSPeerCerts when auth is not specified: %+v", c.TLSPeerCerts)
2504 }
2505 // Now specify "auth" option
2506 connz = pollConnz(t, s, mode, endpoint+"?auth=1", &ConnzOptions{Username: true})
2507 require_True(t, len(connz.Conns) == 1)
2508 c = connz.Conns[0]
2509 if c.TLSPeerCerts == nil {
2510 t.Fatal("Expected TLSPeerCerts to be set, was not")
2511 } else if len(c.TLSPeerCerts) != 1 {
2512 t.Fatalf("Unexpected peer certificates: %+v", c.TLSPeerCerts)
2513 } else {
2514 for _, d := range c.TLSPeerCerts {
2515 if d.Subject != "CN=localhost,OU=nats.io,O=Synadia,ST=California,C=US" {
2516 t.Fatalf("Unexpected subject: %s", d.Subject)
2517 }
2518 if len(d.SubjectPKISha256) != 64 {
2519 t.Fatalf("Unexpected spki_sha256: %s", d.SubjectPKISha256)
2520 }
2521 if len(d.CertSha256) != 64 {
2522 t.Fatalf("Unexpected cert_sha256: %s", d.CertSha256)
2523 }
2524 }
2525 }
2526 }
2527 }
2528
2529 func TestMonitorServerIDs(t *testing.T) {
2530 s := runMonitorServer()
2531 defer s.Shutdown()
2532
2533 murl := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
2534
2535 for mode := 0; mode < 2; mode++ {
2536 v := pollVarz(t, s, mode, murl+"varz", nil)
2537 if v.ID == _EMPTY_ {
2538 t.Fatal("Varz ID is empty")
2539 }
2540 c := pollConnz(t, s, mode, murl+"connz", nil)
2541 if c.ID == _EMPTY_ {
2542 t.Fatal("Connz ID is empty")
2543 }
2544 r := pollRoutez(t, s, mode, murl+"routez", nil)
2545 if r.ID == _EMPTY_ {
2546 t.Fatal("Routez ID is empty")
2547 }
2548 if v.ID != c.ID || v.ID != r.ID {
2549 t.Fatalf("Varz ID [%s] is not equal to Connz ID [%s] or Routez ID [%s]", v.ID, c.ID, r.ID)
2550 }
2551 }
2552 }
2553
2554 func TestMonitorHttpStatsNoUpdatedWhenUsingServerFuncs(t *testing.T) {
2555 s := runMonitorServer()
2556 defer s.Shutdown()
2557
2558 for i := 0; i < 10; i++ {
2559 s.Varz(nil)
2560 s.Connz(nil)
2561 s.Routez(nil)
2562 s.Subsz(nil)
2563 }
2564
2565 v, _ := s.Varz(nil)
2566 endpoints := []string{VarzPath, ConnzPath, RoutezPath, SubszPath}
2567 for _, e := range endpoints {
2568 stats := v.HTTPReqStats[e]
2569 if stats != 0 {
2570 t.Fatalf("Expected HTTPReqStats for %q to be 0, got %v", e, stats)
2571 }
2572 }
2573 }
2574
2575 func TestMonitorClusterEmptyWhenNotDefined(t *testing.T) {
2576 s := runMonitorServer()
2577 defer s.Shutdown()
2578
2579 body := readBody(t, fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port))
2580 var v map[string]any
2581 if err := json.Unmarshal(body, &v); err != nil {
2582 t.Fatalf("Got an error unmarshalling the body: %v\n", err)
2583 }
2584 // Cluster can empty, or be defined but that needs to be empty.
2585 c, ok := v["cluster"]
2586 if !ok {
2587 return
2588 }
2589 if len(c.(map[string]any)) != 0 {
2590 t.Fatalf("Expected an empty cluster definition, instead got %+v\n", c)
2591 }
2592 }
2593
2594 func TestMonitorRoutezPermissions(t *testing.T) {
2595 resetPreviousHTTPConnections()
2596 opts := DefaultMonitorOptions()
2597 opts.NoSystemAccount = true
2598 opts.Cluster.Name = "A"
2599 opts.Cluster.Host = "127.0.0.1"
2600 opts.Cluster.Port = -1
2601 opts.Cluster.Permissions = &RoutePermissions{
2602 Import: &SubjectPermission{
2603 Allow: []string{"foo"},
2604 },
2605 Export: &SubjectPermission{
2606 Allow: []string{"*"},
2607 Deny: []string{"foo", "nats"},
2608 },
2609 }
2610
2611 s1 := RunServer(opts)
2612 defer s1.Shutdown()
2613
2614 opts = DefaultMonitorOptions()
2615 opts.NoSystemAccount = true
2616 opts.ServerName = "monitor_server_2"
2617 opts.Cluster.Host = "127.0.0.1"
2618 opts.Cluster.Name = "A"
2619 opts.Cluster.Port = -1
2620 routeURL, _ := url.Parse(fmt.Sprintf("nats-route://127.0.0.1:%d", s1.ClusterAddr().Port))
2621 opts.Routes = []*url.URL{routeURL}
2622 opts.HTTPPort = -1
2623
2624 s2 := RunServer(opts)
2625 defer s2.Shutdown()
2626
2627 checkClusterFormed(t, s1, s2)
2628
2629 urls := []string{
2630 fmt.Sprintf("http://127.0.0.1:%d/routez", s1.MonitorAddr().Port),
2631 fmt.Sprintf("http://127.0.0.1:%d/routez", s2.MonitorAddr().Port),
2632 }
2633 servers := []*Server{s1, s2}
2634
2635 for i, url := range urls {
2636 for mode := 0; mode < 2; mode++ {
2637 rz := pollRoutez(t, servers[i], mode, url, nil)
2638 // For server 1, we expect to see imports and exports
2639 if i == 0 {
2640 if rz.Import == nil || rz.Import.Allow == nil ||
2641 len(rz.Import.Allow) != 1 || rz.Import.Allow[0] != "foo" ||
2642 rz.Import.Deny != nil {
2643 t.Fatalf("Unexpected Import %v", rz.Import)
2644 }
2645 if rz.Export == nil || rz.Export.Allow == nil || rz.Export.Deny == nil ||
2646 len(rz.Export.Allow) != 1 || rz.Export.Allow[0] != "*" ||
2647 len(rz.Export.Deny) != 2 || rz.Export.Deny[0] != "foo" || rz.Export.Deny[1] != "nats" {
2648 t.Fatalf("Unexpected Export %v", rz.Export)
2649 }
2650 } else {
2651 // We expect to see NO imports and exports for server B by default.
2652 if rz.Import != nil {
2653 t.Fatal("Routez body should NOT contain \"import\" information.")
2654 }
2655 if rz.Export != nil {
2656 t.Fatal("Routez body should NOT contain \"export\" information.")
2657 }
2658 // We do expect to see them show up for the information we have on Server A though.
2659 if len(rz.Routes) != DEFAULT_ROUTE_POOL_SIZE {
2660 t.Fatalf("Expected route array of %d, got %v\n", DEFAULT_ROUTE_POOL_SIZE, len(rz.Routes))
2661 }
2662 route := rz.Routes[0]
2663 if route.Import == nil || route.Import.Allow == nil ||
2664 len(route.Import.Allow) != 1 || route.Import.Allow[0] != "foo" ||
2665 route.Import.Deny != nil {
2666 t.Fatalf("Unexpected Import %v", route.Import)
2667 }
2668 if route.Export == nil || route.Export.Allow == nil || route.Export.Deny == nil ||
2669 len(route.Export.Allow) != 1 || route.Export.Allow[0] != "*" ||
2670 len(route.Export.Deny) != 2 || route.Export.Deny[0] != "foo" || route.Export.Deny[1] != "nats" {
2671 t.Fatalf("Unexpected Export %v", route.Export)
2672 }
2673 }
2674 }
2675 }
2676 }
2677
2678 // Benchmark our Connz generation. Don't use HTTP here, just measure server endpoint.
2679 func Benchmark_Connz(b *testing.B) {
2680 runtime.MemProfileRate = 0
2681
2682 s := runMonitorServerNoHTTPPort()
2683 defer s.Shutdown()
2684
2685 opts := s.getOpts()
2686 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
2687
2688 // Create 250 connections with 100 subs each.
2689 for i := 0; i < 250; i++ {
2690 nc, err := nats.Connect(url)
2691 if err != nil {
2692 b.Fatalf("Error on connection[%d] to %s: %v", i, url, err)
2693 }
2694 for x := 0; x < 100; x++ {
2695 subj := fmt.Sprintf("foo.%d", x)
2696 nc.Subscribe(subj, func(m *nats.Msg) {})
2697 }
2698 nc.Flush()
2699 defer nc.Close()
2700 }
2701
2702 b.ResetTimer()
2703 runtime.MemProfileRate = 1
2704
2705 copts := &ConnzOptions{Subscriptions: false}
2706 for i := 0; i < b.N; i++ {
2707 _, err := s.Connz(copts)
2708 if err != nil {
2709 b.Fatalf("Error on Connz(): %v", err)
2710 }
2711 }
2712 }
2713
2714 func Benchmark_Varz(b *testing.B) {
2715 runtime.MemProfileRate = 0
2716
2717 s := runMonitorServerNoHTTPPort()
2718 defer s.Shutdown()
2719
2720 b.ResetTimer()
2721 runtime.MemProfileRate = 1
2722
2723 for i := 0; i < b.N; i++ {
2724 _, err := s.Varz(nil)
2725 if err != nil {
2726 b.Fatalf("Error on Connz(): %v", err)
2727 }
2728 }
2729 }
2730
2731 func Benchmark_VarzHttp(b *testing.B) {
2732 runtime.MemProfileRate = 0
2733
2734 s := runMonitorServer()
2735 defer s.Shutdown()
2736
2737 murl := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
2738
2739 b.ResetTimer()
2740 runtime.MemProfileRate = 1
2741
2742 for i := 0; i < b.N; i++ {
2743 v := &Varz{}
2744 resp, err := http.Get(murl)
2745 if err != nil {
2746 b.Fatalf("Expected no error: Got %v\n", err)
2747 }
2748 defer resp.Body.Close()
2749 body, err := io.ReadAll(resp.Body)
2750 if err != nil {
2751 b.Fatalf("Got an error reading the body: %v\n", err)
2752 }
2753 if err := json.Unmarshal(body, v); err != nil {
2754 b.Fatalf("Got an error unmarshalling the body: %v\n", err)
2755 }
2756 resp.Body.Close()
2757 }
2758 }
2759
2760 func TestMonitorVarzRaces(t *testing.T) {
2761 s := runMonitorServer()
2762 defer s.Shutdown()
2763
2764 murl := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
2765 done := make(chan struct{})
2766 wg := sync.WaitGroup{}
2767 wg.Add(1)
2768 go func() {
2769 defer wg.Done()
2770 for {
2771 for i := 0; i < 2; i++ {
2772 v := pollVarz(t, s, i, murl, nil)
2773 // Check the field that we are setting in main thread
2774 // to ensure that we have a copy and there is no
2775 // race with fields set in s.info and s.opts
2776 if v.ID == "abc" || v.MaxConn == -1 {
2777 // We will not get there. Need to have something
2778 // otherwise staticcheck will report empty branch
2779 return
2780 }
2781
2782 select {
2783 case <-done:
2784 return
2785 default:
2786 }
2787 }
2788 }
2789 }()
2790
2791 for i := 0; i < 1000; i++ {
2792 // Simulate a change in server's info and options
2793 // by changing something.
2794 s.mu.Lock()
2795 s.info.ID = fmt.Sprintf("serverid_%d", i)
2796 s.opts.MaxConn = 100 + i
2797 s.mu.Unlock()
2798 time.Sleep(time.Nanosecond)
2799 }
2800 close(done)
2801 wg.Wait()
2802
2803 // Now check that there is no race doing parallel polling
2804 wg.Add(3)
2805 done = make(chan struct{})
2806 poll := func() {
2807 defer wg.Done()
2808 for {
2809 for mode := 0; mode < 2; mode++ {
2810 pollVarz(t, s, mode, murl, nil)
2811 }
2812 select {
2813 case <-done:
2814 return
2815 default:
2816 }
2817 }
2818 }
2819 for i := 0; i < 3; i++ {
2820 go poll()
2821 }
2822 time.Sleep(500 * time.Millisecond)
2823 close(done)
2824 wg.Wait()
2825 }
2826
2827 func testMonitorStructPresent(t *testing.T, tag string) {
2828 t.Helper()
2829
2830 resetPreviousHTTPConnections()
2831 opts := DefaultMonitorOptions()
2832 opts.NoSystemAccount = true
2833 s := RunServer(opts)
2834 defer s.Shutdown()
2835
2836 varzURL := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
2837 body := readBody(t, varzURL)
2838 if !bytes.Contains(body, []byte(`"`+tag+`": {}`)) {
2839 t.Fatalf("%s should be present and empty, got %s", tag, body)
2840 }
2841 }
2842
2843 func TestMonitorCluster(t *testing.T) {
2844 testMonitorStructPresent(t, "cluster")
2845
2846 resetPreviousHTTPConnections()
2847 opts := DefaultMonitorOptions()
2848 opts.NoSystemAccount = true
2849 opts.Cluster.Name = "A"
2850 opts.Cluster.Port = -1
2851 opts.Cluster.AuthTimeout = 1
2852 opts.Routes = RoutesFromStr("nats://127.0.0.1:1234")
2853 s := RunServer(opts)
2854 defer s.Shutdown()
2855
2856 expected := ClusterOptsVarz{
2857 "A",
2858 opts.Cluster.Host,
2859 opts.Cluster.Port,
2860 opts.Cluster.AuthTimeout,
2861 []string{"127.0.0.1:1234"},
2862 opts.Cluster.TLSTimeout,
2863 opts.Cluster.TLSConfig != nil,
2864 opts.Cluster.TLSConfig != nil,
2865 DEFAULT_ROUTE_POOL_SIZE,
2866 0,
2867 _EMPTY_,
2868 time.Time{},
2869 }
2870
2871 varzURL := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
2872 for mode := 0; mode < 2; mode++ {
2873 check := func(t *testing.T, v *Varz) {
2874 t.Helper()
2875 if !reflect.DeepEqual(v.Cluster, expected) {
2876 t.Fatalf("mode=%v - expected %+v, got %+v", mode, expected, v.Cluster)
2877 }
2878 }
2879 v := pollVarz(t, s, mode, varzURL, nil)
2880 check(t, v)
2881
2882 // Having this here to make sure that if fields are added in ClusterOptsVarz,
2883 // we make sure to update this test (compiler will report an error if we don't)
2884 _ = ClusterOptsVarz{"", "", 0, 0, nil, 2, false, false, 0, 0, _EMPTY_, time.Time{}}
2885
2886 // Alter the fields to make sure that we have a proper deep copy
2887 // of what may be stored in the server. Anything we change here
2888 // should not affect the next returned value.
2889 v.Cluster.Name = "wrong"
2890 v.Cluster.Host = "wrong"
2891 v.Cluster.Port = 0
2892 v.Cluster.AuthTimeout = 0
2893 v.Cluster.URLs = []string{"wrong"}
2894 v = pollVarz(t, s, mode, varzURL, nil)
2895 check(t, v)
2896 }
2897 }
2898
2899 func TestMonitorClusterURLs(t *testing.T) {
2900 resetPreviousHTTPConnections()
2901
2902 o2 := DefaultOptions()
2903 o2.Cluster.Host = "127.0.0.1"
2904 o2.Cluster.Name = "A"
2905
2906 s2 := RunServer(o2)
2907 defer s2.Shutdown()
2908
2909 s2ClusterHostPort := fmt.Sprintf("127.0.0.1:%d", s2.ClusterAddr().Port)
2910
2911 template := `
2912 port: -1
2913 http: -1
2914 cluster: {
2915 name: "A"
2916 port: -1
2917 routes [
2918 %s
2919 %s
2920 ]
2921 }
2922 `
2923 conf := createConfFile(t, []byte(fmt.Sprintf(template, "nats://"+s2ClusterHostPort, "")))
2924 s1, _ := RunServerWithConfig(conf)
2925 defer s1.Shutdown()
2926
2927 checkClusterFormed(t, s1, s2)
2928
2929 // Check /varz cluster{} to see the URLs from s1 to s2
2930 varzURL := fmt.Sprintf("http://127.0.0.1:%d/varz", s1.MonitorAddr().Port)
2931 for mode := 0; mode < 2; mode++ {
2932 v := pollVarz(t, s1, mode, varzURL, nil)
2933 if n := len(v.Cluster.URLs); n != 1 {
2934 t.Fatalf("mode=%v - Expected 1 URL, got %v", mode, n)
2935 }
2936 if v.Cluster.URLs[0] != s2ClusterHostPort {
2937 t.Fatalf("mode=%v - Expected url %q, got %q", mode, s2ClusterHostPort, v.Cluster.URLs[0])
2938 }
2939 }
2940
2941 otherClusterHostPort := "127.0.0.1:1234"
2942 // Now update the config and add a route
2943 changeCurrentConfigContentWithNewContent(t, conf, []byte(fmt.Sprintf(template, "nats://"+s2ClusterHostPort, "nats://"+otherClusterHostPort)))
2944
2945 if err := s1.Reload(); err != nil {
2946 t.Fatalf("Error on reload: %v", err)
2947 }
2948
2949 // Verify cluster still ok
2950 checkClusterFormed(t, s1, s2)
2951
2952 // Now verify that s1 reports in /varz the new URL
2953 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
2954 for mode := 0; mode < 2; mode++ {
2955 v := pollVarz(t, s1, mode, varzURL, nil)
2956 if n := len(v.Cluster.URLs); n != 2 {
2957 t.Fatalf("mode=%v - Expected 2 URL, got %v", mode, n)
2958 }
2959 gotS2 := false
2960 gotOther := false
2961 for _, u := range v.Cluster.URLs {
2962 if u == s2ClusterHostPort {
2963 gotS2 = true
2964 } else if u == otherClusterHostPort {
2965 gotOther = true
2966 } else {
2967 t.Fatalf("mode=%v - Incorrect url: %q", mode, u)
2968 }
2969 }
2970 if !gotS2 {
2971 t.Fatalf("mode=%v - Did not get cluster URL for s2", mode)
2972 }
2973 if !gotOther {
2974 t.Fatalf("mode=%v - Did not get the new cluster URL", mode)
2975 }
2976 }
2977 return nil
2978 })
2979
2980 // Remove all routes from config
2981 changeCurrentConfigContentWithNewContent(t, conf, []byte(fmt.Sprintf(template, "", "")))
2982
2983 if err := s1.Reload(); err != nil {
2984 t.Fatalf("Error on reload: %v", err)
2985 }
2986
2987 // Now verify that s1 reports no ULRs in /varz
2988 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
2989 for mode := 0; mode < 2; mode++ {
2990 v := pollVarz(t, s1, mode, varzURL, nil)
2991 if n := len(v.Cluster.URLs); n != 0 {
2992 t.Fatalf("mode=%v - Expected 0 URL, got %v", mode, n)
2993 }
2994 }
2995 return nil
2996 })
2997 }
2998
2999 func TestMonitorGateway(t *testing.T) {
3000 testMonitorStructPresent(t, "gateway")
3001
3002 resetPreviousHTTPConnections()
3003 opts := DefaultMonitorOptions()
3004 opts.NoSystemAccount = true
3005 opts.Gateway.Name = "A"
3006 opts.Gateway.Port = -1
3007 opts.Gateway.AuthTimeout = 1
3008 opts.Gateway.TLSTimeout = 1
3009 opts.Gateway.Advertise = "127.0.0.1"
3010 opts.Gateway.ConnectRetries = 1
3011 opts.Gateway.RejectUnknown = false
3012 u1, _ := url.Parse("nats://ivan:pwd@localhost:1234")
3013 u2, _ := url.Parse("nats://localhost:1235")
3014 opts.Gateway.Gateways = []*RemoteGatewayOpts{
3015 {
3016 Name: "B",
3017 TLSTimeout: 1,
3018 URLs: []*url.URL{
3019 u1,
3020 u2,
3021 },
3022 },
3023 }
3024 s := RunServer(opts)
3025 defer s.Shutdown()
3026
3027 expected := GatewayOptsVarz{
3028 "A",
3029 opts.Gateway.Host,
3030 opts.Gateway.Port,
3031 opts.Gateway.AuthTimeout,
3032 opts.Gateway.TLSTimeout,
3033 opts.Gateway.TLSConfig != nil,
3034 opts.Gateway.TLSConfig != nil,
3035 opts.Gateway.Advertise,
3036 opts.Gateway.ConnectRetries,
3037 []RemoteGatewayOptsVarz{{"B", 1, nil}},
3038 opts.Gateway.RejectUnknown,
3039 0,
3040 _EMPTY_,
3041 time.Time{},
3042 }
3043 // Since URLs array is not guaranteed to be always the same order,
3044 // we don't add it in the expected GatewayOptsVarz, instead we
3045 // maintain here.
3046 expectedURLs := []string{"localhost:1234", "localhost:1235"}
3047
3048 varzURL := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
3049 for mode := 0; mode < 2; mode++ {
3050 check := func(t *testing.T, v *Varz) {
3051 t.Helper()
3052 var urls []string
3053 if len(v.Gateway.Gateways) == 1 {
3054 urls = v.Gateway.Gateways[0].URLs
3055 v.Gateway.Gateways[0].URLs = nil
3056 }
3057 if !reflect.DeepEqual(v.Gateway, expected) {
3058 t.Fatalf("mode=%v - expected %+v, got %+v", mode, expected, v.Gateway)
3059 }
3060 // Now compare urls
3061 for _, u := range expectedURLs {
3062 ok := false
3063 for _, u2 := range urls {
3064 if u == u2 {
3065 ok = true
3066 break
3067 }
3068 }
3069 if !ok {
3070 t.Fatalf("mode=%v - expected urls to be %v, got %v", mode, expected.Gateways[0].URLs, urls)
3071 }
3072 }
3073 }
3074 v := pollVarz(t, s, mode, varzURL, nil)
3075 check(t, v)
3076
3077 // Having this here to make sure that if fields are added in GatewayOptsVarz,
3078 // we make sure to update this test (compiler will report an error if we don't)
3079 _ = GatewayOptsVarz{"", "", 0, 0, 0, false, false, "", 0, []RemoteGatewayOptsVarz{{"", 0, nil}}, false, 0, "default", time.Time{}}
3080
3081 // Alter the fields to make sure that we have a proper deep copy
3082 // of what may be stored in the server. Anything we change here
3083 // should not affect the next returned value.
3084 v.Gateway.Name = "wrong"
3085 v.Gateway.Host = "wrong"
3086 v.Gateway.Port = 0
3087 v.Gateway.AuthTimeout = 1234.5
3088 v.Gateway.TLSTimeout = 1234.5
3089 v.Gateway.Advertise = "wrong"
3090 v.Gateway.ConnectRetries = 1234
3091 v.Gateway.Gateways[0].Name = "wrong"
3092 v.Gateway.Gateways[0].TLSTimeout = 1234.5
3093 v.Gateway.Gateways[0].URLs = []string{"wrong"}
3094 v.Gateway.RejectUnknown = true
3095 v = pollVarz(t, s, mode, varzURL, nil)
3096 check(t, v)
3097 }
3098 }
3099
3100 func TestMonitorGatewayURLsUpdated(t *testing.T) {
3101 resetPreviousHTTPConnections()
3102
3103 ob1 := testDefaultOptionsForGateway("B")
3104 sb1 := runGatewayServer(ob1)
3105 defer sb1.Shutdown()
3106
3107 // Start a1 that has a single URL to sb1.
3108 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb1)
3109 oa.HTTPHost = "127.0.0.1"
3110 oa.HTTPPort = MONITOR_PORT
3111 sa := runGatewayServer(oa)
3112 defer sa.Shutdown()
3113
3114 waitForOutboundGateways(t, sa, 1, 2*time.Second)
3115
3116 varzURL := fmt.Sprintf("http://127.0.0.1:%d/varz", sa.MonitorAddr().Port)
3117 // Check the /varz gateway's URLs
3118 for mode := 0; mode < 2; mode++ {
3119 v := pollVarz(t, sa, mode, varzURL, nil)
3120 if n := len(v.Gateway.Gateways); n != 1 {
3121 t.Fatalf("mode=%v - Expected 1 remote gateway, got %v", mode, n)
3122 }
3123 gw := v.Gateway.Gateways[0]
3124 if n := len(gw.URLs); n != 1 {
3125 t.Fatalf("mode=%v - Expected 1 url, got %v", mode, n)
3126 }
3127 expected := oa.Gateway.Gateways[0].URLs[0].Host
3128 if u := gw.URLs[0]; u != expected {
3129 t.Fatalf("mode=%v - Expected URL %q, got %q", mode, expected, u)
3130 }
3131 }
3132
3133 // Now start sb2 that clusters with sb1. sa should add to its list of URLs
3134 // sb2 gateway's connect URL.
3135 ob2 := testDefaultOptionsForGateway("B")
3136 ob2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", sb1.ClusterAddr().Port))
3137 sb2 := runGatewayServer(ob2)
3138 defer sb2.Shutdown()
3139
3140 // Wait for sb1 and sb2 to connect
3141 checkClusterFormed(t, sb1, sb2)
3142 // sb2 should be made aware of gateway A and connect to sa
3143 waitForInboundGateways(t, sa, 2, 2*time.Second)
3144 // Now check that URLs in /varz get updated
3145 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
3146 for mode := 0; mode < 2; mode++ {
3147 v := pollVarz(t, sa, mode, varzURL, nil)
3148 if n := len(v.Gateway.Gateways); n != 1 {
3149 return fmt.Errorf("mode=%v - Expected 1 remote gateway, got %v", mode, n)
3150 }
3151 gw := v.Gateway.Gateways[0]
3152 if n := len(gw.URLs); n != 2 {
3153 return fmt.Errorf("mode=%v - Expected 2 urls, got %v", mode, n)
3154 }
3155
3156 gotSB1 := false
3157 gotSB2 := false
3158 for _, u := range gw.URLs {
3159 if u == fmt.Sprintf("127.0.0.1:%d", sb1.GatewayAddr().Port) {
3160 gotSB1 = true
3161 } else if u == fmt.Sprintf("127.0.0.1:%d", sb2.GatewayAddr().Port) {
3162 gotSB2 = true
3163 } else {
3164 return fmt.Errorf("mode=%v - Incorrect URL to gateway B: %v", mode, u)
3165 }
3166 }
3167 if !gotSB1 {
3168 return fmt.Errorf("mode=%v - Did not get URL to sb1", mode)
3169 }
3170 if !gotSB2 {
3171 return fmt.Errorf("mode=%v - Did not get URL to sb2", mode)
3172 }
3173 }
3174 return nil
3175 })
3176
3177 // Now stop sb2 and make sure that its removal is reflected in varz.
3178 sb2.Shutdown()
3179 // Wait for it to disappear from sa.
3180 waitForInboundGateways(t, sa, 1, 2*time.Second)
3181 // Now check that URLs in /varz get updated.
3182 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
3183 for mode := 0; mode < 2; mode++ {
3184 v := pollVarz(t, sa, mode, varzURL, nil)
3185 if n := len(v.Gateway.Gateways); n != 1 {
3186 return fmt.Errorf("mode=%v - Expected 1 remote gateway, got %v", mode, n)
3187 }
3188 gw := v.Gateway.Gateways[0]
3189 if n := len(gw.URLs); n != 1 {
3190 return fmt.Errorf("mode=%v - Expected 1 url, got %v", mode, n)
3191 }
3192 u := gw.URLs[0]
3193 if u != fmt.Sprintf("127.0.0.1:%d", sb1.GatewayAddr().Port) {
3194 return fmt.Errorf("mode=%v - Did not get URL to sb1", mode)
3195 }
3196 }
3197 return nil
3198 })
3199 }
3200
3201 func TestMonitorGatewayReportItsOwnURLs(t *testing.T) {
3202 resetPreviousHTTPConnections()
3203
3204 // In this test, we show that if a server has its own gateway information
3205 // as a remote (which is the case when remote gateway definitions is copied
3206 // on all clusters), we display the defined URLs.
3207 oa := testGatewayOptionsFromToWithURLs(t, "A", "A", []string{"nats://127.0.0.1:1234", "nats://127.0.0.1:1235"})
3208 oa.HTTPHost = "127.0.0.1"
3209 oa.HTTPPort = MONITOR_PORT
3210 sa := runGatewayServer(oa)
3211 defer sa.Shutdown()
3212
3213 varzURL := fmt.Sprintf("http://127.0.0.1:%d/varz", sa.MonitorAddr().Port)
3214 // Check the /varz gateway's URLs
3215 for mode := 0; mode < 2; mode++ {
3216 v := pollVarz(t, sa, mode, varzURL, nil)
3217 if n := len(v.Gateway.Gateways); n != 1 {
3218 t.Fatalf("mode=%v - Expected 1 remote gateway, got %v", mode, n)
3219 }
3220 gw := v.Gateway.Gateways[0]
3221 if n := len(gw.URLs); n != 2 {
3222 t.Fatalf("mode=%v - Expected 2 urls, got %v", mode, gw.URLs)
3223 }
3224 expected := []string{"127.0.0.1:1234", "127.0.0.1:1235"}
3225 if !reflect.DeepEqual(gw.URLs, expected) {
3226 t.Fatalf("mode=%v - Expected URLs %q, got %q", mode, expected, gw.URLs)
3227 }
3228 }
3229 }
3230
3231 func TestMonitorLeafNode(t *testing.T) {
3232 testMonitorStructPresent(t, "leaf")
3233
3234 resetPreviousHTTPConnections()
3235 opts := DefaultMonitorOptions()
3236 opts.NoSystemAccount = true
3237 opts.LeafNode.Port = -1
3238 opts.LeafNode.AuthTimeout = 1
3239 opts.LeafNode.TLSTimeout = 1
3240 opts.Accounts = []*Account{NewAccount("acc")}
3241 u, _ := url.Parse("nats://ivan:pwd@localhost:1234")
3242 opts.LeafNode.Remotes = []*RemoteLeafOpts{
3243 {
3244 LocalAccount: "acc",
3245 URLs: []*url.URL{u},
3246 TLSTimeout: 1,
3247 },
3248 }
3249 s := RunServer(opts)
3250 defer s.Shutdown()
3251
3252 expected := LeafNodeOptsVarz{
3253 opts.LeafNode.Host,
3254 opts.LeafNode.Port,
3255 opts.LeafNode.AuthTimeout,
3256 opts.LeafNode.TLSTimeout,
3257 opts.LeafNode.TLSConfig != nil,
3258 opts.LeafNode.TLSConfig != nil,
3259 []RemoteLeafOptsVarz{
3260 {
3261 "acc", 1, []string{"localhost:1234"}, nil, false,
3262 },
3263 },
3264 false,
3265 0,
3266 _EMPTY_,
3267 time.Time{},
3268 }
3269
3270 varzURL := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
3271
3272 for mode := 0; mode < 2; mode++ {
3273 check := func(t *testing.T, v *Varz) {
3274 t.Helper()
3275 // Issue 5913. When we have solicited leafnodes but no clustering
3276 // and no clustername, we may need a stable clustername so we use
3277 // the server name as cluster name. However, we should not expose
3278 // it in /varz.
3279 if v.Cluster.Name != _EMPTY_ {
3280 t.Fatalf("mode=%v - unexpected cluster name: %s", mode, v.Cluster.Name)
3281 }
3282 // Check rest is as expected.
3283 if !reflect.DeepEqual(v.LeafNode, expected) {
3284 t.Fatalf("mode=%v - expected %+v, got %+v", mode, expected, v.LeafNode)
3285 }
3286 }
3287 v := pollVarz(t, s, mode, varzURL, nil)
3288 check(t, v)
3289
3290 // Having this here to make sure that if fields are added in ClusterOptsVarz,
3291 // we make sure to update this test (compiler will report an error if we don't)
3292 _ = LeafNodeOptsVarz{"", 0, 0, 0, false, false, []RemoteLeafOptsVarz{{"", 0, nil, nil, false}}, false, 0, _EMPTY_, time.Time{}}
3293
3294 // Alter the fields to make sure that we have a proper deep copy
3295 // of what may be stored in the server. Anything we change here
3296 // should not affect the next returned value.
3297 v.LeafNode.Host = "wrong"
3298 v.LeafNode.Port = 0
3299 v.LeafNode.AuthTimeout = 1234.5
3300 v.LeafNode.TLSTimeout = 1234.5
3301 v.LeafNode.Remotes[0].LocalAccount = "wrong"
3302 v.LeafNode.Remotes[0].URLs = append(v.LeafNode.Remotes[0].URLs, "wrong")
3303 v.LeafNode.Remotes[0].TLSTimeout = 1234.5
3304 v = pollVarz(t, s, mode, varzURL, nil)
3305 check(t, v)
3306 }
3307 }
3308
3309 func pollGatewayz(t *testing.T, s *Server, mode int, url string, opts *GatewayzOptions) *Gatewayz {
3310 t.Helper()
3311 if mode == 0 {
3312 g := &Gatewayz{}
3313 body := readBody(t, url)
3314 if err := json.Unmarshal(body, g); err != nil {
3315 t.Fatalf("Got an error unmarshalling the body: %v\n", err)
3316 }
3317 return g
3318 }
3319 g, err := s.Gatewayz(opts)
3320 if err != nil {
3321 t.Fatalf("Error on Gatewayz: %v", err)
3322 }
3323 return g
3324 }
3325
3326 func TestMonitorGatewayz(t *testing.T) {
3327 resetPreviousHTTPConnections()
3328
3329 // First check that without gateway configured
3330 s := runMonitorServer()
3331 defer s.Shutdown()
3332 url := fmt.Sprintf("http://127.0.0.1:%d/gatewayz", s.MonitorAddr().Port)
3333 for pollMode := 0; pollMode < 2; pollMode++ {
3334 g := pollGatewayz(t, s, pollMode, url, nil)
3335 // Expect Name and port to be empty
3336 if g.Name != _EMPTY_ || g.Port != 0 {
3337 t.Fatalf("Expected no gateway, got %+v", g)
3338 }
3339 }
3340 s.Shutdown()
3341
3342 ob1 := testDefaultOptionsForGateway("B")
3343 sb1 := runGatewayServer(ob1)
3344 defer sb1.Shutdown()
3345
3346 // Start a1 that has a single URL to sb1.
3347 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb1)
3348 oa.HTTPHost = "127.0.0.1"
3349 oa.HTTPPort = MONITOR_PORT
3350 sa := runGatewayServer(oa)
3351 defer sa.Shutdown()
3352
3353 waitForOutboundGateways(t, sa, 1, 2*time.Second)
3354 waitForInboundGateways(t, sa, 1, 2*time.Second)
3355
3356 waitForOutboundGateways(t, sb1, 1, 2*time.Second)
3357 waitForInboundGateways(t, sb1, 1, 2*time.Second)
3358
3359 gatewayzURL := fmt.Sprintf("http://127.0.0.1:%d/gatewayz", sa.MonitorAddr().Port)
3360 for pollMode := 0; pollMode < 2; pollMode++ {
3361 g := pollGatewayz(t, sa, pollMode, gatewayzURL, nil)
3362 if g.Host != oa.Gateway.Host {
3363 t.Fatalf("mode=%v - Expected host to be %q, got %q", pollMode, oa.Gateway.Host, g.Host)
3364 }
3365 if g.Port != oa.Gateway.Port {
3366 t.Fatalf("mode=%v - Expected port to be %v, got %v", pollMode, oa.Gateway.Port, g.Port)
3367 }
3368 if n := len(g.OutboundGateways); n != 1 {
3369 t.Fatalf("mode=%v - Expected outbound to 1 gateway, got %v", pollMode, n)
3370 }
3371 if n := len(g.InboundGateways); n != 1 {
3372 t.Fatalf("mode=%v - Expected inbound from 1 gateway, got %v", pollMode, n)
3373 }
3374 og := g.OutboundGateways["B"]
3375 if og == nil {
3376 t.Fatalf("mode=%v - Expected to find outbound connection to B, got none", pollMode)
3377 }
3378 if !og.IsConfigured {
3379 t.Fatalf("mode=%v - Expected gw connection to be configured, was not", pollMode)
3380 }
3381 if og.Connection == nil {
3382 t.Fatalf("mode=%v - Expected outbound connection to B to be set, wat not", pollMode)
3383 }
3384 if og.Connection.Name != sb1.ID() {
3385 t.Fatalf("mode=%v - Expected outbound connection to B to have name %q, got %q", pollMode, sb1.ID(), og.Connection.Name)
3386 }
3387 if n := len(og.Accounts); n != 0 {
3388 t.Fatalf("mode=%v - Expected no account, got %v", pollMode, n)
3389 }
3390 ig := g.InboundGateways["B"]
3391 if ig == nil {
3392 t.Fatalf("mode=%v - Expected to find inbound connection from B, got none", pollMode)
3393 }
3394 if n := len(ig); n != 1 {
3395 t.Fatalf("mode=%v - Expected 1 inbound connection, got %v", pollMode, n)
3396 }
3397 igc := ig[0]
3398 if igc.Connection == nil {
3399 t.Fatalf("mode=%v - Expected inbound connection to B to be set, wat not", pollMode)
3400 }
3401 if igc.Connection.Name != sb1.ID() {
3402 t.Fatalf("mode=%v - Expected inbound connection to B to have name %q, got %q", pollMode, sb1.ID(), igc.Connection.Name)
3403 }
3404 }
3405
3406 // Now start sb2 that clusters with sb1. sa should add to its list of URLs
3407 // sb2 gateway's connect URL.
3408 ob2 := testDefaultOptionsForGateway("B")
3409 ob2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", sb1.ClusterAddr().Port))
3410 sb2 := runGatewayServer(ob2)
3411 defer sb2.Shutdown()
3412
3413 // Wait for sb1 and sb2 to connect
3414 checkClusterFormed(t, sb1, sb2)
3415 // sb2 should be made aware of gateway A and connect to sa
3416 waitForInboundGateways(t, sa, 2, 2*time.Second)
3417 // Now check that URLs in /varz get updated
3418 checkGatewayB := func(t *testing.T, url string, opts *GatewayzOptions) {
3419 t.Helper()
3420 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
3421 for pollMode := 0; pollMode < 2; pollMode++ {
3422 g := pollGatewayz(t, sa, pollMode, url, opts)
3423 if n := len(g.OutboundGateways); n != 1 {
3424 t.Fatalf("mode=%v - Expected outbound to 1 gateway, got %v", pollMode, n)
3425 }
3426 // The InboundGateways is a map with key the gateway names,
3427 // then value is array of connections. So should be 1 here.
3428 if n := len(g.InboundGateways); n != 1 {
3429 t.Fatalf("mode=%v - Expected inbound from 1 gateway, got %v", pollMode, n)
3430 }
3431 ig := g.InboundGateways["B"]
3432 if ig == nil {
3433 t.Fatalf("mode=%v - Expected to find inbound connection from B, got none", pollMode)
3434 }
3435 if n := len(ig); n != 2 {
3436 t.Fatalf("mode=%v - Expected 2 inbound connections from gateway B, got %v", pollMode, n)
3437 }
3438 gotSB1 := false
3439 gotSB2 := false
3440 for _, rg := range ig {
3441 if rg.Connection != nil {
3442 if rg.Connection.Name == sb1.ID() {
3443 gotSB1 = true
3444 } else if rg.Connection.Name == sb2.ID() {
3445 gotSB2 = true
3446 }
3447 }
3448 }
3449 if !gotSB1 {
3450 t.Fatalf("mode=%v - Missing inbound connection from sb1", pollMode)
3451 }
3452 if !gotSB2 {
3453 t.Fatalf("mode=%v - Missing inbound connection from sb2", pollMode)
3454 }
3455 }
3456 return nil
3457 })
3458 }
3459 checkGatewayB(t, gatewayzURL, nil)
3460
3461 // Start a new cluser C that connects to B. A should see it as
3462 // a non-configured gateway.
3463 oc := testGatewayOptionsFromToWithServers(t, "C", "B", sb1)
3464 sc := runGatewayServer(oc)
3465 defer sc.Shutdown()
3466
3467 // All servers should have 2 outbound connections (one for each other cluster)
3468 waitForOutboundGateways(t, sa, 2, 2*time.Second)
3469 waitForOutboundGateways(t, sb1, 2, 2*time.Second)
3470 waitForOutboundGateways(t, sb2, 2, 2*time.Second)
3471 waitForOutboundGateways(t, sc, 2, 2*time.Second)
3472
3473 // Server sa should have 3 inbounds now
3474 waitForInboundGateways(t, sa, 3, 2*time.Second)
3475
3476 // Check gatewayz again to see that we have C now.
3477 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
3478 for pollMode := 0; pollMode < 2; pollMode++ {
3479 g := pollGatewayz(t, sa, pollMode, gatewayzURL, nil)
3480 if n := len(g.OutboundGateways); n != 2 {
3481 t.Fatalf("mode=%v - Expected outbound to 2 gateways, got %v", pollMode, n)
3482 }
3483 // The InboundGateways is a map with key the gateway names,
3484 // then value is array of connections. So should be 2 here.
3485 if n := len(g.InboundGateways); n != 2 {
3486 t.Fatalf("mode=%v - Expected inbound from 2 gateways, got %v", pollMode, n)
3487 }
3488 og := g.OutboundGateways["C"]
3489 if og == nil {
3490 t.Fatalf("mode=%v - Expected to find outbound connection to C, got none", pollMode)
3491 }
3492 if og.IsConfigured {
3493 t.Fatalf("mode=%v - Expected IsConfigured for gateway C to be false, was true", pollMode)
3494 }
3495 if og.Connection == nil {
3496 t.Fatalf("mode=%v - Expected connection to C, got none", pollMode)
3497 }
3498 if og.Connection.Name != sc.ID() {
3499 t.Fatalf("mode=%v - Expected outbound connection to C to have name %q, got %q", pollMode, sc.ID(), og.Connection.Name)
3500 }
3501 ig := g.InboundGateways["C"]
3502 if ig == nil {
3503 t.Fatalf("mode=%v - Expected to find inbound connection from C, got none", pollMode)
3504 }
3505 if n := len(ig); n != 1 {
3506 t.Fatalf("mode=%v - Expected 1 inbound connections from gateway C, got %v", pollMode, n)
3507 }
3508 igc := ig[0]
3509 if igc.Connection == nil {
3510 t.Fatalf("mode=%v - Expected connection to C, got none", pollMode)
3511 }
3512 if igc.Connection.Name != sc.ID() {
3513 t.Fatalf("mode=%v - Expected outbound connection to C to have name %q, got %q", pollMode, sc.ID(), og.Connection.Name)
3514 }
3515 }
3516 return nil
3517 })
3518
3519 // Select only 1 gateway by passing the name to option/url
3520 opts := &GatewayzOptions{Name: "B"}
3521 checkGatewayB(t, gatewayzURL+"?gw_name=B", opts)
3522
3523 // Stop gateway C and check that we have only B, with and without filter.
3524 sc.Shutdown()
3525 checkGatewayB(t, gatewayzURL+"?gw_name=B", opts)
3526 checkGatewayB(t, gatewayzURL, nil)
3527 }
3528
3529 func TestMonitorGatewayzAccounts(t *testing.T) {
3530 GatewayDoNotForceInterestOnlyMode(true)
3531 defer GatewayDoNotForceInterestOnlyMode(false)
3532
3533 resetPreviousHTTPConnections()
3534
3535 // Create bunch of Accounts
3536 totalAccounts := 15
3537 accounts := ""
3538 for i := 0; i < totalAccounts; i++ {
3539 acc := fmt.Sprintf(" acc_%d: { users=[{user:user_%d, password: pwd}] }\n", i, i)
3540 accounts += acc
3541 }
3542
3543 bConf := createConfFile(t, []byte(fmt.Sprintf(`
3544 accounts {
3545 %s
3546 }
3547 port: -1
3548 http: -1
3549 gateway: {
3550 name: "B"
3551 port: -1
3552 }
3553 no_sys_acc = true
3554 `, accounts)))
3555
3556 sb, ob := RunServerWithConfig(bConf)
3557 defer sb.Shutdown()
3558 sb.SetLogger(&DummyLogger{}, true, true)
3559
3560 // Start a1 that has a single URL to sb1.
3561 aConf := createConfFile(t, []byte(fmt.Sprintf(`
3562 accounts {
3563 %s
3564 }
3565 port: -1
3566 http: -1
3567 gateway: {
3568 name: "A"
3569 port: -1
3570 gateways [
3571 {
3572 name: "B"
3573 url: "nats://127.0.0.1:%d"
3574 }
3575 ]
3576 }
3577 no_sys_acc = true
3578 `, accounts, sb.GatewayAddr().Port)))
3579
3580 sa, oa := RunServerWithConfig(aConf)
3581 defer sa.Shutdown()
3582 sa.SetLogger(&DummyLogger{}, true, true)
3583
3584 waitForOutboundGateways(t, sa, 1, 2*time.Second)
3585 waitForInboundGateways(t, sa, 1, 2*time.Second)
3586 waitForOutboundGateways(t, sb, 1, 2*time.Second)
3587 waitForInboundGateways(t, sb, 1, 2*time.Second)
3588
3589 // Create clients for each account on A and publish a message
3590 // so that list of accounts appear in gatewayz
3591 produceMsgsFromA := func(t *testing.T) {
3592 t.Helper()
3593 for i := 0; i < totalAccounts; i++ {
3594 nc, err := nats.Connect(fmt.Sprintf("nats://user_%d:pwd@%s:%d", i, oa.Host, oa.Port))
3595 if err != nil {
3596 t.Fatalf("Error on connect: %v", err)
3597 }
3598 nc.Publish("foo", []byte("hello"))
3599 nc.Flush()
3600 nc.Close()
3601 }
3602 }
3603 produceMsgsFromA(t)
3604
3605 // Wait for A- for all accounts
3606 gwc := sa.getOutboundGatewayConnection("B")
3607 for i := 0; i < totalAccounts; i++ {
3608 checkForAccountNoInterest(t, gwc, fmt.Sprintf("acc_%d", i), true, 2*time.Second)
3609 }
3610
3611 // Check accounts...
3612 gatewayzURL := fmt.Sprintf("http://127.0.0.1:%d/gatewayz", sa.MonitorAddr().Port)
3613 for pollMode := 0; pollMode < 2; pollMode++ {
3614 // First, without asking for it, they should not be present.
3615 g := pollGatewayz(t, sa, pollMode, gatewayzURL, nil)
3616 og := g.OutboundGateways["B"]
3617 if og == nil {
3618 t.Fatalf("mode=%v - Expected outbound gateway to B, got none", pollMode)
3619 }
3620 if n := len(og.Accounts); n != 0 {
3621 t.Fatalf("mode=%v - Expected accounts list to not be present by default, got %v", pollMode, n)
3622 }
3623 // Now ask for the accounts
3624 g = pollGatewayz(t, sa, pollMode, gatewayzURL+"?accs=1", &GatewayzOptions{Accounts: true})
3625 og = g.OutboundGateways["B"]
3626 if og == nil {
3627 t.Fatalf("mode=%v - Expected outbound gateway to B, got none", pollMode)
3628 }
3629 if n := len(og.Accounts); n != totalAccounts {
3630 t.Fatalf("mode=%v - Expected to get all %d accounts, got %v", pollMode, totalAccounts, n)
3631 }
3632 // Now account details
3633 for _, acc := range og.Accounts {
3634 if acc.InterestMode != Optimistic.String() {
3635 t.Fatalf("mode=%v - Expected optimistic mode, got %q", pollMode, acc.InterestMode)
3636 }
3637 // Since there is no interest at all on B, the publish
3638 // will have resulted in total account no interest, so
3639 // the number of no interest (subject wise) should be 0
3640 if acc.NoInterestCount != 0 {
3641 t.Fatalf("mode=%v - Expected 0 no-interest, got %v", pollMode, acc.NoInterestCount)
3642 }
3643 if acc.NumQueueSubscriptions != 0 || acc.TotalSubscriptions != 0 {
3644 t.Fatalf("mode=%v - Expected total subs to be 0, got %v - and num queue subs to be 0, got %v",
3645 pollMode, acc.TotalSubscriptions, acc.NumQueueSubscriptions)
3646 }
3647 }
3648 }
3649
3650 // Check inbound on B
3651 gwURLServerB := fmt.Sprintf("http://127.0.0.1:%d/gatewayz", sb.MonitorAddr().Port)
3652 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
3653 for pollMode := 0; pollMode < 2; pollMode++ {
3654 // First, without asking for it, they should not be present.
3655 g := pollGatewayz(t, sb, pollMode, gwURLServerB, nil)
3656 igs := g.InboundGateways["A"]
3657 if igs == nil {
3658 return fmt.Errorf("mode=%v - Expected inbound gateway to A, got none", pollMode)
3659 }
3660 if len(igs) != 1 {
3661 return fmt.Errorf("mode=%v - Expected single inbound, got %v", pollMode, len(igs))
3662 }
3663 ig := igs[0]
3664 if n := len(ig.Accounts); n != 0 {
3665 return fmt.Errorf("mode=%v - Expected no account, got %v", pollMode, n)
3666 }
3667 // Check that list of accounts
3668 g = pollGatewayz(t, sb, pollMode, gwURLServerB+"?accs=1", &GatewayzOptions{Accounts: true})
3669 igs = g.InboundGateways["A"]
3670 if igs == nil {
3671 return fmt.Errorf("mode=%v - Expected inbound gateway to A, got none", pollMode)
3672 }
3673 if len(igs) != 1 {
3674 return fmt.Errorf("mode=%v - Expected single inbound, got %v", pollMode, len(igs))
3675 }
3676 ig = igs[0]
3677 if ig.Connection == nil {
3678 return fmt.Errorf("mode=%v - Expected inbound connection from A to be set, wat not", pollMode)
3679 }
3680 if ig.Connection.Name != sa.ID() {
3681 t.Fatalf("mode=%v - Expected inbound connection from A to have name %q, got %q", pollMode, sa.ID(), ig.Connection.Name)
3682 }
3683 if n := len(ig.Accounts); n != totalAccounts {
3684 return fmt.Errorf("mode=%v - Expected to get all %d accounts, got %v", pollMode, totalAccounts, n)
3685 }
3686 // Now account details
3687 for _, acc := range ig.Accounts {
3688 if acc.InterestMode != Optimistic.String() {
3689 return fmt.Errorf("mode=%v - Expected optimistic mode, got %q", pollMode, acc.InterestMode)
3690 }
3691 // Since there is no interest at all on B, the publish
3692 // will have resulted in total account no interest, so
3693 // the number of no interest (subject wise) should be 0
3694 if acc.NoInterestCount != 0 {
3695 t.Fatalf("mode=%v - Expected 0 no-interest, got %v", pollMode, acc.NoInterestCount)
3696 }
3697 // For inbound gateway, NumQueueSubscriptions and TotalSubscriptions
3698 // are not relevant.
3699 if acc.NumQueueSubscriptions != 0 || acc.TotalSubscriptions != 0 {
3700 return fmt.Errorf("mode=%v - For inbound connection, expected num queue subs and total subs to be 0, got %v and %v",
3701 pollMode, acc.TotalSubscriptions, acc.NumQueueSubscriptions)
3702 }
3703 }
3704 }
3705 return nil
3706 })
3707
3708 // Now create subscriptions on B to prevent A- and check on subject no interest
3709 for i := 0; i < totalAccounts; i++ {
3710 nc, err := nats.Connect(fmt.Sprintf("nats://user_%d:pwd@%s:%d", i, ob.Host, ob.Port))
3711 if err != nil {
3712 t.Fatalf("Error on connect: %v", err)
3713 }
3714 defer nc.Close()
3715 // Create a queue sub so it shows up in gatewayz
3716 nc.QueueSubscribeSync("bar", "queue")
3717 // Create plain subscriptions on baz.0, baz.1 and baz.2.
3718 // Create to for each subject. Since gateways will send
3719 // only once per subject, the number of subs should be 3, not 6.
3720 for j := 0; j < 3; j++ {
3721 subj := fmt.Sprintf("baz.%d", j)
3722 nc.SubscribeSync(subj)
3723 nc.SubscribeSync(subj)
3724 }
3725 nc.Flush()
3726 }
3727
3728 for i := 0; i < totalAccounts; i++ {
3729 accName := fmt.Sprintf("acc_%d", i)
3730 checkForRegisteredQSubInterest(t, sa, "B", accName, "bar", 1, 2*time.Second)
3731 }
3732
3733 // Resend msgs from A on foo, on all accounts. There will be no interest on this subject.
3734 produceMsgsFromA(t)
3735
3736 for i := 0; i < totalAccounts; i++ {
3737 accName := fmt.Sprintf("acc_%d", i)
3738 checkForSubjectNoInterest(t, gwc, accName, "foo", true, 2*time.Second)
3739 // Verify that we still have the queue interest registered
3740 checkForRegisteredQSubInterest(t, sa, "B", accName, "bar", 1, 2*time.Second)
3741 }
3742
3743 // Check accounts...
3744 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
3745 for pollMode := 0; pollMode < 2; pollMode++ {
3746 g := pollGatewayz(t, sa, pollMode, gatewayzURL+"?accs=1", &GatewayzOptions{Accounts: true})
3747 og := g.OutboundGateways["B"]
3748 if og == nil {
3749 return fmt.Errorf("mode=%v - Expected outbound gateway to B, got none", pollMode)
3750 }
3751 if n := len(og.Accounts); n != totalAccounts {
3752 return fmt.Errorf("mode=%v - Expected to get all %d accounts, got %v", pollMode, totalAccounts, n)
3753 }
3754 // Now account details
3755 for _, acc := range og.Accounts {
3756 if acc.InterestMode != Optimistic.String() {
3757 return fmt.Errorf("mode=%v - Expected optimistic mode, got %q", pollMode, acc.InterestMode)
3758 }
3759 if acc.NoInterestCount != 1 {
3760 return fmt.Errorf("mode=%v - Expected 1 no-interest, got %v", pollMode, acc.NoInterestCount)
3761 }
3762 if acc.NumQueueSubscriptions != 1 || acc.TotalSubscriptions != 1 {
3763 return fmt.Errorf("mode=%v - Expected total subs to be 1, got %v - and num queue subs to be 1, got %v",
3764 pollMode, acc.TotalSubscriptions, acc.NumQueueSubscriptions)
3765 }
3766 }
3767 }
3768 return nil
3769 })
3770
3771 // Check inbound on server B
3772 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
3773 for pollMode := 0; pollMode < 2; pollMode++ {
3774 // Ask for accounts list
3775 g := pollGatewayz(t, sb, pollMode, gwURLServerB+"?accs=1", &GatewayzOptions{Accounts: true})
3776 igs := g.InboundGateways["A"]
3777 if igs == nil {
3778 return fmt.Errorf("mode=%v - Expected inbound gateway to A, got none", pollMode)
3779 }
3780 if len(igs) != 1 {
3781 return fmt.Errorf("mode=%v - Expected single inbound, got %v", pollMode, len(igs))
3782 }
3783 ig := igs[0]
3784 if ig.Connection == nil {
3785 return fmt.Errorf("mode=%v - Expected inbound connection from A to be set, wat not", pollMode)
3786 }
3787 if ig.Connection.Name != sa.ID() {
3788 t.Fatalf("mode=%v - Expected inbound connection from A to have name %q, got %q", pollMode, sa.ID(), ig.Connection.Name)
3789 }
3790 if n := len(ig.Accounts); n != totalAccounts {
3791 return fmt.Errorf("mode=%v - Expected to get all %d accounts, got %v", pollMode, totalAccounts, n)
3792 }
3793 // Now account details
3794 for _, acc := range ig.Accounts {
3795 if acc.InterestMode != Optimistic.String() {
3796 return fmt.Errorf("mode=%v - Expected optimistic mode, got %q", pollMode, acc.InterestMode)
3797 }
3798 if acc.NoInterestCount != 1 {
3799 return fmt.Errorf("mode=%v - Expected 1 no-interest, got %v", pollMode, acc.NoInterestCount)
3800 }
3801 // For inbound gateway, NumQueueSubscriptions and TotalSubscriptions
3802 // are not relevant.
3803 if acc.NumQueueSubscriptions != 0 || acc.TotalSubscriptions != 0 {
3804 return fmt.Errorf("mode=%v - For inbound connection, expected num queue subs and total subs to be 0, got %v and %v",
3805 pollMode, acc.TotalSubscriptions, acc.NumQueueSubscriptions)
3806 }
3807 }
3808 }
3809 return nil
3810 })
3811
3812 // Make one of the account to switch to interest only
3813 nc, err := nats.Connect(fmt.Sprintf("nats://user_1:pwd@%s:%d", oa.Host, oa.Port))
3814 if err != nil {
3815 t.Fatalf("Error on connect: %v", err)
3816 }
3817 defer nc.Close()
3818 for i := 0; i < 1100; i++ {
3819 nc.Publish(fmt.Sprintf("foo.%d", i), []byte("hello"))
3820 }
3821 nc.Flush()
3822 nc.Close()
3823
3824 // Check that we can select single account
3825 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
3826 for pollMode := 0; pollMode < 2; pollMode++ {
3827 g := pollGatewayz(t, sa, pollMode, gatewayzURL+"?gw_name=B&acc_name=acc_1", &GatewayzOptions{Name: "B", AccountName: "acc_1"})
3828 og := g.OutboundGateways["B"]
3829 if og == nil {
3830 return fmt.Errorf("mode=%v - Expected outbound gateway to B, got none", pollMode)
3831 }
3832 if n := len(og.Accounts); n != 1 {
3833 return fmt.Errorf("mode=%v - Expected to get 1 account, got %v", pollMode, n)
3834 }
3835 // Now account details
3836 acc := og.Accounts[0]
3837 if acc.InterestMode != InterestOnly.String() {
3838 return fmt.Errorf("mode=%v - Expected interest-only mode, got %q", pollMode, acc.InterestMode)
3839 }
3840 // Since we switched, this should be set to 0
3841 if acc.NoInterestCount != 0 {
3842 return fmt.Errorf("mode=%v - Expected 0 no-interest, got %v", pollMode, acc.NoInterestCount)
3843 }
3844 // We have created 3 subs on that account on B, and 1 queue sub.
3845 // So total should be 4 and 1 for queue sub.
3846 if acc.NumQueueSubscriptions != 1 {
3847 return fmt.Errorf("mode=%v - Expected num queue subs to be 1, got %v",
3848 pollMode, acc.NumQueueSubscriptions)
3849 }
3850 if acc.TotalSubscriptions != 4 {
3851 return fmt.Errorf("mode=%v - Expected total subs to be 4, got %v",
3852 pollMode, acc.TotalSubscriptions)
3853 }
3854 }
3855 return nil
3856 })
3857
3858 // Check inbound on B now...
3859 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
3860 for pollMode := 0; pollMode < 2; pollMode++ {
3861 g := pollGatewayz(t, sb, pollMode, gwURLServerB+"?gw_name=A&acc_name=acc_1", &GatewayzOptions{Name: "A", AccountName: "acc_1"})
3862 igs := g.InboundGateways["A"]
3863 if igs == nil {
3864 return fmt.Errorf("mode=%v - Expected inbound gateway from A, got none", pollMode)
3865 }
3866 if len(igs) != 1 {
3867 return fmt.Errorf("mode=%v - Expected single inbound, got %v", pollMode, len(igs))
3868 }
3869 ig := igs[0]
3870 if n := len(ig.Accounts); n != 1 {
3871 return fmt.Errorf("mode=%v - Expected to get 1 account, got %v", pollMode, n)
3872 }
3873 // Now account details
3874 acc := ig.Accounts[0]
3875 if acc.InterestMode != InterestOnly.String() {
3876 return fmt.Errorf("mode=%v - Expected interest-only mode, got %q", pollMode, acc.InterestMode)
3877 }
3878 if acc.InterestMode != InterestOnly.String() {
3879 return fmt.Errorf("Should be in %q mode, got %q", InterestOnly.String(), acc.InterestMode)
3880 }
3881 // Since we switched, this should be set to 0
3882 if acc.NoInterestCount != 0 {
3883 return fmt.Errorf("mode=%v - Expected 0 no-interest, got %v", pollMode, acc.NoInterestCount)
3884 }
3885 // Again, for inbound, these should be always 0.
3886 if acc.NumQueueSubscriptions != 0 || acc.TotalSubscriptions != 0 {
3887 return fmt.Errorf("mode=%v - For inbound connection, expected num queue subs and total subs to be 0, got %v and %v",
3888 pollMode, acc.TotalSubscriptions, acc.NumQueueSubscriptions)
3889 }
3890 }
3891 return nil
3892 })
3893 }
3894
3895 func TestMonitorGatewayzWithSubs(t *testing.T) {
3896 resetPreviousHTTPConnections()
3897
3898 ob := testDefaultOptionsForGateway("B")
3899 aA := NewAccount("A")
3900 aB := NewAccount("B")
3901 ob.Accounts = append(ob.Accounts, aA, aB)
3902 ob.Users = append(ob.Users,
3903 &User{Username: "a", Password: "a", Account: aA},
3904 &User{Username: "b", Password: "b", Account: aB})
3905 sb := runGatewayServer(ob)
3906 defer sb.Shutdown()
3907
3908 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
3909 oa.HTTPHost = "127.0.0.1"
3910 oa.HTTPPort = MONITOR_PORT
3911 aA = NewAccount("A")
3912 aB = NewAccount("B")
3913 oa.Accounts = append(oa.Accounts, aA, aB)
3914 oa.Users = append(oa.Users,
3915 &User{Username: "a", Password: "a", Account: aA},
3916 &User{Username: "b", Password: "b", Account: aB})
3917 sa := runGatewayServer(oa)
3918 defer sa.Shutdown()
3919
3920 waitForOutboundGateways(t, sa, 1, 2*time.Second)
3921 waitForInboundGateways(t, sa, 1, 2*time.Second)
3922
3923 waitForOutboundGateways(t, sb, 1, 2*time.Second)
3924 waitForInboundGateways(t, sb, 1, 2*time.Second)
3925
3926 ncA := natsConnect(t, sb.ClientURL(), nats.UserInfo("a", "a"))
3927 defer ncA.Close()
3928 natsSubSync(t, ncA, "foo")
3929 natsFlush(t, ncA)
3930
3931 ncB := natsConnect(t, sb.ClientURL(), nats.UserInfo("b", "b"))
3932 defer ncB.Close()
3933 natsSubSync(t, ncB, "foo")
3934 natsQueueSubSync(t, ncB, "bar", "baz")
3935 natsFlush(t, ncB)
3936
3937 checkGWInterestOnlyModeInterestOn(t, sa, "B", "A", "foo")
3938 checkGWInterestOnlyModeInterestOn(t, sa, "B", "B", "foo")
3939 checkForRegisteredQSubInterest(t, sa, "B", "B", "bar", 1, time.Second)
3940
3941 for _, test := range []struct {
3942 url string
3943 allAccs bool
3944 opts *GatewayzOptions
3945 }{
3946 {"accs=1&subs=1", true, &GatewayzOptions{Accounts: true, AccountSubscriptions: true}},
3947 {"accs=1&subs=detail", true, &GatewayzOptions{Accounts: true, AccountSubscriptionsDetail: true}},
3948 {"acc_name=B&subs=1", false, &GatewayzOptions{AccountName: "B", AccountSubscriptions: true}},
3949 {"acc_name=B&subs=detail", false, &GatewayzOptions{AccountName: "B", AccountSubscriptionsDetail: true}},
3950 } {
3951 t.Run(test.url, func(t *testing.T) {
3952 gatewayzURL := fmt.Sprintf("http://127.0.0.1:%d/gatewayz?%s", sa.MonitorAddr().Port, test.url)
3953 for pollMode := 0; pollMode < 2; pollMode++ {
3954 gw := pollGatewayz(t, sa, pollMode, gatewayzURL, test.opts)
3955 require_Equal(t, len(gw.OutboundGateways), 1)
3956 ogw, ok := gw.OutboundGateways["B"]
3957 require_True(t, ok)
3958 require_NotNil(t, ogw)
3959 var expected int
3960 if test.allAccs {
3961 expected = 3 // A + B + $G
3962 } else {
3963 expected = 1 // B
3964 }
3965 require_Len(t, len(ogw.Accounts), expected)
3966 accs := map[string]*AccountGatewayz{}
3967 for _, a := range ogw.Accounts {
3968 // Do not include the global account there.
3969 if a.Name == globalAccountName {
3970 continue
3971 }
3972 accs[a.Name] = a
3973 }
3974 // Update the expected number of accounts if we asked for all accounts.
3975 if test.allAccs {
3976 expected--
3977 }
3978 // The account B should always be present.
3979 _, ok = accs["B"]
3980 require_True(t, ok)
3981 if expected == 2 {
3982 _, ok = accs["A"]
3983 require_True(t, ok)
3984 }
3985 // Now that we know we have the proper account(s), check the content.
3986 for n, a := range accs {
3987 require_NotNil(t, a)
3988 require_Equal(t, a.Name, n)
3989 totalSubs := 1
3990 var numQueueSubs int
3991 if n == "B" {
3992 totalSubs++
3993 numQueueSubs = 1
3994 }
3995 require_Equal(t, a.TotalSubscriptions, totalSubs)
3996 require_Equal(t, a.NumQueueSubscriptions, numQueueSubs)
3997
3998 m := map[string]*SubDetail{}
3999 if test.opts.AccountSubscriptions {
4000 require_Len(t, len(a.Subs), totalSubs)
4001 require_Len(t, len(a.SubsDetail), 0)
4002 for _, sub := range a.Subs {
4003 m[sub] = nil
4004 }
4005 } else {
4006 require_Len(t, len(a.Subs), 0)
4007 require_Len(t, len(a.SubsDetail), totalSubs)
4008 for _, sub := range a.SubsDetail {
4009 m[sub.Subject] = &sub
4010 }
4011 }
4012 sd, ok := m["foo"]
4013 require_True(t, ok)
4014 if test.opts.AccountSubscriptionsDetail {
4015 require_NotNil(t, sd)
4016 require_Equal(t, sd.Queue, _EMPTY_)
4017 } else {
4018 require_True(t, sd == nil)
4019 }
4020 sd, ok = m["bar"]
4021 if numQueueSubs == 1 {
4022 require_True(t, ok)
4023 if test.opts.AccountSubscriptionsDetail {
4024 require_NotNil(t, sd)
4025 require_Equal(t, sd.Queue, "baz")
4026 } else {
4027 require_True(t, sd == nil)
4028 }
4029 } else {
4030 require_False(t, ok)
4031 }
4032 }
4033 }
4034 })
4035 }
4036 }
4037
4038 func TestMonitorRoutezRTT(t *testing.T) {
4039 // Do not change default PingInterval and expect RTT to still be reported
4040
4041 ob := DefaultOptions()
4042 sb := RunServer(ob)
4043 defer sb.Shutdown()
4044
4045 oa := DefaultOptions()
4046 oa.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", ob.Cluster.Host, ob.Cluster.Port))
4047 sa := RunServer(oa)
4048 defer sa.Shutdown()
4049
4050 checkClusterFormed(t, sa, sb)
4051
4052 checkRouteInfo := func(t *testing.T, s *Server) {
4053 t.Helper()
4054 routezURL := fmt.Sprintf("http://127.0.0.1:%d/routez", s.MonitorAddr().Port)
4055 for pollMode := 0; pollMode < 2; pollMode++ {
4056 checkFor(t, 2*firstPingInterval, 15*time.Millisecond, func() error {
4057 rz := pollRoutez(t, s, pollMode, routezURL, nil)
4058 // Pool size + 1 for system account
4059 if len(rz.Routes) != DEFAULT_ROUTE_POOL_SIZE+1 {
4060 return fmt.Errorf("Expected %d route, got %v", DEFAULT_ROUTE_POOL_SIZE+1, len(rz.Routes))
4061 }
4062 for _, ri := range rz.Routes {
4063 if ri.RTT == _EMPTY_ {
4064 return fmt.Errorf("Route's RTT not reported")
4065 }
4066 }
4067 return nil
4068 })
4069 }
4070 }
4071 checkRouteInfo(t, sa)
4072 checkRouteInfo(t, sb)
4073 }
4074
4075 func pollLeafz(t *testing.T, s *Server, mode int, url string, opts *LeafzOptions) *Leafz {
4076 t.Helper()
4077 if mode == 0 {
4078 l := &Leafz{}
4079 body := readBody(t, url)
4080 if err := json.Unmarshal(body, l); err != nil {
4081 t.Fatalf("Got an error unmarshalling the body: %v\n", err)
4082 }
4083 return l
4084 }
4085 l, err := s.Leafz(opts)
4086 if err != nil {
4087 t.Fatalf("Error on Leafz: %v", err)
4088 }
4089 return l
4090 }
4091
4092 func TestMonitorOpJWT(t *testing.T) {
4093 content := `
4094 listen: "127.0.0.1:-1"
4095 http: "127.0.0.1:-1"
4096 operator = "../test/configs/nkeys/op.jwt"
4097 resolver = MEMORY
4098 `
4099 conf := createConfFile(t, []byte(content))
4100 sa, _ := RunServerWithConfig(conf)
4101 defer sa.Shutdown()
4102
4103 theJWT, err := os.ReadFile("../test/configs/nkeys/op.jwt")
4104 require_NoError(t, err)
4105 theJWT = []byte(strings.Split(string(theJWT), "\n")[1])
4106 claim, err := jwt.DecodeOperatorClaims(string(theJWT))
4107 require_NoError(t, err)
4108
4109 pollURL := fmt.Sprintf("http://127.0.0.1:%d/varz", sa.MonitorAddr().Port)
4110 for pollMode := 1; pollMode < 2; pollMode++ {
4111 l := pollVarz(t, sa, pollMode, pollURL, nil)
4112
4113 if len(l.TrustedOperatorsJwt) != 1 {
4114 t.Fatalf("Expected one operator jwt")
4115 }
4116 if len(l.TrustedOperatorsClaim) != 1 {
4117 t.Fatalf("Expected one operator claim")
4118 }
4119 if l.TrustedOperatorsJwt[0] != string(theJWT) {
4120 t.Fatalf("Expected operator to be identical to configuration")
4121 }
4122 if !reflect.DeepEqual(l.TrustedOperatorsClaim[0], claim) {
4123 t.Fatal("claims need to be equal")
4124 }
4125 }
4126 }
4127
4128 func TestMonitorLeafz(t *testing.T) {
4129 content := `
4130 server_name: "hub"
4131 listen: "127.0.0.1:-1"
4132 http: "127.0.0.1:-1"
4133 operator = "../test/configs/nkeys/op.jwt"
4134 resolver = MEMORY
4135 ping_interval = 1
4136 leafnodes {
4137 listen: "127.0.0.1:-1"
4138 }
4139 `
4140 conf := createConfFile(t, []byte(content))
4141 sb, ob := RunServerWithConfig(conf)
4142 defer sb.Shutdown()
4143
4144 createAcc := func(t *testing.T) (*Account, string) {
4145 t.Helper()
4146 acc, akp := createAccount(sb)
4147 kp, _ := nkeys.CreateUser()
4148 pub, _ := kp.PublicKey()
4149 nuc := jwt.NewUserClaims(pub)
4150 ujwt, err := nuc.Encode(akp)
4151 if err != nil {
4152 t.Fatalf("Error generating user JWT: %v", err)
4153 }
4154 seed, _ := kp.Seed()
4155 creds := genCredsFile(t, ujwt, seed)
4156 return acc, creds
4157 }
4158 acc1, mycreds1 := createAcc(t)
4159 acc2, mycreds2 := createAcc(t)
4160 leafName := "my-leaf-node"
4161
4162 content = `
4163 port: -1
4164 http: "127.0.0.1:-1"
4165 ping_interval = 1
4166 server_name: %s
4167 accounts {
4168 %s {
4169 users [
4170 {user: user1, password: pwd}
4171 ]
4172 }
4173 %s {
4174 users [
4175 {user: user2, password: pwd}
4176 ]
4177 }
4178 }
4179 leafnodes {
4180 isolate_leafnode_interest: true
4181 remotes = [
4182 {
4183 account: "%s"
4184 url: nats-leaf://127.0.0.1:%d
4185 credentials: '%s'
4186 }
4187 {
4188 account: "%s"
4189 url: nats-leaf://127.0.0.1:%d
4190 credentials: '%s'
4191 }
4192 ]
4193 }
4194 `
4195 config := fmt.Sprintf(content,
4196 leafName,
4197 acc1.Name, acc2.Name,
4198 acc1.Name, ob.LeafNode.Port, mycreds1,
4199 acc2.Name, ob.LeafNode.Port, mycreds2)
4200 conf = createConfFile(t, []byte(config))
4201 sa, oa := RunServerWithConfig(conf)
4202 defer sa.Shutdown()
4203
4204 checkFor(t, time.Second, 15*time.Millisecond, func() error {
4205 if n := sa.NumLeafNodes(); n != 2 {
4206 return fmt.Errorf("Expected 2 leaf connections, got %v", n)
4207 }
4208 return nil
4209 })
4210
4211 // Wait for initial RTT to be computed
4212 time.Sleep(firstPingInterval + 500*time.Millisecond)
4213
4214 ch := make(chan bool, 1)
4215 nc1B := natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", ob.Port), nats.UserCredentials(mycreds1))
4216 defer nc1B.Close()
4217 natsSub(t, nc1B, "foo", func(_ *nats.Msg) { ch <- true })
4218 natsSub(t, nc1B, "bar", func(_ *nats.Msg) {})
4219 natsFlush(t, nc1B)
4220
4221 nc2B := natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", ob.Port), nats.UserCredentials(mycreds2))
4222 defer nc2B.Close()
4223 natsSub(t, nc2B, "bar", func(_ *nats.Msg) { ch <- true })
4224 natsSub(t, nc2B, "foo", func(_ *nats.Msg) {})
4225 natsFlush(t, nc2B)
4226
4227 checkSubInterest(t, sa, acc1.GetName(), "foo", time.Second)
4228 checkSubInterest(t, sa, acc2.GetName(), "bar", time.Second)
4229
4230 nc1A := natsConnect(t, fmt.Sprintf("nats://user1:[email protected]:%d", oa.Port))
4231 defer nc1A.Close()
4232 natsPub(t, nc1A, "foo", []byte("hello"))
4233 natsFlush(t, nc1A)
4234
4235 waitCh(t, ch, "Did not get the message")
4236
4237 nc2A := natsConnect(t, fmt.Sprintf("nats://user2:[email protected]:%d", oa.Port))
4238 defer nc2A.Close()
4239 natsPub(t, nc2A, "bar", []byte("hello"))
4240 natsPub(t, nc2A, "bar", []byte("hello"))
4241 natsFlush(t, nc2A)
4242
4243 waitCh(t, ch, "Did not get the message")
4244 waitCh(t, ch, "Did not get the message")
4245
4246 // Let's poll server A
4247 pollURL := fmt.Sprintf("http://127.0.0.1:%d/leafz?subs=1", sa.MonitorAddr().Port)
4248 for pollMode := 1; pollMode < 2; pollMode++ {
4249 l := pollLeafz(t, sa, pollMode, pollURL, &LeafzOptions{Subscriptions: true})
4250 if l.ID != sa.ID() {
4251 t.Fatalf("Expected ID to be %q, got %q", sa.ID(), l.ID)
4252 }
4253 if l.Now.IsZero() {
4254 t.Fatalf("Expected Now to be set, was not")
4255 }
4256 if l.NumLeafs != 2 {
4257 t.Fatalf("Expected NumLeafs to be 2, got %v", l.NumLeafs)
4258 }
4259 if len(l.Leafs) != 2 {
4260 t.Fatalf("Expected array to be len 2, got %v", len(l.Leafs))
4261 }
4262 for _, ln := range l.Leafs {
4263 if ln.Account == acc1.Name {
4264 if ln.OutMsgs != 1 || ln.OutBytes == 0 || ln.InMsgs != 0 || ln.InBytes != 0 {
4265 t.Fatalf("Expected 1 OutMsgs/Bytes and 0 InMsgs/Bytes, got %+v", ln)
4266 }
4267 } else if ln.Account == acc2.Name {
4268 if ln.OutMsgs != 2 || ln.OutBytes == 0 || ln.InMsgs != 0 || ln.InBytes != 0 {
4269 t.Fatalf("Expected 2 OutMsgs/Bytes and 0 InMsgs/Bytes, got %+v", ln)
4270 }
4271 } else {
4272 t.Fatalf("Expected account to be %q or %q, got %q", acc1.Name, acc2.Name, ln.Account)
4273 }
4274 if ln.Name != "hub" {
4275 t.Fatalf("Expected name to be %q, got %q", "hub", ln.Name)
4276 }
4277 if !ln.IsSpoke {
4278 t.Fatal("Expected leafnode connection to be spoke")
4279 }
4280 if !ln.IsIsolated {
4281 t.Fatal("Expected leafnode connection to be isolated")
4282 }
4283 if ln.RTT == "" {
4284 t.Fatalf("RTT not tracked?")
4285 }
4286 if ln.NumSubs != 3 {
4287 t.Fatalf("Expected 3 subs, got %v", ln.NumSubs)
4288 }
4289 if len(ln.Subs) != 3 {
4290 t.Fatalf("Expected subs to be returned, got %v", len(ln.Subs))
4291 }
4292 var foundFoo bool
4293 var foundBar bool
4294 for _, sub := range ln.Subs {
4295 if sub == "foo" {
4296 foundFoo = true
4297 } else if sub == "bar" {
4298 foundBar = true
4299 }
4300 }
4301 if !foundFoo {
4302 t.Fatal("Did not find subject foo")
4303 }
4304 if !foundBar {
4305 t.Fatal("Did not find subject bar")
4306 }
4307 }
4308 }
4309 // Make sure that if we don't ask for subs, we don't get them
4310 pollURL = fmt.Sprintf("http://127.0.0.1:%d/leafz", sa.MonitorAddr().Port)
4311 for pollMode := 1; pollMode < 2; pollMode++ {
4312 l := pollLeafz(t, sa, pollMode, pollURL, nil)
4313 for _, ln := range l.Leafs {
4314 if ln.NumSubs != 3 {
4315 t.Fatalf("Number of subs should be 3, got %v", ln.NumSubs)
4316 }
4317 if len(ln.Subs) != 0 {
4318 t.Fatalf("Subs should not have been returned, got %v", ln.Subs)
4319 }
4320 }
4321 }
4322 // Make sure that we can request per account - existing account
4323 pollURL = fmt.Sprintf("http://127.0.0.1:%d/leafz?acc=%s", sa.MonitorAddr().Port, acc1.Name)
4324 for pollMode := 1; pollMode < 2; pollMode++ {
4325 l := pollLeafz(t, sa, pollMode, pollURL, &LeafzOptions{Account: acc1.Name})
4326 for _, ln := range l.Leafs {
4327 if ln.Account != acc1.Name {
4328 t.Fatalf("Expected leaf node to be from account %s, got: %v", acc1.Name, ln)
4329 }
4330 }
4331 if len(l.Leafs) != 1 {
4332 t.Fatalf("Expected only two leaf node for this account, got: %v", len(l.Leafs))
4333 }
4334 }
4335 // Make sure that we can request per account - non existing account
4336 pollURL = fmt.Sprintf("http://127.0.0.1:%d/leafz?acc=%s", sa.MonitorAddr().Port, "DOESNOTEXIST")
4337 for pollMode := 1; pollMode < 2; pollMode++ {
4338 l := pollLeafz(t, sa, pollMode, pollURL, &LeafzOptions{Account: "DOESNOTEXIST"})
4339 if len(l.Leafs) != 0 {
4340 t.Fatalf("Expected no leaf node for this account, got: %v", len(l.Leafs))
4341 }
4342 }
4343 // Now polling server B.
4344 pollURL = fmt.Sprintf("http://127.0.0.1:%d/leafz?subs=1", sb.MonitorAddr().Port)
4345 for pollMode := 1; pollMode < 2; pollMode++ {
4346 l := pollLeafz(t, sb, pollMode, pollURL, &LeafzOptions{Subscriptions: true})
4347 if l.ID != sb.ID() {
4348 t.Fatalf("Expected ID to be %q, got %q", sb.ID(), l.ID)
4349 }
4350 if l.Now.IsZero() {
4351 t.Fatalf("Expected Now to be set, was not")
4352 }
4353 if l.NumLeafs != 2 {
4354 t.Fatalf("Expected NumLeafs to be 1, got %v", l.NumLeafs)
4355 }
4356 if len(l.Leafs) != 2 {
4357 t.Fatalf("Expected array to be len 2, got %v", len(l.Leafs))
4358 }
4359 for _, ln := range l.Leafs {
4360 if ln.Account == acc1.Name {
4361 if ln.OutMsgs != 0 || ln.OutBytes != 0 || ln.InMsgs != 1 || ln.InBytes == 0 {
4362 t.Fatalf("Expected 1 InMsgs/Bytes and 0 OutMsgs/Bytes, got %+v", ln)
4363 }
4364 } else if ln.Account == acc2.Name {
4365 if ln.OutMsgs != 0 || ln.OutBytes != 0 || ln.InMsgs != 2 || ln.InBytes == 0 {
4366 t.Fatalf("Expected 2 InMsgs/Bytes and 0 OutMsgs/Bytes, got %+v", ln)
4367 }
4368 } else {
4369 t.Fatalf("Expected account to be %q or %q, got %q", acc1.Name, acc2.Name, ln.Account)
4370 }
4371 if ln.Name != leafName {
4372 t.Fatalf("Expected name to be %q, got %q", leafName, ln.Name)
4373 }
4374 if ln.IsSpoke {
4375 t.Fatal("Expected leafnode connection to be hub")
4376 }
4377 if ln.RTT == "" {
4378 t.Fatalf("RTT not tracked?")
4379 }
4380 // LDS should be only one.
4381 if ln.NumSubs != 5 || len(ln.Subs) != 5 {
4382 t.Fatalf("Expected 5 subs, got %v (%v)", ln.NumSubs, ln.Subs)
4383 }
4384 }
4385 }
4386 }
4387
4388 func pollAccountz(t *testing.T, s *Server, mode int, url string, opts *AccountzOptions) *Accountz {
4389 t.Helper()
4390 if mode == 0 {
4391 body := readBody(t, url)
4392 a := &Accountz{}
4393 if err := json.Unmarshal(body, a); err != nil {
4394 t.Fatalf("Got an error unmarshalling the body: %v\n", err)
4395 }
4396 return a
4397 }
4398 a, err := s.Accountz(opts)
4399 if err != nil {
4400 t.Fatalf("Error on Accountz(): %v", err)
4401 }
4402 return a
4403 }
4404
4405 func pollAccountStatz(t *testing.T, s *Server, mode int, url string, opts *AccountStatzOptions) *AccountStatz {
4406 t.Helper()
4407 if mode == 0 {
4408 body := readBody(t, url)
4409 as := &AccountStatz{}
4410 if err := json.Unmarshal(body, as); err != nil {
4411 t.Fatalf("Got an error unmarshalling the body: %v\n", err)
4412 }
4413 return as
4414 }
4415 as, err := s.AccountStatz(opts)
4416 if err != nil {
4417 t.Fatalf("Error on AccountStatz(): %v", err)
4418 }
4419 return as
4420 }
4421
4422 func TestMonitorAccountz(t *testing.T) {
4423 s := RunServer(DefaultMonitorOptions())
4424 defer s.Shutdown()
4425
4426 for pollMode := 0; pollMode < 2; pollMode++ {
4427 a := pollAccountz(t, s, pollMode, fmt.Sprintf("http://127.0.0.1:%d%s", s.MonitorAddr().Port, AccountzPath), nil)
4428
4429 require_Equal(t, a.ID, s.ID())
4430 require_Equal(t, len(a.Accounts), 2)
4431 for _, acc := range a.Accounts {
4432 switch acc {
4433 case DEFAULT_SYSTEM_ACCOUNT, DEFAULT_GLOBAL_ACCOUNT:
4434 default:
4435 t.Fatalf("Unexpected account: %s", acc)
4436 }
4437 }
4438 require_Equal(t, a.SystemAccount, DEFAULT_SYSTEM_ACCOUNT)
4439 }
4440
4441 for pollMode := 0; pollMode < 2; pollMode++ {
4442 a := pollAccountz(t, s, pollMode, fmt.Sprintf("http://127.0.0.1:%d%s?acc=$SYS", s.MonitorAddr().Port, AccountzPath), &AccountzOptions{Account: DEFAULT_SYSTEM_ACCOUNT})
4443
4444 require_NotNil(t, a.Account)
4445 require_Equal(t, a.Account.AccountName, DEFAULT_SYSTEM_ACCOUNT)
4446 require_Equal(t, a.Account.NameTag, DEFAULT_SYSTEM_ACCOUNT)
4447 require_True(t, a.Account.IsSystem)
4448 require_Equal(t, a.SystemAccount, DEFAULT_SYSTEM_ACCOUNT)
4449 }
4450 }
4451
4452 func TestMonitorAccountStatz(t *testing.T) {
4453 s := RunServer(DefaultMonitorOptions())
4454 defer s.Shutdown()
4455
4456 for pollMode := 0; pollMode < 2; pollMode++ {
4457 a := pollAccountStatz(t, s, pollMode, fmt.Sprintf("http://127.0.0.1:%d%s?unused=1", s.MonitorAddr().Port, AccountStatzPath), &AccountStatzOptions{IncludeUnused: true})
4458
4459 require_Equal(t, a.ID, s.ID())
4460 require_Equal(t, len(a.Accounts), 2)
4461
4462 // Check accounts.
4463 for _, acc := range a.Accounts {
4464 switch acc.Account {
4465 case DEFAULT_GLOBAL_ACCOUNT:
4466 require_Equal(t, acc.Name, DEFAULT_GLOBAL_ACCOUNT)
4467 require_Equal(t, acc.Conns, 0)
4468 case DEFAULT_SYSTEM_ACCOUNT:
4469 require_Equal(t, acc.Name, DEFAULT_SYSTEM_ACCOUNT)
4470 require_Equal(t, acc.Conns, 0)
4471 default:
4472 t.Fatalf("Unexpected account: %+v", acc)
4473 }
4474 }
4475 }
4476 }
4477
4478 // https://github.com/nats-io/nats-server/issues/8251
4479 func TestMonitorAccountStatzLeafNodes(t *testing.T) {
4480 hubConf := createConfFile(t, []byte(`
4481 server_name: "hub"
4482 listen: "127.0.0.1:-1"
4483 http: "127.0.0.1:-1"
4484 accounts {
4485 LEAF_ACC { users [{user: leaf, password: pwd}] }
4486 CLIENT_ACC { users [{user: client, password: pwd}] }
4487 }
4488 leafnodes {
4489 listen: "127.0.0.1:-1"
4490 }
4491 `))
4492 hub, hubOpts := RunServerWithConfig(hubConf)
4493 defer hub.Shutdown()
4494
4495 leafConf := createConfFile(t, []byte(fmt.Sprintf(`
4496 server_name: "leaf"
4497 listen: "127.0.0.1:-1"
4498 leafnodes {
4499 remotes = [
4500 {url: "nats-leaf://leaf:[email protected]:%d"}
4501 ]
4502 }
4503 `, hubOpts.LeafNode.Port)))
4504 leaf, _ := RunServerWithConfig(leafConf)
4505 defer leaf.Shutdown()
4506
4507 checkLeafNodeConnected(t, hub)
4508
4509 // Connect a client to CLIENT_ACC, it will show up in the reporting.
4510 nc := natsConnect(t, hub.ClientURL(), nats.UserInfo("client", "pwd"))
4511 defer nc.Close()
4512
4513 checkAccounts := func(t *testing.T, stz *AccountStatz) {
4514 t.Helper()
4515 accounts := make(map[string]*AccountStat, len(stz.Accounts))
4516 for _, acc := range stz.Accounts {
4517 accounts[acc.Account] = acc
4518 }
4519
4520 // The account with only a leaf node connection should be reported.
4521 leafAcc, ok := accounts["LEAF_ACC"]
4522 if !ok {
4523 t.Fatalf("Expected account LEAF_ACC to be present, got %+v", stz.Accounts)
4524 }
4525 require_Equal(t, leafAcc.Conns, 0)
4526 require_Equal(t, leafAcc.LeafNodes, 1)
4527 require_Equal(t, leafAcc.TotalConns, 1)
4528
4529 // The account with a client connection should be reported.
4530 clientAcc, ok := accounts["CLIENT_ACC"]
4531 if !ok {
4532 t.Fatalf("Expected account CLIENT_ACC to be present, got %+v", stz.Accounts)
4533 }
4534 require_Equal(t, clientAcc.Conns, 1)
4535 require_Equal(t, clientAcc.LeafNodes, 0)
4536 require_Equal(t, clientAcc.TotalConns, 1)
4537
4538 // Unused accounts should still be excluded.
4539 if _, ok := accounts[DEFAULT_GLOBAL_ACCOUNT]; ok {
4540 t.Fatalf("Did not expect unused account %q to be present, got %+v", DEFAULT_GLOBAL_ACCOUNT, stz.Accounts)
4541 }
4542 }
4543
4544 // Check without unused=true and without account filtering.
4545 for pollMode := 0; pollMode < 2; pollMode++ {
4546 stz := pollAccountStatz(t, hub, pollMode, fmt.Sprintf("http://127.0.0.1:%d%s", hub.MonitorAddr().Port, AccountStatzPath), &AccountStatzOptions{})
4547 checkAccounts(t, stz)
4548 }
4549
4550 // Check with explicit account filtering. Only available through AccountStatz() directly.
4551 stz, err := hub.AccountStatz(&AccountStatzOptions{Accounts: []string{"LEAF_ACC", "CLIENT_ACC", DEFAULT_GLOBAL_ACCOUNT}})
4552 require_NoError(t, err)
4553 checkAccounts(t, stz)
4554 }
4555
4556 func runMonitorServerWithOperator(t *testing.T, sysName, accName string) ([]*Server, nkeys.KeyPair, nkeys.KeyPair) {
4557 t.Helper()
4558
4559 resetPreviousHTTPConnections()
4560
4561 sysKp, sysPub := createKey(t)
4562 sysClaim := jwt.NewAccountClaims(sysPub)
4563 sysClaim.Name = sysName
4564 sysJwt := encodeClaim(t, sysClaim, sysPub)
4565
4566 accKp, accPub := createKey(t)
4567 accClaim := jwt.NewAccountClaims(accPub)
4568 accClaim.Name = accName
4569 accClaim.Limits.JetStreamLimits.DiskStorage = -1
4570 accClaim.Limits.JetStreamLimits.MemoryStorage = -1
4571
4572 accJwt := encodeClaim(t, accClaim, accPub)
4573
4574 var servers []*Server
4575
4576 // Main cluster
4577 for i, test := range []struct {
4578 port int
4579 mport int
4580 cport int
4581 route1 int
4582 gport int
4583 gateway1 int
4584 lport int
4585 }{
4586 {7500, 7501, 7502, 5502, 8500, 8503, 7433},
4587 {5500, 5501, 5502, 7502, 8501, 8503, 7434},
4588 {6050, 6051, 6052, 7502, 8502, 8503, 7435},
4589 } {
4590 dir := t.TempDir()
4591 conf := createConfFile(t, []byte(fmt.Sprintf(`
4592 listen: 127.0.0.1:%d
4593 http: 127.0.0.1:%d
4594 jetstream: {
4595 max_mem_store: 10Mb
4596 max_file_store: 10Mb
4597 store_dir: '%s'
4598 }
4599 cluster {
4600 name: c1
4601 listen: %d
4602 routes: [
4603 nats-route://127.0.0.1:%d,
4604 ]
4605 }
4606 gateway {
4607 name: c1
4608 port: %d
4609 gateways: [
4610 {name: c2, urls: [nats://127.0.0.1:%d]},
4611 ]
4612 }
4613 leafnodes {
4614 listen: %d
4615 }
4616 server_name: %s
4617 operator: %s
4618 resolver: MEMORY
4619 system_account: %s
4620 resolver_preload {
4621 %s : %s
4622 %s : %s
4623 }
4624 `, test.port, test.mport, dir, test.cport, test.route1, test.gport, test.gateway1, test.lport, fmt.Sprintf("n%d", i), ojwt, sysPub, accPub, accJwt, sysPub, sysJwt)))
4625
4626 s, _ := RunServerWithConfig(conf)
4627 servers = append(servers, s)
4628 }
4629
4630 // Gateway
4631 for i, test := range []struct {
4632 port int
4633 mport int
4634 cport int
4635 gport int
4636 gateway1 int
4637 }{
4638 {7503, 7504, 6053, 8503, 8500},
4639 } {
4640 conf := createConfFile(t, []byte(fmt.Sprintf(`
4641 listen: 127.0.0.1:%d
4642 http: 127.0.0.1:%d
4643 cluster {
4644 name: c2
4645 listen: %d
4646 }
4647 gateway {
4648 name: c2
4649 port: %d
4650 gateways: [
4651 {name: c1, urls: [nats://127.0.0.1:%d]},
4652 ]
4653 }
4654 server_name: %s
4655 operator: %s
4656 resolver: MEMORY
4657 system_account: %s
4658 resolver_preload {
4659 %s : %s
4660 %s : %s
4661 }
4662 `, test.port, test.mport, test.cport, test.gport, test.gateway1, fmt.Sprintf("n%d", i+3), ojwt, sysPub, accPub, accJwt, sysPub, sysJwt)))
4663
4664 s, _ := RunServerWithConfig(conf)
4665 servers = append(servers, s)
4666 }
4667
4668 _, credsFile := createUser(t, accKp)
4669
4670 // Leafnode
4671 for _, test := range []struct {
4672 port int
4673 mport int
4674 lport int
4675 }{
4676 {7505, 7506, 7433},
4677 } {
4678 conf := createConfFile(t, []byte(fmt.Sprintf(`
4679 listen: 127.0.0.1:%d
4680 http: 127.0.0.1:%d
4681 leafnodes: {
4682 remotes: [
4683 {url: "nats://127.0.0.1:%d", credentials: "%s", account: "APP"},
4684 ]
4685 }
4686 accounts {
4687 SYS: {
4688 users: [
4689 {user: "sys", password: "sys"},
4690 ]
4691 }
4692 APP: {
4693 users: [
4694 {user: "app", password: "app"},
4695 ]
4696 }
4697 }
4698 no_auth_user: "app"
4699 `, test.port, test.mport, test.lport, credsFile)))
4700
4701 s, _ := RunServerWithConfig(conf)
4702 servers = append(servers, s)
4703 }
4704
4705 checkForJSClusterUp(t, servers[:3]...)
4706 waitForOutboundGateways(t, servers[0], 1, 2*time.Second)
4707 waitForOutboundGateways(t, servers[3], 1, 2*time.Second)
4708
4709 return servers, sysKp, accKp
4710 }
4711
4712 func createUser(t *testing.T, accKp nkeys.KeyPair) (string, string) {
4713 t.Helper()
4714
4715 ukp, _ := nkeys.CreateUser()
4716 seed, _ := ukp.Seed()
4717 upub, _ := ukp.PublicKey()
4718 uclaim := newJWTTestUserClaims()
4719 uclaim.Subject = upub
4720 ujwt, err := uclaim.Encode(accKp)
4721 require_NoError(t, err)
4722 return upub, genCredsFile(t, ujwt, seed)
4723 }
4724
4725 func TestMonitorAccountzOperatorMode(t *testing.T) {
4726 sysName := "SYS"
4727 accName := "APP"
4728
4729 srvs, sysKp, accKp := runMonitorServerWithOperator(t, sysName, accName)
4730 for _, s := range srvs {
4731 defer s.Shutdown()
4732 }
4733 s := srvs[0]
4734
4735 sysPub, _ := sysKp.PublicKey()
4736 accPub, _ := accKp.PublicKey()
4737
4738 _, aCreds := createUser(t, accKp)
4739
4740 nc, err := nats.Connect(s.ClientURL(), nats.UserCredentials(aCreds))
4741 require_NoError(t, err)
4742 defer nc.Close()
4743
4744 for pollMode := 0; pollMode < 2; pollMode++ {
4745 a := pollAccountz(t, s, pollMode, fmt.Sprintf("http://127.0.0.1:%d%s", s.MonitorAddr().Port, AccountzPath), nil)
4746
4747 require_Equal(t, a.ID, s.ID())
4748 require_Equal(t, len(a.Accounts), 3)
4749 for _, acc := range a.Accounts {
4750 switch acc {
4751 case sysPub, accPub, DEFAULT_GLOBAL_ACCOUNT:
4752 default:
4753 t.Fatalf("Unexpected account: %s", acc)
4754 }
4755 }
4756 require_Equal(t, a.SystemAccount, sysPub)
4757 }
4758
4759 for pollMode := 0; pollMode < 2; pollMode++ {
4760 a := pollAccountz(t, s, pollMode, fmt.Sprintf("http://127.0.0.1:%d%s?acc=%s", s.MonitorAddr().Port, AccountzPath, sysPub), &AccountzOptions{Account: sysPub})
4761
4762 require_NotNil(t, a.Account)
4763 require_Equal(t, a.Account.AccountName, sysPub)
4764 require_Equal(t, a.Account.NameTag, sysName)
4765 require_True(t, a.Account.IsSystem)
4766 require_Equal(t, a.SystemAccount, sysPub)
4767 }
4768
4769 }
4770
4771 func TestMonitorAccountStatzOperatorMode(t *testing.T) {
4772 sysName := "SYS"
4773 accName := "APP"
4774
4775 srvs, sysKp, accKp := runMonitorServerWithOperator(t, sysName, accName)
4776 for _, s := range srvs {
4777 defer s.Shutdown()
4778 }
4779 s := srvs[0]
4780
4781 sysPub, _ := sysKp.PublicKey()
4782 accPub, _ := accKp.PublicKey()
4783
4784 _, aCreds := createUser(t, accKp)
4785
4786 nc, err := nats.Connect(s.ClientURL(), nats.UserCredentials(aCreds))
4787 require_NoError(t, err)
4788 defer nc.Close()
4789
4790 for pollMode := 0; pollMode < 2; pollMode++ {
4791 a := pollAccountStatz(t, s, pollMode, fmt.Sprintf("http://127.0.0.1:%d%s?unused=1", s.MonitorAddr().Port, AccountStatzPath), &AccountStatzOptions{IncludeUnused: true})
4792
4793 require_Equal(t, a.ID, s.ID())
4794 require_Equal(t, len(a.Accounts), 3)
4795
4796 // Check accounts.
4797 for _, acc := range a.Accounts {
4798 switch acc.Account {
4799 case accPub:
4800 require_Equal(t, acc.Name, accName)
4801 require_True(t, acc.NumSubs > 0)
4802 require_Equal(t, acc.Conns, 1)
4803 case sysPub:
4804 require_Equal(t, acc.Name, sysName)
4805 require_Equal(t, acc.Conns, 0)
4806 case DEFAULT_GLOBAL_ACCOUNT:
4807 require_Equal(t, acc.Name, DEFAULT_GLOBAL_ACCOUNT)
4808 default:
4809 t.Fatalf("Unexpected account: %+v", acc)
4810 }
4811 }
4812 }
4813 }
4814
4815 func TestMonitorAccountStatzDataStatsOperatorMode(t *testing.T) {
4816 sysName := "SYS"
4817 accName := "APP"
4818
4819 srvs, _, accKp := runMonitorServerWithOperator(t, sysName, accName)
4820 for _, s := range srvs {
4821 defer s.Shutdown()
4822 }
4823 // First three servers are the cluster.
4824 n0 := srvs[0]
4825 n1 := srvs[1]
4826
4827 // Gateway server.
4828 n3 := srvs[3]
4829
4830 // Leafnode server.
4831 n4 := srvs[4]
4832
4833 accPub, _ := accKp.PublicKey()
4834
4835 _, aCreds := createUser(t, accKp)
4836
4837 n0c, err := nats.Connect(n0.ClientURL(), nats.UserCredentials(aCreds))
4838 require_NoError(t, err)
4839 defer n0c.Close()
4840
4841 n1c, err := nats.Connect(n1.ClientURL(), nats.UserCredentials(aCreds))
4842 require_NoError(t, err)
4843 defer n1c.Close()
4844
4845 n3c, err := nats.Connect(n3.ClientURL(), nats.UserCredentials(aCreds))
4846 require_NoError(t, err)
4847 defer n3c.Close()
4848
4849 // No auth user for leafnode.
4850 n4c, err := nats.Connect(n4.ClientURL())
4851 require_NoError(t, err)
4852 defer n4c.Close()
4853
4854 // Subscription over a route.
4855 _, err = n1c.Subscribe("foo", func(m *nats.Msg) {})
4856 require_NoError(t, err)
4857
4858 // Subscription over a gateway.
4859 _, err = n3c.Subscribe("bar", func(m *nats.Msg) {})
4860 require_NoError(t, err)
4861
4862 // Subscription over a leafnode.
4863 _, err = n4c.Subscribe("baz", func(m *nats.Msg) {})
4864 require_NoError(t, err)
4865
4866 // Subscription propagation.
4867 time.Sleep(10 * time.Millisecond)
4868
4869 err = n0c.Publish("foo", []byte("Hello"))
4870 require_NoError(t, err)
4871
4872 err = n0c.Publish("bar", []byte("Hello"))
4873 require_NoError(t, err)
4874
4875 err = n0c.Publish("baz", []byte("Hello"))
4876 require_NoError(t, err)
4877
4878 // Publish propagation.
4879 time.Sleep(10 * time.Millisecond)
4880
4881 for pollMode := 0; pollMode < 2; pollMode++ {
4882 for _, s := range srvs {
4883 a := pollAccountStatz(t, s, pollMode, fmt.Sprintf("http://127.0.0.1:%d%s?unused=1", s.MonitorAddr().Port, AccountStatzPath), &AccountStatzOptions{IncludeUnused: true})
4884
4885 for _, acc := range a.Accounts {
4886 if acc.Account != accPub {
4887 continue
4888 }
4889
4890 switch s.Name() {
4891 case "n0":
4892 // Should have received three messages due to the three publishes.
4893 // Should have sent one over a route to n1 for foo.
4894 // Should have sent one over a gateway to n3 for bar.
4895 // Should have sent one over a leaf node to n4 for baz.
4896 require_Equal(t, acc.Sent.Msgs, 3)
4897 require_Equal(t, acc.Sent.Routes.Msgs, 1)
4898 require_Equal(t, acc.Sent.Gateways.Msgs, 1)
4899 require_Equal(t, acc.Sent.Leafs.Msgs, 1)
4900 require_Equal(t, acc.Received.Msgs, 3)
4901 case "n1":
4902 // Should have sent 1 message to a client.
4903 // Should have received 1 message from n0.
4904 require_Equal(t, acc.Sent.Msgs, 1)
4905 require_Equal(t, acc.Sent.Routes.Msgs, 0)
4906 require_Equal(t, acc.Received.Msgs, 1)
4907 require_Equal(t, acc.Received.Routes.Msgs, 1)
4908 case "n2":
4909 // Should have not received anything.
4910 require_Equal(t, acc.Sent.Msgs, 0)
4911 require_Equal(t, acc.Sent.Bytes, 0)
4912 // Gateway, connected to n0
4913 case "n3":
4914 // Should have received 1 message from n0.
4915 // Should have sent 1 message to a client.
4916 require_Equal(t, acc.Sent.Msgs, 1)
4917 require_Equal(t, acc.Sent.Gateways.Msgs, 0)
4918 require_Equal(t, acc.Received.Msgs, 1)
4919 require_Equal(t, acc.Received.Gateways.Msgs, 1)
4920 // Leafnode, connected to n0
4921 case "n4":
4922 // Should have received 1 message from n0.
4923 // Should have sent 1 message to a client.
4924 require_Equal(t, acc.Sent.Msgs, 1)
4925 require_Equal(t, acc.Received.Msgs, 1)
4926 require_Equal(t, acc.Received.Leafs.Msgs, 1)
4927 }
4928 }
4929 }
4930 }
4931 }
4932
4933 func TestMonitorAccountzAccountIssuerUpdate(t *testing.T) {
4934 // create an operator set of keys
4935 okp, err := nkeys.CreateOperator()
4936 require_NoError(t, err)
4937 opk, err := okp.PublicKey()
4938 require_NoError(t, err)
4939
4940 // create the system account
4941 _, sysPK := createKey(t)
4942 sysAc := jwt.NewAccountClaims(sysPK)
4943 sysAc.Name = "SYS"
4944 sysJwt, err := sysAc.Encode(okp)
4945 require_NoError(t, err)
4946
4947 // create the operator with the system
4948 oc := jwt.NewOperatorClaims(opk)
4949 oc.Name = "O"
4950 // add a signing keys
4951 osk1, err := nkeys.CreateOperator()
4952 require_NoError(t, err)
4953 opk1, err := osk1.PublicKey()
4954 require_NoError(t, err)
4955 // add a second signing key
4956 osk2, err := nkeys.CreateOperator()
4957 require_NoError(t, err)
4958 opk2, err := osk2.PublicKey()
4959 require_NoError(t, err)
4960 oc.SigningKeys.Add(opk1, opk2)
4961 // set the system account
4962 oc.SystemAccount = sysPK
4963 // generate
4964 oJWT, err := oc.Encode(okp)
4965 require_NoError(t, err)
4966
4967 // create an account
4968 akp, apk := createKey(t)
4969 ac := jwt.NewAccountClaims(apk)
4970 ac.Name = "A"
4971 // sign with the signing key
4972 aJWT, err := ac.Encode(osk1)
4973 require_NoError(t, err)
4974
4975 // build the mem-resolver
4976 conf := createConfFile(t, []byte(fmt.Sprintf(`
4977 listen: 127.0.0.1:-1
4978 http: 127.0.0.1:-1
4979 operator = %s
4980 resolver = MEMORY
4981 system_account: %s
4982 resolver_preload = {
4983 %s : %s
4984 %s : %s
4985 }
4986 `, oJWT, sysPK, sysPK, sysJwt, apk, aJWT)))
4987
4988 // start the server
4989 s, _ := RunServerWithConfig(conf)
4990 defer s.Shutdown()
4991
4992 // create an user for account A, or we don't see
4993 // the account in accountsz
4994 createUser := func() (string, string) {
4995 ukp, _ := nkeys.CreateUser()
4996 seed, _ := ukp.Seed()
4997 upub, _ := ukp.PublicKey()
4998 uclaim := newJWTTestUserClaims()
4999 uclaim.Subject = upub
5000 ujwt, err := uclaim.Encode(akp)
5001 require_NoError(t, err)
5002 return upub, genCredsFile(t, ujwt, seed)
5003 }
5004
5005 _, aCreds := createUser()
5006 // connect the user
5007 nc, err := nats.Connect(s.ClientURL(), nats.UserCredentials(aCreds))
5008 require_NoError(t, err)
5009 defer nc.Close()
5010
5011 // lookup the account
5012 data := readBody(t, fmt.Sprintf("http://127.0.0.1:%d%s?acc=%s", s.MonitorAddr().Port, AccountzPath, apk))
5013 var ci Accountz
5014 require_NoError(t, json.Unmarshal(data, &ci))
5015 require_Equal(t, ci.Account.IssuerKey, opk1)
5016
5017 // now update the account
5018 aJWT, err = ac.Encode(osk2)
5019 require_NoError(t, err)
5020
5021 updatedConf := []byte(fmt.Sprintf(`
5022 listen: 127.0.0.1:-1
5023 http: 127.0.0.1:-1
5024 operator = %s
5025 resolver = MEMORY
5026 system_account: %s
5027 resolver_preload = {
5028 %s : %s
5029 %s : %s
5030 }
5031 `, oJWT, sysPK, sysPK, sysJwt, apk, aJWT))
5032 // update the configuration file
5033 require_NoError(t, os.WriteFile(conf, updatedConf, 0666))
5034 // reload
5035 require_NoError(t, s.Reload())
5036
5037 data = readBody(t, fmt.Sprintf("http://127.0.0.1:%d%s?acc=%s", s.MonitorAddr().Port, AccountzPath, apk))
5038 require_NoError(t, json.Unmarshal(data, &ci))
5039 require_Equal(t, ci.Account.IssuerKey, opk2)
5040 }
5041
5042 func TestMonitorAuthorizedUsers(t *testing.T) {
5043 kp, _ := nkeys.FromSeed(seed)
5044 usrNKey, _ := kp.PublicKey()
5045 opts := DefaultMonitorOptions()
5046 opts.Nkeys = []*NkeyUser{{Nkey: string(usrNKey)}}
5047 opts.Users = []*User{{Username: "user", Password: "pwd"}}
5048 s := RunServer(opts)
5049 defer s.Shutdown()
5050
5051 checkAuthUser := func(expected string) {
5052 t.Helper()
5053 resetPreviousHTTPConnections()
5054 url := fmt.Sprintf("http://127.0.0.1:%d/connz?auth=true", s.MonitorAddr().Port)
5055 for mode := 0; mode < 2; mode++ {
5056 connz := pollConnz(t, s, mode, url, &ConnzOptions{Username: true})
5057 if l := len(connz.Conns); l != 1 {
5058 t.Fatalf("Expected 1, got %v", l)
5059 }
5060 conn := connz.Conns[0]
5061 au := conn.AuthorizedUser
5062 if au == _EMPTY_ {
5063 t.Fatal("AuthorizedUser is empty!")
5064 }
5065 if au != expected {
5066 t.Fatalf("Expected %q, got %q", expected, au)
5067 }
5068 }
5069 }
5070
5071 c := natsConnect(t, fmt.Sprintf("nats://user:[email protected]:%d", opts.Port))
5072 defer c.Close()
5073 checkAuthUser("user")
5074 c.Close()
5075
5076 c = natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", opts.Port),
5077 nats.Nkey(usrNKey, func(nonce []byte) ([]byte, error) {
5078 return kp.Sign(nonce)
5079 }))
5080 defer c.Close()
5081 // we should get the user's NKey
5082 checkAuthUser(usrNKey)
5083 c.Close()
5084
5085 s.Shutdown()
5086 opts = DefaultMonitorOptions()
5087 opts.Authorization = "sometoken"
5088 s = RunServer(opts)
5089 defer s.Shutdown()
5090
5091 c = natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", opts.Port),
5092 nats.Token("sometoken"))
5093 defer c.Close()
5094 // We should get the token specified by the user
5095 checkAuthUser("[REDACTED]")
5096 c.Close()
5097 s.Shutdown()
5098
5099 opts = DefaultMonitorOptions()
5100 // User an operator seed
5101 kp, _ = nkeys.FromSeed(oSeed)
5102 pub, _ := kp.PublicKey()
5103 opts.TrustedKeys = []string{pub}
5104 s = RunServer(opts)
5105 defer s.Shutdown()
5106
5107 akp, _ := nkeys.CreateAccount()
5108 apub, _ := akp.PublicKey()
5109 nac := jwt.NewAccountClaims(apub)
5110 ajwt, err := nac.Encode(oKp)
5111 if err != nil {
5112 t.Fatalf("Error generating account JWT: %v", err)
5113 }
5114
5115 nkp, _ := nkeys.CreateUser()
5116 upub, _ := nkp.PublicKey()
5117 nuc := jwt.NewUserClaims(upub)
5118 jwt, err := nuc.Encode(akp)
5119 if err != nil {
5120 t.Fatalf("Error generating user JWT: %v", err)
5121 }
5122
5123 buildMemAccResolver(s)
5124 addAccountToMemResolver(s, apub, ajwt)
5125
5126 c = natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", opts.Port),
5127 nats.UserJWT(
5128 func() (string, error) { return jwt, nil },
5129 func(nonce []byte) ([]byte, error) { return nkp.Sign(nonce) }))
5130 defer c.Close()
5131 // we should get the user's pubkey
5132 checkAuthUser(upub)
5133 }
5134
5135 func testMonitorConnzJWTVisibility(t *testing.T, bearer bool) {
5136 t.Helper()
5137
5138 opts := DefaultMonitorOptions()
5139 kp, _ := nkeys.FromSeed(oSeed)
5140 pub, _ := kp.PublicKey()
5141 opts.TrustedKeys = []string{pub}
5142 s := RunServer(opts)
5143 defer s.Shutdown()
5144
5145 akp, _ := nkeys.CreateAccount()
5146 apub, _ := akp.PublicKey()
5147 nac := jwt.NewAccountClaims(apub)
5148 ajwt, err := nac.Encode(oKp)
5149 require_NoError(t, err)
5150
5151 nkp, _ := nkeys.CreateUser()
5152 upub, _ := nkp.PublicKey()
5153 nuc := jwt.NewUserClaims(upub)
5154 nuc.BearerToken = bearer
5155 userJWT, err := nuc.Encode(akp)
5156 require_NoError(t, err)
5157
5158 buildMemAccResolver(s)
5159 addAccountToMemResolver(s, apub, ajwt)
5160
5161 conn, err := net.Dial("tcp", s.Addr().String())
5162 require_NoError(t, err)
5163 defer func() {
5164 if conn != nil {
5165 conn.Close()
5166 }
5167 }()
5168 require_NoError(t, conn.SetDeadline(time.Now().Add(5*time.Second)))
5169 cr := bufio.NewReaderSize(conn, maxBufSize)
5170 info, err := cr.ReadString('\n')
5171 require_NoError(t, err)
5172
5173 var sigField string
5174 if !bearer {
5175 var ni nonceInfo
5176 require_NoError(t, json.Unmarshal([]byte(info[5:]), &ni))
5177 sigraw, err := nkp.Sign([]byte(ni.Nonce))
5178 require_NoError(t, err)
5179 sig := base64.RawURLEncoding.EncodeToString(sigraw)
5180 sigField = fmt.Sprintf(",\"sig\":\"%s\"", sig)
5181 }
5182 cs := fmt.Sprintf("CONNECT {\"jwt\":%q,\"verbose\":true,\"pedantic\":true%s}\r\n", userJWT, sigField)
5183 _, err = conn.Write([]byte(cs))
5184 require_NoError(t, err)
5185 l, err := cr.ReadString('\n')
5186 require_NoError(t, err)
5187 if !strings.HasPrefix(l, "+OK") {
5188 t.Fatalf("Expected +OK, got %q", l)
5189 }
5190
5191 expectedJWT := userJWT
5192 if bearer {
5193 expectedJWT = _EMPTY_
5194 }
5195
5196 checkConnzJWT := func(url, expectedJWT string) {
5197 t.Helper()
5198 var connz *Connz
5199 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
5200 connz = pollConnz(t, s, 0, url, nil)
5201 if len(connz.Conns) != 1 {
5202 return fmt.Errorf("expected 1 connection, got %d", len(connz.Conns))
5203 }
5204 return nil
5205 })
5206 ci := connz.Conns[0]
5207 require_Equal(t, ci.JWT, expectedJWT)
5208 }
5209
5210 baseURL := fmt.Sprintf("http://127.0.0.1:%d/connz", s.MonitorAddr().Port)
5211 checkConnzJWT(baseURL+"?auth=1", expectedJWT)
5212
5213 require_NoError(t, conn.Close())
5214 conn = nil
5215
5216 checkConnzJWT(baseURL+"?state=closed", expectedJWT)
5217 checkConnzJWT(baseURL+"?auth=1&state=closed", expectedJWT)
5218 }
5219
5220 func TestMonitorConnzJWTVisibility(t *testing.T) {
5221 for _, test := range []struct {
5222 name string
5223 bearer bool
5224 }{
5225 {name: "bearer", bearer: true},
5226 {name: "non-bearer", bearer: false},
5227 } {
5228 t.Run(test.name, func(t *testing.T) {
5229 testMonitorConnzJWTVisibility(t, test.bearer)
5230 })
5231 }
5232 }
5233
5234 // Helper function to check that a JS cluster is formed
5235 func checkForJSClusterUp(t *testing.T, servers ...*Server) {
5236 t.Helper()
5237 // We will use the other JetStream helpers here.
5238 c := &cluster{t: t, servers: servers}
5239 c.checkClusterFormed()
5240 c.waitOnClusterReady()
5241 }
5242
5243 func pollJsz(t *testing.T, s *Server, mode int, url string, opts *JSzOptions) *JSInfo {
5244 t.Helper()
5245
5246 if mode == 0 {
5247 body := readBody(t, url)
5248 info := &JSInfo{}
5249 err := json.Unmarshal(body, info)
5250 require_NoError(t, err)
5251 return info
5252 }
5253
5254 info, err := s.Jsz(opts)
5255 require_NoError(t, err)
5256 return info
5257 }
5258
5259 func TestMonitorJszNonJszServer(t *testing.T) {
5260 srv := RunServer(DefaultOptions())
5261 defer srv.Shutdown()
5262
5263 if !srv.ReadyForConnections(5 * time.Second) {
5264 t.Fatalf("server did not become ready")
5265 }
5266
5267 jsi, err := srv.Jsz(&JSzOptions{})
5268 if err != nil {
5269 t.Fatalf("jsi failed: %v", err)
5270 }
5271 if jsi.ID != srv.ID() {
5272 t.Fatalf("did not receive valid info")
5273 }
5274
5275 jsi, err = srv.Jsz(&JSzOptions{LeaderOnly: true})
5276 if !errors.Is(err, errSkipZreq) {
5277 t.Fatalf("expected a skip z req error: %v", err)
5278 }
5279 if jsi != nil {
5280 t.Fatalf("expected no jsi: %v", jsi)
5281 }
5282 }
5283
5284 func TestMonitorJsz(t *testing.T) {
5285 readJsInfo := func(url string) *JSInfo {
5286 t.Helper()
5287 body := readBody(t, url)
5288 info := &JSInfo{}
5289 err := json.Unmarshal(body, info)
5290 require_NoError(t, err)
5291 return info
5292 }
5293 srvs := []*Server{}
5294 for _, test := range []struct {
5295 port int
5296 mport int
5297 cport int
5298 routed int
5299 }{
5300 {7500, 7501, 7502, 5502},
5301 {5500, 5501, 5502, 7502},
5302 } {
5303 s, _ := runMonitorJSServer(t, test.port, test.mport, test.cport, test.routed)
5304 defer s.Shutdown()
5305 srvs = append(srvs, s)
5306 }
5307 checkClusterFormed(t, srvs...)
5308 checkForJSClusterUp(t, srvs...)
5309
5310 nc := natsConnect(t, "nats://usr:[email protected]:7500")
5311 defer nc.Close()
5312 js, err := nc.JetStream(nats.MaxWait(5 * time.Second))
5313 require_NoError(t, err)
5314 _, err = js.AddStream(&nats.StreamConfig{
5315 Name: "my-stream-replicated",
5316 Subjects: []string{"foo", "bar"},
5317 Replicas: 2,
5318 })
5319 require_NoError(t, err)
5320 _, err = js.AddStream(&nats.StreamConfig{
5321 Name: "my-stream-non-replicated",
5322 Subjects: []string{"baz"},
5323 Replicas: 1,
5324 })
5325 require_NoError(t, err)
5326 _, err = js.AddStream(&nats.StreamConfig{
5327 Name: "my-stream-mirror",
5328 Replicas: 2,
5329 Mirror: &nats.StreamSource{
5330 Name: "my-stream-replicated",
5331 },
5332 })
5333 require_NoError(t, err)
5334 _, err = js.AddConsumer("my-stream-replicated", &nats.ConsumerConfig{
5335 Durable: "my-consumer-replicated",
5336 AckPolicy: nats.AckExplicitPolicy,
5337 })
5338 require_NoError(t, err)
5339 _, err = js.AddConsumer("my-stream-non-replicated", &nats.ConsumerConfig{
5340 Durable: "my-consumer-non-replicated",
5341 AckPolicy: nats.AckExplicitPolicy,
5342 })
5343 require_NoError(t, err)
5344 _, err = js.AddConsumer("my-stream-mirror", &nats.ConsumerConfig{
5345 Durable: "my-consumer-mirror",
5346 AckPolicy: nats.AckExplicitPolicy,
5347 })
5348 require_NoError(t, err)
5349 nc.Flush()
5350 _, err = js.Publish("foo", nil)
5351 require_NoError(t, err)
5352 // Wait for mirror replication
5353 time.Sleep(200 * time.Millisecond)
5354
5355 monUrl1 := fmt.Sprintf("http://127.0.0.1:%d/jsz", 7501)
5356 monUrl2 := fmt.Sprintf("http://127.0.0.1:%d/jsz", 5501)
5357
5358 t.Run("default", func(t *testing.T) {
5359 for _, url := range []string{monUrl1, monUrl2} {
5360 info := readJsInfo(url)
5361 if len(info.AccountDetails) != 0 {
5362 t.Fatalf("expected no account to be returned by %s but got %v", url, info)
5363 }
5364 if info.Streams == 0 {
5365 t.Fatalf("expected stream count to be 3 but got %d", info.Streams)
5366 }
5367 if info.Consumers == 0 {
5368 t.Fatalf("expected consumer count to be 3 but got %d", info.Consumers)
5369 }
5370 if info.Messages != 2 {
5371 t.Fatalf("expected two message but got %d", info.Messages)
5372 }
5373 if info.Limits.MaxHAAssets != 1000 {
5374 t.Fatalf("expected max_ha_assets limit to be 1000 got %v", info.Limits)
5375 }
5376 if info.Total != 2 {
5377 t.Fatalf("expected total to be 2 but got %d", info.Total)
5378 }
5379 }
5380 })
5381 t.Run("accounts", func(t *testing.T) {
5382 for _, url := range []string{monUrl1, monUrl2} {
5383 info := readJsInfo(url + "?accounts=true")
5384
5385 require_Equal(t, len(info.AccountDetails), 2)
5386
5387 for _, acc := range info.AccountDetails {
5388 switch acc.Id {
5389 case "ACC":
5390 require_Equal(t, acc.Name, "ACC")
5391 case "BCC_TO_HAVE_ONE_EXTRA":
5392 require_Equal(t, acc.Name, "BCC_TO_HAVE_ONE_EXTRA")
5393 default:
5394 t.Fatalf("Unexpected account: %s", acc.Name)
5395 }
5396 }
5397 }
5398 })
5399 t.Run("accounts reserved metrics", func(t *testing.T) {
5400 for _, url := range []string{monUrl1, monUrl2} {
5401 info := readJsInfo(url + "?accounts=true&acc=ACC")
5402 if len(info.AccountDetails) != 1 {
5403 t.Fatalf("expected single account")
5404 }
5405 acc := info.AccountDetails[0]
5406 got := int(acc.ReservedMemory)
5407 expected := 5242880
5408 if got != expected {
5409 t.Errorf("Expected: %v, got: %v", expected, got)
5410 }
5411 got = int(acc.ReservedStore)
5412 expected = 4194304
5413 if got != expected {
5414 t.Errorf("Expected: %v, got: %v", expected, got)
5415 }
5416
5417 info = readJsInfo(url + "?accounts=true&acc=BCC_TO_HAVE_ONE_EXTRA")
5418 if len(info.AccountDetails) != 1 {
5419 t.Fatalf("expected single account")
5420 }
5421 acc = info.AccountDetails[0]
5422 got = int(acc.ReservedMemory)
5423 expected = -1
5424 if got != expected {
5425 t.Errorf("Expected: %v, got: %v", expected, got)
5426 }
5427 got = int(acc.ReservedStore)
5428 expected = -1
5429 if got != expected {
5430 t.Errorf("Expected: %v, got: %v", expected, got)
5431 }
5432 }
5433 })
5434 t.Run("offset-too-big", func(t *testing.T) {
5435 for _, url := range []string{monUrl1, monUrl2} {
5436 info := readJsInfo(url + "?accounts=true&offset=10")
5437 if len(info.AccountDetails) != 0 {
5438 t.Fatalf("expected no accounts to be returned by %s but got %v", url, info)
5439 }
5440 }
5441 })
5442 t.Run("limit", func(t *testing.T) {
5443 for _, url := range []string{monUrl1, monUrl2} {
5444 info := readJsInfo(url + "?accounts=true&limit=1")
5445 if len(info.AccountDetails) != 1 {
5446 t.Fatalf("expected one account to be returned by %s but got %v", url, info)
5447 }
5448 if info := readJsInfo(url + "?accounts=true&offset=1&limit=1"); len(info.AccountDetails) != 1 {
5449 t.Fatalf("expected one account to be returned by %s but got %v", url, info)
5450 }
5451 }
5452 })
5453 t.Run("offset-stable", func(t *testing.T) {
5454 for _, url := range []string{monUrl1, monUrl2} {
5455 info1 := readJsInfo(url + "?accounts=true&offset=0&limit=1")
5456 if len(info1.AccountDetails) != 1 {
5457 t.Fatalf("expected one account to be returned by %s but got %v", url, info1)
5458 }
5459 info2 := readJsInfo(url + "?accounts=true&offset=0&limit=1")
5460 if len(info2.AccountDetails) != 1 {
5461 t.Fatalf("expected one account to be returned by %s but got %v", url, info2)
5462 }
5463 if info1.AccountDetails[0].Name != info2.AccountDetails[0].Name {
5464 t.Fatalf("absent changes, same offset should result in same account but got: %v %v",
5465 info1.AccountDetails[0].Name, info2.AccountDetails[0].Name)
5466 }
5467
5468 info1 = readJsInfo(url + "?accounts=true&offset=1&limit=1")
5469 if len(info1.AccountDetails) != 1 {
5470 t.Fatalf("expected one account to be returned by %s but got %v", url, info1)
5471 }
5472 info2 = readJsInfo(url + "?accounts=true&offset=1&limit=1")
5473 if len(info2.AccountDetails) != 1 {
5474 t.Fatalf("expected one account to be returned by %s but got %v", url, info2)
5475 }
5476 if info1.AccountDetails[0].Name != info2.AccountDetails[0].Name {
5477 t.Fatalf("absent changes, same offset should result in same account but gut: %v %v",
5478 info1.AccountDetails[0].Name, info2.AccountDetails[0].Name)
5479 }
5480 }
5481 })
5482 t.Run("filter-account", func(t *testing.T) {
5483 for _, url := range []string{monUrl1, monUrl2} {
5484 info := readJsInfo(url + "?acc=ACC")
5485 if len(info.AccountDetails) != 1 {
5486 t.Fatalf("expected account ACC to be returned by %s but got %v", url, info)
5487 }
5488 if info.AccountDetails[0].Name != "ACC" {
5489 t.Fatalf("expected account ACC to be returned by %s but got %v", url, info)
5490 }
5491 if len(info.AccountDetails[0].Streams) != 0 {
5492 t.Fatalf("expected account ACC to be returned by %s but got %v", url, info)
5493 }
5494 }
5495 })
5496 t.Run("streams", func(t *testing.T) {
5497 for _, url := range []string{monUrl1, monUrl2} {
5498 info := readJsInfo(url + "?acc=ACC&streams=true")
5499 if len(info.AccountDetails) != 1 {
5500 t.Fatalf("expected account ACC to be returned by %s but got %v", url, info)
5501 }
5502 if len(info.AccountDetails[0].Streams) == 0 {
5503 t.Fatalf("expected streams to be returned by %s but got %v", url, info)
5504 }
5505 if len(info.AccountDetails[0].Streams[0].Consumer) != 0 {
5506 t.Fatalf("expected no consumers to be returned by %s but got %v", url, info)
5507 }
5508 }
5509 })
5510 t.Run("stream-leader-only", func(t *testing.T) {
5511 // First server
5512 info := readJsInfo(monUrl1 + "?streams=true&stream-leader-only=1")
5513 for _, a := range info.AccountDetails {
5514 for _, s := range a.Streams {
5515 if s.Cluster.Leader != srvs[0].serverName() {
5516 t.Fatalf("expected stream leader to be %s but got %s", srvs[0].serverName(), s.Cluster.Leader)
5517 }
5518 }
5519 }
5520 info = readJsInfo(monUrl2 + "?streams=true&stream-leader-only=1")
5521 for _, a := range info.AccountDetails {
5522 for _, s := range a.Streams {
5523 if s.Cluster.Leader != srvs[1].serverName() {
5524 t.Fatalf("expected stream leader to be %s but got %s", srvs[0].serverName(), s.Cluster.Leader)
5525 }
5526 }
5527 }
5528 })
5529 t.Run("consumers", func(t *testing.T) {
5530 for _, url := range []string{monUrl1, monUrl2} {
5531 info := readJsInfo(url + "?acc=ACC&consumers=true")
5532 if len(info.AccountDetails) != 1 {
5533 t.Fatalf("expected account ACC to be returned by %s but got %v", url, info)
5534 }
5535 if len(info.AccountDetails[0].Streams[0].Consumer) == 0 {
5536 t.Fatalf("expected consumers to be returned by %s but got %v", url, info)
5537 }
5538 if info.AccountDetails[0].Streams[0].Config != nil {
5539 t.Fatal("Config expected to not be present")
5540 }
5541 if info.AccountDetails[0].Streams[0].Consumer[0].Config != nil {
5542 t.Fatal("Config expected to not be present")
5543 }
5544 if len(info.AccountDetails[0].Streams[0].ConsumerRaftGroups) != 0 {
5545 t.Fatalf("expected consumer raft groups to not be returned by %s but got %v", url, info)
5546 }
5547 }
5548 })
5549 t.Run("direct-consumers", func(t *testing.T) {
5550 // It could take time for the sourcing to set up.
5551 checkFor(t, 5*time.Second, 250*time.Millisecond, func() error {
5552 for _, url := range []string{monUrl1, monUrl2} {
5553 info := readJsInfo(url + "?acc=ACC&consumers=true&direct-consumers=true")
5554 if len(info.AccountDetails) != 1 {
5555 t.Fatalf("expected account ACC to be returned by %s but got %v", url, info)
5556 }
5557 for _, stream := range info.AccountDetails[0].Streams {
5558 if len(stream.DirectConsumer) == 0 {
5559 continue
5560 }
5561 if stream.Name != "my-stream-replicated" {
5562 t.Fatalf("expected direct consumers only on the mirror origin stream, %s reported %d on %q",
5563 url, len(stream.DirectConsumer), stream.Name)
5564 }
5565 if len(stream.DirectConsumer) != 1 {
5566 t.Fatalf("expected exactly one direct consumer on %q but %s returned %d",
5567 stream.Name, url, len(stream.DirectConsumer))
5568 }
5569 for _, dc := range stream.DirectConsumer {
5570 if slices.ContainsFunc(stream.Consumer, func(c *ConsumerInfo) bool {
5571 return c.Name == dc.Name
5572 }) {
5573 t.Fatalf("public consumer %q leaked into the direct consumer list of %q on %s",
5574 dc.Name, stream.Name, url)
5575 }
5576 }
5577 return nil
5578 }
5579 }
5580 return fmt.Errorf("expected direct consumer info to be present on one of the servers")
5581 })
5582 })
5583 t.Run("config", func(t *testing.T) {
5584 for _, url := range []string{monUrl1, monUrl2} {
5585 info := readJsInfo(url + "?acc=ACC&consumers=true&config=true")
5586 if len(info.AccountDetails) != 1 {
5587 t.Fatalf("expected account ACC to be returned by %s but got %v", url, info)
5588 }
5589 if info.AccountDetails[0].Streams[0].Config == nil {
5590 t.Fatal("Config expected to be present")
5591 }
5592 if info.AccountDetails[0].Streams[0].Consumer[0].Config == nil {
5593 t.Fatal("Config expected to be present")
5594 }
5595 }
5596 })
5597 t.Run("replication", func(t *testing.T) {
5598 // The replication lag may only be present on the leader
5599 replicationFound := false
5600 for _, url := range []string{monUrl1, monUrl2} {
5601 info := readJsInfo(url + "?acc=ACC&streams=true")
5602 if len(info.AccountDetails) != 1 {
5603 t.Fatalf("expected account ACC to be returned by %s but got %v", url, info)
5604 }
5605 streamFound := false
5606 for _, stream := range info.AccountDetails[0].Streams {
5607 if stream.Name == "my-stream-mirror" {
5608 streamFound = true
5609 if stream.Mirror != nil {
5610 replicationFound = true
5611 }
5612 }
5613 }
5614 if !streamFound {
5615 t.Fatalf("Did not locate my-stream-mirror stream in results")
5616 }
5617 }
5618 if !replicationFound {
5619 t.Fatal("ReplicationLag expected to be present for my-stream-mirror stream")
5620 }
5621 })
5622 t.Run("cluster-info", func(t *testing.T) {
5623 found := 0
5624 for i, url := range []string{monUrl1, monUrl2} {
5625 info := readJsInfo(url + "")
5626 if info.Meta.Peer != getHash(info.Meta.Leader) {
5627 t.Fatalf("Invalid Peer: %+v", info.Meta)
5628 }
5629 if info.Meta.Replicas != nil {
5630 found++
5631 for _, r := range info.Meta.Replicas {
5632 if r.Peer == _EMPTY_ {
5633 t.Fatalf("Replicas' Peer is empty: %+v", r)
5634 }
5635 }
5636 if info.Meta.Leader != srvs[i].Name() {
5637 t.Fatalf("received cluster info from non leader: leader %s, server: %s", info.Meta.Leader, srvs[i].Name())
5638 }
5639 }
5640 }
5641 if found == 0 {
5642 t.Fatalf("did not receive cluster info from any node")
5643 }
5644 if found > 1 {
5645 t.Fatalf("received cluster info from multiple nodes")
5646 }
5647 })
5648 t.Run("meta-snapshot-stats", func(t *testing.T) {
5649 for _, url := range []string{monUrl1, monUrl2} {
5650 info := readJsInfo(url)
5651 require_True(t, info.Meta != nil)
5652 require_True(t, info.Meta.Snapshot != nil)
5653
5654 snapshot := info.Meta.Snapshot
5655
5656 // In case no snapshots have happened there would be some pending entries.
5657 if snapshot.LastTime.IsZero() {
5658 require_True(t, snapshot.PendingEntries >= 1)
5659 require_True(t, snapshot.PendingSize >= 1)
5660 }
5661
5662 // Force meta snapshots on both servers to test snapshot timing.
5663 for _, srv := range srvs {
5664 if js := srv.getJetStream(); js != nil {
5665 if mg := js.getMetaGroup(); mg != nil {
5666 if snap, _, _, err := js.metaSnapshot(); err == nil {
5667 mg.InstallSnapshot(snap, false)
5668 }
5669 }
5670 }
5671 }
5672 // Wait for snapshot timing to be recorded
5673 time.Sleep(100 * time.Millisecond)
5674
5675 // Get latest stats again.
5676 info = readJsInfo(url)
5677 require_True(t, info.Meta != nil)
5678 require_True(t, info.Meta.Snapshot != nil)
5679
5680 snapshot = info.Meta.Snapshot
5681
5682 require_True(t, !snapshot.LastTime.IsZero())
5683 // Assert that snapshot time is in UTC
5684 require_Equal(t, snapshot.LastTime.Location(), time.UTC)
5685
5686 // Assert that duration is non-negative and reasonable
5687 require_True(t, snapshot.LastDuration >= 0)
5688 require_True(t, snapshot.LastDuration < 30*time.Second)
5689
5690 // Assert that snapshot time is recent.
5691 require_True(t, time.Since(snapshot.LastTime) < 5*time.Minute)
5692 }
5693 })
5694 t.Run("account-non-existing", func(t *testing.T) {
5695 for _, url := range []string{monUrl1, monUrl2} {
5696 info := readJsInfo(url + "?acc=DOES_NOT_EXIST")
5697 if len(info.AccountDetails) != 0 {
5698 t.Fatalf("expected no account to be returned by %s but got %v", url, info)
5699 }
5700 }
5701 })
5702 t.Run("account-non-existing-with-stream-details", func(t *testing.T) {
5703 for _, url := range []string{monUrl1, monUrl2} {
5704 info := readJsInfo(url + "?acc=DOES_NOT_EXIST&streams=true")
5705 if len(info.AccountDetails) != 0 {
5706 t.Fatalf("expected no account to be returned by %s but got %v", url, info)
5707 }
5708 }
5709 })
5710 t.Run("unique-tag-exists", func(t *testing.T) {
5711 for _, url := range []string{monUrl1, monUrl2} {
5712 info := readJsInfo(url)
5713 if len(info.Config.UniqueTag) == 0 {
5714 t.Fatalf("expected unique_tag to be returned by %s but got %v", url, info)
5715 }
5716 }
5717 })
5718 t.Run("raftgroups", func(t *testing.T) {
5719 for _, url := range []string{monUrl1, monUrl2} {
5720 info := readJsInfo(url + "?acc=ACC&consumers=true&raft=true")
5721 if len(info.AccountDetails) != 1 {
5722 t.Fatalf("expected account ACC to be returned by %s but got %v", url, info)
5723 }
5724
5725 // We will have two streams and order is not guaranteed. So grab the one we want.
5726 var si StreamDetail
5727 if info.AccountDetails[0].Streams[0].Name == "my-stream-replicated" {
5728 si = info.AccountDetails[0].Streams[0]
5729 } else {
5730 si = info.AccountDetails[0].Streams[1]
5731 }
5732
5733 if len(si.Consumer) == 0 {
5734 t.Fatalf("expected consumers to be returned by %s but got %v", url, info)
5735 }
5736 if len(si.ConsumerRaftGroups) == 0 {
5737 t.Fatalf("expected consumer raft groups to be returned by %s but got %v", url, info)
5738 }
5739 if len(si.RaftGroup) == 0 {
5740 t.Fatal("expected stream raft group info to be included")
5741 }
5742 crgroup := si.ConsumerRaftGroups[0]
5743 if crgroup.Name != "my-consumer-replicated" && crgroup.Name != "my-consumer-mirror" {
5744 t.Fatalf("expected consumer name to be included in raft group info, got: %v", crgroup.Name)
5745 }
5746 if len(crgroup.RaftGroup) == 0 {
5747 t.Fatal("expected consumer raft group info to be included")
5748 }
5749 require_True(t, si.Cluster.SystemAcc)
5750 require_Equal(t, si.Cluster.TrafficAcc, "SYS")
5751 }
5752 })
5753 t.Run("js-api-level", func(t *testing.T) {
5754 for _, url := range []string{monUrl1, monUrl2} {
5755 info := readJsInfo(url)
5756 require_Equal(t, info.API.Level, JSApiLevel)
5757 }
5758 })
5759 }
5760
5761 func TestMonitorJszOperatorMode(t *testing.T) {
5762 sysName := "SYS"
5763 accName := "APP"
5764
5765 srvs, _, accKp := runMonitorServerWithOperator(t, sysName, accName)
5766 for _, s := range srvs {
5767 defer s.Shutdown()
5768 }
5769 s := srvs[0]
5770
5771 accPub, _ := accKp.PublicKey()
5772
5773 _, aCreds := createUser(t, accKp)
5774
5775 nc, err := nats.Connect(s.ClientURL(), nats.UserCredentials(aCreds))
5776 require_NoError(t, err)
5777 defer nc.Close()
5778
5779 // Create a stream so the APP account shows up in Jsz.
5780 js, err := nc.JetStream(nats.MaxWait(5 * time.Second))
5781 require_NoError(t, err)
5782 _, err = js.AddStream(&nats.StreamConfig{
5783 Name: "my-stream",
5784 Subjects: []string{"foo", "bar"},
5785 MaxBytes: 1024,
5786 })
5787 require_NoError(t, err)
5788
5789 for pollMode := 0; pollMode < 2; pollMode++ {
5790 a := pollJsz(t, s, pollMode, fmt.Sprintf("http://127.0.0.1:%d%s?accounts=1", s.MonitorAddr().Port, JszPath), &JSzOptions{Accounts: true})
5791
5792 require_Equal(t, a.ID, s.ID())
5793 require_Equal(t, len(a.AccountDetails), 1)
5794
5795 // Check accounts.
5796 d := a.AccountDetails[0]
5797 require_Equal(t, d.Id, accPub)
5798 require_Equal(t, d.Name, accName)
5799 }
5800 }
5801
5802 func TestMonitorReloadTLSConfig(t *testing.T) {
5803 template := `
5804 listen: "127.0.0.1:-1"
5805 https: "127.0.0.1:-1"
5806 tls {
5807 cert_file: '%s'
5808 key_file: '%s'
5809 ca_file: '../test/configs/certs/ca.pem'
5810
5811 # Set this to make sure that it does not impact secure monitoring
5812 # (which it did, see issue: https://github.com/nats-io/nats-server/issues/2980)
5813 verify_and_map: true
5814 }
5815 `
5816 conf := createConfFile(t, []byte(fmt.Sprintf(template,
5817 "../test/configs/certs/server-noip.pem",
5818 "../test/configs/certs/server-key-noip.pem")))
5819
5820 s, _ := RunServerWithConfig(conf)
5821 defer s.Shutdown()
5822
5823 addr := fmt.Sprintf("127.0.0.1:%d", s.MonitorAddr().Port)
5824 c, err := net.Dial("tcp", addr)
5825 if err != nil {
5826 t.Fatalf("Error creating ws connection: %v", err)
5827 }
5828 defer c.Close()
5829
5830 tc := &TLSConfigOpts{CaFile: "../test/configs/certs/ca.pem"}
5831 tlsConfig, err := GenTLSConfig(tc)
5832 if err != nil {
5833 t.Fatalf("Error generating TLS config: %v", err)
5834 }
5835 tlsConfig.ServerName = "127.0.0.1"
5836 tlsConfig.RootCAs = tlsConfig.ClientCAs
5837 tlsConfig.ClientCAs = nil
5838 c = tls.Client(c, tlsConfig.Clone())
5839 if err := c.(*tls.Conn).Handshake(); err == nil || !strings.Contains(err.Error(), "SAN") {
5840 t.Fatalf("Unexpected error: %v", err)
5841 }
5842 c.Close()
5843
5844 reloadUpdateConfig(t, s, conf, fmt.Sprintf(template,
5845 "../test/configs/certs/server-cert.pem",
5846 "../test/configs/certs/server-key.pem"))
5847
5848 c, err = net.Dial("tcp", addr)
5849 if err != nil {
5850 t.Fatalf("Error creating ws connection: %v", err)
5851 }
5852 defer c.Close()
5853
5854 c = tls.Client(c, tlsConfig.Clone())
5855 if err := c.(*tls.Conn).Handshake(); err != nil {
5856 t.Fatalf("Error on TLS handshake: %v", err)
5857 }
5858
5859 // Need to read something to see if there is a problem with the certificate or not.
5860 var buf [64]byte
5861 c.SetReadDeadline(time.Now().Add(250 * time.Millisecond))
5862 _, err = c.Read(buf[:])
5863 if ne, ok := err.(net.Error); !ok || !ne.Timeout() {
5864 t.Fatalf("Error: %v", err)
5865 }
5866 }
5867
5868 func TestMonitorMQTT(t *testing.T) {
5869 o := DefaultOptions()
5870 o.HTTPHost = "127.0.0.1"
5871 o.HTTPPort = -1
5872 o.ServerName = "mqtt_server"
5873 o.Users = []*User{{Username: "someuser"}}
5874 pinnedCerts := make(PinnedCertSet)
5875 pinnedCerts["7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069"] = struct{}{}
5876 o.MQTT = MQTTOpts{
5877 Host: "127.0.0.1",
5878 Port: -1,
5879 NoAuthUser: "someuser",
5880 JsDomain: "js",
5881 AuthTimeout: 2.0,
5882 TLSMap: true,
5883 TLSTimeout: 3.0,
5884 TLSPinnedCerts: pinnedCerts,
5885 AckWait: 4 * time.Second,
5886 MaxAckPending: 256,
5887 }
5888 s := RunServer(o)
5889 defer s.Shutdown()
5890
5891 expected := &MQTTOptsVarz{
5892 Host: "127.0.0.1",
5893 Port: o.MQTT.Port,
5894 NoAuthUser: "someuser",
5895 JsDomain: "js",
5896 AuthTimeout: 2.0,
5897 TLSMap: true,
5898 TLSTimeout: 3.0,
5899 TLSPinnedCerts: []string{"7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069"},
5900 AckWait: 4 * time.Second,
5901 MaxAckPending: 256,
5902 }
5903 url := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
5904 for mode := 0; mode < 2; mode++ {
5905 v := pollVarz(t, s, mode, url, nil)
5906 vm := &v.MQTT
5907 if !reflect.DeepEqual(vm, expected) {
5908 t.Fatalf("Expected\n%+v\nGot:\n%+v", expected, vm)
5909 }
5910 }
5911 }
5912
5913 func TestMonitorWebsocket(t *testing.T) {
5914 o := DefaultOptions()
5915 o.HTTPHost = "127.0.0.1"
5916 o.HTTPPort = -1
5917 kp, _ := nkeys.FromSeed(oSeed)
5918 pub, _ := kp.PublicKey()
5919 o.TrustedKeys = []string{pub}
5920 o.Users = []*User{{Username: "someuser"}}
5921 pinnedCerts := make(PinnedCertSet)
5922 pinnedCerts["7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069"] = struct{}{}
5923 o.Websocket = WebsocketOpts{
5924 Host: "127.0.0.1",
5925 Port: -1,
5926 Advertise: "somehost:8080",
5927 NoAuthUser: "someuser",
5928 JWTCookie: "somecookiename",
5929 AuthTimeout: 2.0,
5930 NoTLS: true,
5931 TLSMap: true,
5932 TLSPinnedCerts: pinnedCerts,
5933 SameOrigin: true,
5934 AllowedOrigins: []string{"https://origin1", "https://origin2"},
5935 Compression: true,
5936 HandshakeTimeout: 4 * time.Second,
5937 }
5938 s := RunServer(o)
5939 defer s.Shutdown()
5940
5941 expected := &WebsocketOptsVarz{
5942 Host: "127.0.0.1",
5943 Port: o.Websocket.Port,
5944 Advertise: "somehost:8080",
5945 NoAuthUser: "someuser",
5946 JWTCookie: "somecookiename",
5947 AuthTimeout: 2.0,
5948 NoTLS: true,
5949 TLSMap: true,
5950 TLSPinnedCerts: []string{"7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069"},
5951 SameOrigin: true,
5952 AllowedOrigins: []string{"https://origin1", "https://origin2"},
5953 Compression: true,
5954 HandshakeTimeout: 4 * time.Second,
5955 }
5956 url := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
5957 for mode := 0; mode < 2; mode++ {
5958 v := pollVarz(t, s, mode, url, nil)
5959 vw := &v.Websocket
5960 if !reflect.DeepEqual(vw, expected) {
5961 t.Fatalf("Expected\n%+v\nGot:\n%+v", expected, vw)
5962 }
5963 }
5964 }
5965
5966 func TestMonitorServerIDZRequest(t *testing.T) {
5967 conf := createConfFile(t, []byte(`
5968 listen: 127.0.0.1:-1
5969 server_name: TEST22
5970 # For access to system account.
5971 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } }
5972 `))
5973 defer removeFile(t, conf)
5974
5975 s, _ := RunServerWithConfig(conf)
5976 defer s.Shutdown()
5977
5978 nc, err := nats.Connect(s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
5979 require_NoError(t, err)
5980 defer nc.Close()
5981
5982 subject := fmt.Sprintf(serverPingReqSubj, "IDZ")
5983 resp, err := nc.Request(subject, nil, time.Second)
5984 require_NoError(t, err)
5985
5986 var sid ServerID
5987 err = json.Unmarshal(resp.Data, &sid)
5988 require_NoError(t, err)
5989
5990 require_True(t, sid.Name == "TEST22")
5991 require_True(t, strings.HasPrefix(sid.ID, "N"))
5992 }
5993
5994 func TestMonitorProfilez(t *testing.T) {
5995 s := RunServer(DefaultOptions())
5996 defer s.Shutdown()
5997
5998 // Then start profiling.
5999 s.StartProfiler()
6000
6001 // Now check that all of the profiles that we expect are
6002 // returning instead of erroring.
6003 for _, try := range []*ProfilezOptions{
6004 {Name: "allocs", Debug: 0},
6005 {Name: "allocs", Debug: 1},
6006 {Name: "block", Debug: 0},
6007 {Name: "goroutine", Debug: 0},
6008 {Name: "goroutine", Debug: 1},
6009 {Name: "goroutine", Debug: 2},
6010 {Name: "heap", Debug: 0},
6011 {Name: "heap", Debug: 1},
6012 {Name: "mutex", Debug: 0},
6013 {Name: "threadcreate", Debug: 0},
6014 } {
6015 if ps := s.profilez(try); ps.Error != _EMPTY_ {
6016 t.Fatalf("Unexpected error on %v: %s", try, ps.Error)
6017 }
6018 }
6019 }
6020
6021 func TestMonitorRoutezPoolSize(t *testing.T) {
6022 conf1 := createConfFile(t, []byte(`
6023 port: -1
6024 http: -1
6025 cluster {
6026 port: -1
6027 name: "local"
6028 pool_size: 5
6029 }
6030 no_sys_acc: true
6031 `))
6032 defer removeFile(t, conf1)
6033 s1, o1 := RunServerWithConfig(conf1)
6034 defer s1.Shutdown()
6035
6036 conf23 := createConfFile(t, []byte(fmt.Sprintf(`
6037 port: -1
6038 http: -1
6039 cluster {
6040 port: -1
6041 name: "local"
6042 routes: ["nats://127.0.0.1:%d"]
6043 pool_size: 5
6044 }
6045 no_sys_acc: true
6046 `, o1.Cluster.Port)))
6047 defer removeFile(t, conf23)
6048
6049 s2, _ := RunServerWithConfig(conf23)
6050 defer s2.Shutdown()
6051 s3, _ := RunServerWithConfig(conf23)
6052 defer s3.Shutdown()
6053
6054 checkClusterFormed(t, s1, s2, s3)
6055
6056 for i, s := range []*Server{s1, s2, s3} {
6057 url := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
6058 for mode := 0; mode < 2; mode++ {
6059 v := pollVarz(t, s, mode, url, nil)
6060 if v.Cluster.PoolSize != 5 {
6061 t.Fatalf("Expected Cluster.PoolSize==5, got %v", v.Cluster.PoolSize)
6062 }
6063 if v.Remotes != 2 {
6064 t.Fatalf("Expected Remotes==2, got %v", v.Remotes)
6065 }
6066 if v.Routes != 10 {
6067 t.Fatalf("Expected NumRoutes==10, got %v", v.Routes)
6068 }
6069 }
6070
6071 url = fmt.Sprintf("http://127.0.0.1:%d/routez", s.MonitorAddr().Port)
6072 for mode := 0; mode < 2; mode++ {
6073 v := pollRoutez(t, s, mode, url, nil)
6074 if v.NumRoutes != 10 {
6075 t.Fatalf("Expected NumRoutes==10, got %v", v.NumRoutes)
6076 }
6077 if n := len(v.Routes); n != 10 {
6078 t.Fatalf("Expected len(Routes)==10, got %v", n)
6079 }
6080 remotes := make(map[string]int)
6081 for _, r := range v.Routes {
6082 remotes[r.RemoteID]++
6083 }
6084 if n := len(remotes); n != 2 {
6085 t.Fatalf("Expected routes for 2 different servers, got %v", n)
6086 }
6087 switch i {
6088 case 0:
6089 if n := remotes[s2.ID()]; n != 5 {
6090 t.Fatalf("Expected 5 routes from S1 to S2, got %v", n)
6091 }
6092 if n := remotes[s3.ID()]; n != 5 {
6093 t.Fatalf("Expected 5 routes from S1 to S3, got %v", n)
6094 }
6095 case 1:
6096 if n := remotes[s1.ID()]; n != 5 {
6097 t.Fatalf("Expected 5 routes from S2 to S1, got %v", n)
6098 }
6099 if n := remotes[s3.ID()]; n != 5 {
6100 t.Fatalf("Expected 5 routes from S2 to S3, got %v", n)
6101 }
6102 case 2:
6103 if n := remotes[s1.ID()]; n != 5 {
6104 t.Fatalf("Expected 5 routes from S3 to S1, got %v", n)
6105 }
6106 if n := remotes[s2.ID()]; n != 5 {
6107 t.Fatalf("Expected 5 routes from S3 to S2, got %v", n)
6108 }
6109 }
6110 }
6111 }
6112 }
6113
6114 func TestMonitorRoutezPerAccount(t *testing.T) {
6115 conf1 := createConfFile(t, []byte(`
6116 port: -1
6117 http: -1
6118 accounts {
6119 A { users: [{user: "a", password: "pwd"}] }
6120 }
6121 cluster {
6122 port: -1
6123 name: "local"
6124 accounts: ["A"]
6125 }
6126 `))
6127 defer removeFile(t, conf1)
6128 s1, o1 := RunServerWithConfig(conf1)
6129 defer s1.Shutdown()
6130
6131 conf23 := createConfFile(t, []byte(fmt.Sprintf(`
6132 port: -1
6133 http: -1
6134 accounts {
6135 A { users: [{user: "a", password: "pwd"}] }
6136 }
6137 cluster {
6138 port: -1
6139 name: "local"
6140 routes: ["nats://127.0.0.1:%d"]
6141 accounts: ["A"]
6142 }
6143 `, o1.Cluster.Port)))
6144 defer removeFile(t, conf23)
6145
6146 s2, _ := RunServerWithConfig(conf23)
6147 defer s2.Shutdown()
6148 s3, _ := RunServerWithConfig(conf23)
6149 defer s3.Shutdown()
6150
6151 checkClusterFormed(t, s1, s2, s3)
6152
6153 for _, s := range []*Server{s1, s2, s3} {
6154 // Default pool size + account "A" + system account (added by default)
6155 enr := 2 * (DEFAULT_ROUTE_POOL_SIZE + 1 + 1)
6156 url := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
6157 for mode := 0; mode < 2; mode++ {
6158 v := pollVarz(t, s, mode, url, nil)
6159 if v.Remotes != 2 {
6160 t.Fatalf("Expected Remotes==2, got %v", v.Remotes)
6161 }
6162 if v.Routes != enr {
6163 t.Fatalf("Expected NumRoutes==%d, got %v", enr, v.Routes)
6164 }
6165 }
6166
6167 url = fmt.Sprintf("http://127.0.0.1:%d/routez", s.MonitorAddr().Port)
6168 for mode := 0; mode < 2; mode++ {
6169 v := pollRoutez(t, s, mode, url, nil)
6170 if v.NumRoutes != enr {
6171 t.Fatalf("Expected NumRoutes==%d, got %v", enr, v.NumRoutes)
6172 }
6173 if n := len(v.Routes); n != enr {
6174 t.Fatalf("Expected len(Routes)==%d, got %v", enr, n)
6175 }
6176 remotes := make(map[string]int)
6177 for _, r := range v.Routes {
6178 var acc int
6179 if r.Account == "A" {
6180 acc = 1
6181 }
6182 remotes[r.RemoteID] += acc
6183 }
6184 if n := len(remotes); n != 2 {
6185 t.Fatalf("Expected routes for 2 different servers, got %v", n)
6186 }
6187 for remoteID, v := range remotes {
6188 if v != 1 {
6189 t.Fatalf("Expected one and only one connection for account A for remote %q, got %v", remoteID, v)
6190 }
6191 }
6192 }
6193 }
6194 }
6195
6196 func TestMonitorConnzOperatorAccountNames(t *testing.T) {
6197 sysName := "SYS"
6198 accName := "APP"
6199
6200 srvs, _, accKp := runMonitorServerWithOperator(t, sysName, accName)
6201 for _, s := range srvs {
6202 defer s.Shutdown()
6203 }
6204 s := srvs[0]
6205
6206 accPub, _ := accKp.PublicKey()
6207
6208 // Now create 2 users.
6209 _, creds := createUser(t, accKp)
6210
6211 nc, err := nats.Connect(s.ClientURL(), nats.UserCredentials(creds))
6212 require_NoError(t, err)
6213 defer nc.Close()
6214
6215 for pollMode := 0; pollMode < 2; pollMode++ {
6216 url := fmt.Sprintf("http://127.0.0.1:%d/connz?auth=1", s.MonitorAddr().Port)
6217 connz := pollConnz(t, s, pollMode, url, &ConnzOptions{Username: true})
6218 require_Equal(t, connz.NumConns, 2)
6219 idx := slices.IndexFunc(connz.Conns, func(c *ConnInfo) bool {
6220 return c.Kind == kindStringMap[CLIENT]
6221 })
6222 ci := connz.Conns[idx]
6223 require_Equal(t, ci.Account, accPub)
6224 require_Equal(t, ci.NameTag, accName)
6225 }
6226 }
6227
6228 func TestMonitorConnzOperatorModeFilterByUser(t *testing.T) {
6229 sysName := "SYS"
6230 accName := "APP"
6231
6232 srvs, _, accKp := runMonitorServerWithOperator(t, sysName, accName)
6233 for _, s := range srvs {
6234 defer s.Shutdown()
6235 }
6236 s := srvs[0]
6237
6238 // Now create 2 users.
6239 aUser, aCreds := createUser(t, accKp)
6240 bUser, bCreds := createUser(t, accKp)
6241
6242 var users []*nats.Conn
6243
6244 // Create 2 for A
6245 for i := 0; i < 2; i++ {
6246 nc, err := nats.Connect(s.ClientURL(), nats.UserCredentials(aCreds))
6247 require_NoError(t, err)
6248 defer nc.Close()
6249 users = append(users, nc)
6250 }
6251 // Create 5 for B
6252 for i := 0; i < 5; i++ {
6253 nc, err := nats.Connect(s.ClientURL(), nats.UserCredentials(bCreds))
6254 require_NoError(t, err)
6255 defer nc.Close()
6256 users = append(users, nc)
6257 }
6258
6259 // Test A
6260 connz := pollConnz(t, s, 1, _EMPTY_, &ConnzOptions{User: aUser, Username: true})
6261 require_True(t, connz.NumConns == 2)
6262 for _, ci := range connz.Conns {
6263 require_True(t, ci.AuthorizedUser == aUser)
6264 }
6265 // Test B
6266 connz = pollConnz(t, s, 1, _EMPTY_, &ConnzOptions{User: bUser, Username: true})
6267 require_True(t, connz.NumConns == 5)
6268 for _, ci := range connz.Conns {
6269 require_True(t, ci.AuthorizedUser == bUser)
6270 }
6271
6272 // Make sure URL access is the same.
6273 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
6274 urlFull := url + fmt.Sprintf("connz?auth=true&user=%s", aUser)
6275 connz = pollConnz(t, s, 0, urlFull, nil)
6276 require_True(t, connz.NumConns == 2)
6277 for _, ci := range connz.Conns {
6278 require_True(t, ci.AuthorizedUser == aUser)
6279 }
6280
6281 // Now test closed filtering as well.
6282 for _, nc := range users {
6283 nc.Close()
6284 }
6285 // Let them process and be moved to closed ring buffer in server.
6286 time.Sleep(100 * time.Millisecond)
6287
6288 connz = pollConnz(t, s, 1, _EMPTY_, &ConnzOptions{User: aUser, Username: true, State: ConnClosed})
6289 require_True(t, connz.NumConns == 2)
6290 for _, ci := range connz.Conns {
6291 require_True(t, ci.AuthorizedUser == aUser)
6292 }
6293 }
6294
6295 func TestMonitorConnzSortByRTT(t *testing.T) {
6296 s := runMonitorServer()
6297 defer s.Shutdown()
6298
6299 for i := 0; i < 10; i++ {
6300 nc, err := nats.Connect(s.ClientURL())
6301 require_NoError(t, err)
6302 defer nc.Close()
6303 }
6304
6305 connz := pollConnz(t, s, 1, _EMPTY_, &ConnzOptions{Sort: ByRTT})
6306 require_True(t, connz.NumConns == 10)
6307
6308 var rtt int64
6309 for _, ci := range connz.Conns {
6310 if rtt == 0 {
6311 rtt = ci.rtt
6312 } else {
6313 if ci.rtt > rtt {
6314 t.Fatalf("RTT not in descending order: %v vs %v",
6315 time.Duration(rtt), time.Duration(ci.rtt))
6316 }
6317 rtt = ci.rtt
6318 }
6319 }
6320
6321 // Make sure url works as well.
6322 url := fmt.Sprintf("http://127.0.0.1:%d/connz?sort=rtt", s.MonitorAddr().Port)
6323 connz = pollConnz(t, s, 0, url, nil)
6324 require_True(t, connz.NumConns == 10)
6325
6326 rtt = 0
6327 for _, ci := range connz.Conns {
6328 crttd, err := time.ParseDuration(ci.RTT)
6329 require_NoError(t, err)
6330 crtt := int64(crttd)
6331 if rtt == 0 {
6332 rtt = crtt
6333 } else {
6334 if crtt > rtt {
6335 t.Fatalf("RTT not in descending order: %v vs %v",
6336 time.Duration(rtt), time.Duration(crtt))
6337 }
6338 rtt = ci.rtt
6339 }
6340 }
6341 }
6342
6343 func TestMonitorConnzIncludesLeafnodes(t *testing.T) {
6344 content := `
6345 server_name: "hub"
6346 listen: "127.0.0.1:-1"
6347 http: "127.0.0.1:-1"
6348 operator = "../test/configs/nkeys/op.jwt"
6349 resolver = MEMORY
6350 ping_interval = 1
6351 leafnodes {
6352 listen: "127.0.0.1:-1"
6353 }
6354 `
6355 conf := createConfFile(t, []byte(content))
6356 sb, ob := RunServerWithConfig(conf)
6357 defer sb.Shutdown()
6358
6359 createAcc := func(t *testing.T) (*Account, string) {
6360 t.Helper()
6361 acc, akp := createAccount(sb)
6362 kp, _ := nkeys.CreateUser()
6363 pub, _ := kp.PublicKey()
6364 nuc := jwt.NewUserClaims(pub)
6365 ujwt, err := nuc.Encode(akp)
6366 if err != nil {
6367 t.Fatalf("Error generating user JWT: %v", err)
6368 }
6369 seed, _ := kp.Seed()
6370 creds := genCredsFile(t, ujwt, seed)
6371 return acc, creds
6372 }
6373 acc, mycreds := createAcc(t)
6374 leafName := "my-leaf-node"
6375
6376 content = `
6377 port: -1
6378 http: "127.0.0.1:-1"
6379 ping_interval = 1
6380 server_name: %s
6381 accounts {
6382 %s {
6383 users [
6384 {user: user1, password: pwd}
6385 ]
6386 }
6387 }
6388 leafnodes {
6389 remotes = [
6390 {
6391 account: "%s"
6392 url: nats-leaf://127.0.0.1:%d
6393 credentials: '%s'
6394 }
6395 ]
6396 }
6397 `
6398 config := fmt.Sprintf(content,
6399 leafName,
6400 acc.Name,
6401 acc.Name, ob.LeafNode.Port, mycreds)
6402 conf = createConfFile(t, []byte(config))
6403 sa, _ := RunServerWithConfig(conf)
6404 defer sa.Shutdown()
6405
6406 checkFor(t, time.Second, 15*time.Millisecond, func() error {
6407 if n := sa.NumLeafNodes(); n != 1 {
6408 return fmt.Errorf("Expected 1 leaf connection, got %v", n)
6409 }
6410 return nil
6411 })
6412
6413 for test, options := range map[string]*ConnzOptions{
6414 "WithoutAccount": {},
6415 "WithAccount": {Account: acc.Name},
6416 } {
6417 t.Run(test, func(t *testing.T) {
6418 c := pollConnz(t, sb, 1, "http://127.0.0.1:%d/connz", options)
6419 require_Equal(t, c.NumConns, 1)
6420 require_Equal(t, c.Conns[0].Kind, kindStringMap[LEAF])
6421 })
6422 }
6423 }
6424
6425 // https://github.com/nats-io/nats-server/issues/4144
6426 func TestMonitorAccountszMappingOrderReporting(t *testing.T) {
6427 conf := createConfFile(t, []byte(`
6428 listen: 127.0.0.1:-1
6429 server_name: SR22
6430 accounts {
6431 CLOUD {
6432 exports [ { service: "downlink.>" } ]
6433 }
6434 CLOUD2 {
6435 exports [ { service: "downlink.>" } ]
6436 }
6437 APP {
6438 imports [
6439 { service: { account: CLOUD, subject: "downlink.>"}, to: "event.>"}
6440 { service: { account: CLOUD2, subject: "downlink.>"}, to: "event.>"}
6441 ]
6442 }
6443 }`))
6444
6445 s, _ := RunServerWithConfig(conf)
6446 defer s.Shutdown()
6447
6448 az, err := s.Accountz(&AccountzOptions{"APP"})
6449 require_NoError(t, err)
6450 require_NotNil(t, az.Account)
6451 require_True(t, len(az.Account.Imports) > 0)
6452
6453 var found bool
6454 m := map[string]struct{}{}
6455 for _, si := range az.Account.Imports {
6456 if si.Import.Subject == "downlink.>" {
6457 found = true
6458 require_True(t, si.Import.LocalSubject == "event.>")
6459 m[si.Import.Account] = struct{}{}
6460 }
6461 }
6462 require_True(t, found)
6463 if len(m) != 2 {
6464 t.Fatalf("Expected imports from CLOUD and CLOUD2, got %v", m)
6465 }
6466 }
6467
6468 // expectHealthStatus makes a request to the URL and checks the HTTP status code,
6469 // Content-Type header and health status string.
6470 func expectHealthStatus(t *testing.T, url string, statusCode int, wantStatus string) {
6471 t.Helper()
6472
6473 body := readBodyEx(t, url, statusCode, appJSONContent)
6474 checkHealthStatus(t, body, wantStatus)
6475 }
6476
6477 // checkHealthStatus checks the health status from a JSON response.
6478 func checkHealthStatus(t *testing.T, body []byte, wantStatus string) {
6479 t.Helper()
6480
6481 h := &HealthStatus{}
6482
6483 if err := json.Unmarshal(body, h); err != nil {
6484 t.Fatalf("error unmarshalling the body: %v", err)
6485 }
6486
6487 if h.Status != wantStatus {
6488 t.Errorf("want health status %q, got %q", wantStatus, h.Status)
6489 }
6490 }
6491
6492 // checkHealthzEndpoint makes requests to the /healthz endpoint and checks the health status.
6493 func checkHealthzEndpoint(t *testing.T, address string, statusCode int, wantStatus string) {
6494 t.Helper()
6495
6496 cases := map[string]string{
6497 "healthz": fmt.Sprintf("http://%s/healthz", address),
6498 "js-enabled-only": fmt.Sprintf("http://%s/healthz?js-enabled-only=true", address),
6499 "js-server-only": fmt.Sprintf("http://%s/healthz?js-server-only=true", address),
6500 }
6501
6502 for name, url := range cases {
6503 t.Run(name, func(t *testing.T) {
6504 expectHealthStatus(t, url, statusCode, wantStatus)
6505 })
6506 }
6507 }
6508
6509 func TestMonitorHealthzStatusOK(t *testing.T) {
6510 s := runMonitorServer()
6511 defer s.Shutdown()
6512
6513 checkHealthzEndpoint(t, s.MonitorAddr().String(), http.StatusOK, "ok")
6514 }
6515
6516 func TestMonitorHealthzStatusError(t *testing.T) {
6517 s := runMonitorServer()
6518 defer s.Shutdown()
6519
6520 // Intentionally causing an error in readyForConnections().
6521 // Note: Private field access, taking advantage of having the tests in the same package.
6522 s.mu.Lock()
6523 sl := s.listener
6524 s.listener = nil
6525 s.mu.Unlock()
6526
6527 checkHealthzEndpoint(t, s.MonitorAddr().String(), http.StatusInternalServerError, "error")
6528
6529 // Restore for proper shutdown.
6530 s.mu.Lock()
6531 s.listener = sl
6532 s.mu.Unlock()
6533 }
6534
6535 func TestMonitorHealthzStatusUnavailable(t *testing.T) {
6536 opts := DefaultMonitorOptions()
6537 opts.JetStream = true
6538
6539 s := RunServer(opts)
6540 defer s.Shutdown()
6541
6542 if !s.JetStreamEnabled() {
6543 t.Fatalf("want JetStream to be enabled first")
6544 }
6545
6546 err := s.DisableJetStream()
6547
6548 if err != nil {
6549 t.Fatalf("got an error disabling JetStream: %v", err)
6550 }
6551
6552 for _, test := range []struct {
6553 name string
6554 url string
6555 statusCode int
6556 wantStatus string
6557 }{
6558 {
6559 "healthz",
6560 fmt.Sprintf("http://%s/healthz?", s.MonitorAddr().String()),
6561 http.StatusServiceUnavailable,
6562 "unavailable",
6563 },
6564 {
6565 "js-enabled-only",
6566 fmt.Sprintf("http://%s/healthz?js-enabled-only=true", s.MonitorAddr().String()),
6567 http.StatusServiceUnavailable,
6568 "unavailable",
6569 },
6570 {
6571 "js-server-only",
6572 fmt.Sprintf("http://%s/healthz?js-server-only=true", s.MonitorAddr().String()),
6573 http.StatusOK,
6574 "ok",
6575 },
6576 } {
6577 t.Run(test.name, func(t *testing.T) {
6578 t.Run("no-details", func(t *testing.T) {
6579 expectHealthStatus(t, test.url, test.statusCode, test.wantStatus)
6580 })
6581 t.Run("with-details", func(t *testing.T) {
6582 detailsUrl := fmt.Sprintf("%s&details=true", test.url)
6583 if test.wantStatus != "ok" {
6584 test.wantStatus = "error"
6585 }
6586 expectHealthStatus(t, detailsUrl, test.statusCode, test.wantStatus)
6587 })
6588 })
6589 }
6590 }
6591
6592 func TestServerHealthz(t *testing.T) {
6593 t.Run("BasicHealth", func(t *testing.T) {
6594 s := runMonitorServer()
6595 defer s.Shutdown()
6596
6597 // Test with nil options
6598 status := s.Healthz(nil)
6599 if status == nil {
6600 t.Fatal("Expected non-nil HealthStatus")
6601 }
6602 if status.Status != "ok" {
6603 t.Fatalf("Expected status 'ok', got %q", status.Status)
6604 }
6605 if status.StatusCode != http.StatusOK {
6606 t.Fatalf("Expected status code %d, got %d", http.StatusOK, status.StatusCode)
6607 }
6608
6609 // Test with empty options
6610 status = s.Healthz(&HealthzOptions{})
6611 if status == nil {
6612 t.Fatal("Expected non-nil HealthStatus")
6613 }
6614 if status.Status != "ok" {
6615 t.Fatalf("Expected status 'ok', got %q", status.Status)
6616 }
6617
6618 // Test with JSServerOnly option
6619 status = s.Healthz(&HealthzOptions{JSServerOnly: true})
6620 if status == nil {
6621 t.Fatal("Expected non-nil HealthStatus")
6622 }
6623 if status.Status != "ok" {
6624 t.Fatalf("Expected status 'ok', got %q", status.Status)
6625 }
6626 })
6627
6628 t.Run("BadRequestMissingAccount", func(t *testing.T) {
6629 s := runMonitorServer()
6630 defer s.Shutdown()
6631
6632 // Stream without account should return bad request
6633 status := s.Healthz(&HealthzOptions{Stream: "TEST"})
6634 if status.StatusCode != http.StatusBadRequest {
6635 t.Fatalf("Expected status code %d, got %d", http.StatusBadRequest, status.StatusCode)
6636 }
6637 if status.Status != "error" {
6638 t.Fatalf("Expected status 'error', got %q", status.Status)
6639 }
6640 })
6641
6642 t.Run("BadRequestMissingStream", func(t *testing.T) {
6643 s := runMonitorServer()
6644 defer s.Shutdown()
6645
6646 // Consumer without stream should return bad request
6647 status := s.Healthz(&HealthzOptions{Account: "ACC", Consumer: "TEST"})
6648 if status.StatusCode != http.StatusBadRequest {
6649 t.Fatalf("Expected status code %d, got %d", http.StatusBadRequest, status.StatusCode)
6650 }
6651 if status.Status != "error" {
6652 t.Fatalf("Expected status 'error', got %q", status.Status)
6653 }
6654 })
6655
6656 t.Run("DetailsOption", func(t *testing.T) {
6657 s := runMonitorServer()
6658 defer s.Shutdown()
6659
6660 // Test with Details option - should still return ok for healthy server
6661 status := s.Healthz(&HealthzOptions{Details: true})
6662 if status == nil {
6663 t.Fatal("Expected non-nil HealthStatus")
6664 }
6665 if status.Status != "ok" {
6666 t.Fatalf("Expected status 'ok', got %q", status.Status)
6667 }
6668
6669 // Test bad request with details - should populate Errors slice
6670 status = s.Healthz(&HealthzOptions{Stream: "TEST", Details: true})
6671 if status.StatusCode != http.StatusBadRequest {
6672 t.Fatalf("Expected status code %d, got %d", http.StatusBadRequest, status.StatusCode)
6673 }
6674 if len(status.Errors) == 0 {
6675 t.Fatal("Expected Errors slice to be populated with Details=true")
6676 }
6677 if status.Errors[0].Type != HealthzErrorBadRequest {
6678 t.Fatalf("Expected error type %v, got %v", HealthzErrorBadRequest, status.Errors[0].Type)
6679 }
6680 })
6681
6682 t.Run("ServerNotReady", func(t *testing.T) {
6683 s := runMonitorServer()
6684 defer s.Shutdown()
6685
6686 // Simulate server not ready by removing listener
6687 s.mu.Lock()
6688 sl := s.listener
6689 s.listener = nil
6690 s.mu.Unlock()
6691
6692 status := s.Healthz(nil)
6693 if status.StatusCode != http.StatusInternalServerError {
6694 t.Fatalf("Expected status code %d, got %d", http.StatusInternalServerError, status.StatusCode)
6695 }
6696 if status.Status != "error" {
6697 t.Fatalf("Expected status 'error', got %q", status.Status)
6698 }
6699
6700 // Restore for proper shutdown
6701 s.mu.Lock()
6702 s.listener = sl
6703 s.mu.Unlock()
6704 })
6705
6706 t.Run("JetStreamUnavailable", func(t *testing.T) {
6707 opts := DefaultMonitorOptions()
6708 opts.JetStream = true
6709 s := RunServer(opts)
6710 defer s.Shutdown()
6711
6712 if !s.JetStreamEnabled() {
6713 t.Fatalf("want JetStream to be enabled first")
6714 }
6715
6716 err := s.DisableJetStream()
6717 if err != nil {
6718 t.Fatalf("got an error disabling JetStream: %v", err)
6719 }
6720
6721 // Should report unavailable when JS is disabled
6722 status := s.Healthz(nil)
6723 if status.StatusCode != http.StatusServiceUnavailable {
6724 t.Fatalf("Expected status code %d, got %d", http.StatusServiceUnavailable, status.StatusCode)
6725 }
6726 if status.Status != "unavailable" {
6727 t.Fatalf("Expected status 'unavailable', got %q", status.Status)
6728 }
6729
6730 // JSServerOnly should still report ok
6731 status = s.Healthz(&HealthzOptions{JSServerOnly: true})
6732 if status.Status != "ok" {
6733 t.Fatalf("Expected status 'ok' with JSServerOnly, got %q", status.Status)
6734 }
6735 })
6736 }
6737
6738 // When we converted ipq to use generics we still were using sync.Map. Currently you can not convert
6739 // any or any to a generic parameterized type. So this stopped working and panics.
6740 func TestMonitorIpqzWithGenerics(t *testing.T) {
6741 opts := DefaultMonitorOptions()
6742 opts.JetStream = true
6743
6744 s := RunServer(opts)
6745 defer s.Shutdown()
6746
6747 url := fmt.Sprintf("http://%s/ipqueuesz?all=1", s.MonitorAddr().String())
6748 body := readBody(t, url)
6749 require_True(t, len(body) > 0)
6750
6751 queues := IpqueueszStatus{}
6752 require_NoError(t, json.Unmarshal(body, &queues))
6753 require_True(t, len(queues) >= 4)
6754 _, ok := queues["SendQ"]
6755 require_True(t, ok)
6756 }
6757
6758 func TestMonitorVarzSyncInterval(t *testing.T) {
6759 resetPreviousHTTPConnections()
6760 opts := DefaultMonitorOptions()
6761 opts.JetStream = true
6762 opts.SyncInterval = 22 * time.Second
6763 opts.SyncAlways = true
6764
6765 s := RunServer(opts)
6766 defer s.Shutdown()
6767
6768 url := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
6769
6770 jscfg := pollVarz(t, s, 0, url, nil).JetStream.Config
6771 require_True(t, jscfg.SyncInterval == opts.SyncInterval)
6772 require_True(t, jscfg.SyncAlways)
6773 }
6774
6775 func TestMonitorVarzJSApiLevel(t *testing.T) {
6776 resetPreviousHTTPConnections()
6777 opts := DefaultMonitorOptions()
6778 opts.JetStream = true
6779
6780 s := RunServer(opts)
6781 defer s.Shutdown()
6782
6783 url := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
6784
6785 varz := pollVarz(t, s, 0, url, nil)
6786 apiLevel := varz.JetStream.Stats.API.Level
6787 require_Equal(t, apiLevel, JSApiLevel)
6788 }
6789
6790 func TestMonitorVarzMetadata(t *testing.T) {
6791 s := runMonitorServer()
6792 defer s.Shutdown()
6793
6794 v, err := s.Varz(nil)
6795 require_NoError(t, err)
6796
6797 expected := map[string]string{"key1": "value1", "key2": "value2"}
6798 if !reflect.DeepEqual(expected, v.Metadata) {
6799 t.Fatalf("expected: %v, got: %v", expected, v.Metadata)
6800 }
6801 }
6802
6803 func TestMonitorVarzFeatureFlags(t *testing.T) {
6804 featureFlags["fix"] = false
6805 t.Cleanup(func() { delete(featureFlags, "fix") })
6806
6807 expected := make(map[string]bool)
6808 for k, v := range featureFlags {
6809 expected[k] = v
6810 }
6811 expected["fix"] = true
6812
6813 s := runMonitorServer()
6814 defer s.Shutdown()
6815
6816 v, err := s.Varz(nil)
6817 require_NoError(t, err)
6818
6819 if !reflect.DeepEqual(expected, v.FeatureFlags) {
6820 t.Fatalf("expected: %v, got: %v", expected, v.FeatureFlags)
6821 }
6822 }
6823
6824 func TestMonitorVarzTLSCertEndDate(t *testing.T) {
6825 resetPreviousHTTPConnections()
6826 opts := DefaultMonitorOptions()
6827 tlsConfig, err := GenTLSConfig(
6828 &TLSConfigOpts{
6829 CertFile: "../test/configs/certs/server-cert.pem",
6830 KeyFile: "../test/configs/certs/server-key.pem",
6831 CaFile: "../test/configs/certs/ca.pem",
6832 })
6833 if err != nil {
6834 t.Fatalf("Error generating TLS config: %v", err)
6835 }
6836
6837 opts.TLSConfig = tlsConfig
6838 opts.Cluster.TLSConfig = tlsConfig
6839 opts.Gateway.TLSConfig = tlsConfig
6840 opts.LeafNode.TLSConfig = tlsConfig
6841 opts.MQTT.TLSConfig = tlsConfig
6842 opts.Websocket.TLSConfig = tlsConfig
6843
6844 s := RunServer(opts)
6845 defer s.Shutdown()
6846
6847 url := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
6848 v := pollVarz(t, s, 0, url, nil)
6849
6850 expected := time.Date(2032, 8, 24, 20, 23, 02, 0, time.UTC)
6851
6852 check := func(t *testing.T, notAfter time.Time) {
6853 t.Helper()
6854 if notAfter != expected {
6855 t.Fatalf("Expected expiration date '%v', got '%v'", expected, notAfter)
6856 }
6857 }
6858
6859 check(t, v.TLSCertNotAfter)
6860 check(t, v.Cluster.TLSCertNotAfter)
6861 check(t, v.Gateway.TLSCertNotAfter)
6862 check(t, v.LeafNode.TLSCertNotAfter)
6863 check(t, v.MQTT.TLSCertNotAfter)
6864 check(t, v.Websocket.TLSCertNotAfter)
6865 }
6866
6867 func TestMetaClusterInfoSnapshotStats(t *testing.T) {
6868 c := createJetStreamClusterExplicit(t, "R3S", 3)
6869 defer c.shutdown()
6870
6871 // Create a stream to generate some meta activity.
6872 s := c.randomNonLeader()
6873 nc, js := jsClientConnect(t, s)
6874 defer nc.Close()
6875 _, err := js.AddStream(&nats.StreamConfig{
6876 Name: "TEST",
6877 Subjects: []string{"foo"},
6878 Replicas: 3,
6879 })
6880 require_NoError(t, err)
6881
6882 leader := c.leader()
6883 require_True(t, leader != nil)
6884
6885 // Check Jsz() includes Snapshot.
6886 checkFor(t, 5*time.Second, 250*time.Millisecond, func() error {
6887 jsi, err := leader.Jsz(nil)
6888 if err != nil {
6889 return err
6890 }
6891 if jsi.Meta == nil {
6892 return errors.New("expected meta cluster info from Jsz")
6893 }
6894 if jsi.Meta.Snapshot == nil {
6895 return errors.New("expected snapshot stats in Jsz meta cluster info")
6896 }
6897 return nil
6898 })
6899
6900 // Check Varz() includes Snapshot.
6901 checkFor(t, 5*time.Second, 250*time.Millisecond, func() error {
6902 v, err := leader.Varz(nil)
6903 if err != nil {
6904 return err
6905 }
6906 if v.JetStream.Meta == nil {
6907 return errors.New("expected meta cluster info from Varz")
6908 }
6909 if v.JetStream.Meta.Snapshot == nil {
6910 return errors.New("expected snapshot stats in Varz meta cluster info")
6911 }
6912 return nil
6913 })
6914
6915 // Check STATSZ event includes Snapshot.
6916 snc, _ := jsClientConnect(t, c.randomServer(), nats.UserInfo("admin", "s3cr3t!"))
6917 defer snc.Close()
6918
6919 ch := make(chan *nats.Msg, 1)
6920 _, err = snc.ChanSubscribe(fmt.Sprintf(serverStatsSubj, leader.ID()), ch)
6921 require_NoError(t, err)
6922
6923 msg := require_ChanRead(t, ch, 5*time.Second)
6924 var m ServerStatsMsg
6925 require_NoError(t, json.Unmarshal(msg.Data, &m))
6926 require_True(t, m.Stats.JetStream != nil)
6927 require_True(t, m.Stats.JetStream.Meta != nil)
6928 require_True(t, m.Stats.JetStream.Meta.Snapshot != nil)
6929 }
6930
6931 func TestMonitorConnzAccountRace(t *testing.T) {
6932 s := runMonitorServerWithAccounts()
6933 defer s.Shutdown()
6934
6935 accA, err := s.LookupAccount("A")
6936 if err != nil {
6937 t.Fatalf("LookupAccount A: %v", err)
6938 }
6939 accB, err := s.LookupAccount("B")
6940 if err != nil {
6941 t.Fatalf("LookupAccount B: %v", err)
6942 }
6943
6944 // Real client bound to account A.
6945 nc := createClientConnWithUserSubscribeAndPublish(t, s, "a", "a")
6946 defer nc.Close()
6947
6948 // Grab the server-side *client.
6949 var c *client
6950 checkFor(t, 2*time.Second, 5*time.Millisecond, func() error {
6951 accA.mu.RLock()
6952 defer accA.mu.RUnlock()
6953 for cl := range accA.clients {
6954 c = cl
6955 return nil
6956 }
6957 return errors.New("could not find server-side client for account A")
6958 })
6959
6960 var wg sync.WaitGroup
6961 stop := make(chan struct{})
6962
6963 // Writer: write c.acc under c.mu, mimicking registerWithAccount /
6964 // swapAccountAfterReload binding/swapping an account.
6965 wg.Add(1)
6966 go func() {
6967 defer wg.Done()
6968 for {
6969 select {
6970 case <-stop:
6971 return
6972 default:
6973 }
6974 c.mu.Lock()
6975 if c.acc == accA {
6976 c.acc = accB
6977 } else {
6978 c.acc = accA
6979 }
6980 c.mu.Unlock()
6981 }
6982 }()
6983
6984 // Reader: account-filter path reads client.acc / client.acc.Name under only s.mu.
6985 wg.Add(1)
6986 go func() {
6987 defer wg.Done()
6988 for {
6989 select {
6990 case <-stop:
6991 return
6992 default:
6993 }
6994 if _, err := s.Connz(&ConnzOptions{Account: "A"}); err != nil {
6995 t.Errorf("Connz error: %v", err)
6996 return
6997 }
6998 }
6999 }()
7000
7001 time.Sleep(500 * time.Millisecond)
7002 close(stop)
7003 wg.Wait()
7004
7005 // Restore so shutdown/cleanup is consistent.
7006 c.mu.Lock()
7007 c.acc = accA
7008 c.mu.Unlock()
7009 }
7010
7011 func TestConnzClosedSubsDetailNoSharedMutation(t *testing.T) {
7012 s := runMonitorServer()
7013 defer s.Shutdown()
7014
7015 // Inject a closed client with subscription detail directly into the ring buffer.
7016 cc := &closedClient{}
7017 cc.Cid = 1
7018 cc.subs = []SubDetail{{Subject: "foo.bar"}}
7019 cc.NumSubs = 1
7020 s.mu.Lock()
7021 s.closed.append(cc)
7022 s.mu.Unlock()
7023
7024 // Concurrently request closed connections with subscription detail.
7025 var wg sync.WaitGroup
7026 opts := &ConnzOptions{State: ConnClosed, SubscriptionsDetail: true}
7027 for range 4 {
7028 wg.Add(1)
7029 go func() {
7030 defer wg.Done()
7031 if _, err := s.Connz(opts); err != nil {
7032 t.Errorf("Error on Connz: %v", err)
7033 }
7034 }()
7035 }
7036 wg.Wait()
7037
7038 // The shared cached object must not have been mutated.
7039 s.mu.Lock()
7040 leaked := cc.SubsDetail != nil
7041 s.mu.Unlock()
7042 require_False(t, leaked)
7043
7044 // A plain closed-conn query must not carry SubsDetail.
7045 c, err := s.Connz(&ConnzOptions{State: ConnClosed})
7046 require_NoError(t, err)
7047 require_Len(t, len(c.Conns), 1)
7048 if c.Conns[0].SubsDetail != nil {
7049 t.Fatalf("Plain closed-conn query unexpectedly carried SubsDetail: %+v", c.Conns[0].SubsDetail)
7050 }
7051 }