Debian Codegraph @

test/cluster_test.go

raw
1 // Copyright 2012-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package test
15
16 import (
17 "errors"
18 "fmt"
19 "math"
20 "net"
21 "runtime"
22 "strings"
23 "sync"
24 "testing"
25 "time"
26
27 "github.com/nats-io/nats.go"
28 )
29
30 // tsTestServers returns a slice of fabricated URLs that point at non-existent
31 // NATS servers. Tests that rely on a "list with a single live server and many
32 // dead ones" pattern build their server list by appending the live URL to
33 // (a subset of) these.
34 func tsTestServers() []string {
35 return []string{
36 "nats://127.0.0.1:11222",
37 "nats://127.0.0.1:11223",
38 "nats://127.0.0.1:11224",
39 "nats://127.0.0.1:11225",
40 "nats://127.0.0.1:11226",
41 "nats://127.0.0.1:11227",
42 "nats://127.0.0.1:11228",
43 }
44 }
45
46 func TestServersOption(t *testing.T) {
47 c := newTester(t)
48
49 opts := nats.GetDefaultOptions()
50 opts.NoRandomize = true
51 // Need to lower this for Windows tests, otherwise would take too long.
52 opts.Timeout = 100 * time.Millisecond
53
54 // When getting "connection refused", we transform to ErrNoServers.
55 // However, on Windows, the connect() will get a i/o timeout, but
56 // we can't really suppress that one since we don't know if it is
57 // a real timeout or a failure to connect. So check differencly.
58 // Not nats.DefaultURL: 4222 is the tester's management endpoint here, so
59 // use a known-dead URL instead.
60 opts.Servers = []string{"nats://127.0.0.1:11221"}
61 _, err := opts.Connect()
62 if runtime.GOOS == "windows" {
63 if err == nil || !strings.Contains(err.Error(), "timeout") {
64 t.Fatalf("Expected timeout, got %v", err)
65 }
66 } else if err != nats.ErrNoServers {
67 t.Fatalf("Wrong error: '%v'", err)
68 }
69 opts.Servers = tsTestServers()
70 _, err = opts.Connect()
71 if runtime.GOOS == "windows" {
72 if err == nil || !strings.Contains(err.Error(), "timeout") {
73 t.Fatalf("Expected timeout, got %v", err)
74 }
75 } else if err == nil || err != nats.ErrNoServers {
76 t.Fatalf("Did not receive proper error: %v", err)
77 }
78
79 // Make sure we can connect to first server if running
80 s1Inst := c.CreateServer(t, false)
81 s1URL := s1Inst.Servers[0].URL
82 opts.Servers = append([]string{s1URL}, tsTestServers()...)
83
84 nc, err := opts.Connect()
85 if err != nil {
86 t.Fatalf("Could not connect: %v\n", err)
87 }
88 if nc.ConnectedUrl() != s1URL {
89 nc.Close()
90 t.Fatalf("Does not report correct connection: %s\n",
91 nc.ConnectedUrl())
92 }
93 nc.Close()
94 s1Inst.Destroy(t)
95
96 // Make sure we can connect to a non first server if running
97 s2Inst := c.CreateServer(t, false)
98 t.Cleanup(func() { s2Inst.Destroy(t) })
99 s2URL := s2Inst.Servers[0].URL
100 opts.Servers = append(tsTestServers(), s2URL)
101
102 nc, err = opts.Connect()
103 if err != nil {
104 t.Fatalf("Could not connect: %v\n", err)
105 }
106 defer nc.Close()
107 if nc.ConnectedUrl() != s2URL {
108 t.Fatalf("Does not report correct connection: %s\n",
109 nc.ConnectedUrl())
110 }
111 }
112
113 func TestNewStyleServersOption(t *testing.T) {
114 c := newTester(t)
115
116 // Not nats.DefaultURL: 4222 is the tester's management endpoint here, so
117 // use a known-dead URL instead.
118 _, err := nats.Connect("nats://127.0.0.1:11221", nats.DontRandomize(), nats.Timeout(100*time.Millisecond))
119 if runtime.GOOS == "windows" {
120 if err == nil || !strings.Contains(err.Error(), "timeout") {
121 t.Fatalf("Expected timeout, got %v", err)
122 }
123 } else if err != nats.ErrNoServers {
124 t.Fatalf("Wrong error: '%v'\n", err)
125 }
126
127 deadServers := strings.Join(tsTestServers(), ",")
128 _, err = nats.Connect(deadServers, nats.DontRandomize(), nats.Timeout(100*time.Millisecond))
129 if runtime.GOOS == "windows" {
130 if err == nil || !strings.Contains(err.Error(), "timeout") {
131 t.Fatalf("Expected timeout, got %v", err)
132 }
133 } else if err == nil || err != nats.ErrNoServers {
134 t.Fatalf("Did not receive proper error: %v\n", err)
135 }
136
137 // Make sure we can connect to first server if running
138 s1Inst := c.CreateServer(t, false)
139 s1URL := s1Inst.Servers[0].URL
140
141 srvsWithS1 := strings.Join(append([]string{s1URL}, tsTestServers()...), ",")
142 nc, err := nats.Connect(srvsWithS1, nats.DontRandomize(), nats.Timeout(100*time.Millisecond))
143 if err != nil {
144 t.Fatalf("Could not connect: %v\n", err)
145 }
146 if nc.ConnectedUrl() != s1URL {
147 nc.Close()
148 t.Fatalf("Does not report correct connection: %s\n",
149 nc.ConnectedUrl())
150 }
151 nc.Close()
152 s1Inst.Destroy(t)
153
154 // Make sure we can connect to a non-first server if running
155 s2Inst := c.CreateServer(t, false)
156 t.Cleanup(func() { s2Inst.Destroy(t) })
157 s2URL := s2Inst.Servers[0].URL
158
159 srvsWithS2 := strings.Join(append(tsTestServers(), s2URL), ",")
160 nc, err = nats.Connect(srvsWithS2, nats.DontRandomize(), nats.Timeout(100*time.Millisecond))
161 if err != nil {
162 t.Fatalf("Could not connect: %v\n", err)
163 }
164 defer nc.Close()
165 if nc.ConnectedUrl() != s2URL {
166 t.Fatalf("Does not report correct connection: %s\n",
167 nc.ConnectedUrl())
168 }
169 }
170
171 func TestAuthServers(t *testing.T) {
172 c := newTester(t)
173
174 authBody := `authorization {
175 user: derek
176 password: foo
177 timeout: 1
178 }`
179 authOpts := singleUserPassOpts(authBody)
180
181 as1Inst := c.CreateServer(t, false, authOpts...)
182 t.Cleanup(func() { as1Inst.Destroy(t) })
183 as2Inst := c.CreateServer(t, false, authOpts...)
184 t.Cleanup(func() { as2Inst.Destroy(t) })
185
186 as1URL := as1Inst.Servers[0].URL
187 as2URL := as2Inst.Servers[0].URL
188
189 plainServers := []string{as1URL, as2URL}
190 pservers := strings.Join(plainServers, ",")
191 nc, err := nats.Connect(pservers, nats.DontRandomize(), nats.Timeout(5*time.Second))
192 if err == nil {
193 nc.Close()
194 t.Fatalf("Expect Auth failure, got no error\n")
195 }
196
197 if !strings.Contains(err.Error(), "Authorization") {
198 t.Fatalf("Wrong error, wanted Auth failure, got '%s'\n", err)
199 }
200
201 if !errors.Is(err, nats.ErrAuthorization) {
202 t.Fatalf("Expected error '%v', got '%v'", nats.ErrAuthorization, err)
203 }
204
205 // Test that we can connect to a subsequent correct server.
206 // Embed creds in the second URL.
207 as2HostPort := strings.TrimPrefix(as2URL, "nats://")
208 authServers := []string{
209 as1URL,
210 fmt.Sprintf("nats://derek:foo@%s", as2HostPort),
211 }
212 aservers := strings.Join(authServers, ",")
213 nc, err = nats.Connect(aservers, nats.DontRandomize(), nats.Timeout(5*time.Second))
214 if err != nil {
215 t.Fatalf("Expected to connect properly: %v\n", err)
216 }
217 defer nc.Close()
218 if nc.ConnectedUrl() != authServers[1] {
219 t.Fatalf("Does not report correct connection: %s\n",
220 nc.ConnectedUrl())
221 }
222 }
223
224 func TestBasicClusterReconnect(t *testing.T) {
225 c := newTester(t)
226 s1Inst := c.CreateServer(t, false)
227 t.Cleanup(func() { s1Inst.Destroy(t) })
228 s2Inst := c.CreateServer(t, false)
229 t.Cleanup(func() { s2Inst.Destroy(t) })
230
231 s1URL := s1Inst.Servers[0].URL
232 s2URL := s2Inst.Servers[0].URL
233
234 servers := strings.Join([]string{s1URL, s2URL}, ",")
235
236 dch := make(chan bool)
237 rch := make(chan bool)
238
239 dcbCalled := false
240
241 opts := []nats.Option{nats.DontRandomize(),
242 nats.Timeout(100 * time.Millisecond),
243 nats.DisconnectErrHandler(func(nc *nats.Conn, _ error) {
244 // Suppress any additional callbacks
245 if dcbCalled {
246 return
247 }
248 dcbCalled = true
249 dch <- true
250 }),
251 nats.ReconnectHandler(func(_ *nats.Conn) { rch <- true }),
252 }
253
254 nc, err := nats.Connect(servers, opts...)
255 if err != nil {
256 t.Fatalf("Expected to connect, got err: %v\n", err)
257 }
258 defer nc.Close()
259
260 s1Inst.StopServer(t, s1Inst.Servers[0])
261
262 // wait for disconnect
263 if e := WaitTime(dch, 2*time.Second); e != nil {
264 t.Fatal("Did not receive a disconnect callback message")
265 }
266
267 reconnectTimeStart := time.Now()
268
269 // wait for reconnect
270 if e := WaitTime(rch, 2*time.Second); e != nil {
271 t.Fatal("Did not receive a reconnect callback message")
272 }
273
274 if nc.ConnectedUrl() != s2URL {
275 t.Fatalf("Does not report correct connection: %s\n",
276 nc.ConnectedUrl())
277 }
278
279 // Make sure we did not wait on reconnect for default time.
280 // Reconnect should be fast since it will be a switch to the
281 // second server and not be dependent on server restart time.
282
283 // On Windows, a failed connect takes more than a second, so
284 // account for that.
285 maxDuration := 100 * time.Millisecond
286 if runtime.GOOS == "windows" {
287 maxDuration = 1100 * time.Millisecond
288 }
289 reconnectTime := time.Since(reconnectTimeStart)
290 if reconnectTime > maxDuration {
291 t.Fatalf("Took longer than expected to reconnect: %v\n", reconnectTime)
292 }
293 }
294
295 func TestHotSpotReconnect(t *testing.T) {
296 c := newTester(t)
297 s1Inst := c.CreateServer(t, false)
298 t.Cleanup(func() { s1Inst.Destroy(t) })
299
300 s1URL := s1Inst.Servers[0].URL
301
302 numClients := 32
303 clients := []*nats.Conn{}
304
305 wg := &sync.WaitGroup{}
306 wg.Add(numClients)
307
308 opts := []nats.Option{
309 nats.ReconnectWait(50 * time.Millisecond),
310 nats.ReconnectJitter(0, 0),
311 nats.ReconnectHandler(func(_ *nats.Conn) { wg.Done() }),
312 }
313
314 // Pre-create s2 and s3 but stop them immediately, so every client lands
315 // on s1 before they are brought up.
316 s2Inst := c.CreateServer(t, false)
317 t.Cleanup(func() { s2Inst.Destroy(t) })
318 s3Inst := c.CreateServer(t, false)
319 t.Cleanup(func() { s3Inst.Destroy(t) })
320 s2URL := s2Inst.Servers[0].URL
321 s3URL := s3Inst.Servers[0].URL
322 s2Inst.StopServer(t, s2Inst.Servers[0])
323 s3Inst.StopServer(t, s3Inst.Servers[0])
324
325 var srvrs string
326 allServers := []string{s1URL, s2URL, s3URL}
327 if runtime.GOOS == "windows" {
328 // On Windows, keep the list short to avoid long connect timeouts on
329 // dead URLs.
330 srvrs = strings.Join(allServers, ",")
331 opts = append(opts, nats.Timeout(100*time.Millisecond))
332 } else {
333 srvrs = strings.Join(allServers, ",")
334 }
335
336 for range numClients {
337 nc, err := nats.Connect(srvrs, opts...)
338 if err != nil {
339 t.Fatalf("Expected to connect, got err: %v\n", err)
340 }
341 defer nc.Close()
342 if nc.ConnectedUrl() != s1URL {
343 t.Fatalf("Connected to incorrect server: %v\n", nc.ConnectedUrl())
344 }
345 clients = append(clients, nc)
346 }
347
348 // Now bring up s2 and s3 so they can absorb clients when s1 shuts down.
349 s2Inst.StartServer(t, s2Inst.Servers[0])
350 s3Inst.StartServer(t, s3Inst.Servers[0])
351
352 s1Inst.StopServer(t, s1Inst.Servers[0])
353
354 numServers := 2
355
356 // Wait on all reconnects
357 wg.Wait()
358
359 // Walk the clients and calculate how many of each..
360 cs := make(map[string]int)
361 for _, nc := range clients {
362 cs[nc.ConnectedUrl()]++
363 nc.Close()
364 }
365 if len(cs) != numServers {
366 t.Fatalf("Wrong number of reported servers: %d vs %d\n", len(cs), numServers)
367 }
368 expected := numClients / numServers
369 v := uint(float32(expected) * 0.50)
370
371 // Check that each item is within acceptable range
372 for s, total := range cs {
373 delta := uint(math.Abs(float64(expected - total)))
374 if delta > v {
375 t.Fatalf("Connected clients to server: %s out of range: %d\n", s, total)
376 }
377 }
378 }
379
380 func TestProperReconnectDelay(t *testing.T) {
381 c := newTester(t)
382 s1Inst := c.CreateServer(t, false)
383 t.Cleanup(func() { s1Inst.Destroy(t) })
384 s1URL := s1Inst.Servers[0].URL
385
386 var srvs string
387 opts := nats.GetDefaultOptions()
388 if runtime.GOOS == "windows" {
389 srvs = strings.Join(append([]string{s1URL}, tsTestServers()[:1]...), ",")
390 } else {
391 srvs = strings.Join(append([]string{s1URL}, tsTestServers()...), ",")
392 }
393 opts.NoRandomize = true
394
395 dcbCalled := false
396 closedCbCalled := false
397 dch := make(chan bool)
398
399 dcb := func(nc *nats.Conn) {
400 // Suppress any additional calls
401 if dcbCalled {
402 return
403 }
404 dcbCalled = true
405 dch <- true
406 }
407
408 ccb := func(_ *nats.Conn) {
409 closedCbCalled = true
410 }
411
412 nc, err := nats.Connect(srvs, nats.DontRandomize(), nats.DisconnectHandler(dcb), nats.ClosedHandler(ccb))
413 if err != nil {
414 t.Fatalf("Expected to connect, got err: %v\n", err)
415 }
416 defer nc.Close()
417
418 s1Inst.StopServer(t, s1Inst.Servers[0])
419
420 // wait for disconnect
421 if e := WaitTime(dch, 2*time.Second); e != nil {
422 t.Fatal("Did not receive a disconnect callback message")
423 }
424
425 // Wait, want to make sure we don't spin on reconnect to non-existent servers.
426 time.Sleep(1 * time.Second)
427
428 // Make sure we are still reconnecting..
429 if closedCbCalled {
430 t.Fatal("Closed CB was triggered, should not have been.")
431 }
432 if status := nc.Status(); status != nats.RECONNECTING {
433 t.Fatalf("Wrong status: %d\n", status)
434 }
435 }
436
437 func TestProperFalloutAfterMaxAttempts(t *testing.T) {
438 c := newTester(t)
439 s1Inst := c.CreateServer(t, false)
440 t.Cleanup(func() { s1Inst.Destroy(t) })
441 s1URL := s1Inst.Servers[0].URL
442
443 opts := nats.GetDefaultOptions()
444 // Reduce the list of servers for Windows tests
445 if runtime.GOOS == "windows" {
446 opts.Servers = append([]string{s1URL}, tsTestServers()[:1]...)
447 opts.MaxReconnect = 2
448 opts.Timeout = 100 * time.Millisecond
449 } else {
450 opts.Servers = append([]string{s1URL}, tsTestServers()...)
451 opts.MaxReconnect = 5
452 }
453 opts.NoRandomize = true
454 opts.ReconnectWait = (25 * time.Millisecond)
455 nats.ReconnectJitter(0, 0)(&opts)
456
457 // Buffered so the testservice-managed server (which may briefly re-bind
458 // the port between reconnect cycles) cannot stall the async callback
459 // dispatcher by blocking on a second disconnect event.
460 dch := make(chan bool, 16)
461 opts.DisconnectedErrCB = func(_ *nats.Conn, _ error) {
462 select {
463 case dch <- true:
464 default:
465 }
466 }
467
468 closedCbCalled := false
469 cch := make(chan bool, 1)
470
471 opts.ClosedCB = func(_ *nats.Conn) {
472 closedCbCalled = true
473 cch <- true
474 }
475
476 nc, err := opts.Connect()
477 if err != nil {
478 t.Fatalf("Expected to connect, got err: %v\n", err)
479 }
480 defer nc.Close()
481
482 s1Inst.StopServer(t, s1Inst.Servers[0])
483
484 // On Windows, creating a TCP connection to a server not running takes more than
485 // a second. So be generous with the WaitTime.
486
487 // wait for disconnect
488 if e := WaitTime(dch, 5*time.Second); e != nil {
489 t.Fatal("Did not receive a disconnect callback message")
490 }
491
492 // Wait for ClosedCB
493 if e := WaitTime(cch, 5*time.Second); e != nil {
494 t.Fatal("Did not receive a closed callback message")
495 }
496
497 // Make sure we are not still reconnecting..
498 if !closedCbCalled {
499 t.Logf("%+v\n", nc)
500 t.Fatal("Closed CB was not triggered, should have been.")
501 }
502
503 // Expect connection to be closed...
504 if !nc.IsClosed() {
505 t.Fatalf("Wrong status: %d\n", nc.Status())
506 }
507 }
508
509 func TestProperFalloutAfterMaxAttemptsWithAuthMismatch(t *testing.T) {
510 c := newTester(t)
511 s1Inst := c.CreateServer(t, false)
512 t.Cleanup(func() { s1Inst.Destroy(t) })
513 s1URL := s1Inst.Servers[0].URL
514
515 // Second server requires TLS with client cert verification; an
516 // untrusted plain-text client connection will fail auth handshake.
517 s2Inst := c.CreateServer(t, false, managedTLSOpts(t))
518 t.Cleanup(func() { s2Inst.Destroy(t) })
519 s2URL := s2Inst.Servers[0].URL
520
521 myServers := []string{s1URL, s2URL}
522
523 opts := nats.GetDefaultOptions()
524 opts.Servers = myServers
525 opts.NoRandomize = true
526 if runtime.GOOS == "windows" {
527 opts.MaxReconnect = 2
528 opts.Timeout = 100 * time.Millisecond
529 } else {
530 opts.MaxReconnect = 5
531 }
532 opts.ReconnectWait = (25 * time.Millisecond)
533 nats.ReconnectJitter(0, 0)(&opts)
534
535 // Buffered so the testservice-managed server (which may briefly re-bind
536 // the port between reconnect cycles) cannot stall the async callback
537 // dispatcher by blocking on a second disconnect event.
538 dch := make(chan bool, 16)
539 opts.DisconnectedErrCB = func(_ *nats.Conn, _ error) {
540 select {
541 case dch <- true:
542 default:
543 }
544 }
545
546 closedCbCalled := false
547 cch := make(chan bool, 1)
548
549 opts.ClosedCB = func(_ *nats.Conn) {
550 closedCbCalled = true
551 cch <- true
552 }
553
554 nc, err := opts.Connect()
555 if err != nil {
556 t.Fatalf("Expected to connect, got err: %v\n", err)
557 }
558 defer nc.Close()
559
560 s1Inst.StopServer(t, s1Inst.Servers[0])
561
562 // On Windows, creating a TCP connection to a server not running takes more than
563 // a second. So be generous with the WaitTime.
564
565 // wait for disconnect
566 if e := WaitTime(dch, 5*time.Second); e != nil {
567 t.Fatal("Did not receive a disconnect callback message")
568 }
569
570 // Wait for ClosedCB
571 if e := WaitTime(cch, 5*time.Second); e != nil {
572 reconnects := nc.Stats().Reconnects
573 t.Fatalf("Did not receive a closed callback message, #reconnects: %v", reconnects)
574 }
575
576 // Make sure we have not exceeded the per-server MaxReconnect budget.
577 // nc.Stats().Reconnects is a global counter that increments on every
578 // successful TCP-level reconnect across the whole pool; MaxReconnect caps
579 // attempts PER SERVER. With a 2-server pool where both briefly accept TCP
580 // (StopServer has a short listener-drain window), the global count can
581 // legitimately reach len(servers)*MaxReconnect. The client is not
582 // exceeding its per-server budget; assert the true upper bound.
583 reconnects := nc.Stats().Reconnects
584 if reconnects < uint64(opts.MaxReconnect) || reconnects > uint64(len(myServers)*opts.MaxReconnect) {
585 t.Fatalf("Num reconnects was %v, expected within [%v, %v]", reconnects, opts.MaxReconnect, len(myServers)*opts.MaxReconnect)
586 }
587
588 // Make sure we are not still reconnecting..
589 if !closedCbCalled {
590 t.Logf("%+v\n", nc)
591 t.Fatal("Closed CB was not triggered, should have been.")
592 }
593
594 // Expect connection to be closed...
595 if !nc.IsClosed() {
596 t.Fatalf("Wrong status: %d\n", nc.Status())
597 }
598 }
599
600 func TestTimeoutOnNoServers(t *testing.T) {
601 c := newTester(t)
602 s1Inst := c.CreateServer(t, false)
603 t.Cleanup(func() { s1Inst.Destroy(t) })
604 s1URL := s1Inst.Servers[0].URL
605
606 opts := nats.GetDefaultOptions()
607 if runtime.GOOS == "windows" {
608 opts.Servers = append([]string{s1URL}, tsTestServers()[:1]...)
609 opts.MaxReconnect = 2
610 opts.Timeout = 100 * time.Millisecond
611 opts.ReconnectWait = (100 * time.Millisecond)
612 nats.ReconnectJitter(0, 0)(&opts)
613 } else {
614 opts.Servers = append([]string{s1URL}, tsTestServers()...)
615 // 1 second total time wait
616 opts.MaxReconnect = 10
617 opts.ReconnectWait = (100 * time.Millisecond)
618 nats.ReconnectJitter(0, 0)(&opts)
619 }
620 opts.NoRandomize = true
621
622 dch := make(chan bool)
623 opts.DisconnectedErrCB = func(nc *nats.Conn, _ error) {
624 // Suppress any additional calls
625 nc.SetDisconnectErrHandler(nil)
626 dch <- true
627 }
628
629 cch := make(chan bool)
630 opts.ClosedCB = func(_ *nats.Conn) {
631 cch <- true
632 }
633
634 nc, err := opts.Connect()
635 if err != nil {
636 t.Fatalf("Expected to connect, got err: %v\n", err)
637 }
638 defer nc.Close()
639
640 s1Inst.StopServer(t, s1Inst.Servers[0])
641
642 // On Windows, creating a connection to a non-running server takes
643 // more than a second. So be generous with WaitTime
644
645 // wait for disconnect
646 if e := WaitTime(dch, 5*time.Second); e != nil {
647 t.Fatal("Did not receive a disconnect callback message")
648 }
649
650 startWait := time.Now()
651
652 // Wait for ClosedCB
653 if e := WaitTime(cch, 5*time.Second); e != nil {
654 t.Fatal("Did not receive a closed callback message")
655 }
656
657 if runtime.GOOS != "windows" {
658 timeWait := time.Since(startWait)
659
660 // Use 500ms as variable time delta
661 variable := (500 * time.Millisecond)
662 expected := (time.Duration(opts.MaxReconnect) * opts.ReconnectWait)
663
664 if timeWait > (expected + variable) {
665 t.Fatalf("Waited too long for Closed state: %d\n", timeWait/time.Millisecond)
666 }
667 }
668 }
669
670 func TestPingReconnect(t *testing.T) {
671 RECONNECTS := 4
672 c := newTester(t)
673 s1Inst := c.CreateServer(t, false)
674 t.Cleanup(func() { s1Inst.Destroy(t) })
675 s1URL := s1Inst.Servers[0].URL
676
677 opts := nats.GetDefaultOptions()
678 opts.Servers = append([]string{s1URL}, tsTestServers()...)
679 opts.NoRandomize = true
680 opts.Timeout = 100 * time.Millisecond
681 opts.ReconnectWait = 200 * time.Millisecond
682 nats.ReconnectJitter(0, 0)(&opts)
683 opts.PingInterval = 50 * time.Millisecond
684 opts.MaxPingsOut = -1
685
686 var wg sync.WaitGroup
687 wg.Add(1)
688 rch := make(chan time.Time, RECONNECTS)
689 dch := make(chan time.Time, RECONNECTS)
690
691 opts.DisconnectedErrCB = func(_ *nats.Conn, _ error) {
692 d := dch
693 select {
694 case d <- time.Now():
695 default:
696 d = nil
697 }
698 }
699
700 opts.ReconnectedCB = func(c *nats.Conn) {
701 r := rch
702 select {
703 case r <- time.Now():
704 default:
705 r = nil
706 wg.Done()
707 }
708 }
709
710 nc, err := opts.Connect()
711 if err != nil {
712 t.Fatalf("Expected to connect, got err: %v\n", err)
713 }
714 defer nc.Close()
715
716 wg.Wait()
717 s1Inst.StopServer(t, s1Inst.Servers[0])
718
719 <-dch
720 for range RECONNECTS - 1 {
721 disconnectedAt := <-dch
722 reconnectAt := <-rch
723 pingCycle := disconnectedAt.Sub(reconnectAt)
724 if pingCycle > 2*opts.PingInterval {
725 t.Fatalf("Reconnect due to ping took %s", pingCycle.String())
726 }
727 }
728 }
729
730 type checkPoolUpdatedDialer struct {
731 conn net.Conn
732 first, final bool
733 ra int
734 }
735
736 func (d *checkPoolUpdatedDialer) Dial(network, address string) (net.Conn, error) {
737 doReal := false
738 if d.first {
739 d.first = false
740 doReal = true
741 } else if d.final {
742 d.ra++
743 return nil, errors.New("On purpose")
744 } else {
745 d.ra++
746 if d.ra == 15 {
747 d.ra = 0
748 doReal = true
749 }
750 }
751 if doReal {
752 c, err := net.Dial(network, address)
753 if err != nil {
754 return nil, err
755 }
756 d.conn = c
757 return c, nil
758 }
759 return nil, errors.New("On purpose")
760 }
761
762 func TestServerPoolUpdatedWhenRouteGoesAway(t *testing.T) {
763 c := newTester(t)
764 // Build a 3-node cluster so client-server URL gossip is exercised.
765 // The tester's NATS_ADVERTISE env var makes each node gossip a host:port
766 // the client can dial (localhost in host mode, the service name in CI),
767 // so the gossiped pool URLs match the inst.Servers[i].URL values below.
768 clusterInst := c.CreateCluster(t, 3, false)
769 t.Cleanup(func() { clusterInst.Destroy(t) })
770
771 s1 := clusterInst.Servers[0]
772 s2 := clusterInst.Servers[1]
773 s3 := clusterInst.Servers[2]
774
775 s1Url := s1.URL
776 s2Url := s2.URL
777 s3Url := s3.URL
778
779 // Stop s2 and s3 initially so the client sees them only once they are
780 // brought up, after the initial connect to s1.
781 clusterInst.StopServer(t, s2)
782 clusterInst.StopServer(t, s3)
783
784 ch := make(chan bool, 1)
785 chch := make(chan bool, 1)
786 connHandler := func(_ *nats.Conn) {
787 chch <- true
788 }
789 // SkipHostLookup keeps srvPool entries 1:1 with the bootstrap URL and the
790 // gossiped connect_urls. Without it, nats.go's parseServerURL does
791 // net.LookupHost on any non-IP host (the bootstrap "nats://nats:port" and
792 // every gossiped hostname URL) and adds every resolved IP as a separate
793 // pool entry alongside the hostname — inflating the pool with bridge-IP
794 // duplicates in CI's docker bridge mode and on dual-stack hosts that
795 // expand "localhost" to both 127.0.0.1 and ::1.
796 nc, err := nats.Connect(s1Url,
797 nats.SkipHostLookup(),
798 nats.ReconnectHandler(connHandler),
799 nats.DiscoveredServersHandler(func(_ *nats.Conn) {
800 ch <- true
801 }))
802 if err != nil {
803 t.Fatalf("Error on connect")
804 }
805
806 clusterInst.StartServer(t, s2)
807
808 // Wait to be notified
809 if err := Wait(ch); err != nil {
810 t.Fatal("New server callback was not invoked")
811 }
812
813 checkPool := func(expected []string) {
814 // Don't use discovered here, but Servers to have the full list.
815 // Also, there may be cases where the mesh is not formed yet,
816 // so try again on failure.
817 var (
818 ds []string
819 timeout = time.Now().Add(5 * time.Second)
820 )
821 for time.Now().Before(timeout) {
822 ds = nc.Servers()
823 if len(ds) == len(expected) {
824 m := make(map[string]struct{}, len(ds))
825 for _, url := range ds {
826 m[url] = struct{}{}
827 }
828 ok := true
829 for _, url := range expected {
830 if _, present := m[url]; !present {
831 ok = false
832 break
833 }
834 }
835 if ok {
836 return
837 }
838 }
839 time.Sleep(50 * time.Millisecond)
840 }
841 stackFatalf(t, "Expected %v, got %v", expected, ds)
842 }
843 // Verify that we now know about s2
844 checkPool([]string{s1Url, s2Url})
845
846 clusterInst.StartServer(t, s3)
847
848 // Wait to be notified
849 if err := Wait(ch); err != nil {
850 t.Fatal("New server callback was not invoked")
851 }
852 // Verify that we now know about s3
853 checkPool([]string{s1Url, s2Url, s3Url})
854
855 // Stop s1. Since this was passed to the Connect() call, this one should
856 // still be present.
857 clusterInst.StopServer(t, s1)
858 // Wait for reconnect
859 if err := Wait(chch); err != nil {
860 t.Fatal("Reconnect handler not invoked")
861 }
862 checkPool([]string{s1Url, s2Url, s3Url})
863
864 // Check the server we reconnected to.
865 reConnectedTo := nc.ConnectedUrl()
866 expected := []string{s1Url}
867 restartS2 := false
868 if reConnectedTo == s2Url {
869 restartS2 = true
870 clusterInst.StopServer(t, s2)
871 expected = append(expected, s3Url)
872 } else if reConnectedTo == s3Url {
873 clusterInst.StopServer(t, s3)
874 expected = append(expected, s2Url)
875 } else {
876 t.Fatalf("Unexpected server client has reconnected to: %v", reConnectedTo)
877 }
878 // Wait for reconnect
879 if err := Wait(chch); err != nil {
880 t.Fatal("Reconnect handler not invoked")
881 }
882 // The implicit server that we just shutdown should have been removed from the pool
883 checkPool(expected)
884
885 // Restart the one that was shutdown and check that it is now back in the pool
886 if restartS2 {
887 clusterInst.StartServer(t, s2)
888 expected = append(expected, s2Url)
889 } else {
890 clusterInst.StartServer(t, s3)
891 expected = append(expected, s3Url)
892 }
893 // Since this is not a "new" server, the DiscoveredServersCB won't be invoked.
894 checkPool(expected)
895
896 nc.Close()
897
898 // Restart s1
899 clusterInst.StartServer(t, s1)
900
901 // We should have all 3 servers running now...
902
903 // Create a client connection with special dialer.
904 //
905 // SkipHostLookup() keeps the srvPool entries 1:1 with the gossiped URLs.
906 // Without it, hostnames like "localhost" are expanded by net.LookupHost
907 // to both 127.0.0.1 and ::1 — every gossiped URL doubles, and the
908 // reconnect-count assertion below loses its alignment with the pool size.
909 d := &checkPoolUpdatedDialer{first: true}
910 nc, err = nats.Connect(s1Url,
911 nats.MaxReconnects(10),
912 nats.ReconnectWait(15*time.Millisecond),
913 nats.ReconnectJitter(0, 0),
914 nats.SkipHostLookup(),
915 nats.SetCustomDialer(d),
916 nats.ReconnectHandler(connHandler),
917 nats.ClosedHandler(connHandler))
918 if err != nil {
919 t.Fatalf("Error on connect")
920 }
921 defer nc.Close()
922
923 // Make sure that we have all 3 servers in the pool (this will wait if required)
924 checkPool(expected)
925
926 // Cause disconnection between client and server. We are going to reconnect
927 // and we want to check that when we get the INFO again with the list of
928 // servers, we don't lose the knowledge of how many times we tried to
929 // reconnect.
930 d.conn.Close()
931
932 // Wait for client to reconnect to a server
933 if err := Wait(chch); err != nil {
934 t.Fatal("Reconnect handler not invoked")
935 }
936 // At this point, we should have tried to reconnect 5 times to each server.
937 // For the one we reconnected to, its max reconnect attempts should have been
938 // cleared, not for the other ones.
939
940 // Cause a disconnect again and ensure we won't reconnect.
941 d.final = true
942 d.conn.Close()
943
944 // Wait for Close callback to be invoked.
945 if err := Wait(chch); err != nil {
946 t.Fatal("Close handler not invoked")
947 }
948
949 // Since MaxReconnect is 10, after trying 5 more times on 2 of the servers,
950 // these should have been removed. We have still 5 more tries for the server
951 // we did previously reconnect to.
952 // So total of reconnect attempt should be: 2*5+1*10=20
953 if d.ra != 20 {
954 t.Fatalf("Should have tried to reconnect 20 more times, got %v", d.ra)
955 }
956
957 nc.Close()
958 }
959
960 func TestIgnoreDiscoveredServers(t *testing.T) {
961 c := newTester(t)
962 // CreateCluster brings both servers up connected via routes; stop the
963 // second immediately so each subtest can start it after the client
964 // connects.
965 clusterInst := c.CreateCluster(t, 2, false)
966 t.Cleanup(func() { clusterInst.Destroy(t) })
967
968 s1 := clusterInst.Servers[0]
969 s2 := clusterInst.Servers[1]
970 s1URL := s1.URL
971
972 // Wait for the pool size on nc to reach expected, polling.
973 checkPoolSize := func(nc *nats.Conn, expected int) {
974 t.Helper()
975 timeout := time.Now().Add(5 * time.Second)
976 for time.Now().Before(timeout) {
977 if len(nc.Servers()) == expected {
978 return
979 }
980 time.Sleep(50 * time.Millisecond)
981 }
982 t.Fatalf("Expected %d server(s), got %d: %v", expected, len(nc.Servers()), nc.Servers())
983 }
984
985 t.Run("add new servers to pool", func(t *testing.T) {
986 // Ensure starting state: s2 is down so the client sees a 1-server pool.
987 clusterInst.StopServer(t, s2)
988
989 nc, err := nats.Connect(s1URL)
990 if err != nil {
991 t.Fatalf("Error on connect: %v", err)
992 }
993 defer nc.Close()
994
995 clusterInst.StartServer(t, s2)
996
997 checkPoolSize(nc, 2)
998 if len(nc.DiscoveredServers()) != 1 {
999 t.Fatalf("Expected 1 discovered server, got %v", nc.DiscoveredServers())
1000 }
1001 })
1002
1003 t.Run("ignore new servers", func(t *testing.T) {
1004 // Reset to s2-down baseline before the subtest.
1005 clusterInst.StopServer(t, s2)
1006 time.Sleep(200 * time.Millisecond)
1007
1008 nc, err := nats.Connect(s1URL,
1009 nats.IgnoreDiscoveredServers(),
1010 )
1011 if err != nil {
1012 t.Fatalf("Error on connect: %v", err)
1013 }
1014 defer nc.Close()
1015
1016 // Control connection to the same server, without the option under
1017 // test. Waiting for its pool to grow proves the gossip was actually
1018 // delivered; without that the negative assertion below races an
1019 // arbitrary sleep and passes vacuously on a slow box.
1020 control, err := nats.Connect(s1URL)
1021 if err != nil {
1022 t.Fatalf("Error on connect: %v", err)
1023 }
1024 defer control.Close()
1025
1026 clusterInst.StartServer(t, s2)
1027
1028 checkPoolSize(control, 2)
1029 // The server writes the async INFO before answering this connection's
1030 // PING, so once the flush returns nc has necessarily read it too.
1031 nc.Flush()
1032
1033 if len(nc.Servers()) != 1 {
1034 t.Fatalf("Expected 1 server, got %d: %v", len(nc.Servers()), nc.Servers())
1035 }
1036 if len(nc.DiscoveredServers()) != 0 {
1037 t.Fatalf("Expected no discovered servers, got %v", nc.DiscoveredServers())
1038 }
1039 })
1040 }