Debian Codegraph @

server/routes_test.go

raw
1 // Copyright 2013-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 "bufio"
18 "bytes"
19 "context"
20 "crypto/tls"
21 "encoding/json"
22 "fmt"
23 "math/rand"
24 "net"
25 "net/http"
26 "net/http/httptest"
27 "net/url"
28 "os"
29 "reflect"
30 "runtime"
31 "strconv"
32 "strings"
33 "sync"
34 "sync/atomic"
35 "testing"
36 "time"
37
38 "github.com/nats-io/jwt/v2"
39 "github.com/nats-io/nats.go"
40 "github.com/nats-io/nkeys"
41 )
42
43 func init() {
44 routeConnectDelay = 15 * time.Millisecond
45 routeConnectMaxDelay = 15 * time.Millisecond
46 }
47
48 func checkNumRoutes(t *testing.T, s *Server, expected int) {
49 t.Helper()
50 checkFor(t, 5*time.Second, 15*time.Millisecond, func() error {
51 if nr := s.NumRoutes(); nr != expected {
52 return fmt.Errorf("Expected %v routes, got %v", expected, nr)
53 }
54 return nil
55 })
56 }
57
58 func checkSubInterest(t *testing.T, s *Server, accName, subject string, timeout time.Duration) {
59 t.Helper()
60 checkFor(t, timeout, 15*time.Millisecond, func() error {
61 acc, err := s.LookupAccount(accName)
62 if err != nil {
63 return fmt.Errorf("error looking up account %q: %v", accName, err)
64 }
65 if acc.SubscriptionInterest(subject) {
66 return nil
67 }
68 return fmt.Errorf("no subscription interest for account %q on %q", accName, subject)
69 })
70 }
71
72 func checkSubNoInterest(t *testing.T, s *Server, accName, subject string, timeout time.Duration) {
73 t.Helper()
74 checkFor(t, timeout, 15*time.Millisecond, func() error {
75 acc, err := s.LookupAccount(accName)
76 if err != nil {
77 return fmt.Errorf("error looking up account %q: %v", accName, err)
78 }
79 if acc.SubscriptionInterest(subject) {
80 return fmt.Errorf("unexpected subscription interest for account %q on %q", accName, subject)
81 }
82 return nil
83 })
84 }
85
86 func TestRouteConfig(t *testing.T) {
87 opts, err := ProcessConfigFile("./configs/cluster.conf")
88 if err != nil {
89 t.Fatalf("Received an error reading route config file: %v\n", err)
90 }
91
92 golden := &Options{
93 ConfigFile: "./configs/cluster.conf",
94 Host: "127.0.0.1",
95 Port: 4242,
96 Username: "derek",
97 Password: "porkchop",
98 AuthTimeout: 1.0,
99 Cluster: ClusterOpts{
100 Name: "abc",
101 Host: "127.0.0.1",
102 Port: 4244,
103 Username: "route_user",
104 Password: "top_secret",
105 AuthTimeout: 1.0,
106 NoAdvertise: true,
107 ConnectRetries: 2,
108 ConnectBackoff: true,
109 },
110 PidFile: "/tmp/nats-server/nats_cluster_test.pid",
111 configDigest: "sha256:b2f6d54063e43a85f5a09d198204f044bc154f9f9ccfb84e47d5762091aec487",
112 authBlockDefined: true,
113 }
114
115 // Setup URLs
116 r1, _ := url.Parse("nats-route://foo:[email protected]:4245")
117 r2, _ := url.Parse("nats-route://foo:[email protected]:4246")
118
119 golden.Routes = []*url.URL{r1, r2}
120
121 checkOptionsEqual(t, golden, opts)
122 }
123
124 func TestClusterAdvertise(t *testing.T) {
125 lst, err := natsListen("tcp", "127.0.0.1:0")
126 if err != nil {
127 t.Fatalf("Error starting listener: %v", err)
128 }
129 ch := make(chan error)
130 go func() {
131 c, err := lst.Accept()
132 if err != nil {
133 ch <- err
134 return
135 }
136 c.Close()
137 ch <- nil
138 }()
139
140 optsA, err := ProcessConfigFile("./configs/seed.conf")
141 require_NoError(t, err)
142 optsA.NoSigs, optsA.NoLog = true, true
143 srvA := RunServer(optsA)
144 defer srvA.Shutdown()
145
146 srvARouteURL := fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host, srvA.ClusterAddr().Port)
147 optsB := nextServerOpts(optsA)
148 optsB.Routes = RoutesFromStr(srvARouteURL)
149
150 srvB := RunServer(optsB)
151 defer srvB.Shutdown()
152
153 // Wait for these 2 to connect to each other
154 checkClusterFormed(t, srvA, srvB)
155
156 // Now start server C that connects to A. A should ask B to connect to C,
157 // based on C's URL. But since C configures a Cluster.Advertise, it will connect
158 // to our listener.
159 optsC := nextServerOpts(optsB)
160 optsC.Cluster.Advertise = lst.Addr().String()
161 optsC.ClientAdvertise = "me:1"
162 optsC.Routes = RoutesFromStr(srvARouteURL)
163
164 srvC := RunServer(optsC)
165 defer srvC.Shutdown()
166
167 select {
168 case e := <-ch:
169 if e != nil {
170 t.Fatalf("Error: %v", e)
171 }
172 case <-time.After(2 * time.Second):
173 t.Fatalf("Test timed out")
174 }
175 }
176
177 func TestClusterAdvertiseErrorOnStartup(t *testing.T) {
178 opts := DefaultOptions()
179 // Set invalid address
180 opts.Cluster.Advertise = "addr:::123"
181 testFatalErrorOnStart(t, opts, "Cluster.Advertise")
182 }
183
184 func TestClientAdvertise(t *testing.T) {
185 optsA, err := ProcessConfigFile("./configs/seed.conf")
186 require_NoError(t, err)
187 optsA.NoSigs, optsA.NoLog = true, true
188
189 srvA := RunServer(optsA)
190 defer srvA.Shutdown()
191
192 optsB := nextServerOpts(optsA)
193 optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host, optsA.Cluster.Port))
194 optsB.ClientAdvertise = "me:1"
195 srvB := RunServer(optsB)
196 defer srvB.Shutdown()
197
198 checkClusterFormed(t, srvA, srvB)
199
200 nc, err := nats.Connect(fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port))
201 if err != nil {
202 t.Fatalf("Error on connect: %v", err)
203 }
204 defer nc.Close()
205 checkFor(t, time.Second, 15*time.Millisecond, func() error {
206 ds := nc.DiscoveredServers()
207 if len(ds) == 1 {
208 if ds[0] == "nats://me:1" {
209 return nil
210 }
211 }
212 return fmt.Errorf("Did not get expected discovered servers: %v", nc.DiscoveredServers())
213 })
214 }
215
216 func TestServerRoutesWithClients(t *testing.T) {
217 optsA, err := ProcessConfigFile("./configs/srv_a.conf")
218 require_NoError(t, err)
219 optsB, err := ProcessConfigFile("./configs/srv_b.conf")
220 require_NoError(t, err)
221
222 optsA.NoSigs, optsA.NoLog = true, true
223 optsB.NoSigs, optsB.NoLog = true, true
224
225 srvA := RunServer(optsA)
226 defer srvA.Shutdown()
227
228 urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, optsA.Port)
229 urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, optsB.Port)
230
231 nc1, err := nats.Connect(urlA)
232 if err != nil {
233 t.Fatalf("Error creating client: %v\n", err)
234 }
235 defer nc1.Close()
236
237 ch := make(chan bool)
238 sub, _ := nc1.Subscribe("foo", func(m *nats.Msg) { ch <- true })
239 nc1.QueueSubscribe("foo", "bar", func(m *nats.Msg) {})
240 nc1.Publish("foo", []byte("Hello"))
241 // Wait for message
242 <-ch
243 sub.Unsubscribe()
244
245 srvB := RunServer(optsB)
246 defer srvB.Shutdown()
247
248 // Wait for route to form.
249 checkClusterFormed(t, srvA, srvB)
250
251 nc2, err := nats.Connect(urlB)
252 if err != nil {
253 t.Fatalf("Error creating client: %v\n", err)
254 }
255 defer nc2.Close()
256 nc2.Publish("foo", []byte("Hello"))
257 nc2.Flush()
258 }
259
260 func TestServerRoutesWithAuthAndBCrypt(t *testing.T) {
261 optsA, err := ProcessConfigFile("./configs/srv_a_bcrypt.conf")
262 require_NoError(t, err)
263 optsB, err := ProcessConfigFile("./configs/srv_b_bcrypt.conf")
264 require_NoError(t, err)
265
266 optsA.NoSigs, optsA.NoLog = true, true
267 optsB.NoSigs, optsB.NoLog = true, true
268
269 srvA := RunServer(optsA)
270 defer srvA.Shutdown()
271
272 srvB := RunServer(optsB)
273 defer srvB.Shutdown()
274
275 // Wait for route to form.
276 checkClusterFormed(t, srvA, srvB)
277
278 urlA := fmt.Sprintf("nats://%s:%s@%s:%d/", optsA.Username, optsA.Password, optsA.Host, optsA.Port)
279 urlB := fmt.Sprintf("nats://%s:%s@%s:%d/", optsB.Username, optsB.Password, optsB.Host, optsB.Port)
280
281 nc1, err := nats.Connect(urlA)
282 if err != nil {
283 t.Fatalf("Error creating client: %v\n", err)
284 }
285 defer nc1.Close()
286
287 // Test that we are connected.
288 ch := make(chan bool)
289 sub, err := nc1.Subscribe("foo", func(m *nats.Msg) { ch <- true })
290 if err != nil {
291 t.Fatalf("Error creating subscription: %v\n", err)
292 }
293 nc1.Flush()
294 defer sub.Unsubscribe()
295
296 checkSubInterest(t, srvB, globalAccountName, "foo", time.Second)
297
298 nc2, err := nats.Connect(urlB)
299 if err != nil {
300 t.Fatalf("Error creating client: %v\n", err)
301 }
302 defer nc2.Close()
303 nc2.Publish("foo", []byte("Hello"))
304 nc2.Flush()
305
306 // Wait for message
307 select {
308 case <-ch:
309 case <-time.After(2 * time.Second):
310 t.Fatal("Timeout waiting for message across route")
311 }
312 }
313
314 // Helper function to check that a cluster is formed
315 func checkClusterFormed(t testing.TB, servers ...*Server) {
316 t.Helper()
317 var _enr [8]int
318 enr := _enr[:0]
319 for _, a := range servers {
320 if a.getOpts().Cluster.PoolSize < 0 {
321 enr = append(enr, len(servers)-1)
322 } else {
323 a.mu.RLock()
324 nr := a.routesPoolSize + len(a.accRoutes)
325 a.mu.RUnlock()
326 total := 0
327 for _, b := range servers {
328 if a == b {
329 continue
330 }
331 bo := b.getOpts()
332 if ps := bo.Cluster.PoolSize; ps < 0 {
333 total++
334 } else {
335 bps := ps + len(bo.Cluster.PinnedAccounts)
336 total += max(nr, bps)
337 }
338 }
339 enr = append(enr, total)
340 }
341 }
342 checkFor(t, 10*time.Second, 100*time.Millisecond, func() error {
343 for i, s := range servers {
344 if numRoutes := s.NumRoutes(); numRoutes != enr[i] {
345 return fmt.Errorf("Expected %d routes for server %q, got %d", enr[i], s, numRoutes)
346 }
347 }
348 return nil
349 })
350 }
351
352 // Helper function to generate next opts to make sure no port conflicts etc.
353 func nextServerOpts(opts *Options) *Options {
354 nopts := *opts
355 nopts.Port = -1
356 nopts.Cluster.Port = -1
357 nopts.HTTPPort = -1
358 if nopts.Gateway.Name != "" {
359 nopts.Gateway.Port = -1
360 }
361 nopts.ServerName = ""
362 return &nopts
363 }
364
365 func TestSeedSolicitWorks(t *testing.T) {
366 optsSeed, err := ProcessConfigFile("./configs/seed.conf")
367 require_NoError(t, err)
368
369 optsSeed.NoSigs, optsSeed.NoLog = true, true
370 optsSeed.NoSystemAccount = true
371
372 srvSeed := RunServer(optsSeed)
373 defer srvSeed.Shutdown()
374
375 optsA := nextServerOpts(optsSeed)
376 optsA.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsSeed.Cluster.Host,
377 srvSeed.ClusterAddr().Port))
378
379 srvA := RunServer(optsA)
380 defer srvA.Shutdown()
381
382 urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, srvA.ClusterAddr().Port)
383
384 nc1, err := nats.Connect(urlA)
385 if err != nil {
386 t.Fatalf("Error creating client: %v\n", err)
387 }
388 defer nc1.Close()
389
390 // Test that we are connected.
391 ch := make(chan bool)
392 nc1.Subscribe("foo", func(m *nats.Msg) { ch <- true })
393 nc1.Flush()
394
395 optsB := nextServerOpts(optsA)
396 optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsSeed.Cluster.Host,
397 srvSeed.ClusterAddr().Port))
398
399 srvB := RunServer(optsB)
400 defer srvB.Shutdown()
401
402 urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, srvB.ClusterAddr().Port)
403
404 nc2, err := nats.Connect(urlB)
405 if err != nil {
406 t.Fatalf("Error creating client: %v\n", err)
407 }
408 defer nc2.Close()
409
410 checkClusterFormed(t, srvSeed, srvA, srvB)
411 checkExpectedSubs(t, 1, srvB)
412
413 nc2.Publish("foo", []byte("Hello"))
414
415 // Wait for message
416 select {
417 case <-ch:
418 case <-time.After(2 * time.Second):
419 t.Fatal("Timeout waiting for message across route")
420 }
421 }
422
423 func TestTLSSeedSolicitWorks(t *testing.T) {
424 optsSeed, err := ProcessConfigFile("./configs/seed_tls.conf")
425 require_NoError(t, err)
426
427 optsSeed.NoSigs, optsSeed.NoLog = true, true
428 optsSeed.NoSystemAccount = true
429
430 srvSeed := RunServer(optsSeed)
431 defer srvSeed.Shutdown()
432
433 seedRouteURL := fmt.Sprintf("nats://%s:%d", optsSeed.Cluster.Host,
434 srvSeed.ClusterAddr().Port)
435 optsA := nextServerOpts(optsSeed)
436 optsA.Routes = RoutesFromStr(seedRouteURL)
437
438 srvA := RunServer(optsA)
439 defer srvA.Shutdown()
440
441 urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, srvA.Addr().(*net.TCPAddr).Port)
442
443 nc1, err := nats.Connect(urlA)
444 if err != nil {
445 t.Fatalf("Error creating client: %v\n", err)
446 }
447 defer nc1.Close()
448
449 // Test that we are connected.
450 ch := make(chan bool)
451 nc1.Subscribe("foo", func(m *nats.Msg) { ch <- true })
452 nc1.Flush()
453
454 optsB := nextServerOpts(optsA)
455 optsB.Routes = RoutesFromStr(seedRouteURL)
456
457 srvB := RunServer(optsB)
458 defer srvB.Shutdown()
459
460 urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, srvB.Addr().(*net.TCPAddr).Port)
461
462 nc2, err := nats.Connect(urlB)
463 if err != nil {
464 t.Fatalf("Error creating client: %v\n", err)
465 }
466 defer nc2.Close()
467
468 checkClusterFormed(t, srvSeed, srvA, srvB)
469 checkExpectedSubs(t, 1, srvB)
470
471 nc2.Publish("foo", []byte("Hello"))
472
473 // Wait for message
474 select {
475 case <-ch:
476 case <-time.After(2 * time.Second):
477 t.Fatal("Timeout waiting for message across route")
478 }
479 }
480
481 func TestChainedSolicitWorks(t *testing.T) {
482 optsSeed, err := ProcessConfigFile("./configs/seed.conf")
483 require_NoError(t, err)
484
485 optsSeed.NoSigs, optsSeed.NoLog = true, true
486 optsSeed.NoSystemAccount = true
487
488 srvSeed := RunServer(optsSeed)
489 defer srvSeed.Shutdown()
490
491 seedRouteURL := fmt.Sprintf("nats://%s:%d", optsSeed.Cluster.Host,
492 srvSeed.ClusterAddr().Port)
493 optsA := nextServerOpts(optsSeed)
494 optsA.Routes = RoutesFromStr(seedRouteURL)
495
496 srvA := RunServer(optsA)
497 defer srvA.Shutdown()
498
499 urlSeed := fmt.Sprintf("nats://%s:%d/", optsSeed.Host, srvA.Addr().(*net.TCPAddr).Port)
500
501 nc1, err := nats.Connect(urlSeed)
502 if err != nil {
503 t.Fatalf("Error creating client: %v\n", err)
504 }
505 defer nc1.Close()
506
507 // Test that we are connected.
508 ch := make(chan bool)
509 nc1.Subscribe("foo", func(m *nats.Msg) { ch <- true })
510 nc1.Flush()
511
512 optsB := nextServerOpts(optsA)
513 // Server B connects to A
514 optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host,
515 srvA.ClusterAddr().Port))
516
517 srvB := RunServer(optsB)
518 defer srvB.Shutdown()
519
520 urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, srvB.Addr().(*net.TCPAddr).Port)
521
522 nc2, err := nats.Connect(urlB)
523 if err != nil {
524 t.Fatalf("Error creating client: %v\n", err)
525 }
526 defer nc2.Close()
527
528 checkClusterFormed(t, srvSeed, srvA, srvB)
529 checkExpectedSubs(t, 1, srvB)
530
531 nc2.Publish("foo", []byte("Hello"))
532
533 // Wait for message
534 select {
535 case <-ch:
536 case <-time.After(2 * time.Second):
537 t.Fatal("Timeout waiting for message across route")
538 }
539 }
540
541 // Helper function to check that a server (or list of servers) have the
542 // expected number of subscriptions.
543 func checkExpectedSubs(t *testing.T, expected int, servers ...*Server) {
544 t.Helper()
545 checkFor(t, 4*time.Second, 10*time.Millisecond, func() error {
546 for _, s := range servers {
547 if numSubs := int(s.NumSubscriptions()); numSubs != expected {
548 return fmt.Errorf("Expected %d subscriptions for server %q, got %d", expected, s.ID(), numSubs)
549 }
550 }
551 return nil
552 })
553 }
554
555 func TestTLSChainedSolicitWorks(t *testing.T) {
556 optsSeed, err := ProcessConfigFile("./configs/seed_tls.conf")
557 require_NoError(t, err)
558
559 optsSeed.NoSigs, optsSeed.NoLog = true, true
560 optsSeed.NoSystemAccount = true
561
562 srvSeed := RunServer(optsSeed)
563 defer srvSeed.Shutdown()
564
565 urlSeedRoute := fmt.Sprintf("nats://%s:%d", optsSeed.Cluster.Host,
566 srvSeed.ClusterAddr().Port)
567 optsA := nextServerOpts(optsSeed)
568 optsA.Routes = RoutesFromStr(urlSeedRoute)
569
570 srvA := RunServer(optsA)
571 defer srvA.Shutdown()
572
573 urlSeed := fmt.Sprintf("nats://%s:%d/", optsSeed.Host, srvSeed.Addr().(*net.TCPAddr).Port)
574
575 nc1, err := nats.Connect(urlSeed)
576 if err != nil {
577 t.Fatalf("Error creating client: %v\n", err)
578 }
579 defer nc1.Close()
580
581 // Test that we are connected.
582 ch := make(chan bool)
583 nc1.Subscribe("foo", func(m *nats.Msg) { ch <- true })
584 nc1.Flush()
585
586 optsB := nextServerOpts(optsA)
587 // Server B connects to A
588 optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host,
589 srvA.ClusterAddr().Port))
590
591 srvB := RunServer(optsB)
592 defer srvB.Shutdown()
593
594 checkClusterFormed(t, srvSeed, srvA, srvB)
595 checkExpectedSubs(t, 1, srvA, srvB)
596
597 urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, srvB.Addr().(*net.TCPAddr).Port)
598
599 nc2, err := nats.Connect(urlB)
600 if err != nil {
601 t.Fatalf("Error creating client: %v\n", err)
602 }
603 defer nc2.Close()
604
605 nc2.Publish("foo", []byte("Hello"))
606
607 // Wait for message
608 select {
609 case <-ch:
610 case <-time.After(2 * time.Second):
611 t.Fatal("Timeout waiting for message across route")
612 }
613 }
614
615 func TestRouteTLSHandshakeError(t *testing.T) {
616 optsSeed, err := ProcessConfigFile("./configs/seed_tls.conf")
617 require_NoError(t, err)
618 optsSeed.NoLog = true
619 optsSeed.NoSigs = true
620 srvSeed := RunServer(optsSeed)
621 defer srvSeed.Shutdown()
622
623 opts := DefaultOptions()
624 opts.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsSeed.Cluster.Host, optsSeed.Cluster.Port))
625
626 srv := RunServer(opts)
627 defer srv.Shutdown()
628
629 time.Sleep(500 * time.Millisecond)
630
631 checkNumRoutes(t, srv, 0)
632 }
633
634 func TestBlockedShutdownOnRouteAcceptLoopFailure(t *testing.T) {
635 opts := DefaultOptions()
636 opts.Cluster.Host = "x.x.x.x"
637 opts.Cluster.Port = 7222
638
639 s := New(opts)
640 s.Start()
641 // Wait a second
642 time.Sleep(time.Second)
643 ch := make(chan bool)
644 go func() {
645 s.Shutdown()
646 ch <- true
647 }()
648
649 timeout := time.NewTimer(5 * time.Second)
650 select {
651 case <-ch:
652 return
653 case <-timeout.C:
654 t.Fatal("Shutdown did not complete")
655 }
656 }
657
658 func TestRouteUseIPv6(t *testing.T) {
659 opts := DefaultOptions()
660 opts.Cluster.Host = "::"
661 opts.Cluster.Port = 6222
662
663 // I believe that there is no IPv6 support on Travis...
664 // Regardless, cannot have this test fail simply because IPv6 is disabled
665 // on the host.
666 hp := net.JoinHostPort(opts.Cluster.Host, strconv.Itoa(opts.Cluster.Port))
667 _, err := net.ResolveTCPAddr("tcp", hp)
668 if err != nil {
669 t.Skipf("Skipping this test since there is no IPv6 support on this host: %v", err)
670 }
671
672 s := RunServer(opts)
673 defer s.Shutdown()
674
675 routeUp := false
676 timeout := time.Now().Add(5 * time.Second)
677 for time.Now().Before(timeout) && !routeUp {
678 // We know that the server is local and listening to
679 // all IPv6 interfaces. Try connect using IPv6 loopback.
680 if conn, err := net.Dial("tcp", "[::1]:6222"); err != nil {
681 // Travis seem to have the server actually listening to 0.0.0.0,
682 // so try with 127.0.0.1
683 if conn, err := net.Dial("tcp", "127.0.0.1:6222"); err != nil {
684 time.Sleep(time.Second)
685 continue
686 } else {
687 conn.Close()
688 }
689 } else {
690 conn.Close()
691 }
692 routeUp = true
693 }
694 if !routeUp {
695 t.Fatal("Server failed to start route accept loop")
696 }
697 }
698
699 func TestClientConnectToRoutePort(t *testing.T) {
700 opts := DefaultOptions()
701
702 // Since client will first connect to the route listen port, set the
703 // cluster's Host to 127.0.0.1 so it works on Windows too, since on
704 // Windows, a client can't use 0.0.0.0 in a connect.
705 opts.Cluster.Host = "127.0.0.1"
706 s := RunServer(opts)
707 defer s.Shutdown()
708
709 url := fmt.Sprintf("nats://%s:%d", opts.Cluster.Host, s.ClusterAddr().Port)
710 clientURL := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
711 // When connecting to the ROUTE port, the client library will receive the
712 // CLIENT port in the INFO protocol. This URL is added to the client's pool
713 // and will be tried after the initial connect failure. So all those
714 // nats.Connect() should succeed.
715 // The only reason for a failure would be if there are too many FDs in time-wait
716 // which would delay the creation of TCP connection. So keep the total of
717 // attempts rather small.
718 total := 10
719 for i := 0; i < total; i++ {
720 nc, err := nats.Connect(url)
721 if err != nil {
722 t.Fatalf("Unexpected error on connect: %v", err)
723 }
724 defer nc.Close()
725 if nc.ConnectedUrl() != clientURL {
726 t.Fatalf("Expected client to be connected to %v, got %v", clientURL, nc.ConnectedUrl())
727 }
728 }
729
730 s.Shutdown()
731 // Try again with NoAdvertise and this time, the client should fail to connect.
732 opts.Cluster.NoAdvertise = true
733 s = RunServer(opts)
734 defer s.Shutdown()
735
736 for i := 0; i < total; i++ {
737 nc, err := nats.Connect(url)
738 if err == nil {
739 nc.Close()
740 t.Fatal("Expected error on connect, got none")
741 }
742 }
743 }
744
745 type checkDuplicateRouteLogger struct {
746 DummyLogger
747 gotDuplicate bool
748 }
749
750 func (l *checkDuplicateRouteLogger) Debugf(format string, v ...any) {
751 l.Lock()
752 defer l.Unlock()
753 msg := fmt.Sprintf(format, v...)
754 if strings.Contains(msg, "duplicate remote route") {
755 l.gotDuplicate = true
756 }
757 }
758
759 func TestRoutesToEachOther(t *testing.T) {
760 optsA := DefaultOptions()
761 optsA.Cluster.Port = 7246
762 optsA.Routes = RoutesFromStr("nats://127.0.0.1:7247")
763
764 optsB := DefaultOptions()
765 optsB.Cluster.Port = 7247
766 optsB.Routes = RoutesFromStr("nats://127.0.0.1:7246")
767
768 srvALogger := &checkDuplicateRouteLogger{}
769 srvA := New(optsA)
770 srvA.SetLogger(srvALogger, true, false)
771 defer srvA.Shutdown()
772
773 srvBLogger := &checkDuplicateRouteLogger{}
774 srvB := New(optsB)
775 srvB.SetLogger(srvBLogger, true, false)
776 defer srvB.Shutdown()
777
778 go srvA.Start()
779 go srvB.Start()
780
781 start := time.Now()
782 checkClusterFormed(t, srvA, srvB)
783 end := time.Now()
784
785 srvALogger.Lock()
786 gotIt := srvALogger.gotDuplicate
787 srvALogger.Unlock()
788 if !gotIt {
789 srvBLogger.Lock()
790 gotIt = srvBLogger.gotDuplicate
791 srvBLogger.Unlock()
792 }
793 if gotIt {
794 dur := end.Sub(start)
795 // It should not take too long to have a successful connection
796 // between the 2 servers.
797 if dur > 5*time.Second {
798 t.Logf("Cluster formed, but took a long time: %v", dur)
799 }
800 } else {
801 t.Log("Was not able to get duplicate route this time!")
802 }
803 }
804
805 func wait(ch chan bool) error {
806 select {
807 case <-ch:
808 return nil
809 case <-time.After(5 * time.Second):
810 }
811 return fmt.Errorf("timeout")
812 }
813
814 func TestServerPoolUpdatedWhenRouteGoesAway(t *testing.T) {
815 s1Opts := DefaultOptions()
816 s1Opts.ServerName = "A"
817 s1Opts.Host = "127.0.0.1"
818 s1Opts.Port = 4222
819 s1Opts.Cluster.Host = "127.0.0.1"
820 s1Opts.Cluster.Port = 6222
821 s1Opts.Routes = RoutesFromStr("nats://127.0.0.1:6223,nats://127.0.0.1:6224")
822 s1 := RunServer(s1Opts)
823 defer s1.Shutdown()
824
825 s1Url := "nats://127.0.0.1:4222"
826 s2Url := "nats://127.0.0.1:4223"
827 s3Url := "nats://127.0.0.1:4224"
828
829 ch := make(chan bool, 1)
830 chch := make(chan bool, 1)
831 connHandler := func(_ *nats.Conn) {
832 chch <- true
833 }
834 nc, err := nats.Connect(s1Url,
835 nats.ReconnectWait(50*time.Millisecond),
836 nats.ReconnectHandler(connHandler),
837 nats.DiscoveredServersHandler(func(_ *nats.Conn) {
838 ch <- true
839 }))
840 if err != nil {
841 t.Fatalf("Error on connect")
842 }
843 defer nc.Close()
844
845 s2Opts := DefaultOptions()
846 s2Opts.ServerName = "B"
847 s2Opts.Host = "127.0.0.1"
848 s2Opts.Port = s1Opts.Port + 1
849 s2Opts.Cluster.Host = "127.0.0.1"
850 s2Opts.Cluster.Port = 6223
851 s2Opts.Routes = RoutesFromStr("nats://127.0.0.1:6222,nats://127.0.0.1:6224")
852 s2 := RunServer(s2Opts)
853 defer s2.Shutdown()
854
855 // Wait to be notified
856 if err := wait(ch); err != nil {
857 t.Fatal("New server callback was not invoked")
858 }
859
860 checkPool := func(expected []string) {
861 t.Helper()
862 // Don't use discovered here, but Servers to have the full list.
863 // Also, there may be cases where the mesh is not formed yet,
864 // so try again on failure.
865 checkFor(t, 5*time.Second, 50*time.Millisecond, func() error {
866 ds := nc.Servers()
867 if len(ds) == len(expected) {
868 m := make(map[string]struct{}, len(ds))
869 for _, url := range ds {
870 m[url] = struct{}{}
871 }
872 ok := true
873 for _, url := range expected {
874 if _, present := m[url]; !present {
875 ok = false
876 break
877 }
878 }
879 if ok {
880 return nil
881 }
882 }
883 return fmt.Errorf("Expected %v, got %v", expected, ds)
884 })
885 }
886 // Verify that we now know about s2
887 checkPool([]string{s1Url, s2Url})
888
889 s3Opts := DefaultOptions()
890 s3Opts.ServerName = "C"
891 s3Opts.Host = "127.0.0.1"
892 s3Opts.Port = s2Opts.Port + 1
893 s3Opts.Cluster.Host = "127.0.0.1"
894 s3Opts.Cluster.Port = 6224
895 s3Opts.Routes = RoutesFromStr("nats://127.0.0.1:6222,nats://127.0.0.1:6223")
896 s3 := RunServer(s3Opts)
897 defer s3.Shutdown()
898
899 // Wait to be notified
900 if err := wait(ch); err != nil {
901 t.Fatal("New server callback was not invoked")
902 }
903 // Verify that we now know about s3
904 checkPool([]string{s1Url, s2Url, s3Url})
905
906 // Stop s1. Since this was passed to the Connect() call, this one should
907 // still be present.
908 s1.Shutdown()
909 // Wait for reconnect
910 if err := wait(chch); err != nil {
911 t.Fatal("Reconnect handler not invoked")
912 }
913 checkPool([]string{s1Url, s2Url, s3Url})
914
915 // Check the server we reconnected to.
916 reConnectedTo := nc.ConnectedUrl()
917 expected := []string{s1Url}
918 if reConnectedTo == s2Url {
919 s2.Shutdown()
920 expected = append(expected, s3Url)
921 } else if reConnectedTo == s3Url {
922 s3.Shutdown()
923 expected = append(expected, s2Url)
924 } else {
925 t.Fatalf("Unexpected server client has reconnected to: %v", reConnectedTo)
926 }
927 // Wait for reconnect
928 if err := wait(chch); err != nil {
929 t.Fatal("Reconnect handler not invoked")
930 }
931 // The implicit server that we just shutdown should have been removed from the pool
932 checkPool(expected)
933 nc.Close()
934 }
935
936 func TestRouteFailedConnRemovedFromTmpMap(t *testing.T) {
937 for _, test := range []struct {
938 name string
939 poolSize int
940 }{
941 {"no pooling", -1},
942 {"pool 1", 1},
943 {"pool 3", 3},
944 } {
945 t.Run(test.name, func(t *testing.T) {
946 optsA, err := ProcessConfigFile("./configs/srv_a.conf")
947 require_NoError(t, err)
948 optsA.NoSigs, optsA.NoLog = true, true
949 optsA.Cluster.PoolSize = test.poolSize
950
951 optsB, err := ProcessConfigFile("./configs/srv_b.conf")
952 require_NoError(t, err)
953 optsB.NoSigs, optsB.NoLog = true, true
954 optsB.Cluster.PoolSize = test.poolSize
955
956 srvA := New(optsA)
957 defer srvA.Shutdown()
958 srvB := New(optsB)
959 defer srvB.Shutdown()
960
961 // Start this way to increase chance of having the two connect
962 // to each other at the same time. This will cause one of the
963 // route to be dropped.
964 wg := &sync.WaitGroup{}
965 wg.Add(2)
966 go func() {
967 srvA.Start()
968 wg.Done()
969 }()
970 go func() {
971 srvB.Start()
972 wg.Done()
973 }()
974
975 checkClusterFormed(t, srvA, srvB)
976
977 // Ensure that maps are empty
978 checkMap := func(s *Server) {
979 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
980 s.grMu.Lock()
981 l := len(s.grTmpClients)
982 s.grMu.Unlock()
983 if l != 0 {
984 return fmt.Errorf("grTmpClients map should be empty, got %v", l)
985 }
986 return nil
987 })
988 }
989 checkMap(srvA)
990 checkMap(srvB)
991
992 srvB.Shutdown()
993 srvA.Shutdown()
994 wg.Wait()
995 })
996 }
997 }
998
999 func getFirstRoute(s *Server) *client {
1000 for _, conns := range s.routes {
1001 for _, r := range conns {
1002 if r != nil {
1003 return r
1004 }
1005 }
1006 }
1007 return nil
1008 }
1009
1010 func TestRoutePermsAppliedOnInboundAndOutboundRoute(t *testing.T) {
1011
1012 perms := &RoutePermissions{
1013 Import: &SubjectPermission{
1014 Allow: []string{"imp.foo"},
1015 Deny: []string{"imp.bar"},
1016 },
1017 Export: &SubjectPermission{
1018 Allow: []string{"exp.foo"},
1019 Deny: []string{"exp.bar"},
1020 },
1021 }
1022
1023 optsA, err := ProcessConfigFile("./configs/seed.conf")
1024 require_NoError(t, err)
1025 optsA.NoLog = true
1026 optsA.NoSigs = true
1027 optsA.Cluster.Permissions = perms
1028 srva := RunServer(optsA)
1029 defer srva.Shutdown()
1030
1031 optsB := DefaultOptions()
1032 optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host, optsA.Cluster.Port))
1033 srvb := RunServer(optsB)
1034 defer srvb.Shutdown()
1035
1036 checkClusterFormed(t, srva, srvb)
1037
1038 // Ensure permission is properly set
1039 check := func(t *testing.T, s *Server) {
1040 t.Helper()
1041 var route *client
1042 s.mu.Lock()
1043 route = getFirstRoute(s)
1044 s.mu.Unlock()
1045 route.mu.Lock()
1046 perms := route.perms
1047 route.mu.Unlock()
1048 if perms == nil {
1049 t.Fatal("Expected perms to be set")
1050 }
1051 if perms.pub.allow == nil || perms.pub.allow.Count() != 1 {
1052 t.Fatal("unexpected pub allow perms")
1053 }
1054 if r := perms.pub.allow.Match("imp.foo"); len(r.psubs) != 1 {
1055 t.Fatal("unexpected pub allow match")
1056 }
1057 if perms.pub.deny == nil || perms.pub.deny.Count() != 1 {
1058 t.Fatal("unexpected pub deny perms")
1059 }
1060 if r := perms.pub.deny.Match("imp.bar"); len(r.psubs) != 1 {
1061 t.Fatal("unexpected pub deny match")
1062 }
1063 if perms.sub.allow == nil || perms.sub.allow.Count() != 1 {
1064 t.Fatal("unexpected sub allow perms")
1065 }
1066 if r := perms.sub.allow.Match("exp.foo"); len(r.psubs) != 1 {
1067 t.Fatal("unexpected sub allow match")
1068 }
1069 if perms.sub.deny == nil || perms.sub.deny.Count() != 1 {
1070 t.Fatal("unexpected sub deny perms")
1071 }
1072 if r := perms.sub.deny.Match("exp.bar"); len(r.psubs) != 1 {
1073 t.Fatal("unexpected sub deny match")
1074 }
1075 }
1076
1077 // First check when permissions are set on the server accepting the route connection
1078 check(t, srva)
1079
1080 srvb.Shutdown()
1081 srva.Shutdown()
1082
1083 optsA.Cluster.Permissions = nil
1084 optsB.Cluster.Permissions = perms
1085
1086 srva = RunServer(optsA)
1087 defer srva.Shutdown()
1088
1089 srvb = RunServer(optsB)
1090 defer srvb.Shutdown()
1091
1092 checkClusterFormed(t, srva, srvb)
1093
1094 // Now check for permissions set on server initiating the route connection
1095 check(t, srvb)
1096 }
1097
1098 func TestRouteSendLocalSubsWithLowMaxPending(t *testing.T) {
1099 optsA := DefaultOptions()
1100 optsA.MaxPayload = 1024
1101 optsA.MaxPending = 1024
1102 optsA.NoSystemAccount = true
1103 srvA := RunServer(optsA)
1104 defer srvA.Shutdown()
1105
1106 nc, err := nats.Connect(fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port))
1107 if err != nil {
1108 t.Fatalf("Error on connect: %v", err)
1109 }
1110 defer nc.Close()
1111 numSubs := 1000
1112 for i := 0; i < numSubs; i++ {
1113 subj := fmt.Sprintf("fo.bar.%d", i)
1114 nc.Subscribe(subj, func(_ *nats.Msg) {})
1115 }
1116 checkExpectedSubs(t, numSubs, srvA)
1117
1118 // Now create a route between B and A
1119 optsB := DefaultOptions()
1120 optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host, optsA.Cluster.Port))
1121 optsB.NoSystemAccount = true
1122 srvB := RunServer(optsB)
1123 defer srvB.Shutdown()
1124
1125 checkClusterFormed(t, srvA, srvB)
1126
1127 // Check that all subs have been sent ok
1128 checkExpectedSubs(t, numSubs, srvA, srvB)
1129 }
1130
1131 func TestRouteNoCrashOnAddingSubToRoute(t *testing.T) {
1132 opts := DefaultOptions()
1133 s := RunServer(opts)
1134 defer s.Shutdown()
1135
1136 numRoutes := routeTargetInit + 2
1137 total := int32(numRoutes)
1138 count := int32(0)
1139 ch := make(chan bool, 1)
1140 cb := func(_ *nats.Msg) {
1141 if n := atomic.AddInt32(&count, 1); n == total {
1142 ch <- true
1143 }
1144 }
1145
1146 var servers []*Server
1147 servers = append(servers, s)
1148
1149 seedURL := fmt.Sprintf("nats://%s:%d", opts.Cluster.Host, opts.Cluster.Port)
1150 for i := 0; i < numRoutes; i++ {
1151 ropts := DefaultOptions()
1152 ropts.Routes = RoutesFromStr(seedURL)
1153 rs := RunServer(ropts)
1154 defer rs.Shutdown()
1155 servers = append(servers, rs)
1156
1157 // Confirm routes are active before clients connect.
1158 for _, srv := range servers {
1159 rz, err := srv.Routez(nil)
1160 require_NoError(t, err)
1161 for i, route := range rz.Routes {
1162 if route.LastActivity.IsZero() {
1163 t.Errorf("Expected LastActivity to be valid (%d)", i)
1164 }
1165 }
1166 }
1167
1168 // Create a sub on each routed server.
1169 nc := natsConnect(t, fmt.Sprintf("nats://%s:%d", ropts.Host, ropts.Port))
1170 defer nc.Close()
1171 natsSub(t, nc, "foo", cb)
1172 }
1173 checkClusterFormed(t, servers...)
1174
1175 // Make sure all subs are registered in s.
1176 gacc := s.globalAccount()
1177 gacc.mu.RLock()
1178 sl := gacc.sl
1179 gacc.mu.RUnlock()
1180 checkFor(t, time.Second, 15*time.Millisecond, func() error {
1181 var _subs [64]*subscription
1182 subs := _subs[:0]
1183 sl.All(&subs)
1184 var ts int
1185 for _, sub := range subs {
1186 if string(sub.subject) == "foo" {
1187 ts++
1188 }
1189 }
1190 if ts != int(numRoutes) {
1191 return fmt.Errorf("Not all %d routed subs were registered: %d", numRoutes, ts)
1192 }
1193 return nil
1194 })
1195
1196 pubNC := natsConnect(t, fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port))
1197 defer pubNC.Close()
1198 natsPub(t, pubNC, "foo", []byte("hello world!"))
1199
1200 waitCh(t, ch, "Did not get all messages")
1201 }
1202
1203 func TestRouteRTT(t *testing.T) {
1204 ob := DefaultOptions()
1205 ob.PingInterval = 15 * time.Millisecond
1206 sb := RunServer(ob)
1207 defer sb.Shutdown()
1208
1209 oa := DefaultOptions()
1210 oa.PingInterval = 15 * time.Millisecond
1211 oa.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", ob.Cluster.Host, ob.Cluster.Port))
1212 sa := RunServer(oa)
1213 defer sa.Shutdown()
1214
1215 checkClusterFormed(t, sa, sb)
1216
1217 checkRTT := func(t *testing.T, s *Server) time.Duration {
1218 t.Helper()
1219 var route *client
1220 s.mu.Lock()
1221 route = getFirstRoute(s)
1222 s.mu.Unlock()
1223
1224 var rtt time.Duration
1225 checkFor(t, 2*firstPingInterval, 15*time.Millisecond, func() error {
1226 route.mu.Lock()
1227 rtt = route.rtt
1228 route.mu.Unlock()
1229 if rtt == 0 {
1230 return fmt.Errorf("RTT not tracked")
1231 }
1232 return nil
1233 })
1234 return rtt
1235 }
1236
1237 prevA := checkRTT(t, sa)
1238 prevB := checkRTT(t, sb)
1239
1240 checkUpdated := func(t *testing.T, s *Server, prev time.Duration) {
1241 t.Helper()
1242 attempts := 0
1243 timeout := time.Now().Add(2 * firstPingInterval)
1244 for time.Now().Before(timeout) {
1245 if rtt := checkRTT(t, s); rtt != prev {
1246 return
1247 }
1248 attempts++
1249 if attempts == 5 {
1250 // If could be that we are very unlucky
1251 // and the RTT is constant. So override
1252 // the route's RTT to 0 to see if it gets
1253 // updated.
1254 s.mu.Lock()
1255 if r := getFirstRoute(s); r != nil {
1256 r.mu.Lock()
1257 r.rtt = 0
1258 r.mu.Unlock()
1259 }
1260 s.mu.Unlock()
1261 }
1262 time.Sleep(15 * time.Millisecond)
1263 }
1264 t.Fatalf("RTT probably not updated")
1265 }
1266 checkUpdated(t, sa, prevA)
1267 checkUpdated(t, sb, prevB)
1268
1269 sa.Shutdown()
1270 sb.Shutdown()
1271
1272 // Now check that initial RTT is computed prior to first PingInterval
1273 // Get new options to avoid possible race changing the ping interval.
1274 ob = DefaultOptions()
1275 ob.PingInterval = time.Minute
1276 sb = RunServer(ob)
1277 defer sb.Shutdown()
1278
1279 oa = DefaultOptions()
1280 oa.PingInterval = time.Minute
1281 oa.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", ob.Cluster.Host, ob.Cluster.Port))
1282 sa = RunServer(oa)
1283 defer sa.Shutdown()
1284
1285 checkClusterFormed(t, sa, sb)
1286 checkRTT(t, sa)
1287 checkRTT(t, sb)
1288 }
1289
1290 func TestRouteCloseTLSConnection(t *testing.T) {
1291 opts := DefaultOptions()
1292 opts.DisableShortFirstPing = true
1293 opts.Cluster.Name = "A"
1294 opts.Cluster.Host = "127.0.0.1"
1295 opts.Cluster.Port = -1
1296 opts.Cluster.TLSTimeout = 100
1297 tc := &TLSConfigOpts{
1298 CertFile: "./configs/certs/server.pem",
1299 KeyFile: "./configs/certs/key.pem",
1300 Insecure: true,
1301 }
1302 tlsConf, err := GenTLSConfig(tc)
1303 if err != nil {
1304 t.Fatalf("Error generating tls config: %v", err)
1305 }
1306 opts.Cluster.TLSConfig = tlsConf
1307 opts.NoLog = true
1308 opts.NoSigs = true
1309 s := RunServer(opts)
1310 defer s.Shutdown()
1311
1312 endpoint := net.JoinHostPort(opts.Cluster.Host, fmt.Sprintf("%d", opts.Cluster.Port))
1313 conn, err := net.DialTimeout("tcp", endpoint, 2*time.Second)
1314 if err != nil {
1315 t.Fatalf("Unexpected error on dial: %v", err)
1316 }
1317 defer conn.Close()
1318
1319 tlsConn := tls.Client(conn, &tls.Config{InsecureSkipVerify: true})
1320 defer tlsConn.Close()
1321 if err := tlsConn.Handshake(); err != nil {
1322 t.Fatalf("Unexpected error during handshake: %v", err)
1323 }
1324 connectOp := []byte("CONNECT {\"name\":\"route\",\"verbose\":false,\"pedantic\":false,\"tls_required\":true,\"cluster\":\"A\"}\r\n")
1325 if _, err := tlsConn.Write(connectOp); err != nil {
1326 t.Fatalf("Unexpected error writing CONNECT: %v", err)
1327 }
1328 infoOp := []byte("INFO {\"server_id\":\"route\",\"tls_required\":true}\r\n")
1329 if _, err := tlsConn.Write(infoOp); err != nil {
1330 t.Fatalf("Unexpected error writing CONNECT: %v", err)
1331 }
1332 if _, err := tlsConn.Write([]byte("PING\r\n")); err != nil {
1333 t.Fatalf("Unexpected error writing PING: %v", err)
1334 }
1335
1336 checkFor(t, time.Second, 15*time.Millisecond, func() error {
1337 if s.NumRoutes() != 1 {
1338 return fmt.Errorf("No route registered yet")
1339 }
1340 return nil
1341 })
1342
1343 // Get route connection
1344 var route *client
1345 s.mu.Lock()
1346 route = getFirstRoute(s)
1347 s.mu.Unlock()
1348 // Fill the buffer. We want to timeout on write so that nc.Close()
1349 // would block due to a write that cannot complete.
1350 buf := make([]byte, 64*1024)
1351 done := false
1352 for !done {
1353 route.nc.SetWriteDeadline(time.Now().Add(time.Second))
1354 if _, err := route.nc.Write(buf); err != nil {
1355 done = true
1356 }
1357 route.nc.SetWriteDeadline(time.Time{})
1358 }
1359 ch := make(chan bool)
1360 go func() {
1361 select {
1362 case <-ch:
1363 return
1364 case <-time.After(3 * time.Second):
1365 fmt.Println("!!!! closeConnection is blocked, test will hang !!!")
1366 return
1367 }
1368 }()
1369 // Close the route
1370 route.closeConnection(SlowConsumerWriteDeadline)
1371 ch <- true
1372 }
1373
1374 func TestRouteClusterNameConflictBetweenStaticAndDynamic(t *testing.T) {
1375 o1 := DefaultOptions()
1376 o1.Cluster.Name = "AAAAAAAAAAAAAAAAAAAA" // make it alphabetically the "smallest"
1377 s1 := RunServer(o1)
1378 defer s1.Shutdown()
1379
1380 o2 := DefaultOptions()
1381 o2.Cluster.Name = "" // intentional, let it be assigned dynamically
1382 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
1383 s2 := RunServer(o2)
1384 defer s2.Shutdown()
1385
1386 checkClusterFormed(t, s1, s2)
1387 }
1388
1389 type testRouteResolver struct{}
1390
1391 func (r *testRouteResolver) LookupHost(ctx context.Context, host string) ([]string, error) {
1392 return []string{"127.0.0.1", "other.host.in.cluster"}, nil
1393 }
1394
1395 type routeHostLookupLogger struct {
1396 DummyLogger
1397 errCh chan string
1398 ch chan bool
1399 count int
1400 }
1401
1402 func (l *routeHostLookupLogger) Debugf(format string, v ...any) {
1403 l.Lock()
1404 defer l.Unlock()
1405 msg := fmt.Sprintf(format, v...)
1406 if strings.Contains(msg, "127.0.0.1:1234") {
1407 l.errCh <- msg
1408 } else if strings.Contains(msg, "other.host.in.cluster") {
1409 if l.count++; l.count == 10 {
1410 l.ch <- true
1411 }
1412 }
1413 }
1414
1415 func TestRouteIPResolutionAndRouteToSelf(t *testing.T) {
1416 o := DefaultOptions()
1417 o.Cluster.Port = 1234
1418 r := &testRouteResolver{}
1419 o.Cluster.resolver = r
1420 o.Routes = RoutesFromStr("nats://routehost:1234")
1421 o.Debug = true
1422 o.NoLog = false
1423 s, err := NewServer(o)
1424 if err != nil {
1425 t.Fatalf("Error creating server: %v", err)
1426 }
1427 defer s.Shutdown()
1428 l := &routeHostLookupLogger{errCh: make(chan string, 1), ch: make(chan bool, 1)}
1429 s.SetLogger(l, true, true)
1430 s.Start()
1431 if err := s.readyForConnections(time.Second); err != nil {
1432 t.Fatal(err)
1433 }
1434
1435 select {
1436 case e := <-l.errCh:
1437 t.Fatalf("Unexpected trace: %q", e)
1438 case <-l.ch:
1439 // Ok
1440 return
1441 }
1442 }
1443
1444 func TestRouteDuplicateServerName(t *testing.T) {
1445 o := DefaultOptions()
1446 o.ServerName = "A"
1447 s := RunServer(o)
1448 defer s.Shutdown()
1449
1450 l := &captureErrorLogger{errCh: make(chan string, 1)}
1451 s.SetLogger(l, false, false)
1452
1453 o2 := DefaultOptions()
1454 // Set the same server name on purpose
1455 o2.ServerName = "A"
1456 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o.Cluster.Port))
1457 s2 := RunServer(o2)
1458 defer s2.Shutdown()
1459
1460 // This is an error now so can't wait on cluster formed.
1461 select {
1462 case w := <-l.errCh:
1463 if !strings.Contains(w, "Remote server has a duplicate name") {
1464 t.Fatalf("Expected warning about same name, got %q", w)
1465 }
1466 case <-time.After(5 * time.Second):
1467 t.Fatal("Should have gotten a warning regarding duplicate server name")
1468 }
1469 }
1470
1471 func TestRouteLockReleasedOnTLSFailure(t *testing.T) {
1472 o1 := DefaultOptions()
1473 o1.Cluster.Name = "abc"
1474 o1.Cluster.Host = "127.0.0.1"
1475 o1.Cluster.Port = -1
1476 o1.Cluster.TLSTimeout = 0.25
1477 tc := &TLSConfigOpts{
1478 CertFile: "./configs/certs/server.pem",
1479 KeyFile: "./configs/certs/key.pem",
1480 Insecure: true,
1481 }
1482 tlsConf, err := GenTLSConfig(tc)
1483 if err != nil {
1484 t.Fatalf("Error generating tls config: %v", err)
1485 }
1486 o1.Cluster.TLSConfig = tlsConf
1487 s1 := RunServer(o1)
1488 defer s1.Shutdown()
1489
1490 l := &captureErrorLogger{errCh: make(chan string, 10)}
1491 s1.SetLogger(l, false, false)
1492
1493 o2 := DefaultOptions()
1494 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
1495 s2 := RunServer(o2)
1496 defer s2.Shutdown()
1497
1498 select {
1499 case err := <-l.errCh:
1500 if !strings.Contains(err, "TLS") {
1501 t.Fatalf("Unexpected error: %v", err)
1502 }
1503 case <-time.After(time.Second):
1504 }
1505
1506 s2.Shutdown()
1507
1508 // Wait for longer than the TLS timeout and check that tlsTimeout is not stuck
1509 time.Sleep(500 * time.Millisecond)
1510
1511 buf := make([]byte, 10000)
1512 n := runtime.Stack(buf, true)
1513 if bytes.Contains(buf[:n], []byte("tlsTimeout")) {
1514 t.Fatal("Seem connection lock was not released")
1515 }
1516 }
1517
1518 type localhostResolver struct{}
1519
1520 func (r *localhostResolver) LookupHost(ctx context.Context, host string) ([]string, error) {
1521 return []string{"127.0.0.1"}, nil
1522 }
1523
1524 func TestTLSRoutesCertificateImplicitAllowPass(t *testing.T) {
1525 testTLSRoutesCertificateImplicitAllow(t, true)
1526 }
1527
1528 func TestTLSRoutesCertificateImplicitAllowFail(t *testing.T) {
1529 testTLSRoutesCertificateImplicitAllow(t, false)
1530 }
1531
1532 func testTLSRoutesCertificateImplicitAllow(t *testing.T, pass bool) {
1533 // Base config for the servers
1534 cfg := createTempFile(t, "cfg")
1535 cfg.WriteString(fmt.Sprintf(`
1536 cluster {
1537 tls {
1538 cert_file = "../test/configs/certs/tlsauth/server.pem"
1539 key_file = "../test/configs/certs/tlsauth/server-key.pem"
1540 ca_file = "../test/configs/certs/tlsauth/ca.pem"
1541 verify_cert_and_check_known_urls = true
1542 insecure = %t
1543 timeout = 1
1544 }
1545 }
1546 `, !pass)) // set insecure to skip verification on the outgoing end
1547 if err := cfg.Sync(); err != nil {
1548 t.Fatal(err)
1549 }
1550 cfg.Close()
1551
1552 optsA := LoadConfig(cfg.Name())
1553 optsB := LoadConfig(cfg.Name())
1554
1555 routeURLs := "nats://localhost:9935, nats://localhost:9936"
1556 if !pass {
1557 routeURLs = "nats://127.0.0.1:9935, nats://127.0.0.1:9936"
1558 }
1559 optsA.Host = "127.0.0.1"
1560 optsA.Port = 9335
1561 optsA.Cluster.Name = "xyz"
1562 optsA.Cluster.Host = optsA.Host
1563 optsA.Cluster.Port = 9935
1564 optsA.Cluster.resolver = &localhostResolver{}
1565 optsA.Routes = RoutesFromStr(routeURLs)
1566 optsA.NoSystemAccount = true
1567 srvA := RunServer(optsA)
1568 defer srvA.Shutdown()
1569
1570 optsB.Host = "127.0.0.1"
1571 optsB.Port = 9336
1572 optsB.Cluster.Name = "xyz"
1573 optsB.Cluster.Host = optsB.Host
1574 optsB.Cluster.Port = 9936
1575 optsB.Cluster.resolver = &localhostResolver{}
1576 optsB.Routes = RoutesFromStr(routeURLs)
1577 optsB.NoSystemAccount = true
1578 srvB := RunServer(optsB)
1579 defer srvB.Shutdown()
1580
1581 if pass {
1582 checkNumRoutes(t, srvA, DEFAULT_ROUTE_POOL_SIZE)
1583 checkNumRoutes(t, srvB, DEFAULT_ROUTE_POOL_SIZE)
1584 } else {
1585 time.Sleep(1 * time.Second) // the fail case uses the IP, so a short wait is sufficient
1586 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
1587 if srvA.NumRoutes() != 0 || srvB.NumRoutes() != 0 {
1588 return fmt.Errorf("No route connection expected")
1589 }
1590 return nil
1591 })
1592 }
1593 }
1594
1595 func TestSubjectRenameViaJetStreamAck(t *testing.T) {
1596 s := RunRandClientPortServer(t)
1597 defer s.Shutdown()
1598 errChan := make(chan error)
1599 defer close(errChan)
1600 ncPub := natsConnect(t, s.ClientURL(), nats.UserInfo("client", "pwd"),
1601 nats.ErrorHandler(func(conn *nats.Conn, s *nats.Subscription, err error) {
1602 errChan <- err
1603 }))
1604 defer ncPub.Close()
1605 require_NoError(t, ncPub.PublishRequest("SVC.ALLOWED", "$JS.ACK.whatever@ADMIN", nil))
1606 select {
1607 case err := <-errChan:
1608 require_Contains(t, err.Error(), "Permissions Violation for Publish with Reply of")
1609 case <-time.After(time.Second):
1610 t.Fatalf("Expected error")
1611 }
1612 }
1613
1614 func TestClusterQueueGroupWeightTrackingLeak(t *testing.T) {
1615 o := DefaultOptions()
1616 o.ServerName = "A"
1617 s := RunServer(o)
1618 defer s.Shutdown()
1619
1620 o2 := DefaultOptions()
1621 o2.ServerName = "B"
1622 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o.Cluster.Port))
1623 s2 := RunServer(o2)
1624 defer s2.Shutdown()
1625
1626 nc := natsConnect(t, s.ClientURL())
1627 defer nc.Close()
1628
1629 // Create a queue subscription
1630 sub := natsQueueSubSync(t, nc, "foo", "bar")
1631
1632 // Check on s0 that we have the proper queue weight info
1633 acc := s.GlobalAccount()
1634
1635 check := func(present bool, expected int32) {
1636 t.Helper()
1637 sub := subscription{subject: []byte("foo"), queue: []byte("bar")}
1638 key := keyFromSubWithOrigin(&sub)
1639 checkFor(t, time.Second, 15*time.Millisecond, func() error {
1640 acc.mu.RLock()
1641 v, ok := acc.lws[key]
1642 acc.mu.RUnlock()
1643 if present {
1644 if !ok {
1645 return fmt.Errorf("the key is not present")
1646 }
1647 if v != expected {
1648 return fmt.Errorf("lws does not contain expected value of %v: %v", expected, v)
1649 }
1650 } else if ok {
1651 return fmt.Errorf("the key is present with value %v and should not be", v)
1652 }
1653 return nil
1654 })
1655 }
1656 check(true, 1)
1657
1658 // Now unsub, and it should be removed, not just be 0
1659 sub.Unsubscribe()
1660 check(false, 0)
1661
1662 // Still make sure that the subject interest is gone from both servers.
1663 checkSubGone := func(s *Server) {
1664 t.Helper()
1665 checkFor(t, time.Second, 15*time.Millisecond, func() error {
1666 acc := s.GlobalAccount()
1667 acc.mu.RLock()
1668 res := acc.sl.Match("foo")
1669 acc.mu.RUnlock()
1670 if res != nil && len(res.qsubs) > 0 {
1671 return fmt.Errorf("Found queue sub on foo for server %v", s)
1672 }
1673 return nil
1674 })
1675 }
1676 checkSubGone(s)
1677 checkSubGone(s2)
1678 }
1679
1680 type testRouteReconnectLogger struct {
1681 DummyLogger
1682 ch chan string
1683 }
1684
1685 func (l *testRouteReconnectLogger) Debugf(format string, v ...any) {
1686 msg := fmt.Sprintf(format, v...)
1687 if strings.Contains(msg, "Trying to connect to route") {
1688 select {
1689 case l.ch <- msg:
1690 default:
1691 }
1692 }
1693 }
1694
1695 func TestRouteSolicitedReconnectsEvenIfImplicit(t *testing.T) {
1696 o1 := DefaultOptions()
1697 o1.ServerName = "A"
1698 s1 := RunServer(o1)
1699 defer s1.Shutdown()
1700
1701 o2 := DefaultOptions()
1702 o2.ServerName = "B"
1703 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
1704 // Not strictly required to reconnect, but if the reconnect were to fail for any reason
1705 // then the server would retry only once and then stops. So set it to some higher value
1706 // and then we will check that the server does not try more than that.
1707 o2.Cluster.ConnectRetries = 3
1708 s2 := RunServer(o2)
1709 defer s2.Shutdown()
1710
1711 o3 := DefaultOptions()
1712 o3.ServerName = "C"
1713 o3.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
1714 o3.Cluster.ConnectRetries = 3
1715 s3 := RunServer(o3)
1716 defer s3.Shutdown()
1717
1718 checkClusterFormed(t, s1, s2, s3)
1719
1720 s2.mu.Lock()
1721 s2.forEachRoute(func(r *client) {
1722 r.mu.Lock()
1723 // Close the route between S2 and S3 (that do not have explicit route to each other)
1724 if r.route.remoteID == s3.ID() {
1725 r.nc.Close()
1726 }
1727 r.mu.Unlock()
1728 })
1729 s2.mu.Unlock()
1730 // Wait a bit to make sure that we don't check for cluster formed too soon (need to make
1731 // sure that connection is really removed and reconnect mechanism starts).
1732 time.Sleep(500 * time.Millisecond)
1733 checkClusterFormed(t, s1, s2, s3)
1734
1735 // Now shutdown server 3 and make sure that s2 stops trying to reconnect to s3 at one point
1736 l := &testRouteReconnectLogger{ch: make(chan string, 10)}
1737 s2.SetLogger(l, true, false)
1738 s3.Shutdown()
1739 // S2 should retry ConnectRetries+1 times and then stop
1740 // Take into account default route pool size and system account dedicated route
1741 for i := 0; i < (DEFAULT_ROUTE_POOL_SIZE+1)*(o2.Cluster.ConnectRetries+1); i++ {
1742 select {
1743 case <-l.ch:
1744 case <-time.After(2 * time.Second):
1745 t.Fatal("Did not attempt to reconnect")
1746 }
1747 }
1748 // Now it should have stopped (in tests, reconnect delay is down to 15ms, so we don't need
1749 // to wait for too long).
1750 select {
1751 case msg := <-l.ch:
1752 t.Fatalf("Unexpected attempt to reconnect: %s", msg)
1753 case <-time.After(50 * time.Millisecond):
1754 // OK
1755 }
1756 }
1757
1758 func TestRouteReconnectExponentialBackoff(t *testing.T) {
1759 oRouteConnectDelay := routeConnectDelay
1760 oRouteConnectMaxDelay := routeConnectMaxDelay
1761 routeConnectDelay = 500 * time.Millisecond
1762 routeConnectMaxDelay = 2 * time.Second
1763 defer func() {
1764 routeConnectDelay = oRouteConnectDelay
1765 routeConnectMaxDelay = oRouteConnectMaxDelay
1766 }()
1767
1768 o1 := DefaultOptions()
1769 o1.ServerName = "A"
1770 s1 := RunServer(o1)
1771 defer s1.Shutdown()
1772
1773 o2 := DefaultOptions()
1774 o2.ServerName = "B"
1775 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
1776 o2.Cluster.ConnectRetries = 3
1777 o2.Cluster.ConnectBackoff = true
1778 s2 := RunServer(o2)
1779 defer s2.Shutdown()
1780
1781 checkClusterFormed(t, s1, s2)
1782
1783 // Now shutdown server 1 and make sure that s2 stops trying to reconnect to s1 at one point
1784 l := &testRouteReconnectLogger{ch: make(chan string, 10)}
1785 s2.SetLogger(l, true, false)
1786
1787 // Remove initial delay before reconnect, and allow for some skew.
1788 now := time.Now().Add(DEFAULT_ROUTE_RECONNECT).Add(-100 * time.Millisecond)
1789 var delay time.Duration
1790
1791 // S2 should retry ConnectRetries+1 times and then stop
1792 // Take into account default route pool size and system account dedicated route
1793 s1.Shutdown()
1794 for i := 0; i < (DEFAULT_ROUTE_POOL_SIZE+1)*(o2.Cluster.ConnectRetries+1); i++ {
1795 select {
1796 case <-l.ch:
1797 if since := time.Since(now); since < delay {
1798 t.Fatalf("Expected delay to take %v, took %v", delay, since)
1799 }
1800 if i > 0 && (i+1)%(DEFAULT_ROUTE_POOL_SIZE+1) == 0 {
1801 if delay == 0 {
1802 delay = routeConnectDelay
1803 } else {
1804 delay *= 2
1805 }
1806 if delay > routeConnectMaxDelay {
1807 delay = routeConnectMaxDelay
1808 }
1809 }
1810 case <-time.After(routeConnectMaxDelay + time.Second):
1811 t.Fatal("Did not attempt to reconnect")
1812 }
1813 }
1814 }
1815
1816 func TestRouteSaveTLSName(t *testing.T) {
1817 c1Conf := createConfFile(t, []byte(`
1818 port: -1
1819 cluster {
1820 name: "abc"
1821 port: -1
1822 pool_size: -1
1823 tls {
1824 cert_file: '../test/configs/certs/server-noip.pem'
1825 key_file: '../test/configs/certs/server-key-noip.pem'
1826 ca_file: '../test/configs/certs/ca.pem'
1827 }
1828 }
1829 `))
1830 s1, o1 := RunServerWithConfig(c1Conf)
1831 defer s1.Shutdown()
1832
1833 tmpl := `
1834 port: -1
1835 cluster {
1836 name: "abc"
1837 port: -1
1838 pool_size: -1
1839 routes: ["nats://%s:%d"]
1840 tls {
1841 cert_file: '../test/configs/certs/server-noip.pem'
1842 key_file: '../test/configs/certs/server-key-noip.pem'
1843 ca_file: '../test/configs/certs/ca.pem'
1844 }
1845 }
1846 `
1847 c2And3Conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, "localhost", o1.Cluster.Port)))
1848 s2, _ := RunServerWithConfig(c2And3Conf)
1849 defer s2.Shutdown()
1850
1851 checkClusterFormed(t, s1, s2)
1852
1853 s3, _ := RunServerWithConfig(c2And3Conf)
1854 defer s3.Shutdown()
1855
1856 checkClusterFormed(t, s1, s2, s3)
1857
1858 reloadUpdateConfig(t, s2, c2And3Conf, fmt.Sprintf(tmpl, "127.0.0.1", o1.Cluster.Port))
1859
1860 s2.mu.RLock()
1861 s2.forEachRoute(func(r *client) {
1862 r.mu.Lock()
1863 if r.route.routeType == Implicit {
1864 r.nc.Close()
1865 }
1866 r.mu.Unlock()
1867 })
1868 s2.mu.RUnlock()
1869
1870 checkClusterFormed(t, s1, s2, s3)
1871
1872 // Set a logger to capture errors trying to connect after clearing
1873 // the routeTLSName and causing a disconnect
1874 l := &captureErrorLogger{errCh: make(chan string, 1)}
1875 s2.SetLogger(l, false, false)
1876
1877 var gotIt bool
1878 for i := 0; !gotIt && i < 5; i++ {
1879 s2.mu.Lock()
1880 s2.routeTLSName = _EMPTY_
1881 s2.forEachRoute(func(r *client) {
1882 r.mu.Lock()
1883 if r.route.routeType == Implicit {
1884 r.nc.Close()
1885 }
1886 r.mu.Unlock()
1887 })
1888 s2.mu.Unlock()
1889 select {
1890 case <-l.errCh:
1891 gotIt = true
1892 case <-time.After(time.Second):
1893 // Try again
1894 }
1895 }
1896 if !gotIt {
1897 t.Fatal("Did not get the handshake error")
1898 }
1899
1900 // Now get back to localhost in config and reload config and
1901 // it should start to work again.
1902 reloadUpdateConfig(t, s2, c2And3Conf, fmt.Sprintf(tmpl, "localhost", o1.Cluster.Port))
1903 checkClusterFormed(t, s1, s2, s3)
1904 }
1905
1906 func TestRoutePoolAndPerAccountErrors(t *testing.T) {
1907 conf := createConfFile(t, []byte(`
1908 port: -1
1909 cluster {
1910 port: -1
1911 accounts: ["abc", "def", "abc"]
1912 }
1913 `))
1914 o := LoadConfig(conf)
1915 if _, err := NewServer(o); err == nil || !strings.Contains(err.Error(), "duplicate") {
1916 t.Fatalf("Expected error about duplicate, got %v", err)
1917 }
1918
1919 conf1 := createConfFile(t, []byte(`
1920 port: -1
1921 accounts {
1922 abc { users: [{user:abc, password: pwd}] }
1923 def { users: [{user:def, password: pwd}] }
1924 }
1925 cluster {
1926 port: -1
1927 name: "local"
1928 accounts: ["abc"]
1929 }
1930 `))
1931 s1, o1 := RunServerWithConfig(conf1)
1932 defer s1.Shutdown()
1933
1934 l := &captureErrorLogger{errCh: make(chan string, 10)}
1935 s1.SetLogger(l, false, false)
1936
1937 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
1938 port: -1
1939 accounts {
1940 abc { users: [{user:abc, password: pwd}] }
1941 def { users: [{user:def, password: pwd}] }
1942 }
1943 cluster {
1944 port: -1
1945 name: "local"
1946 routes: ["nats://127.0.0.1:%d"]
1947 accounts: ["def"]
1948 }
1949 `, o1.Cluster.Port)))
1950 s2, _ := RunServerWithConfig(conf2)
1951 defer s2.Shutdown()
1952
1953 for i := 0; i < 2; i++ {
1954 select {
1955 case e := <-l.errCh:
1956 if !strings.Contains(e, "No route for account \"def\"") {
1957 t.Fatalf("Expected error about no route for account, got %v", e)
1958 }
1959 case <-time.After(2 * time.Second):
1960 t.Fatalf("Did not get expected error regarding no route for account")
1961 }
1962 time.Sleep(DEFAULT_ROUTE_RECONNECT + 100*time.Millisecond)
1963 }
1964 }
1965
1966 func TestRoutePool(t *testing.T) {
1967 tmpl := `
1968 port: -1
1969 accounts {
1970 A { users: [{user: "a", password: "a"}] }
1971 B { users: [{user: "b", password: "b"}] }
1972 }
1973 cluster {
1974 port: -1
1975 name: "local"
1976 %s
1977 pool_size: 2
1978 }
1979 `
1980 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, _EMPTY_)))
1981 s1, o1 := RunServerWithConfig(conf1)
1982 defer s1.Shutdown()
1983
1984 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl,
1985 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
1986 s2, _ := RunServerWithConfig(conf2)
1987 defer s2.Shutdown()
1988
1989 checkClusterFormed(t, s1, s2)
1990
1991 checkRoutePoolIdx := func(s *Server, accName string, expected int) {
1992 t.Helper()
1993 a, err := s.LookupAccount(accName)
1994 require_NoError(t, err)
1995 require_True(t, a != nil)
1996 a.mu.RLock()
1997 rpi := a.routePoolIdx
1998 a.mu.RUnlock()
1999 require_True(t, rpi == expected)
2000 }
2001 checkRoutePoolIdx(s1, "A", 0)
2002 checkRoutePoolIdx(s2, "A", 0)
2003 checkRoutePoolIdx(s2, "B", 1)
2004 checkRoutePoolIdx(s2, "B", 1)
2005
2006 sendAndRecv := func(acc, user, pwd string) {
2007 t.Helper()
2008 s2nc := natsConnect(t, s2.ClientURL(), nats.UserInfo(user, pwd))
2009 defer s2nc.Close()
2010
2011 sub := natsSubSync(t, s2nc, "foo")
2012 natsFlush(t, s2nc)
2013
2014 s1nc := natsConnect(t, s1.ClientURL(), nats.UserInfo(user, pwd))
2015 defer s1nc.Close()
2016
2017 checkSubInterest(t, s1, acc, "foo", time.Second)
2018
2019 for i := 0; i < 1000; i++ {
2020 natsPub(t, s1nc, "foo", []byte("hello"))
2021 }
2022 for i := 0; i < 1000; i++ {
2023 natsNexMsg(t, sub, time.Second)
2024 }
2025 // Make sure we don't receive more
2026 if msg, err := sub.NextMsg(150 * time.Millisecond); err == nil {
2027 t.Fatalf("Unexpected message: %+v", msg)
2028 }
2029 }
2030
2031 sendAndRecv("A", "a", "a")
2032 sendAndRecv("B", "b", "b")
2033
2034 checkStats := func(s *Server, isOut bool) {
2035 t.Helper()
2036 s.mu.RLock()
2037 defer s.mu.RUnlock()
2038 for _, conns := range s.routes {
2039 for i, r := range conns {
2040 r.mu.Lock()
2041 if isOut {
2042 if v := r.stats.outMsgs; v < 1000 {
2043 r.mu.Unlock()
2044 t.Fatalf("Expected at least 1000 in out msgs for route %v, got %v", i+1, v)
2045 }
2046 } else {
2047 if v := r.stats.inMsgs; v < 1000 {
2048 r.mu.Unlock()
2049 t.Fatalf("Expected at least 1000 in msgs for route %v, got %v", i+1, v)
2050 }
2051 }
2052 r.mu.Unlock()
2053 }
2054 }
2055 }
2056 checkStats(s1, true)
2057 checkStats(s2, false)
2058
2059 disconnectRoute := func(s *Server, idx int) {
2060 t.Helper()
2061 attempts := 0
2062 TRY_AGAIN:
2063 s.mu.RLock()
2064 for _, conns := range s.routes {
2065 for i, r := range conns {
2066 if i != idx {
2067 continue
2068 }
2069 if r != nil {
2070 r.mu.Lock()
2071 nc := r.nc
2072 r.mu.Unlock()
2073 if nc == nil {
2074 s.mu.RUnlock()
2075 if attempts++; attempts < 10 {
2076 time.Sleep(250 * time.Millisecond)
2077 goto TRY_AGAIN
2078 }
2079 t.Fatalf("Route %v net.Conn is nil", i)
2080 }
2081 nc.Close()
2082 } else {
2083 s.mu.RUnlock()
2084 if attempts++; attempts < 10 {
2085 time.Sleep(250 * time.Millisecond)
2086 goto TRY_AGAIN
2087 }
2088 t.Fatalf("Route %v connection is nil", i)
2089 }
2090 }
2091 }
2092 s.mu.RUnlock()
2093 time.Sleep(250 * time.Millisecond)
2094 checkClusterFormed(t, s1, s2)
2095 }
2096 disconnectRoute(s1, 0)
2097 disconnectRoute(s2, 1)
2098 }
2099
2100 func TestRoutePoolConnectRace(t *testing.T) {
2101 for _, test := range []struct {
2102 name string
2103 poolSize int
2104 }{
2105 {"no pool", -1},
2106 {"pool size 1", 1},
2107 {"pool size 5", 5},
2108 } {
2109 t.Run(test.name, func(t *testing.T) {
2110 // This test will have each server point to each other and that is causing
2111 // each one to attempt to connect routes to each other which should lead
2112 // to connections needing to be dropped. We make sure that there is still
2113 // resolution and there is the expected number of routes.
2114 createSrv := func(name string, port int) *Server {
2115 o := DefaultOptions()
2116 o.Port = -1
2117 o.ServerName = name
2118 o.Cluster.PoolSize = test.poolSize
2119 o.Cluster.Name = "local"
2120 o.Cluster.Port = port
2121 o.Routes = RoutesFromStr("nats://127.0.0.1:1234,nats://127.0.0.1:1235,nats://127.0.0.1:1236")
2122 s, err := NewServer(o)
2123 if err != nil {
2124 t.Fatalf("Error creating server: %v", err)
2125 }
2126 return s
2127 }
2128 s1 := createSrv("A", 1234)
2129 s2 := createSrv("B", 1235)
2130 s3 := createSrv("C", 1236)
2131
2132 l := &captureDebugLogger{dbgCh: make(chan string, 100)}
2133 s1.SetLogger(l, true, false)
2134
2135 servers := []*Server{s1, s2, s3}
2136
2137 for _, s := range servers {
2138 go s.Start()
2139 defer s.Shutdown()
2140 }
2141
2142 checkClusterFormed(t, s1, s2, s3)
2143
2144 for done, duplicate := false, 0; !done; {
2145 select {
2146 case e := <-l.dbgCh:
2147 if strings.Contains(e, "duplicate") {
2148 if duplicate++; duplicate > 20 {
2149 t.Fatalf("Routes are constantly reconnecting: %v", e)
2150 }
2151 }
2152 case <-time.After(DEFAULT_ROUTE_RECONNECT + 250*time.Millisecond):
2153 // More than reconnect and some, and no reconnect, so we are good.
2154 done = true
2155 }
2156 }
2157
2158 // Also, check that they all report as solicited and configured in monitoring.
2159 for _, s := range servers {
2160 routes, err := s.Routez(nil)
2161 require_NoError(t, err)
2162 for _, r := range routes.Routes {
2163 if !r.DidSolicit {
2164 t.Fatalf("All routes should have been marked as solicited, this one was not: %+v", r)
2165 }
2166 if !r.IsConfigured {
2167 t.Fatalf("All routes should have been marked as configured, this one was not: %+v", r)
2168 }
2169 }
2170 }
2171
2172 for _, s := range servers {
2173 s.Shutdown()
2174 s.WaitForShutdown()
2175 }
2176 })
2177 }
2178 }
2179
2180 func TestRoutePoolRouteStoredSameIndexBothSides(t *testing.T) {
2181 tmpl := `
2182 port: -1
2183 accounts {
2184 A { users: [{user: "a", password: "a"}] }
2185 B { users: [{user: "b", password: "b"}] }
2186 C { users: [{user: "c", password: "c"}] }
2187 D { users: [{user: "d", password: "d"}] }
2188 }
2189 cluster {
2190 port: -1
2191 name: "local"
2192 %s
2193 pool_size: 4
2194 }
2195 no_sys_acc: true
2196 `
2197 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, _EMPTY_)))
2198 s1, o1 := RunServerWithConfig(conf1)
2199 defer s1.Shutdown()
2200
2201 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl,
2202 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
2203 s2, _ := RunServerWithConfig(conf2)
2204 defer s2.Shutdown()
2205
2206 for i := 0; i < 20; i++ {
2207 checkClusterFormed(t, s1, s2)
2208
2209 collect := func(s *Server, checkRemoteAddr bool) []string {
2210 addrs := make([]string, 0, 4)
2211 s.mu.RLock()
2212 s.forEachRoute(func(r *client) {
2213 var addr string
2214 r.mu.Lock()
2215 if r.nc != nil {
2216 if checkRemoteAddr {
2217 addr = r.nc.RemoteAddr().String()
2218 } else {
2219 addr = r.nc.LocalAddr().String()
2220 }
2221 addrs = append(addrs, addr)
2222 }
2223 r.mu.Unlock()
2224 })
2225 s.mu.RUnlock()
2226 return addrs
2227 }
2228
2229 addrsS1 := collect(s1, true)
2230 addrsS2 := collect(s2, false)
2231 if len(addrsS1) != 4 || len(addrsS2) != 4 {
2232 // It could be that connections were not ready (r.nc is nil in collect())
2233 // if that is the case, try again.
2234 i--
2235 continue
2236 }
2237
2238 if !reflect.DeepEqual(addrsS1, addrsS2) {
2239 t.Fatalf("Connections not stored at same index:\ns1=%v\ns2=%v", addrsS1, addrsS2)
2240 }
2241
2242 s1.mu.RLock()
2243 s1.forEachRoute(func(r *client) {
2244 r.mu.Lock()
2245 if r.nc != nil {
2246 r.nc.Close()
2247 }
2248 r.mu.Unlock()
2249 })
2250 s1.mu.RUnlock()
2251 }
2252 }
2253
2254 func TestRoutePoolSizeDifferentOnEachServer(t *testing.T) {
2255 tmpl := `
2256 port: -1
2257 server_name: "%s"
2258 accounts {
2259 A { users: [{user: "A", password: "pwd"}] }
2260 B { users: [{user: "B", password: "pwd"}] }
2261 C { users: [{user: "C", password: "pwd"}] }
2262 D { users: [{user: "D", password: "pwd"}] }
2263 }
2264 cluster {
2265 port: -1
2266 name: "local"
2267 %s
2268 pool_size: %d
2269 accounts: [%s]
2270 }
2271 no_sys_acc: true
2272 `
2273 conf1 := createConfFile(t, fmt.Appendf(nil, tmpl, "S1", _EMPTY_, 3, `"A"`))
2274 s1, o1 := RunServerWithConfig(conf1)
2275 defer s1.Shutdown()
2276
2277 conf2 := createConfFile(t, fmt.Appendf(nil, tmpl, "S2",
2278 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port), 2, `"A"`))
2279 s2, o2 := RunServerWithConfig(conf2)
2280 defer s2.Shutdown()
2281
2282 conf3 := createConfFile(t, fmt.Appendf(nil, tmpl, "S3",
2283 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port), 4, `"A"`))
2284 s3, o3 := RunServerWithConfig(conf3)
2285 defer s3.Shutdown()
2286
2287 // Since each one has a different configured pool size, we are not going
2288 // to use checkClusterFormed, but use a low level checFor here.
2289 servers := []*Server{s1, s2, s3}
2290
2291 // Both S2 and S3 solicit connections to S1, and with the order the servers
2292 // are started, S2 will implicitly connect to S3. With that in mind, the
2293 // expected number of routes for each server will be as such:
2294 // S1: when S2 solicits 2+1 routes, it will detect that S1 is configured
2295 // for 3+1, so S1<->S2 will have the max of the two, which is 4 routes,
2296 // then when S3 solicits its 4+1 routes, the total will be 4+5=9 routes.
2297 // S2: it solicits 2+1 but since S1 is configured for 3+1, it will have
2298 // 3+1 routes to S1, and when being told to connect to S3, it will start
2299 // with 2+1 but since S3 is configured for 4+1, it will have that many
2300 // connections, so total is 4+5=9 too.
2301 // S3: it solicits 4+1 routes to S1, so S1 although configured for 3+1
2302 // will accept the 4+1, and when S2 implicitly connects to S3, it will
2303 // force S2 to create 4+1 connections too. So here the total is 5+5=10.
2304 expected := []int{9, 9, 10}
2305 checkCluster := func() {
2306 t.Helper()
2307 // In most case, we will do a config reload and want to give time
2308 // for connections to be closed before checking.
2309 time.Sleep(50 * time.Millisecond)
2310 for i, s := range servers {
2311 if !s.isRunning() {
2312 continue
2313 }
2314 checkFor(t, 10*time.Second, 25*time.Millisecond, func() error {
2315 if numRoutes := s.NumRoutes(); numRoutes != expected[i] {
2316 return fmt.Errorf("Expected %d routes for server %q, got %d", expected[i], s, numRoutes)
2317 }
2318 return nil
2319 })
2320 }
2321 }
2322 checkCluster()
2323
2324 // We will create a subscription per account per server.
2325 accs := []string{"A", "B", "C", "D"}
2326 var aconns [][]*nats.Conn
2327 var asubs [][]*nats.Subscription
2328 for _, acc := range accs {
2329 var subs []*nats.Subscription
2330 var conns []*nats.Conn
2331 for _, s := range servers {
2332 nc := natsConnect(t, s.ClientURL(), nats.UserInfo(acc, "pwd"))
2333 defer nc.Close()
2334 conns = append(conns, nc)
2335 sub := natsSubSync(t, nc, "foo")
2336 subs = append(subs, sub)
2337 }
2338 asubs = append(asubs, subs)
2339 aconns = append(aconns, conns)
2340 }
2341
2342 // Now we will check that a message produced on each account from
2343 // each server reaches all subs.
2344 checkRecv := func(payload string) {
2345 t.Helper()
2346 // We first to check the interest on all servers for each account
2347 for _, s := range servers {
2348 for _, acc := range accs {
2349 checkSubInterest(t, s, acc, "foo", time.Second)
2350 }
2351 }
2352
2353 // Now from each server, and each account, send a message and check
2354 // that all subs for this account receive the message.
2355 for _, s := range servers {
2356 for i, acc := range accs {
2357 nc := natsConnect(t, s.ClientURL(), nats.UserInfo(acc, "pwd"))
2358 defer nc.Close()
2359
2360 natsPub(t, nc, "foo", []byte(payload))
2361 for j, sub := range asubs[i] {
2362 if _, err := sub.NextMsg(time.Second); err != nil {
2363 t.Fatalf("Producer on %q - account=%q - sub on server %q - err=%v",
2364 s, acc, servers[j], err)
2365 }
2366 // Wait a tiny bit and check that there is not a duplicate
2367 if msg, err := sub.NextMsg(10 * time.Millisecond); err == nil {
2368 t.Fatalf("Producer on %q - account=%q - sub on server %q received a duplicate msg=%s",
2369 s, acc, servers[j], msg.Data)
2370 }
2371 }
2372 }
2373 }
2374 }
2375 checkRecv("hello1")
2376
2377 // Now that the 3 servers are up and we know their route port, we will
2378 // update the config of each server so that they have routes that point
2379 // to each other (so each server will solicit) and for routes to be
2380 // recreated, then test again.
2381 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "S1",
2382 fmt.Sprintf("routes:[\"nats://127.0.0.1:%d\",\"nats://127.0.0.1:%d\"]", o2.Cluster.Port, o3.Cluster.Port), 3, `"A"`))
2383 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "S2",
2384 fmt.Sprintf("routes:[\"nats://127.0.0.1:%d\",\"nats://127.0.0.1:%d\"]", o1.Cluster.Port, o3.Cluster.Port), 2, `"A"`))
2385 reloadUpdateConfig(t, s3, conf3, fmt.Sprintf(tmpl, "S3",
2386 fmt.Sprintf("routes:[\"nats://127.0.0.1:%d\",\"nats://127.0.0.1:%d\"]", o1.Cluster.Port, o2.Cluster.Port), 4, `"A"`))
2387
2388 time.Sleep(50 * time.Millisecond)
2389
2390 // Collect all route TCP connections so we close them all as fast as possible
2391 var rcs []net.Conn
2392 for _, s := range servers {
2393 s.mu.RLock()
2394 s.forEachRoute(func(r *client) {
2395 r.mu.Lock()
2396 rcs = append(rcs, r.nc)
2397 r.mu.Unlock()
2398 })
2399 s.mu.RUnlock()
2400 }
2401 // Close all connections
2402 for _, c := range rcs {
2403 c.Close()
2404 }
2405
2406 checkCluster()
2407 checkRecv("hello2")
2408
2409 // Now we will make account "B" have a dedicated route, and remove the one for "A"
2410 // Now upgrade one of the account to a dedicated route.
2411 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "S1",
2412 fmt.Sprintf("routes:[\"nats://127.0.0.1:%d\",\"nats://127.0.0.1:%d\"]", o2.Cluster.Port, o3.Cluster.Port), 3, `"B"`))
2413 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "S2",
2414 fmt.Sprintf("routes:[\"nats://127.0.0.1:%d\",\"nats://127.0.0.1:%d\"]", o1.Cluster.Port, o3.Cluster.Port), 2, `"B"`))
2415 reloadUpdateConfig(t, s3, conf3, fmt.Sprintf(tmpl, "S3",
2416 fmt.Sprintf("routes:[\"nats://127.0.0.1:%d\",\"nats://127.0.0.1:%d\"]", o1.Cluster.Port, o2.Cluster.Port), 4, `"B"`))
2417
2418 checkCluster()
2419 checkRecv("hello3")
2420
2421 // Since we are going to shutdown and not restart S3,
2422 // close client connections to this server.
2423 for _, conns := range aconns {
2424 conns[2].Close()
2425 }
2426 // Get S3 server ID and shut it down.
2427 s3ID := s3.ID()
2428 s3.Shutdown()
2429
2430 // Wait for routes to be gone from S1 and S2.
2431 expected = []int{4, 4}
2432 servers = servers[:2]
2433 checkCluster()
2434
2435 // Check that both S1 and S2 have cleaned-up the remoteRoutePoolSize for S3.
2436 for _, s := range servers {
2437 s.mu.RLock()
2438 rps, ok := s.remoteRoutePoolSize[s3ID]
2439 s.mu.RUnlock()
2440 if ok {
2441 t.Fatalf("On server %q, found remote pool size of %v for S3", s, rps)
2442 }
2443 }
2444
2445 s1.Shutdown()
2446 s2.Shutdown()
2447
2448 // Now start 2 servers with different pool size.
2449 conf1 = createConfFile(t, fmt.Appendf(nil, tmpl, "S1", _EMPTY_, 3, `"A"`))
2450 s1, o1 = RunServerWithConfig(conf1)
2451 defer s1.Shutdown()
2452
2453 conf2 = createConfFile(t, fmt.Appendf(nil, tmpl, "S2",
2454 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port), 2, `"A"`))
2455 s2, _ = RunServerWithConfig(conf2)
2456 defer s2.Shutdown()
2457
2458 servers = []*Server{s1, s2}
2459 expected = []int{4, 4}
2460 checkCluster()
2461
2462 // Now check that S1 and S2 have the proper remoteRoutePoolSize to each other.
2463 expectedRPS := func(s *Server, otherID string, expected int) {
2464 t.Helper()
2465 s.mu.RLock()
2466 defer s.mu.RUnlock()
2467 rps, ok := s.remoteRoutePoolSize[otherID]
2468 require_True(t, ok)
2469 require_Equal(t, rps, expected)
2470 }
2471 s2ID := s2.ID()
2472 expectedRPS(s1, s2ID, 2)
2473 expectedRPS(s2, s1.ID(), 3)
2474
2475 // We will now config reload S2 with an increased pool size, but we want
2476 // to have S1 in a condition where the update does not go through the
2477 // process of re-creating the connections slice completely, which could
2478 // happen when the config reload reconnect from S2 to S1 happens in a way
2479 // that the earlier connections in the slice are replaced before the later
2480 // are, which prevents the situation in removeRoute() where all slots are
2481 // empty. To do so with certainty, we are going to replace the last
2482 // connection in s1's routes with a "fake" one that is not going to close
2483 // when s2 reloads.
2484 s1.mu.Lock()
2485 conns, ok := s1.routes[s2ID]
2486 if ok {
2487 rc := conns[2]
2488 conns[2] = &client{kind: ROUTER, route: &route{}}
2489 // Empty the slot in a bit and close the old connection.
2490 time.AfterFunc(150*time.Millisecond, func() {
2491 s1.mu.Lock()
2492 conns, ok := s1.routes[s2ID]
2493 if ok {
2494 conns[2] = nil
2495 }
2496 s1.mu.Unlock()
2497 rc.closeConnection(ReadError)
2498 })
2499 }
2500 s1.mu.Unlock()
2501 require_True(t, ok)
2502
2503 // Increase the pool size.
2504 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "S2",
2505 fmt.Sprintf("routes:[\"nats://127.0.0.1:%d\"]", o1.Cluster.Port), 4, `"A"`))
2506 expected = []int{5, 5}
2507 checkCluster()
2508
2509 expectedRPS(s1, s2ID, 4)
2510 expectedRPS(s2, s1.ID(), 3)
2511
2512 // Try to decrease now...
2513 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "S2",
2514 fmt.Sprintf("routes:[\"nats://127.0.0.1:%d\"]", o1.Cluster.Port), 2, `"A"`))
2515 expected = []int{4, 4}
2516 checkCluster()
2517
2518 expectedRPS(s1, s2ID, 2)
2519 expectedRPS(s2, s1.ID(), 3)
2520 }
2521
2522 type captureRMsgTrace struct {
2523 DummyLogger
2524 sync.Mutex
2525 traces *bytes.Buffer
2526 out []string
2527 }
2528
2529 func (l *captureRMsgTrace) Tracef(format string, args ...any) {
2530 l.Lock()
2531 defer l.Unlock()
2532 msg := fmt.Sprintf(format, args...)
2533 if strings.Contains(msg, "[RMSG ") {
2534 l.traces.WriteString(msg)
2535 l.out = append(l.out, msg)
2536 }
2537 }
2538
2539 func TestRoutePerAccount(t *testing.T) {
2540
2541 akp1, _ := nkeys.CreateAccount()
2542 acc1, _ := akp1.PublicKey()
2543
2544 akp2, _ := nkeys.CreateAccount()
2545 acc2, _ := akp2.PublicKey()
2546
2547 tmpl := `
2548 port: -1
2549 accounts {
2550 %s { users: [{user: "a", password: "a"}] }
2551 %s { users: [{user: "b", password: "b"}] }
2552 }
2553 cluster {
2554 port: -1
2555 name: "local"
2556 %s
2557 accounts: ["%s"]
2558 }
2559 `
2560 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, acc1, acc2, _EMPTY_, acc2)))
2561 s1, o1 := RunServerWithConfig(conf1)
2562 defer s1.Shutdown()
2563
2564 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl,
2565 acc1, acc2,
2566 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port),
2567 acc2)))
2568 s2, _ := RunServerWithConfig(conf2)
2569 defer s2.Shutdown()
2570
2571 l := &captureRMsgTrace{traces: &bytes.Buffer{}}
2572 s2.SetLogger(l, false, true)
2573
2574 checkClusterFormed(t, s1, s2)
2575
2576 disconnectRoute := func(s *Server) {
2577 t.Helper()
2578 attempts := 0
2579 TRY_AGAIN:
2580 s.mu.RLock()
2581 if conns, ok := s.accRoutes[acc2]; ok {
2582 for _, r := range conns {
2583 if r != nil {
2584 r.mu.Lock()
2585 nc := r.nc
2586 r.mu.Unlock()
2587 if nc == nil {
2588 s.mu.RUnlock()
2589 if attempts++; attempts < 10 {
2590 time.Sleep(250 * time.Millisecond)
2591 goto TRY_AGAIN
2592 }
2593 t.Fatal("Route net.Conn is nil")
2594 }
2595 nc.Close()
2596 } else {
2597 s.mu.RUnlock()
2598 if attempts++; attempts < 10 {
2599 time.Sleep(250 * time.Millisecond)
2600 goto TRY_AGAIN
2601 }
2602 t.Fatal("Route connection is nil")
2603 }
2604 }
2605 }
2606 s.mu.RUnlock()
2607 time.Sleep(250 * time.Millisecond)
2608 checkClusterFormed(t, s1, s2)
2609 }
2610 disconnectRoute(s1)
2611 disconnectRoute(s2)
2612
2613 sendAndRecv := func(acc, user, pwd string) {
2614 t.Helper()
2615 s2nc := natsConnect(t, s2.ClientURL(), nats.UserInfo(user, pwd))
2616 defer s2nc.Close()
2617
2618 sub := natsSubSync(t, s2nc, "foo")
2619 natsFlush(t, s2nc)
2620
2621 s1nc := natsConnect(t, s1.ClientURL(), nats.UserInfo(user, pwd))
2622 defer s1nc.Close()
2623
2624 checkSubInterest(t, s1, acc, "foo", time.Second)
2625
2626 for i := 0; i < 10; i++ {
2627 natsPub(t, s1nc, "foo", []byte("hello"))
2628 }
2629 for i := 0; i < 10; i++ {
2630 natsNexMsg(t, sub, time.Second)
2631 }
2632 // Make sure we don't receive more
2633 if msg, err := sub.NextMsg(150 * time.Millisecond); err == nil {
2634 t.Fatalf("Unexpected message: %+v", msg)
2635 }
2636 }
2637
2638 sendAndRecv(acc1, "a", "a")
2639 sendAndRecv(acc2, "b", "b")
2640
2641 l.Lock()
2642 traces := l.traces.String()
2643 out := append([]string(nil), l.out...)
2644 l.Unlock()
2645 // We should not have any "[RMSG <acc2>"
2646 if strings.Contains(traces, fmt.Sprintf("[RMSG %s", acc2)) {
2647 var outStr string
2648 for _, l := range out {
2649 outStr += l + "\r\n"
2650 }
2651 t.Fatalf("Should not have included account %q in protocol, got:\n%s", acc2, outStr)
2652 }
2653 }
2654
2655 func TestRoutePerAccountImplicit(t *testing.T) {
2656 tmpl := `
2657 port: -1
2658 accounts {
2659 A { users: [{user: "a", password: "a"}] }
2660 B { users: [{user: "b", password: "b"}] }
2661 }
2662 cluster {
2663 port: -1
2664 name: "local"
2665 accounts: ["A"]
2666 %s
2667 }
2668 `
2669 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, _EMPTY_)))
2670 s1, o1 := RunServerWithConfig(conf1)
2671 defer s1.Shutdown()
2672
2673 conf2And3 := createConfFile(t, []byte(fmt.Sprintf(tmpl,
2674 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
2675 s2, _ := RunServerWithConfig(conf2And3)
2676 defer s2.Shutdown()
2677
2678 checkClusterFormed(t, s1, s2)
2679
2680 s3, _ := RunServerWithConfig(conf2And3)
2681 defer s3.Shutdown()
2682
2683 checkClusterFormed(t, s1, s2, s3)
2684
2685 // On s3, close the per-account routes from s2
2686 s3.mu.RLock()
2687 for _, conns := range s3.accRoutes {
2688 for rem, r := range conns {
2689 if rem != s2.ID() {
2690 continue
2691 }
2692 r.mu.Lock()
2693 if r.nc != nil {
2694 r.nc.Close()
2695 }
2696 r.mu.Unlock()
2697 }
2698 }
2699 s3.mu.RUnlock()
2700 // Wait a bit to make sure there is a disconnect, then check the cluster is ok
2701 time.Sleep(250 * time.Millisecond)
2702 checkClusterFormed(t, s1, s2, s3)
2703 }
2704
2705 func TestRoutePerAccountDefaultForSysAccount(t *testing.T) {
2706 tmpl := `
2707 port: -1
2708 accounts {
2709 A { users: [{user: "a", password: "a"}] }
2710 B { users: [{user: "b", password: "b"}] }
2711 }
2712 cluster {
2713 port: -1
2714 name: "local"
2715 %s
2716 %s
2717 %s
2718 }
2719 %s
2720 `
2721 for _, test := range []struct {
2722 name string
2723 accounts string
2724 sysAcc string
2725 noSysAcc bool
2726 }{
2727 {"default sys no accounts", _EMPTY_, _EMPTY_, false},
2728 {"default sys in accounts", "accounts: [\"$SYS\"]", _EMPTY_, false},
2729 {"default sys with other accounts", "accounts: [\"A\",\"$SYS\"]", _EMPTY_, false},
2730 {"explicit sys no accounts", _EMPTY_, "system_account: B", false},
2731 {"explicit sys in accounts", "accounts: [\"B\"]", "system_account: B", false},
2732 {"explicit sys with other accounts", "accounts: [\"B\",\"A\"]", "system_account: B", false},
2733 {"no system account no accounts", _EMPTY_, "no_sys_acc: true", true},
2734 {"no system account with accounts", "accounts: [\"A\"]", "no_sys_acc: true", true},
2735 } {
2736 t.Run(test.name, func(t *testing.T) {
2737 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, _EMPTY_, test.accounts,
2738 _EMPTY_, test.sysAcc)))
2739 s1, o1 := RunServerWithConfig(conf1)
2740 defer s1.Shutdown()
2741
2742 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, _EMPTY_, test.accounts,
2743 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port), test.sysAcc)))
2744 s2, _ := RunServerWithConfig(conf2)
2745 defer s2.Shutdown()
2746
2747 checkClusterFormed(t, s1, s2)
2748
2749 checkSysAccRoute := func(s *Server) {
2750 t.Helper()
2751 var name string
2752 acc := s.SystemAccount()
2753 if test.noSysAcc {
2754 if acc != nil {
2755 t.Fatalf("Should not be any system account, got %q", acc.GetName())
2756 }
2757 // We will check that there is no accRoutes for the default
2758 // system account name
2759 name = DEFAULT_SYSTEM_ACCOUNT
2760 } else {
2761 acc.mu.RLock()
2762 pi := acc.routePoolIdx
2763 name = acc.Name
2764 acc.mu.RUnlock()
2765 if pi != -1 {
2766 t.Fatalf("System account %q should have route pool index==-1, got %v", name, pi)
2767 }
2768 }
2769 s.mu.RLock()
2770 _, ok := s.accRoutes[name]
2771 s.mu.RUnlock()
2772 if test.noSysAcc {
2773 if ok {
2774 t.Fatalf("System account %q should not have its own route, since NoSystemAccount was specified", name)
2775 }
2776 } else if !ok {
2777 t.Fatalf("System account %q should be present in accRoutes, it was not", name)
2778 }
2779 }
2780 checkSysAccRoute(s1)
2781 checkSysAccRoute(s2)
2782
2783 // Check that this is still the case after a config reload
2784 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "pool_size: 4", test.accounts,
2785 _EMPTY_, test.sysAcc))
2786 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "pool_size: 4", test.accounts,
2787 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port), test.sysAcc))
2788
2789 checkSysAccRoute(s1)
2790 checkSysAccRoute(s2)
2791 })
2792 }
2793 }
2794
2795 func TestRoutePerAccountConnectRace(t *testing.T) {
2796 // This test will have each server point to each other and that is causing
2797 // each one to attempt to connect routes to each other which should lead
2798 // to connections needing to be dropped. We make sure that there is still
2799 // resolution and there is the expected number of routes.
2800 createSrv := func(name string, port int) *Server {
2801 o := DefaultOptions()
2802 o.Port = -1
2803 o.ServerName = name
2804 o.Accounts = []*Account{NewAccount("A")}
2805 o.NoSystemAccount = true
2806 o.Cluster.PoolSize = 1
2807 o.Cluster.PinnedAccounts = []string{"A"}
2808 o.Cluster.Name = "local"
2809 o.Cluster.Port = port
2810 o.Routes = RoutesFromStr("nats://127.0.0.1:1234,nats://127.0.0.1:1235,nats://127.0.0.1:1236")
2811 s, err := NewServer(o)
2812 if err != nil {
2813 t.Fatalf("Error creating server: %v", err)
2814 }
2815 return s
2816 }
2817 s1 := createSrv("A", 1234)
2818 s2 := createSrv("B", 1235)
2819 s3 := createSrv("C", 1236)
2820
2821 l := &captureDebugLogger{dbgCh: make(chan string, 100)}
2822 s1.SetLogger(l, true, false)
2823
2824 servers := []*Server{s1, s2, s3}
2825
2826 for _, s := range servers {
2827 go s.Start()
2828 defer s.Shutdown()
2829 }
2830
2831 checkClusterFormed(t, s1, s2, s3)
2832
2833 for done, duplicate := false, 0; !done; {
2834 select {
2835 case e := <-l.dbgCh:
2836 if strings.Contains(e, "duplicate") {
2837 if duplicate++; duplicate > 10 {
2838 t.Fatalf("Routes are constantly reconnecting: %v", e)
2839 }
2840 }
2841 case <-time.After(DEFAULT_ROUTE_RECONNECT + 250*time.Millisecond):
2842 // More than reconnect and some, and no reconnect, so we are good.
2843 done = true
2844 }
2845 }
2846
2847 // Also, check that they all report as solicited and configured in monitoring.
2848 for _, s := range servers {
2849 routes, err := s.Routez(nil)
2850 require_NoError(t, err)
2851 for _, r := range routes.Routes {
2852 if !r.DidSolicit {
2853 t.Fatalf("All routes should have been marked as solicited, this one was not: %+v", r)
2854 }
2855 if !r.IsConfigured {
2856 t.Fatalf("All routes should have been marked as configured, this one was not: %+v", r)
2857 }
2858 }
2859 }
2860
2861 for _, s := range servers {
2862 s.Shutdown()
2863 s.WaitForShutdown()
2864 }
2865 }
2866
2867 func TestRoutePerAccountGossipWorks(t *testing.T) {
2868 tmplA := `
2869 port: -1
2870 server_name: "A"
2871 accounts {
2872 A { users: [{user: "A", password: "pwd"}] }
2873 B { users: [{user: "B", password: "pwd"}] }
2874 }
2875 cluster {
2876 port: %d
2877 name: "local"
2878 accounts: ["A"]
2879 %s
2880 }
2881 `
2882 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmplA, -1, _EMPTY_)))
2883 s1, o1 := RunServerWithConfig(conf1)
2884 defer s1.Shutdown()
2885
2886 tmplBC := `
2887 port: -1
2888 server_name: "%s"
2889 accounts {
2890 A { users: [{user: "A", password: "pwd"}] }
2891 B { users: [{user: "B", password: "pwd"}] }
2892 }
2893 cluster {
2894 port: -1
2895 name: "local"
2896 %s
2897 accounts: ["A"]
2898 }
2899 `
2900 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmplBC, "B",
2901 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
2902 s2, _ := RunServerWithConfig(conf2)
2903 defer s2.Shutdown()
2904
2905 checkClusterFormed(t, s1, s2)
2906
2907 // Now connect s3 to s1 and make sure that s2 connects properly to s3.
2908 conf3 := createConfFile(t, []byte(fmt.Sprintf(tmplBC, "C",
2909 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
2910 s3, _ := RunServerWithConfig(conf3)
2911 defer s3.Shutdown()
2912
2913 checkClusterFormed(t, s1, s2, s3)
2914
2915 s3.Shutdown()
2916 s2.Shutdown()
2917 s1.Shutdown()
2918
2919 // Slightly different version where s2 is connecting to s1, while s1
2920 // connects to s3 (and s3 does not solicit connections).
2921
2922 conf1 = createConfFile(t, []byte(fmt.Sprintf(tmplA, -1, _EMPTY_)))
2923 s1, o1 = RunServerWithConfig(conf1)
2924 defer s1.Shutdown()
2925
2926 conf2 = createConfFile(t, []byte(fmt.Sprintf(tmplBC, "B",
2927 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
2928 s2, _ = RunServerWithConfig(conf2)
2929 defer s2.Shutdown()
2930
2931 checkClusterFormed(t, s1, s2)
2932
2933 // Start s3 first that will simply accept connections
2934 conf3 = createConfFile(t, []byte(fmt.Sprintf(tmplBC, "C", _EMPTY_)))
2935 s3, o3 := RunServerWithConfig(conf3)
2936 defer s3.Shutdown()
2937
2938 // Now config reload s1 so that it points to s3.
2939 reloadUpdateConfig(t, s1, conf1,
2940 fmt.Sprintf(tmplA, o1.Cluster.Port, fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o3.Cluster.Port)))
2941
2942 checkClusterFormed(t, s1, s2, s3)
2943 }
2944
2945 func TestRoutePerAccountGossipWorksWithOldServerNotSeed(t *testing.T) {
2946 tmplA := `
2947 port: -1
2948 server_name: "A"
2949 accounts {
2950 A { users: [{user: "A", password: "pwd"}] }
2951 B { users: [{user: "B", password: "pwd"}] }
2952 }
2953 cluster {
2954 port: %d
2955 name: "local"
2956 accounts: ["A"]
2957 }
2958 `
2959 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmplA, -1)))
2960 s1, o1 := RunServerWithConfig(conf1)
2961 defer s1.Shutdown()
2962
2963 // Here, server "B" will have no pooling/accounts.
2964 tmplB := `
2965 port: -1
2966 server_name: "B"
2967 accounts {
2968 A { users: [{user: "A", password: "pwd"}] }
2969 B { users: [{user: "B", password: "pwd"}] }
2970 }
2971 cluster {
2972 port: -1
2973 name: "local"
2974 routes: ["nats://127.0.0.1:%d"]
2975 pool_size: -1
2976 }
2977 `
2978 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmplB, o1.Cluster.Port)))
2979 s2, _ := RunServerWithConfig(conf2)
2980 defer s2.Shutdown()
2981
2982 checkClusterFormed(t, s1, s2)
2983
2984 l := &captureErrorLogger{errCh: make(chan string, 100)}
2985 s2.SetLogger(l, false, false)
2986
2987 // Now connect s3 to s1. Server s1 should not gossip to s2 information
2988 // about pinned-account routes or extra routes from the pool.
2989 tmplC := `
2990 port: -1
2991 server_name: "C"
2992 accounts {
2993 A { users: [{user: "A", password: "pwd"}] }
2994 B { users: [{user: "B", password: "pwd"}] }
2995 }
2996 cluster {
2997 port: -1
2998 name: "local"
2999 routes: ["nats://127.0.0.1:%d"]
3000 accounts: ["A"]
3001 }
3002 `
3003 conf3 := createConfFile(t, []byte(fmt.Sprintf(tmplC, o1.Cluster.Port)))
3004 s3, _ := RunServerWithConfig(conf3)
3005 defer s3.Shutdown()
3006
3007 checkClusterFormed(t, s1, s2, s3)
3008
3009 // We should not have had s2 try to create dedicated routes for "A" or "$SYS"
3010 tm := time.NewTimer(time.Second)
3011 defer tm.Stop()
3012 for {
3013 select {
3014 case err := <-l.errCh:
3015 if strings.Contains(err, "dedicated route") {
3016 t.Fatalf("Server s2 should not have tried to create a dedicated route: %s", err)
3017 }
3018 case <-tm.C:
3019 return
3020 }
3021 }
3022 }
3023
3024 func TestRoutePerAccountGossipWorksWithOldServerSeed(t *testing.T) {
3025 tmplA := `
3026 port: -1
3027 server_name: "A"
3028 accounts {
3029 A { users: [{user: "A", password: "pwd"}] }
3030 B { users: [{user: "B", password: "pwd"}] }
3031 }
3032 cluster {
3033 port: %d
3034 name: "local"
3035 pool_size: %d
3036 %s
3037 }
3038 `
3039 // Start with s1 being an "old" server, which does not support pooling/pinned-accounts.
3040 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmplA, -1, -1, _EMPTY_)))
3041 s1, o1 := RunServerWithConfig(conf1)
3042 defer s1.Shutdown()
3043
3044 tmplBC := `
3045 port: -1
3046 server_name: "%s"
3047 accounts {
3048 A { users: [{user: "A", password: "pwd"}] }
3049 B { users: [{user: "B", password: "pwd"}] }
3050 }
3051 cluster {
3052 port: -1
3053 name: "local"
3054 pool_size: 3
3055 routes: ["nats://127.0.0.1:%d"]
3056 accounts: ["A"]
3057 }
3058 `
3059 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmplBC, "B", o1.Cluster.Port)))
3060 s2, _ := RunServerWithConfig(conf2)
3061 defer s2.Shutdown()
3062
3063 checkClusterFormed(t, s1, s2)
3064
3065 // Now connect s3 to s1 and make sure that s2 connects properly to s3.
3066 conf3 := createConfFile(t, []byte(fmt.Sprintf(tmplBC, "C", o1.Cluster.Port)))
3067 s3, _ := RunServerWithConfig(conf3)
3068 defer s3.Shutdown()
3069
3070 checkClusterFormed(t, s1, s2, s3)
3071
3072 checkRoutes := func(s *Server, expected int) {
3073 t.Helper()
3074 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
3075 if nr := s.NumRoutes(); nr != expected {
3076 return fmt.Errorf("Server %q should have %v routes, got %v", s.Name(), expected, nr)
3077 }
3078 return nil
3079 })
3080 }
3081 // Since s1 has no pooling/pinned-accounts, there should be only 2 routes,
3082 // one to s2 and one to s3.
3083 checkRoutes(s1, 2)
3084 // s2 and s3 should have 1 route to s1 and 3(pool)+"A"+"$SYS" == 6
3085 checkRoutes(s2, 6)
3086 checkRoutes(s3, 6)
3087
3088 s1.Shutdown()
3089
3090 // The server s1 will now support pooling and accounts pinning.
3091 // Restart the server s1 with the same cluster port otherwise
3092 // s2/s3 would not be able to reconnect.
3093 conf1 = createConfFile(t, []byte(fmt.Sprintf(tmplA, o1.Cluster.Port, 3, "accounts: [\"A\"]")))
3094 s1, _ = RunServerWithConfig(conf1)
3095 defer s1.Shutdown()
3096 // Make sure reconnect occurs. We should now have 5 routes.
3097 checkClusterFormed(t, s1, s2, s3)
3098 // Now all servers should have 3+2 to each other, so 10 total.
3099 checkRoutes(s1, 10)
3100 checkRoutes(s2, 10)
3101 checkRoutes(s3, 10)
3102 }
3103
3104 func TestRoutePoolPerAccountSubUnsubProtoParsing(t *testing.T) {
3105 for _, test := range []struct {
3106 name string
3107 extra string
3108 }{
3109 {"regular", _EMPTY_},
3110 {"pooling", "pool_size: 5"},
3111 {"per-account", "accounts: [\"A\"]"},
3112 } {
3113 t.Run(test.name, func(t *testing.T) {
3114 confATemplate := `
3115 port: -1
3116 accounts {
3117 A { users: [{user: "user1", password: "pwd"}] }
3118 }
3119 cluster {
3120 listen: 127.0.0.1:-1
3121 %s
3122 }
3123 `
3124 confA := createConfFile(t, []byte(fmt.Sprintf(confATemplate, test.extra)))
3125 srva, optsA := RunServerWithConfig(confA)
3126 defer srva.Shutdown()
3127
3128 confBTemplate := `
3129 port: -1
3130 accounts {
3131 A { users: [{user: "user1", password: "pwd"}] }
3132 }
3133 cluster {
3134 listen: 127.0.0.1:-1
3135 routes = [
3136 "nats://127.0.0.1:%d"
3137 ]
3138 %s
3139 }
3140 `
3141 confB := createConfFile(t, []byte(fmt.Sprintf(confBTemplate, optsA.Cluster.Port, test.extra)))
3142 srvb, _ := RunServerWithConfig(confB)
3143 defer srvb.Shutdown()
3144
3145 checkClusterFormed(t, srva, srvb)
3146
3147 ncA := natsConnect(t, srva.ClientURL(), nats.UserInfo("user1", "pwd"))
3148 defer ncA.Close()
3149
3150 for i := 0; i < 2; i++ {
3151 var sub *nats.Subscription
3152 if i == 0 {
3153 sub = natsSubSync(t, ncA, "foo")
3154 } else {
3155 sub = natsQueueSubSync(t, ncA, "foo", "bar")
3156 }
3157
3158 checkSubInterest(t, srvb, "A", "foo", 2*time.Second)
3159
3160 checkSubs := func(s *Server, queue, expected bool) {
3161 t.Helper()
3162 acc, err := s.LookupAccount("A")
3163 if err != nil {
3164 t.Fatalf("Error looking account: %v", err)
3165 }
3166 checkFor(t, time.Second, 15*time.Millisecond, func() error {
3167 acc.mu.RLock()
3168 res := acc.sl.Match("foo")
3169 acc.mu.RUnlock()
3170 if expected {
3171 if queue && (len(res.qsubs) == 0 || len(res.psubs) != 0) {
3172 return fmt.Errorf("Expected queue sub, did not find it")
3173 } else if !queue && (len(res.psubs) == 0 || len(res.qsubs) != 0) {
3174 return fmt.Errorf("Expected psub, did not find it")
3175 }
3176 } else if len(res.psubs)+len(res.qsubs) != 0 {
3177 return fmt.Errorf("Unexpected subscription: %+v", res)
3178 }
3179 return nil
3180 })
3181 }
3182
3183 checkSubs(srva, i == 1, true)
3184 checkSubs(srvb, i == 1, true)
3185
3186 sub.Unsubscribe()
3187 natsFlush(t, ncA)
3188
3189 checkSubs(srva, i == 1, false)
3190 checkSubs(srvb, i == 1, false)
3191 }
3192 })
3193 }
3194 }
3195
3196 func TestRoutePoolPerAccountStreamImport(t *testing.T) {
3197 for _, test := range []struct {
3198 name string
3199 route string
3200 }{
3201 {"regular", _EMPTY_},
3202 {"pooled", "pool_size: 5"},
3203 {"one per account", "accounts: [\"A\"]"},
3204 {"both per account", "accounts: [\"A\", \"B\"]"},
3205 } {
3206 t.Run(test.name, func(t *testing.T) {
3207 tmplA := `
3208 server_name: "A"
3209 port: -1
3210 accounts {
3211 A {
3212 users: [{user: "user1", password: "pwd"}]
3213 exports: [{stream: "foo"}]
3214 }
3215 B {
3216 users: [{user: "user2", password: "pwd"}]
3217 imports: [{stream: {subject: "foo", account: "A"}}]
3218 }
3219 C { users: [{user: "user3", password: "pwd"}] }
3220 D { users: [{user: "user4", password: "pwd"}] }
3221 }
3222 cluster {
3223 name: "local"
3224 listen: 127.0.0.1:-1
3225 %s
3226 }
3227 `
3228 confA := createConfFile(t, []byte(fmt.Sprintf(tmplA, test.route)))
3229 srva, optsA := RunServerWithConfig(confA)
3230 defer srva.Shutdown()
3231
3232 tmplB := `
3233 server_name: "B"
3234 port: -1
3235 accounts {
3236 A {
3237 users: [{user: "user1", password: "pwd"}]
3238 exports: [{stream: "foo"}]
3239 }
3240 B {
3241 users: [{user: "user2", password: "pwd"}]
3242 imports: [{stream: {subject: "foo", account: "A"}}]
3243 }
3244 C { users: [{user: "user3", password: "pwd"}] }
3245 D { users: [{user: "user4", password: "pwd"}] }
3246 }
3247 cluster {
3248 name: "local"
3249 listen: 127.0.0.1:-1
3250 %s
3251 %s
3252 }
3253 `
3254 confB := createConfFile(t, []byte(fmt.Sprintf(tmplB,
3255 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", optsA.Cluster.Port),
3256 test.route)))
3257 srvb, _ := RunServerWithConfig(confB)
3258 defer srvb.Shutdown()
3259
3260 checkClusterFormed(t, srva, srvb)
3261
3262 ncB := natsConnect(t, srvb.ClientURL(), nats.UserInfo("user2", "pwd"))
3263 defer ncB.Close()
3264
3265 sub := natsSubSync(t, ncB, "foo")
3266
3267 checkSubInterest(t, srva, "B", "foo", time.Second)
3268 checkSubInterest(t, srva, "A", "foo", time.Second)
3269
3270 ncA := natsConnect(t, srva.ClientURL(), nats.UserInfo("user1", "pwd"))
3271 defer ncA.Close()
3272
3273 natsPub(t, ncA, "foo", []byte("hello"))
3274 natsNexMsg(t, sub, time.Second)
3275
3276 natsUnsub(t, sub)
3277 natsFlush(t, ncB)
3278
3279 checkFor(t, time.Second, 15*time.Millisecond, func() error {
3280 for _, acc := range []string{"A", "B"} {
3281 a, err := srva.LookupAccount(acc)
3282 if err != nil {
3283 return err
3284 }
3285 a.mu.RLock()
3286 r := a.sl.Match("foo")
3287 a.mu.RUnlock()
3288 if len(r.psubs) != 0 {
3289 return fmt.Errorf("Subscription not unsubscribed")
3290 }
3291 }
3292 return nil
3293 })
3294 })
3295 }
3296 }
3297
3298 func TestRoutePoolAndPerAccountWithServiceLatencyNoDataRace(t *testing.T) {
3299 // For this test, we want the system (SYS) and SERVICE accounts to be bound
3300 // to different routes. So the names and pool size have been chosen accordingly.
3301 for _, test := range []struct {
3302 name string
3303 poolStr string
3304 }{
3305 {"pool", "pool_size: 5"},
3306 {"per account", "accounts: [\"SYS\", \"SERVICE\", \"REQUESTOR\"]"},
3307 } {
3308 t.Run(test.name, func(t *testing.T) {
3309 tmpl := `
3310 port: -1
3311 accounts {
3312 SYS {
3313 users [{user: "sys", password: "pwd"}]
3314 }
3315 SERVICE {
3316 users [{user: "svc", password: "pwd"}]
3317 exports = [
3318 {service: "req.*", latency: {subject: "results"}}
3319 ]
3320 }
3321 REQUESTOR {
3322 users [{user: "req", password: "pwd"}]
3323 imports = [
3324 {service: {account: "SERVICE", subject: "req.echo"}, to: "request"}
3325 ]
3326 }
3327 }
3328 system_account: "SYS"
3329 cluster {
3330 name: "local"
3331 port: -1
3332 %s
3333 %s
3334 }
3335 `
3336 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, test.poolStr, _EMPTY_)))
3337 s1, opts1 := RunServerWithConfig(conf1)
3338 defer s1.Shutdown()
3339
3340 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, test.poolStr,
3341 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", opts1.Cluster.Port))))
3342 s2, _ := RunServerWithConfig(conf2)
3343 defer s2.Shutdown()
3344
3345 checkClusterFormed(t, s1, s2)
3346
3347 // Create service provider.
3348 nc := natsConnect(t, s1.ClientURL(), nats.UserInfo("svc", "pwd"))
3349 defer nc.Close()
3350
3351 // The service listener.
3352 natsSub(t, nc, "req.echo", func(msg *nats.Msg) {
3353 msg.Respond(msg.Data)
3354 })
3355
3356 // Listen for metrics
3357 rsub := natsSubSync(t, nc, "results")
3358 natsFlush(t, nc)
3359 checkSubInterest(t, s2, "SERVICE", "results", time.Second)
3360
3361 // Create second client and send request from this one.
3362 nc2 := natsConnect(t, s2.ClientURL(), nats.UserInfo("req", "pwd"))
3363 defer nc2.Close()
3364
3365 for i := 0; i < 5; i++ {
3366 // Send the request.
3367 _, err := nc2.Request("request", []byte("hello"), time.Second)
3368 require_NoError(t, err)
3369 // Get the latency result
3370 natsNexMsg(t, rsub, time.Second)
3371 }
3372 })
3373 }
3374 }
3375
3376 func TestRouteParseOriginClusterMsgArgs(t *testing.T) {
3377 for _, test := range []struct {
3378 racc bool
3379 args string
3380 pacache string
3381 reply string
3382 queues [][]byte
3383 }{
3384 {true, "ORIGIN foo 12 345\r\n", "MY_ACCOUNT foo", _EMPTY_, nil},
3385 {true, "ORIGIN foo bar 12 345\r\n", "MY_ACCOUNT foo", "bar", nil},
3386 {true, "ORIGIN foo + bar queue1 queue2 12 345\r\n", "MY_ACCOUNT foo", "bar", [][]byte{[]byte("queue1"), []byte("queue2")}},
3387 {true, "ORIGIN foo | queue1 queue2 12 345\r\n", "MY_ACCOUNT foo", _EMPTY_, [][]byte{[]byte("queue1"), []byte("queue2")}},
3388
3389 {false, "ORIGIN MY_ACCOUNT foo 12 345\r\n", "MY_ACCOUNT foo", _EMPTY_, nil},
3390 {false, "ORIGIN MY_ACCOUNT foo bar 12 345\r\n", "MY_ACCOUNT foo", "bar", nil},
3391 {false, "ORIGIN MY_ACCOUNT foo + bar queue1 queue2 12 345\r\n", "MY_ACCOUNT foo", "bar", [][]byte{[]byte("queue1"), []byte("queue2")}},
3392 {false, "ORIGIN MY_ACCOUNT foo | queue1 queue2 12 345\r\n", "MY_ACCOUNT foo", _EMPTY_, [][]byte{[]byte("queue1"), []byte("queue2")}},
3393 } {
3394 t.Run(test.args, func(t *testing.T) {
3395 c := &client{kind: ROUTER, route: &route{}}
3396 if test.racc {
3397 c.route.accName = []byte("MY_ACCOUNT")
3398 }
3399 if err := c.processRoutedOriginClusterMsgArgs([]byte(test.args)); err != nil {
3400 t.Fatalf("Error processing: %v", err)
3401 }
3402 if string(c.pa.origin) != "ORIGIN" {
3403 t.Fatalf("Invalid origin: %q", c.pa.origin)
3404 }
3405 if string(c.pa.account) != "MY_ACCOUNT" {
3406 t.Fatalf("Invalid account: %q", c.pa.account)
3407 }
3408 if string(c.pa.subject) != "foo" {
3409 t.Fatalf("Invalid subject: %q", c.pa.subject)
3410 }
3411 if string(c.pa.reply) != test.reply {
3412 t.Fatalf("Invalid reply: %q", c.pa.reply)
3413 }
3414 if !reflect.DeepEqual(c.pa.queues, test.queues) {
3415 t.Fatalf("Invalid queues: %v", c.pa.queues)
3416 }
3417 if c.pa.hdr != 12 {
3418 t.Fatalf("Invalid header size: %v", c.pa.hdr)
3419 }
3420 if c.pa.size != 345 {
3421 t.Fatalf("Invalid size: %v", c.pa.size)
3422 }
3423 })
3424 }
3425 }
3426
3427 func TestRoutePoolAndPerAccountOperatorMode(t *testing.T) {
3428 _, spub := createKey(t)
3429 sysClaim := jwt.NewAccountClaims(spub)
3430 sysClaim.Name = "SYS"
3431 sysJwt := encodeClaim(t, sysClaim, spub)
3432
3433 akp, apub := createKey(t)
3434 claima := jwt.NewAccountClaims(apub)
3435 ajwt := encodeClaim(t, claima, apub)
3436
3437 bkp, bpub := createKey(t)
3438 claimb := jwt.NewAccountClaims(bpub)
3439 bjwt := encodeClaim(t, claimb, bpub)
3440
3441 ckp, cpub := createKey(t)
3442 claimc := jwt.NewAccountClaims(cpub)
3443 cjwt := encodeClaim(t, claimc, cpub)
3444
3445 _, dpub := createKey(t)
3446
3447 basePath := "/ngs/v1/accounts/jwt/"
3448 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
3449 if r.URL.Path == basePath {
3450 w.Write([]byte("ok"))
3451 } else if strings.HasSuffix(r.URL.Path, spub) {
3452 w.Write([]byte(sysJwt))
3453 } else if strings.HasSuffix(r.URL.Path, apub) {
3454 w.Write([]byte(ajwt))
3455 } else if strings.HasSuffix(r.URL.Path, bpub) {
3456 w.Write([]byte(bjwt))
3457 } else if strings.HasSuffix(r.URL.Path, cpub) {
3458 w.Write([]byte(cjwt))
3459 }
3460 }))
3461 defer ts.Close()
3462
3463 operator := fmt.Sprintf(`
3464 operator: %s
3465 system_account: %s
3466 resolver: URL("%s%s")
3467 `, ojwt, spub, ts.URL, basePath)
3468
3469 tmpl := `
3470 listen: 127.0.0.1:-1
3471 server_name: %s
3472 cluster {
3473 port: -1
3474 name: "local"
3475 %s
3476 accounts: ["` + apub + `"%s]
3477 }
3478 ` + operator
3479
3480 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "A", _EMPTY_, _EMPTY_)))
3481 s1, o1 := RunServerWithConfig(conf1)
3482 defer s1.Shutdown()
3483
3484 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "B", fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port),
3485 _EMPTY_)))
3486 s2, _ := RunServerWithConfig(conf2)
3487 defer s2.Shutdown()
3488
3489 checkClusterFormed(t, s1, s2)
3490
3491 checkRoute := func(s *Server, acc string, perAccount bool) {
3492 t.Helper()
3493 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
3494 s.mu.RLock()
3495 _, ok := s.accRoutes[acc]
3496 s.mu.RUnlock()
3497 if perAccount && !ok {
3498 return fmt.Errorf("No dedicated route for account %q on server %q", acc, s)
3499 } else if !perAccount && ok {
3500 return fmt.Errorf("Dedicated route for account %q on server %q", acc, s)
3501 }
3502 return nil
3503 })
3504 }
3505 // Route for accounts "apub" and "spub" should be a dedicated route
3506 checkRoute(s1, apub, true)
3507 checkRoute(s2, apub, true)
3508 checkRoute(s1, spub, true)
3509 checkRoute(s2, spub, true)
3510 // Route for account "bpub" should not
3511 checkRoute(s1, bpub, false)
3512 checkRoute(s2, bpub, false)
3513
3514 checkComm := func(acc string, kp nkeys.KeyPair, subj string) {
3515 t.Helper()
3516 usr := createUserCreds(t, nil, kp)
3517 ncAs2 := natsConnect(t, s2.ClientURL(), usr)
3518 defer ncAs2.Close()
3519 sub := natsSubSync(t, ncAs2, subj)
3520 checkSubInterest(t, s1, acc, subj, time.Second)
3521
3522 ncAs1 := natsConnect(t, s1.ClientURL(), usr)
3523 defer ncAs1.Close()
3524 natsPub(t, ncAs1, subj, nil)
3525 natsNexMsg(t, sub, time.Second)
3526 }
3527 checkComm(apub, akp, "foo")
3528 checkComm(bpub, bkp, "bar")
3529
3530 // Add account "bpub" in accounts doing a configuration reload
3531 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", _EMPTY_, fmt.Sprintf(",\"%s\"", bpub)))
3532 // Already the route should be moved to a dedicated route, even
3533 // before doing the config reload on s2.
3534 checkRoute(s1, bpub, true)
3535 checkRoute(s2, bpub, true)
3536 // Account "apub" should still have its dedicated route
3537 checkRoute(s1, apub, true)
3538 checkRoute(s2, apub, true)
3539 // So the system account
3540 checkRoute(s1, spub, true)
3541 checkRoute(s2, spub, true)
3542 // Let's complete the config reload on srvb
3543 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port),
3544 fmt.Sprintf(",\"%s\"", bpub)))
3545 checkClusterFormed(t, s1, s2)
3546 // Check communication on account bpub again.
3547 checkComm(bpub, bkp, "baz")
3548
3549 // Now add with config reload an account that has not been used yet (cpub).
3550 // We will also remove account bpub from the account list.
3551 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", _EMPTY_, fmt.Sprintf(",\"%s\"", cpub)))
3552 // Again, check before reloading s2.
3553 checkRoute(s1, cpub, true)
3554 checkRoute(s2, cpub, true)
3555 // Now reload s2 and do other checks.
3556 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port),
3557 fmt.Sprintf(",\"%s\"", cpub)))
3558 checkClusterFormed(t, s1, s2)
3559 checkRoute(s1, bpub, false)
3560 checkRoute(s2, bpub, false)
3561 checkComm(cpub, ckp, "bat")
3562
3563 // Finally, let's try to add an account that the account server rejects.
3564 err := os.WriteFile(conf1, []byte(fmt.Sprintf(tmpl, "A", _EMPTY_, fmt.Sprintf(",\"%s\",\"%s\"", cpub, dpub))), 0666)
3565 require_NoError(t, err)
3566 if err := s1.Reload(); err == nil || !strings.Contains(err.Error(), dpub) {
3567 t.Fatalf("Expected error about not being able to lookup this account, got %q", err)
3568 }
3569 }
3570
3571 func TestRoutePoolAndPerAccountWithOlderServer(t *testing.T) {
3572 tmpl := `
3573 port: -1
3574 server_name: "%s"
3575 accounts {
3576 A { users: [{user: "A", password: "pwd"}] }
3577 B { users: [{user: "B", password: "pwd"}] }
3578 }
3579 cluster {
3580 port: -1
3581 name: "local"
3582 pool_size: 5
3583 accounts: ["A"]
3584 %s
3585 }
3586 `
3587 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "A", _EMPTY_)))
3588 s1, o1 := RunServerWithConfig(conf1)
3589 defer s1.Shutdown()
3590
3591 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "B",
3592 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
3593 s2, _ := RunServerWithConfig(conf2)
3594 defer s2.Shutdown()
3595
3596 // Have s3 explicitly disable pooling (to behave as an old server)
3597 conf3 := createConfFile(t, []byte(fmt.Sprintf(`
3598 port: -1
3599 server_name: "C"
3600 accounts {
3601 A { users: [{user: "A", password: "pwd"}] }
3602 B { users: [{user: "B", password: "pwd"}] }
3603 }
3604 cluster {
3605 port: -1
3606 name: "local"
3607 pool_size: -1
3608 routes: ["nats://127.0.0.1:%d"]
3609 }
3610 `, o1.Cluster.Port)))
3611 s3, _ := RunServerWithConfig(conf3)
3612 defer s3.Shutdown()
3613
3614 checkClusterFormed(t, s1, s2, s3)
3615
3616 check := func(acc, subj string, subSrv, pubSrv1, pubSrv2 *Server) {
3617 t.Helper()
3618
3619 ncSub := natsConnect(t, subSrv.ClientURL(), nats.UserInfo(acc, "pwd"))
3620 defer ncSub.Close()
3621 sub := natsSubSync(t, ncSub, subj)
3622
3623 checkSubInterest(t, pubSrv1, acc, subj, time.Second)
3624 checkSubInterest(t, pubSrv2, acc, subj, time.Second)
3625
3626 pub := func(s *Server) {
3627 t.Helper()
3628 nc := natsConnect(t, s.ClientURL(), nats.UserInfo(acc, "pwd"))
3629 defer nc.Close()
3630
3631 natsPub(t, nc, subj, []byte("hello"))
3632 natsNexMsg(t, sub, time.Second)
3633 }
3634 pub(pubSrv1)
3635 pub(pubSrv2)
3636 }
3637 check("A", "subj1", s1, s2, s3)
3638 check("A", "subj2", s2, s1, s3)
3639 check("A", "subj3", s3, s1, s2)
3640 check("B", "subj4", s1, s2, s3)
3641 check("B", "subj5", s2, s1, s3)
3642 check("B", "subj6", s3, s1, s2)
3643 }
3644
3645 type testDuplicateRouteLogger struct {
3646 DummyLogger
3647 ch chan struct{}
3648 count int
3649 }
3650
3651 func (l *testDuplicateRouteLogger) Noticef(format string, args ...any) {
3652 msg := fmt.Sprintf(format, args...)
3653 if !strings.Contains(msg, DuplicateRoute.String()) {
3654 return
3655 }
3656 select {
3657 case l.ch <- struct{}{}:
3658 default:
3659 }
3660 l.Mutex.Lock()
3661 l.count++
3662 l.Mutex.Unlock()
3663 }
3664
3665 // This test will make sure that a server with pooling does not
3666 // keep trying to connect to a non pooled (for instance old) server.
3667 // Will also make sure that if the old server is simply accepting
3668 // connections, and restarted, the server with pooling will connect.
3669 func TestRoutePoolWithOlderServerConnectAndReconnect(t *testing.T) {
3670 tmplA := `
3671 port: -1
3672 server_name: "A"
3673 cluster {
3674 port: -1
3675 name: "local"
3676 pool_size: 3
3677 %s
3678 }
3679 `
3680 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmplA, _EMPTY_)))
3681 s1, o1 := RunServerWithConfig(conf1)
3682 defer s1.Shutdown()
3683
3684 l := &testDuplicateRouteLogger{ch: make(chan struct{}, 50)}
3685 s1.SetLogger(l, false, false)
3686
3687 tmplB := `
3688 port: -1
3689 server_name: "B"
3690 cluster {
3691 port: %d
3692 name: "local"
3693 pool_size: -1
3694 %s
3695 }
3696 `
3697 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmplB, -1,
3698 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
3699 s2, o2 := RunServerWithConfig(conf2)
3700 defer s2.Shutdown()
3701
3702 checkClusterFormed(t, s1, s2)
3703
3704 // Now reload configuration of s1 to point to s2.
3705 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmplA, fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o2.Cluster.Port)))
3706 checkClusterFormed(t, s1, s2)
3707
3708 // We could get some, but it should settle.
3709 checkRepeatConnect := func() {
3710 t.Helper()
3711 tm := time.NewTimer(4 * routeConnectDelay)
3712 var last time.Time
3713 for done := false; !done; {
3714 select {
3715 case <-l.ch:
3716 last = time.Now()
3717 case <-tm.C:
3718 done = true
3719 }
3720 }
3721 if dur := time.Since(last); dur <= routeConnectDelay {
3722 t.Fatalf("Still attempted to connect %v ago", dur)
3723 }
3724 }
3725 checkRepeatConnect()
3726
3727 // Now shutdown s2 and restart it without active route to s1.
3728 // Check that cluster can still be formed: that is, s1 is
3729 // still trying to connect to s2.
3730 s2.Shutdown()
3731 // Wait for more than a regular reconnect delay attempt.
3732 // Note that in test it is set to 15ms.
3733 time.Sleep(50 * time.Millisecond)
3734 // Restart the server s2 with the same cluster port otherwise
3735 // s1 would not be able to reconnect.
3736 conf2 = createConfFile(t, []byte(fmt.Sprintf(tmplB, o2.Cluster.Port, _EMPTY_)))
3737 s2, _ = RunServerWithConfig(conf2)
3738 defer s2.Shutdown()
3739 // Make sure reconnect occurs
3740 checkClusterFormed(t, s1, s2)
3741 // And again, make sure there is no repeat-connect
3742 checkRepeatConnect()
3743 }
3744
3745 func TestRoutePoolBadAuthNoRunawayCreateRoute(t *testing.T) {
3746 conf1 := createConfFile(t, []byte(`
3747 server_name: "S1"
3748 listen: "127.0.0.1:-1"
3749 cluster {
3750 name: "local"
3751 listen: "127.0.0.1:-1"
3752 pool_size: 4
3753 authorization {
3754 user: "correct"
3755 password: "correct"
3756 timeout: 5
3757 }
3758 }
3759 `))
3760 s1, o1 := RunServerWithConfig(conf1)
3761 defer s1.Shutdown()
3762
3763 l := &captureErrorLogger{errCh: make(chan string, 100)}
3764 s1.SetLogger(l, false, false)
3765
3766 tmpl := `
3767 server_name: "S2"
3768 listen: "127.0.0.1:-1"
3769 cluster {
3770 name: "local"
3771 listen: "127.0.0.1:-1"
3772 pool_size: 5
3773 routes: ["nats://%[email protected]:%d"]
3774 }
3775 `
3776 conf2 := createConfFile(t, fmt.Appendf(nil, tmpl, "incorrect:incorrect", o1.Cluster.Port))
3777 s2, _ := RunServerWithConfig(conf2)
3778 defer s2.Shutdown()
3779
3780 deadline := time.Now().Add(2 * time.Second)
3781 var errors int
3782 for time.Now().Before(deadline) {
3783 select {
3784 case <-l.errCh:
3785 errors++
3786 default:
3787 }
3788 }
3789 // We should not get that many errors now. In the past, we would get more
3790 // than 200 for the 2 sec wait.
3791 if errors > 10 {
3792 t.Fatalf("Unexpected number of errors: %v", errors)
3793 }
3794
3795 // Reload with proper credentials.
3796 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "correct:correct", o1.Cluster.Port))
3797 // Ensure we can connect.
3798 checkClusterFormed(t, s1, s2)
3799 }
3800
3801 func TestRouteCompressionOptions(t *testing.T) {
3802 org := testDefaultClusterCompression
3803 testDefaultClusterCompression = _EMPTY_
3804 defer func() { testDefaultClusterCompression = org }()
3805
3806 tmpl := `
3807 port: -1
3808 cluster {
3809 port: -1
3810 compression: %s
3811 }
3812 `
3813 for _, test := range []struct {
3814 name string
3815 mode string
3816 rttVals []int
3817 expected string
3818 rtts []time.Duration
3819 }{
3820 {"boolean enabled", "true", nil, CompressionS2Fast, nil},
3821 {"string enabled", "enabled", nil, CompressionS2Fast, nil},
3822 {"string EnaBled", "EnaBled", nil, CompressionS2Fast, nil},
3823 {"string on", "on", nil, CompressionS2Fast, nil},
3824 {"string ON", "ON", nil, CompressionS2Fast, nil},
3825 {"string fast", "fast", nil, CompressionS2Fast, nil},
3826 {"string Fast", "Fast", nil, CompressionS2Fast, nil},
3827 {"string s2_fast", "s2_fast", nil, CompressionS2Fast, nil},
3828 {"string s2_Fast", "s2_Fast", nil, CompressionS2Fast, nil},
3829 {"boolean disabled", "false", nil, CompressionOff, nil},
3830 {"string disabled", "disabled", nil, CompressionOff, nil},
3831 {"string DisableD", "DisableD", nil, CompressionOff, nil},
3832 {"string off", "off", nil, CompressionOff, nil},
3833 {"string OFF", "OFF", nil, CompressionOff, nil},
3834 {"better", "better", nil, CompressionS2Better, nil},
3835 {"Better", "Better", nil, CompressionS2Better, nil},
3836 {"s2_better", "s2_better", nil, CompressionS2Better, nil},
3837 {"S2_BETTER", "S2_BETTER", nil, CompressionS2Better, nil},
3838 {"best", "best", nil, CompressionS2Best, nil},
3839 {"BEST", "BEST", nil, CompressionS2Best, nil},
3840 {"s2_best", "s2_best", nil, CompressionS2Best, nil},
3841 {"S2_BEST", "S2_BEST", nil, CompressionS2Best, nil},
3842 {"auto no rtts", "auto", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
3843 {"s2_auto no rtts", "s2_auto", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
3844 {"auto", "{mode: auto, rtt_thresholds: [%s]}", []int{1}, CompressionS2Auto, []time.Duration{time.Millisecond}},
3845 {"Auto", "{Mode: Auto, thresholds: [%s]}", []int{1, 2}, CompressionS2Auto, []time.Duration{time.Millisecond, 2 * time.Millisecond}},
3846 {"s2_auto", "{mode: s2_auto, thresholds: [%s]}", []int{1, 2, 3}, CompressionS2Auto, []time.Duration{time.Millisecond, 2 * time.Millisecond, 3 * time.Millisecond}},
3847 {"s2_AUTO", "{mode: s2_AUTO, thresholds: [%s]}", []int{1, 2, 3, 4}, CompressionS2Auto, []time.Duration{time.Millisecond, 2 * time.Millisecond, 3 * time.Millisecond, 4 * time.Millisecond}},
3848 {"s2_auto:-10,5,10", "{mode: s2_auto, thresholds: [%s]}", []int{-10, 5, 10}, CompressionS2Auto, []time.Duration{0, 5 * time.Millisecond, 10 * time.Millisecond}},
3849 {"s2_auto:5,10,15", "{mode: s2_auto, thresholds: [%s]}", []int{5, 10, 15}, CompressionS2Auto, []time.Duration{5 * time.Millisecond, 10 * time.Millisecond, 15 * time.Millisecond}},
3850 {"s2_auto:0,5,10", "{mode: s2_auto, thresholds: [%s]}", []int{0, 5, 10}, CompressionS2Auto, []time.Duration{0, 5 * time.Millisecond, 10 * time.Millisecond}},
3851 {"s2_auto:5,10,0,20", "{mode: s2_auto, thresholds: [%s]}", []int{5, 10, 0, 20}, CompressionS2Auto, []time.Duration{5 * time.Millisecond, 10 * time.Millisecond, 0, 20 * time.Millisecond}},
3852 {"s2_auto:0,10,0,20", "{mode: s2_auto, thresholds: [%s]}", []int{0, 10, 0, 20}, CompressionS2Auto, []time.Duration{0, 10 * time.Millisecond, 0, 20 * time.Millisecond}},
3853 {"s2_auto:0,0,0,20", "{mode: s2_auto, thresholds: [%s]}", []int{0, 0, 0, 20}, CompressionS2Auto, []time.Duration{0, 0, 0, 20 * time.Millisecond}},
3854 {"s2_auto:0,10,0,0", "{mode: s2_auto, rtt_thresholds: [%s]}", []int{0, 10, 0, 0}, CompressionS2Auto, []time.Duration{0, 10 * time.Millisecond}},
3855 } {
3856 t.Run(test.name, func(t *testing.T) {
3857 var val string
3858 if len(test.rttVals) > 0 {
3859 var rtts string
3860 for i, v := range test.rttVals {
3861 if i > 0 {
3862 rtts += ", "
3863 }
3864 rtts += fmt.Sprintf("%dms", v)
3865 }
3866 val = fmt.Sprintf(test.mode, rtts)
3867 } else {
3868 val = test.mode
3869 }
3870 conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, val)))
3871 s, o := RunServerWithConfig(conf)
3872 defer s.Shutdown()
3873
3874 if cm := o.Cluster.Compression.Mode; cm != test.expected {
3875 t.Fatalf("Expected compression value to be %q, got %q", test.expected, cm)
3876 }
3877 if !reflect.DeepEqual(test.rtts, o.Cluster.Compression.RTTThresholds) {
3878 t.Fatalf("Expected RTT tresholds to be %+v, got %+v", test.rtts, o.Cluster.Compression.RTTThresholds)
3879 }
3880 s.Shutdown()
3881
3882 o.Cluster.Port = -1
3883 o.Cluster.Compression.Mode = test.mode
3884 if len(test.rttVals) > 0 {
3885 o.Cluster.Compression.Mode = CompressionS2Auto
3886 o.Cluster.Compression.RTTThresholds = o.Cluster.Compression.RTTThresholds[:0]
3887 for _, v := range test.rttVals {
3888 o.Cluster.Compression.RTTThresholds = append(o.Cluster.Compression.RTTThresholds, time.Duration(v)*time.Millisecond)
3889 }
3890 }
3891 s = RunServer(o)
3892 defer s.Shutdown()
3893 if cm := o.Cluster.Compression.Mode; cm != test.expected {
3894 t.Fatalf("Expected compression value to be %q, got %q", test.expected, cm)
3895 }
3896 if !reflect.DeepEqual(test.rtts, o.Cluster.Compression.RTTThresholds) {
3897 t.Fatalf("Expected RTT tresholds to be %+v, got %+v", test.rtts, o.Cluster.Compression.RTTThresholds)
3898 }
3899 })
3900 }
3901 // Test that with no compression specified, we default to "accept"
3902 conf := createConfFile(t, []byte(`
3903 port: -1
3904 cluster {
3905 port: -1
3906 }
3907 `))
3908 s, o := RunServerWithConfig(conf)
3909 defer s.Shutdown()
3910 if cm := o.Cluster.Compression.Mode; cm != CompressionAccept {
3911 t.Fatalf("Expected compression value to be %q, got %q", CompressionAccept, cm)
3912 }
3913 for _, test := range []struct {
3914 name string
3915 mode string
3916 rtts []time.Duration
3917 err string
3918 }{
3919 {"unsupported mode", "gzip", nil, "unsupported"},
3920 {"not ascending order", "s2_auto", []time.Duration{
3921 5 * time.Millisecond,
3922 10 * time.Millisecond,
3923 2 * time.Millisecond,
3924 }, "ascending"},
3925 {"too many thresholds", "s2_auto", []time.Duration{
3926 5 * time.Millisecond,
3927 10 * time.Millisecond,
3928 20 * time.Millisecond,
3929 40 * time.Millisecond,
3930 60 * time.Millisecond,
3931 }, "more than 4"},
3932 {"all 0", "s2_auto", []time.Duration{0, 0, 0, 0}, "at least one"},
3933 {"single 0", "s2_auto", []time.Duration{0}, "at least one"},
3934 } {
3935 t.Run(test.name, func(t *testing.T) {
3936 o := DefaultOptions()
3937 o.Cluster.Port = -1
3938 o.Cluster.Compression = CompressionOpts{test.mode, test.rtts}
3939 if _, err := NewServer(o); err == nil || !strings.Contains(err.Error(), test.err) {
3940 t.Fatalf("Unexpected error: %v", err)
3941 }
3942 })
3943 }
3944 }
3945
3946 func TestS2WriterOptionsForFastCompression(t *testing.T) {
3947 opts := s2WriterOptions(CompressionS2Fast)
3948 if len(opts) == 0 {
3949 t.Fatal("Expected non-empty writer options for fast compression mode")
3950 }
3951 }
3952
3953 type testConnSentBytes struct {
3954 net.Conn
3955 sync.RWMutex
3956 sent int
3957 }
3958
3959 func (c *testConnSentBytes) Write(p []byte) (int, error) {
3960 n, err := c.Conn.Write(p)
3961 c.Lock()
3962 c.sent += n
3963 c.Unlock()
3964 return n, err
3965 }
3966
3967 func TestRouteCompression(t *testing.T) {
3968 tmpl := `
3969 port: -1
3970 server_name: "%s"
3971 accounts {
3972 A { users: [{user: "a", pass: "pwd"}] }
3973 }
3974 cluster {
3975 name: "local"
3976 port: -1
3977 compression: true
3978 pool_size: %d
3979 %s
3980 %s
3981 }
3982 `
3983 for _, test := range []struct {
3984 name string
3985 poolSize int
3986 accounts string
3987 }{
3988 {"no pooling", -1, _EMPTY_},
3989 {"pooling", 3, _EMPTY_},
3990 {"per account", 1, "accounts: [\"A\"]"},
3991 } {
3992 t.Run(test.name, func(t *testing.T) {
3993 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "S1", test.poolSize, test.accounts, _EMPTY_)))
3994 s1, o1 := RunServerWithConfig(conf1)
3995 defer s1.Shutdown()
3996
3997 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "S2", test.poolSize, test.accounts,
3998 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
3999 s2, _ := RunServerWithConfig(conf2)
4000 defer s2.Shutdown()
4001
4002 checkClusterFormed(t, s1, s2)
4003
4004 s1.mu.RLock()
4005 s1.forEachRoute(func(r *client) {
4006 r.mu.Lock()
4007 r.nc = &testConnSentBytes{Conn: r.nc}
4008 r.mu.Unlock()
4009 })
4010 s1.mu.RUnlock()
4011
4012 nc2 := natsConnect(t, s2.ClientURL(), nats.UserInfo("a", "pwd"))
4013 defer nc2.Close()
4014 sub := natsSubSync(t, nc2, "foo")
4015 natsFlush(t, nc2)
4016 checkSubInterest(t, s1, "A", "foo", time.Second)
4017
4018 nc1 := natsConnect(t, s1.ClientURL(), nats.UserInfo("a", "pwd"))
4019 defer nc1.Close()
4020
4021 var payloads [][]byte
4022 count := 26
4023 for i := 0; i < count; i++ {
4024 n := rand.Intn(2048) + 1
4025 p := make([]byte, n)
4026 for j := 0; j < n; j++ {
4027 p[j] = byte(i) + 'A'
4028 }
4029 payloads = append(payloads, p)
4030 natsPub(t, nc1, "foo", p)
4031 }
4032
4033 totalPayloadSize := 0
4034 for i := 0; i < count; i++ {
4035 m := natsNexMsg(t, sub, time.Second)
4036 if !bytes.Equal(m.Data, payloads[i]) {
4037 t.Fatalf("Expected payload %q - got %q", payloads[i], m.Data)
4038 }
4039 totalPayloadSize += len(m.Data)
4040 }
4041
4042 // Also check that the route stats shows that compression likely occurred
4043 var out int
4044 s1.mu.RLock()
4045 if len(test.accounts) > 0 {
4046 rems := s1.accRoutes["A"]
4047 if rems == nil {
4048 t.Fatal("Did not find route for account")
4049 }
4050 for _, r := range rems {
4051 r.mu.Lock()
4052 if r.nc != nil {
4053 nc := r.nc.(*testConnSentBytes)
4054 nc.RLock()
4055 out = nc.sent
4056 nc.RUnlock()
4057 }
4058 r.mu.Unlock()
4059 break
4060 }
4061 } else {
4062 ai, _ := s1.accounts.Load("A")
4063 acc := ai.(*Account)
4064 acc.mu.RLock()
4065 pi := acc.routePoolIdx
4066 acc.mu.RUnlock()
4067 s1.forEachRouteIdx(pi, func(r *client) bool {
4068 r.mu.Lock()
4069 if r.nc != nil {
4070 nc := r.nc.(*testConnSentBytes)
4071 nc.RLock()
4072 out = nc.sent
4073 nc.RUnlock()
4074 }
4075 r.mu.Unlock()
4076 return false
4077 })
4078 }
4079 s1.mu.RUnlock()
4080 // Should at least be smaller than totalPayloadSize, use 20%.
4081 limit := totalPayloadSize * 80 / 100
4082 if int(out) > limit {
4083 t.Fatalf("Expected s1's outBytes to be less than %v, got %v", limit, out)
4084 }
4085 })
4086 }
4087 }
4088
4089 func TestRouteCompressionMatrixModes(t *testing.T) {
4090 tmpl := `
4091 port: -1
4092 server_name: "%s"
4093 cluster {
4094 name: "local"
4095 port: -1
4096 compression: %s
4097 pool_size: -1
4098 %s
4099 }
4100 `
4101 for _, test := range []struct {
4102 name string
4103 s1 string
4104 s2 string
4105 s1Expected string
4106 s2Expected string
4107 }{
4108 {"off off", "off", "off", CompressionOff, CompressionOff},
4109 {"off accept", "off", "accept", CompressionOff, CompressionOff},
4110 {"off on", "off", "on", CompressionOff, CompressionOff},
4111 {"off better", "off", "better", CompressionOff, CompressionOff},
4112 {"off best", "off", "best", CompressionOff, CompressionOff},
4113
4114 {"accept off", "accept", "off", CompressionOff, CompressionOff},
4115 {"accept accept", "accept", "accept", CompressionOff, CompressionOff},
4116 {"accept on", "accept", "on", CompressionS2Fast, CompressionS2Fast},
4117 {"accept better", "accept", "better", CompressionS2Better, CompressionS2Better},
4118 {"accept best", "accept", "best", CompressionS2Best, CompressionS2Best},
4119
4120 {"on off", "on", "off", CompressionOff, CompressionOff},
4121 {"on accept", "on", "accept", CompressionS2Fast, CompressionS2Fast},
4122 {"on on", "on", "on", CompressionS2Fast, CompressionS2Fast},
4123 {"on better", "on", "better", CompressionS2Fast, CompressionS2Better},
4124 {"on best", "on", "best", CompressionS2Fast, CompressionS2Best},
4125
4126 {"better off", "better", "off", CompressionOff, CompressionOff},
4127 {"better accept", "better", "accept", CompressionS2Better, CompressionS2Better},
4128 {"better on", "better", "on", CompressionS2Better, CompressionS2Fast},
4129 {"better better", "better", "better", CompressionS2Better, CompressionS2Better},
4130 {"better best", "better", "best", CompressionS2Better, CompressionS2Best},
4131
4132 {"best off", "best", "off", CompressionOff, CompressionOff},
4133 {"best accept", "best", "accept", CompressionS2Best, CompressionS2Best},
4134 {"best on", "best", "on", CompressionS2Best, CompressionS2Fast},
4135 {"best better", "best", "better", CompressionS2Best, CompressionS2Better},
4136 {"best best", "best", "best", CompressionS2Best, CompressionS2Best},
4137 } {
4138 t.Run(test.name, func(t *testing.T) {
4139 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "A", test.s1, _EMPTY_)))
4140 s1, o1 := RunServerWithConfig(conf1)
4141 defer s1.Shutdown()
4142
4143 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "B", test.s2, fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
4144 s2, _ := RunServerWithConfig(conf2)
4145 defer s2.Shutdown()
4146
4147 checkClusterFormed(t, s1, s2)
4148
4149 nc1 := natsConnect(t, s1.ClientURL())
4150 defer nc1.Close()
4151
4152 nc2 := natsConnect(t, s2.ClientURL())
4153 defer nc2.Close()
4154
4155 payload := make([]byte, 128)
4156 check := func(ncp, ncs *nats.Conn, subj string, s *Server) {
4157 t.Helper()
4158 sub := natsSubSync(t, ncs, subj)
4159 checkSubInterest(t, s, globalAccountName, subj, time.Second)
4160 natsPub(t, ncp, subj, payload)
4161 natsNexMsg(t, sub, time.Second)
4162
4163 for _, srv := range []*Server{s1, s2} {
4164 rz, err := srv.Routez(nil)
4165 require_NoError(t, err)
4166 var expected string
4167 if srv == s1 {
4168 expected = test.s1Expected
4169 } else {
4170 expected = test.s2Expected
4171 }
4172 if cm := rz.Routes[0].Compression; cm != expected {
4173 t.Fatalf("Server %s - expected compression %q, got %q", srv, expected, cm)
4174 }
4175 }
4176 }
4177 check(nc1, nc2, "foo", s1)
4178 check(nc2, nc1, "bar", s2)
4179 })
4180 }
4181 }
4182
4183 func TestRouteCompressionWithOlderServer(t *testing.T) {
4184 tmpl := `
4185 port: -1
4186 server_name: "%s"
4187 cluster {
4188 port: -1
4189 name: "local"
4190 %s
4191 %s
4192 }
4193 `
4194 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "A", _EMPTY_, "compression: \"on\"")))
4195 s1, o1 := RunServerWithConfig(conf1)
4196 defer s1.Shutdown()
4197
4198 routes := fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port)
4199 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "B", routes, "compression: \"not supported\"")))
4200 s2, _ := RunServerWithConfig(conf2)
4201 defer s2.Shutdown()
4202
4203 checkClusterFormed(t, s1, s2)
4204
4205 // Make sure that s1 route's compression is "off"
4206 s1.mu.RLock()
4207 s1.forEachRoute(func(r *client) {
4208 r.mu.Lock()
4209 cm := r.route.compression
4210 r.mu.Unlock()
4211 if cm != CompressionNotSupported {
4212 s1.mu.RUnlock()
4213 t.Fatalf("Compression should be %q, got %q", CompressionNotSupported, cm)
4214 }
4215 })
4216 s1.mu.RUnlock()
4217 }
4218
4219 func TestRouteCompressionImplicitRoute(t *testing.T) {
4220 tmpl := `
4221 port: -1
4222 server_name: "%s"
4223 cluster {
4224 port: -1
4225 name: "local"
4226 %s
4227 %s
4228 }
4229 `
4230 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "A", _EMPTY_, _EMPTY_)))
4231 s1, o1 := RunServerWithConfig(conf1)
4232 defer s1.Shutdown()
4233
4234 routes := fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port)
4235 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "B", routes, "compression: \"fast\"")))
4236 s2, _ := RunServerWithConfig(conf2)
4237 defer s2.Shutdown()
4238
4239 conf3 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "C", routes, "compression: \"best\"")))
4240 s3, _ := RunServerWithConfig(conf3)
4241 defer s3.Shutdown()
4242
4243 checkClusterFormed(t, s1, s2, s3)
4244
4245 checkComp := func(s *Server, remoteID, expected string) {
4246 t.Helper()
4247 s.mu.RLock()
4248 defer s.mu.RUnlock()
4249 var err error
4250 s.forEachRoute(func(r *client) {
4251 if err != nil {
4252 return
4253 }
4254 var cm string
4255 ok := true
4256 r.mu.Lock()
4257 if r.route.remoteID == remoteID {
4258 cm = r.route.compression
4259 ok = cm == expected
4260 }
4261 r.mu.Unlock()
4262 if !ok {
4263 err = fmt.Errorf("Server %q - expected route to %q to use compression %q, got %q",
4264 s, remoteID, expected, cm)
4265 }
4266 })
4267 }
4268 checkComp(s1, s2.ID(), CompressionS2Fast)
4269 checkComp(s1, s3.ID(), CompressionS2Best)
4270 checkComp(s2, s1.ID(), CompressionS2Fast)
4271 checkComp(s2, s3.ID(), CompressionS2Best)
4272 checkComp(s3, s1.ID(), CompressionS2Best)
4273 checkComp(s3, s2.ID(), CompressionS2Best)
4274 }
4275
4276 func TestRouteCompressionAuto(t *testing.T) {
4277 tmpl := `
4278 port: -1
4279 server_name: "%s"
4280 ping_interval: "%s"
4281 cluster {
4282 port: -1
4283 name: "local"
4284 compression: %s
4285 %s
4286 }
4287 `
4288 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "A", "10s", "s2_fast", _EMPTY_)))
4289 s1, o1 := RunServerWithConfig(conf1)
4290 defer s1.Shutdown()
4291
4292 // Start with 0ms RTT
4293 np := createNetProxy(0, 1024*1024*1024, 1024*1024*1024, fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port), true)
4294 routes := fmt.Sprintf("routes: [\"%s\"]", np.routeURL())
4295
4296 rtts := "{mode: s2_auto, rtt_thresholds: [100ms, 200ms, 300ms]}"
4297 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "B", "500ms", rtts, routes)))
4298 s2, _ := RunServerWithConfig(conf2)
4299 defer s2.Shutdown()
4300 defer np.stop()
4301
4302 checkClusterFormed(t, s1, s2)
4303
4304 checkComp := func(expected string) {
4305 t.Helper()
4306 checkFor(t, 4*time.Second, 50*time.Millisecond, func() error {
4307 s2.mu.RLock()
4308 defer s2.mu.RUnlock()
4309 if n := s2.numRoutes(); n != 4 {
4310 return fmt.Errorf("Cluster not formed properly, got %v routes", n)
4311 }
4312 var err error
4313 s2.forEachRoute(func(r *client) {
4314 if err != nil {
4315 return
4316 }
4317 r.mu.Lock()
4318 cm := r.route.compression
4319 r.mu.Unlock()
4320 if cm != expected {
4321 err = fmt.Errorf("Route %v compression mode expected to be %q, got %q", r, expected, cm)
4322 }
4323 })
4324 return err
4325 })
4326 }
4327 checkComp(CompressionS2Uncompressed)
4328
4329 // Change the proxy RTT and we should get compression "fast"
4330 np.updateRTT(150 * time.Millisecond)
4331 checkComp(CompressionS2Fast)
4332
4333 // Now 250ms, and get "better"
4334 np.updateRTT(250 * time.Millisecond)
4335 checkComp(CompressionS2Better)
4336
4337 // Above 350 and we should get "best"
4338 np.updateRTT(350 * time.Millisecond)
4339 checkComp(CompressionS2Best)
4340
4341 // Down to 1ms and again should get "uncompressed"
4342 np.updateRTT(1 * time.Millisecond)
4343 checkComp(CompressionS2Uncompressed)
4344
4345 // Do a config reload with disabling uncompressed
4346 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", "500ms", "{mode: s2_auto, rtt_thresholds: [0ms, 100ms, 0ms, 300ms]}", routes))
4347 // Change the RTT back down to 1ms, but we should not go uncompressed,
4348 // we should have "fast" compression.
4349 np.updateRTT(1 * time.Millisecond)
4350 checkComp(CompressionS2Fast)
4351 // Now bump to 150ms and we should be using "best", not the "better" mode
4352 np.updateRTT(150 * time.Millisecond)
4353 checkComp(CompressionS2Best)
4354 // Try 400ms and we should still be using "best"
4355 np.updateRTT(400 * time.Millisecond)
4356 checkComp(CompressionS2Best)
4357
4358 // Try other variations
4359 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", "500ms", "{mode: s2_auto, rtt_thresholds: [50ms, 150ms, 0ms, 0ms]}", routes))
4360 np.updateRTT(0 * time.Millisecond)
4361 checkComp(CompressionS2Uncompressed)
4362 np.updateRTT(100 * time.Millisecond)
4363 checkComp(CompressionS2Fast)
4364 // Since we expect the same compression level, just wait before doing
4365 // the update and the next check.
4366 time.Sleep(100 * time.Millisecond)
4367 np.updateRTT(250 * time.Millisecond)
4368 checkComp(CompressionS2Fast)
4369
4370 // Now disable compression on s1
4371 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", "10s", "off", _EMPTY_))
4372 // Wait a bit to make sure we don't check for cluster too soon since
4373 // we expect a disconnect.
4374 time.Sleep(100 * time.Millisecond)
4375 checkClusterFormed(t, s1, s2)
4376 // Now change the RTT values in the proxy.
4377 np.updateRTT(0 * time.Millisecond)
4378 // Now check that s2 also shows as "off". Wait for some ping intervals.
4379 time.Sleep(200 * time.Millisecond)
4380 checkComp(CompressionOff)
4381 }
4382
4383 func TestRoutePings(t *testing.T) {
4384 routeMaxPingInterval = 50 * time.Millisecond
4385 defer func() { routeMaxPingInterval = defaultRouteMaxPingInterval }()
4386
4387 o1 := DefaultOptions()
4388 s1 := RunServer(o1)
4389 defer s1.Shutdown()
4390
4391 o2 := DefaultOptions()
4392 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
4393 s2 := RunServer(o2)
4394 defer s2.Shutdown()
4395
4396 checkClusterFormed(t, s1, s2)
4397
4398 ch := make(chan struct{}, 1)
4399 s1.mu.RLock()
4400 s1.forEachRemote(func(r *client) {
4401 r.mu.Lock()
4402 r.nc = &capturePingConn{r.nc, ch}
4403 r.mu.Unlock()
4404 })
4405 s1.mu.RUnlock()
4406
4407 for i := 0; i < 5; i++ {
4408 select {
4409 case <-ch:
4410 case <-time.After(250 * time.Millisecond):
4411 t.Fatalf("Did not send PING")
4412 }
4413 }
4414 }
4415
4416 func TestRouteCustomPing(t *testing.T) {
4417 pingInterval := 50 * time.Millisecond
4418 o1 := DefaultOptions()
4419 o1.Cluster.PingInterval = pingInterval
4420 o1.Cluster.MaxPingsOut = 2
4421 s1 := RunServer(o1)
4422 defer s1.Shutdown()
4423
4424 o2 := DefaultOptions()
4425 o2.Cluster.PingInterval = pingInterval
4426 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
4427 s2 := RunServer(o2)
4428 defer s2.Shutdown()
4429
4430 checkClusterFormed(t, s1, s2)
4431
4432 ch := make(chan struct{}, 1)
4433 s1.mu.RLock()
4434 s1.forEachRemote(func(r *client) {
4435 r.mu.Lock()
4436 r.nc = &capturePingConn{r.nc, ch}
4437 r.mu.Unlock()
4438 })
4439 s1.mu.RUnlock()
4440
4441 for i := 0; i < 5; i++ {
4442 select {
4443 case <-ch:
4444 case <-time.After(250 * time.Millisecond):
4445 t.Fatalf("Did not send PING")
4446 }
4447 }
4448 }
4449
4450 func TestRouteCompressionStaleConnectionUsesClusterPingMax(t *testing.T) {
4451 mockListener, err := net.Listen("tcp", "127.0.0.1:0")
4452 require_NoError(t, err)
4453 defer mockListener.Close()
4454 mockPort := mockListener.Addr().(*net.TCPAddr).Port
4455
4456 // The mock peer never sends INFO, so the soliciting route never completes
4457 // compression negotiation. The connection can only be closed by the stale
4458 // watch installed in createRoute.
4459 connCh := make(chan net.Conn, 1)
4460 go func() {
4461 conn, err := mockListener.Accept()
4462 if err != nil {
4463 return
4464 }
4465 connCh <- conn
4466 }()
4467
4468 // Cluster.MaxPingsOut and MaxPingsOut differ so the stale timer's deadline
4469 // distinguishes which is used: 50ms*2 = 100ms vs 50ms*101 ≈ 5s.
4470 o := DefaultOptions()
4471 o.Cluster.Compression.Mode = CompressionS2Fast
4472 o.Cluster.PingInterval = 50 * time.Millisecond
4473 o.Cluster.MaxPingsOut = 1
4474 o.MaxPingsOut = 100
4475 o.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", mockPort))
4476 s := RunServer(o)
4477 defer s.Shutdown()
4478
4479 var conn net.Conn
4480 select {
4481 case conn = <-connCh:
4482 case <-time.After(2 * time.Second):
4483 t.Fatalf("Mock listener did not accept route connection")
4484 }
4485 defer conn.Close()
4486
4487 require_NoError(t, conn.SetReadDeadline(time.Now().Add(1500*time.Millisecond)))
4488 buf := make([]byte, 256)
4489 start := time.Now()
4490 for {
4491 if _, err = conn.Read(buf); err != nil {
4492 break
4493 }
4494 }
4495 if elapsed := time.Since(start); elapsed > time.Second {
4496 t.Fatalf("Stale-connection timer used wrong ping_max: closed after %v, expected <1s (Cluster.MaxPingsOut=1)", elapsed)
4497 }
4498 }
4499
4500 func TestRouteNoLeakOnSlowConsumer(t *testing.T) {
4501 o1 := DefaultOptions()
4502 o1.Cluster.PoolSize = -1
4503 s1 := RunServer(o1)
4504 defer s1.Shutdown()
4505
4506 o2 := DefaultOptions()
4507 o2.Cluster.PoolSize = -1
4508 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
4509 s2 := RunServer(o2)
4510 defer s2.Shutdown()
4511
4512 checkClusterFormed(t, s1, s2)
4513
4514 // For any route connections on the first server, drop the write
4515 // deadline down and then get the client to try sending something.
4516 // This should result in an effectively immediate write timeout,
4517 // which will surface as a slow consumer.
4518 s1.mu.Lock()
4519 for _, cl := range s1.routes {
4520 for _, c := range cl {
4521 c.mu.Lock()
4522 c.out.wdl = time.Nanosecond
4523 c.mu.Unlock()
4524 c.sendRTTPing()
4525 }
4526 }
4527 s1.mu.Unlock()
4528
4529 // By now the routes should have gone down, so check that there
4530 // aren't any routes listed still.
4531 checkFor(t, time.Millisecond*500, time.Millisecond*25, func() error {
4532 if nc := s1.NumRoutes(); nc != 0 {
4533 return fmt.Errorf("Server 1 should have no route connections, got %v", nc)
4534 }
4535 if nc := s2.NumRoutes(); nc != 0 {
4536 return fmt.Errorf("Server 2 should have no route connections, got %v", nc)
4537 }
4538 return nil
4539 })
4540 var got, expected int64
4541 got = s1.NumSlowConsumers()
4542 expected = 1
4543 if got != expected {
4544 t.Errorf("got: %d, expected: %d", got, expected)
4545 }
4546 got = int64(s1.NumSlowConsumersRoutes())
4547 if got != expected {
4548 t.Errorf("got: %d, expected: %d", got, expected)
4549 }
4550 got = int64(s1.NumSlowConsumersClients())
4551 expected = 0
4552 if got != expected {
4553 t.Errorf("got: %d, expected: %d", got, expected)
4554 }
4555 varz, err := s1.Varz(nil)
4556 if err != nil {
4557 t.Fatal(err)
4558 }
4559 if varz.SlowConsumersStats.Clients != 0 {
4560 t.Error("Expected no slow consumer clients")
4561 }
4562 if varz.SlowConsumersStats.Routes != 1 {
4563 t.Error("Expected a slow consumer route")
4564 }
4565 }
4566
4567 func TestRouteNoAppSubLeakOnSlowConsumer(t *testing.T) {
4568 o1 := DefaultOptions()
4569 o1.MaxPending = 1024
4570 o1.MaxPayload = int32(o1.MaxPending)
4571 s1 := RunServer(o1)
4572 defer s1.Shutdown()
4573
4574 o2 := DefaultOptions()
4575 o2.MaxPending = 1024
4576 o2.MaxPayload = int32(o2.MaxPending)
4577 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
4578 s2 := RunServer(o2)
4579 defer s2.Shutdown()
4580
4581 checkClusterFormed(t, s1, s2)
4582
4583 checkSub := func(expected bool) {
4584 t.Helper()
4585 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
4586 subsz, err := s1.Subsz(&SubszOptions{Subscriptions: true, Account: globalAccountName})
4587 require_NoError(t, err)
4588 for _, sub := range subsz.Subs {
4589 if sub.Subject == "foo" {
4590 if expected {
4591 return nil
4592 }
4593 return fmt.Errorf("Subscription should not have been found: %+v", sub)
4594 }
4595 }
4596 if expected {
4597 return fmt.Errorf("Subscription on `foo` not found")
4598 }
4599 return nil
4600 })
4601 }
4602
4603 checkRoutedSub := func(expected bool) {
4604 t.Helper()
4605 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
4606 routez, err := s2.Routez(&RoutezOptions{Subscriptions: true})
4607 require_NoError(t, err)
4608 for _, route := range routez.Routes {
4609 if route.Account != _EMPTY_ {
4610 continue
4611 }
4612 if len(route.Subs) == 1 && route.Subs[0] == "foo" {
4613 if expected {
4614 return nil
4615 }
4616 return fmt.Errorf("Subscription should not have been found: %+v", route.Subs)
4617 }
4618 }
4619 if expected {
4620 return fmt.Errorf("Did not find `foo` subscription")
4621 }
4622 return nil
4623 })
4624 }
4625
4626 checkClosed := func(cid uint64) {
4627 t.Helper()
4628 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
4629 connz, err := s1.Connz(&ConnzOptions{State: ConnClosed, CID: cid, Subscriptions: true})
4630 if err != nil {
4631 return err
4632 }
4633 require_Len(t, len(connz.Conns), 1)
4634 conn := connz.Conns[0]
4635 require_Equal(t, conn.Reason, SlowConsumerPendingBytes.String())
4636 subs := conn.Subs
4637 require_Len(t, len(subs), 1)
4638 require_Equal[string](t, subs[0], "foo")
4639 return nil
4640 })
4641 }
4642
4643 for i := 0; i < 5; i++ {
4644 nc := natsConnect(t, s1.ClientURL())
4645 defer nc.Close()
4646
4647 natsSubSync(t, nc, "foo")
4648 natsFlush(t, nc)
4649
4650 checkSub(true)
4651 checkRoutedSub(true)
4652
4653 cid, err := nc.GetClientID()
4654 require_NoError(t, err)
4655 c := s1.getClient(cid)
4656 payload := make([]byte, 2048)
4657 c.mu.Lock()
4658 c.queueOutbound([]byte(fmt.Sprintf("MSG foo 1 2048\r\n%s\r\n", payload)))
4659 closed := c.isClosed()
4660 c.mu.Unlock()
4661
4662 require_True(t, closed)
4663 checkSub(false)
4664 checkRoutedSub(false)
4665 checkClosed(cid)
4666
4667 nc.Close()
4668 }
4669 }
4670
4671 func TestRouteSlowConsumerRecover(t *testing.T) {
4672 o1 := DefaultOptions()
4673 o1.Cluster.PoolSize = -1
4674 s1 := RunServer(o1)
4675 defer s1.Shutdown()
4676
4677 rtt := 1500 * time.Nanosecond
4678 upRate := 1024 * 1024
4679 downRate := 128 * 1024
4680 np := createNetProxy(rtt, upRate, downRate, fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port), true)
4681 defer np.stop()
4682
4683 o2 := DefaultOptions()
4684 o2.Cluster.PoolSize = -1
4685 o2.Routes = RoutesFromStr(np.routeURL())
4686 s2 := RunServer(o2)
4687 defer s2.Shutdown()
4688
4689 checkClusterFormed(t, s1, s2)
4690
4691 changeWriteDeadline := func(s *Server, duration time.Duration) {
4692 s.mu.Lock()
4693 for _, cl := range s.routes {
4694 for _, c := range cl {
4695 c.mu.Lock()
4696 c.out.wdl = duration
4697 c.mu.Unlock()
4698 }
4699 }
4700 s.mu.Unlock()
4701 }
4702 hasSlowConsumerRoutes := func(s *Server) bool {
4703 var sc bool
4704 s.mu.Lock()
4705 Loop:
4706 for _, cl := range s.routes {
4707 for _, c := range cl {
4708 c.mu.Lock()
4709 sc = c.flags.isSet(isSlowConsumer)
4710 c.mu.Unlock()
4711 if sc {
4712 break Loop
4713 }
4714 }
4715 }
4716 s.mu.Unlock()
4717 return sc
4718 }
4719
4720 // Start with a shorter write deadline to cause errors
4721 // then bump it again later to let it recover.
4722 changeWriteDeadline(s1, 1*time.Second)
4723
4724 ncA, err := nats.Connect(s1.Addr().String())
4725 require_NoError(t, err)
4726 defer ncA.Close()
4727
4728 ncB, err := nats.Connect(s2.Addr().String())
4729 require_NoError(t, err)
4730 defer ncB.Close()
4731
4732 var wg sync.WaitGroup
4733 ncB.Subscribe("test", func(*nats.Msg) {
4734 ncB.Close()
4735 })
4736 ncB.Flush()
4737
4738 ctx, cancel := context.WithTimeout(context.Background(), 800*time.Millisecond)
4739 defer cancel()
4740
4741 go func() {
4742 var total int
4743 payload := bytes.Repeat([]byte("A"), 132*1024)
4744 for range time.NewTicker(30 * time.Millisecond).C {
4745 select {
4746 case <-ctx.Done():
4747 wg.Done()
4748 return
4749 default:
4750 }
4751 ncA.Publish("test", payload)
4752 ncA.Flush()
4753 total++
4754 }
4755 }()
4756 wg.Add(1)
4757
4758 checkFor(t, 20*time.Second, 2*time.Millisecond, func() error {
4759 if s1.NumRoutes() < 1 {
4760 return fmt.Errorf("No routes connected")
4761 }
4762 if !hasSlowConsumerRoutes(s1) {
4763 if s1.NumSlowConsumersRoutes() > 0 {
4764 // In case it has recovered already.
4765 return nil
4766 }
4767 return fmt.Errorf("Expected Slow Consumer routes")
4768 }
4769 return nil
4770 })
4771 cancel()
4772 changeWriteDeadline(s1, 5*time.Second)
4773 np.updateRTT(0)
4774 checkFor(t, 20*time.Second, 10*time.Millisecond, func() error {
4775 if s1.NumRoutes() < 1 {
4776 return fmt.Errorf("No routes connected")
4777 }
4778 if hasSlowConsumerRoutes(s1) {
4779 return fmt.Errorf("Expected Slow Consumer routes to recover")
4780 }
4781 return nil
4782 })
4783
4784 checkFor(t, 20*time.Second, 100*time.Millisecond, func() error {
4785 var got, expected int64
4786 got = int64(s1.NumSlowConsumersRoutes())
4787 expected = 1
4788 if got != expected {
4789 return fmt.Errorf("got: %d, expected: %d", got, expected)
4790 }
4791 return nil
4792 })
4793 wg.Wait()
4794 }
4795
4796 func TestRouteNoLeakOnAuthTimeout(t *testing.T) {
4797 opts := DefaultOptions()
4798 opts.Cluster.Username = "foo"
4799 opts.Cluster.Password = "bar"
4800 opts.AuthTimeout = 0.01 // Deliberately short timeout
4801 s := RunServer(opts)
4802 defer s.Shutdown()
4803
4804 c, err := net.Dial("tcp", net.JoinHostPort(opts.Host, fmt.Sprintf("%d", opts.Cluster.Port)))
4805 if err != nil {
4806 t.Fatalf("Error connecting: %v", err)
4807 }
4808 defer c.Close()
4809
4810 cr := bufio.NewReader(c)
4811
4812 // Wait for INFO...
4813 line, _, _ := cr.ReadLine()
4814 var info serverInfo
4815 if err = json.Unmarshal(line[5:], &info); err != nil {
4816 t.Fatalf("Could not parse INFO json: %v\n", err)
4817 }
4818
4819 // Wait out the clock so we hit the auth timeout
4820 time.Sleep(secondsToDuration(opts.AuthTimeout) * 2)
4821 line, _, _ = cr.ReadLine()
4822 if string(line) != "-ERR 'Authentication Timeout'" {
4823 t.Fatalf("Expected '-ERR 'Authentication Timeout'' but got %q", line)
4824 }
4825
4826 // There shouldn't be a route entry as we didn't set up.
4827 if nc := s.NumRoutes(); nc != 0 {
4828 t.Fatalf("Server should have no route connections, got %v", nc)
4829 }
4830 }
4831
4832 func TestRouteNoRaceOnClusterNameNegotiation(t *testing.T) {
4833 // Running the test 5 times was consistently producing the race.
4834 for i := 0; i < 5; i++ {
4835 o1 := DefaultOptions()
4836 // Set this cluster name as dynamic
4837 o1.Cluster.Name = _EMPTY_
4838 // Increase number of routes and pinned accounts to increase
4839 // the number of processRouteConnect() happening in parallel
4840 // to produce the race.
4841 o1.Cluster.PoolSize = 5
4842 o1.Cluster.PinnedAccounts = []string{"A", "B", "C", "D"}
4843 o1.Accounts = []*Account{NewAccount("A"), NewAccount("B"), NewAccount("C"), NewAccount("D")}
4844 s1 := RunServer(o1)
4845 defer s1.Shutdown()
4846
4847 route := RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
4848
4849 o2 := DefaultOptions()
4850 // Set this one as explicit. Use name that is likely to be "higher"
4851 // than the dynamic one.
4852 o2.Cluster.Name = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
4853 o2.Cluster.PoolSize = 5
4854 o2.Cluster.PinnedAccounts = []string{"A", "B", "C", "D"}
4855 o2.Accounts = []*Account{NewAccount("A"), NewAccount("B"), NewAccount("C"), NewAccount("D")}
4856 o2.Routes = route
4857 s2 := RunServer(o2)
4858 defer s2.Shutdown()
4859 checkClusterFormed(t, s1, s2)
4860 s2.Shutdown()
4861 s1.Shutdown()
4862 }
4863 }
4864
4865 func TestRouteImplicitNotTooManyDuplicates(t *testing.T) {
4866 for _, test := range []struct {
4867 name string
4868 pooling bool
4869 compression bool
4870 }{
4871 {"no pooling-no compression", false, false},
4872 {"no pooling-compression", false, true},
4873 {"pooling-no compression", true, false},
4874 {"pooling-compression", true, true},
4875 } {
4876 t.Run(test.name, func(t *testing.T) {
4877 o := DefaultOptions()
4878 o.ServerName = "SEED"
4879 if !test.pooling {
4880 o.Cluster.PoolSize = -1
4881 }
4882 if !test.compression {
4883 o.Cluster.Compression.Mode = CompressionOff
4884 }
4885 seed := RunServer(o)
4886 defer seed.Shutdown()
4887
4888 dl := &testDuplicateRouteLogger{}
4889
4890 servers := make([]*Server, 0, 10)
4891 for i := 0; i < cap(servers); i++ {
4892 io := DefaultOptions()
4893 io.ServerName = fmt.Sprintf("IMPLICIT_%d", i+1)
4894 io.NoLog = false
4895 io.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o.Cluster.Port))
4896 if !test.pooling {
4897 io.Cluster.PoolSize = -1
4898 }
4899 if !test.compression {
4900 io.Cluster.Compression.Mode = CompressionOff
4901 }
4902 is, err := NewServer(io)
4903 require_NoError(t, err)
4904 // Will do defer of shutdown later.
4905 is.SetLogger(dl, true, false)
4906 is.Start()
4907 servers = append(servers, is)
4908 }
4909
4910 allServers := make([]*Server, 0, len(servers)+1)
4911 allServers = append(allServers, seed)
4912 allServers = append(allServers, servers...)
4913
4914 // Let's make sure that we wait for each server to be ready.
4915 for _, s := range allServers {
4916 if !s.ReadyForConnections(2 * time.Second) {
4917 t.Fatalf("Server %q is not ready for connections", s)
4918 }
4919 }
4920
4921 // Do the defer of shutdown of all servers this way instead of individual
4922 // defers when starting them. It takes less time for the servers to shutdown
4923 // this way.
4924 defer func() {
4925 for _, s := range allServers {
4926 s.Shutdown()
4927 }
4928 }()
4929 checkClusterFormed(t, allServers...)
4930
4931 dl.Mutex.Lock()
4932 count := dl.count
4933 dl.Mutex.Unlock()
4934 // Getting duplicates should not be considered fatal, it is an optimization
4935 // to reduce the occurrences of those. But to make sure we don't have a
4936 // regression, we will fail the test if we get say more than 20 or so (
4937 // without the code change, we would get more than 500 of duplicates).
4938 if count > 20 {
4939 t.Fatalf("Got more duplicates than anticipated: %v", count)
4940 }
4941 })
4942 }
4943 }
4944
4945 func TestRouteImplicitJoinsSeparateGroups(t *testing.T) {
4946 // The test TestRouteImplicitNotTooManyDuplicates makes sure that we do
4947 // not have too many duplicate routes cases when processing implicit routes.
4948 // This test is to ensure that the code changes to reduce the number
4949 // of duplicate routes does not prevent the formation of the cluster
4950 // with the given setup (which is admittedly not good since a disconnect
4951 // between some routes would not result in a reconnect leading to a full mesh).
4952 // Still, original code was able to create the original full mesh, so we want
4953 // to make sure that this is still possible.
4954 for _, test := range []struct {
4955 name string
4956 pooling bool
4957 compression bool
4958 }{
4959 {"no pooling-no compression", false, false},
4960 {"no pooling-compression", false, true},
4961 {"pooling-no compression", true, false},
4962 {"pooling-compression", true, true},
4963 } {
4964 t.Run(test.name, func(t *testing.T) {
4965 setOpts := func(o *Options) {
4966 if !test.pooling {
4967 o.Cluster.PoolSize = -1
4968 }
4969 if !test.compression {
4970 o.Cluster.Compression.Mode = CompressionOff
4971 }
4972 }
4973
4974 // Create a cluster s1/s2/s3
4975 o1 := DefaultOptions()
4976 o1.ServerName = "S1"
4977 setOpts(o1)
4978 s1 := RunServer(o1)
4979 defer s1.Shutdown()
4980
4981 o2 := DefaultOptions()
4982 o2.ServerName = "S2"
4983 setOpts(o2)
4984 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
4985 s2 := RunServer(o2)
4986 defer s2.Shutdown()
4987
4988 tmpl := `
4989 server_name: "S3"
4990 listen: "127.0.0.1:-1"
4991 cluster {
4992 name: "abc"
4993 listen: "127.0.0.1:-1"
4994 %s
4995 %s
4996 routes: ["nats://127.0.0.1:%d"%s]
4997 }
4998 `
4999 var poolCfg string
5000 var compressionCfg string
5001 if !test.pooling {
5002 poolCfg = "pool_size: -1"
5003 }
5004 if !test.compression {
5005 compressionCfg = "compression: off"
5006 }
5007 conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, poolCfg, compressionCfg, o1.Cluster.Port, _EMPTY_)))
5008 s3, _ := RunServerWithConfig(conf)
5009 defer s3.Shutdown()
5010
5011 checkClusterFormed(t, s1, s2, s3)
5012
5013 // Now s4 and s5 connected to each other, but not linked to s1/s2/s3
5014 o4 := DefaultOptions()
5015 o4.ServerName = "S4"
5016 setOpts(o4)
5017 s4 := RunServer(o4)
5018 defer s4.Shutdown()
5019
5020 o5 := DefaultOptions()
5021 o5.ServerName = "S5"
5022 setOpts(o5)
5023 o5.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o4.Cluster.Port))
5024 s5 := RunServer(o5)
5025 defer s5.Shutdown()
5026
5027 checkClusterFormed(t, s4, s5)
5028
5029 // Now add a route from s3 to s4 and make sure that we have a full mesh.
5030 routeToS4 := fmt.Sprintf(`, "nats://127.0.0.1:%d"`, o4.Cluster.Port)
5031 reloadUpdateConfig(t, s3, conf, fmt.Sprintf(tmpl, poolCfg, compressionCfg, o1.Cluster.Port, routeToS4))
5032
5033 checkClusterFormed(t, s1, s2, s3, s4, s5)
5034 })
5035 }
5036 }
5037
5038 // Extra regression test for issue fixed via:
5039 //
5040 // https://github.com/nats-io/nats-server/commit/d5ef552ae46d7c284e4bfdf01211f97893b2f38f
5041 func TestRouteMsgWithManyHeadersDoesNotCorruptJSON(t *testing.T) {
5042 tmpl := `
5043 port: -1
5044 server_name: "%s"
5045 accounts {
5046 A {
5047 users: [ { user: a, password: pwd } ]
5048 exports: [ { service: "svc.>" } ]
5049 }
5050 B {
5051 users: [ { user: b, password: pwd } ]
5052 imports: [ { service: { account: A, subject: "svc.>" } } ]
5053 }
5054 }
5055 cluster {
5056 name: "TEST"
5057 port: -1
5058 compression: s2_fast
5059 %s
5060 }
5061 `
5062 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "S1", "")))
5063 s1, o1 := RunServerWithConfig(conf1)
5064 defer s1.Shutdown()
5065
5066 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "S2",
5067 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
5068 s2, _ := RunServerWithConfig(conf2)
5069 defer s2.Shutdown()
5070
5071 checkClusterFormed(t, s1, s2)
5072
5073 // Account A responder on S2 — the destination of the service import.
5074 ncAResp := natsConnect(t, s2.ClientURL(), nats.UserInfo("a", "pwd"))
5075 defer ncAResp.Close()
5076 respCount := atomic.Int64{}
5077 _, err := ncAResp.Subscribe("svc.>", func(m *nats.Msg) {
5078 respCount.Add(1)
5079 })
5080 require_NoError(t, err)
5081 require_NoError(t, ncAResp.Flush())
5082
5083 // Account B subscriber on S2 — receives over the route from S1.
5084 ncB2 := natsConnect(t, s2.ClientURL(), nats.UserInfo("b", "pwd"))
5085 defer ncB2.Close()
5086 subB2, err := ncB2.SubscribeSync("svc.>")
5087 require_NoError(t, err)
5088 defer subB2.Unsubscribe()
5089 require_NoError(t, subB2.SetPendingLimits(-1, -1))
5090 require_NoError(t, ncB2.Flush())
5091
5092 checkSubInterest(t, s1, "A", "svc.foo", time.Second)
5093 checkSubInterest(t, s1, "B", "svc.foo", time.Second)
5094 checkSubInterest(t, s2, "B", "svc.foo", time.Second)
5095
5096 total := 3000
5097 bodies := make([][]byte, total)
5098 for i := 0; i < total; i++ {
5099 filler := strings.Repeat("x", 32+rand.Intn(12*1024))
5100 body := fmt.Sprintf(
5101 `{"branch":"main","idx":%d,`+
5102 `"some_tag":"tag-aaaaaaaaaaaaaaaaaaaaaaaa",`+
5103 `"data":{"context":{"commit":"0123456789abcdef0123456789abcdef01234567",`+
5104 `"scope":"api","filler":%q},`+
5105 `"payload":{"client_ip_address":"2001:db8::1","seq":%d}}}`,
5106 i, filler, i)
5107 bodies[i] = []byte(body)
5108 }
5109
5110 producers := 8
5111 var pwg sync.WaitGroup
5112 for p := 0; p < producers; p++ {
5113 pwg.Add(1)
5114 go func(p int) {
5115 defer pwg.Done()
5116 pnc := natsConnect(t, s1.ClientURL(), nats.UserInfo("b", "pwd"))
5117 defer pnc.Close()
5118 for i := p; i < total; i += producers {
5119 m := nats.NewMsg(fmt.Sprintf("svc.%d", i%64))
5120 m.Data = bodies[i]
5121 // Many headers, varying sizes, in a mix that sorts before and after "Nats-Request-Info"
5122 // so that it has both leading and trailing neighbors.
5123 m.Header.Set("Idx", strconv.Itoa(i))
5124 m.Header.Set("Nats-Msg-Id", fmt.Sprintf("msg-%06d", i))
5125 // Extra header which will be removed on the fly.
5126 m.Header.Set("Nats-Request-Info", `{"acc":"B","user":"b","host":"prefilled"}`)
5127 m.Header.Set("Trace-Id", "trace-aaaaaaaaaaaaaaaaaaaaaaaa")
5128 m.Header.Set("Span-Id", "span-bbbbbbbbbbbbbbbbbbbbbbbb")
5129 m.Header.Set("Request-Id", "request-cccccccccccccccccccccccc")
5130 m.Header.Set("Source-App", "test-app")
5131 m.Header.Set("X-Filler", strings.Repeat("filler-", 16)+strconv.Itoa(rand.Int()))
5132 m.Header.Set("X-Tail-Header", fmt.Sprintf("idx=%d-stable-tail-data", i))
5133 if err := pnc.PublishMsg(m); err != nil {
5134 t.Errorf("publish %d: %v", i, err)
5135 return
5136 }
5137 }
5138 _ = pnc.Flush()
5139 }(p)
5140 }
5141 pwg.Wait()
5142
5143 seen := make(map[int]bool, total)
5144 deadline := time.Now().Add(120 * time.Second)
5145 for len(seen) < total {
5146 if time.Now().After(deadline) {
5147 t.Fatalf("subB2: timed out: got %d/%d", len(seen), total)
5148 }
5149 m, err := subB2.NextMsg(2 * time.Second)
5150 if err != nil {
5151 continue
5152 }
5153 var parsed struct {
5154 Branch string `json:"branch"`
5155 Idx int `json:"idx"`
5156 Tag string `json:"some_tag"`
5157 Data struct {
5158 Context struct {
5159 Commit string `json:"commit"`
5160 Scope string `json:"scope"`
5161 Filler string `json:"filler"`
5162 } `json:"context"`
5163 Payload struct {
5164 ClientIPAddress string `json:"client_ip_address"`
5165 Seq int `json:"seq"`
5166 } `json:"payload"`
5167 } `json:"data"`
5168 }
5169 if err := json.Unmarshal(m.Data, &parsed); err != nil {
5170 t.Fatalf("subB2 json.Unmarshal failed: %v: data[:256]=%q",
5171 err, m.Data[:min(256, len(m.Data))])
5172 }
5173 // Ensure all headers are still present.
5174 idxStr := m.Header.Get("Idx")
5175 if idxStr == "" {
5176 keys := make([]string, 0, len(m.Header))
5177 for k := range m.Header {
5178 keys = append(keys, k)
5179 }
5180 t.Fatalf("subB2: received message with no/empty Idx header (corruption): subj=%s data[:128]=%q allHeaderKeys=%v",
5181 m.Subject, m.Data[:min(128, len(m.Data))], keys)
5182 }
5183 // Detect garbage header keys (e.g., 'c"' from leftover '"acc":"B"...')
5184 // and silently dropped expected keys.
5185 expectedKeys := map[string]bool{
5186 "Idx": true, "Nats-Msg-Id": true, "Nats-Request-Info": true,
5187 "Trace-Id": true, "Span-Id": true, "Request-Id": true,
5188 "Source-App": true, "X-Filler": true, "X-Tail-Header": true,
5189 }
5190 gotKeys := make(map[string]bool, len(m.Header))
5191 for k := range m.Header {
5192 gotKeys[k] = true
5193 }
5194 for k := range gotKeys {
5195 if !expectedKeys[k] {
5196 keys := make([]string, 0, len(gotKeys))
5197 for kk := range gotKeys {
5198 keys = append(keys, kk)
5199 }
5200 t.Fatalf("subB2 idx=%s: unexpected header key %q (corruption); allKeys=%v",
5201 idxStr, k, keys)
5202 }
5203 }
5204 for k := range expectedKeys {
5205 if !gotKeys[k] {
5206 keys := make([]string, 0, len(gotKeys))
5207 for kk := range gotKeys {
5208 keys = append(keys, kk)
5209 }
5210 t.Fatalf("subB2 idx=%s: expected header key %q missing (corruption); allKeys=%v",
5211 idxStr, k, keys)
5212 }
5213 }
5214 idx, err := strconv.Atoi(idxStr)
5215 require_NoError(t, err)
5216 // Bounds check so corruption that rewrites Idx to an out-of-range value
5217 // cannot inflate len(seen) and produce a false negative.
5218 if idx < 0 || idx >= total {
5219 t.Fatalf("subB2: Idx header out of range (corruption): idx=%d total=%d data[:128]=%q",
5220 idx, total, m.Data[:min(128, len(m.Data))])
5221 }
5222
5223 // Check that parsed JSON contains the expected data.
5224 if parsed.Idx != idx {
5225 t.Fatalf("subB2 idx=%d: parsed idx mismatch got=%d", idx, parsed.Idx)
5226 }
5227 if parsed.Data.Payload.Seq != idx {
5228 t.Fatalf("subB2 idx=%d: parsed payload.seq mismatch got=%d", idx, parsed.Data.Payload.Seq)
5229 }
5230 // Headers should round-trip intact.
5231 if got := m.Header.Get("Idx"); got != idxStr {
5232 t.Fatalf("subB2 idx=%d: Idx header corrupted, got=%q", idx, got)
5233 }
5234 if got := m.Header.Get("Nats-Msg-Id"); got != fmt.Sprintf("msg-%06d", idx) {
5235 t.Fatalf("subB2 idx=%d: Nats-Msg-Id corrupted, got=%q", idx, got)
5236 }
5237 wantTail := fmt.Sprintf("idx=%d-stable-tail-data", idx)
5238 if got := m.Header.Get("X-Tail-Header"); got != wantTail {
5239 t.Fatalf("subB2 idx=%d: X-Tail-Header corrupted, got=%q want=%q", idx, got, wantTail)
5240 }
5241 seen[idx] = true
5242 }
5243
5244 // Check that all messages were received.
5245 checkFor(t, 5*time.Second, 50*time.Millisecond, func() error {
5246 if got := respCount.Load(); got != int64(total) {
5247 return fmt.Errorf("Account A responder: got %d/%d messages", got, total)
5248 }
5249 return nil
5250 })
5251 }
5252
5253 func TestRouteConfigureWriteDeadline(t *testing.T) {
5254 o1, o2 := DefaultOptions(), DefaultOptions()
5255
5256 o1.Cluster.WriteDeadline = 5 * time.Second
5257 s1 := RunServer(o1)
5258 defer s1.Shutdown()
5259
5260 o2.Cluster.WriteDeadline = 6 * time.Second
5261 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
5262 s2 := RunServer(o2)
5263 defer s2.Shutdown()
5264
5265 checkClusterFormed(t, s1, s2)
5266
5267 s1.mu.RLock()
5268 s2.mu.RLock()
5269 defer s1.mu.RUnlock()
5270 defer s2.mu.RUnlock()
5271
5272 s1.forEachRoute(func(r *client) {
5273 require_Equal(t, r.out.wdl, 5*time.Second)
5274 })
5275
5276 s2.forEachRoute(func(r *client) {
5277 require_Equal(t, r.out.wdl, 6*time.Second)
5278 })
5279 }
5280
5281 func TestRouteConfigureWriteTimeoutPolicy(t *testing.T) {
5282 for name, policy := range map[string]WriteTimeoutPolicy{
5283 "Default": WriteTimeoutPolicyDefault,
5284 "Retry": WriteTimeoutPolicyRetry,
5285 "Close": WriteTimeoutPolicyClose,
5286 } {
5287 t.Run(name, func(t *testing.T) {
5288 o1 := testDefaultOptionsForGateway("B")
5289 o1.Gateway.WriteTimeout = policy
5290 s1 := runGatewayServer(o1)
5291 defer s1.Shutdown()
5292
5293 o2 := testGatewayOptionsFromToWithServers(t, "A", "B", s1)
5294 s2 := runGatewayServer(o2)
5295 defer s2.Shutdown()
5296
5297 waitForOutboundGateways(t, s2, 1, time.Second)
5298 waitForInboundGateways(t, s1, 1, time.Second)
5299 waitForOutboundGateways(t, s1, 1, time.Second)
5300
5301 s1.mu.RLock()
5302 defer s1.mu.RUnlock()
5303
5304 s1.forEachRoute(func(r *client) {
5305 if policy == WriteTimeoutPolicyDefault {
5306 require_Equal(t, r.out.wtp, WriteTimeoutPolicyRetry)
5307 } else {
5308 require_Equal(t, r.out.wtp, policy)
5309 }
5310 })
5311 })
5312 }
5313 }
5314
5315 func TestRoutePoolFirstPongBlocksChain(t *testing.T) {
5316 // Use a very short ping interval so the timer fires quickly, before we (the mock server) send our INFO.
5317 orgMaxPing := routeMaxPingInterval
5318 routeMaxPingInterval = 200 * time.Millisecond
5319 defer func() { routeMaxPingInterval = orgMaxPing }()
5320
5321 // Start a TCP listener acting as a mock route server. S2 will solicit a connection to this listener.
5322 mockListener, err := net.Listen("tcp", "127.0.0.1:0")
5323 require_NoError(t, err)
5324 defer mockListener.Close()
5325
5326 mockPort := mockListener.Addr().(*net.TCPAddr).Port
5327
5328 o2 := DefaultOptions()
5329 o2.ServerName = "S2"
5330 o2.Cluster.Name = "local"
5331 o2.Cluster.PoolSize = 3
5332 o2.Cluster.Compression.Mode = CompressionOff
5333 o2.Cluster.MaxPingsOut = 10
5334 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", mockPort))
5335 s2 := RunServer(o2)
5336 defer s2.Shutdown()
5337
5338 var ready sync.WaitGroup
5339 var keepAlive sync.WaitGroup
5340 mockListener.(*net.TCPListener).SetDeadline(time.Now().Add(5 * time.Second))
5341 handleConnection := func() {
5342 conn, err := mockListener.Accept()
5343 if err != nil {
5344 ready.Done()
5345 require_NoError(t, err)
5346 }
5347 defer conn.Close()
5348 br := bufio.NewReader(conn)
5349
5350 // Ensure we call these before conn.Close() above.
5351 // We have to wait for both connections to be ready and then wait for the test to finish.
5352 defer keepAlive.Wait()
5353 defer ready.Done()
5354
5355 // S2 sends CONNECT immediately (solicited route).
5356 // Read it but do NOT send our INFO yet — we want S2's timer to fire first.
5357 require_NoError(t, conn.SetReadDeadline(time.Now().Add(5*time.Second)))
5358
5359 // Read S2's CONNECT line.
5360 line, err := br.ReadString('\n')
5361 require_NoError(t, err)
5362 require_True(t, strings.HasPrefix(line, "CONNECT"))
5363
5364 // Wait for S2's timer PING to arrive.
5365 // The readLoop on S2 is blocked waiting for our INFO, so the
5366 // timer goroutine enqueues the PING on S2's outbound buffer.
5367 checkFor(t, 5*time.Second, 100*time.Millisecond, func() error {
5368 if _, err = conn.Write([]byte("PING\r\n")); err != nil {
5369 return err
5370 }
5371 if line, err = br.ReadString('\n'); err != nil {
5372 return err
5373 }
5374 t.Logf("S2 received: %q", line)
5375 if !strings.HasPrefix(line, "PING") {
5376 return fmt.Errorf("expected PING, got %q", line)
5377 }
5378 return nil
5379 })
5380
5381 // Respond with PONG — this sets firstPong on S2's route connection
5382 // BEFORE addRoute has run (since we haven't sent INFO yet).
5383 _, err = conn.Write([]byte("PONG\r\n"))
5384 require_NoError(t, err)
5385
5386 // NOW send our INFO. This triggers S2's processRouteInfo → addRoute,
5387 // which sets startNewRoute and sends another PING.
5388 mockInfo := Info{
5389 ID: "MOCK_SERVER_ID",
5390 Name: "mock-server",
5391 Host: "127.0.0.1",
5392 Port: mockPort,
5393 Cluster: "local",
5394 Headers: true,
5395 Proto: 1,
5396 RoutePoolSize: 3,
5397 }
5398 infoJSON, err := json.Marshal(mockInfo)
5399 require_NoError(t, err)
5400 _, err = fmt.Fprintf(conn, "INFO %s\r\n", infoJSON)
5401 require_NoError(t, err)
5402
5403 // Read S2's delayed INFO (sent during addRoute) + subscription data + PING.
5404 // We need to consume everything up to and including the PING.
5405 for {
5406 line, err = br.ReadString('\n')
5407 require_NoError(t, err)
5408 if strings.HasPrefix(line, "PING") {
5409 break
5410 }
5411 }
5412
5413 // Respond to addRoute's PING with PONG.
5414 _, err = conn.Write([]byte("PONG\r\n"))
5415 require_NoError(t, err)
5416 }
5417
5418 // Keep the below connections alive until the test is done.
5419 // This allows us to check that S2 creates the next pool connection.
5420 keepAlive.Add(1)
5421 defer keepAlive.Done()
5422
5423 ready.Add(2)
5424 for range 2 {
5425 go handleConnection()
5426 }
5427 ready.Wait()
5428
5429 // Check if S2 attempts to create a second pool connection by
5430 // trying to accept another connection on our mock listener.
5431 secondConnCh := make(chan struct{}, 1)
5432 go func() {
5433 mockListener.(*net.TCPListener).SetDeadline(time.Now().Add(2 * time.Second))
5434 if c2, err := mockListener.Accept(); err == nil {
5435 c2.Close()
5436 secondConnCh <- struct{}{}
5437 }
5438 }()
5439
5440 select {
5441 case <-secondConnCh:
5442 // Good — S2 tried to create the next pool connection.
5443 // The fix works: startNewRoute was consumed despite firstPong.
5444 case <-time.After(2 * time.Second):
5445 t.Fatalf("S2 did not attempt to create next pool connection; " +
5446 "firstPong blocked startNewRoute consumption, pool chain is broken")
5447 }
5448 }
5449
5450 // https://github.com/nats-io/nats-server/issues/8233
5451 func TestRouteSubUnsubRaceLosesRemoteInterest(t *testing.T) {
5452 oa := DefaultOptions()
5453 sa := RunServer(oa)
5454 defer sa.Shutdown()
5455
5456 ob := DefaultOptions()
5457 ob.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", oa.Cluster.Port))
5458 sb := RunServer(ob)
5459 defer sb.Shutdown()
5460
5461 checkClusterFormed(t, sa, sb)
5462
5463 // A client on node B, used to confirm the user-visible symptom: a request to
5464 // the subject gets "no responders" even though a live responder exists on A.
5465 ncReq := natsConnect(t, sb.ClientURL())
5466 defer ncReq.Close()
5467
5468 // Many subjects raced at once so they all contend the same global-account
5469 // acc.mu and the single pinned A->B route.mu.
5470 const (
5471 conns = 100
5472 waves = 10
5473 )
5474
5475 // Connection pools, reused across waves. ncMinus owns the original subscription
5476 // that gets removed, ncPlus adds the new responder that must survive. They are
5477 // distinct connections so their operations run on different readLoop goroutines
5478 // on node A and can race.
5479 ncMinus := make([]*nats.Conn, conns)
5480 ncPlus := make([]*nats.Conn, conns)
5481 for i := 0; i < conns; i++ {
5482 ncMinus[i] = natsConnect(t, sa.ClientURL())
5483 defer ncMinus[i].Close()
5484 ncPlus[i] = natsConnect(t, sa.ClientURL())
5485 defer ncPlus[i].Close()
5486 }
5487
5488 accB := sb.globalAccount()
5489 for w := range waves {
5490 subjects := make([]string, conns)
5491 minusSubs := make([]*nats.Subscription, conns)
5492 for i := range conns {
5493 subjects[i] = fmt.Sprintf("foo.%d.%d", w, i)
5494 // Original interest, mirrored to B via RS+. This is the "live"
5495 // subscription on B that makes the reordered RS+ a no-op.
5496 minusSubs[i] = natsSubSync(t, ncMinus[i], subjects[i])
5497 }
5498 for i := range conns {
5499 natsFlush(t, ncMinus[i])
5500 }
5501 // Make sure B sees all of the original interest before we start, so its
5502 // route already tracks each key.
5503 for i := range conns {
5504 checkSubInterest(t, sb, globalAccountName, subjects[i], 5*time.Second)
5505 }
5506
5507 // Fire the wave: for each subject, simultaneously remove the original
5508 // interest (-1) and add a replacement responder (+1) on node A.
5509 start := make(chan struct{})
5510 var wg sync.WaitGroup
5511 wg.Add(2 * conns)
5512 for i := range conns {
5513 go func() {
5514 defer wg.Done()
5515 <-start
5516 minusSubs[i].Unsubscribe()
5517 ncMinus[i].Flush()
5518 }()
5519 go func() {
5520 defer wg.Done()
5521 <-start
5522 ncPlus[i].Subscribe(subjects[i], func(m *nats.Msg) {
5523 m.Respond([]byte("ok"))
5524 })
5525 ncPlus[i].Flush()
5526 }()
5527 }
5528 close(start)
5529 wg.Wait()
5530
5531 // Barrier: subscribe a marker on the same (pinned) route and wait for B
5532 // to observe it. Because all of the wave's RS+/RS- protos were enqueued
5533 // on that same route connection before this one, FIFO ordering
5534 // guarantees that once B has the marker it has processed every proto
5535 // from the wave.
5536 marker := fmt.Sprintf("marker.%d", w)
5537 natsSubSync(t, ncPlus[0], marker)
5538 natsFlush(t, ncPlus[0])
5539 checkSubInterest(t, sb, globalAccountName, marker, 5*time.Second)
5540
5541 // Every subject still has a live local responder on A (the ncPlus sub),
5542 // so B must still have interest. If the race fired, B silently lost it.
5543 for i := range conns {
5544 if accB.SubscriptionInterest(subjects[i]) {
5545 continue
5546 }
5547 // Confirm the exact reported symptom: a request from a client on B
5548 // gets "no responders" although A has a live responder.
5549 _, rerr := ncReq.Request(subjects[i], []byte("ping"), time.Second)
5550 t.Fatalf("wave %d: node B lost interest in %q while node A still has a "+
5551 "live local responder; request from B returned %v (want a reply). "+
5552 "RS+/RS- were reordered on the A->B route by the "+
5553 "updateRouteSubscriptionMap race", w, subjects[i], rerr)
5554 }
5555 }
5556 }
5557
5558 // Benchmarks for message arg processing functions to measure heap allocations.
5559 // These functions parse incoming protocol messages and split arguments.
5560
5561 func BenchmarkProcessRoutedMsgArgs(b *testing.B) {
5562 // RMSG format: account subject [reply] size
5563 arg := []byte("$G foo.bar _INBOX.xxx 1024")
5564 c := &client{kind: ROUTER, route: &route{}}
5565 b.ReportAllocs()
5566 b.ResetTimer()
5567 for b.Loop() {
5568 if err := c.processRoutedMsgArgs(arg); err != nil {
5569 b.Fatal(err)
5570 }
5571 }
5572 }
5573
5574 func BenchmarkProcessRoutedHeaderMsgArgs(b *testing.B) {
5575 // HMSG format: account subject [reply] headerSize totalSize
5576 arg := []byte("$G foo.bar 12 1024")
5577 c := &client{kind: ROUTER, route: &route{}}
5578 b.ReportAllocs()
5579 b.ResetTimer()
5580 for b.Loop() {
5581 if err := c.processRoutedHeaderMsgArgs(arg); err != nil {
5582 b.Fatal(err)
5583 }
5584 }
5585 }
5586
5587 func BenchmarkProcessRoutedOriginClusterMsgArgs(b *testing.B) {
5588 // Origin cluster HMSG format: origin account subject [reply] headerSize totalSize
5589 arg := []byte("ORIGIN MY_ACCOUNT foo.bar 12 345")
5590 c := &client{kind: ROUTER, route: &route{}}
5591 b.ReportAllocs()
5592 b.ResetTimer()
5593 for b.Loop() {
5594 if err := c.processRoutedOriginClusterMsgArgs(arg); err != nil {
5595 b.Fatal(err)
5596 }
5597 }
5598 }
5599
5600 func BenchmarkProcessLeafMsgArgs(b *testing.B) {
5601 // LMSG format: subject [reply] size
5602 arg := []byte("foo.bar _INBOX.xxx 1024")
5603 c := &client{kind: LEAF}
5604 b.ReportAllocs()
5605 b.ResetTimer()
5606 for b.Loop() {
5607 if err := c.processLeafMsgArgs(arg); err != nil {
5608 b.Fatal(err)
5609 }
5610 }
5611 }
5612
5613 func BenchmarkProcessLeafHeaderMsgArgs(b *testing.B) {
5614 // Leaf HMSG format: subject headerSize totalSize
5615 arg := []byte("foo.bar 12 1024")
5616 c := &client{kind: LEAF}
5617 b.ReportAllocs()
5618 b.ResetTimer()
5619 for b.Loop() {
5620 if err := c.processLeafHeaderMsgArgs(arg); err != nil {
5621 b.Fatal(err)
5622 }
5623 }
5624 }
5625
5626 // Benchmarks with queue subscribers to exercise the larger arg paths.
5627
5628 func BenchmarkProcessRoutedMsgArgs_Queues(b *testing.B) {
5629 // RMSG format with queues: account subject replyIndicator reply queue1 queue2 size
5630 arg := []byte("$G foo.bar + _INBOX.xxx queue1 queue2 1024")
5631 c := &client{kind: ROUTER, route: &route{}}
5632 b.ReportAllocs()
5633 b.ResetTimer()
5634 for b.Loop() {
5635 if err := c.processRoutedMsgArgs(arg); err != nil {
5636 b.Fatal(err)
5637 }
5638 }
5639 }
5640
5641 func BenchmarkProcessRoutedHeaderMsgArgs_Queues(b *testing.B) {
5642 // HMSG format with queues: account subject replyIndicator reply queue1 queue2 headerSize totalSize
5643 arg := []byte("$G foo.bar + _INBOX.xxx queue1 queue2 12 1024")
5644 c := &client{kind: ROUTER, route: &route{}}
5645 b.ReportAllocs()
5646 b.ResetTimer()
5647 for b.Loop() {
5648 if err := c.processRoutedHeaderMsgArgs(arg); err != nil {
5649 b.Fatal(err)
5650 }
5651 }
5652 }
5653
5654 func BenchmarkProcessLeafMsgArgs_Queues(b *testing.B) {
5655 // LMSG format with queues: subject replyIndicator reply queue1 queue2 size
5656 arg := []byte("foo.bar + _INBOX.xxx queue1 queue2 1024")
5657 c := &client{kind: LEAF}
5658 b.ReportAllocs()
5659 b.ResetTimer()
5660 for b.Loop() {
5661 if err := c.processLeafMsgArgs(arg); err != nil {
5662 b.Fatal(err)
5663 }
5664 }
5665 }
5666
5667 func TestRouteReconnectAfterSolicitedUpgradeAdoptsConfiguredURL(t *testing.T) {
5668 // Default pool size + pinned $SYS route, like a production setup, with a
5669 // hostname-based route URL like production configs use.
5670 ob := DefaultOptions()
5671 sb := RunServer(ob)
5672 defer sb.Shutdown()
5673
5674 oa := DefaultOptions()
5675 oa.Routes = RoutesFromStr(fmt.Sprintf("nats://localhost:%d", sb.ClusterAddr().Port))
5676 sa := RunServer(oa)
5677 defer sa.Shutdown()
5678 checkClusterFormed(t, sa, sb)
5679
5680 // Find A's pooled route connection for the slot that carries the global
5681 // account's interest.
5682 gSlot := computeRoutePoolIdx(sa.getOpts().Cluster.PoolSize, globalAccountName)
5683 var route *client
5684 sa.mu.RLock()
5685 sa.forEachRouteIdx(gSlot, func(r *client) bool {
5686 route = r
5687 return false
5688 })
5689 sa.mu.RUnlock()
5690 require_NotNil(t, route)
5691
5692 // Put the connection in the pre-upgrade gossip-dial state, then run the
5693 // actual upgrade with the configured URL, as duplicate-route resolution
5694 // does. The upgrade must adopt the configured URL so the later reconnect
5695 // passes routeStillValid.
5696 gossipURL, err := url.Parse(fmt.Sprintf("nats-route://127.0.0.1:%d/", sb.ClusterAddr().Port))
5697 require_NoError(t, err)
5698 route.mu.Lock()
5699 route.route.didSolicit = true
5700 route.route.routeType = Implicit
5701 route.route.url = gossipURL
5702 route.mu.Unlock()
5703
5704 configured := oa.Routes[0]
5705 upgradeRouteToSolicited(route, configured, Explicit)
5706
5707 route.mu.Lock()
5708 upURL := route.route.url
5709 route.mu.Unlock()
5710 require_Equal(t, upURL, configured)
5711
5712 // Drop the connection the way a fault would (slow consumer). The sibling
5713 // pool slots and the pinned $SYS route stay up, so the remote is never
5714 // treated as new and only this reconnect can re-establish the slot.
5715 route.closeConnection(SlowConsumerWriteDeadline)
5716 checkClusterFormed(t, sa, sb)
5717
5718 // Interest must flow across the re-established slot again.
5719 nca := natsConnect(t, sa.ClientURL())
5720 defer nca.Close()
5721 ncb := natsConnect(t, sb.ClientURL())
5722 defer ncb.Close()
5723 natsSub(t, ncb, "reconnect.echo", func(m *nats.Msg) { m.Respond(m.Data) })
5724 natsFlush(t, ncb)
5725 checkSubInterest(t, sa, globalAccountName, "reconnect.echo", 2*time.Second)
5726 _, err = nca.Request("reconnect.echo", []byte("ping"), time.Second)
5727 require_NoError(t, err)
5728 }
5729
5730 func TestRouteReconnectAfterDuplicateRouteAdoptsConfiguredURL(t *testing.T) {
5731 // handleDuplicateRoute is the other path that promotes a route to Explicit,
5732 // used for duplicate per-account (pinned) routes and for any duplicate
5733 // route in non-pool mode. It must adopt the configured URL too, otherwise
5734 // routeStillValid rejects the gossiped one and the reconnect is abandoned.
5735 // The global account is pinned here so interest can use ordinary pub/sub.
5736 ob := DefaultOptions()
5737 ob.Cluster.PinnedAccounts = []string{globalAccountName}
5738 sb := RunServer(ob)
5739 defer sb.Shutdown()
5740
5741 oa := DefaultOptions()
5742 oa.Cluster.PinnedAccounts = []string{globalAccountName}
5743 oa.Routes = RoutesFromStr(fmt.Sprintf("nats://localhost:%d", sb.ClusterAddr().Port))
5744 sa := RunServer(oa)
5745 defer sa.Shutdown()
5746 checkClusterFormed(t, sa, sb)
5747
5748 // Grab A's pinned route for the global account.
5749 var pinned *client
5750 sa.mu.RLock()
5751 for _, r := range sa.accRoutes[globalAccountName] {
5752 pinned = r
5753 }
5754 sa.mu.RUnlock()
5755 require_NotNil(t, pinned)
5756
5757 // Put the connection in the pre-upgrade gossip-dial state, then resolve it
5758 // as a duplicate against the configured explicit route, as addRoute does
5759 // for a pinned account. The upgrade must adopt the configured URL so the
5760 // later reconnect passes routeStillValid.
5761 gossipURL, err := url.Parse(fmt.Sprintf("nats-route://127.0.0.1:%d/", sb.ClusterAddr().Port))
5762 require_NoError(t, err)
5763 pinned.mu.Lock()
5764 pinned.route.didSolicit = true
5765 pinned.route.routeType = Implicit
5766 pinned.route.url = gossipURL
5767 pinned.mu.Unlock()
5768
5769 configured := oa.Routes[0]
5770 dup := &client{}
5771 dup.route = &route{
5772 url: configured,
5773 didSolicit: true,
5774 routeType: Explicit,
5775 accName: []byte(globalAccountName),
5776 }
5777 handleDuplicateRoute(pinned, dup, true)
5778
5779 pinned.mu.Lock()
5780 upURL := pinned.route.url
5781 pinned.mu.Unlock()
5782 require_Equal(t, upURL, configured)
5783
5784 // Drop the connection the way a fault would (slow consumer). The pinned
5785 // route must come back, otherwise this account's mesh stays severed while
5786 // every pooled route looks healthy.
5787 pinned.closeConnection(SlowConsumerWriteDeadline)
5788 checkClusterFormed(t, sa, sb)
5789
5790 checkFor(t, 5*time.Second, 50*time.Millisecond, func() error {
5791 sa.mu.RLock()
5792 defer sa.mu.RUnlock()
5793 for _, r := range sa.accRoutes[globalAccountName] {
5794 if r != nil && r != pinned {
5795 return nil
5796 }
5797 }
5798 return fmt.Errorf("pinned route for %q did not reconnect", globalAccountName)
5799 })
5800
5801 // Interest must flow across the re-established pinned route again.
5802 nca := natsConnect(t, sa.ClientURL())
5803 defer nca.Close()
5804 ncb := natsConnect(t, sb.ClientURL())
5805 defer ncb.Close()
5806 natsSub(t, ncb, "pinned.echo", func(m *nats.Msg) { m.Respond(m.Data) })
5807 natsFlush(t, ncb)
5808 checkSubInterest(t, sa, globalAccountName, "pinned.echo", 2*time.Second)
5809 _, err = nca.Request("pinned.echo", []byte("ping"), time.Second)
5810 require_NoError(t, err)
5811 }