Debian Codegraph @

server/events_test.go

raw
1 // Copyright 2018-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "bytes"
18 "crypto/sha256"
19 "encoding/json"
20 "errors"
21 "fmt"
22 "math/rand"
23 "net/http"
24 "net/http/httptest"
25 "os"
26 "reflect"
27 "runtime"
28 "runtime/debug"
29 "strings"
30 "sync"
31 "sync/atomic"
32 "testing"
33 "time"
34
35 "github.com/nats-io/jwt/v2"
36 "github.com/nats-io/nats.go"
37 "github.com/nats-io/nkeys"
38 "github.com/nats-io/nuid"
39 )
40
41 func createAccount(s *Server) (*Account, nkeys.KeyPair) {
42 okp, _ := nkeys.FromSeed(oSeed)
43 akp, _ := nkeys.CreateAccount()
44 pub, _ := akp.PublicKey()
45 nac := jwt.NewAccountClaims(pub)
46 jwt, _ := nac.Encode(okp)
47 addAccountToMemResolver(s, pub, jwt)
48 acc, err := s.LookupAccount(pub)
49 if err != nil {
50 panic(err)
51 }
52 return acc, akp
53 }
54
55 func createUserCredsEx(t *testing.T, nuc *jwt.UserClaims, akp nkeys.KeyPair) nats.Option {
56 t.Helper()
57 kp, _ := nkeys.CreateUser()
58 nuc.Subject, _ = kp.PublicKey()
59 ujwt, err := nuc.Encode(akp)
60 if err != nil {
61 t.Fatalf("Error generating user JWT: %v", err)
62 }
63 userCB := func() (string, error) {
64 return ujwt, nil
65 }
66 sigCB := func(nonce []byte) ([]byte, error) {
67 sig, _ := kp.Sign(nonce)
68 return sig, nil
69 }
70 return nats.UserJWT(userCB, sigCB)
71 }
72
73 func createUserCreds(t *testing.T, _ *Server, akp nkeys.KeyPair) nats.Option {
74 return createUserCredsEx(t, jwt.NewUserClaims("test"), akp)
75 }
76
77 func runTrustedServer(t *testing.T) (*Server, *Options) {
78 t.Helper()
79 opts := DefaultOptions()
80 kp, _ := nkeys.FromSeed(oSeed)
81 pub, _ := kp.PublicKey()
82 opts.TrustedKeys = []string{pub}
83 opts.AccountResolver = &MemAccResolver{}
84 s := RunServer(opts)
85 return s, opts
86 }
87
88 func runTrustedCluster(t *testing.T) (*Server, *Options, *Server, *Options, nkeys.KeyPair) {
89 t.Helper()
90
91 kp, _ := nkeys.FromSeed(oSeed)
92 pub, _ := kp.PublicKey()
93
94 mr := &MemAccResolver{}
95
96 // Now create a system account.
97 // NOTE: This can NOT be shared directly between servers.
98 // Set via server options.
99 okp, _ := nkeys.FromSeed(oSeed)
100 akp, _ := nkeys.CreateAccount()
101 apub, _ := akp.PublicKey()
102 nac := jwt.NewAccountClaims(apub)
103 jwt, _ := nac.Encode(okp)
104
105 mr.Store(apub, jwt)
106
107 optsA := DefaultOptions()
108 optsA.Cluster.Name = "TEST_CLUSTER_22"
109 optsA.Cluster.Host = "127.0.0.1"
110 optsA.TrustedKeys = []string{pub}
111 optsA.AccountResolver = mr
112 optsA.SystemAccount = apub
113 optsA.ServerName = "A_SRV"
114 // Add in dummy gateway
115 optsA.Gateway.Name = "TEST_CLUSTER_22"
116 optsA.Gateway.Host = "127.0.0.1"
117 optsA.Gateway.Port = -1
118 optsA.gatewaysSolicitDelay = 30 * time.Second
119
120 sa := RunServer(optsA)
121
122 optsB := nextServerOpts(optsA)
123 optsB.ServerName = "B_SRV"
124 optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host, optsA.Cluster.Port))
125 sb := RunServer(optsB)
126
127 checkClusterFormed(t, sa, sb)
128
129 return sa, optsA, sb, optsB, akp
130 }
131
132 func runTrustedGateways(t *testing.T) (*Server, *Options, *Server, *Options, nkeys.KeyPair) {
133 t.Helper()
134
135 kp, _ := nkeys.FromSeed(oSeed)
136 pub, _ := kp.PublicKey()
137
138 mr := &MemAccResolver{}
139
140 // Now create a system account.
141 // NOTE: This can NOT be shared directly between servers.
142 // Set via server options.
143 okp, _ := nkeys.FromSeed(oSeed)
144 akp, _ := nkeys.CreateAccount()
145 apub, _ := akp.PublicKey()
146 nac := jwt.NewAccountClaims(apub)
147 jwt, _ := nac.Encode(okp)
148
149 mr.Store(apub, jwt)
150
151 optsA := testDefaultOptionsForGateway("A")
152 optsA.Cluster.Name = "A"
153 optsA.Cluster.Host = "127.0.0.1"
154 optsA.TrustedKeys = []string{pub}
155 optsA.AccountResolver = mr
156 optsA.SystemAccount = apub
157
158 sa := RunServer(optsA)
159
160 optsB := testGatewayOptionsFromToWithServers(t, "B", "A", sa)
161 optsB.Cluster.Name = "B"
162 optsB.TrustedKeys = []string{pub}
163 optsB.AccountResolver = mr
164 optsB.SystemAccount = apub
165
166 sb := RunServer(optsB)
167
168 waitForInboundGateways(t, sa, 1, time.Second)
169 waitForOutboundGateways(t, sa, 1, time.Second)
170 waitForInboundGateways(t, sb, 1, time.Second)
171 waitForOutboundGateways(t, sb, 1, time.Second)
172
173 return sa, optsA, sb, optsB, akp
174 }
175
176 func TestSystemAccount(t *testing.T) {
177 s, _ := runTrustedServer(t)
178 defer s.Shutdown()
179
180 acc, _ := createAccount(s)
181 s.setSystemAccount(acc)
182
183 s.mu.Lock()
184 defer s.mu.Unlock()
185
186 if s.sys == nil || s.sys.account == nil {
187 t.Fatalf("Expected sys.account to be non-nil")
188 }
189 if s.sys.client == nil {
190 t.Fatalf("Expected sys.client to be non-nil")
191 }
192
193 s.sys.client.mu.Lock()
194 defer s.sys.client.mu.Unlock()
195 if s.sys.client.echo {
196 t.Fatalf("Internal clients should always have echo false")
197 }
198 }
199
200 func TestSystemAccountNewConnection(t *testing.T) {
201 s, opts := runTrustedServer(t)
202 defer s.Shutdown()
203
204 acc, akp := createAccount(s)
205 s.setSystemAccount(acc)
206
207 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
208 ncs, err := nats.Connect(url, createUserCreds(t, s, akp))
209 if err != nil {
210 t.Fatalf("Error on connect: %v", err)
211 }
212 defer ncs.Close()
213
214 // We may not be able to hear ourselves (if the event is processed
215 // before we create the sub), so we need to create a second client to
216 // trigger the connect/disconnect events.
217 acc2, akp2 := createAccount(s)
218
219 // Be explicit to only receive the event for acc2.
220 sub, _ := ncs.SubscribeSync(fmt.Sprintf("$SYS.ACCOUNT.%s.>", acc2.Name))
221 defer sub.Unsubscribe()
222 ncs.Flush()
223
224 nc, err := nats.Connect(url, createUserCreds(t, s, akp2), nats.Name("TEST EVENTS"))
225 if err != nil {
226 t.Fatalf("Error on connect: %v", err)
227 }
228 defer nc.Close()
229
230 msg, err := sub.NextMsg(time.Second)
231 if err != nil {
232 t.Fatalf("Error receiving msg: %v", err)
233 }
234 connsMsg, err := sub.NextMsg(time.Second)
235 if err != nil {
236 t.Fatalf("Error receiving msg: %v", err)
237 }
238 if strings.HasPrefix(msg.Subject, fmt.Sprintf("$SYS.ACCOUNT.%s.SERVER.CONNS", acc2.Name)) {
239 msg, connsMsg = connsMsg, msg
240 }
241 if !strings.HasPrefix(connsMsg.Subject, fmt.Sprintf("$SYS.ACCOUNT.%s.SERVER.CONNS", acc2.Name)) {
242 t.Fatalf("Expected subject to start with %q, got %q", "$SYS.ACCOUNT.<account>.CONNECT", msg.Subject)
243 }
244 conns := AccountNumConns{}
245 if err := json.Unmarshal(connsMsg.Data, &conns); err != nil {
246 t.Fatalf("Error unmarshalling conns event message: %v", err)
247 } else if conns.Account != acc2.Name {
248 t.Fatalf("Wrong account in conns message: %v", conns)
249 } else if conns.Conns != 1 || conns.TotalConns != 1 || conns.LeafNodes != 0 {
250 t.Fatalf("Wrong counts in conns message: %v", conns)
251 }
252 if !strings.HasPrefix(msg.Subject, fmt.Sprintf("$SYS.ACCOUNT.%s.CONNECT", acc2.Name)) {
253 t.Fatalf("Expected subject to start with %q, got %q", "$SYS.ACCOUNT.<account>.CONNECT", msg.Subject)
254 }
255 tokens := strings.Split(msg.Subject, ".")
256 if len(tokens) < 4 {
257 t.Fatalf("Expected 4 tokens, got %d", len(tokens))
258 }
259 account := tokens[2]
260 if account != acc2.Name {
261 t.Fatalf("Expected %q for account, got %q", acc2.Name, account)
262 }
263
264 cem := ConnectEventMsg{}
265 if err := json.Unmarshal(msg.Data, &cem); err != nil {
266 t.Fatalf("Error unmarshalling connect event message: %v", err)
267 }
268 if cem.Type != ConnectEventMsgType {
269 t.Fatalf("Incorrect schema in connect event: %s", cem.Type)
270 }
271 if cem.Time.IsZero() {
272 t.Fatalf("Event time is not set")
273 }
274 if len(cem.ID) != 22 {
275 t.Fatalf("Event ID is incorrectly set to len %d", len(cem.ID))
276 }
277 if cem.Server.ID != s.ID() {
278 t.Fatalf("Expected server to be %q, got %q", s.ID(), cem.Server.ID)
279 }
280 if cem.Server.Seq == 0 {
281 t.Fatalf("Expected sequence to be non-zero")
282 }
283 if cem.Client.Name != "TEST EVENTS" {
284 t.Fatalf("Expected client name to be %q, got %q", "TEST EVENTS", cem.Client.Name)
285 }
286 if cem.Client.Lang != "go" {
287 t.Fatalf("Expected client lang to be \"go\", got %q", cem.Client.Lang)
288 }
289
290 // Now close the other client. Should fire a disconnect event.
291 // First send and receive some messages.
292 sub2, _ := nc.SubscribeSync("foo")
293 defer sub2.Unsubscribe()
294 sub3, _ := nc.SubscribeSync("*")
295 defer sub3.Unsubscribe()
296
297 for i := 0; i < 10; i++ {
298 nc.Publish("foo", []byte("HELLO WORLD"))
299 }
300 nc.Flush()
301 nc.Close()
302
303 msg, err = sub.NextMsg(time.Second)
304 if err != nil {
305 t.Fatalf("Error receiving msg: %v", err)
306 }
307 connsMsg, err = sub.NextMsg(time.Second)
308 if err != nil {
309 t.Fatalf("Error receiving msg: %v", err)
310 }
311 if strings.HasPrefix(msg.Subject, fmt.Sprintf("$SYS.ACCOUNT.%s.SERVER.CONNS", acc2.Name)) {
312 msg, connsMsg = connsMsg, msg
313 }
314 if !strings.HasPrefix(connsMsg.Subject, fmt.Sprintf("$SYS.ACCOUNT.%s.SERVER.CONNS", acc2.Name)) {
315 t.Fatalf("Expected subject to start with %q, got %q", "$SYS.ACCOUNT.<account>.CONNECT", msg.Subject)
316 } else if !strings.Contains(string(connsMsg.Data), `"total_conns":0`) {
317 t.Fatalf("Expected event to reflect created connection, got: %s", string(connsMsg.Data))
318 }
319 conns = AccountNumConns{}
320 if err := json.Unmarshal(connsMsg.Data, &conns); err != nil {
321 t.Fatalf("Error unmarshalling conns event message: %v", err)
322 } else if conns.Account != acc2.Name {
323 t.Fatalf("Wrong account in conns message: %v", conns)
324 } else if conns.Conns != 0 || conns.TotalConns != 0 || conns.LeafNodes != 0 {
325 t.Fatalf("Wrong counts in conns message: %v", conns)
326 }
327 if !strings.HasPrefix(msg.Subject, fmt.Sprintf("$SYS.ACCOUNT.%s.DISCONNECT", acc2.Name)) {
328 t.Fatalf("Expected subject to start with %q, got %q", "$SYS.ACCOUNT.<account>.DISCONNECT", msg.Subject)
329 }
330 tokens = strings.Split(msg.Subject, ".")
331 if len(tokens) < 4 {
332 t.Fatalf("Expected 4 tokens, got %d", len(tokens))
333 }
334 account = tokens[2]
335 if account != acc2.Name {
336 t.Fatalf("Expected %q for account, got %q", acc2.Name, account)
337 }
338
339 dem := DisconnectEventMsg{}
340 if err := json.Unmarshal(msg.Data, &dem); err != nil {
341 t.Fatalf("Error unmarshalling disconnect event message: %v", err)
342 }
343 if dem.Type != DisconnectEventMsgType {
344 t.Fatalf("Incorrect schema in connect event: %s", cem.Type)
345 }
346 if dem.Time.IsZero() {
347 t.Fatalf("Event time is not set")
348 }
349 if len(dem.ID) != 22 {
350 t.Fatalf("Event ID is incorrectly set to len %d", len(cem.ID))
351 }
352 if dem.Server.ID != s.ID() {
353 t.Fatalf("Expected server to be %q, got %q", s.ID(), dem.Server.ID)
354 }
355 if dem.Server.Seq == 0 {
356 t.Fatalf("Expected sequence to be non-zero")
357 }
358 if dem.Server.Seq <= cem.Server.Seq {
359 t.Fatalf("Expected sequence to be increasing")
360 }
361
362 if cem.Client.Name != "TEST EVENTS" {
363 t.Fatalf("Expected client name to be %q, got %q", "TEST EVENTS", dem.Client.Name)
364 }
365 if dem.Client.Lang != "go" {
366 t.Fatalf("Expected client lang to be \"go\", got %q", dem.Client.Lang)
367 }
368
369 if dem.Sent.Msgs != 10 {
370 t.Fatalf("Expected 10 msgs sent, got %d", dem.Sent.Msgs)
371 }
372 if dem.Sent.Bytes != 110 {
373 t.Fatalf("Expected 110 bytes sent, got %d", dem.Sent.Bytes)
374 }
375 if dem.Received.Msgs != 20 {
376 t.Fatalf("Expected 20 msgs received, got %d", dem.Sent.Msgs)
377 }
378 if dem.Received.Bytes != 220 {
379 t.Fatalf("Expected 220 bytes sent, got %d", dem.Sent.Bytes)
380 }
381 }
382
383 func runTrustedLeafServer(t *testing.T) (*Server, *Options) {
384 t.Helper()
385 opts := DefaultOptions()
386 kp, _ := nkeys.FromSeed(oSeed)
387 pub, _ := kp.PublicKey()
388 opts.TrustedKeys = []string{pub}
389 opts.AccountResolver = &MemAccResolver{}
390 opts.LeafNode.Port = -1
391 s := RunServer(opts)
392 return s, opts
393 }
394
395 func genCredsFile(t *testing.T, jwt string, seed []byte) string {
396 creds := `
397 -----BEGIN NATS USER JWT-----
398 %s
399 ------END NATS USER JWT------
400
401 ************************* IMPORTANT *************************
402 NKEY Seed printed below can be used to sign and prove identity.
403 NKEYs are sensitive and should be treated as secrets.
404
405 -----BEGIN USER NKEY SEED-----
406 %s
407 ------END USER NKEY SEED------
408
409 *************************************************************
410 `
411 return createConfFile(t, []byte(strings.Replace(fmt.Sprintf(creds, jwt, seed), "\t\t", "", -1)))
412 }
413
414 func runSolicitWithCredentials(t *testing.T, opts *Options, creds string) (*Server, *Options, string) {
415 content := `
416 port: -1
417 leafnodes {
418 remotes = [
419 {
420 url: nats-leaf://127.0.0.1:%d
421 credentials: '%s'
422 }
423 ]
424 }
425 `
426 config := fmt.Sprintf(content, opts.LeafNode.Port, creds)
427 conf := createConfFile(t, []byte(config))
428 s, opts := RunServerWithConfig(conf)
429 return s, opts, conf
430 }
431
432 // Helper function to check that a leaf node has connected to our server.
433 func checkLeafNodeConnected(t testing.TB, s *Server) {
434 t.Helper()
435 checkLeafNodeConnectedCount(t, s, 1)
436 }
437
438 // Helper function to check that a leaf node has connected to n server.
439 func checkLeafNodeConnectedCount(t testing.TB, s *Server, lnCons int) {
440 t.Helper()
441 checkFor(t, 5*time.Second, 15*time.Millisecond, func() error {
442 if nln := s.NumLeafNodes(); nln != lnCons {
443 return fmt.Errorf("Expected %d connected leafnode(s) for server %v, got %d",
444 lnCons, s, nln)
445 }
446 return nil
447 })
448 }
449
450 func TestSystemAccountingWithLeafNodes(t *testing.T) {
451 s, opts := runTrustedLeafServer(t)
452 defer s.Shutdown()
453
454 acc, akp := createAccount(s)
455 s.setSystemAccount(acc)
456
457 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
458 ncs, err := nats.Connect(url, createUserCreds(t, s, akp))
459 if err != nil {
460 t.Fatalf("Error on connect: %v", err)
461 }
462 defer ncs.Close()
463
464 acc2, akp2 := createAccount(s)
465
466 // Be explicit to only receive the event for acc2 account.
467 sub, _ := ncs.SubscribeSync(fmt.Sprintf("$SYS.ACCOUNT.%s.DISCONNECT", acc2.Name))
468 defer sub.Unsubscribe()
469 ncs.Flush()
470
471 kp, _ := nkeys.CreateUser()
472 pub, _ := kp.PublicKey()
473 nuc := jwt.NewUserClaims(pub)
474 ujwt, err := nuc.Encode(akp2)
475 if err != nil {
476 t.Fatalf("Error generating user JWT: %v", err)
477 }
478 seed, _ := kp.Seed()
479 mycreds := genCredsFile(t, ujwt, seed)
480
481 // Create a server that solicits a leafnode connection.
482 sl, slopts, _ := runSolicitWithCredentials(t, opts, mycreds)
483 defer sl.Shutdown()
484
485 checkLeafNodeConnected(t, s)
486
487 // Compute the expected number of subs on "sl" based on number
488 // of existing subs before creating the sub on "s".
489 expected := int(sl.NumSubscriptions() + 1)
490
491 nc, err := nats.Connect(url, createUserCreds(t, s, akp2), nats.Name("TEST LEAFNODE EVENTS"))
492 if err != nil {
493 t.Fatalf("Error on connect: %v", err)
494 }
495 defer nc.Close()
496 fooSub := natsSubSync(t, nc, "foo")
497 natsFlush(t, nc)
498
499 checkExpectedSubs(t, expected, sl)
500
501 surl := fmt.Sprintf("nats://%s:%d", slopts.Host, slopts.Port)
502 nc2, err := nats.Connect(surl, nats.Name("TEST LEAFNODE EVENTS"))
503 if err != nil {
504 t.Fatalf("Error on connect: %v", err)
505 }
506 defer nc2.Close()
507
508 // Compute the expected number of subs on "s" based on number
509 // of existing subs before creating the sub on "sl".
510 expected = int(s.NumSubscriptions() + 1)
511
512 m := []byte("HELLO WORLD")
513
514 // Now generate some traffic
515 starSub := natsSubSync(t, nc2, "*")
516 for i := 0; i < 10; i++ {
517 nc2.Publish("foo", m)
518 nc2.Publish("bar", m)
519 }
520 natsFlush(t, nc2)
521
522 checkExpectedSubs(t, expected, s)
523
524 // Now send some from the cluster side too.
525 for i := 0; i < 10; i++ {
526 nc.Publish("foo", m)
527 nc.Publish("bar", m)
528 }
529 nc.Flush()
530
531 // Make sure all messages are received
532 for i := 0; i < 20; i++ {
533 if _, err := fooSub.NextMsg(time.Second); err != nil {
534 t.Fatalf("Did not get message: %v", err)
535 }
536 }
537 for i := 0; i < 40; i++ {
538 if _, err := starSub.NextMsg(time.Second); err != nil {
539 t.Fatalf("Did not get message: %v", err)
540 }
541 }
542
543 // Now shutdown the leafnode server since this is where the event tracking should
544 // happen. Right now we do not track local clients to the leafnode server that
545 // solicited to the cluster, but we should track usage once the leafnode connection stops.
546 sl.Shutdown()
547
548 // Make sure we get disconnect event and that tracking is correct.
549 msg, err := sub.NextMsg(time.Second)
550 if err != nil {
551 t.Fatalf("Error receiving msg: %v", err)
552 }
553
554 dem := DisconnectEventMsg{}
555 if err := json.Unmarshal(msg.Data, &dem); err != nil {
556 t.Fatalf("Error unmarshalling disconnect event message: %v", err)
557 }
558 if dem.Sent.Msgs != 10 {
559 t.Fatalf("Expected 10 msgs sent, got %d", dem.Sent.Msgs)
560 }
561 if dem.Sent.Bytes != 110 {
562 t.Fatalf("Expected 110 bytes sent, got %d", dem.Sent.Bytes)
563 }
564 if dem.Received.Msgs != 20 {
565 t.Fatalf("Expected 20 msgs received, got %d", dem.Received.Msgs)
566 }
567 if dem.Received.Bytes != 220 {
568 t.Fatalf("Expected 220 bytes sent, got %d", dem.Received.Bytes)
569 }
570 }
571
572 func TestSystemAccountDisconnectBadLogin(t *testing.T) {
573 s, opts := runTrustedServer(t)
574 defer s.Shutdown()
575
576 acc, akp := createAccount(s)
577 s.setSystemAccount(acc)
578
579 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
580 ncs, err := nats.Connect(url, createUserCreds(t, s, akp))
581 if err != nil {
582 t.Fatalf("Error on connect: %v", err)
583 }
584 defer ncs.Close()
585
586 // Listen for auth error events though.
587 asub, _ := ncs.SubscribeSync("$SYS.SERVER.*.CLIENT.AUTH.ERR")
588 defer asub.Unsubscribe()
589
590 ncs.Flush()
591
592 nats.Connect(url, nats.Name("TEST BAD LOGIN"))
593
594 m, err := asub.NextMsg(100 * time.Millisecond)
595 if err != nil {
596 t.Fatalf("Should have heard an auth error event")
597 }
598 dem := DisconnectEventMsg{}
599 if err := json.Unmarshal(m.Data, &dem); err != nil {
600 t.Fatalf("Error unmarshalling disconnect event message: %v", err)
601 }
602 if dem.Reason != "Authentication Failure" {
603 t.Fatalf("Expected auth error, got %q", dem.Reason)
604 }
605 }
606
607 func TestSysSubscribeRace(t *testing.T) {
608 s, opts := runTrustedServer(t)
609 defer s.Shutdown()
610
611 acc, akp := createAccount(s)
612 s.setSystemAccount(acc)
613
614 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
615
616 nc, err := nats.Connect(url, createUserCreds(t, s, akp))
617 if err != nil {
618 t.Fatalf("Error on connect: %v", err)
619 }
620 defer nc.Close()
621
622 done := make(chan struct{})
623 wg := sync.WaitGroup{}
624 wg.Add(1)
625 go func() {
626 defer wg.Done()
627 for {
628 nc.Publish("foo", []byte("hello"))
629 select {
630 case <-done:
631 return
632 default:
633 }
634 }
635 }()
636
637 time.Sleep(10 * time.Millisecond)
638
639 received := make(chan struct{})
640 // Create message callback handler.
641 cb := func(sub *subscription, producer *client, _ *Account, subject, reply string, msg []byte) {
642 select {
643 case received <- struct{}{}:
644 default:
645 }
646 }
647 // Now create an internal subscription
648 sub, err := s.sysSubscribe("foo", cb)
649 if sub == nil || err != nil {
650 t.Fatalf("Expected to subscribe, got %v", err)
651 }
652 select {
653 case <-received:
654 close(done)
655 case <-time.After(time.Second):
656 t.Fatalf("Did not receive the message")
657 }
658 wg.Wait()
659 }
660
661 func TestSystemAccountInternalSubscriptions(t *testing.T) {
662 s, opts := runTrustedServer(t)
663 defer s.Shutdown()
664
665 sub, err := s.sysSubscribe("foo", nil)
666 if sub != nil || err != ErrNoSysAccount {
667 t.Fatalf("Expected to get proper error, got %v", err)
668 }
669
670 acc, akp := createAccount(s)
671 s.setSystemAccount(acc)
672
673 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
674
675 nc, err := nats.Connect(url, createUserCreds(t, s, akp))
676 if err != nil {
677 t.Fatalf("Error on connect: %v", err)
678 }
679 defer nc.Close()
680
681 sub, err = s.sysSubscribe("foo", nil)
682 if sub != nil || err == nil {
683 t.Fatalf("Expected to get error for no handler, got %v", err)
684 }
685
686 received := make(chan *nats.Msg)
687 // Create message callback handler.
688 cb := func(sub *subscription, _ *client, _ *Account, subject, reply string, msg []byte) {
689 copy := append([]byte(nil), msg...)
690 received <- &nats.Msg{Subject: subject, Reply: reply, Data: copy}
691 }
692
693 // Now create an internal subscription
694 sub, err = s.sysSubscribe("foo", cb)
695 if sub == nil || err != nil {
696 t.Fatalf("Expected to subscribe, got %v", err)
697 }
698 // Now send out a message from our normal client.
699 nc.Publish("foo", []byte("HELLO WORLD"))
700
701 var msg *nats.Msg
702
703 select {
704 case msg = <-received:
705 if msg.Subject != "foo" {
706 t.Fatalf("Expected \"foo\" as subject, got %q", msg.Subject)
707 }
708 if msg.Reply != "" {
709 t.Fatalf("Expected no reply, got %q", msg.Reply)
710 }
711 if !bytes.Equal(msg.Data, []byte("HELLO WORLD")) {
712 t.Fatalf("Got the wrong msg payload: %q", msg.Data)
713 }
714 break
715 case <-time.After(time.Second):
716 t.Fatalf("Did not receive the message")
717 }
718 s.sysUnsubscribe(sub)
719
720 // Now send out a message from our normal client.
721 // We should not see this one.
722 nc.Publish("foo", []byte("You There?"))
723
724 select {
725 case <-received:
726 t.Fatalf("Received a message when we should not have")
727 case <-time.After(100 * time.Millisecond):
728 break
729 }
730
731 // Now make sure we do not hear ourselves. We optimize this for internally
732 // generated messages.
733 s.mu.Lock()
734 s.sendInternalMsg("foo", "", nil, msg.Data)
735 s.mu.Unlock()
736
737 select {
738 case <-received:
739 t.Fatalf("Received a message when we should not have")
740 case <-time.After(100 * time.Millisecond):
741 break
742 }
743 }
744
745 func TestSystemAccountConnectionUpdatesStopAfterNoLocal(t *testing.T) {
746 sa, _, sb, optsB, _ := runTrustedCluster(t)
747 defer sa.Shutdown()
748 defer sb.Shutdown()
749
750 // Normal Account
751 okp, _ := nkeys.FromSeed(oSeed)
752 akp, _ := nkeys.CreateAccount()
753 pub, _ := akp.PublicKey()
754 nac := jwt.NewAccountClaims(pub)
755 nac.Limits.Conn = 4 // Limit to 4 connections.
756 jwt, _ := nac.Encode(okp)
757
758 addAccountToMemResolver(sa, pub, jwt)
759
760 // Listen for updates to the new account connection activity.
761 received := make(chan *nats.Msg, 10)
762 cb := func(sub *subscription, _ *client, _ *Account, subject, reply string, msg []byte) {
763 copy := append([]byte(nil), msg...)
764 received <- &nats.Msg{Subject: subject, Reply: reply, Data: copy}
765 }
766 subj := fmt.Sprintf(accConnsEventSubjNew, pub)
767 sub, err := sa.sysSubscribe(subj, cb)
768 if sub == nil || err != nil {
769 t.Fatalf("Expected to subscribe, got %v", err)
770 }
771 defer sa.sysUnsubscribe(sub)
772
773 // Create a few users on the new account.
774 clients := []*nats.Conn{}
775
776 url := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
777 for i := 0; i < 4; i++ {
778 nc, err := nats.Connect(url, createUserCreds(t, sb, akp))
779 if err != nil {
780 t.Fatalf("Error on connect: %v", err)
781 }
782 defer nc.Close()
783 clients = append(clients, nc)
784 }
785
786 // Wait for all 4 notifications.
787 checkFor(t, time.Second, 50*time.Millisecond, func() error {
788 if len(received) == 4 {
789 return nil
790 }
791 return fmt.Errorf("Not enough messages, %d vs 4", len(received))
792 })
793
794 // Now lookup the account doing the events on sb.
795 acc, _ := sb.LookupAccount(pub)
796 // Make sure we have the timer running.
797 acc.mu.RLock()
798 ctmr := acc.ctmr
799 acc.mu.RUnlock()
800 if ctmr == nil {
801 t.Fatalf("Expected event timer for acc conns to be running")
802 }
803
804 // Now close all of the connections.
805 for _, nc := range clients {
806 nc.Close()
807 }
808
809 // Wait for the 4 new notifications, 8 total (4 for connect, 4 for disconnect)
810 checkFor(t, time.Second, 50*time.Millisecond, func() error {
811 if len(received) == 8 {
812 return nil
813 }
814 return fmt.Errorf("Not enough messages, %d vs 4", len(received))
815 })
816 // Drain the messages.
817 for i := 0; i < 7; i++ {
818 <-received
819 }
820 // Check last one.
821 msg := <-received
822 m := AccountNumConns{}
823 if err := json.Unmarshal(msg.Data, &m); err != nil {
824 t.Fatalf("Error unmarshalling account connections request message: %v", err)
825 }
826 if m.Conns != 0 {
827 t.Fatalf("Expected Conns to be 0, got %d", m.Conns)
828 }
829
830 // Should not receive any more messages..
831 select {
832 case <-received:
833 t.Fatalf("Did not expect a message here")
834 case <-time.After(50 * time.Millisecond):
835 break
836 }
837
838 // Make sure we have the timer is NOT running.
839 acc.mu.RLock()
840 ctmr = acc.ctmr
841 acc.mu.RUnlock()
842 if ctmr != nil {
843 t.Fatalf("Expected event timer for acc conns to NOT be running after reaching zero local clients")
844 }
845 }
846
847 func TestSystemAccountConnectionLimits(t *testing.T) {
848 sa, optsA, sb, optsB, _ := runTrustedCluster(t)
849 defer sa.Shutdown()
850 defer sb.Shutdown()
851
852 // We want to test that we are limited to a certain number of active connections
853 // across multiple servers.
854
855 // Let's create a user account.
856 okp, _ := nkeys.FromSeed(oSeed)
857 akp, _ := nkeys.CreateAccount()
858 pub, _ := akp.PublicKey()
859 nac := jwt.NewAccountClaims(pub)
860 nac.Limits.Conn = 4 // Limit to 4 connections.
861 jwt, _ := nac.Encode(okp)
862
863 addAccountToMemResolver(sa, pub, jwt)
864
865 urlA := fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port)
866 urlB := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
867
868 // Create a user on each server. Break on first failure.
869 for {
870 nca1, err := nats.Connect(urlA, createUserCreds(t, sa, akp))
871 if err != nil {
872 break
873 }
874 defer nca1.Close()
875 ncb1, err := nats.Connect(urlB, createUserCreds(t, sb, akp))
876 if err != nil {
877 break
878 }
879 defer ncb1.Close()
880 }
881
882 checkFor(t, 5*time.Second, 50*time.Millisecond, func() error {
883 total := sa.NumClients() + sb.NumClients()
884 if total > int(nac.Limits.Conn) {
885 return fmt.Errorf("Expected only %d connections, was allowed to connect %d", nac.Limits.Conn, total)
886 }
887 return nil
888 })
889 }
890
891 func TestBadAccountUpdate(t *testing.T) {
892 sa, _ := runTrustedServer(t)
893 defer sa.Shutdown()
894 akp1, _ := nkeys.CreateAccount()
895 pub, _ := akp1.PublicKey()
896 nac := jwt.NewAccountClaims(pub)
897 ajwt1, err := nac.Encode(oKp)
898 require_NoError(t, err)
899 addAccountToMemResolver(sa, pub, ajwt1)
900 akp2, _ := nkeys.CreateAccount()
901 pub2, _ := akp2.PublicKey()
902 nac.Subject = pub2 // maliciously use a different subject but pretend to remain pub
903 ajwt2, err := nac.Encode(oKp)
904 require_NoError(t, err)
905 acc, err := sa.fetchAccount(pub)
906 require_NoError(t, err)
907 if err := sa.updateAccountWithClaimJWT(acc, ajwt2); err != ErrAccountValidation {
908 t.Fatalf("expected %v but got %v", ErrAccountValidation, err)
909 }
910 }
911
912 // Make sure connection limits apply to the system account itself.
913 func TestSystemAccountSystemConnectionLimitsHonored(t *testing.T) {
914 sa, optsA, sb, optsB, sakp := runTrustedCluster(t)
915 defer sa.Shutdown()
916 defer sb.Shutdown()
917
918 okp, _ := nkeys.FromSeed(oSeed)
919 // Update system account to have 10 connections
920 pub, _ := sakp.PublicKey()
921 nac := jwt.NewAccountClaims(pub)
922 nac.Limits.Conn = 10
923 ajwt, _ := nac.Encode(okp)
924
925 addAccountToMemResolver(sa, pub, ajwt)
926 addAccountToMemResolver(sb, pub, ajwt)
927
928 // Update the accounts on each server with new claims to force update.
929 sysAccA := sa.SystemAccount()
930 sa.updateAccountWithClaimJWT(sysAccA, ajwt)
931 sysAccB := sb.SystemAccount()
932 sb.updateAccountWithClaimJWT(sysAccB, ajwt)
933
934 // Check system here first, with no external it should be zero.
935 sacc := sa.SystemAccount()
936 if nlc := sacc.NumLocalConnections(); nlc != 0 {
937 t.Fatalf("Expected no local connections, got %d", nlc)
938 }
939
940 urlA := fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port)
941 urlB := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
942
943 // Create a user on each server. Break on first failure.
944 tc := 0
945 for {
946 nca1, err := nats.Connect(urlA, createUserCreds(t, sa, sakp))
947 if err != nil {
948 break
949 }
950 defer nca1.Close()
951 tc++
952
953 ncb1, err := nats.Connect(urlB, createUserCreds(t, sb, sakp))
954 if err != nil {
955 break
956 }
957 defer ncb1.Close()
958 tc++
959
960 // The account's connection count is exchanged between servers
961 // so that the local count on each server reflects the total count.
962 // Pause a bit to give a chance to each server to process the update.
963 time.Sleep(15 * time.Millisecond)
964 }
965 if tc != 10 {
966 t.Fatalf("Expected to get 10 external connections, got %d", tc)
967 }
968
969 checkFor(t, 1*time.Second, 50*time.Millisecond, func() error {
970 total := sa.NumClients() + sb.NumClients()
971 if total > int(nac.Limits.Conn) {
972 return fmt.Errorf("Expected only %d connections, was allowed to connect %d", nac.Limits.Conn, total)
973 }
974 return nil
975 })
976 }
977
978 // Test that the remote accounting works when a server is started some time later.
979 func TestSystemAccountConnectionLimitsServersStaggered(t *testing.T) {
980 sa, optsA, sb, optsB, _ := runTrustedCluster(t)
981 defer sa.Shutdown()
982 sb.Shutdown()
983
984 // Let's create a user account.
985 okp, _ := nkeys.FromSeed(oSeed)
986 akp, _ := nkeys.CreateAccount()
987 pub, _ := akp.PublicKey()
988 nac := jwt.NewAccountClaims(pub)
989 nac.Limits.Conn = 4 // Limit to 4 connections.
990 jwt, _ := nac.Encode(okp)
991
992 addAccountToMemResolver(sa, pub, jwt)
993
994 urlA := fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port)
995 // Create max connections on sa.
996 for i := 0; i < int(nac.Limits.Conn); i++ {
997 nc, err := nats.Connect(urlA, createUserCreds(t, sa, akp))
998 if err != nil {
999 t.Fatalf("Unexpected error on #%d try: %v", i+1, err)
1000 }
1001 defer nc.Close()
1002 }
1003
1004 // Restart server B.
1005 optsB.AccountResolver = sa.AccountResolver()
1006 optsB.SystemAccount = sa.SystemAccount().Name
1007 sb = RunServer(optsB)
1008 defer sb.Shutdown()
1009 checkClusterFormed(t, sa, sb)
1010
1011 // Trigger a load of the user account on the new server
1012 // NOTE: If we do not load the user, the user can be the first
1013 // to request this account, hence the connection will succeed.
1014 checkFor(t, time.Second, 15*time.Millisecond, func() error {
1015 if acc, err := sb.LookupAccount(pub); acc == nil || err != nil {
1016 return fmt.Errorf("LookupAccount did not return account or failed, err=%v", err)
1017 }
1018 return nil
1019 })
1020
1021 // Expect this to fail.
1022 urlB := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
1023 if _, err := nats.Connect(urlB, createUserCreds(t, sb, akp)); err == nil {
1024 t.Fatalf("Expected connection to fail due to max limit")
1025 }
1026 }
1027
1028 // Test that the remote accounting works when a server is shutdown.
1029 func TestSystemAccountConnectionLimitsServerShutdownGraceful(t *testing.T) {
1030 sa, optsA, sb, optsB, _ := runTrustedCluster(t)
1031 defer sa.Shutdown()
1032 defer sb.Shutdown()
1033
1034 // Let's create a user account.
1035 okp, _ := nkeys.FromSeed(oSeed)
1036 akp, _ := nkeys.CreateAccount()
1037 pub, _ := akp.PublicKey()
1038 nac := jwt.NewAccountClaims(pub)
1039 nac.Limits.Conn = 10 // Limit to 10 connections.
1040 jwt, _ := nac.Encode(okp)
1041
1042 addAccountToMemResolver(sa, pub, jwt)
1043 addAccountToMemResolver(sb, pub, jwt)
1044
1045 urlA := fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port)
1046 urlB := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
1047
1048 for i := 0; i < 5; i++ {
1049 nc, err := nats.Connect(urlA, nats.NoReconnect(), createUserCreds(t, sa, akp))
1050 if err != nil {
1051 t.Fatalf("Expected to connect, got %v", err)
1052 }
1053 defer nc.Close()
1054 nc, err = nats.Connect(urlB, nats.NoReconnect(), createUserCreds(t, sb, akp))
1055 if err != nil {
1056 t.Fatalf("Expected to connect, got %v", err)
1057 }
1058 defer nc.Close()
1059 }
1060
1061 // We are at capacity so both of these should fail.
1062 if _, err := nats.Connect(urlA, createUserCreds(t, sa, akp)); err == nil {
1063 t.Fatalf("Expected connection to fail due to max limit")
1064 }
1065 if _, err := nats.Connect(urlB, createUserCreds(t, sb, akp)); err == nil {
1066 t.Fatalf("Expected connection to fail due to max limit")
1067 }
1068
1069 // Now shutdown Server B.
1070 sb.Shutdown()
1071
1072 // Now we should be able to create more on A now.
1073 for i := 0; i < 5; i++ {
1074 nc, err := nats.Connect(urlA, createUserCreds(t, sa, akp))
1075 if err != nil {
1076 t.Fatalf("Expected to connect on %d, got %v", i, err)
1077 }
1078 defer nc.Close()
1079 }
1080 }
1081
1082 // Test that the remote accounting works when a server goes away.
1083 func TestSystemAccountConnectionLimitsServerShutdownForced(t *testing.T) {
1084 sa, optsA, sb, optsB, _ := runTrustedCluster(t)
1085 defer sa.Shutdown()
1086
1087 // Let's create a user account.
1088 okp, _ := nkeys.FromSeed(oSeed)
1089 akp, _ := nkeys.CreateAccount()
1090 pub, _ := akp.PublicKey()
1091 nac := jwt.NewAccountClaims(pub)
1092 nac.Limits.Conn = 20 // Limit to 20 connections.
1093 jwt, _ := nac.Encode(okp)
1094
1095 addAccountToMemResolver(sa, pub, jwt)
1096 addAccountToMemResolver(sb, pub, jwt)
1097
1098 urlA := fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port)
1099 urlB := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
1100
1101 for i := 0; i < 10; i++ {
1102 c, err := nats.Connect(urlA, nats.NoReconnect(), createUserCreds(t, sa, akp))
1103 if err != nil {
1104 t.Fatalf("Expected to connect, got %v", err)
1105 }
1106 defer c.Close()
1107 c, err = nats.Connect(urlB, nats.NoReconnect(), createUserCreds(t, sb, akp))
1108 if err != nil {
1109 t.Fatalf("Expected to connect, got %v", err)
1110 }
1111 defer c.Close()
1112 }
1113
1114 // Now shutdown Server B. Do so such that no communications go out.
1115 sb.mu.Lock()
1116 sb.sys = nil
1117 sb.mu.Unlock()
1118 sb.Shutdown()
1119
1120 if _, err := nats.Connect(urlA, createUserCreds(t, sa, akp)); err == nil {
1121 t.Fatalf("Expected connection to fail due to max limit")
1122 }
1123
1124 // Let's speed up the checking process.
1125 sa.mu.Lock()
1126 sa.sys.chkOrph = 10 * time.Millisecond
1127 sa.sys.orphMax = 30 * time.Millisecond
1128 sa.sys.sweeper.Reset(sa.sys.chkOrph)
1129 sa.mu.Unlock()
1130
1131 // We should eventually be able to connect.
1132 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
1133 if c, err := nats.Connect(urlA, createUserCreds(t, sa, akp)); err != nil {
1134 return err
1135 } else {
1136 c.Close()
1137 }
1138 return nil
1139 })
1140 }
1141
1142 func TestSystemAccountFromConfig(t *testing.T) {
1143 kp, _ := nkeys.FromSeed(oSeed)
1144 opub, _ := kp.PublicKey()
1145 akp, _ := nkeys.CreateAccount()
1146 apub, _ := akp.PublicKey()
1147 nac := jwt.NewAccountClaims(apub)
1148 ajwt, err := nac.Encode(kp)
1149 if err != nil {
1150 t.Fatalf("Error generating account JWT: %v", err)
1151 }
1152 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1153 w.Write([]byte(ajwt))
1154 }))
1155 defer ts.Close()
1156
1157 confTemplate := `
1158 listen: -1
1159 trusted: %s
1160 system_account: %s
1161 resolver: URL("%s/jwt/v1/accounts/")
1162 `
1163
1164 conf := createConfFile(t, []byte(fmt.Sprintf(confTemplate, opub, apub, ts.URL)))
1165
1166 s, _ := RunServerWithConfig(conf)
1167 defer s.Shutdown()
1168
1169 if acc := s.SystemAccount(); acc == nil || acc.Name != apub {
1170 t.Fatalf("System Account not properly set")
1171 }
1172 }
1173
1174 func TestAccountClaimsUpdates(t *testing.T) {
1175 test := func(subj string) {
1176 s, opts := runTrustedServer(t)
1177 defer s.Shutdown()
1178
1179 sacc, sakp := createAccount(s)
1180 s.setSystemAccount(sacc)
1181
1182 // Let's create a normal account with limits we can update.
1183 okp, _ := nkeys.FromSeed(oSeed)
1184 akp, _ := nkeys.CreateAccount()
1185 pub, _ := akp.PublicKey()
1186 nac := jwt.NewAccountClaims(pub)
1187 nac.Limits.Conn = 4
1188 ajwt, _ := nac.Encode(okp)
1189
1190 addAccountToMemResolver(s, pub, ajwt)
1191
1192 acc, _ := s.LookupAccount(pub)
1193 if acc.MaxActiveConnections() != 4 {
1194 t.Fatalf("Expected to see a limit of 4 connections")
1195 }
1196
1197 // Simulate a systems publisher so we can do an account claims update.
1198 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1199 nc, err := nats.Connect(url, createUserCreds(t, s, sakp))
1200 if err != nil {
1201 t.Fatalf("Error on connect: %v", err)
1202 }
1203 defer nc.Close()
1204
1205 // Update the account
1206 nac = jwt.NewAccountClaims(pub)
1207 nac.Limits.Conn = 8
1208 issAt := time.Now().Add(-30 * time.Second).Unix()
1209 nac.IssuedAt = issAt
1210 expires := time.Now().Add(2 * time.Second).Unix()
1211 nac.Expires = expires
1212 ajwt, _ = nac.Encode(okp)
1213
1214 // Publish to the system update subject.
1215 claimUpdateSubj := fmt.Sprintf(subj, pub)
1216 nc.Publish(claimUpdateSubj, []byte(ajwt))
1217 nc.Flush()
1218 time.Sleep(200 * time.Millisecond)
1219
1220 acc, _ = s.LookupAccount(pub)
1221 if acc.MaxActiveConnections() != 8 {
1222 t.Fatalf("Account was not updated")
1223 }
1224 }
1225 t.Run("new", func(t *testing.T) {
1226 test(accUpdateEventSubjNew)
1227 })
1228 t.Run("old", func(t *testing.T) {
1229 test(accUpdateEventSubjOld)
1230 })
1231 }
1232
1233 func TestAccountReqMonitoring(t *testing.T) {
1234 s, opts := runTrustedServer(t)
1235 defer s.Shutdown()
1236 sacc, sakp := createAccount(s)
1237 s.setSystemAccount(sacc)
1238 s.EnableJetStream(&JetStreamConfig{StoreDir: t.TempDir()})
1239 unusedAcc, _ := createAccount(s)
1240 acc, akp := createAccount(s)
1241 acc.EnableJetStream(nil, nil)
1242 subsz := fmt.Sprintf(accDirectReqSubj, acc.Name, "SUBSZ")
1243 connz := fmt.Sprintf(accDirectReqSubj, acc.Name, "CONNZ")
1244 jsz := fmt.Sprintf(accDirectReqSubj, acc.Name, "JSZ")
1245
1246 pStatz := fmt.Sprintf(accPingReqSubj, "STATZ")
1247 statz := func(name string) string { return fmt.Sprintf(accDirectReqSubj, name, "STATZ") }
1248 // Create system account connection to query
1249 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1250 ncSys, err := nats.Connect(url, createUserCreds(t, s, sakp))
1251 if err != nil {
1252 t.Fatalf("Error on connect: %v", err)
1253 }
1254 defer ncSys.Close()
1255 // Create a connection that we can query
1256 nc, err := nats.Connect(url, createUserCreds(t, s, akp))
1257 if err != nil {
1258 t.Fatalf("Error on connect: %v", err)
1259 }
1260 defer nc.Close()
1261 // query SUBSZ for account
1262 resp, err := ncSys.Request(subsz, nil, time.Second)
1263 require_NoError(t, err)
1264 require_Contains(t, string(resp.Data), `"num_subscriptions":5,`)
1265 // create a subscription
1266 sub, err := nc.Subscribe("foo", func(msg *nats.Msg) {})
1267 require_NoError(t, err)
1268 defer sub.Unsubscribe()
1269
1270 require_NoError(t, nc.Flush())
1271 // query SUBSZ for account
1272 resp, err = ncSys.Request(subsz, nil, time.Second)
1273 require_NoError(t, err)
1274 require_Contains(t, string(resp.Data), `"num_subscriptions":6,`, `"subject":"foo"`)
1275 // query connections for account
1276 resp, err = ncSys.Request(connz, nil, time.Second)
1277 require_NoError(t, err)
1278 require_Contains(t, string(resp.Data), `"num_connections":1,`, `"total":1,`)
1279 // query connections for js account
1280 resp, err = ncSys.Request(jsz, nil, time.Second)
1281 require_NoError(t, err)
1282 require_Contains(t, string(resp.Data), `"memory":0,`, `"storage":0,`)
1283 // query statz/conns for account
1284 resp, err = ncSys.Request(statz(acc.Name), nil, time.Second)
1285 require_NoError(t, err)
1286 respContentAcc := []string{`"conns":1,`, `"total_conns":1`, `"slow_consumers":0`, `"sent":{"msgs":0,"bytes":0`,
1287 `"received":{"msgs":0,"bytes":0`, `"num_subscriptions":`, fmt.Sprintf(`"acc":"%s"`, acc.Name)}
1288 require_Contains(t, string(resp.Data), respContentAcc...)
1289
1290 rIb := ncSys.NewRespInbox()
1291 rSub, err := ncSys.SubscribeSync(rIb)
1292 require_NoError(t, err)
1293 require_NoError(t, ncSys.PublishRequest(pStatz, rIb, nil))
1294 minRespContentForBothAcc := []string{`"conns":1,`, `"total_conns":1`, `"slow_consumers":0`, `"acc":"`, `"num_subscriptions":`}
1295 resp, err = rSub.NextMsg(time.Second)
1296 require_NoError(t, err)
1297 require_Contains(t, string(resp.Data), minRespContentForBothAcc...)
1298 // expect one entry per account
1299 require_Contains(t, string(resp.Data), fmt.Sprintf(`"acc":"%s"`, acc.Name), fmt.Sprintf(`"acc":"%s"`, sacc.Name))
1300
1301 // Test ping with filter by account name
1302 require_NoError(t, ncSys.PublishRequest(pStatz, rIb, []byte(fmt.Sprintf(`{"accounts":["%s"]}`, sacc.Name))))
1303 m, err := rSub.NextMsg(time.Second)
1304 require_NoError(t, err)
1305 require_Contains(t, string(m.Data), minRespContentForBothAcc...)
1306
1307 require_NoError(t, ncSys.PublishRequest(pStatz, rIb, []byte(fmt.Sprintf(`{"accounts":["%s"]}`, acc.Name))))
1308 m, err = rSub.NextMsg(time.Second)
1309 require_NoError(t, err)
1310 require_Contains(t, string(m.Data), respContentAcc...)
1311
1312 // Test include unused for statz and ping of statz
1313 unusedContent := []string{`"conns":0,`, `"total_conns":0`, `"slow_consumers":0`,
1314 fmt.Sprintf(`"acc":"%s"`, unusedAcc.Name)}
1315
1316 resp, err = ncSys.Request(statz(unusedAcc.Name),
1317 []byte(fmt.Sprintf(`{"accounts":["%s"], "include_unused":true}`, unusedAcc.Name)),
1318 time.Second)
1319 require_NoError(t, err)
1320 require_Contains(t, string(resp.Data), unusedContent...)
1321
1322 require_NoError(t, ncSys.PublishRequest(pStatz, rIb,
1323 []byte(fmt.Sprintf(`{"accounts":["%s"], "include_unused":true}`, unusedAcc.Name))))
1324 resp, err = rSub.NextMsg(time.Second)
1325 require_NoError(t, err)
1326 require_Contains(t, string(resp.Data), unusedContent...)
1327
1328 require_NoError(t, ncSys.PublishRequest(pStatz, rIb, []byte(fmt.Sprintf(`{"accounts":["%s"]}`, unusedAcc.Name))))
1329 _, err = rSub.NextMsg(200 * time.Millisecond)
1330 require_Error(t, err)
1331
1332 // Test ping from within account, send extra message to check counters.
1333 require_NoError(t, nc.Publish("foo", nil))
1334 ib := nc.NewRespInbox()
1335 rSub, err = nc.SubscribeSync(ib)
1336 require_NoError(t, err)
1337 require_NoError(t, nc.PublishRequest(pStatz, ib, nil))
1338 require_NoError(t, nc.Flush())
1339 resp, err = rSub.NextMsg(time.Second)
1340 require_NoError(t, err)
1341
1342 // Since we now have processed our own message, sent msgs will be at least 1.
1343 payload := string(resp.Data)
1344 respContentAcc = []string{`"conns":1,`, `"total_conns":1`, `"slow_consumers":0`, `"sent":{"msgs":1,"bytes":0`, fmt.Sprintf(`"acc":"%s"`, acc.Name)}
1345 require_Contains(t, payload, respContentAcc...)
1346
1347 // Depending on timing, statz message could be accounted too.
1348 receivedOK := strings.Contains(payload, `"received":{"msgs":1,"bytes":0`) || strings.Contains(payload, `"received":{"msgs":2,"bytes":0`)
1349 require_True(t, receivedOK)
1350 _, err = rSub.NextMsg(200 * time.Millisecond)
1351 require_Error(t, err)
1352 }
1353
1354 func TestAccountReqInfo(t *testing.T) {
1355 s, opts := runTrustedServer(t)
1356 defer s.Shutdown()
1357 sacc, sakp := createAccount(s)
1358 s.setSystemAccount(sacc)
1359 // Let's create an account with service export.
1360 akp, _ := nkeys.CreateAccount()
1361 pub1, _ := akp.PublicKey()
1362 nac1 := jwt.NewAccountClaims(pub1)
1363 nac1.Exports.Add(&jwt.Export{Subject: "req.*", Type: jwt.Service})
1364 ajwt1, _ := nac1.Encode(oKp)
1365 addAccountToMemResolver(s, pub1, ajwt1)
1366 s.LookupAccount(pub1)
1367 info1 := fmt.Sprintf(accDirectReqSubj, pub1, "INFO")
1368 // Now add an account with service imports.
1369 akp2, _ := nkeys.CreateAccount()
1370 pub2, _ := akp2.PublicKey()
1371 nac2 := jwt.NewAccountClaims(pub2)
1372 nac2.Imports.Add(&jwt.Import{Account: pub1, Subject: "req.1", Type: jwt.Service})
1373 ajwt2, _ := nac2.Encode(oKp)
1374 addAccountToMemResolver(s, pub2, ajwt2)
1375 s.LookupAccount(pub2)
1376 info2 := fmt.Sprintf(accDirectReqSubj, pub2, "INFO")
1377 // Create system account connection to query
1378 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1379 ncSys, err := nats.Connect(url, createUserCreds(t, s, sakp))
1380 if err != nil {
1381 t.Fatalf("Error on connect: %v", err)
1382 }
1383 defer ncSys.Close()
1384 checkCommon := func(info *AccountInfo, srv *ServerInfo, pub, jwt string) {
1385 if info.Complete != true {
1386 t.Fatalf("Unexpected value: %v", info.Complete)
1387 } else if info.Expired != false {
1388 t.Fatalf("Unexpected value: %v", info.Expired)
1389 } else if info.JetStream != false {
1390 t.Fatalf("Unexpected value: %v", info.JetStream)
1391 } else if info.ClientCnt != 0 {
1392 t.Fatalf("Unexpected value: %v", info.ClientCnt)
1393 } else if info.AccountName != pub {
1394 t.Fatalf("Unexpected value: %v", info.AccountName)
1395 } else if info.LeafCnt != 0 {
1396 t.Fatalf("Unexpected value: %v", info.LeafCnt)
1397 } else if info.Jwt != jwt {
1398 t.Fatalf("Unexpected value: %v", info.Jwt)
1399 } else if srv.Cluster != "abc" {
1400 t.Fatalf("Unexpected value: %v", srv.Cluster)
1401 } else if srv.Name != s.Name() {
1402 t.Fatalf("Unexpected value: %v", srv.Name)
1403 } else if srv.Host != opts.Host {
1404 t.Fatalf("Unexpected value: %v", srv.Host)
1405 } else if srv.Seq < 1 {
1406 t.Fatalf("Unexpected value: %v", srv.Seq)
1407 }
1408 }
1409 info := AccountInfo{}
1410 srv := ServerInfo{}
1411 msg := struct {
1412 Data *AccountInfo `json:"data"`
1413 Srv *ServerInfo `json:"server"`
1414 }{
1415 &info,
1416 &srv,
1417 }
1418 if resp, err := ncSys.Request(info1, nil, time.Second); err != nil {
1419 t.Fatalf("Error on request: %v", err)
1420 } else if err := json.Unmarshal(resp.Data, &msg); err != nil {
1421 t.Fatalf("Unmarshalling failed: %v", err)
1422 } else if len(info.Exports) != 1 {
1423 t.Fatalf("Unexpected value: %v", info.Exports)
1424 } else if len(info.Imports) != 4 {
1425 t.Fatalf("Unexpected value: %+v", info.Imports)
1426 } else if info.Exports[0].Subject != "req.*" {
1427 t.Fatalf("Unexpected value: %v", info.Exports)
1428 } else if info.Exports[0].Type != jwt.Service {
1429 t.Fatalf("Unexpected value: %v", info.Exports)
1430 } else if info.Exports[0].ResponseType != jwt.ResponseTypeSingleton {
1431 t.Fatalf("Unexpected value: %v", info.Exports)
1432 } else if info.SubCnt != 4 {
1433 t.Fatalf("Unexpected value: %v", info.SubCnt)
1434 } else {
1435 checkCommon(&info, &srv, pub1, ajwt1)
1436 }
1437 info = AccountInfo{}
1438 srv = ServerInfo{}
1439 if resp, err := ncSys.Request(info2, nil, time.Second); err != nil {
1440 t.Fatalf("Error on request: %v", err)
1441 } else if err := json.Unmarshal(resp.Data, &msg); err != nil {
1442 t.Fatalf("Unmarshalling failed: %v", err)
1443 } else if len(info.Exports) != 0 {
1444 t.Fatalf("Unexpected value: %v", info.Exports)
1445 } else if len(info.Imports) != 5 {
1446 t.Fatalf("Unexpected value: %+v", info.Imports)
1447 }
1448 // Here we need to find our import
1449 var si *ExtImport
1450 for _, im := range info.Imports {
1451 if im.Subject == "req.1" {
1452 si = &im
1453 break
1454 }
1455 }
1456 if si == nil {
1457 t.Fatalf("Could not find our import")
1458 }
1459 if si.Type != jwt.Service {
1460 t.Fatalf("Unexpected value: %+v", si)
1461 } else if si.Account != pub1 {
1462 t.Fatalf("Unexpected value: %+v", si)
1463 } else if info.SubCnt != 5 {
1464 t.Fatalf("Unexpected value: %+v", si)
1465 } else {
1466 checkCommon(&info, &srv, pub2, ajwt2)
1467 }
1468 }
1469
1470 func TestAccountClaimsUpdatesWithServiceImports(t *testing.T) {
1471 s, opts := runTrustedServer(t)
1472 defer s.Shutdown()
1473
1474 sacc, sakp := createAccount(s)
1475 s.setSystemAccount(sacc)
1476
1477 okp, _ := nkeys.FromSeed(oSeed)
1478
1479 // Let's create an account with service export.
1480 akp, _ := nkeys.CreateAccount()
1481 pub, _ := akp.PublicKey()
1482 nac := jwt.NewAccountClaims(pub)
1483 nac.Exports.Add(&jwt.Export{Subject: "req.*", Type: jwt.Service})
1484 ajwt, _ := nac.Encode(okp)
1485 addAccountToMemResolver(s, pub, ajwt)
1486 s.LookupAccount(pub)
1487
1488 // Now add an account with multiple service imports.
1489 akp2, _ := nkeys.CreateAccount()
1490 pub2, _ := akp2.PublicKey()
1491 nac2 := jwt.NewAccountClaims(pub2)
1492 nac2.Imports.Add(&jwt.Import{Account: pub, Subject: "req.1", Type: jwt.Service})
1493 ajwt2, _ := nac2.Encode(okp)
1494
1495 addAccountToMemResolver(s, pub2, ajwt2)
1496 s.LookupAccount(pub2)
1497
1498 startSubs := s.NumSubscriptions()
1499
1500 // Simulate a systems publisher so we can do an account claims update.
1501 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1502 nc, err := nats.Connect(url, createUserCreds(t, s, sakp))
1503 if err != nil {
1504 t.Fatalf("Error on connect: %v", err)
1505 }
1506 defer nc.Close()
1507
1508 // Update the account several times
1509 for i := 1; i <= 10; i++ {
1510 nac2 = jwt.NewAccountClaims(pub2)
1511 nac2.Limits.Conn = int64(i)
1512 nac2.Imports.Add(&jwt.Import{Account: pub, Subject: "req.1", Type: jwt.Service})
1513 ajwt2, _ = nac2.Encode(okp)
1514
1515 // Publish to the system update subject.
1516 claimUpdateSubj := fmt.Sprintf(accUpdateEventSubjNew, pub2)
1517 nc.Publish(claimUpdateSubj, []byte(ajwt2))
1518 }
1519 nc.Flush()
1520 time.Sleep(50 * time.Millisecond)
1521
1522 if startSubs < s.NumSubscriptions() {
1523 t.Fatalf("Subscriptions leaked: %d vs %d", startSubs, s.NumSubscriptions())
1524 }
1525 }
1526
1527 func TestAccountConnsLimitExceededAfterUpdate(t *testing.T) {
1528 s, opts := runTrustedServer(t)
1529 defer s.Shutdown()
1530
1531 sacc, _ := createAccount(s)
1532 s.setSystemAccount(sacc)
1533
1534 // Let's create a normal account with limits we can update.
1535 okp, _ := nkeys.FromSeed(oSeed)
1536 akp, _ := nkeys.CreateAccount()
1537 pub, _ := akp.PublicKey()
1538 nac := jwt.NewAccountClaims(pub)
1539 nac.Limits.Conn = 10
1540 ajwt, _ := nac.Encode(okp)
1541
1542 addAccountToMemResolver(s, pub, ajwt)
1543 acc, _ := s.LookupAccount(pub)
1544
1545 // Now create the max connections.
1546 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1547 for {
1548 nc, err := nats.Connect(url, createUserCreds(t, s, akp))
1549 if err != nil {
1550 break
1551 }
1552 defer nc.Close()
1553 }
1554
1555 // We should have max here.
1556 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
1557 if total := s.NumClients(); total != acc.MaxActiveConnections() {
1558 return fmt.Errorf("Expected %d connections, got %d", acc.MaxActiveConnections(), total)
1559 }
1560 return nil
1561 })
1562
1563 // Now change limits to make current connections over the limit.
1564 nac = jwt.NewAccountClaims(pub)
1565 nac.Limits.Conn = 2
1566 ajwt, _ = nac.Encode(okp)
1567
1568 s.updateAccountWithClaimJWT(acc, ajwt)
1569 if acc.MaxActiveConnections() != 2 {
1570 t.Fatalf("Expected max connections to be set to 2, got %d", acc.MaxActiveConnections())
1571 }
1572 // We should have closed the excess connections.
1573 checkClientsCount(t, s, acc.MaxActiveConnections())
1574 }
1575
1576 func TestAccountConnsLimitExceededAfterUpdateDisconnectNewOnly(t *testing.T) {
1577 s, opts := runTrustedServer(t)
1578 defer s.Shutdown()
1579
1580 sacc, _ := createAccount(s)
1581 s.setSystemAccount(sacc)
1582
1583 // Let's create a normal account with limits we can update.
1584 okp, _ := nkeys.FromSeed(oSeed)
1585 akp, _ := nkeys.CreateAccount()
1586 pub, _ := akp.PublicKey()
1587 nac := jwt.NewAccountClaims(pub)
1588 nac.Limits.Conn = 10
1589 ajwt, _ := nac.Encode(okp)
1590
1591 addAccountToMemResolver(s, pub, ajwt)
1592 acc, _ := s.LookupAccount(pub)
1593
1594 // Now create the max connections.
1595 // We create half then we will wait and then create the rest.
1596 // Will test that we disconnect the newest ones.
1597 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1598 for i := 0; i < 5; i++ {
1599 nc, err := nats.Connect(url, nats.Name("OLD"), nats.NoReconnect(), createUserCreds(t, s, akp))
1600 require_NoError(t, err)
1601 defer nc.Close()
1602 }
1603 time.Sleep(500 * time.Millisecond)
1604 for i := 0; i < 5; i++ {
1605 nc, err := nats.Connect(url, nats.Name("NEW"), nats.NoReconnect(), createUserCreds(t, s, akp))
1606 require_NoError(t, err)
1607 defer nc.Close()
1608 }
1609
1610 // We should have max here.
1611 checkClientsCount(t, s, acc.MaxActiveConnections())
1612
1613 // Now change limits to make current connections over the limit.
1614 nac = jwt.NewAccountClaims(pub)
1615 nac.Limits.Conn = 5
1616 ajwt, _ = nac.Encode(okp)
1617
1618 s.updateAccountWithClaimJWT(acc, ajwt)
1619 if acc.MaxActiveConnections() != 5 {
1620 t.Fatalf("Expected max connections to be set to 2, got %d", acc.MaxActiveConnections())
1621 }
1622 // We should have closed the excess connections.
1623 checkClientsCount(t, s, acc.MaxActiveConnections())
1624
1625 connz, err := s.Connz(nil)
1626 require_NoError(t, err)
1627
1628 // There should only be OLD connections.
1629 for _, c := range connz.Conns {
1630 require_Equal(t, c.Name, "OLD")
1631 }
1632 }
1633
1634 func TestSystemAccountWithBadRemoteLatencyUpdate(t *testing.T) {
1635 s, _ := runTrustedServer(t)
1636 defer s.Shutdown()
1637
1638 acc, _ := createAccount(s)
1639 s.setSystemAccount(acc)
1640
1641 rl := remoteLatency{
1642 Account: "NONSENSE",
1643 ReqId: "_INBOX.22",
1644 }
1645 b, _ := json.Marshal(&rl)
1646 s.remoteLatencyUpdate(nil, nil, nil, "foo", _EMPTY_, nil, b)
1647 }
1648
1649 func TestSystemAccountWithGateways(t *testing.T) {
1650 sa, oa, sb, ob, akp := runTrustedGateways(t)
1651 defer sa.Shutdown()
1652 defer sb.Shutdown()
1653
1654 // Create a client on A that will subscribe on $SYS.ACCOUNT.>
1655 urla := fmt.Sprintf("nats://%s:%d", oa.Host, oa.Port)
1656 nca := natsConnect(t, urla, createUserCreds(t, sa, akp), nats.Name("SYS"))
1657 defer nca.Close()
1658 nca.Flush()
1659
1660 sub, _ := nca.SubscribeSync("$SYS.ACCOUNT.>")
1661 defer sub.Unsubscribe()
1662 nca.Flush()
1663
1664 // If this tests fails with wrong number after 10 seconds we may have
1665 // added a new initial subscription for the eventing system.
1666 checkExpectedSubs(t, 62, sa)
1667
1668 // Create a client on B and see if we receive the event
1669 urlb := fmt.Sprintf("nats://%s:%d", ob.Host, ob.Port)
1670 ncb := natsConnect(t, urlb, createUserCreds(t, sb, akp), nats.Name("TEST EVENTS"))
1671 defer ncb.Close()
1672
1673 // space for .CONNECT and .CONNS from SYS and $G as well as one extra message
1674 msgs := [4]*nats.Msg{}
1675 var err error
1676 msgs[0], err = sub.NextMsg(time.Second)
1677 require_NoError(t, err)
1678 msgs[1], err = sub.NextMsg(time.Second)
1679 require_NoError(t, err)
1680 // TODO: There is a race currently that can cause the server to process the
1681 // system event *after* the subscription on "A" has been registered, and so
1682 // the "nca" client would receive its own CONNECT message.
1683 msgs[2], _ = sub.NextMsg(250 * time.Millisecond)
1684
1685 findMsgs := func(sub string) []*nats.Msg {
1686 rMsgs := []*nats.Msg{}
1687 for _, m := range msgs {
1688 if m == nil {
1689 continue
1690 }
1691 if m.Subject == sub {
1692 rMsgs = append(rMsgs, m)
1693 }
1694 }
1695 return rMsgs
1696 }
1697
1698 msg := findMsgs(fmt.Sprintf("$SYS.ACCOUNT.%s.CONNECT", sa.SystemAccount().Name))
1699 var bMsg *nats.Msg
1700 if len(msg) < 1 {
1701 t.Fatal("Expected at least one message")
1702 }
1703 bMsg = msg[len(msg)-1]
1704
1705 require_Contains(t, string(bMsg.Data), sb.ID())
1706 require_Contains(t, string(bMsg.Data), `"cluster":"B"`)
1707 require_Contains(t, string(bMsg.Data), `"name":"TEST EVENTS"`)
1708
1709 connsMsgA := findMsgs(fmt.Sprintf("$SYS.ACCOUNT.%s.SERVER.CONNS", sa.SystemAccount().Name))
1710 if len(connsMsgA) != 1 {
1711 t.Fatal("Expected a message")
1712 }
1713 }
1714
1715 func TestSystemAccountNoAuthUser(t *testing.T) {
1716 conf := createConfFile(t, []byte(`
1717 listen: "127.0.0.1:-1"
1718 accounts {
1719 $SYS {
1720 users [{user: "admin", password: "pwd"}]
1721 }
1722 }
1723 `))
1724 defer os.Remove(conf)
1725 s, o := RunServerWithConfig(conf)
1726 defer s.Shutdown()
1727
1728 for _, test := range []struct {
1729 name string
1730 usrInfo string
1731 ok bool
1732 account string
1733 }{
1734 {"valid user/pwd", "admin:pwd@", true, "$SYS"},
1735 {"invalid pwd", "admin:wrong@", false, _EMPTY_},
1736 {"some token", "sometoken@", false, _EMPTY_},
1737 {"user used without pwd", "admin@", false, _EMPTY_}, // will be treated as a token
1738 {"user with empty password", "admin:@", false, _EMPTY_},
1739 {"no user means global account", _EMPTY_, true, globalAccountName},
1740 } {
1741 t.Run(test.name, func(t *testing.T) {
1742 url := fmt.Sprintf("nats://%s127.0.0.1:%d", test.usrInfo, o.Port)
1743 nc, err := nats.Connect(url)
1744 if err != nil {
1745 if test.ok {
1746 t.Fatalf("Unexpected error: %v", err)
1747 }
1748 return
1749 } else if !test.ok {
1750 nc.Close()
1751 t.Fatalf("Should have failed, did not")
1752 }
1753 var accName string
1754 s.mu.Lock()
1755 for _, c := range s.clients {
1756 c.mu.Lock()
1757 if c.acc != nil {
1758 accName = c.acc.Name
1759 }
1760 c.mu.Unlock()
1761 break
1762 }
1763 s.mu.Unlock()
1764 nc.Close()
1765 checkClientsCount(t, s, 0)
1766 if accName != test.account {
1767 t.Fatalf("The account should have been %q, got %q", test.account, accName)
1768 }
1769 })
1770 }
1771 }
1772
1773 func TestServerAccountConns(t *testing.T) {
1774 // speed up hb
1775 orgHBInterval := eventsHBInterval
1776 eventsHBInterval = time.Millisecond * 100
1777 defer func() { eventsHBInterval = orgHBInterval }()
1778 conf := createConfFile(t, []byte(`
1779 host: 127.0.0.1
1780 port: -1
1781 system_account: SYS
1782 accounts: {
1783 SYS: {users: [{user: s, password: s}]}
1784 ACC: {users: [{user: a, password: a}]}
1785 }`))
1786 s, _ := RunServerWithConfig(conf)
1787 defer s.Shutdown()
1788
1789 nc := natsConnect(t, s.ClientURL(), nats.UserInfo("a", "a"))
1790 defer nc.Close()
1791
1792 subOut, err := nc.SubscribeSync("foo")
1793 require_NoError(t, err)
1794 hw := "HELLO WORLD"
1795 nc.Publish("foo", []byte(hw))
1796 nc.Publish("bar", []byte(hw)) // will only count towards received
1797 nc.Flush()
1798 m, err := subOut.NextMsg(time.Second)
1799 require_NoError(t, err)
1800 require_Equal(t, string(m.Data), hw)
1801
1802 ncs := natsConnect(t, s.ClientURL(), nats.UserInfo("s", "s"))
1803 defer ncs.Close()
1804 subs, err := ncs.SubscribeSync("$SYS.ACCOUNT.ACC.SERVER.CONNS")
1805 require_NoError(t, err)
1806
1807 m, err = subs.NextMsg(time.Second)
1808 require_NoError(t, err)
1809 accConns := &AccountNumConns{}
1810 err = json.Unmarshal(m.Data, accConns)
1811 require_NoError(t, err)
1812
1813 require_True(t, accConns.Received.Msgs == 2)
1814 require_True(t, accConns.Received.Bytes == 2*int64(len(hw)))
1815 require_True(t, accConns.Sent.Msgs == 1)
1816 require_True(t, accConns.Sent.Bytes == int64(len(hw)))
1817 }
1818
1819 func TestServerEventsStatsZ(t *testing.T) {
1820 serverStatsReqSubj := "$SYS.REQ.SERVER.%s.STATSZ"
1821 preStart := time.Now().UTC()
1822 // Add little bit of delay to make sure that time check
1823 // between pre-start and actual start does not fail.
1824 time.Sleep(5 * time.Millisecond)
1825 sa, optsA, sb, _, akp := runTrustedCluster(t)
1826 defer sa.Shutdown()
1827 defer sb.Shutdown()
1828 // Same between actual start and post start.
1829 time.Sleep(5 * time.Millisecond)
1830 postStart := time.Now().UTC()
1831
1832 url := fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port)
1833 ncs, err := nats.Connect(url, createUserCreds(t, sa, akp))
1834 if err != nil {
1835 t.Fatalf("Error on connect: %v", err)
1836 }
1837 defer ncs.Close()
1838
1839 subj := fmt.Sprintf(serverStatsSubj, sa.ID())
1840 sub, _ := ncs.SubscribeSync(subj)
1841 defer sub.Unsubscribe()
1842 ncs.Publish("foo", []byte("HELLO WORLD"))
1843 ncs.Flush()
1844
1845 // Let's speed up the checking process.
1846 sa.mu.Lock()
1847 sa.sys.statsz = 10 * time.Millisecond
1848 sa.sys.stmr.Reset(sa.sys.statsz)
1849 sa.mu.Unlock()
1850
1851 _, err = sub.NextMsg(time.Second)
1852 if err != nil {
1853 t.Fatalf("Error receiving msg: %v", err)
1854 }
1855 // Get it the second time so we can check some stats
1856 msg, err := sub.NextMsg(time.Second)
1857 if err != nil {
1858 t.Fatalf("Error receiving msg: %v", err)
1859 }
1860 m := ServerStatsMsg{}
1861 if err := json.Unmarshal(msg.Data, &m); err != nil {
1862 t.Fatalf("Error unmarshalling the statz json: %v", err)
1863 }
1864 if m.Server.ID != sa.ID() {
1865 t.Fatalf("Did not match IDs")
1866 }
1867 if m.Server.Cluster != "TEST_CLUSTER_22" {
1868 t.Fatalf("Did not match cluster name")
1869 }
1870 if m.Server.Version != VERSION {
1871 t.Fatalf("Did not match server version")
1872 }
1873 if !m.Stats.Start.After(preStart) && m.Stats.Start.Before(postStart) {
1874 t.Fatalf("Got a wrong start time for the server %v", m.Stats.Start)
1875 }
1876 if m.Stats.Connections != 1 {
1877 t.Fatalf("Did not match connections of 1, got %d", m.Stats.Connections)
1878 }
1879 if m.Stats.ActiveAccounts != 1 {
1880 t.Fatalf("Did not match active accounts of 1, got %d", m.Stats.ActiveAccounts)
1881 }
1882 if m.Stats.Sent.Msgs < 1 {
1883 t.Fatalf("Did not match sent msgs of >=1, got %d", m.Stats.Sent.Msgs)
1884 }
1885 if m.Stats.Received.Msgs < 1 {
1886 t.Fatalf("Did not match received msgs of >=1, got %d", m.Stats.Received.Msgs)
1887 }
1888 if m.Stats.ReceivedFromClients.Msgs < 1 {
1889 t.Fatalf("Did not match received from client msgs of >=1, got %d", m.Stats.ReceivedFromClients.Msgs)
1890 }
1891 if m.Stats.ReceivedFromClients.Bytes < 1 {
1892 t.Fatalf("Did not match received from client bytes of >=1, got %d", m.Stats.ReceivedFromClients.Bytes)
1893 }
1894 if m.Stats.SentToClients.Msgs < 1 {
1895 t.Fatalf("Did not match sent to client msgs of >= 1, got %d", m.Stats.SentToClients.Msgs)
1896 }
1897 if m.Stats.SentToClients.Bytes < 1 {
1898 t.Fatalf("Did not match sent to client bytes of >= 1, got %d", m.Stats.SentToClients.Bytes)
1899 }
1900
1901 // Default pool size + 1 for system account
1902 expectedRoutes := DEFAULT_ROUTE_POOL_SIZE + 1
1903 if lr := len(m.Stats.Routes); lr != expectedRoutes {
1904 t.Fatalf("Expected %d routes, but got %d", expectedRoutes, lr)
1905 }
1906
1907 // Now let's prompt this server to send us the statsz
1908 subj = fmt.Sprintf(serverStatsReqSubj, sa.ID())
1909 msg, err = ncs.Request(subj, nil, time.Second)
1910 if err != nil {
1911 t.Fatalf("Error trying to request statsz: %v", err)
1912 }
1913 m2 := ServerStatsMsg{}
1914 if err := json.Unmarshal(msg.Data, &m2); err != nil {
1915 t.Fatalf("Error unmarshalling the statz json: %v", err)
1916 }
1917 if m2.Server.ID != sa.ID() {
1918 t.Fatalf("Did not match IDs")
1919 }
1920 if m2.Stats.Connections != 1 {
1921 t.Fatalf("Did not match connections of 1, got %d", m2.Stats.Connections)
1922 }
1923 if m2.Stats.ActiveAccounts != 1 {
1924 t.Fatalf("Did not match active accounts of 1, got %d", m2.Stats.ActiveAccounts)
1925 }
1926 if m2.Stats.Sent.Msgs < 3 {
1927 t.Fatalf("Did not match sent msgs of >= 3, got %d", m2.Stats.Sent.Msgs)
1928 }
1929 if m2.Stats.Received.Msgs < 1 {
1930 t.Fatalf("Did not match received msgs of >= 1, got %d", m2.Stats.Received.Msgs)
1931 }
1932 if lr := len(m2.Stats.Routes); lr != expectedRoutes {
1933 t.Fatalf("Expected %d routes, but got %d", expectedRoutes, lr)
1934 }
1935
1936 msg, err = ncs.Request(subj, nil, time.Second)
1937 if err != nil {
1938 t.Fatalf("Error trying to request statsz: %v", err)
1939 }
1940 m3 := ServerStatsMsg{}
1941 if err := json.Unmarshal(msg.Data, &m3); err != nil {
1942 t.Fatalf("Error unmarshalling the statz json: %v", err)
1943 }
1944 if m3.Server.ID != sa.ID() {
1945 t.Fatalf("Did not match IDs")
1946 }
1947 if m3.Stats.Connections != 1 {
1948 t.Fatalf("Did not match connections of 1, got %d", m3.Stats.Connections)
1949 }
1950 if m3.Stats.ActiveAccounts != 1 {
1951 t.Fatalf("Did not match active accounts of 1, got %d", m3.Stats.ActiveAccounts)
1952 }
1953 if m3.Stats.Sent.Msgs < 4 {
1954 t.Fatalf("Did not match sent msgs of >= 4, got %d", m3.Stats.Sent.Msgs)
1955 }
1956 if m3.Stats.Received.Msgs < 2 {
1957 t.Fatalf("Did not match received msgs of >= 2, got %d", m3.Stats.Received.Msgs)
1958 }
1959 if lr := len(m3.Stats.Routes); lr != expectedRoutes {
1960 t.Fatalf("Expected %d routes, but got %d", expectedRoutes, lr)
1961 }
1962 for _, sr := range m3.Stats.Routes {
1963 if sr.Name != "B_SRV" {
1964 t.Fatalf("Expected server A's route to B to have Name set to %q, got %q", "B", sr.Name)
1965 }
1966 }
1967 // Increment stalls to confirm they are reported.
1968 atomic.AddInt64(&sb.stalls, 3)
1969
1970 // Now query B and check that route's name is "A"
1971 subj = fmt.Sprintf(serverStatsReqSubj, sb.ID())
1972 ncs.SubscribeSync(subj)
1973 msg, err = ncs.Request(subj, nil, time.Second)
1974 if err != nil {
1975 t.Fatalf("Error trying to request statsz: %v", err)
1976 }
1977 m = ServerStatsMsg{}
1978 if err := json.Unmarshal(msg.Data, &m); err != nil {
1979 t.Fatalf("Error unmarshalling the statz json: %v", err)
1980 }
1981 if lr := len(m.Stats.Routes); lr != expectedRoutes {
1982 t.Fatalf("Expected %d routes, but got %d", expectedRoutes, lr)
1983 }
1984 for _, sr := range m.Stats.Routes {
1985 if sr.Name != "A_SRV" {
1986 t.Fatalf("Expected server B's route to A to have Name set to %q, got %q", "A_SRV", sr.Name)
1987 }
1988 }
1989 require_Equal(t, m.Stats.StalledClients, 3)
1990 }
1991
1992 func TestServerEventsStatsZForcedBroadcastNotRateLimited(t *testing.T) {
1993 // Tests will set this generally faster, but here we want the rate limiter
1994 // to actually be active.
1995 original := statszRateLimit
1996 statszRateLimit = time.Hour
1997 defer func() { statszRateLimit = original }()
1998
1999 s, opts := runTrustedServer(t)
2000 defer s.Shutdown()
2001
2002 acc, akp := createAccount(s)
2003 require_NoError(t, s.setSystemAccount(acc))
2004
2005 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
2006 nc, err := nats.Connect(url, createUserCreds(t, s, akp))
2007 require_NoError(t, err)
2008 defer nc.Close()
2009
2010 subj := fmt.Sprintf(serverStatsSubj, s.ID())
2011
2012 // Arrange so that the rate limiter would suppress any broadcast:
2013 // stop the periodic heartbeat timer so it cannot produce a broadcast,
2014 // and set lastStatsz to "now" so we are well within the interval.
2015 s.mu.Lock()
2016 if s.sys.stmr != nil {
2017 s.sys.stmr.Stop()
2018 }
2019 s.sys.cstatsz = time.Hour
2020 s.sys.statsz = time.Hour
2021 s.sys.lastStatsz = time.Now()
2022 s.mu.Unlock()
2023
2024 // Let any inflight startup statsz goroutines finish before we subscribe,
2025 // so they cannot land in our subscription as a false positive.
2026 time.Sleep(300 * time.Millisecond)
2027
2028 // From here on the only thing that can publish to this subject is an
2029 // un-suppressed broadcast.
2030 sub, err := nc.SubscribeSync(subj)
2031 require_NoError(t, err)
2032 defer sub.Unsubscribe()
2033 require_NoError(t, nc.Flush())
2034
2035 // Re-arm the suppression window right before the request.
2036 s.mu.Lock()
2037 s.sys.lastStatsz = time.Now()
2038 s.mu.Unlock()
2039
2040 // Issue a forced (no-reply) STATSZ request. This is the path a new meta
2041 // leader uses to force an immediate broadcast. It must reset lastStatsz
2042 // and broadcast immediately even though we are within the rate-limit
2043 // interval.
2044 s.statszReq(nil, nil, nil, subj, _EMPTY_, nil, nil)
2045
2046 // Make sure it is a statsz from our server.
2047 msg, err := sub.NextMsg(2 * time.Second)
2048 require_NoError(t, err)
2049 var m ServerStatsMsg
2050 require_NoError(t, json.Unmarshal(msg.Data, &m))
2051 require_Equal(t, m.Server.ID, s.ID())
2052 require_Equal(t, m.Stats.Connections, 1)
2053 }
2054
2055 func TestServerEventsHealthZSingleServer(t *testing.T) {
2056 type healthzResp struct {
2057 Healthz HealthStatus `json:"data"`
2058 Server ServerInfo `json:"server"`
2059 }
2060 cfg := fmt.Sprintf(`listen: 127.0.0.1:-1
2061
2062 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
2063
2064 no_auth_user: one
2065
2066 accounts {
2067 ONE { users = [ { user: "one", pass: "p" } ]; jetstream: enabled }
2068 $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
2069 }`, t.TempDir())
2070
2071 serverHealthzReqSubj := "$SYS.REQ.SERVER.%s.HEALTHZ"
2072 s, _ := RunServerWithConfig(createConfFile(t, []byte(cfg)))
2073 defer s.Shutdown()
2074
2075 ncs, err := nats.Connect(s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
2076 if err != nil {
2077 t.Fatalf("Error connecting to cluster: %v", err)
2078 }
2079
2080 defer ncs.Close()
2081 ncAcc, err := nats.Connect(s.ClientURL())
2082 if err != nil {
2083 t.Fatalf("Error on connect: %v", err)
2084 }
2085 defer ncAcc.Close()
2086 js, err := ncAcc.JetStream()
2087 if err != nil {
2088 t.Fatalf("Error creating JetStream context: %v", err)
2089 }
2090 _, err = js.AddStream(&nats.StreamConfig{
2091 Name: "test",
2092 Subjects: []string{"foo"},
2093 })
2094 if err != nil {
2095 t.Fatalf("Error creating stream: %v", err)
2096 }
2097 _, err = js.AddConsumer("test", &nats.ConsumerConfig{
2098 Name: "cons",
2099 })
2100 if err != nil {
2101 t.Fatalf("Error creating consumer: %v", err)
2102 }
2103
2104 subj := fmt.Sprintf(serverHealthzReqSubj, s.ID())
2105
2106 tests := []struct {
2107 name string
2108 req *HealthzEventOptions
2109 expected HealthStatus
2110 }{
2111 {
2112 name: "no parameters",
2113 expected: HealthStatus{Status: "ok", StatusCode: 200},
2114 },
2115 {
2116 name: "with js enabled only",
2117 req: &HealthzEventOptions{
2118 HealthzOptions: HealthzOptions{
2119 JSEnabledOnly: true,
2120 },
2121 },
2122 expected: HealthStatus{Status: "ok", StatusCode: 200},
2123 },
2124 {
2125 name: "with server only",
2126 req: &HealthzEventOptions{
2127 HealthzOptions: HealthzOptions{
2128 JSServerOnly: true,
2129 },
2130 },
2131 expected: HealthStatus{Status: "ok", StatusCode: 200},
2132 },
2133 {
2134 name: "with js meta only",
2135 req: &HealthzEventOptions{
2136 HealthzOptions: HealthzOptions{
2137 JSMetaOnly: true,
2138 },
2139 },
2140 expected: HealthStatus{Status: "ok", StatusCode: 200},
2141 },
2142 {
2143 name: "with account name",
2144 req: &HealthzEventOptions{
2145 HealthzOptions: HealthzOptions{
2146 Account: "ONE",
2147 },
2148 },
2149 expected: HealthStatus{Status: "ok", StatusCode: 200},
2150 },
2151 {
2152 name: "with account name and stream",
2153 req: &HealthzEventOptions{
2154 HealthzOptions: HealthzOptions{
2155 Account: "ONE",
2156 Stream: "test",
2157 },
2158 },
2159 expected: HealthStatus{Status: "ok", StatusCode: 200},
2160 },
2161 {
2162 name: "with account name, stream and consumer",
2163 req: &HealthzEventOptions{
2164 HealthzOptions: HealthzOptions{
2165 Account: "ONE",
2166 Stream: "test",
2167 Consumer: "cons",
2168 },
2169 },
2170 expected: HealthStatus{Status: "ok", StatusCode: 200},
2171 },
2172 {
2173 name: "with stream only",
2174 req: &HealthzEventOptions{
2175 HealthzOptions: HealthzOptions{
2176 Stream: "test",
2177 },
2178 },
2179 expected: HealthStatus{
2180 Status: "error",
2181 StatusCode: 400,
2182 Error: `"account" must not be empty when checking stream health`,
2183 },
2184 },
2185 {
2186 name: "with stream only, detailed",
2187 req: &HealthzEventOptions{
2188 HealthzOptions: HealthzOptions{
2189 Details: true,
2190 Stream: "test",
2191 },
2192 },
2193 expected: HealthStatus{
2194 Status: "error",
2195 StatusCode: 400,
2196 Errors: []HealthzError{
2197 {
2198 Type: HealthzErrorBadRequest,
2199 Error: `"account" must not be empty when checking stream health`,
2200 },
2201 },
2202 },
2203 },
2204 {
2205 name: "with account and consumer",
2206 req: &HealthzEventOptions{
2207 HealthzOptions: HealthzOptions{
2208 Account: "ONE",
2209 Consumer: "cons",
2210 },
2211 },
2212 expected: HealthStatus{
2213 Status: "error",
2214 StatusCode: 400,
2215 Error: `"stream" must not be empty when checking consumer health`,
2216 },
2217 },
2218 {
2219 name: "with account and consumer, detailed",
2220 req: &HealthzEventOptions{
2221 HealthzOptions: HealthzOptions{
2222 Account: "ONE",
2223 Consumer: "cons",
2224 Details: true,
2225 },
2226 },
2227 expected: HealthStatus{
2228 Status: "error",
2229 StatusCode: 400,
2230 Errors: []HealthzError{
2231 {
2232 Type: HealthzErrorBadRequest,
2233 Error: `"stream" must not be empty when checking consumer health`,
2234 },
2235 },
2236 },
2237 },
2238 {
2239 name: "account not found",
2240 req: &HealthzEventOptions{
2241 HealthzOptions: HealthzOptions{
2242 Account: "abc",
2243 },
2244 },
2245 expected: HealthStatus{
2246 Status: "unavailable",
2247 StatusCode: 404,
2248 Error: `JetStream account "abc" not found`,
2249 },
2250 },
2251 {
2252 name: "account not found, detailed",
2253 req: &HealthzEventOptions{
2254 HealthzOptions: HealthzOptions{
2255 Account: "abc",
2256 Details: true,
2257 },
2258 },
2259 expected: HealthStatus{
2260 Status: "error",
2261 StatusCode: 404,
2262 Errors: []HealthzError{
2263 {
2264 Type: HealthzErrorAccount,
2265 Account: "abc",
2266 Error: `JetStream account "abc" not found`,
2267 },
2268 },
2269 },
2270 },
2271 {
2272 name: "stream not found",
2273 req: &HealthzEventOptions{
2274 HealthzOptions: HealthzOptions{
2275 Account: "ONE",
2276 Stream: "abc",
2277 },
2278 },
2279 expected: HealthStatus{
2280 Status: "unavailable",
2281 StatusCode: 404,
2282 Error: `JetStream stream "abc" not found on account "ONE"`,
2283 },
2284 },
2285 {
2286 name: "stream not found, detailed",
2287 req: &HealthzEventOptions{
2288 HealthzOptions: HealthzOptions{
2289 Account: "ONE",
2290 Stream: "abc",
2291 Details: true,
2292 },
2293 },
2294 expected: HealthStatus{
2295 Status: "error",
2296 StatusCode: 404,
2297 Errors: []HealthzError{
2298 {
2299 Type: HealthzErrorStream,
2300 Account: "ONE",
2301 Stream: "abc",
2302 Error: `JetStream stream "abc" not found on account "ONE"`,
2303 },
2304 },
2305 },
2306 },
2307 {
2308 name: "consumer not found",
2309 req: &HealthzEventOptions{
2310 HealthzOptions: HealthzOptions{
2311 Account: "ONE",
2312 Stream: "test",
2313 Consumer: "abc",
2314 },
2315 },
2316 expected: HealthStatus{
2317 Status: "unavailable",
2318 StatusCode: 404,
2319 Error: `JetStream consumer "abc" not found for stream "test" on account "ONE"`,
2320 },
2321 },
2322 {
2323 name: "consumer not found, detailed",
2324 req: &HealthzEventOptions{
2325 HealthzOptions: HealthzOptions{
2326 Account: "ONE",
2327 Stream: "test",
2328 Consumer: "abc",
2329 Details: true,
2330 },
2331 },
2332 expected: HealthStatus{
2333 Status: "error",
2334 StatusCode: 404,
2335 Errors: []HealthzError{
2336 {
2337 Type: HealthzErrorConsumer,
2338 Account: "ONE",
2339 Stream: "test",
2340 Consumer: "abc",
2341 Error: `JetStream consumer "abc" not found for stream "test" on account "ONE"`,
2342 },
2343 },
2344 },
2345 },
2346 }
2347 for _, test := range tests {
2348 t.Run(test.name, func(t *testing.T) {
2349 var body []byte
2350 var err error
2351 if test.req != nil {
2352 body, err = json.Marshal(test.req)
2353 if err != nil {
2354 t.Fatalf("Error marshaling request body: %v", err)
2355 }
2356 }
2357 msg, err := ncs.Request(subj, body, 1*time.Second)
2358 if err != nil {
2359 t.Fatalf("Error trying to request healthz: %v", err)
2360 }
2361 var health healthzResp
2362 if err := json.Unmarshal(msg.Data, &health); err != nil {
2363 t.Fatalf("Error unmarshalling the statz json: %v", err)
2364 }
2365 if !reflect.DeepEqual(health.Healthz, test.expected) {
2366 t.Errorf("Invalid healthz status; want: %+v; got: %+v", test.expected, health.Healthz)
2367 }
2368 })
2369 }
2370 }
2371
2372 func TestServerEventsHealthZClustered(t *testing.T) {
2373 type healthzResp struct {
2374 Healthz HealthStatus `json:"data"`
2375 Server ServerInfo `json:"server"`
2376 }
2377 serverHealthzReqSubj := "$SYS.REQ.SERVER.%s.HEALTHZ"
2378 c := createJetStreamClusterWithTemplate(t, jsClusterAccountsTempl, "JSC", 3)
2379 defer c.shutdown()
2380
2381 ncs, err := nats.Connect(c.randomServer().ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
2382 if err != nil {
2383 t.Fatalf("Error connecting to cluster: %v", err)
2384 }
2385
2386 defer ncs.Close()
2387 ncAcc, err := nats.Connect(c.randomServer().ClientURL())
2388 if err != nil {
2389 t.Fatalf("Error on connect: %v", err)
2390 }
2391 defer ncAcc.Close()
2392 js, err := ncAcc.JetStream()
2393 if err != nil {
2394 t.Fatalf("Error creating JetStream context: %v", err)
2395 }
2396 _, err = js.AddStream(&nats.StreamConfig{
2397 Name: "test",
2398 Subjects: []string{"foo"},
2399 Replicas: 3,
2400 })
2401 if err != nil {
2402 t.Fatalf("Error creating stream: %v", err)
2403 }
2404 _, err = js.AddConsumer("test", &nats.ConsumerConfig{
2405 Name: "cons",
2406 Replicas: 3,
2407 })
2408 if err != nil {
2409 t.Fatalf("Error creating consumer: %v", err)
2410 }
2411
2412 c.waitOnStreamLeader("ONE", "test")
2413 c.waitOnConsumerLeader("ONE", "test", "cons")
2414 c.waitOnAllCurrent()
2415
2416 subj := fmt.Sprintf(serverHealthzReqSubj, c.servers[0].ID())
2417 pingSubj := fmt.Sprintf(serverHealthzReqSubj, "PING")
2418
2419 tests := []struct {
2420 name string
2421 req *HealthzEventOptions
2422 expected HealthStatus
2423 expectedError string
2424 }{
2425 {
2426 name: "no parameters",
2427 expected: HealthStatus{Status: "ok", StatusCode: 200},
2428 },
2429 {
2430 name: "with js enabled only",
2431 req: &HealthzEventOptions{
2432 HealthzOptions: HealthzOptions{
2433 JSEnabledOnly: true,
2434 },
2435 },
2436 expected: HealthStatus{Status: "ok", StatusCode: 200},
2437 },
2438 {
2439 name: "with server only",
2440 req: &HealthzEventOptions{
2441 HealthzOptions: HealthzOptions{
2442 JSServerOnly: true,
2443 },
2444 },
2445 expected: HealthStatus{Status: "ok", StatusCode: 200},
2446 },
2447 {
2448 name: "with account name",
2449 req: &HealthzEventOptions{
2450 HealthzOptions: HealthzOptions{
2451 Account: "ONE",
2452 },
2453 },
2454 expected: HealthStatus{Status: "ok", StatusCode: 200},
2455 },
2456 {
2457 name: "with account name and stream",
2458 req: &HealthzEventOptions{
2459 HealthzOptions: HealthzOptions{
2460 Account: "ONE",
2461 Stream: "test",
2462 },
2463 },
2464 expected: HealthStatus{Status: "ok", StatusCode: 200},
2465 },
2466 {
2467 name: "with account name, stream and consumer",
2468 req: &HealthzEventOptions{
2469 HealthzOptions: HealthzOptions{
2470 Account: "ONE",
2471 Stream: "test",
2472 Consumer: "cons",
2473 },
2474 },
2475 expected: HealthStatus{Status: "ok", StatusCode: 200},
2476 },
2477 {
2478 name: "with stream only",
2479 req: &HealthzEventOptions{
2480 HealthzOptions: HealthzOptions{
2481 Stream: "test",
2482 },
2483 },
2484 expected: HealthStatus{
2485 Status: "error",
2486 StatusCode: 400,
2487 Error: `"account" must not be empty when checking stream health`,
2488 },
2489 expectedError: "Bad request:",
2490 },
2491 {
2492 name: "with stream only, detailed",
2493 req: &HealthzEventOptions{
2494 HealthzOptions: HealthzOptions{
2495 Details: true,
2496 Stream: "test",
2497 },
2498 },
2499 expected: HealthStatus{
2500 Status: "error",
2501 StatusCode: 400,
2502 Errors: []HealthzError{
2503 {
2504 Type: HealthzErrorBadRequest,
2505 Error: `"account" must not be empty when checking stream health`,
2506 },
2507 },
2508 },
2509 },
2510 {
2511 name: "account not found",
2512 req: &HealthzEventOptions{
2513 HealthzOptions: HealthzOptions{
2514 Account: "abc",
2515 },
2516 },
2517 expected: HealthStatus{
2518 Status: "unavailable",
2519 StatusCode: 404,
2520 Error: `JetStream account "abc" not found`,
2521 },
2522 expectedError: `account "abc" not found`,
2523 },
2524 {
2525 name: "account not found, detailed",
2526 req: &HealthzEventOptions{
2527 HealthzOptions: HealthzOptions{
2528 Account: "abc",
2529 Details: true,
2530 },
2531 },
2532 expected: HealthStatus{
2533 Status: "error",
2534 StatusCode: 404,
2535 Errors: []HealthzError{
2536 {
2537 Type: HealthzErrorAccount,
2538 Account: "abc",
2539 Error: `JetStream account "abc" not found`,
2540 },
2541 },
2542 },
2543 },
2544 {
2545 name: "stream not found",
2546 req: &HealthzEventOptions{
2547 HealthzOptions: HealthzOptions{
2548 Account: "ONE",
2549 Stream: "abc",
2550 },
2551 },
2552 expected: HealthStatus{
2553 Status: "unavailable",
2554 StatusCode: 404,
2555 Error: `JetStream stream "abc" not found on account "ONE"`,
2556 },
2557 expectedError: `stream "abc" not found`,
2558 },
2559 {
2560 name: "stream not found, detailed",
2561 req: &HealthzEventOptions{
2562 HealthzOptions: HealthzOptions{
2563 Account: "ONE",
2564 Stream: "abc",
2565 Details: true,
2566 },
2567 },
2568 expected: HealthStatus{
2569 Status: "error",
2570 StatusCode: 404,
2571 Errors: []HealthzError{
2572 {
2573 Type: HealthzErrorStream,
2574 Account: "ONE",
2575 Stream: "abc",
2576 Error: `JetStream stream "abc" not found on account "ONE"`,
2577 },
2578 },
2579 },
2580 },
2581 {
2582 name: "consumer not found",
2583 req: &HealthzEventOptions{
2584 HealthzOptions: HealthzOptions{
2585 Account: "ONE",
2586 Stream: "test",
2587 Consumer: "abc",
2588 },
2589 },
2590 expected: HealthStatus{
2591 Status: "unavailable",
2592 StatusCode: 404,
2593 Error: `JetStream consumer "abc" not found for stream "test" on account "ONE"`,
2594 },
2595 expectedError: `consumer "abc" not found for stream "test"`,
2596 },
2597 {
2598 name: "consumer not found, detailed",
2599 req: &HealthzEventOptions{
2600 HealthzOptions: HealthzOptions{
2601 Account: "ONE",
2602 Stream: "test",
2603 Consumer: "abc",
2604 Details: true,
2605 },
2606 },
2607 expected: HealthStatus{
2608 Status: "error",
2609 StatusCode: 404,
2610 Errors: []HealthzError{
2611 {
2612 Type: HealthzErrorConsumer,
2613 Account: "ONE",
2614 Stream: "test",
2615 Consumer: "abc",
2616 Error: `JetStream consumer "abc" not found for stream "test" on account "ONE"`,
2617 },
2618 },
2619 },
2620 },
2621 }
2622 for _, test := range tests {
2623 t.Run(test.name, func(t *testing.T) {
2624 var body []byte
2625 var err error
2626 if test.req != nil {
2627 body, err = json.Marshal(test.req)
2628 if err != nil {
2629 t.Fatalf("Error marshaling request body: %v", err)
2630 }
2631 }
2632 msg, err := ncs.Request(subj, body, 1*time.Second)
2633 if err != nil {
2634 t.Fatalf("Error trying to request healthz: %v", err)
2635 }
2636 var health healthzResp
2637 if err := json.Unmarshal(msg.Data, &health); err != nil {
2638 t.Fatalf("Error unmarshalling the statz json: %v", err)
2639 }
2640 if !reflect.DeepEqual(health.Healthz, test.expected) {
2641 t.Errorf("Invalid healthz status; want: %+v; got: %+v", test.expected, health.Healthz)
2642 }
2643
2644 reply := ncs.NewRespInbox()
2645 sub, err := ncs.SubscribeSync(reply)
2646 if err != nil {
2647 t.Fatalf("Error creating subscription: %v", err)
2648 }
2649 defer sub.Unsubscribe()
2650
2651 // now PING all servers
2652 if err := ncs.PublishRequest(pingSubj, reply, body); err != nil {
2653 t.Fatalf("Publish error: %v", err)
2654 }
2655 for i := 0; i < 3; i++ {
2656 msg, err := sub.NextMsg(1 * time.Second)
2657 if err != nil {
2658 t.Fatalf("Error fetching healthz PING response: %v", err)
2659 }
2660 var health healthzResp
2661 if err := json.Unmarshal(msg.Data, &health); err != nil {
2662 t.Fatalf("Error unmarshalling the statz json: %v", err)
2663 }
2664 if !reflect.DeepEqual(health.Healthz, test.expected) {
2665 t.Errorf("Invalid healthz status; want: %+v; got: %+v", test.expected, health.Healthz)
2666 }
2667 }
2668 if _, err := sub.NextMsg(50 * time.Millisecond); !errors.Is(err, nats.ErrTimeout) {
2669 t.Fatalf("Expected timeout error; got: %v", err)
2670 }
2671 })
2672 }
2673 }
2674
2675 func TestServerEventsHealthZClustered_NoReplicas(t *testing.T) {
2676 type healthzResp struct {
2677 Healthz HealthStatus `json:"data"`
2678 Server ServerInfo `json:"server"`
2679 }
2680 serverHealthzReqSubj := "$SYS.REQ.SERVER.%s.HEALTHZ"
2681 c := createJetStreamClusterWithTemplate(t, jsClusterAccountsTempl, "JSC", 3)
2682 defer c.shutdown()
2683
2684 ncs, err := nats.Connect(c.randomServer().ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
2685 if err != nil {
2686 t.Fatalf("Error connecting to cluster: %v", err)
2687 }
2688
2689 defer ncs.Close()
2690 ncAcc, err := nats.Connect(c.randomServer().ClientURL())
2691 if err != nil {
2692 t.Fatalf("Error on connect: %v", err)
2693 }
2694 defer ncAcc.Close()
2695 js, err := ncAcc.JetStream()
2696 if err != nil {
2697 t.Fatalf("Error creating JetStream context: %v", err)
2698 }
2699
2700 pingSubj := fmt.Sprintf(serverHealthzReqSubj, "PING")
2701
2702 t.Run("non-replicated stream", func(t *testing.T) {
2703 _, err = js.AddStream(&nats.StreamConfig{
2704 Name: "test",
2705 Subjects: []string{"foo"},
2706 })
2707 if err != nil {
2708 t.Fatalf("Error creating stream: %v", err)
2709 }
2710 _, err = js.AddConsumer("test", &nats.ConsumerConfig{
2711 Name: "cons",
2712 })
2713 if err != nil {
2714 t.Fatalf("Error creating consumer: %v", err)
2715 }
2716 body, err := json.Marshal(HealthzEventOptions{
2717 HealthzOptions: HealthzOptions{
2718 Account: "ONE",
2719 Stream: "test",
2720 },
2721 })
2722 if err != nil {
2723 t.Fatalf("Error marshaling request body: %v", err)
2724 }
2725
2726 reply := ncs.NewRespInbox()
2727 sub, err := ncs.SubscribeSync(reply)
2728 if err != nil {
2729 t.Fatalf("Error creating subscription: %v", err)
2730 }
2731 defer sub.Unsubscribe()
2732
2733 // now PING all servers
2734 if err := ncs.PublishRequest(pingSubj, reply, body); err != nil {
2735 t.Fatalf("Publish error: %v", err)
2736 }
2737 var healthy int
2738 for i := 0; i < 3; i++ {
2739 msg, err := sub.NextMsg(1 * time.Second)
2740 if err != nil {
2741 t.Fatalf("Error fetching healthz PING response: %v", err)
2742 }
2743 var health healthzResp
2744 if err := json.Unmarshal(msg.Data, &health); err != nil {
2745 t.Fatalf("Error unmarshalling the statz json: %v", err)
2746 }
2747 if health.Healthz.Status == "ok" {
2748 healthy++
2749 continue
2750 }
2751 if !strings.Contains(health.Healthz.Error, `stream "test" not found`) {
2752 t.Errorf("Expected error to contain: %q, got: %s", `stream "test" not found`, health.Healthz.Error)
2753 }
2754 }
2755 if healthy != 1 {
2756 t.Fatalf("Expected 1 healthy server; got: %d", healthy)
2757 }
2758 if _, err := sub.NextMsg(50 * time.Millisecond); !errors.Is(err, nats.ErrTimeout) {
2759 t.Fatalf("Expected timeout error; got: %v", err)
2760 }
2761 })
2762
2763 t.Run("non-replicated consumer", func(t *testing.T) {
2764 _, err = js.AddStream(&nats.StreamConfig{
2765 Name: "test-repl",
2766 Subjects: []string{"bar"},
2767 Replicas: 3,
2768 })
2769 if err != nil {
2770 t.Fatalf("Error creating stream: %v", err)
2771 }
2772 _, err = js.AddConsumer("test-repl", &nats.ConsumerConfig{
2773 Name: "cons-single",
2774 })
2775 if err != nil {
2776 t.Fatalf("Error creating consumer: %v", err)
2777 }
2778 body, err := json.Marshal(HealthzEventOptions{
2779 HealthzOptions: HealthzOptions{
2780 Account: "ONE",
2781 Stream: "test-repl",
2782 Consumer: "cons-single",
2783 },
2784 })
2785 if err != nil {
2786 t.Fatalf("Error marshaling request body: %v", err)
2787 }
2788
2789 reply := ncs.NewRespInbox()
2790 sub, err := ncs.SubscribeSync(reply)
2791 if err != nil {
2792 t.Fatalf("Error creating subscription: %v", err)
2793 }
2794 defer sub.Unsubscribe()
2795
2796 // now PING all servers
2797 if err := ncs.PublishRequest(pingSubj, reply, body); err != nil {
2798 t.Fatalf("Publish error: %v", err)
2799 }
2800 var healthy int
2801 for i := 0; i < 3; i++ {
2802 msg, err := sub.NextMsg(1 * time.Second)
2803 if err != nil {
2804 t.Fatalf("Error fetching healthz PING response: %v", err)
2805 }
2806 var health healthzResp
2807 if err := json.Unmarshal(msg.Data, &health); err != nil {
2808 t.Fatalf("Error unmarshalling the statz json: %v", err)
2809 }
2810 if health.Healthz.Status == "ok" {
2811 healthy++
2812 continue
2813 }
2814 if !strings.Contains(health.Healthz.Error, `consumer "cons-single" not found`) {
2815 t.Errorf("Expected error to contain: %q, got: %s", `consumer "cons-single" not found`, health.Healthz.Error)
2816 }
2817 }
2818 if healthy != 1 {
2819 t.Fatalf("Expected 1 healthy server; got: %d", healthy)
2820 }
2821 if _, err := sub.NextMsg(50 * time.Millisecond); !errors.Is(err, nats.ErrTimeout) {
2822 t.Fatalf("Expected timeout error; got: %v", err)
2823 }
2824 })
2825
2826 }
2827
2828 func TestServerEventsHealthZJetStreamNotEnabled(t *testing.T) {
2829 type healthzResp struct {
2830 Healthz HealthStatus `json:"data"`
2831 Server ServerInfo `json:"server"`
2832 }
2833 cfg := `listen: 127.0.0.1:-1
2834
2835 accounts {
2836 $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
2837 }`
2838
2839 serverHealthzReqSubj := "$SYS.REQ.SERVER.%s.HEALTHZ"
2840 s, _ := RunServerWithConfig(createConfFile(t, []byte(cfg)))
2841 defer s.Shutdown()
2842
2843 ncs, err := nats.Connect(s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
2844 if err != nil {
2845 t.Fatalf("Error connecting to cluster: %v", err)
2846 }
2847
2848 defer ncs.Close()
2849
2850 subj := fmt.Sprintf(serverHealthzReqSubj, s.ID())
2851
2852 msg, err := ncs.Request(subj, nil, 1*time.Second)
2853 if err != nil {
2854 t.Fatalf("Error trying to request healthz: %v", err)
2855 }
2856 var health healthzResp
2857 if err := json.Unmarshal(msg.Data, &health); err != nil {
2858 t.Fatalf("Error unmarshalling the statz json: %v", err)
2859 }
2860 if health.Healthz.Status != "ok" {
2861 t.Errorf("Invalid healthz status; want: %q; got: %q", "ok", health.Healthz.Status)
2862 }
2863 if health.Healthz.Error != "" {
2864 t.Errorf("HealthZ error: %s", health.Healthz.Error)
2865 }
2866 }
2867
2868 func TestServerEventsPingStatsZ(t *testing.T) {
2869 sa, _, sb, optsB, akp := runTrustedCluster(t)
2870 defer sa.Shutdown()
2871 defer sb.Shutdown()
2872 url := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
2873 nc, err := nats.Connect(url, createUserCreds(t, sb, akp))
2874 if err != nil {
2875 t.Fatalf("Error on connect: %v", err)
2876 }
2877 defer nc.Close()
2878 test := func(req []byte) {
2879 reply := nc.NewRespInbox()
2880 sub, _ := nc.SubscribeSync(reply)
2881 nc.PublishRequest(serverStatsPingReqSubj, reply, req)
2882 // Make sure its a statsz
2883 m := ServerStatsMsg{}
2884 // Receive both manually.
2885 msg, err := sub.NextMsg(time.Second)
2886 if err != nil {
2887 t.Fatalf("Error receiving msg: %v", err)
2888 }
2889 if err := json.Unmarshal(msg.Data, &m); err != nil {
2890 t.Fatalf("Error unmarshalling the statz json: %v", err)
2891 }
2892 msg, err = sub.NextMsg(time.Second)
2893 if err != nil {
2894 t.Fatalf("Error receiving msg: %v", err)
2895 }
2896 if err := json.Unmarshal(msg.Data, &m); err != nil {
2897 t.Fatalf("Error unmarshalling the statz json: %v", err)
2898 }
2899 }
2900 strRequestTbl := []string{
2901 `{"cluster":"TEST"}`,
2902 `{"cluster":"CLUSTER"}`,
2903 `{"server_name":"SRV"}`,
2904 `{"server_name":"_"}`,
2905 fmt.Sprintf(`{"host":"%s"}`, optsB.Host),
2906 fmt.Sprintf(`{"host":"%s", "cluster":"CLUSTER", "name":"SRV"}`, optsB.Host),
2907 }
2908 for i, opt := range strRequestTbl {
2909 t.Run(fmt.Sprintf("%s-%d", t.Name(), i), func(t *testing.T) {
2910 test([]byte(opt))
2911 })
2912 }
2913 requestTbl := []StatszEventOptions{
2914 {EventFilterOptions: EventFilterOptions{Cluster: "TEST"}},
2915 {EventFilterOptions: EventFilterOptions{Cluster: "CLUSTER"}},
2916 {EventFilterOptions: EventFilterOptions{Name: "SRV"}},
2917 {EventFilterOptions: EventFilterOptions{Name: "_"}},
2918 {EventFilterOptions: EventFilterOptions{Host: optsB.Host}},
2919 {EventFilterOptions: EventFilterOptions{Host: optsB.Host, Cluster: "CLUSTER", Name: "SRV"}},
2920 }
2921 for i, opt := range requestTbl {
2922 t.Run(fmt.Sprintf("%s-%d", t.Name(), i), func(t *testing.T) {
2923 msg, _ := json.MarshalIndent(&opt, "", " ")
2924 test(msg)
2925 })
2926 }
2927 }
2928
2929 func TestServerEventsPingStatsZDedicatedRecvQ(t *testing.T) {
2930 sa, _, sb, optsB, akp := runTrustedCluster(t)
2931 defer sa.Shutdown()
2932 defer sb.Shutdown()
2933 url := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
2934 nc, err := nats.Connect(url, createUserCreds(t, sb, akp))
2935 require_NoError(t, err)
2936 defer nc.Close()
2937 // We need to wait a little bit for the $SYS.SERVER.ACCOUNT.%s.CONNS
2938 // event to be pushed in the mux'ed queue.
2939 time.Sleep(300 * time.Millisecond)
2940
2941 testReq := func(t *testing.T, subj string, expectTwo bool) {
2942 for _, s := range []*Server{sa, sb} {
2943 s.mu.RLock()
2944 recvq := s.sys.recvq
2945 s.mu.RUnlock()
2946 recvq.Lock()
2947 defer recvq.Unlock()
2948 }
2949 reply := nc.NewRespInbox()
2950 sub := natsSubSync(t, nc, reply)
2951 nc.PublishRequest(subj, reply, nil)
2952 msg := natsNexMsg(t, sub, time.Second)
2953 if len(msg.Data) == 0 {
2954 t.Fatal("Unexpected empty response")
2955 }
2956 // Make sure its a statsz
2957 m := ServerStatsMsg{}
2958 err := json.Unmarshal(msg.Data, &m)
2959 require_NoError(t, err)
2960 require_False(t, m.Stats.Start.IsZero())
2961 if expectTwo {
2962 msg = natsNexMsg(t, sub, time.Second)
2963 err = json.Unmarshal(msg.Data, &m)
2964 require_NoError(t, err)
2965 require_False(t, m.Stats.Start.IsZero())
2966 }
2967 }
2968 const statsz = "STATSZ"
2969 for _, test := range []struct {
2970 name string
2971 f func() string
2972 expectTwo bool
2973 }{
2974 {"server stats ping request subject", func() string { return serverStatsPingReqSubj }, true},
2975 {"server ping request subject", func() string { return fmt.Sprintf(serverPingReqSubj, statsz) }, true},
2976 {"server a direct request subject", func() string { return fmt.Sprintf(serverDirectReqSubj, sa.ID(), statsz) }, false},
2977 {"server b direct request subject", func() string { return fmt.Sprintf(serverDirectReqSubj, sb.ID(), statsz) }, false},
2978 } {
2979 t.Run(test.name, func(t *testing.T) {
2980 testReq(t, test.f(), test.expectTwo)
2981 })
2982 }
2983 }
2984
2985 func TestServerEventsPingStatsZFilter(t *testing.T) {
2986 sa, _, sb, optsB, akp := runTrustedCluster(t)
2987 defer sa.Shutdown()
2988 defer sb.Shutdown()
2989
2990 url := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
2991 nc, err := nats.Connect(url, createUserCreds(t, sb, akp))
2992 if err != nil {
2993 t.Fatalf("Error on connect: %v", err)
2994 }
2995 defer nc.Close()
2996
2997 requestTbl := []string{
2998 `{"cluster":"DOESNOTEXIST"}`,
2999 `{"host":"DOESNOTEXIST"}`,
3000 `{"server_name":"DOESNOTEXIST"}`,
3001 }
3002 for i, msg := range requestTbl {
3003 t.Run(fmt.Sprintf("%s-%d", t.Name(), i), func(t *testing.T) {
3004 // Receive both manually.
3005 if _, err := nc.Request(serverStatsPingReqSubj, []byte(msg), time.Second/4); err != nats.ErrTimeout {
3006 t.Fatalf("Error, expected timeout: %v", err)
3007 }
3008 })
3009 }
3010 requestObjTbl := []EventFilterOptions{
3011 {Cluster: "DOESNOTEXIST"},
3012 {Host: "DOESNOTEXIST"},
3013 {Name: "DOESNOTEXIST"},
3014 }
3015 for i, opt := range requestObjTbl {
3016 t.Run(fmt.Sprintf("%s-%d", t.Name(), i), func(t *testing.T) {
3017 msg, _ := json.MarshalIndent(&opt, "", " ")
3018 // Receive both manually.
3019 if _, err := nc.Request(serverStatsPingReqSubj, []byte(msg), time.Second/4); err != nats.ErrTimeout {
3020 t.Fatalf("Error, expected timeout: %v", err)
3021 }
3022 })
3023 }
3024 }
3025
3026 func TestServerEventsPingStatsZFailFilter(t *testing.T) {
3027 sa, _, sb, optsB, akp := runTrustedCluster(t)
3028 defer sa.Shutdown()
3029 defer sb.Shutdown()
3030
3031 url := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
3032 nc, err := nats.Connect(url, createUserCreds(t, sb, akp))
3033 if err != nil {
3034 t.Fatalf("Error on connect: %v", err)
3035 }
3036 defer nc.Close()
3037
3038 // Receive both manually.
3039 if msg, err := nc.Request(serverStatsPingReqSubj, []byte(`{MALFORMEDJSON`), time.Second/4); err != nil {
3040 t.Fatalf("Error: %v", err)
3041 } else {
3042 resp := make(map[string]map[string]any)
3043 if err := json.Unmarshal(msg.Data, &resp); err != nil {
3044 t.Fatalf("Error unmarshalling the response json: %v", err)
3045 }
3046 if resp["error"]["code"].(float64) != http.StatusBadRequest {
3047 t.Fatal("bad error code")
3048 }
3049 }
3050 }
3051
3052 func TestServerEventsPingMonitorz(t *testing.T) {
3053 sa, _, sb, optsB, akp := runTrustedCluster(t)
3054 defer sa.Shutdown()
3055 defer sb.Shutdown()
3056 sysAcc, _ := akp.PublicKey()
3057 url := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
3058 nc, err := nats.Connect(url, createUserCreds(t, sb, akp))
3059 if err != nil {
3060 t.Fatalf("Error on connect: %v", err)
3061 }
3062 defer nc.Close()
3063
3064 nc.Flush()
3065
3066 tests := []struct {
3067 endpoint string
3068 opt any
3069 resp any
3070 respField []string
3071 }{
3072 {"VARZ", nil, &Varz{},
3073 []string{"now", "cpu", "system_account"}},
3074 {"SUBSZ", nil, &Subsz{},
3075 []string{"num_subscriptions", "num_cache"}},
3076 {"CONNZ", nil, &Connz{},
3077 []string{"now", "connections"}},
3078 {"ROUTEZ", nil, &Routez{},
3079 []string{"now", "routes"}},
3080 {"GATEWAYZ", nil, &Gatewayz{},
3081 []string{"now", "outbound_gateways", "inbound_gateways"}},
3082 {"LEAFZ", nil, &Leafz{},
3083 []string{"now", "leafs"}},
3084
3085 {"SUBSZ", &SubszOptions{}, &Subsz{},
3086 []string{"num_subscriptions", "num_cache"}},
3087 {"CONNZ", &ConnzOptions{}, &Connz{},
3088 []string{"now", "connections"}},
3089 {"ROUTEZ", &RoutezOptions{}, &Routez{},
3090 []string{"now", "routes"}},
3091 {"GATEWAYZ", &GatewayzOptions{}, &Gatewayz{},
3092 []string{"now", "outbound_gateways", "inbound_gateways"}},
3093 {"LEAFZ", &LeafzOptions{}, &Leafz{},
3094 []string{"now", "leafs"}},
3095 {"ACCOUNTZ", &AccountzOptions{}, &Accountz{},
3096 []string{"now", "accounts"}},
3097
3098 {"SUBSZ", &SubszOptions{Limit: 5}, &Subsz{},
3099 []string{"num_subscriptions", "num_cache"}},
3100 {"CONNZ", &ConnzOptions{Limit: 5}, &Connz{},
3101 []string{"now", "connections"}},
3102 {"ROUTEZ", &RoutezOptions{SubscriptionsDetail: true}, &Routez{},
3103 []string{"now", "routes"}},
3104 {"GATEWAYZ", &GatewayzOptions{Accounts: true}, &Gatewayz{},
3105 []string{"now", "outbound_gateways", "inbound_gateways"}},
3106 {"LEAFZ", &LeafzOptions{Subscriptions: true}, &Leafz{},
3107 []string{"now", "leafs"}},
3108 {"ACCOUNTZ", &AccountzOptions{Account: sysAcc}, &Accountz{},
3109 []string{"now", "account_detail"}},
3110 {"LEAFZ", &LeafzOptions{Account: sysAcc}, &Leafz{},
3111 []string{"now", "leafs"}},
3112
3113 {"ROUTEZ", json.RawMessage(`{"cluster":""}`), &Routez{},
3114 []string{"now", "routes"}},
3115 {"ROUTEZ", json.RawMessage(`{"name":""}`), &Routez{},
3116 []string{"now", "routes"}},
3117 {"ROUTEZ", json.RawMessage(`{"cluster":"TEST_CLUSTER_22"}`), &Routez{},
3118 []string{"now", "routes"}},
3119 {"ROUTEZ", json.RawMessage(`{"cluster":"CLUSTER"}`), &Routez{},
3120 []string{"now", "routes"}},
3121 {"ROUTEZ", json.RawMessage(`{"cluster":"TEST_CLUSTER_22", "subscriptions":true}`), &Routez{},
3122 []string{"now", "routes"}},
3123
3124 {"JSZ", nil, &JSzOptions{}, []string{"now", "disabled"}},
3125
3126 {"HEALTHZ", nil, &JSzOptions{}, []string{"status"}},
3127 {"HEALTHZ", &HealthzOptions{JSEnabledOnly: true}, &JSzOptions{}, []string{"status"}},
3128 {"HEALTHZ", &HealthzOptions{JSServerOnly: true}, &JSzOptions{}, []string{"status"}},
3129 {"HEALTHZ", &HealthzOptions{JSMetaOnly: true}, &JSzOptions{}, []string{"status"}},
3130 {"EXPVARZ", nil, &ExpvarzStatus{}, []string{"memstats", "cmdline"}},
3131 }
3132
3133 for i, test := range tests {
3134 t.Run(fmt.Sprintf("%s-%d", test.endpoint, i), func(t *testing.T) {
3135 var opt []byte
3136 if test.opt != nil {
3137 opt, err = json.Marshal(test.opt)
3138 if err != nil {
3139 t.Fatalf("Error marshaling opts: %v", err)
3140 }
3141 }
3142 reply := nc.NewRespInbox()
3143 replySubj, _ := nc.SubscribeSync(reply)
3144
3145 // set a header to make sure request parsing knows to ignore them
3146 nc.PublishMsg(&nats.Msg{
3147 Subject: fmt.Sprintf("%s.%s", serverStatsPingReqSubj, test.endpoint),
3148 Reply: reply,
3149 Header: nats.Header{"header": []string{"for header sake"}},
3150 Data: opt,
3151 })
3152
3153 // Receive both manually.
3154 msg, err := replySubj.NextMsg(time.Second)
3155 if err != nil {
3156 t.Fatalf("Error receiving msg: %v", err)
3157 }
3158 response1 := make(map[string]map[string]any)
3159
3160 if err := json.Unmarshal(msg.Data, &response1); err != nil {
3161 t.Fatalf("Error unmarshalling response1 json: %v", err)
3162 }
3163
3164 serverName := ""
3165 if response1["server"]["name"] == "A_SRV" {
3166 serverName = "B_SRV"
3167 } else if response1["server"]["name"] == "B_SRV" {
3168 serverName = "A_SRV"
3169 } else {
3170 t.Fatalf("Error finding server in %s", string(msg.Data))
3171 }
3172 if resp, ok := response1["data"]; !ok {
3173 t.Fatalf("Error finding: %s in %s",
3174 strings.ToLower(test.endpoint), string(msg.Data))
3175 } else {
3176 for _, respField := range test.respField {
3177 if _, ok := resp[respField]; !ok {
3178 t.Fatalf("Error finding: %s in %s", respField, resp)
3179 }
3180 }
3181 }
3182
3183 msg, err = replySubj.NextMsg(time.Second)
3184 if err != nil {
3185 t.Fatalf("Error receiving msg: %v", err)
3186 }
3187 response2 := make(map[string]map[string]any)
3188 if err := json.Unmarshal(msg.Data, &response2); err != nil {
3189 t.Fatalf("Error unmarshalling the response2 json: %v", err)
3190 }
3191 if response2["server"]["name"] != serverName {
3192 t.Fatalf("Error finding server %s in %s", serverName, string(msg.Data))
3193 }
3194 if resp, ok := response2["data"]; !ok {
3195 t.Fatalf("Error finding: %s in %s",
3196 strings.ToLower(test.endpoint), string(msg.Data))
3197 } else {
3198 for _, respField := range test.respField {
3199 if val, ok := resp[respField]; !ok {
3200 t.Fatalf("Error finding: %s in %s", respField, resp)
3201 } else if val == nil {
3202 t.Fatalf("Nil value found: %s in %s", respField, resp)
3203 }
3204 }
3205 }
3206 })
3207 }
3208 }
3209
3210 func TestGatewayNameClientInfo(t *testing.T) {
3211 sa, _, sb, _, _ := runTrustedCluster(t)
3212 defer sa.Shutdown()
3213 defer sb.Shutdown()
3214
3215 c, _, l := newClientForServer(sa)
3216 defer c.close()
3217
3218 var info Info
3219 err := json.Unmarshal([]byte(l[5:]), &info)
3220 if err != nil {
3221 t.Fatalf("Could not parse INFO json: %v\n", err)
3222 }
3223 if info.Cluster != "TEST_CLUSTER_22" {
3224 t.Fatalf("Expected a cluster name of 'TEST_CLUSTER_22', got %q", info.Cluster)
3225 }
3226 }
3227
3228 type slowAccResolver struct {
3229 sync.Mutex
3230 AccountResolver
3231 acc string
3232 }
3233
3234 func (sr *slowAccResolver) Fetch(name string) (string, error) {
3235 sr.Lock()
3236 delay := sr.acc == name
3237 sr.Unlock()
3238 if delay {
3239 time.Sleep(200 * time.Millisecond)
3240 }
3241 return sr.AccountResolver.Fetch(name)
3242 }
3243
3244 func TestConnectionUpdatesTimerProperlySet(t *testing.T) {
3245 origEventsHBInterval := eventsHBInterval
3246 eventsHBInterval = 50 * time.Millisecond
3247 defer func() { eventsHBInterval = origEventsHBInterval }()
3248
3249 sa, _, sb, optsB, _ := runTrustedCluster(t)
3250 defer sa.Shutdown()
3251 defer sb.Shutdown()
3252
3253 // Normal Account
3254 okp, _ := nkeys.FromSeed(oSeed)
3255 akp, _ := nkeys.CreateAccount()
3256 pub, _ := akp.PublicKey()
3257 nac := jwt.NewAccountClaims(pub)
3258 nac.Limits.Conn = 10 // set any limit...
3259 jwt, _ := nac.Encode(okp)
3260
3261 addAccountToMemResolver(sa, pub, jwt)
3262
3263 // Listen for HB updates...
3264 count := int32(0)
3265 cb := func(sub *subscription, _ *client, _ *Account, subject, reply string, msg []byte) {
3266 atomic.AddInt32(&count, 1)
3267 }
3268 subj := fmt.Sprintf(accConnsEventSubjNew, pub)
3269 sub, err := sa.sysSubscribe(subj, cb)
3270 if sub == nil || err != nil {
3271 t.Fatalf("Expected to subscribe, got %v", err)
3272 }
3273 defer sa.sysUnsubscribe(sub)
3274
3275 url := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
3276 nc := natsConnect(t, url, createUserCreds(t, sb, akp))
3277 defer nc.Close()
3278
3279 time.Sleep(500 * time.Millisecond)
3280 // After waiting 500ms with HB interval of 50ms, we should get
3281 // about 10 updates, no much more
3282 if n := atomic.LoadInt32(&count); n > 15 {
3283 t.Fatalf("Expected about 10 updates, got %v", n)
3284 }
3285
3286 // Now lookup the account doing the events on sb.
3287 acc, _ := sb.LookupAccount(pub)
3288 // Make sure we have the timer running.
3289 acc.mu.RLock()
3290 ctmr := acc.ctmr
3291 acc.mu.RUnlock()
3292 if ctmr == nil {
3293 t.Fatalf("Expected event timer for acc conns to be running")
3294 }
3295
3296 nc.Close()
3297
3298 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
3299 // Make sure we have the timer is NOT running.
3300 acc.mu.RLock()
3301 ctmr = acc.ctmr
3302 acc.mu.RUnlock()
3303 if ctmr != nil {
3304 return fmt.Errorf("Expected event timer for acc conns to NOT be running after reaching zero local clients")
3305 }
3306 return nil
3307 })
3308 }
3309
3310 func TestServerEventsReceivedByQSubs(t *testing.T) {
3311 s, opts := runTrustedServer(t)
3312 defer s.Shutdown()
3313
3314 acc, akp := createAccount(s)
3315 s.setSystemAccount(acc)
3316
3317 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
3318 ncs, err := nats.Connect(url, createUserCreds(t, s, akp))
3319 if err != nil {
3320 t.Fatalf("Error on connect: %v", err)
3321 }
3322 defer ncs.Close()
3323
3324 // Listen for auth error events.
3325 qsub, _ := ncs.QueueSubscribeSync("$SYS.SERVER.*.CLIENT.AUTH.ERR", "queue")
3326 defer qsub.Unsubscribe()
3327
3328 ncs.Flush()
3329
3330 nats.Connect(url, nats.Name("TEST BAD LOGIN"))
3331
3332 m, err := qsub.NextMsg(time.Second)
3333 if err != nil {
3334 t.Fatalf("Should have heard an auth error event")
3335 }
3336 dem := DisconnectEventMsg{}
3337 if err := json.Unmarshal(m.Data, &dem); err != nil {
3338 t.Fatalf("Error unmarshalling disconnect event message: %v", err)
3339 }
3340 if dem.Reason != "Authentication Failure" {
3341 t.Fatalf("Expected auth error, got %q", dem.Reason)
3342 }
3343 }
3344
3345 func TestServerEventsFilteredByTag(t *testing.T) {
3346 confA := createConfFile(t, []byte(`
3347 listen: -1
3348 server_name: srv-A
3349 server_tags: ["foo", "bar"]
3350 cluster {
3351 name: clust
3352 listen: -1
3353 no_advertise: true
3354 }
3355 system_account: SYS
3356 accounts: {
3357 SYS: {
3358 users: [
3359 {user: b, password: b}
3360 ]
3361 }
3362 }
3363 no_auth_user: b
3364 `))
3365 sA, _ := RunServerWithConfig(confA)
3366 defer sA.Shutdown()
3367 confB := createConfFile(t, []byte(fmt.Sprintf(`
3368 listen: -1
3369 server_name: srv-B
3370 server_tags: ["bar", "baz"]
3371 cluster {
3372 name: clust
3373 listen: -1
3374 no_advertise: true
3375 routes [
3376 nats-route://127.0.0.1:%d
3377 ]
3378 }
3379 system_account: SYS
3380 accounts: {
3381 SYS: {
3382 users: [
3383 {user: b, password: b}
3384 ]
3385 }
3386 }
3387 no_auth_user: b
3388 `, sA.opts.Cluster.Port)))
3389 sB, _ := RunServerWithConfig(confB)
3390 defer sB.Shutdown()
3391 checkClusterFormed(t, sA, sB)
3392 nc := natsConnect(t, sA.ClientURL())
3393 defer nc.Close()
3394
3395 ib := nats.NewInbox()
3396 req := func(tags ...string) {
3397 t.Helper()
3398 r, err := json.Marshal(VarzEventOptions{EventFilterOptions: EventFilterOptions{Tags: tags}})
3399 require_NoError(t, err)
3400 err = nc.PublishRequest(fmt.Sprintf(serverPingReqSubj, "VARZ"), ib, r)
3401 require_NoError(t, err)
3402 }
3403
3404 msgs := make(chan *nats.Msg, 10)
3405 defer close(msgs)
3406 _, err := nc.ChanSubscribe(ib, msgs)
3407 require_NoError(t, err)
3408 req("none")
3409 select {
3410 case <-msgs:
3411 t.Fatalf("no message expected")
3412 case <-time.After(200 * time.Millisecond):
3413 }
3414 req("foo")
3415 m := <-msgs
3416 require_Contains(t, string(m.Data), "srv-A", "foo", "bar")
3417 req("foo", "bar")
3418 m = <-msgs
3419 require_Contains(t, string(m.Data), "srv-A", "foo", "bar")
3420 req("baz")
3421 m = <-msgs
3422 require_Contains(t, string(m.Data), "srv-B", "bar", "baz")
3423 req("bar")
3424 m1 := <-msgs
3425 m2 := <-msgs
3426 require_Contains(t, string(m1.Data)+string(m2.Data), "srv-A", "srv-B", "foo", "bar", "baz")
3427 require_Len(t, len(msgs), 0)
3428 }
3429
3430 func TestServerUnstableEventFilterMatch(t *testing.T) {
3431 confA := createConfFile(t, []byte(`
3432 listen: -1
3433 server_name: srv1
3434 server_tags: ["foo", "bar"]
3435 cluster {
3436 name: clust
3437 listen: -1
3438 no_advertise: true
3439 }
3440 system_account: SYS
3441 accounts: {
3442 SYS: {
3443 users: [
3444 {user: b, password: b}
3445 ]
3446 }
3447 }
3448 no_auth_user: b
3449 `))
3450 sA, _ := RunServerWithConfig(confA)
3451 defer sA.Shutdown()
3452 confB := createConfFile(t, []byte(fmt.Sprintf(`
3453 listen: -1
3454 server_name: srv10
3455 server_tags: ["bar", "baz"]
3456 cluster {
3457 name: clust
3458 listen: -1
3459 no_advertise: true
3460 routes [
3461 nats-route://127.0.0.1:%d
3462 ]
3463 }
3464 system_account: SYS
3465 accounts: {
3466 SYS: {
3467 users: [
3468 {user: b, password: b}
3469 ]
3470 }
3471 }
3472 no_auth_user: b
3473 `, sA.opts.Cluster.Port)))
3474 sB, _ := RunServerWithConfig(confB)
3475 defer sB.Shutdown()
3476 checkClusterFormed(t, sA, sB)
3477
3478 tester := func(t *testing.T, nc *nats.Conn, name string, count int) {
3479 t.Helper()
3480
3481 r, err := json.Marshal(VarzEventOptions{EventFilterOptions: EventFilterOptions{Name: name, ExactMatch: true}})
3482 require_NoError(t, err)
3483
3484 for i := 0; i < count; i++ {
3485 res, err := nc.Request(fmt.Sprintf(serverPingReqSubj, "VARZ"), r, time.Second)
3486 require_NoError(t, err)
3487
3488 var vz ServerAPIVarzResponse
3489 err = json.Unmarshal(res.Data, &vz)
3490 require_NoError(t, err)
3491
3492 if vz.Server.Name != name {
3493 t.Fatalf("Expected server name to be %q, got %q", name, vz.Server.Name)
3494 }
3495 }
3496 }
3497
3498 // Connects to srv1 so it's most likely to respond first while we are asking srv10 to respond.
3499 nc := natsConnect(t, sA.ClientURL())
3500 defer nc.Close()
3501 tester(t, nc, "srv10", 10)
3502
3503 // Connects to srv10 so it's most likely to respond first while we are asking srv1 to respond.
3504 nc.Close()
3505 nc = natsConnect(t, sB.ClientURL())
3506 defer nc.Close()
3507 tester(t, nc, "srv1", 10)
3508 }
3509
3510 // https://github.com/nats-io/nats-server/issues/3177
3511 func TestServerEventsAndDQSubscribers(t *testing.T) {
3512 c := createJetStreamClusterWithTemplate(t, jsClusterAccountsTempl, "DDQ", 3)
3513 defer c.shutdown()
3514
3515 nc, err := nats.Connect(c.randomServer().ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
3516 require_NoError(t, err)
3517 defer nc.Close()
3518
3519 sub, err := nc.QueueSubscribeSync("$SYS.ACCOUNT.*.DISCONNECT", "qq")
3520 require_NoError(t, err)
3521 nc.Flush()
3522
3523 // Create and disconnect 10 random connections.
3524 for i := 0; i < 10; i++ {
3525 nc, err := nats.Connect(c.randomServer().ClientURL())
3526 require_NoError(t, err)
3527 nc.Close()
3528 }
3529
3530 checkSubsPending(t, sub, 10)
3531 }
3532
3533 func TestServerEventsStatszSingleServer(t *testing.T) {
3534 conf := createConfFile(t, []byte(`
3535 listen: "127.0.0.1:-1"
3536 accounts { $SYS { users [{user: "admin", password: "p1d"}]} }
3537 `))
3538 s, _ := RunServerWithConfig(conf)
3539 defer s.Shutdown()
3540
3541 // Grab internal system client.
3542 s.mu.RLock()
3543 sysc := s.sys.client
3544 wait := s.sys.cstatsz + 25*time.Millisecond
3545 s.mu.RUnlock()
3546
3547 // Wait for when first statsz would have gone out..
3548 time.Sleep(wait)
3549
3550 sysc.mu.Lock()
3551 outMsgs := sysc.stats.outMsgs
3552 sysc.mu.Unlock()
3553
3554 require_True(t, outMsgs == 0)
3555
3556 // Connect as a system user and make sure if there is
3557 // subscription interest that we will receive updates.
3558 nc, _ := jsClientConnect(t, s, nats.UserInfo("admin", "p1d"))
3559 defer nc.Close()
3560
3561 sub, err := nc.SubscribeSync(fmt.Sprintf(serverStatsSubj, "*"))
3562 require_NoError(t, err)
3563
3564 checkSubsPending(t, sub, 1)
3565 }
3566
3567 func TestServerEventsReload(t *testing.T) {
3568 conf := createConfFile(t, []byte(`
3569 listen: "127.0.0.1:-1"
3570 accounts: {
3571 $SYS { users [{user: "admin", password: "p1d"}]}
3572 test { users [{user: "foo", password: "bar"}]}
3573 }
3574 ping_interval: "100ms"
3575 `))
3576 opts := LoadConfig(conf)
3577 s := RunServer(opts)
3578 defer s.Shutdown()
3579 subject := fmt.Sprintf(serverReloadReqSubj, s.info.ID)
3580
3581 // Connect as a test user and make sure the reload endpoint is not
3582 // accessible.
3583 ncTest, _ := jsClientConnect(t, s, nats.UserInfo("foo", "bar"))
3584 defer ncTest.Close()
3585 testReply := ncTest.NewRespInbox()
3586 sub, err := ncTest.SubscribeSync(testReply)
3587 require_NoError(t, err)
3588 err = ncTest.PublishRequest(subject, testReply, nil)
3589 require_NoError(t, err)
3590 _, err = sub.NextMsg(time.Second)
3591 require_Error(t, err)
3592
3593 require_True(t, s.getOpts().PingInterval == 100*time.Millisecond)
3594
3595 // Connect as a system user.
3596 nc, _ := jsClientConnect(t, s, nats.UserInfo("admin", "p1d"))
3597 defer nc.Close()
3598
3599 // rewrite the config file with a different ping interval
3600 err = os.WriteFile(conf, []byte(`
3601 listen: "127.0.0.1:-1"
3602 accounts: {
3603 $SYS { users [{user: "admin", password: "p1d"}]}
3604 test { users [{user: "foo", password: "bar"}]}
3605 }
3606 ping_interval: "200ms"
3607 `), 0666)
3608 require_NoError(t, err)
3609
3610 msg, err := nc.Request(subject, nil, time.Second)
3611 require_NoError(t, err)
3612
3613 var apiResp = ServerAPIResponse{}
3614 err = json.Unmarshal(msg.Data, &apiResp)
3615 require_NoError(t, err)
3616
3617 require_True(t, apiResp.Data == nil)
3618 require_True(t, apiResp.Error == nil)
3619
3620 // See that the ping interval has changed.
3621 require_True(t, s.getOpts().PingInterval == 200*time.Millisecond)
3622
3623 // rewrite the config file with a different ping interval
3624 err = os.WriteFile(conf, []byte(`garbage and nonsense`), 0666)
3625 require_NoError(t, err)
3626
3627 // Request the server to reload and wait for the response.
3628 msg, err = nc.Request(subject, nil, time.Second)
3629 require_NoError(t, err)
3630
3631 apiResp = ServerAPIResponse{}
3632 err = json.Unmarshal(msg.Data, &apiResp)
3633 require_NoError(t, err)
3634
3635 require_True(t, apiResp.Data == nil)
3636 require_Error(t, apiResp.Error, fmt.Errorf("Parse error on line 1: 'Expected a top-level value to end with a new line, comment or EOF, but got 'n' instead.'"))
3637
3638 // See that the ping interval has not changed.
3639 require_True(t, s.getOpts().PingInterval == 200*time.Millisecond)
3640 }
3641
3642 func TestServerEventsLDMKick(t *testing.T) {
3643 ldmed := make(chan bool, 1)
3644 disconnected := make(chan bool, 1)
3645
3646 s, opts := runTrustedServer(t)
3647 defer s.Shutdown()
3648
3649 acc, akp := createAccount(s)
3650 s.setSystemAccount(acc)
3651
3652 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
3653 ncs, err := nats.Connect(url, createUserCreds(t, s, akp))
3654 if err != nil {
3655 t.Fatalf("Error on connect: %v", err)
3656 }
3657 defer ncs.Close()
3658
3659 _, akp2 := createAccount(s)
3660
3661 nc, err := nats.Connect(url, createUserCreds(t, s, akp2), nats.Name("TEST EVENTS LDM+KICK"), nats.LameDuckModeHandler(func(_ *nats.Conn) { ldmed <- true }))
3662 if err != nil {
3663 t.Fatalf("Error on connect: %v", err)
3664 }
3665 defer nc.Close()
3666
3667 nc.SetDisconnectErrHandler(func(_ *nats.Conn, err error) { disconnected <- true })
3668
3669 cid, err := nc.GetClientID()
3670 if err != nil {
3671 t.Fatalf("Error on getting the CID: %v", err)
3672 }
3673
3674 reqldm := LDMClientReq{CID: cid}
3675 reqldmpayload, _ := json.Marshal(reqldm)
3676 reqkick := KickClientReq{CID: cid}
3677 reqkickpayload, _ := json.Marshal(reqkick)
3678
3679 // Test for data races when getting the client by ID
3680 uc := createUserCreds(t, s, akp2)
3681 totalClients := 100
3682 someClients := make([]*nats.Conn, 0, totalClients)
3683 for i := 0; i < totalClients; i++ {
3684 nc, err := nats.Connect(s.ClientURL(), uc)
3685 require_NoError(t, err)
3686 defer nc.Close()
3687 someClients = append(someClients, nc)
3688 }
3689 var wg sync.WaitGroup
3690 wg.Add(1)
3691 go func() {
3692 defer wg.Done()
3693 for i := 0; i < totalClients; i++ {
3694 someClients[i].Close()
3695 }
3696 }()
3697 defer wg.Wait()
3698
3699 _, err = ncs.Request(fmt.Sprintf("$SYS.REQ.SERVER.%s.LDM", s.ID()), reqldmpayload, time.Second)
3700 require_NoError(t, err)
3701
3702 select {
3703 case <-ldmed:
3704 case <-time.After(time.Second):
3705 t.Fatalf("timeout waiting for the connection to receive the LDM signal")
3706 }
3707
3708 _, err = ncs.Request(fmt.Sprintf("$SYS.REQ.SERVER.%s.KICK", s.ID()), reqkickpayload, time.Second)
3709 require_NoError(t, err)
3710
3711 select {
3712 case <-disconnected:
3713 case <-time.After(time.Second):
3714 t.Fatalf("timeout waiting for the client to get disconnected")
3715 }
3716 }
3717
3718 func Benchmark_GetHash(b *testing.B) {
3719 b.StopTimer()
3720 // Get 100 random names
3721 names := make([]string, 0, 100)
3722 for i := 0; i < 100; i++ {
3723 names = append(names, nuid.Next())
3724 }
3725 hashes := make([]string, 0, 100)
3726 for j := 0; j < 100; j++ {
3727 sha := sha256.New()
3728 sha.Write([]byte(names[j]))
3729 b := sha.Sum(nil)
3730 for i := 0; i < 8; i++ {
3731 b[i] = digits[int(b[i]%base)]
3732 }
3733 hashes = append(hashes, string(b[:8]))
3734 }
3735 wg := sync.WaitGroup{}
3736 wg.Add(8)
3737 errCh := make(chan error, 8)
3738 b.StartTimer()
3739 for i := 0; i < 8; i++ {
3740 go func() {
3741 defer wg.Done()
3742 for i := 0; i < b.N; i++ {
3743 idx := rand.Intn(100)
3744 if h := getHash(names[idx]); h != hashes[idx] {
3745 errCh <- fmt.Errorf("Hash for name %q was %q, but should be %q", names[idx], h, hashes[idx])
3746 return
3747 }
3748 }
3749 }()
3750 }
3751 wg.Wait()
3752 select {
3753 case err := <-errCh:
3754 b.Fatal(err.Error())
3755 default:
3756 }
3757 }
3758
3759 func TestClusterSetupMsgs(t *testing.T) {
3760 // Tests will set this general faster, but here we want default for production.
3761 original := statszRateLimit
3762 statszRateLimit = defaultStatszRateLimit
3763 defer func() { statszRateLimit = original }()
3764
3765 numServers := 10
3766 c := createClusterEx(t, false, 0, false, "cluster", numServers)
3767 defer shutdownCluster(c)
3768
3769 checkFor(t, 3*time.Second, 500*time.Millisecond, func() error {
3770 var totalOut int
3771 for _, server := range c.servers {
3772 totalOut += int(atomic.LoadInt64(&server.outMsgs))
3773 }
3774 totalExpected := numServers * numServers
3775 if totalOut >= totalExpected {
3776 return fmt.Errorf("Total outMsgs is %d, expected < %d\n", totalOut, totalExpected)
3777 }
3778 return nil
3779 })
3780 }
3781
3782 func TestServerEventsProfileZNotBlockingRecvQ(t *testing.T) {
3783 sa, _, sb, optsB, akp := runTrustedCluster(t)
3784 defer sa.Shutdown()
3785 defer sb.Shutdown()
3786 // For this test, we will run a single server because the profiling
3787 // would fail for the second server since it would detect that
3788 // one profiling is already running (2 servers, but same process).
3789 sa.Shutdown()
3790 url := fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port)
3791 nc, err := nats.Connect(url, createUserCreds(t, sb, akp))
3792 require_NoError(t, err)
3793 defer nc.Close()
3794 // We need to wait a little bit for the $SYS.SERVER.ACCOUNT.%s.CONNS
3795 // event to be pushed in the mux'ed queue.
3796 time.Sleep(300 * time.Millisecond)
3797
3798 po := ProfilezOptions{Name: "cpu", Duration: 1 * time.Second}
3799 req, err := json.Marshal(po)
3800 require_NoError(t, err)
3801
3802 testReq := func(t *testing.T, subj string) {
3803 // Block the recvQ by locking it for the duration of this test.
3804 sb.mu.RLock()
3805 recvq := sb.sys.recvq
3806 sb.mu.RUnlock()
3807 recvq.Lock()
3808 defer recvq.Unlock()
3809
3810 // Send the profilez request on the given subject.
3811 reply := nc.NewRespInbox()
3812 sub := natsSubSync(t, nc, reply)
3813 nc.PublishRequest(subj, reply, req)
3814 msg := natsNexMsg(t, sub, 10*time.Second)
3815 if len(msg.Data) == 0 {
3816 t.Fatal("Unexpected empty response")
3817 }
3818 // Make sure its a ServerAPIResponse
3819 resp := ServerAPIResponse{Data: &ProfilezStatus{}}
3820 err := json.Unmarshal(msg.Data, &resp)
3821 require_NoError(t, err)
3822 // Check profile status to make sure that we got something.
3823 ps := resp.Data.(*ProfilezStatus)
3824 if ps.Error != _EMPTY_ {
3825 t.Fatalf("%s", ps.Error)
3826 }
3827 require_True(t, len(ps.Profile) > 0)
3828 }
3829 const profilez = "PROFILEZ"
3830 for _, test := range []struct {
3831 name string
3832 f func() string
3833 }{
3834 {"server profilez request subject", func() string { return fmt.Sprintf(serverPingReqSubj, profilez) }},
3835 {"server direct request subject", func() string { return fmt.Sprintf(serverDirectReqSubj, sb.ID(), profilez) }},
3836 } {
3837 t.Run(test.name, func(t *testing.T) {
3838 testReq(t, test.f())
3839 })
3840 }
3841 }
3842
3843 func TestServerEventsStatsZJetStreamApiLevel(t *testing.T) {
3844 s, opts := runTrustedServer(t)
3845 defer s.Shutdown()
3846
3847 acc, akp := createAccount(s)
3848 s.setSystemAccount(acc)
3849 s.EnableJetStream(&JetStreamConfig{StoreDir: t.TempDir()})
3850
3851 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
3852 ncs, err := nats.Connect(url, createUserCreds(t, s, akp))
3853 require_NoError(t, err)
3854 defer ncs.Close()
3855
3856 msg, err := ncs.Request("$SYS.REQ.SERVER.PING.STATSZ", nil, time.Second)
3857 require_NoError(t, err)
3858
3859 var stats ServerStatsMsg
3860 err = json.Unmarshal(msg.Data, &stats)
3861 require_NoError(t, err)
3862
3863 require_Equal(t, stats.Stats.JetStream.Stats.API.Level, JSApiLevel)
3864 }
3865
3866 func TestServerEventsPingStatsSlowConsumersStats(t *testing.T) {
3867 s, _ := runTrustedServer(t)
3868 defer s.Shutdown()
3869
3870 acc, akp := createAccount(s)
3871 s.setSystemAccount(acc)
3872 ncs, err := nats.Connect(s.ClientURL(), createUserCreds(t, s, akp))
3873 require_NoError(t, err)
3874 defer ncs.Close()
3875
3876 const statsz = "STATSZ"
3877 for _, test := range []struct {
3878 name string
3879 f func() string
3880 expectTwo bool
3881 }{
3882 {"server stats ping request subject", func() string { return serverStatsPingReqSubj }, true},
3883 {"server ping request subject", func() string { return fmt.Sprintf(serverPingReqSubj, statsz) }, true},
3884 {"server direct request subject", func() string { return fmt.Sprintf(serverDirectReqSubj, s.ID(), statsz) }, false},
3885 } {
3886 t.Run(test.name, func(t *testing.T) {
3887 // Clear all slow consumers values
3888 s.scStats.clients.Store(0)
3889 s.scStats.routes.Store(0)
3890 s.scStats.gateways.Store(0)
3891 s.scStats.leafs.Store(0)
3892
3893 msg, err := ncs.Request(test.f(), nil, time.Second)
3894 require_NoError(t, err)
3895
3896 var ssm ServerStatsMsg
3897 err = json.Unmarshal(msg.Data, &ssm)
3898 require_NoError(t, err)
3899
3900 // No slow consumer stats, so should be nil
3901 require_True(t, ssm.Stats.SlowConsumersStats == nil)
3902
3903 // Now set some values
3904 s.scStats.clients.Store(1)
3905 s.scStats.routes.Store(2)
3906 s.scStats.gateways.Store(3)
3907 s.scStats.leafs.Store(4)
3908
3909 msg, err = ncs.Request(test.f(), nil, time.Second)
3910 require_NoError(t, err)
3911
3912 ssm = ServerStatsMsg{}
3913 err = json.Unmarshal(msg.Data, &ssm)
3914 require_NoError(t, err)
3915
3916 require_NotNil(t, ssm.Stats.SlowConsumersStats)
3917 scs := ssm.Stats.SlowConsumersStats
3918 require_Equal(t, scs.Clients, 1)
3919 require_Equal(t, scs.Routes, 2)
3920 require_Equal(t, scs.Gateways, 3)
3921 require_Equal(t, scs.Leafs, 4)
3922 })
3923 }
3924 }
3925
3926 func TestServerEventsPingStatsStaleConnectionStats(t *testing.T) {
3927 templ := `
3928 listen: "127.0.0.1:-1"
3929 system_account = sys
3930 accounts {
3931 a {
3932 users = [{ user: a, pass: a }]
3933 }
3934 b {
3935 users = [{ user: b, pass: b }]
3936 }
3937 sys {
3938 users = [{ user: sys, pass: sys }]
3939 }
3940 }
3941 `
3942 conf := createConfFile(t, []byte(templ))
3943 s, _ := RunServerWithConfig(conf)
3944 defer s.Shutdown()
3945
3946 // 3 different ways to get statz:
3947 const statsz = "STATSZ"
3948
3949 // $SYS.REQ.SERVER.NCBT6MBA7Q7ZF4R4WVXTSZTCZDPPXX2ALLN3XM75VCBCNMPIKQFPFLKV.STATSZ
3950 dirReqSubject := func(s *Server) string {
3951 return fmt.Sprintf(serverDirectReqSubj, s.ID(), statsz)
3952 }
3953 // $SYS.REQ.SERVER.PING.STATSZ
3954 pingReqSubject := func(s *Server) string {
3955 return fmt.Sprintf(serverPingReqSubj, statsz)
3956 }
3957 // $SYS.REQ.SERVER.PING
3958 statsPingSubject := func(s *Server) string {
3959 return serverStatsPingReqSubj
3960 }
3961 subjects := []string{dirReqSubject(s), pingReqSubject(s), statsPingSubject(s)}
3962
3963 ncs, err := nats.Connect(s.ClientURL(), nats.UserInfo("sys", "sys"))
3964 require_NoError(t, err)
3965
3966 for _, subject := range subjects {
3967 msg, err := ncs.Request(subject, nil, time.Second)
3968 require_NoError(t, err)
3969
3970 var ssm ServerStatsMsg
3971 err = json.Unmarshal(msg.Data, &ssm)
3972 require_NoError(t, err)
3973
3974 // No stale connection stats.
3975 require_True(t, ssm.Stats.StaleConnectionStats == nil)
3976 require_Equal(t, s.NumStaleConnections(), int64(0))
3977 require_Equal(t, s.NumStaleConnectionsClients(), uint64(0))
3978 require_Equal(t, s.NumStaleConnectionsRoutes(), uint64(0))
3979 require_Equal(t, s.NumStaleConnectionsGateways(), uint64(0))
3980 require_Equal(t, s.NumStaleConnectionsLeafs(), uint64(0))
3981 }
3982
3983 // Set some values and confirm.
3984 s.staleStats.clients.Store(1)
3985 s.staleStats.routes.Store(2)
3986 s.staleStats.gateways.Store(3)
3987 s.staleStats.leafs.Store(4)
3988 atomic.StoreInt64(&s.staleConnections, 10)
3989 require_Equal(t, s.NumStaleConnections(), int64(10))
3990 require_Equal(t, s.NumStaleConnectionsClients(), uint64(1))
3991 require_Equal(t, s.NumStaleConnectionsRoutes(), uint64(2))
3992 require_Equal(t, s.NumStaleConnectionsGateways(), uint64(3))
3993 require_Equal(t, s.NumStaleConnectionsLeafs(), uint64(4))
3994
3995 for _, subject := range subjects {
3996 msg, err := ncs.Request(subject, nil, time.Second)
3997 require_NoError(t, err)
3998
3999 ssm := ServerStatsMsg{}
4000 err = json.Unmarshal(msg.Data, &ssm)
4001 require_NoError(t, err)
4002
4003 require_NotNil(t, ssm.Stats.StaleConnectionStats)
4004 stcs := ssm.Stats.StaleConnectionStats
4005 require_Equal(t, stcs.Clients, 1)
4006 require_Equal(t, stcs.Routes, 2)
4007 require_Equal(t, stcs.Gateways, 3)
4008 require_Equal(t, stcs.Leafs, 4)
4009 require_Equal(t, ssm.Stats.StaleConnections, int64(10))
4010 }
4011 }
4012
4013 func TestServerEventsStatszMaxProcsMemLimit(t *testing.T) {
4014 // We want to prove that our set values are reflected in STATSZ,
4015 // so we can't use constants that might match the system that
4016 // the test is run on.
4017 omp, omm := runtime.GOMAXPROCS(-1), debug.SetMemoryLimit(-1)
4018 mp, mm := runtime.GOMAXPROCS(omp*2)*2, debug.SetMemoryLimit(omm/2)/2
4019
4020 // When we're done, put everything back.
4021 defer runtime.GOMAXPROCS(omp)
4022 defer debug.SetMemoryLimit(omm)
4023
4024 s, opts := runTrustedServer(t)
4025 defer s.Shutdown()
4026
4027 acc, akp := createAccount(s)
4028 s.setSystemAccount(acc)
4029
4030 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
4031 ncs, err := nats.Connect(url, createUserCreds(t, s, akp))
4032 require_NoError(t, err)
4033 defer ncs.Close()
4034
4035 msg, err := ncs.Request("$SYS.REQ.SERVER.PING.STATSZ", nil, time.Second)
4036 require_NoError(t, err)
4037
4038 var stats ServerStatsMsg
4039 require_NoError(t, json.Unmarshal(msg.Data, &stats))
4040 require_Equal(t, stats.Stats.MaxProcs, mp)
4041 require_Equal(t, stats.Stats.MemLimit, mm)
4042 }
4043
4044 func TestSubszPagination(t *testing.T) {
4045 type subszResp struct {
4046 Subsz Subsz `json:"data"`
4047 Server ServerInfo `json:"server"`
4048 }
4049 s, opts := runTrustedServer(t)
4050 defer s.Shutdown()
4051
4052 sysAcc, sysAkp := createAccount(s)
4053 s.setSystemAccount(sysAcc)
4054
4055 acc, akp := createAccount(s)
4056
4057 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
4058 ncSys, err := nats.Connect(url, createUserCreds(t, s, sysAkp))
4059 require_NoError(t, err)
4060 defer ncSys.Close()
4061
4062 nc, err := nats.Connect(url, createUserCreds(t, s, akp))
4063 if err != nil {
4064 t.Fatalf("Error on connect: %v", err)
4065 }
4066 defer nc.Close()
4067
4068 // Create 100 subscriptions.
4069 for i := range 100 {
4070 nc.Subscribe(fmt.Sprintf("foo.%d", i), func(_ *nats.Msg) {})
4071 }
4072
4073 time.Sleep(100 * time.Millisecond)
4074
4075 reqSubject := fmt.Sprintf(accDirectReqSubj, acc.Name, "SUBSZ")
4076
4077 // Request the first page.
4078 subszReq := SubszOptions{Subscriptions: true, Limit: 10}
4079 req, _ := json.Marshal(subszReq)
4080 msg, err := ncSys.Request(reqSubject, req, time.Second)
4081 require_NoError(t, err)
4082
4083 var subsz subszResp
4084 require_NoError(t, json.Unmarshal(msg.Data, &subsz))
4085 require_Equal(t, len(subsz.Subsz.Subs), 10)
4086
4087 // we cannot check for equality since we have to account for the monitoring subscriptions
4088 if subsz.Subsz.Total < 100 || subsz.Subsz.Total > 110 {
4089 t.Fatalf("Expected total subscriptions to be more than 100 and less than 110, got %d", subsz.Subsz.Total)
4090 }
4091
4092 // Now test with a sub filter
4093
4094 // create 10 subs on "bar.*"
4095 for range 10 {
4096 nc.Subscribe("bar.*", func(_ *nats.Msg) {})
4097 }
4098
4099 time.Sleep(100 * time.Millisecond)
4100
4101 subszReq = SubszOptions{Subscriptions: true, Limit: 5, Test: "bar.A"}
4102 req, _ = json.Marshal(subszReq)
4103 msg, err = ncSys.Request(reqSubject, req, time.Second)
4104 require_NoError(t, err)
4105
4106 var subszFiltered subszResp
4107 require_NoError(t, json.Unmarshal(msg.Data, &subszFiltered))
4108 require_Equal(t, len(subszFiltered.Subsz.Subs), 5)
4109 require_Equal(t, subszFiltered.Subsz.Total, 10)
4110 }
4111
4112 func TestServerEventsConnectDisconnectForGlobalAcc(t *testing.T) {
4113 conf := createConfFile(t, []byte(`
4114 listen: "127.0.0.1:-1"
4115 accounts {
4116 $SYS {
4117 users [{user: "admin", password: "pwd"}]
4118 }
4119 }
4120 `))
4121 defer os.Remove(conf)
4122
4123 s, opts := RunServerWithConfig(conf)
4124 defer s.Shutdown()
4125
4126 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
4127 ncs, err := nats.Connect(url, nats.UserInfo("admin", "pwd"))
4128 require_NoError(t, err)
4129 defer ncs.Close()
4130
4131 s1, err := ncs.SubscribeSync(fmt.Sprintf(connectEventSubj, globalAccountName))
4132 require_NoError(t, err)
4133 s2, err := ncs.SubscribeSync(fmt.Sprintf(disconnectEventSubj, globalAccountName))
4134 require_NoError(t, err)
4135
4136 // Flush to make sure subscriptions are established
4137 require_NoError(t, ncs.Flush())
4138
4139 // Connect to global account
4140 ncg, err := nats.Connect(url, nats.UserInfo("", ""))
4141 require_NoError(t, err)
4142
4143 // System account should get a connect event
4144 msg, err := s1.NextMsg(5 * time.Second)
4145 require_NoError(t, err)
4146 require_Equal(t, msg.Subject, fmt.Sprintf(connectEventSubj, globalAccountName))
4147
4148 // Disconnect from global account
4149 ncg.Close()
4150
4151 // System account should get a disconnect event
4152 msg, err = s2.NextMsg(5 * time.Second)
4153 require_NoError(t, err)
4154 require_Equal(t, msg.Subject, fmt.Sprintf(disconnectEventSubj, globalAccountName))
4155 }
4156
4157 func TestSendInternalAccountMsgWithReplyDoesNotMutateHeaderSlice(t *testing.T) {
4158 s := RunServer(DefaultOptions())
4159 defer s.Shutdown()
4160
4161 nc, err := nats.Connect(s.ClientURL())
4162 require_NoError(t, err)
4163 defer nc.Close()
4164
4165 sub, err := nc.SubscribeSync("foo")
4166 require_NoError(t, err)
4167 require_NoError(t, nc.Flush())
4168
4169 // Build a header slice with significant spare capacity, like callers
4170 // constructing headers with append/genHeader naturally do.
4171 hdr := make([]byte, 0, 256)
4172 hdr = append(hdr, "NATS/1.0\r\nFoo: bar\r\n\r\n"...)
4173
4174 // Snapshot the entire backing array so we can detect any mutation,
4175 // including writes past len(hdr) into spare capacity.
4176 snapshot := make([]byte, cap(hdr))
4177 copy(snapshot, hdr[:cap(hdr)])
4178
4179 body := []byte("REPRO_LEAK_BODY")
4180 err = s.sendInternalAccountMsgWithReply(s.globalAccount(), "foo", _EMPTY_, hdr, body, false)
4181 require_NoError(t, err)
4182
4183 msg, err := sub.NextMsg(2 * time.Second)
4184 require_NoError(t, err)
4185 require_Equal(t, string(msg.Data), "REPRO_LEAK_BODY")
4186 require_Equal(t, msg.Header.Get("Foo"), "bar")
4187
4188 // The caller's hdr slice (and its full backing array) must be untouched.
4189 got := hdr[:cap(hdr)]
4190 if !bytes.Equal(got, snapshot) {
4191 t.Fatalf("hdr backing array was mutated by send:\n want: %q\n got: %q", snapshot, got)
4192 }
4193 }
4194
4195 func TestEventsResetChSendNoPanicAfterShutdownEventing(t *testing.T) {
4196 s := RunServer(DefaultOptions())
4197 defer s.Shutdown()
4198
4199 // Simulate a sender that grabbed the channel reference before it was nil-ed,
4200 // exactly as the production senders do under s.mu.
4201 s.mu.Lock()
4202 if s.sys == nil || s.sys.resetCh == nil {
4203 s.mu.Unlock()
4204 t.Fatal("expected system eventing to be running")
4205 }
4206 rc := s.sys.resetCh
4207 s.mu.Unlock()
4208
4209 // Drive eventing shutdown to completion. With the old code this closed rc.
4210 s.shutdownEventing()
4211
4212 // Stand in for the (now exited) internal send loop so that, on a healthy
4213 // open channel, the send can complete.
4214 go func() { <-rc }()
4215
4216 // Perform the send using the same select-against-quitCh pattern as the
4217 // production senders. On the buggy code rc is closed and this panics.
4218 done := make(chan any, 1)
4219 go func() {
4220 defer func() { done <- recover() }()
4221 select {
4222 case rc <- struct{}{}:
4223 case <-s.quitCh:
4224 }
4225 }()
4226
4227 select {
4228 case r := <-done:
4229 if r != nil {
4230 t.Fatalf("send on resetCh panicked during shutdown: %v", r)
4231 }
4232 case <-time.After(5 * time.Second):
4233 t.Fatal("send on resetCh blocked unexpectedly")
4234 }
4235 }
4236
4237 func TestEventsRemoteLatencyUpdateNilLatency(t *testing.T) {
4238 s, _ := runTrustedServer(t)
4239 defer s.Shutdown()
4240
4241 // Enable internal events by setting a system account.
4242 sacc, _ := createAccount(s)
4243 require_NoError(t, s.setSystemAccount(sacc))
4244
4245 // Target account that will own the tracked response serviceImport.
4246 acc, _ := createAccount(s)
4247
4248 // Construct the offending state directly: a response serviceImport with a
4249 // .T-suffixed tracked reply, tracking enabled, but a nil latency.
4250 reply := "_R_.abcdef.T"
4251 si := &serviceImport{
4252 acc: acc,
4253 from: reply,
4254 to: reply,
4255 response: true,
4256 tracking: true, // tracking on, but...
4257 latency: nil, // ...no latency object -> nil deref at si.latency.subject
4258 }
4259 acc.mu.Lock()
4260 if acc.exports.responses == nil {
4261 acc.exports.responses = make(map[string]*serviceImport)
4262 }
4263 acc.exports.responses[reply] = si
4264 acc.mu.Unlock()
4265
4266 // Craft a remote latency measurement that resolves to this serviceImport.
4267 rl := remoteLatency{
4268 Account: acc.Name,
4269 ReqId: reply,
4270 }
4271 msg, err := json.Marshal(&rl)
4272 require_NoError(t, err)
4273
4274 // On unfixed code this panics with a nil pointer dereference on
4275 // si.latency.subject. With the fix it returns cleanly.
4276 var recovered any
4277 func() {
4278 defer func() {
4279 if r := recover(); r != nil {
4280 recovered = r
4281 // The panic occurred while holding acc.mu.RLock() (taken just
4282 // before the offending deref and released just after). Release
4283 // it so the deferred s.Shutdown does not deadlock.
4284 acc.mu.RUnlock()
4285 }
4286 }()
4287 s.remoteLatencyUpdate(nil, nil, nil, "$SYS.LATENCY.M2."+reply, "", nil, msg)
4288 }()
4289
4290 if recovered != nil {
4291 t.Fatalf("remoteLatencyUpdate panicked on nil si.latency: %v", recovered)
4292 }
4293 }