Debian Codegraph @

server/gateway_test.go

raw
1 // Copyright 2018-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "bufio"
18 "bytes"
19 "context"
20 "crypto/tls"
21 "encoding/json"
22 "fmt"
23 "net"
24 "net/url"
25 "os"
26 "runtime"
27 "strconv"
28 "strings"
29 "sync"
30 "sync/atomic"
31 "testing"
32 "time"
33
34 "github.com/nats-io/nats-server/v2/logger"
35 "github.com/nats-io/nats.go"
36 "github.com/nats-io/nkeys"
37 "golang.org/x/crypto/ocsp"
38
39 . "github.com/nats-io/nats-server/v2/internal/ocsp"
40 )
41
42 func init() {
43 gatewayConnectDelay = 15 * time.Millisecond
44 gatewayConnectMaxDelay = 15 * time.Millisecond
45 gatewayReconnectDelay = 15 * time.Millisecond
46 }
47
48 // Wait for the expected number of outbound gateways, or fails.
49 func waitForOutboundGateways(t *testing.T, s *Server, expected int, timeout time.Duration) {
50 t.Helper()
51 if timeout < 2*time.Second {
52 timeout = 2 * time.Second
53 }
54 checkFor(t, timeout, 15*time.Millisecond, func() error {
55 if n := s.numOutboundGateways(); n != expected {
56 return fmt.Errorf("Expected %v outbound gateway(s), got %v", expected, n)
57 }
58 return nil
59 })
60 }
61
62 // Wait for the expected number of inbound gateways, or fails.
63 func waitForInboundGateways(t *testing.T, s *Server, expected int, timeout time.Duration) {
64 t.Helper()
65 if timeout < 2*time.Second {
66 timeout = 2 * time.Second
67 }
68 checkFor(t, timeout, 15*time.Millisecond, func() error {
69 if n := s.numInboundGateways(); n != expected {
70 return fmt.Errorf("Expected %v inbound gateway(s), got %v", expected, n)
71 }
72 return nil
73 })
74 }
75
76 func waitForGatewayFailedConnect(t *testing.T, s *Server, gwName string, expectFailure bool, timeout time.Duration) {
77 t.Helper()
78 checkFor(t, timeout, 15*time.Millisecond, func() error {
79 var c int
80 cfg := s.getRemoteGateway(gwName)
81 if cfg != nil {
82 c = cfg.getConnAttempts()
83 }
84 if expectFailure && c <= 1 {
85 return fmt.Errorf("Expected several attempts to connect, got %v", c)
86 } else if !expectFailure && c > 1 {
87 return fmt.Errorf("Expected single attempt to connect, got %v", c)
88 }
89 return nil
90 })
91 }
92
93 func checkForRegisteredQSubInterest(t *testing.T, s *Server, gwName, acc, subj string, expected int, timeout time.Duration) {
94 t.Helper()
95 checkFor(t, timeout, 15*time.Millisecond, func() error {
96 count := 0
97 c := s.getOutboundGatewayConnection(gwName)
98 ei, _ := c.gw.outsim.Load(acc)
99 if ei != nil {
100 sl := ei.(*outsie).sl
101 r := sl.Match(subj)
102 for _, qsubs := range r.qsubs {
103 count += len(qsubs)
104 }
105 }
106 if count == expected {
107 return nil
108 }
109 return fmt.Errorf("Expected %v qsubs in sublist, got %v", expected, count)
110 })
111 }
112
113 func checkForSubjectNoInterest(t *testing.T, c *client, account, subject string, expectNoInterest bool, timeout time.Duration) {
114 t.Helper()
115 checkFor(t, timeout, 15*time.Millisecond, func() error {
116 ei, _ := c.gw.outsim.Load(account)
117 if ei == nil {
118 return fmt.Errorf("Did not receive subject no-interest")
119 }
120 e := ei.(*outsie)
121 e.RLock()
122 _, inMap := e.ni[subject]
123 e.RUnlock()
124 if expectNoInterest {
125 if inMap {
126 return nil
127 }
128 return fmt.Errorf("Did not receive subject no-interest on %q", subject)
129 }
130 if inMap {
131 return fmt.Errorf("No-interest on subject %q was not cleared", subject)
132 }
133 return nil
134 })
135 }
136
137 func checkForAccountNoInterest(t *testing.T, c *client, account string, expectedNoInterest bool, timeout time.Duration) {
138 t.Helper()
139 checkFor(t, timeout, 15*time.Millisecond, func() error {
140 ei, ok := c.gw.outsim.Load(account)
141 if !ok && expectedNoInterest {
142 return fmt.Errorf("No-interest for account %q not yet registered", account)
143 } else if ok && !expectedNoInterest {
144 return fmt.Errorf("Account %q should not have a no-interest", account)
145 }
146 if ei != nil {
147 return fmt.Errorf("Account %q should have a global no-interest, not subject no-interest", account)
148 }
149 return nil
150 })
151 }
152
153 func checkGWInterestOnlyMode(t *testing.T, s *Server, outboundGWName, accName string) {
154 t.Helper()
155 checkGWInterestOnlyModeOrNotPresent(t, s, outboundGWName, accName, false)
156 }
157
158 func checkGWInterestOnlyModeOrNotPresent(t *testing.T, s *Server, outboundGWName, accName string, notPresentOk bool) {
159 t.Helper()
160 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
161 gwc := s.getOutboundGatewayConnection(outboundGWName)
162 if gwc == nil {
163 return fmt.Errorf("No outbound gateway connection %q for server %v", outboundGWName, s)
164 }
165 gwc.mu.Lock()
166 defer gwc.mu.Unlock()
167 out, ok := gwc.gw.outsim.Load(accName)
168 if !ok {
169 if notPresentOk {
170 return nil
171 } else {
172 return fmt.Errorf("Server %v - outbound gateway connection %q: no account %q found in map",
173 s, outboundGWName, accName)
174 }
175 }
176 if out == nil {
177 return fmt.Errorf("Server %v - outbound gateway connection %q: interest map not found for account %q",
178 s, outboundGWName, accName)
179 }
180 e := out.(*outsie)
181 e.RLock()
182 defer e.RUnlock()
183 if e.mode != InterestOnly {
184 return fmt.Errorf(
185 "Server %v - outbound gateway connection %q: account %q mode shoule be InterestOnly but is %v",
186 s, outboundGWName, accName, e.mode)
187 }
188 return nil
189 })
190 }
191
192 func checkGWInterestOnlyModeInterestOn(t *testing.T, s *Server, outboundGWName, accName, subject string) {
193 t.Helper()
194 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
195 c := s.getOutboundGatewayConnection(outboundGWName)
196 outsiei, _ := c.gw.outsim.Load(accName)
197 if outsiei == nil {
198 return fmt.Errorf("Server %s - outbound gateway connection %q: no map entry found for account %q",
199 s, outboundGWName, accName)
200 }
201 outsie := outsiei.(*outsie)
202 r := outsie.sl.Match(subject)
203 if len(r.psubs) == 0 {
204 return fmt.Errorf("Server %s - outbound gateway connection %q - account %q: no subject interest for %q",
205 s, outboundGWName, accName, subject)
206 }
207 return nil
208 })
209 }
210
211 func waitCh(t *testing.T, ch chan bool, errTxt string) {
212 t.Helper()
213 select {
214 case <-ch:
215 return
216 case <-time.After(5 * time.Second):
217 t.Fatal(errTxt)
218 }
219 }
220
221 var noOpErrHandler = func(_ *nats.Conn, _ *nats.Subscription, _ error) {}
222
223 func natsConnect(t testing.TB, url string, options ...nats.Option) *nats.Conn {
224 t.Helper()
225 opts := nats.GetDefaultOptions()
226 for _, opt := range options {
227 if err := opt(&opts); err != nil {
228 t.Fatalf("Error applying client option: %v", err)
229 }
230 }
231 nc, err := nats.Connect(url, options...)
232 if err != nil {
233 t.Fatalf("Error on connect: %v", err)
234 }
235 if opts.AsyncErrorCB == nil {
236 // Set this up to not pollute the logs when running tests.
237 nc.SetErrorHandler(noOpErrHandler)
238 }
239
240 return nc
241 }
242
243 func natsSub(t *testing.T, nc *nats.Conn, subj string, cb nats.MsgHandler) *nats.Subscription {
244 t.Helper()
245 sub, err := nc.Subscribe(subj, cb)
246 if err != nil {
247 t.Fatalf("Error on subscribe: %v", err)
248 }
249 return sub
250 }
251
252 func natsSubSync(t *testing.T, nc *nats.Conn, subj string) *nats.Subscription {
253 t.Helper()
254 sub, err := nc.SubscribeSync(subj)
255 if err != nil {
256 t.Fatalf("Error on subscribe: %v", err)
257 }
258 return sub
259 }
260
261 func natsNexMsg(t *testing.T, sub *nats.Subscription, timeout time.Duration) *nats.Msg {
262 t.Helper()
263 msg, err := sub.NextMsg(timeout)
264 if err != nil {
265 t.Fatalf("Failed getting next message: %v", err)
266 }
267 return msg
268 }
269
270 func natsQueueSub(t *testing.T, nc *nats.Conn, subj, queue string, cb nats.MsgHandler) *nats.Subscription {
271 t.Helper()
272 sub, err := nc.QueueSubscribe(subj, queue, cb)
273 if err != nil {
274 t.Fatalf("Error on subscribe: %v", err)
275 }
276 return sub
277 }
278
279 func natsQueueSubSync(t *testing.T, nc *nats.Conn, subj, queue string) *nats.Subscription {
280 t.Helper()
281 sub, err := nc.QueueSubscribeSync(subj, queue)
282 if err != nil {
283 t.Fatalf("Error on subscribe: %v", err)
284 }
285 return sub
286 }
287
288 func natsFlush(t *testing.T, nc *nats.Conn) {
289 t.Helper()
290 if err := nc.Flush(); err != nil {
291 t.Fatalf("Error on flush: %v", err)
292 }
293 }
294
295 func natsPub(t testing.TB, nc *nats.Conn, subj string, payload []byte) {
296 t.Helper()
297 if err := nc.Publish(subj, payload); err != nil {
298 t.Fatalf("Error on publish: %v", err)
299 }
300 }
301
302 func natsPubReq(t *testing.T, nc *nats.Conn, subj, reply string, payload []byte) {
303 t.Helper()
304 if err := nc.PublishRequest(subj, reply, payload); err != nil {
305 t.Fatalf("Error on publish: %v", err)
306 }
307 }
308
309 func natsUnsub(t *testing.T, sub *nats.Subscription) {
310 t.Helper()
311 if err := sub.Unsubscribe(); err != nil {
312 t.Fatalf("Error on unsubscribe: %v", err)
313 }
314 }
315
316 func testDefaultOptionsForGateway(name string) *Options {
317 o := DefaultOptions()
318 o.NoSystemAccount = true
319 o.Cluster.Name = name
320 o.Gateway.Name = name
321 o.Gateway.Host = "127.0.0.1"
322 o.Gateway.Port = -1
323 o.gatewaysSolicitDelay = 15 * time.Millisecond
324 return o
325 }
326
327 func runGatewayServer(o *Options) *Server {
328 s := RunServer(o)
329 s.SetLogger(&DummyLogger{}, true, true)
330 return s
331 }
332
333 func testGatewayOptionsFromToWithServers(t *testing.T, org, dst string, servers ...*Server) *Options {
334 t.Helper()
335 o := testDefaultOptionsForGateway(org)
336 gw := &RemoteGatewayOpts{Name: dst}
337 for _, s := range servers {
338 us := fmt.Sprintf("nats://127.0.0.1:%d", s.GatewayAddr().Port)
339 u, err := url.Parse(us)
340 if err != nil {
341 t.Fatalf("Error parsing url: %v", err)
342 }
343 gw.URLs = append(gw.URLs, u)
344 }
345 o.Gateway.Gateways = append(o.Gateway.Gateways, gw)
346 return o
347 }
348
349 func testAddGatewayURLs(t *testing.T, o *Options, dst string, urls []string) {
350 t.Helper()
351 gw := &RemoteGatewayOpts{Name: dst}
352 for _, us := range urls {
353 u, err := url.Parse(us)
354 if err != nil {
355 t.Fatalf("Error parsing url: %v", err)
356 }
357 gw.URLs = append(gw.URLs, u)
358 }
359 o.Gateway.Gateways = append(o.Gateway.Gateways, gw)
360 }
361
362 func testGatewayOptionsFromToWithURLs(t *testing.T, org, dst string, urls []string) *Options {
363 o := testDefaultOptionsForGateway(org)
364 testAddGatewayURLs(t, o, dst, urls)
365 return o
366 }
367
368 func testGatewayOptionsWithTLS(t *testing.T, name string) *Options {
369 t.Helper()
370 o := testDefaultOptionsForGateway(name)
371 var (
372 tc = &TLSConfigOpts{}
373 err error
374 )
375 if name == "A" {
376 tc.CertFile = "../test/configs/certs/srva-cert.pem"
377 tc.KeyFile = "../test/configs/certs/srva-key.pem"
378 } else {
379 tc.CertFile = "../test/configs/certs/srvb-cert.pem"
380 tc.KeyFile = "../test/configs/certs/srvb-key.pem"
381 }
382 tc.CaFile = "../test/configs/certs/ca.pem"
383 o.Gateway.TLSConfig, err = GenTLSConfig(tc)
384 if err != nil {
385 t.Fatalf("Error generating TLS config: %v", err)
386 }
387 o.Gateway.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
388 o.Gateway.TLSConfig.RootCAs = o.Gateway.TLSConfig.ClientCAs
389 o.Gateway.TLSTimeout = 2.0
390 return o
391 }
392
393 func testGatewayOptionsFromToWithTLS(t *testing.T, org, dst string, urls []string) *Options {
394 o := testGatewayOptionsWithTLS(t, org)
395 testAddGatewayURLs(t, o, dst, urls)
396 return o
397 }
398
399 func TestGatewayBasic(t *testing.T) {
400 o2 := testDefaultOptionsForGateway("B")
401 o2.Gateway.ConnectRetries = 0
402 s2 := runGatewayServer(o2)
403 defer s2.Shutdown()
404
405 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
406 s1 := runGatewayServer(o1)
407 defer s1.Shutdown()
408
409 // s1 should have an outbound gateway to s2.
410 waitForOutboundGateways(t, s1, 1, time.Second)
411 // s2 should have an inbound gateway
412 waitForInboundGateways(t, s2, 1, time.Second)
413 // and an outbound too
414 waitForOutboundGateways(t, s2, 1, time.Second)
415
416 // Stop s2 server
417 s2.Shutdown()
418
419 // gateway should go away
420 waitForOutboundGateways(t, s1, 0, time.Second)
421 waitForInboundGateways(t, s1, 0, time.Second)
422
423 // Restart server
424 s2 = runGatewayServer(o2)
425 defer s2.Shutdown()
426
427 // gateway should reconnect
428 waitForOutboundGateways(t, s1, 1, 2*time.Second)
429 waitForOutboundGateways(t, s2, 1, 2*time.Second)
430 waitForInboundGateways(t, s1, 1, 2*time.Second)
431 waitForInboundGateways(t, s2, 1, 2*time.Second)
432
433 // Shutdown s1, remove the gateway from A to B and restart.
434 s1.Shutdown()
435 // When s2 detects the connection is closed, it will attempt
436 // to reconnect once (even if the route is implicit).
437 // We need to wait more than a dial timeout to make sure
438 // s1 does not restart too quickly and s2 can actually reconnect.
439 time.Sleep(DEFAULT_ROUTE_DIAL + 250*time.Millisecond)
440 // Restart s1 without gateway to B.
441 o1.Gateway.Gateways = nil
442 s1 = runGatewayServer(o1)
443 defer s1.Shutdown()
444
445 // s1 should not have any outbound nor inbound
446 waitForOutboundGateways(t, s1, 0, 2*time.Second)
447 waitForInboundGateways(t, s1, 0, 2*time.Second)
448
449 // Same for s2
450 waitForOutboundGateways(t, s2, 0, 2*time.Second)
451 waitForInboundGateways(t, s2, 0, 2*time.Second)
452
453 // Verify that s2 no longer has A gateway in its list
454 checkFor(t, time.Second, 15*time.Millisecond, func() error {
455 if s2.getRemoteGateway("A") != nil {
456 return fmt.Errorf("Gateway A should have been removed from s2")
457 }
458 return nil
459 })
460 }
461
462 func TestGatewayIgnoreSelfReference(t *testing.T) {
463 o := testDefaultOptionsForGateway("A")
464 // To create a reference to itself before running the server
465 // it means that we have to assign an explicit port
466 o.Gateway.Port = 5222
467 o.gatewaysSolicitDelay = 0
468 u, _ := url.Parse(fmt.Sprintf("nats://%s:%d", o.Gateway.Host, o.Gateway.Port))
469 cfg := &RemoteGatewayOpts{
470 Name: "A",
471 URLs: []*url.URL{u},
472 }
473 o.Gateway.Gateways = append(o.Gateway.Gateways, cfg)
474 o.NoSystemAccount = true
475 s := runGatewayServer(o)
476 defer s.Shutdown()
477
478 // Wait a bit to make sure that there is no attempt to connect.
479 time.Sleep(20 * time.Millisecond)
480
481 // No outbound connection expected, and no attempt to connect.
482 if s.getRemoteGateway("A") != nil {
483 t.Fatalf("Should not have a remote gateway config for A")
484 }
485 if s.getOutboundGatewayConnection("A") != nil {
486 t.Fatalf("Should not have a gateway connection to A")
487 }
488 s.Shutdown()
489
490 // Now try with config files and include
491 s1, _ := RunServerWithConfig("configs/gwa.conf")
492 defer s1.Shutdown()
493
494 s2, _ := RunServerWithConfig("configs/gwb.conf")
495 defer s2.Shutdown()
496
497 waitForOutboundGateways(t, s1, 1, 2*time.Second)
498 waitForOutboundGateways(t, s2, 1, 2*time.Second)
499 waitForInboundGateways(t, s1, 1, 2*time.Second)
500 waitForInboundGateways(t, s2, 1, 2*time.Second)
501
502 if s1.getRemoteGateway("A") != nil {
503 t.Fatalf("Should not have a remote gateway config for A")
504 }
505 if s1.getOutboundGatewayConnection("A") != nil {
506 t.Fatalf("Should not have a gateway connection to A")
507 }
508 if s2.getRemoteGateway("B") != nil {
509 t.Fatalf("Should not have a remote gateway config for B")
510 }
511 if s2.getOutboundGatewayConnection("B") != nil {
512 t.Fatalf("Should not have a gateway connection to B")
513 }
514 }
515
516 func TestGatewayHeaderInfo(t *testing.T) {
517 o := testDefaultOptionsForGateway("A")
518 s := runGatewayServer(o)
519 defer s.Shutdown()
520
521 gwconn, err := net.Dial("tcp", net.JoinHostPort(o.Gateway.Host, fmt.Sprintf("%d", o.Gateway.Port)))
522 if err != nil {
523 t.Fatalf("Error dialing server: %v\n", err)
524 }
525 defer gwconn.Close()
526 client := bufio.NewReaderSize(gwconn, maxBufSize)
527 l, err := client.ReadString('\n')
528 if err != nil {
529 t.Fatalf("Error receiving info from server: %v\n", err)
530 }
531 var info serverInfo
532 if err = json.Unmarshal([]byte(l[5:]), &info); err != nil {
533 t.Fatalf("Could not parse INFO json: %v\n", err)
534 }
535 if !info.Headers {
536 t.Fatalf("Expected by default for header support to be enabled")
537 }
538
539 s.Shutdown()
540 gwconn.Close()
541
542 // Now turn headers off.
543 o.NoHeaderSupport = true
544 s = runGatewayServer(o)
545 defer s.Shutdown()
546
547 gwconn, err = net.Dial("tcp", net.JoinHostPort(o.Gateway.Host, fmt.Sprintf("%d", o.Gateway.Port)))
548 if err != nil {
549 t.Fatalf("Error dialing server: %v\n", err)
550 }
551 defer gwconn.Close()
552 client = bufio.NewReaderSize(gwconn, maxBufSize)
553 l, err = client.ReadString('\n')
554 if err != nil {
555 t.Fatalf("Error receiving info from server: %v\n", err)
556 }
557 if err = json.Unmarshal([]byte(l[5:]), &info); err != nil {
558 t.Fatalf("Could not parse INFO json: %v\n", err)
559 }
560 if info.Headers {
561 t.Fatalf("Expected header support to be disabled")
562 }
563 }
564
565 func TestGatewayRejectsInfoBeforeConnect(t *testing.T) {
566 o := testDefaultOptionsForGateway("A")
567 s := runGatewayServer(o)
568 defer s.Shutdown()
569
570 gwconn, err := net.Dial("tcp", net.JoinHostPort(o.Gateway.Host, strconv.Itoa(o.Gateway.Port)))
571 if err != nil {
572 t.Fatalf("Error dialing server: %v", err)
573 }
574 defer gwconn.Close()
575
576 client := bufio.NewReaderSize(gwconn, maxBufSize)
577 if _, err := client.ReadString('\n'); err != nil {
578 t.Fatalf("Error receiving initial INFO from server: %v", err)
579 }
580
581 if _, err := fmt.Fprint(gwconn, "INFO {}\r\n"); err != nil {
582 t.Fatalf("Error sending gateway INFO: %v", err)
583 }
584
585 if err := gwconn.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
586 t.Fatalf("Error setting read deadline: %v", err)
587 }
588 l, err := client.ReadString('\n')
589 if err != nil {
590 t.Fatalf("Expected authorization failure, got read error: %v", err)
591 }
592 if !strings.Contains(l, "Authorization Violation") {
593 t.Fatalf("Expected authorization violation, got %q", l)
594 }
595 }
596
597 func TestGatewayHeaderSupport(t *testing.T) {
598 o2 := testDefaultOptionsForGateway("B")
599 o2.Gateway.ConnectRetries = 0
600 s2 := runGatewayServer(o2)
601 defer s2.Shutdown()
602
603 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
604 s1 := runGatewayServer(o1)
605 defer s1.Shutdown()
606
607 // s1 should have an outbound gateway to s2.
608 waitForOutboundGateways(t, s1, 1, time.Second)
609 // and an inbound too
610 waitForInboundGateways(t, s1, 1, time.Second)
611 // s2 should have an inbound gateway
612 waitForInboundGateways(t, s2, 1, time.Second)
613 // and an outbound too
614 waitForOutboundGateways(t, s2, 1, time.Second)
615
616 c, cr, _ := newClientForServer(s1)
617 defer c.close()
618
619 connect := "CONNECT {\"headers\":true}"
620 subOp := "SUB foo 1"
621 pingOp := "PING\r\n"
622 cmd := strings.Join([]string{connect, subOp, pingOp}, "\r\n")
623 c.parseAsync(cmd)
624 if _, err := cr.ReadString('\n'); err != nil {
625 t.Fatalf("Error receiving msg from server: %v\n", err)
626 }
627
628 // Wait for interest to be registered on s2
629 checkGWInterestOnlyModeInterestOn(t, s2, "A", globalAccountName, "foo")
630
631 b, _, _ := newClientForServer(s2)
632 defer b.close()
633
634 pubOp := "HPUB foo 12 14\r\nName:Derek\r\nOK\r\n"
635 cmd = strings.Join([]string{connect, pubOp}, "\r\n")
636 b.parseAsync(cmd)
637
638 l, err := cr.ReadString('\n')
639 if err != nil {
640 t.Fatalf("Error receiving msg from server: %v\n", err)
641 }
642
643 am := hmsgPat.FindAllStringSubmatch(l, -1)
644 if len(am) == 0 {
645 t.Fatalf("Did not get a match for %q", l)
646 }
647 matches := am[0]
648 if len(matches) != 7 {
649 t.Fatalf("Did not get correct # matches: %d vs %d\n", len(matches), 7)
650 }
651 if matches[SUB_INDEX] != "foo" {
652 t.Fatalf("Did not get correct subject: '%s'\n", matches[SUB_INDEX])
653 }
654 if matches[SID_INDEX] != "1" {
655 t.Fatalf("Did not get correct sid: '%s'\n", matches[SID_INDEX])
656 }
657 if matches[HDR_INDEX] != "12" {
658 t.Fatalf("Did not get correct msg length: '%s'\n", matches[HDR_INDEX])
659 }
660 if matches[TLEN_INDEX] != "14" {
661 t.Fatalf("Did not get correct msg length: '%s'\n", matches[TLEN_INDEX])
662 }
663 checkPayload(cr, []byte("Name:Derek\r\nOK\r\n"), t)
664 }
665
666 func TestGatewayHeaderDeliverStrippedMsg(t *testing.T) {
667 o2 := testDefaultOptionsForGateway("B")
668 o2.Gateway.ConnectRetries = 0
669 s2 := runGatewayServer(o2)
670 defer s2.Shutdown()
671
672 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
673 o1.NoHeaderSupport = true
674 s1 := runGatewayServer(o1)
675 defer s1.Shutdown()
676
677 // s1 should have an outbound gateway to s2.
678 waitForOutboundGateways(t, s1, 1, time.Second)
679 // and an inbound too
680 waitForInboundGateways(t, s1, 1, time.Second)
681 // s2 should have an inbound gateway
682 waitForInboundGateways(t, s2, 1, time.Second)
683 // and an outbound too
684 waitForOutboundGateways(t, s2, 1, time.Second)
685
686 c, cr, _ := newClientForServer(s1)
687 defer c.close()
688
689 connect := "CONNECT {\"headers\":true}"
690 subOp := "SUB foo 1"
691 pingOp := "PING\r\n"
692 cmd := strings.Join([]string{connect, subOp, pingOp}, "\r\n")
693 c.parseAsync(cmd)
694 if _, err := cr.ReadString('\n'); err != nil {
695 t.Fatalf("Error receiving msg from server: %v\n", err)
696 }
697
698 // Wait for interest to be registered on s2
699 checkGWInterestOnlyModeInterestOn(t, s2, "A", globalAccountName, "foo")
700
701 b, _, _ := newClientForServer(s2)
702 defer b.close()
703
704 pubOp := "HPUB foo 12 14\r\nName:Derek\r\nOK\r\n"
705 cmd = strings.Join([]string{connect, pubOp}, "\r\n")
706 b.parseAsync(cmd)
707
708 l, err := cr.ReadString('\n')
709 if err != nil {
710 t.Fatalf("Error receiving msg from server: %v\n", err)
711 }
712 am := smsgPat.FindAllStringSubmatch(l, -1)
713 if len(am) == 0 {
714 t.Fatalf("Did not get a correct match for %q", l)
715 }
716 matches := am[0]
717 if len(matches) != 6 {
718 t.Fatalf("Did not get correct # matches: %d vs %d\n", len(matches), 6)
719 }
720 if matches[SUB_INDEX] != "foo" {
721 t.Fatalf("Did not get correct subject: '%s'\n", matches[SUB_INDEX])
722 }
723 if matches[SID_INDEX] != "1" {
724 t.Fatalf("Did not get correct sid: '%s'\n", matches[SID_INDEX])
725 }
726 if matches[LEN_INDEX] != "2" {
727 t.Fatalf("Did not get correct msg length: '%s'\n", matches[LEN_INDEX])
728 }
729 checkPayload(cr, []byte("OK\r\n"), t)
730 if cr.Buffered() != 0 {
731 t.Fatalf("Expected no extra bytes to be buffered, got %d", cr.Buffered())
732 }
733 }
734
735 func TestGatewaySolicitDelay(t *testing.T) {
736 o2 := testDefaultOptionsForGateway("B")
737 s2 := runGatewayServer(o2)
738 defer s2.Shutdown()
739
740 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
741 // Set the solicit delay to 0. This tests that server will use its
742 // default value, currently set at 1 sec.
743 o1.gatewaysSolicitDelay = 0
744 start := time.Now()
745 s1 := runGatewayServer(o1)
746 defer s1.Shutdown()
747
748 // After 500ms, check outbound gateway. Should not be there.
749 time.Sleep(500 * time.Millisecond)
750 if time.Since(start) < defaultSolicitGatewaysDelay {
751 if s1.numOutboundGateways() > 0 {
752 t.Fatalf("The outbound gateway was initiated sooner than expected (%v)", time.Since(start))
753 }
754 }
755 // Ultimately, s1 should have an outbound gateway to s2.
756 waitForOutboundGateways(t, s1, 1, 2*time.Second)
757 // s2 should have an inbound gateway
758 waitForInboundGateways(t, s2, 1, 2*time.Second)
759
760 s1.Shutdown()
761 // Make sure that server can be shutdown while waiting
762 // for that initial solicit delay
763 o1.gatewaysSolicitDelay = 2 * time.Second
764 s1 = runGatewayServer(o1)
765 start = time.Now()
766 s1.Shutdown()
767 if dur := time.Since(start); dur >= 2*time.Second {
768 t.Fatalf("Looks like shutdown was delayed: %v", dur)
769 }
770 }
771
772 func TestGatewaySolicitDelayWithImplicitOutbounds(t *testing.T) {
773 // Cause a situation where A connects to B, and because of
774 // delay of solicit gateways set on B, we want to make sure
775 // that B does not end-up with 2 connections to A.
776 o2 := testDefaultOptionsForGateway("B")
777 o2.gatewaysSolicitDelay = 500 * time.Millisecond
778 s2 := runGatewayServer(o2)
779 defer s2.Shutdown()
780
781 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
782 s1 := runGatewayServer(o1)
783 defer s1.Shutdown()
784
785 // s1 should have an outbound and inbound gateway to s2.
786 waitForOutboundGateways(t, s1, 1, 2*time.Second)
787 // s2 should have an inbound gateway
788 waitForInboundGateways(t, s2, 1, 2*time.Second)
789 // Wait for more than s2 solicit delay
790 time.Sleep(750 * time.Millisecond)
791 // The way we store outbound (map key'ed by gw name), we would
792 // not know if we had created 2 (since the newer would replace
793 // the older in the map). But if a second connection was made,
794 // then s1 would have 2 inbounds. So check it has only 1.
795 waitForInboundGateways(t, s1, 1, time.Second)
796 }
797
798 type slowResolver struct {
799 inLookupCh chan struct{}
800 releaseCh chan struct{}
801 }
802
803 func (r *slowResolver) LookupHost(ctx context.Context, h string) ([]string, error) {
804 if r.inLookupCh != nil {
805 select {
806 case r.inLookupCh <- struct{}{}:
807 default:
808 }
809 <-r.releaseCh
810 } else {
811 time.Sleep(500 * time.Millisecond)
812 }
813 return []string{h}, nil
814 }
815
816 func TestGatewaySolicitShutdown(t *testing.T) {
817 var urls []string
818 for i := 0; i < 5; i++ {
819 u := fmt.Sprintf("nats://localhost:%d", 1234+i)
820 urls = append(urls, u)
821 }
822 o1 := testGatewayOptionsFromToWithURLs(t, "A", "B", urls)
823 o1.Gateway.resolver = &slowResolver{}
824 s1 := runGatewayServer(o1)
825 defer s1.Shutdown()
826
827 time.Sleep(o1.gatewaysSolicitDelay + 10*time.Millisecond)
828
829 start := time.Now()
830 s1.Shutdown()
831 if dur := time.Since(start); dur > 1200*time.Millisecond {
832 t.Fatalf("Took too long to shutdown: %v", dur)
833 }
834 }
835
836 func testFatalErrorOnStart(t *testing.T, o *Options, errTxt string) {
837 t.Helper()
838 s := New(o)
839 defer s.Shutdown()
840 l := &captureFatalLogger{fatalCh: make(chan string, 1)}
841 s.SetLogger(l, false, false)
842 // This does not block
843 s.Start()
844 select {
845 case e := <-l.fatalCh:
846 if !strings.Contains(e, errTxt) {
847 t.Fatalf("Error should contain %q, got %s", errTxt, e)
848 }
849 case <-time.After(time.Second):
850 t.Fatal("Should have got a fatal error")
851 }
852 s.Shutdown()
853 s.WaitForShutdown()
854 }
855
856 func TestGatewayListenError(t *testing.T) {
857 o2 := testDefaultOptionsForGateway("B")
858 s2 := runGatewayServer(o2)
859 defer s2.Shutdown()
860
861 o1 := testDefaultOptionsForGateway("A")
862 o1.Gateway.Port = s2.GatewayAddr().Port
863 testFatalErrorOnStart(t, o1, "listening on")
864 }
865
866 func TestGatewayWithListenToAny(t *testing.T) {
867 confB1 := createConfFile(t, []byte(`
868 listen: "127.0.0.1:-1"
869 cluster {
870 listen: "127.0.0.1:-1"
871 }
872 gateway {
873 name: "B"
874 listen: "0.0.0.0:-1"
875 }
876 `))
877 sb1, ob1 := RunServerWithConfig(confB1)
878 defer sb1.Shutdown()
879
880 confB2 := createConfFile(t, []byte(fmt.Sprintf(`
881 listen: "127.0.0.1:-1"
882 cluster {
883 listen: "127.0.0.1:-1"
884 routes: ["%s"]
885 }
886 gateway {
887 name: "B"
888 listen: "0.0.0.0:-1"
889 }
890 `, fmt.Sprintf("nats://127.0.0.1:%d", sb1.ClusterAddr().Port))))
891 sb2, ob2 := RunServerWithConfig(confB2)
892 defer sb2.Shutdown()
893
894 checkClusterFormed(t, sb1, sb2)
895
896 confA := createConfFile(t, []byte(fmt.Sprintf(`
897 listen: "127.0.0.1:-1"
898 cluster {
899 listen: "127.0.0.1:-1"
900 }
901 gateway {
902 name: "A"
903 listen: "0.0.0.0:-1"
904 gateways [
905 {
906 name: "B"
907 urls: ["%s", "%s"]
908 }
909 ]
910 }
911 `, fmt.Sprintf("nats://127.0.0.1:%d", ob1.Gateway.Port), fmt.Sprintf("nats://127.0.0.1:%d", ob2.Gateway.Port))))
912 oa := LoadConfig(confA)
913 oa.gatewaysSolicitDelay = 15 * time.Millisecond
914 sa := runGatewayServer(oa)
915 defer sa.Shutdown()
916
917 waitForOutboundGateways(t, sa, 1, time.Second)
918 waitForOutboundGateways(t, sb1, 1, time.Second)
919 waitForOutboundGateways(t, sb2, 1, time.Second)
920 waitForInboundGateways(t, sa, 2, time.Second)
921
922 checkAll := func(t *testing.T) {
923 t.Helper()
924 checkURL := func(t *testing.T, s *Server) {
925 t.Helper()
926 url := s.getGatewayURL()
927 if strings.HasPrefix(url, "0.0.0.0") {
928 t.Fatalf("URL still references 0.0.0.0")
929 }
930 s.gateway.RLock()
931 for url := range s.gateway.URLs {
932 if strings.HasPrefix(url, "0.0.0.0") {
933 s.gateway.RUnlock()
934 t.Fatalf("URL still references 0.0.0.0")
935 }
936 }
937 s.gateway.RUnlock()
938
939 var cfg *gatewayCfg
940 if s.getGatewayName() == "A" {
941 cfg = s.getRemoteGateway("B")
942 } else {
943 cfg = s.getRemoteGateway("A")
944 }
945 urls := cfg.getURLs()
946 for _, url := range urls {
947 if strings.HasPrefix(url.Host, "0.0.0.0") {
948 t.Fatalf("URL still references 0.0.0.0")
949 }
950 }
951 }
952 checkURL(t, sb1)
953 checkURL(t, sb2)
954 checkURL(t, sa)
955 }
956 checkAll(t)
957 // Perform a reload and ensure that nothing has changed
958 servers := []*Server{sb1, sb2, sa}
959 for _, s := range servers {
960 if err := s.Reload(); err != nil {
961 t.Fatalf("Error on reload: %v", err)
962 }
963 checkAll(t)
964 }
965 }
966
967 func TestGatewayAdvertise(t *testing.T) {
968 o3 := testDefaultOptionsForGateway("C")
969 s3 := runGatewayServer(o3)
970 defer s3.Shutdown()
971
972 o2 := testDefaultOptionsForGateway("B")
973 s2 := runGatewayServer(o2)
974 defer s2.Shutdown()
975
976 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
977 // Set the advertise so that this points to C
978 o1.Gateway.Advertise = fmt.Sprintf("127.0.0.1:%d", s3.GatewayAddr().Port)
979 s1 := runGatewayServer(o1)
980 defer s1.Shutdown()
981
982 // We should have outbound from s1 to s2
983 waitForOutboundGateways(t, s1, 1, time.Second)
984 // But no inbound from s2
985 waitForInboundGateways(t, s1, 0, time.Second)
986
987 // And since B tries to connect to A but reaches C, it should fail to connect,
988 // and without connect retries, stop trying. So no outbound for s2, and no
989 // inbound/outbound for s3.
990 waitForInboundGateways(t, s2, 1, time.Second)
991 waitForOutboundGateways(t, s2, 0, time.Second)
992 waitForInboundGateways(t, s3, 0, time.Second)
993 waitForOutboundGateways(t, s3, 0, time.Second)
994 }
995
996 func TestGatewayAdvertiseErr(t *testing.T) {
997 o1 := testDefaultOptionsForGateway("A")
998 o1.Gateway.Advertise = "wrong:address"
999 testFatalErrorOnStart(t, o1, "Gateway.Advertise")
1000 }
1001
1002 func TestGatewayAuth(t *testing.T) {
1003 o2 := testDefaultOptionsForGateway("B")
1004 o2.Gateway.Username = "me"
1005 o2.Gateway.Password = "pwd"
1006 s2 := runGatewayServer(o2)
1007 defer s2.Shutdown()
1008
1009 o1 := testGatewayOptionsFromToWithURLs(t, "A", "B", []string{fmt.Sprintf("nats://me:[email protected]:%d", s2.GatewayAddr().Port)})
1010 s1 := runGatewayServer(o1)
1011 defer s1.Shutdown()
1012
1013 // s1 should have an outbound gateway to s2.
1014 waitForOutboundGateways(t, s1, 1, time.Second)
1015 // s2 should have an inbound gateway
1016 waitForInboundGateways(t, s2, 1, time.Second)
1017
1018 s2.Shutdown()
1019 s1.Shutdown()
1020
1021 o2.Gateway.Username = "me"
1022 o2.Gateway.Password = "wrong"
1023 s2 = runGatewayServer(o2)
1024 defer s2.Shutdown()
1025
1026 s1 = runGatewayServer(o1)
1027 defer s1.Shutdown()
1028
1029 // Connection should fail...
1030 waitForGatewayFailedConnect(t, s1, "B", true, 2*time.Second)
1031
1032 s2.Shutdown()
1033 s1.Shutdown()
1034 o2.Gateway.Username = "wrong"
1035 o2.Gateway.Password = "pwd"
1036 s2 = runGatewayServer(o2)
1037 defer s2.Shutdown()
1038
1039 s1 = runGatewayServer(o1)
1040 defer s1.Shutdown()
1041
1042 // Connection should fail...
1043 waitForGatewayFailedConnect(t, s1, "B", true, 2*time.Second)
1044 }
1045
1046 func TestGatewayTLS(t *testing.T) {
1047 o2 := testGatewayOptionsWithTLS(t, "B")
1048 s2 := runGatewayServer(o2)
1049 defer s2.Shutdown()
1050
1051 o1 := testGatewayOptionsFromToWithTLS(t, "A", "B", []string{fmt.Sprintf("nats://127.0.0.1:%d", s2.GatewayAddr().Port)})
1052 s1 := runGatewayServer(o1)
1053 defer s1.Shutdown()
1054
1055 // s1 should have an outbound gateway to s2.
1056 waitForOutboundGateways(t, s1, 1, time.Second)
1057 // s2 should have an inbound gateway
1058 waitForInboundGateways(t, s2, 1, time.Second)
1059 // and vice-versa
1060 waitForOutboundGateways(t, s2, 1, time.Second)
1061 waitForInboundGateways(t, s1, 1, time.Second)
1062
1063 // Stop s2 server
1064 s2.Shutdown()
1065
1066 // gateway should go away
1067 waitForOutboundGateways(t, s1, 0, time.Second)
1068 waitForInboundGateways(t, s1, 0, time.Second)
1069 waitForOutboundGateways(t, s2, 0, time.Second)
1070 waitForInboundGateways(t, s2, 0, time.Second)
1071
1072 // Restart server
1073 s2 = runGatewayServer(o2)
1074 defer s2.Shutdown()
1075
1076 // gateway should reconnect
1077 waitForOutboundGateways(t, s1, 1, 2*time.Second)
1078 waitForOutboundGateways(t, s2, 1, 2*time.Second)
1079 waitForInboundGateways(t, s1, 1, 2*time.Second)
1080 waitForInboundGateways(t, s2, 1, 2*time.Second)
1081
1082 s1.Shutdown()
1083 // Wait for s2 to lose connections to s1.
1084 waitForOutboundGateways(t, s2, 0, 2*time.Second)
1085 waitForInboundGateways(t, s2, 0, 2*time.Second)
1086
1087 // Make an explicit TLS config for remote gateway config "B"
1088 // on cluster A.
1089 o1.Gateway.Gateways[0].TLSConfig = o1.Gateway.TLSConfig.Clone()
1090 u, _ := url.Parse(fmt.Sprintf("tls://localhost:%d", s2.GatewayAddr().Port))
1091 o1.Gateway.Gateways[0].URLs = []*url.URL{u}
1092 // Make the TLSTimeout so small that it should fail to connect.
1093 smallTimeout := 0.00000001
1094 o1.Gateway.Gateways[0].TLSTimeout = smallTimeout
1095 s1 = runGatewayServer(o1)
1096 defer s1.Shutdown()
1097
1098 // Check that s1 reports connection failures
1099 waitForGatewayFailedConnect(t, s1, "B", true, 2*time.Second)
1100
1101 // Check that TLSConfig from s1's remote "B" is based on
1102 // what we have configured.
1103 cfg := s1.getRemoteGateway("B")
1104 cfg.RLock()
1105 tlsName := cfg.tlsName
1106 timeout := cfg.TLSTimeout
1107 cfg.RUnlock()
1108 if tlsName != "localhost" {
1109 t.Fatalf("Expected server name to be localhost, got %v", tlsName)
1110 }
1111 if timeout != smallTimeout {
1112 t.Fatalf("Expected tls timeout to be %v, got %v", smallTimeout, timeout)
1113 }
1114 s1.Shutdown()
1115 // Wait for s2 to lose connections to s1.
1116 waitForOutboundGateways(t, s2, 0, 2*time.Second)
1117 waitForInboundGateways(t, s2, 0, 2*time.Second)
1118
1119 // Remove explicit TLSTimeout from gateway "B" and check that
1120 // we use the A's spec one.
1121 o1.Gateway.Gateways[0].TLSTimeout = 0
1122 s1 = runGatewayServer(o1)
1123 defer s1.Shutdown()
1124
1125 waitForOutboundGateways(t, s1, 1, 2*time.Second)
1126 waitForOutboundGateways(t, s2, 1, 2*time.Second)
1127 waitForInboundGateways(t, s1, 1, 2*time.Second)
1128 waitForInboundGateways(t, s2, 1, 2*time.Second)
1129
1130 cfg = s1.getRemoteGateway("B")
1131 cfg.RLock()
1132 timeout = cfg.TLSTimeout
1133 cfg.RUnlock()
1134 if timeout != o1.Gateway.TLSTimeout {
1135 t.Fatalf("Expected tls timeout to be %v, got %v", o1.Gateway.TLSTimeout, timeout)
1136 }
1137 }
1138
1139 func TestGatewayTLSErrors(t *testing.T) {
1140 o2 := testDefaultOptionsForGateway("B")
1141 s2 := runGatewayServer(o2)
1142 defer s2.Shutdown()
1143
1144 o1 := testGatewayOptionsFromToWithTLS(t, "A", "B", []string{fmt.Sprintf("nats://127.0.0.1:%d", s2.ClusterAddr().Port)})
1145 s1 := runGatewayServer(o1)
1146 defer s1.Shutdown()
1147
1148 // Expect s1 to have a failed to connect count > 0
1149 waitForGatewayFailedConnect(t, s1, "B", true, 2*time.Second)
1150 }
1151
1152 func TestGatewayServerNameInTLSConfig(t *testing.T) {
1153 o2 := testDefaultOptionsForGateway("B")
1154 var (
1155 tc = &TLSConfigOpts{}
1156 err error
1157 )
1158 tc.CertFile = "../test/configs/certs/server-noip.pem"
1159 tc.KeyFile = "../test/configs/certs/server-key-noip.pem"
1160 tc.CaFile = "../test/configs/certs/ca.pem"
1161 o2.Gateway.TLSConfig, err = GenTLSConfig(tc)
1162 if err != nil {
1163 t.Fatalf("Error generating TLS config: %v", err)
1164 }
1165 o2.Gateway.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
1166 o2.Gateway.TLSConfig.RootCAs = o2.Gateway.TLSConfig.ClientCAs
1167 o2.Gateway.TLSTimeout = 2.0
1168 s2 := runGatewayServer(o2)
1169 defer s2.Shutdown()
1170
1171 o1 := testGatewayOptionsFromToWithTLS(t, "A", "B", []string{fmt.Sprintf("nats://127.0.0.1:%d", s2.GatewayAddr().Port)})
1172 s1 := runGatewayServer(o1)
1173 defer s1.Shutdown()
1174
1175 // s1 should fail to connect since we don't have proper expected hostname.
1176 waitForGatewayFailedConnect(t, s1, "B", true, 2*time.Second)
1177
1178 // Now set server name, and it should work.
1179 s1.Shutdown()
1180 o1.Gateway.TLSConfig.ServerName = "localhost"
1181 s1 = runGatewayServer(o1)
1182 defer s1.Shutdown()
1183
1184 waitForOutboundGateways(t, s1, 1, 2*time.Second)
1185 }
1186
1187 func TestGatewayWrongDestination(t *testing.T) {
1188 // Start a server with a gateway named "C"
1189 o2 := testDefaultOptionsForGateway("C")
1190 s2 := runGatewayServer(o2)
1191 defer s2.Shutdown()
1192
1193 // Configure a gateway to "B", but since we are connecting to "C"...
1194 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
1195 s1 := runGatewayServer(o1)
1196 defer s1.Shutdown()
1197
1198 // we should not be able to connect.
1199 waitForGatewayFailedConnect(t, s1, "B", true, time.Second)
1200
1201 // Shutdown s2 and fix the gateway name.
1202 // s1 should then connect ok and failed connect should be cleared.
1203 s2.Shutdown()
1204
1205 // Reset the conn attempts
1206 cfg := s1.getRemoteGateway("B")
1207 cfg.resetConnAttempts()
1208
1209 o2.Gateway.Name = "B"
1210 o2.Cluster.Name = "B"
1211 s2 = runGatewayServer(o2)
1212 defer s2.Shutdown()
1213
1214 // At some point, the number of failed connect count should be reset to 0.
1215 waitForGatewayFailedConnect(t, s1, "B", false, 2*time.Second)
1216 }
1217
1218 func TestGatewayConnectToWrongPort(t *testing.T) {
1219 o2 := testDefaultOptionsForGateway("B")
1220 s2 := runGatewayServer(o2)
1221 defer s2.Shutdown()
1222
1223 // Configure a gateway to "B", but connect to the wrong port
1224 urls := []string{fmt.Sprintf("nats://127.0.0.1:%d", s2.Addr().(*net.TCPAddr).Port)}
1225 o1 := testGatewayOptionsFromToWithURLs(t, "A", "B", urls)
1226 s1 := runGatewayServer(o1)
1227 defer s1.Shutdown()
1228
1229 // we should not be able to connect.
1230 waitForGatewayFailedConnect(t, s1, "B", true, time.Second)
1231
1232 s1.Shutdown()
1233
1234 // Repeat with route port
1235 urls = []string{fmt.Sprintf("nats://127.0.0.1:%d", s2.ClusterAddr().Port)}
1236 o1 = testGatewayOptionsFromToWithURLs(t, "A", "B", urls)
1237 s1 = runGatewayServer(o1)
1238 defer s1.Shutdown()
1239
1240 // we should not be able to connect.
1241 waitForGatewayFailedConnect(t, s1, "B", true, time.Second)
1242
1243 s1.Shutdown()
1244
1245 // Now have a client connect to s2's gateway port.
1246 nc, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", s2.GatewayAddr().Port))
1247 if err == nil {
1248 nc.Close()
1249 t.Fatal("Expected error, got none")
1250 }
1251 }
1252
1253 func TestGatewayCreateImplicit(t *testing.T) {
1254 // Create a regular cluster of 2 servers
1255 o2 := testDefaultOptionsForGateway("B")
1256 s2 := runGatewayServer(o2)
1257 defer s2.Shutdown()
1258
1259 o3 := testDefaultOptionsForGateway("B")
1260 o3.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", s2.ClusterAddr().Port))
1261 s3 := runGatewayServer(o3)
1262 defer s3.Shutdown()
1263
1264 checkClusterFormed(t, s2, s3)
1265
1266 // Now start s1 that creates a Gateway connection to s2 or s3
1267 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2, s3)
1268 s1 := runGatewayServer(o1)
1269 defer s1.Shutdown()
1270
1271 // We should have an outbound gateway connection on ALL servers.
1272 waitForOutboundGateways(t, s1, 1, 2*time.Second)
1273 waitForOutboundGateways(t, s2, 1, 2*time.Second)
1274 waitForOutboundGateways(t, s3, 1, 2*time.Second)
1275
1276 // Server s1 must have 2 inbound ones
1277 waitForInboundGateways(t, s1, 2, 2*time.Second)
1278
1279 // However, s1 may have created the outbound to s2 or s3. It is possible that
1280 // either s2 or s3 does not an inbound connection.
1281 s2Inbound := s2.numInboundGateways()
1282 s3Inbound := s3.numInboundGateways()
1283 if (s2Inbound == 1 && s3Inbound != 0) || (s3Inbound == 1 && s2Inbound != 0) {
1284 t.Fatalf("Unexpected inbound for s2/s3: %v/%v", s2Inbound, s3Inbound)
1285 }
1286 }
1287
1288 func TestGatewayCreateImplicitOnNewRoute(t *testing.T) {
1289 // Start with only 2 clusters of 1 server each
1290 o2 := testDefaultOptionsForGateway("B")
1291 s2 := runGatewayServer(o2)
1292 defer s2.Shutdown()
1293
1294 // Now start s1 that creates a Gateway connection to s2
1295 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
1296 s1 := runGatewayServer(o1)
1297 defer s1.Shutdown()
1298
1299 // Check outbounds
1300 waitForOutboundGateways(t, s1, 1, 2*time.Second)
1301 waitForOutboundGateways(t, s2, 1, 2*time.Second)
1302
1303 // Now add a server to cluster B
1304 o3 := testDefaultOptionsForGateway("B")
1305 o3.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", s2.ClusterAddr().Port))
1306 s3 := runGatewayServer(o3)
1307 defer s3.Shutdown()
1308
1309 // Wait for cluster between s2/s3 to form
1310 checkClusterFormed(t, s2, s3)
1311
1312 // s3 should have been notified about existence of A and create its gateway to A.
1313 waitForOutboundGateways(t, s1, 1, 2*time.Second)
1314 waitForOutboundGateways(t, s2, 1, 2*time.Second)
1315 waitForOutboundGateways(t, s3, 1, 2*time.Second)
1316 }
1317
1318 func TestGatewayImplicitReconnect(t *testing.T) {
1319 o2 := testDefaultOptionsForGateway("B")
1320 o2.Gateway.ConnectRetries = 5
1321 s2 := runGatewayServer(o2)
1322 defer s2.Shutdown()
1323
1324 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
1325 s1 := runGatewayServer(o1)
1326 defer s1.Shutdown()
1327
1328 // s1 should have an outbound gateway to s2.
1329 waitForOutboundGateways(t, s1, 1, time.Second)
1330 // s2 should have an inbound gateway
1331 waitForInboundGateways(t, s2, 1, time.Second)
1332 // It will have also created an implicit outbound connection to s1.
1333 // We need to wait for that implicit outbound connection to be made
1334 // to show that it will try to reconnect when we stop/restart s1
1335 // (without config to connect to B).
1336 waitForOutboundGateways(t, s2, 1, time.Second)
1337
1338 // Shutdown s1, remove the gateway from A to B and restart.
1339 s1.Shutdown()
1340 o1.Gateway.Gateways = o1.Gateway.Gateways[:0]
1341 s1 = runGatewayServer(o1)
1342 defer s1.Shutdown()
1343
1344 // s1 should have both outbound and inbound to s2
1345 waitForOutboundGateways(t, s1, 1, 2*time.Second)
1346 waitForInboundGateways(t, s1, 1, 2*time.Second)
1347
1348 // Same for s2
1349 waitForOutboundGateways(t, s2, 1, 2*time.Second)
1350 waitForInboundGateways(t, s2, 1, 2*time.Second)
1351
1352 // Verify that s2 still has "A" in its gateway config
1353 if s2.getRemoteGateway("A") == nil {
1354 t.Fatal("Gateway A should be in s2")
1355 }
1356 }
1357
1358 func TestGatewayImplicitReconnectRace(t *testing.T) {
1359 ob := testDefaultOptionsForGateway("B")
1360 resolver := &slowResolver{
1361 inLookupCh: make(chan struct{}, 1),
1362 releaseCh: make(chan struct{}),
1363 }
1364 ob.Gateway.resolver = resolver
1365 sb := runGatewayServer(ob)
1366 defer sb.Shutdown()
1367
1368 oa1 := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
1369 sa1 := runGatewayServer(oa1)
1370 defer sa1.Shutdown()
1371
1372 // Wait for the proper connections
1373 waitForOutboundGateways(t, sa1, 1, time.Second)
1374 waitForOutboundGateways(t, sb, 1, time.Second)
1375 waitForInboundGateways(t, sa1, 1, time.Second)
1376 waitForInboundGateways(t, sb, 1, time.Second)
1377
1378 // On sb, change the URL to sa1 so that it is a name, instead of an IP,
1379 // so that we hit the slow resolver.
1380 cfg := sb.getRemoteGateway("A")
1381 cfg.updateURLs([]string{fmt.Sprintf("localhost:%d", sa1.GatewayAddr().Port)})
1382
1383 // Shutdown sa1 now...
1384 sa1.Shutdown()
1385
1386 // Wait to be notified that B has detected the connection close
1387 // and it is trying to resolve the host during the reconnect.
1388 <-resolver.inLookupCh
1389
1390 // Start a new "A" server (sa2).
1391 oa2 := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
1392 sa2 := runGatewayServer(oa2)
1393 defer sa2.Shutdown()
1394
1395 // Make sure we have our outbound to sb registered on sa2 and inbound
1396 // from sa2 on sb before releasing the resolver.
1397 waitForOutboundGateways(t, sa2, 1, 2*time.Second)
1398 waitForInboundGateways(t, sb, 1, 2*time.Second)
1399
1400 // Now release the resolver and ensure we have all connections.
1401 close(resolver.releaseCh)
1402
1403 waitForOutboundGateways(t, sb, 1, 2*time.Second)
1404 waitForInboundGateways(t, sa2, 1, 2*time.Second)
1405 }
1406
1407 type gwReconnAttemptLogger struct {
1408 DummyLogger
1409 errCh chan string
1410 }
1411
1412 func (l *gwReconnAttemptLogger) Errorf(format string, v ...any) {
1413 msg := fmt.Sprintf(format, v...)
1414 if strings.Contains(msg, `Error connecting to implicit gateway "A"`) {
1415 select {
1416 case l.errCh <- msg:
1417 default:
1418 }
1419 }
1420 }
1421
1422 func TestGatewayImplicitReconnectHonorConnectRetries(t *testing.T) {
1423 ob := testDefaultOptionsForGateway("B")
1424 ob.ReconnectErrorReports = 1
1425 ob.Gateway.ConnectRetries = 2
1426 sb := runGatewayServer(ob)
1427 defer sb.Shutdown()
1428
1429 l := &gwReconnAttemptLogger{errCh: make(chan string, 3)}
1430 sb.SetLogger(l, true, false)
1431
1432 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
1433 sa := runGatewayServer(oa)
1434 defer sa.Shutdown()
1435
1436 // Wait for the proper connections
1437 waitForOutboundGateways(t, sa, 1, time.Second)
1438 waitForOutboundGateways(t, sb, 1, time.Second)
1439 waitForInboundGateways(t, sa, 1, time.Second)
1440 waitForInboundGateways(t, sb, 1, time.Second)
1441
1442 // Now have C connect to B.
1443 oc := testGatewayOptionsFromToWithServers(t, "C", "B", sb)
1444 sc := runGatewayServer(oc)
1445 defer sc.Shutdown()
1446
1447 // Wait for the proper connections
1448 waitForOutboundGateways(t, sa, 2, time.Second)
1449 waitForOutboundGateways(t, sb, 2, time.Second)
1450 waitForOutboundGateways(t, sc, 2, time.Second)
1451 waitForInboundGateways(t, sa, 2, time.Second)
1452 waitForInboundGateways(t, sb, 2, time.Second)
1453 waitForInboundGateways(t, sc, 2, time.Second)
1454
1455 // Shutdown sa now...
1456 sa.Shutdown()
1457
1458 // B will try to reconnect to A 3 times (we stop after attempts > ConnectRetries)
1459 timeout := time.NewTimer(time.Second)
1460 for i := 0; i < 3; i++ {
1461 select {
1462 case <-l.errCh:
1463 // OK
1464 case <-timeout.C:
1465 t.Fatal("Did not get debug trace about reconnect")
1466 }
1467 }
1468 // If we get 1 more, we have an issue!
1469 select {
1470 case e := <-l.errCh:
1471 t.Fatalf("Should not have attempted to reconnect: %q", e)
1472 case <-time.After(250 * time.Millisecond):
1473 // OK!
1474 }
1475
1476 waitForOutboundGateways(t, sb, 1, 2*time.Second)
1477 waitForInboundGateways(t, sb, 1, 2*time.Second)
1478 waitForOutboundGateways(t, sc, 1, 2*time.Second)
1479 waitForInboundGateways(t, sc, 1, 2*time.Second)
1480 }
1481
1482 func TestGatewayReconnectExponentialBackoff(t *testing.T) {
1483 oGatewayConnectDelay := gatewayConnectDelay
1484 oGatewayConnectMaxDelay := gatewayConnectMaxDelay
1485 gatewayConnectDelay = 500 * time.Millisecond
1486 gatewayConnectMaxDelay = 2 * time.Second
1487 defer func() {
1488 gatewayConnectDelay = oGatewayConnectDelay
1489 gatewayConnectMaxDelay = oGatewayConnectMaxDelay
1490 }()
1491
1492 ob := testDefaultOptionsForGateway("B")
1493 ob.ReconnectErrorReports = 1
1494 ob.Gateway.ConnectRetries = 3
1495 ob.Gateway.ConnectBackoff = true
1496 sb := runGatewayServer(ob)
1497 defer sb.Shutdown()
1498
1499 l := &gwReconnAttemptLogger{errCh: make(chan string, 3)}
1500 sb.SetLogger(l, true, false)
1501
1502 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
1503 sa := runGatewayServer(oa)
1504 defer sa.Shutdown()
1505
1506 // Wait for the proper connections
1507 waitForOutboundGateways(t, sa, 1, time.Second)
1508 waitForOutboundGateways(t, sb, 1, time.Second)
1509 waitForInboundGateways(t, sa, 1, time.Second)
1510 waitForInboundGateways(t, sb, 1, time.Second)
1511
1512 // Remove initial delay before reconnect, and allow for some skew.
1513 now := time.Now().Add(gatewayReconnectDelay).Add(-100 * time.Millisecond)
1514 var delay time.Duration
1515
1516 // B will try to reconnect to A 3 times (we stop after attempts > ConnectRetries)
1517 sa.Shutdown()
1518 for i := 0; i < ob.Gateway.ConnectRetries+1; i++ {
1519 select {
1520 case <-l.errCh:
1521 if since := time.Since(now); since < delay {
1522 t.Fatalf("Expected delay to take %v, took %v", delay, since)
1523 }
1524 if delay == 0 {
1525 delay = gatewayConnectDelay
1526 } else {
1527 delay *= 2
1528 }
1529 if delay > gatewayConnectMaxDelay {
1530 delay = gatewayConnectMaxDelay
1531 }
1532 case <-time.After(gatewayConnectMaxDelay + time.Second):
1533 t.Fatal("Did not attempt to reconnect")
1534 }
1535 }
1536 }
1537
1538 func TestGatewayURLsFromClusterSentInINFO(t *testing.T) {
1539 o2 := testDefaultOptionsForGateway("B")
1540 s2 := runGatewayServer(o2)
1541 defer s2.Shutdown()
1542
1543 o3 := testDefaultOptionsForGateway("B")
1544 o3.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", s2.ClusterAddr().Port))
1545 s3 := runGatewayServer(o3)
1546 defer s3.Shutdown()
1547
1548 checkClusterFormed(t, s2, s3)
1549
1550 // Now start s1 that creates a Gateway connection to s2
1551 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
1552 s1 := runGatewayServer(o1)
1553 defer s1.Shutdown()
1554
1555 // Make sure we have proper outbound/inbound
1556 waitForOutboundGateways(t, s1, 1, time.Second)
1557 waitForOutboundGateways(t, s2, 1, time.Second)
1558 waitForOutboundGateways(t, s3, 1, time.Second)
1559
1560 // Although s1 connected to s2 and knew only about s2, it should have
1561 // received the list of gateway URLs in the B cluster. So if we shutdown
1562 // server s2, it should be able to reconnect to s3.
1563 s2.Shutdown()
1564 // Wait for s3 to register that there s2 is gone.
1565 checkNumRoutes(t, s3, 0)
1566 // s1 should have reconnected to s3 because it learned about it
1567 // when connecting earlier to s2.
1568 waitForOutboundGateways(t, s1, 1, 2*time.Second)
1569 // Also make sure that the gateway's urls map has 2 urls.
1570 gw := s1.getRemoteGateway("B")
1571 if gw == nil {
1572 t.Fatal("Did not find gateway B")
1573 }
1574 gw.RLock()
1575 l := len(gw.urls)
1576 gw.RUnlock()
1577 if l != 2 {
1578 t.Fatalf("S1 should have 2 urls, got %v", l)
1579 }
1580 }
1581
1582 func TestGatewayUseUpdatedURLs(t *testing.T) {
1583 // For this test, we have cluster B with an explicit gateway to cluster A
1584 // on a given URL. Then we create cluster A with a gateway to B with server B's
1585 // GW url, and we expect server B to ultimately create an outbound GW connection
1586 // to server A (with the URL it will get from server A connecting to it).
1587
1588 ob := testGatewayOptionsFromToWithURLs(t, "B", "A", []string{"nats://127.0.0.1:1234"})
1589 sb := runGatewayServer(ob)
1590 defer sb.Shutdown()
1591
1592 // Add a delay before starting server A to make sure that server B start
1593 // initiating the connection to A on inexistant server at :1234.
1594 time.Sleep(100 * time.Millisecond)
1595
1596 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
1597 sa := runGatewayServer(oa)
1598 defer sa.Shutdown()
1599
1600 // sa should have no problem creating outbound connection to sb
1601 waitForOutboundGateways(t, sa, 1, time.Second)
1602
1603 // Make sure that since sb learns about sa's GW URL, it can successfully
1604 // connect to it.
1605 waitForOutboundGateways(t, sb, 1, 3*time.Second)
1606 waitForInboundGateways(t, sb, 1, time.Second)
1607 waitForInboundGateways(t, sa, 1, time.Second)
1608 }
1609
1610 func TestGatewayAutoDiscovery(t *testing.T) {
1611 o4 := testDefaultOptionsForGateway("D")
1612 s4 := runGatewayServer(o4)
1613 defer s4.Shutdown()
1614
1615 o3 := testGatewayOptionsFromToWithServers(t, "C", "D", s4)
1616 s3 := runGatewayServer(o3)
1617 defer s3.Shutdown()
1618
1619 o2 := testGatewayOptionsFromToWithServers(t, "B", "C", s3)
1620 s2 := runGatewayServer(o2)
1621 defer s2.Shutdown()
1622
1623 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
1624 s1 := runGatewayServer(o1)
1625 defer s1.Shutdown()
1626
1627 // Each server should have 3 outbound gateway connections.
1628 waitForOutboundGateways(t, s1, 3, 2*time.Second)
1629 waitForOutboundGateways(t, s2, 3, 2*time.Second)
1630 waitForOutboundGateways(t, s3, 3, 2*time.Second)
1631 waitForOutboundGateways(t, s4, 3, 2*time.Second)
1632
1633 s1.Shutdown()
1634 s2.Shutdown()
1635 s3.Shutdown()
1636 s4.Shutdown()
1637
1638 o2 = testDefaultOptionsForGateway("B")
1639 s2 = runGatewayServer(o2)
1640 defer s2.Shutdown()
1641
1642 o4 = testGatewayOptionsFromToWithServers(t, "D", "B", s2)
1643 s4 = runGatewayServer(o4)
1644 defer s4.Shutdown()
1645
1646 o3 = testGatewayOptionsFromToWithServers(t, "C", "B", s2)
1647 s3 = runGatewayServer(o3)
1648 defer s3.Shutdown()
1649
1650 o1 = testGatewayOptionsFromToWithServers(t, "A", "B", s2)
1651 s1 = runGatewayServer(o1)
1652 defer s1.Shutdown()
1653
1654 // Each server should have 3 outbound gateway connections.
1655 waitForOutboundGateways(t, s1, 3, 2*time.Second)
1656 waitForOutboundGateways(t, s2, 3, 2*time.Second)
1657 waitForOutboundGateways(t, s3, 3, 2*time.Second)
1658 waitForOutboundGateways(t, s4, 3, 2*time.Second)
1659
1660 s1.Shutdown()
1661 s2.Shutdown()
1662 s3.Shutdown()
1663 s4.Shutdown()
1664
1665 o1 = testDefaultOptionsForGateway("A")
1666 s1 = runGatewayServer(o1)
1667 defer s1.Shutdown()
1668
1669 o2 = testDefaultOptionsForGateway("A")
1670 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", s1.ClusterAddr().Port))
1671 s2 = runGatewayServer(o2)
1672 defer s2.Shutdown()
1673
1674 o3 = testDefaultOptionsForGateway("A")
1675 o3.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", s1.ClusterAddr().Port))
1676 s3 = runGatewayServer(o3)
1677 defer s3.Shutdown()
1678
1679 checkClusterFormed(t, s1, s2, s3)
1680
1681 o4 = testGatewayOptionsFromToWithServers(t, "B", "A", s1)
1682 s4 = runGatewayServer(o4)
1683 defer s4.Shutdown()
1684
1685 waitForOutboundGateways(t, s1, 1, 2*time.Second)
1686 waitForOutboundGateways(t, s2, 1, 2*time.Second)
1687 waitForOutboundGateways(t, s3, 1, 2*time.Second)
1688 waitForOutboundGateways(t, s4, 1, 2*time.Second)
1689 waitForInboundGateways(t, s4, 3, 2*time.Second)
1690
1691 o5 := testGatewayOptionsFromToWithServers(t, "C", "B", s4)
1692 s5 := runGatewayServer(o5)
1693 defer s5.Shutdown()
1694
1695 waitForOutboundGateways(t, s1, 2, 2*time.Second)
1696 waitForOutboundGateways(t, s2, 2, 2*time.Second)
1697 waitForOutboundGateways(t, s3, 2, 2*time.Second)
1698 waitForOutboundGateways(t, s4, 2, 2*time.Second)
1699 waitForInboundGateways(t, s4, 4, 2*time.Second)
1700 waitForOutboundGateways(t, s5, 2, 2*time.Second)
1701 waitForInboundGateways(t, s5, 4, 2*time.Second)
1702 }
1703
1704 func TestGatewayRejectUnknown(t *testing.T) {
1705 o2 := testDefaultOptionsForGateway("B")
1706 s2 := runGatewayServer(o2)
1707 defer s2.Shutdown()
1708
1709 // Create a gateway from A to B, but configure B to reject non configured ones.
1710 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
1711 o1.Gateway.RejectUnknown = true
1712 s1 := runGatewayServer(o1)
1713 defer s1.Shutdown()
1714
1715 // Wait for outbound/inbound to be created.
1716 waitForOutboundGateways(t, s1, 1, time.Second)
1717 waitForOutboundGateways(t, s2, 1, time.Second)
1718 waitForInboundGateways(t, s1, 1, time.Second)
1719 waitForInboundGateways(t, s2, 1, time.Second)
1720
1721 // Create gateway C to B. B will tell C to connect to A,
1722 // which A should reject.
1723 o3 := testGatewayOptionsFromToWithServers(t, "C", "B", s2)
1724 s3 := runGatewayServer(o3)
1725 defer s3.Shutdown()
1726
1727 // s3 should have outbound to B, but not to A
1728 waitForOutboundGateways(t, s3, 1, time.Second)
1729 // s2 should have 2 inbounds (one from s1 one from s3)
1730 waitForInboundGateways(t, s2, 2, time.Second)
1731
1732 // s1 should have single outbound/inbound with s2.
1733 waitForOutboundGateways(t, s1, 1, time.Second)
1734 waitForInboundGateways(t, s1, 1, time.Second)
1735
1736 // It should not have a registered remote gateway with C (s3)
1737 if s1.getOutboundGatewayConnection("C") != nil {
1738 t.Fatalf("A should not have outbound gateway to C")
1739 }
1740 if s1.getRemoteGateway("C") != nil {
1741 t.Fatalf("A should not have a registered remote gateway to C")
1742 }
1743
1744 // Restart s1 and this time, B will tell A to connect to C.
1745 // But A will not even attempt that since it does not have
1746 // C configured.
1747 s1.Shutdown()
1748 waitForOutboundGateways(t, s2, 1, time.Second)
1749 waitForInboundGateways(t, s2, 1, time.Second)
1750 s1 = runGatewayServer(o1)
1751 defer s1.Shutdown()
1752 waitForOutboundGateways(t, s2, 2, time.Second)
1753 waitForInboundGateways(t, s2, 2, time.Second)
1754 waitForOutboundGateways(t, s1, 1, time.Second)
1755 waitForInboundGateways(t, s1, 1, time.Second)
1756 waitForOutboundGateways(t, s3, 1, time.Second)
1757 waitForInboundGateways(t, s3, 1, time.Second)
1758 // It should not have a registered remote gateway with C (s3)
1759 if s1.getOutboundGatewayConnection("C") != nil {
1760 t.Fatalf("A should not have outbound gateway to C")
1761 }
1762 if s1.getRemoteGateway("C") != nil {
1763 t.Fatalf("A should not have a registered remote gateway to C")
1764 }
1765 }
1766
1767 func TestGatewayNoReconnectOnClose(t *testing.T) {
1768 o2 := testDefaultOptionsForGateway("B")
1769 s2 := runGatewayServer(o2)
1770 defer s2.Shutdown()
1771
1772 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
1773 s1 := runGatewayServer(o1)
1774 defer s1.Shutdown()
1775
1776 waitForOutboundGateways(t, s1, 1, time.Second)
1777 waitForOutboundGateways(t, s2, 1, time.Second)
1778
1779 // Shutdown s1, and check that there is no attempt to reconnect.
1780 s1.Shutdown()
1781 time.Sleep(250 * time.Millisecond)
1782 waitForOutboundGateways(t, s1, 0, time.Second)
1783 waitForOutboundGateways(t, s2, 0, time.Second)
1784 waitForInboundGateways(t, s2, 0, time.Second)
1785 }
1786
1787 func TestGatewayDontSendSubInterest(t *testing.T) {
1788 o2 := testDefaultOptionsForGateway("B")
1789 s2 := runGatewayServer(o2)
1790 defer s2.Shutdown()
1791
1792 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
1793 s1 := runGatewayServer(o1)
1794 defer s1.Shutdown()
1795
1796 waitForOutboundGateways(t, s1, 1, time.Second)
1797 waitForOutboundGateways(t, s2, 1, time.Second)
1798
1799 s2Url := fmt.Sprintf("nats://127.0.0.1:%d", o2.Port)
1800 subnc := natsConnect(t, s2Url)
1801 defer subnc.Close()
1802 natsSub(t, subnc, "foo", func(_ *nats.Msg) {})
1803 natsFlush(t, subnc)
1804
1805 checkExpectedSubs(t, 1, s2)
1806 // Subscription should not be sent to s1
1807 checkExpectedSubs(t, 0, s1)
1808
1809 // Restart s1
1810 s1.Shutdown()
1811 s1 = runGatewayServer(o1)
1812 defer s1.Shutdown()
1813 waitForOutboundGateways(t, s1, 1, time.Second)
1814 waitForOutboundGateways(t, s2, 1, time.Second)
1815
1816 checkExpectedSubs(t, 1, s2)
1817 checkExpectedSubs(t, 0, s1)
1818 }
1819
1820 func setAccountUserPassInOptions(o *Options, accName, username, password string) {
1821 acc := NewAccount(accName)
1822 o.Accounts = append(o.Accounts, acc)
1823 o.Users = append(o.Users, &User{Username: username, Password: password, Account: acc})
1824 }
1825
1826 func TestGatewayAccountInterest(t *testing.T) {
1827 GatewayDoNotForceInterestOnlyMode(true)
1828 defer GatewayDoNotForceInterestOnlyMode(false)
1829
1830 o2 := testDefaultOptionsForGateway("B")
1831 // Add users to cause s2 to require auth. Will add an account with user later.
1832 o2.Users = append([]*User(nil), &User{Username: "test", Password: "pwd"})
1833 s2 := runGatewayServer(o2)
1834 defer s2.Shutdown()
1835
1836 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
1837 setAccountUserPassInOptions(o1, "$foo", "ivan", "password")
1838 s1 := runGatewayServer(o1)
1839 defer s1.Shutdown()
1840
1841 // Make this server initiate connection to A, so it is faster
1842 // when restarting it at the end of this test.
1843 o3 := testGatewayOptionsFromToWithServers(t, "C", "A", s1)
1844 setAccountUserPassInOptions(o3, "$foo", "ivan", "password")
1845 s3 := runGatewayServer(o3)
1846 defer s3.Shutdown()
1847
1848 waitForOutboundGateways(t, s1, 2, time.Second)
1849 waitForOutboundGateways(t, s2, 2, time.Second)
1850 waitForOutboundGateways(t, s3, 2, time.Second)
1851
1852 s1Url := fmt.Sprintf("nats://ivan:[email protected]:%d", o1.Port)
1853 nc := natsConnect(t, s1Url)
1854 defer nc.Close()
1855 natsPub(t, nc, "foo", []byte("hello"))
1856 natsFlush(t, nc)
1857
1858 // On first send, the message should be sent.
1859 checkCount := func(t *testing.T, c *client, expected int) {
1860 t.Helper()
1861 c.mu.Lock()
1862 out := c.outMsgs
1863 c.mu.Unlock()
1864 if int(out) != expected {
1865 t.Fatalf("Expected %d message(s) to be sent over, got %v", expected, out)
1866 }
1867 }
1868 gwcb := s1.getOutboundGatewayConnection("B")
1869 checkCount(t, gwcb, 1)
1870 gwcc := s1.getOutboundGatewayConnection("C")
1871 checkCount(t, gwcc, 1)
1872
1873 // S2 and S3 should have sent a protocol indicating no account interest.
1874 checkForAccountNoInterest(t, gwcb, "$foo", true, 2*time.Second)
1875 checkForAccountNoInterest(t, gwcc, "$foo", true, 2*time.Second)
1876 // Second send should not go to B nor C.
1877 natsPub(t, nc, "foo", []byte("hello"))
1878 natsFlush(t, nc)
1879 checkCount(t, gwcb, 1)
1880 checkCount(t, gwcc, 1)
1881
1882 // Add account to S2 and a client, this should clear the no-interest
1883 // for that account.
1884 s2FooAcc, err := s2.RegisterAccount("$foo")
1885 if err != nil {
1886 t.Fatalf("Error registering account: %v", err)
1887 }
1888 s2.mu.Lock()
1889 s2.users["ivan"] = &User{Account: s2FooAcc, Username: "ivan", Password: "password"}
1890 s2.mu.Unlock()
1891 s2Url := fmt.Sprintf("nats://ivan:[email protected]:%d", o2.Port)
1892 ncS2 := natsConnect(t, s2Url)
1893 defer ncS2.Close()
1894 // Any subscription should cause s2 to send an A+
1895 natsSubSync(t, ncS2, "asub")
1896 // Wait for the A+
1897 checkForAccountNoInterest(t, gwcb, "$foo", false, 2*time.Second)
1898
1899 // Now publish a message that should go to B
1900 natsPub(t, nc, "foo", []byte("hello"))
1901 natsFlush(t, nc)
1902 checkCount(t, gwcb, 2)
1903 // Still won't go to C since there is no sub interest
1904 checkCount(t, gwcc, 1)
1905
1906 // We should have received a subject no interest for foo
1907 checkForSubjectNoInterest(t, gwcb, "$foo", "foo", true, 2*time.Second)
1908
1909 // Now if we close the client, which removed the sole subscription,
1910 // and publish to a new subject, we should then get an A-
1911 ncS2.Close()
1912 // Wait a bit...
1913 time.Sleep(20 * time.Millisecond)
1914 // Publish on new subject
1915 natsPub(t, nc, "bar", []byte("hello"))
1916 natsFlush(t, nc)
1917 // It should go out to B...
1918 checkCount(t, gwcb, 3)
1919 // But then we should get a A-
1920 checkForAccountNoInterest(t, gwcb, "$foo", true, 2*time.Second)
1921
1922 // Restart C and that should reset the no-interest
1923 s3.Shutdown()
1924 s3 = runGatewayServer(o3)
1925 defer s3.Shutdown()
1926
1927 waitForOutboundGateways(t, s1, 2, 2*time.Second)
1928 waitForOutboundGateways(t, s2, 2, 2*time.Second)
1929 waitForOutboundGateways(t, s3, 2, 2*time.Second)
1930
1931 // First refresh gwcc
1932 gwcc = s1.getOutboundGatewayConnection("C")
1933 // Verify that it's count is 0
1934 checkCount(t, gwcc, 0)
1935 // Publish and now...
1936 natsPub(t, nc, "foo", []byte("hello"))
1937 natsFlush(t, nc)
1938 // it should not go to B (no sub interest)
1939 checkCount(t, gwcb, 3)
1940 // but will go to C
1941 checkCount(t, gwcc, 1)
1942 }
1943
1944 func TestGatewayAccountUnsub(t *testing.T) {
1945 ob := testDefaultOptionsForGateway("B")
1946 sb := runGatewayServer(ob)
1947 defer sb.Shutdown()
1948
1949 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
1950 sa := runGatewayServer(oa)
1951 defer sa.Shutdown()
1952
1953 waitForOutboundGateways(t, sa, 1, time.Second)
1954 waitForOutboundGateways(t, sb, 1, time.Second)
1955 waitForInboundGateways(t, sa, 1, time.Second)
1956 waitForInboundGateways(t, sb, 1, time.Second)
1957
1958 // Connect on B
1959 ncb := natsConnect(t, fmt.Sprintf("nats://%s:%d", ob.Host, ob.Port))
1960 defer ncb.Close()
1961 // Create subscription
1962 natsSub(t, ncb, "foo", func(m *nats.Msg) {
1963 ncb.Publish(m.Reply, []byte("reply"))
1964 })
1965 natsFlush(t, ncb)
1966
1967 // Connect on A
1968 nca := natsConnect(t, fmt.Sprintf("nats://%s:%d", oa.Host, oa.Port))
1969 defer nca.Close()
1970 // Send a request
1971 if _, err := nca.Request("foo", []byte("req"), time.Second); err != nil {
1972 t.Fatalf("Error getting reply: %v", err)
1973 }
1974
1975 // Now close connection on B
1976 ncb.Close()
1977
1978 // Publish lots of messages on "foo" from A.
1979 // We should receive an A- shortly and the number
1980 // of outbound messages from A to B should not be
1981 // close to the number of messages sent here.
1982 total := 5000
1983 for i := 0; i < total; i++ {
1984 natsPub(t, nca, "foo", []byte("hello"))
1985 // Try to slow down things a bit to give a chance
1986 // to srvB to send the A- and to srvA to be able
1987 // to process it, which will then suppress the sends.
1988 if i%100 == 0 {
1989 natsFlush(t, nca)
1990 }
1991 }
1992 natsFlush(t, nca)
1993
1994 c := sa.getOutboundGatewayConnection("B")
1995 c.mu.Lock()
1996 out := c.outMsgs
1997 c.mu.Unlock()
1998
1999 if out >= int64(80*total)/100 {
2000 t.Fatalf("Unexpected number of messages sent from A to B: %v", out)
2001 }
2002 }
2003
2004 func TestGatewaySubjectInterest(t *testing.T) {
2005 GatewayDoNotForceInterestOnlyMode(true)
2006 defer GatewayDoNotForceInterestOnlyMode(false)
2007
2008 o1 := testDefaultOptionsForGateway("A")
2009 setAccountUserPassInOptions(o1, "$foo", "ivan", "password")
2010 s1 := runGatewayServer(o1)
2011 defer s1.Shutdown()
2012
2013 o2 := testGatewayOptionsFromToWithServers(t, "B", "A", s1)
2014 setAccountUserPassInOptions(o2, "$foo", "ivan", "password")
2015 s2 := runGatewayServer(o2)
2016 defer s2.Shutdown()
2017
2018 waitForOutboundGateways(t, s1, 1, time.Second)
2019 waitForOutboundGateways(t, s2, 1, time.Second)
2020
2021 // We will create a subscription that we are not testing so
2022 // that we don't get an A- in this test.
2023 s2Url := fmt.Sprintf("nats://ivan:[email protected]:%d", o2.Port)
2024 ncb := natsConnect(t, s2Url)
2025 defer ncb.Close()
2026 natsSubSync(t, ncb, "not.used")
2027 checkExpectedSubs(t, 1, s2)
2028
2029 s1Url := fmt.Sprintf("nats://ivan:[email protected]:%d", o1.Port)
2030 nc := natsConnect(t, s1Url)
2031 defer nc.Close()
2032 natsPub(t, nc, "foo", []byte("hello"))
2033 natsFlush(t, nc)
2034
2035 // On first send, the message should be sent.
2036 checkCount := func(t *testing.T, c *client, expected int) {
2037 t.Helper()
2038 c.mu.Lock()
2039 out := c.outMsgs
2040 c.mu.Unlock()
2041 if int(out) != expected {
2042 t.Fatalf("Expected %d message(s) to be sent over, got %v", expected, out)
2043 }
2044 }
2045 gwcb := s1.getOutboundGatewayConnection("B")
2046 checkCount(t, gwcb, 1)
2047
2048 // S2 should have sent a protocol indicating no subject interest.
2049 checkNoInterest := func(t *testing.T, subject string, expectedNoInterest bool) {
2050 t.Helper()
2051 checkForSubjectNoInterest(t, gwcb, "$foo", subject, expectedNoInterest, 2*time.Second)
2052 }
2053 checkNoInterest(t, "foo", true)
2054 // Second send should not go through to B
2055 natsPub(t, nc, "foo", []byte("hello"))
2056 natsFlush(t, nc)
2057 checkCount(t, gwcb, 1)
2058
2059 // Now create subscription interest on B (s2)
2060 ch := make(chan bool, 1)
2061 sub := natsSub(t, ncb, "foo", func(_ *nats.Msg) {
2062 ch <- true
2063 })
2064 natsFlush(t, ncb)
2065 checkExpectedSubs(t, 2, s2)
2066 checkExpectedSubs(t, 0, s1)
2067
2068 // This should clear the no interest for this subject
2069 checkNoInterest(t, "foo", false)
2070 // Third send should go to B
2071 natsPub(t, nc, "foo", []byte("hello"))
2072 natsFlush(t, nc)
2073 checkCount(t, gwcb, 2)
2074
2075 // Make sure message is received
2076 waitCh(t, ch, "Did not get our message")
2077 // Now unsubscribe, there won't be an UNSUB sent to the gateway.
2078 natsUnsub(t, sub)
2079 natsFlush(t, ncb)
2080 checkExpectedSubs(t, 1, s2)
2081 checkExpectedSubs(t, 0, s1)
2082
2083 // So now sending a message should go over, but then we should get an RS-
2084 natsPub(t, nc, "foo", []byte("hello"))
2085 natsFlush(t, nc)
2086 checkCount(t, gwcb, 3)
2087
2088 checkNoInterest(t, "foo", true)
2089
2090 // Send one more time and now it should not go to B
2091 natsPub(t, nc, "foo", []byte("hello"))
2092 natsFlush(t, nc)
2093 checkCount(t, gwcb, 3)
2094
2095 // Send on bar, message should go over.
2096 natsPub(t, nc, "bar", []byte("hello"))
2097 natsFlush(t, nc)
2098 checkCount(t, gwcb, 4)
2099
2100 // But now we should have receives an RS- on bar.
2101 checkNoInterest(t, "bar", true)
2102
2103 // Check that wildcards are supported. Create a subscription on '*' on B.
2104 // This should clear the no-interest on both "foo" and "bar"
2105 natsSub(t, ncb, "*", func(_ *nats.Msg) {})
2106 natsFlush(t, ncb)
2107 checkExpectedSubs(t, 2, s2)
2108 checkExpectedSubs(t, 0, s1)
2109 checkNoInterest(t, "foo", false)
2110 checkNoInterest(t, "bar", false)
2111 // Publish on message on foo and one on bar and they should go.
2112 natsPub(t, nc, "foo", []byte("hello"))
2113 natsPub(t, nc, "bar", []byte("hello"))
2114 natsFlush(t, nc)
2115 checkCount(t, gwcb, 6)
2116
2117 // Restart B and that should clear everything on A
2118 ncb.Close()
2119 s2.Shutdown()
2120 s2 = runGatewayServer(o2)
2121 defer s2.Shutdown()
2122
2123 waitForOutboundGateways(t, s1, 1, time.Second)
2124 waitForOutboundGateways(t, s2, 1, time.Second)
2125
2126 ncb = natsConnect(t, s2Url)
2127 defer ncb.Close()
2128 natsSubSync(t, ncb, "not.used")
2129 checkExpectedSubs(t, 1, s2)
2130
2131 gwcb = s1.getOutboundGatewayConnection("B")
2132 checkCount(t, gwcb, 0)
2133 natsPub(t, nc, "foo", []byte("hello"))
2134 natsFlush(t, nc)
2135 checkCount(t, gwcb, 1)
2136
2137 checkNoInterest(t, "foo", true)
2138
2139 natsPub(t, nc, "foo", []byte("hello"))
2140 natsFlush(t, nc)
2141 checkCount(t, gwcb, 1)
2142
2143 // Add a node to B cluster and subscribe there.
2144 // We want to ensure that the no-interest is cleared
2145 // when s2 receives remote SUB from s2bis
2146 o2bis := testGatewayOptionsFromToWithServers(t, "B", "A", s1)
2147 setAccountUserPassInOptions(o2bis, "$foo", "ivan", "password")
2148 o2bis.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", s2.ClusterAddr().Port))
2149 s2bis := runGatewayServer(o2bis)
2150 defer s2bis.Shutdown()
2151
2152 checkClusterFormed(t, s2, s2bis)
2153
2154 // Make sure all outbound gateway connections are setup
2155 waitForOutboundGateways(t, s1, 1, time.Second)
2156 waitForOutboundGateways(t, s2, 1, time.Second)
2157 waitForOutboundGateways(t, s2bis, 1, time.Second)
2158
2159 // A should have 2 inbound
2160 waitForInboundGateways(t, s1, 2, time.Second)
2161
2162 // Create sub on s2bis
2163 ncb2bis := natsConnect(t, fmt.Sprintf("nats://ivan:[email protected]:%d", o2bis.Port))
2164 defer ncb2bis.Close()
2165 natsSub(t, ncb2bis, "foo", func(_ *nats.Msg) {})
2166 natsFlush(t, ncb2bis)
2167
2168 // Wait for subscriptions to be registered locally on s2bis and remotely on s2
2169 checkExpectedSubs(t, 2, s2, s2bis)
2170
2171 // Check that subject no-interest on A was cleared.
2172 checkNoInterest(t, "foo", false)
2173
2174 // Now publish. Remember, s1 has outbound gateway to s2, and s2 does not
2175 // have a local subscription and has previously sent a no-interest on "foo".
2176 // We check that this has been cleared due to the interest on s2bis.
2177 natsPub(t, nc, "foo", []byte("hello"))
2178 natsFlush(t, nc)
2179 checkCount(t, gwcb, 2)
2180 }
2181
2182 func TestGatewayDoesntSendBackToItself(t *testing.T) {
2183 o2 := testDefaultOptionsForGateway("B")
2184 s2 := runGatewayServer(o2)
2185 defer s2.Shutdown()
2186
2187 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
2188 s1 := runGatewayServer(o1)
2189 defer s1.Shutdown()
2190
2191 waitForOutboundGateways(t, s1, 1, time.Second)
2192 waitForOutboundGateways(t, s2, 1, time.Second)
2193
2194 s2Url := fmt.Sprintf("nats://127.0.0.1:%d", o2.Port)
2195 nc2 := natsConnect(t, s2Url)
2196 defer nc2.Close()
2197
2198 count := int32(0)
2199 cb := func(_ *nats.Msg) {
2200 atomic.AddInt32(&count, 1)
2201 }
2202 natsSub(t, nc2, "foo", cb)
2203 natsFlush(t, nc2)
2204
2205 s1Url := fmt.Sprintf("nats://127.0.0.1:%d", o1.Port)
2206 nc1 := natsConnect(t, s1Url)
2207 defer nc1.Close()
2208
2209 natsSub(t, nc1, "foo", cb)
2210 natsFlush(t, nc1)
2211
2212 // Now send 1 message. If there is a cycle, after few ms we
2213 // should have tons of messages...
2214 natsPub(t, nc1, "foo", []byte("cycle"))
2215 natsFlush(t, nc1)
2216 time.Sleep(100 * time.Millisecond)
2217 if c := atomic.LoadInt32(&count); c != 2 {
2218 t.Fatalf("Expected only 2 messages, got %v", c)
2219 }
2220 }
2221
2222 func TestGatewayOrderedOutbounds(t *testing.T) {
2223 o2 := testDefaultOptionsForGateway("B")
2224 s2 := runGatewayServer(o2)
2225 defer s2.Shutdown()
2226
2227 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
2228 s1 := runGatewayServer(o1)
2229 defer s1.Shutdown()
2230
2231 o3 := testGatewayOptionsFromToWithServers(t, "C", "B", s2)
2232 s3 := runGatewayServer(o3)
2233 defer s3.Shutdown()
2234
2235 waitForOutboundGateways(t, s1, 2, time.Second)
2236 waitForOutboundGateways(t, s2, 2, time.Second)
2237 waitForOutboundGateways(t, s3, 2, time.Second)
2238
2239 gws := make([]*client, 0, 2)
2240 s2.getOutboundGatewayConnections(&gws)
2241
2242 // RTTs are expected to be initially 0. So update RTT of first
2243 // in the array so that its value is no longer 0, this should
2244 // cause order to be flipped.
2245 c := gws[0]
2246 c.mu.Lock()
2247 c.sendPing()
2248 c.mu.Unlock()
2249
2250 // Wait a tiny but
2251 time.Sleep(15 * time.Millisecond)
2252 // Get the ordering again.
2253 gws = gws[:0]
2254 s2.getOutboundGatewayConnections(&gws)
2255 // Verify order is correct.
2256 fRTT := gws[0].getRTTValue()
2257 sRTT := gws[1].getRTTValue()
2258 if fRTT > sRTT {
2259 t.Fatalf("Wrong ordering: %v, %v", fRTT, sRTT)
2260 }
2261
2262 // What is the first in the array?
2263 gws[0].mu.Lock()
2264 gwName := gws[0].gw.name
2265 gws[0].mu.Unlock()
2266 if gwName == "A" {
2267 s1.Shutdown()
2268 } else {
2269 s3.Shutdown()
2270 }
2271 waitForOutboundGateways(t, s2, 1, time.Second)
2272 gws = gws[:0]
2273 s2.getOutboundGatewayConnections(&gws)
2274 if len(gws) != 1 {
2275 t.Fatalf("Expected size of outo to be 1, got %v", len(gws))
2276 }
2277 gws[0].mu.Lock()
2278 name := gws[0].gw.name
2279 gws[0].mu.Unlock()
2280 if gwName == name {
2281 t.Fatalf("Gateway %q should have been removed", gwName)
2282 }
2283 // Stop the remaining gateway
2284 if gwName == "A" {
2285 s3.Shutdown()
2286 } else {
2287 s1.Shutdown()
2288 }
2289 waitForOutboundGateways(t, s2, 0, time.Second)
2290 gws = gws[:0]
2291 s2.getOutboundGatewayConnections(&gws)
2292 if len(gws) != 0 {
2293 t.Fatalf("Expected size of outo to be 0, got %v", len(gws))
2294 }
2295 }
2296
2297 func TestGatewayQueueSub(t *testing.T) {
2298 o2 := testDefaultOptionsForGateway("B")
2299 s2 := runGatewayServer(o2)
2300 defer s2.Shutdown()
2301
2302 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
2303 s1 := runGatewayServer(o1)
2304 defer s1.Shutdown()
2305
2306 waitForOutboundGateways(t, s1, 1, time.Second)
2307 waitForOutboundGateways(t, s2, 1, time.Second)
2308
2309 sBUrl := fmt.Sprintf("nats://127.0.0.1:%d", o2.Port)
2310 ncB := natsConnect(t, sBUrl)
2311 defer ncB.Close()
2312
2313 count2 := int32(0)
2314 cb2 := func(_ *nats.Msg) {
2315 atomic.AddInt32(&count2, 1)
2316 }
2317 qsubOnB := natsQueueSub(t, ncB, "foo", "bar", cb2)
2318 natsFlush(t, ncB)
2319
2320 sAUrl := fmt.Sprintf("nats://127.0.0.1:%d", o1.Port)
2321 ncA := natsConnect(t, sAUrl)
2322 defer ncA.Close()
2323
2324 count1 := int32(0)
2325 cb1 := func(_ *nats.Msg) {
2326 atomic.AddInt32(&count1, 1)
2327 }
2328 qsubOnA := natsQueueSub(t, ncA, "foo", "bar", cb1)
2329 natsFlush(t, ncA)
2330
2331 // Make sure subs are registered on each server
2332 checkExpectedSubs(t, 1, s1, s2)
2333 checkForRegisteredQSubInterest(t, s1, "B", globalAccountName, "foo", 1, time.Second)
2334 checkForRegisteredQSubInterest(t, s2, "A", globalAccountName, "foo", 1, time.Second)
2335
2336 total := 100
2337 send := func(t *testing.T, nc *nats.Conn) {
2338 t.Helper()
2339 for i := 0; i < total; i++ {
2340 // Alternate with adding a reply
2341 if i%2 == 0 {
2342 natsPubReq(t, nc, "foo", "reply", []byte("msg"))
2343 } else {
2344 natsPub(t, nc, "foo", []byte("msg"))
2345 }
2346 }
2347 natsFlush(t, nc)
2348 }
2349 // Send from client connecting to S1 (cluster A)
2350 send(t, ncA)
2351
2352 check := func(t *testing.T, count *int32, expected int) {
2353 t.Helper()
2354 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
2355 if n := int(atomic.LoadInt32(count)); n != expected {
2356 return fmt.Errorf("Expected to get %v messages, got %v", expected, n)
2357 }
2358 return nil
2359 })
2360 }
2361 // Check that all messages stay on S1 (cluster A)
2362 check(t, &count1, total)
2363 check(t, &count2, 0)
2364
2365 // Now send from the other side
2366 send(t, ncB)
2367 check(t, &count1, total)
2368 check(t, &count2, total)
2369
2370 // Reset counters
2371 atomic.StoreInt32(&count1, 0)
2372 atomic.StoreInt32(&count2, 0)
2373
2374 // Add different queue group and make sure that messages are received
2375 count3 := int32(0)
2376 cb3 := func(_ *nats.Msg) {
2377 atomic.AddInt32(&count3, 1)
2378 }
2379 batQSub := natsQueueSub(t, ncB, "foo", "bat", cb3)
2380 natsFlush(t, ncB)
2381 checkExpectedSubs(t, 2, s2)
2382
2383 checkForRegisteredQSubInterest(t, s1, "B", globalAccountName, "foo", 2, time.Second)
2384
2385 send(t, ncA)
2386 check(t, &count1, total)
2387 check(t, &count2, 0)
2388 check(t, &count3, total)
2389
2390 // Reset counters
2391 atomic.StoreInt32(&count1, 0)
2392 atomic.StoreInt32(&count2, 0)
2393 atomic.StoreInt32(&count3, 0)
2394
2395 natsUnsub(t, batQSub)
2396 natsFlush(t, ncB)
2397 checkExpectedSubs(t, 1, s2)
2398
2399 checkForRegisteredQSubInterest(t, s1, "B", globalAccountName, "foo", 1, time.Second)
2400
2401 // Stop qsub on A, and send messages to A, they should
2402 // be routed to B.
2403 qsubOnA.Unsubscribe()
2404 checkExpectedSubs(t, 0, s1)
2405 send(t, ncA)
2406 check(t, &count1, 0)
2407 check(t, &count2, total)
2408
2409 // Reset counters
2410 atomic.StoreInt32(&count1, 0)
2411 atomic.StoreInt32(&count2, 0)
2412
2413 // Create a C gateway now
2414 o3 := testGatewayOptionsFromToWithServers(t, "C", "B", s2)
2415 s3 := runGatewayServer(o3)
2416 defer s3.Shutdown()
2417
2418 waitForOutboundGateways(t, s1, 2, time.Second)
2419 waitForOutboundGateways(t, s2, 2, time.Second)
2420 waitForOutboundGateways(t, s3, 2, time.Second)
2421
2422 waitForInboundGateways(t, s1, 2, time.Second)
2423 waitForInboundGateways(t, s2, 2, time.Second)
2424 waitForInboundGateways(t, s3, 2, time.Second)
2425
2426 // Create another qsub "bar"
2427 sCUrl := fmt.Sprintf("nats://127.0.0.1:%d", o3.Port)
2428 ncC := natsConnect(t, sCUrl)
2429 defer ncC.Close()
2430 // Associate this with count1 (since A qsub is no longer running)
2431 natsQueueSub(t, ncC, "foo", "bar", cb1)
2432 natsFlush(t, ncC)
2433 checkExpectedSubs(t, 1, s3)
2434 checkForRegisteredQSubInterest(t, s1, "C", globalAccountName, "foo", 1, time.Second)
2435 checkForRegisteredQSubInterest(t, s2, "C", globalAccountName, "foo", 1, time.Second)
2436
2437 // Artificially bump the RTT from A to C so that
2438 // the code should favor sending to B.
2439 gwcC := s1.getOutboundGatewayConnection("C")
2440 gwcC.mu.Lock()
2441 gwcC.rtt = 10 * time.Second
2442 gwcC.mu.Unlock()
2443 s1.gateway.orderOutboundConnections()
2444
2445 send(t, ncA)
2446 check(t, &count1, 0)
2447 check(t, &count2, total)
2448
2449 // Add a new group on s3 that should receive all messages
2450 natsQueueSub(t, ncC, "foo", "baz", cb3)
2451 natsFlush(t, ncC)
2452 checkExpectedSubs(t, 2, s3)
2453 checkForRegisteredQSubInterest(t, s1, "C", globalAccountName, "foo", 2, time.Second)
2454 checkForRegisteredQSubInterest(t, s2, "C", globalAccountName, "foo", 2, time.Second)
2455
2456 // Reset counters
2457 atomic.StoreInt32(&count1, 0)
2458 atomic.StoreInt32(&count2, 0)
2459
2460 // Make the RTTs equal
2461 gwcC.mu.Lock()
2462 gwcC.rtt = time.Second
2463 gwcC.mu.Unlock()
2464
2465 gwcB := s1.getOutboundGatewayConnection("B")
2466 gwcB.mu.Lock()
2467 gwcB.rtt = time.Second
2468 gwcB.mu.Unlock()
2469
2470 s1.gateway.Lock()
2471 s1.gateway.orderOutboundConnectionsLocked()
2472 destName := s1.gateway.outo[0].gw.name
2473 s1.gateway.Unlock()
2474
2475 send(t, ncA)
2476 // Group baz should receive all messages
2477 check(t, &count3, total)
2478
2479 // Ordering is normally re-evaluated when processing PONGs,
2480 // but rest of the time order will remain the same.
2481 // Since RTT are equal, messages will go to the first
2482 // GW in the array.
2483 if destName == "B" {
2484 check(t, &count2, total)
2485 } else if destName == "C" && int(atomic.LoadInt32(&count2)) != total {
2486 check(t, &count1, total)
2487 }
2488
2489 // Unsubscribe qsub on B and C should receive
2490 // all messages on count1 and count3.
2491 qsubOnB.Unsubscribe()
2492 checkExpectedSubs(t, 0, s2)
2493
2494 // gwcB should have the qsubs interest map empty now.
2495 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
2496 ei, _ := gwcB.gw.outsim.Load(globalAccountName)
2497 if ei != nil {
2498 sl := ei.(*outsie).sl
2499 if sl.Count() == 0 {
2500 return nil
2501 }
2502 }
2503 return fmt.Errorf("Qsub interest for account should have been removed")
2504 })
2505
2506 // Reset counters
2507 atomic.StoreInt32(&count1, 0)
2508 atomic.StoreInt32(&count2, 0)
2509 atomic.StoreInt32(&count3, 0)
2510
2511 send(t, ncA)
2512 check(t, &count1, total)
2513 check(t, &count3, total)
2514 }
2515
2516 func TestGatewayQueueSubNotSuppressedByDeniedLeafQueue(t *testing.T) {
2517 ob := testDefaultOptionsForGateway("B")
2518 sb := runGatewayServer(ob)
2519 defer sb.Shutdown()
2520
2521 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
2522 oa.NoSystemAccount = false
2523 oa.Accounts = []*Account{NewAccount("SYS")}
2524 oa.SystemAccount = "SYS"
2525 oa.LeafNode.Host = "127.0.0.1"
2526 oa.LeafNode.Port = -1
2527 oa.Users = []*User{
2528 {
2529 Username: "leaf",
2530 Password: "pwd",
2531 Permissions: &Permissions{
2532 Publish: &SubjectPermission{Allow: []string{">"}},
2533 Subscribe: &SubjectPermission{
2534 Allow: []string{">"},
2535 Deny: []string{"admin.secret workers"},
2536 },
2537 },
2538 },
2539 }
2540 sa := runGatewayServer(oa)
2541 defer sa.Shutdown()
2542
2543 waitForOutboundGateways(t, sa, 1, time.Second)
2544 waitForOutboundGateways(t, sb, 1, time.Second)
2545
2546 leafURL, err := url.Parse(fmt.Sprintf("nats://leaf:[email protected]:%d", oa.LeafNode.Port))
2547 require_NoError(t, err)
2548 ol := DefaultOptions()
2549 ol.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{leafURL}}}
2550 sl := RunServer(ol)
2551 defer sl.Shutdown()
2552 checkLeafNodeConnected(t, sa)
2553 checkLeafNodeConnected(t, sl)
2554
2555 ncLeaf := natsConnect(t, sl.ClientURL())
2556 defer ncLeaf.Close()
2557 leafSub := natsQueueSubSync(t, ncLeaf, "admin.secret", "workers")
2558 natsFlush(t, ncLeaf)
2559
2560 ncB := natsConnect(t, sb.ClientURL())
2561 defer ncB.Close()
2562 gatewaySub := natsQueueSubSync(t, ncB, "admin.secret", "workers")
2563 natsFlush(t, ncB)
2564
2565 checkForRegisteredQSubInterest(t, sa, "B", globalAccountName, "admin.secret", 1, time.Second)
2566 checkFor(t, time.Second, 10*time.Millisecond, func() error {
2567 if !sa.globalAccount().sl.HasInterest("admin.secret") {
2568 return fmt.Errorf("leaf queue interest has not propagated")
2569 }
2570 return nil
2571 })
2572 checkFor(t, time.Second, 10*time.Millisecond, func() error {
2573 sa.mu.Lock()
2574 leafs := make([]*client, 0, len(sa.leafs))
2575 for _, lc := range sa.leafs {
2576 leafs = append(leafs, lc)
2577 }
2578 sa.mu.Unlock()
2579 for _, lc := range leafs {
2580 lc.mu.Lock()
2581 isGlobal := lc.acc != nil && lc.acc.Name == globalAccountName
2582 denied := isGlobal && lc.mperms != nil && lc.checkDenySub("admin.secret", "workers")
2583 lc.mu.Unlock()
2584 if denied {
2585 return nil
2586 }
2587 }
2588 return fmt.Errorf("leaf queue deny filter has not been initialized")
2589 })
2590
2591 ncA := natsConnect(t, sa.ClientURL())
2592 defer ncA.Close()
2593 natsPub(t, ncA, "admin.secret", []byte("gateway"))
2594 natsFlush(t, ncA)
2595
2596 msg := natsNexMsg(t, gatewaySub, time.Second)
2597 require_Equal(t, "gateway", string(msg.Data))
2598 if _, err := leafSub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
2599 t.Fatalf("Expected leaf queue subscription to be denied, got %v", err)
2600 }
2601 }
2602
2603 func TestGatewayTotalQSubs(t *testing.T) {
2604 ob1 := testDefaultOptionsForGateway("B")
2605 sb1 := runGatewayServer(ob1)
2606 defer sb1.Shutdown()
2607
2608 ob2 := testDefaultOptionsForGateway("B")
2609 ob2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", sb1.ClusterAddr().Port))
2610 sb2 := runGatewayServer(ob2)
2611 defer sb2.Shutdown()
2612
2613 checkClusterFormed(t, sb1, sb2)
2614
2615 sb1URL := fmt.Sprintf("nats://%s:%d", ob1.Host, ob1.Port)
2616 ncb1 := natsConnect(t, sb1URL, nats.ReconnectWait(50*time.Millisecond))
2617 defer ncb1.Close()
2618
2619 sb2URL := fmt.Sprintf("nats://%s:%d", ob2.Host, ob2.Port)
2620 ncb2 := natsConnect(t, sb2URL, nats.ReconnectWait(50*time.Millisecond))
2621 defer ncb2.Close()
2622
2623 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb1)
2624 sa := runGatewayServer(oa)
2625 defer sa.Shutdown()
2626
2627 waitForOutboundGateways(t, sa, 1, 2*time.Second)
2628 waitForOutboundGateways(t, sb1, 1, 2*time.Second)
2629 waitForOutboundGateways(t, sb2, 1, 2*time.Second)
2630 waitForInboundGateways(t, sa, 2, 2*time.Second)
2631 waitForInboundGateways(t, sb1, 1, 2*time.Second)
2632
2633 checkTotalQSubs := func(t *testing.T, s *Server, expected int) {
2634 t.Helper()
2635 checkFor(t, time.Second, 15*time.Millisecond, func() error {
2636 if n := int(atomic.LoadInt64(&s.gateway.totalQSubs)); n != expected {
2637 return fmt.Errorf("Expected TotalQSubs to be %v, got %v", expected, n)
2638 }
2639 return nil
2640 })
2641 }
2642
2643 cb := func(_ *nats.Msg) {}
2644
2645 natsQueueSub(t, ncb1, "foo", "bar", cb)
2646 checkTotalQSubs(t, sa, 1)
2647 qsub2 := natsQueueSub(t, ncb1, "foo", "baz", cb)
2648 checkTotalQSubs(t, sa, 2)
2649 qsub3 := natsQueueSub(t, ncb1, "foo", "baz", cb)
2650 checkTotalQSubs(t, sa, 2)
2651
2652 // Shutdown sb1, there should be a failover from clients
2653 // to sb2. sb2 will then send the queue subs to sa.
2654 sb1.Shutdown()
2655
2656 checkClientsCount(t, sb2, 2)
2657 checkExpectedSubs(t, 3, sb2)
2658
2659 waitForOutboundGateways(t, sa, 1, 2*time.Second)
2660 waitForOutboundGateways(t, sb2, 1, 2*time.Second)
2661 waitForInboundGateways(t, sa, 1, 2*time.Second)
2662 waitForInboundGateways(t, sb2, 1, 2*time.Second)
2663
2664 // When sb1 is shutdown, the total qsubs on sa should fall
2665 // down to 0, but will be updated as soon as sa and sb2
2666 // connect to each other. So instead we will verify by
2667 // making sure that the count is 2 instead of 4 if there
2668 // was a bug.
2669 // (note that there are 2 qsubs on same group, so only
2670 // 1 RS+ would have been sent for that group)
2671 checkTotalQSubs(t, sa, 2)
2672
2673 // Restart sb1
2674 sb1 = runGatewayServer(ob1)
2675 defer sb1.Shutdown()
2676
2677 checkClusterFormed(t, sb1, sb2)
2678
2679 waitForOutboundGateways(t, sa, 1, 2*time.Second)
2680 waitForOutboundGateways(t, sb1, 1, 2*time.Second)
2681 waitForOutboundGateways(t, sb2, 1, 2*time.Second)
2682 waitForInboundGateways(t, sa, 2, 2*time.Second)
2683 waitForInboundGateways(t, sb1, 0, 2*time.Second)
2684 waitForInboundGateways(t, sb2, 1, 2*time.Second)
2685
2686 // Now start unsubscribing. Start with one of the duplicate
2687 // and check that count stays same.
2688 natsUnsub(t, qsub3)
2689 checkTotalQSubs(t, sa, 2)
2690 // Now the other, which would cause an RS-
2691 natsUnsub(t, qsub2)
2692 checkTotalQSubs(t, sa, 1)
2693 // Now test that if connections are closed, things are updated
2694 // properly.
2695 ncb1.Close()
2696 ncb2.Close()
2697 checkTotalQSubs(t, sa, 0)
2698 }
2699
2700 func TestGatewaySendQSubsOnGatewayConnect(t *testing.T) {
2701 o2 := testDefaultOptionsForGateway("B")
2702 s2 := runGatewayServer(o2)
2703 defer s2.Shutdown()
2704
2705 s2Url := fmt.Sprintf("nats://127.0.0.1:%d", o2.Port)
2706 subnc := natsConnect(t, s2Url)
2707 defer subnc.Close()
2708
2709 ch := make(chan bool, 1)
2710 cb := func(_ *nats.Msg) {
2711 ch <- true
2712 }
2713 natsQueueSub(t, subnc, "foo", "bar", cb)
2714 natsFlush(t, subnc)
2715
2716 // Now start s1 that creates a gateway to s2
2717 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
2718 s1 := runGatewayServer(o1)
2719 defer s1.Shutdown()
2720
2721 waitForOutboundGateways(t, s1, 1, time.Second)
2722 waitForOutboundGateways(t, s2, 1, time.Second)
2723
2724 checkForRegisteredQSubInterest(t, s1, "B", globalAccountName, "foo", 1, time.Second)
2725
2726 // Publish from s1, message should be received on s2.
2727 pubnc := natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", o1.Port))
2728 defer pubnc.Close()
2729 // Publish 1 message
2730 natsPub(t, pubnc, "foo", []byte("hello"))
2731 waitCh(t, ch, "Did not get out message")
2732 pubnc.Close()
2733
2734 s1.Shutdown()
2735 s1 = runGatewayServer(o1)
2736 defer s1.Shutdown()
2737
2738 waitForOutboundGateways(t, s1, 1, time.Second)
2739 waitForOutboundGateways(t, s2, 1, time.Second)
2740
2741 checkForRegisteredQSubInterest(t, s1, "B", globalAccountName, "foo", 1, time.Second)
2742
2743 pubnc = natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", o1.Port))
2744 defer pubnc.Close()
2745 // Publish 1 message
2746 natsPub(t, pubnc, "foo", []byte("hello"))
2747 waitCh(t, ch, "Did not get out message")
2748 }
2749
2750 func TestGatewaySendRemoteQSubs(t *testing.T) {
2751 GatewayDoNotForceInterestOnlyMode(true)
2752 defer GatewayDoNotForceInterestOnlyMode(false)
2753
2754 ob1 := testDefaultOptionsForGateway("B")
2755 sb1 := runGatewayServer(ob1)
2756 defer sb1.Shutdown()
2757
2758 ob2 := testDefaultOptionsForGateway("B")
2759 ob2.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", ob1.Cluster.Host, ob1.Cluster.Port))
2760 sb2 := runGatewayServer(ob2)
2761 defer sb2.Shutdown()
2762
2763 checkClusterFormed(t, sb1, sb2)
2764
2765 sbURL := fmt.Sprintf("nats://127.0.0.1:%d", ob2.Port)
2766 subnc := natsConnect(t, sbURL)
2767 defer subnc.Close()
2768
2769 ch := make(chan bool, 1)
2770 cb := func(_ *nats.Msg) {
2771 ch <- true
2772 }
2773 qsub1 := natsQueueSub(t, subnc, "foo", "bar", cb)
2774 qsub2 := natsQueueSub(t, subnc, "foo", "bar", cb)
2775 natsFlush(t, subnc)
2776
2777 // There will be 2 local qsubs on the sb2 server where the client is connected
2778 checkExpectedSubs(t, 2, sb2)
2779 // But only 1 remote on sb1
2780 checkExpectedSubs(t, 1, sb1)
2781
2782 // Now start s1 that creates a gateway to sb1 (the one that does not have the local QSub)
2783 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb1)
2784 sa := runGatewayServer(oa)
2785 defer sa.Shutdown()
2786
2787 waitForOutboundGateways(t, sa, 1, time.Second)
2788 waitForOutboundGateways(t, sb1, 1, time.Second)
2789 waitForOutboundGateways(t, sb2, 1, time.Second)
2790
2791 checkForRegisteredQSubInterest(t, sa, "B", globalAccountName, "foo", 1, time.Second)
2792
2793 // Publish from s1, message should be received on s2.
2794 saURL := fmt.Sprintf("nats://127.0.0.1:%d", oa.Port)
2795 pubnc := natsConnect(t, saURL)
2796 defer pubnc.Close()
2797 // Publish 1 message
2798 natsPub(t, pubnc, "foo", []byte("hello"))
2799 natsFlush(t, pubnc)
2800 waitCh(t, ch, "Did not get out message")
2801
2802 // Note that since cluster B has no plain sub, an "RS- $G foo" will have been sent.
2803 // Wait for the no interest to be received by A
2804 checkFor(t, time.Second, 15*time.Millisecond, func() error {
2805 gw := sa.getOutboundGatewayConnection("B").gw
2806 ei, _ := gw.outsim.Load(globalAccountName)
2807 if ei != nil {
2808 e := ei.(*outsie)
2809 e.RLock()
2810 defer e.RUnlock()
2811 if _, inMap := e.ni["foo"]; inMap {
2812 return nil
2813 }
2814 }
2815 return fmt.Errorf("No-interest still not registered")
2816 })
2817
2818 // Unsubscribe 1 qsub
2819 natsUnsub(t, qsub1)
2820 natsFlush(t, subnc)
2821 // There should be only 1 local qsub on sb2 now, and the remote should still exist on sb1
2822 checkExpectedSubs(t, 1, sb1, sb2)
2823
2824 // Publish 1 message
2825 natsPub(t, pubnc, "foo", []byte("hello"))
2826 natsFlush(t, pubnc)
2827 waitCh(t, ch, "Did not get out message")
2828
2829 // Unsubscribe the remaining
2830 natsUnsub(t, qsub2)
2831 natsFlush(t, subnc)
2832
2833 // No more subs now on both sb1 and sb2
2834 checkExpectedSubs(t, 0, sb1, sb2)
2835
2836 // Server sb1 should not have qsub in its sub interest map
2837 checkFor(t, time.Second, 15*time.Millisecond, func() error {
2838 var entry *sitally
2839 var err error
2840 sb1.gateway.pasi.Lock()
2841 asim := sb1.gateway.pasi.m[globalAccountName]
2842 if asim != nil {
2843 entry = asim["foo bar"]
2844 }
2845 if entry != nil {
2846 err = fmt.Errorf("Map should not have an entry, got %#v", entry)
2847 }
2848 sb1.gateway.pasi.Unlock()
2849 return err
2850 })
2851
2852 // Let's wait for A to receive the unsubscribe
2853 checkFor(t, time.Second, 15*time.Millisecond, func() error {
2854 gw := sa.getOutboundGatewayConnection("B").gw
2855 ei, _ := gw.outsim.Load(globalAccountName)
2856 if ei != nil {
2857 sl := ei.(*outsie).sl
2858 if sl.Count() == 0 {
2859 return nil
2860 }
2861 }
2862 return fmt.Errorf("Interest still present")
2863 })
2864
2865 // Now send a message, it won't be sent because A received an RS-
2866 // on the first published message since there was no plain sub interest.
2867 natsPub(t, pubnc, "foo", []byte("hello"))
2868 natsFlush(t, pubnc)
2869
2870 // Get the gateway connection from A (sa) to B (sb1)
2871 gw := sa.getOutboundGatewayConnection("B")
2872 gw.mu.Lock()
2873 out := gw.outMsgs
2874 gw.mu.Unlock()
2875 if out != 2 {
2876 t.Fatalf("Expected 2 out messages, got %v", out)
2877 }
2878
2879 // Restart A
2880 pubnc.Close()
2881 sa.Shutdown()
2882 sa = runGatewayServer(oa)
2883 defer sa.Shutdown()
2884
2885 waitForOutboundGateways(t, sa, 1, time.Second)
2886
2887 // Check qsubs interest should be empty
2888 checkFor(t, time.Second, 15*time.Millisecond, func() error {
2889 gw := sa.getOutboundGatewayConnection("B").gw
2890 if ei, _ := gw.outsim.Load(globalAccountName); ei == nil {
2891 return nil
2892 }
2893 return fmt.Errorf("Interest still present")
2894 })
2895 }
2896
2897 func TestGatewayComplexSetup(t *testing.T) {
2898 doLog := false
2899
2900 // This test will have the following setup:
2901 // --- means route connection
2902 // === means gateway connection
2903 // [o] is outbound
2904 // [i] is inbound
2905 // Each server as an outbound connection to the other cluster.
2906 // It may have 0 or more inbound connection(s).
2907 //
2908 // Cluster A Cluster B
2909 // sa1 [o]===========>[i]
2910 // | [i]<===========[o]
2911 // | sb1 ------- sb2
2912 // | [i] [o]
2913 // sa2 [o]=============^ ||
2914 // [i]<========================||
2915 ob1 := testDefaultOptionsForGateway("B")
2916 sb1 := runGatewayServer(ob1)
2917 defer sb1.Shutdown()
2918 if doLog {
2919 sb1.SetLogger(logger.NewTestLogger("[B1] - ", true), true, true)
2920 }
2921
2922 oa1 := testGatewayOptionsFromToWithServers(t, "A", "B", sb1)
2923 sa1 := runGatewayServer(oa1)
2924 defer sa1.Shutdown()
2925 if doLog {
2926 sa1.SetLogger(logger.NewTestLogger("[A1] - ", true), true, true)
2927 }
2928
2929 waitForOutboundGateways(t, sa1, 1, time.Second)
2930 waitForOutboundGateways(t, sb1, 1, time.Second)
2931
2932 waitForInboundGateways(t, sa1, 1, time.Second)
2933 waitForInboundGateways(t, sb1, 1, time.Second)
2934
2935 oa2 := testGatewayOptionsFromToWithServers(t, "A", "B", sb1)
2936 oa2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", sa1.ClusterAddr().Port))
2937 sa2 := runGatewayServer(oa2)
2938 defer sa2.Shutdown()
2939 if doLog {
2940 sa2.SetLogger(logger.NewTestLogger("[A2] - ", true), true, true)
2941 }
2942
2943 checkClusterFormed(t, sa1, sa2)
2944
2945 waitForOutboundGateways(t, sa2, 1, time.Second)
2946 waitForInboundGateways(t, sb1, 2, time.Second)
2947
2948 ob2 := testGatewayOptionsFromToWithServers(t, "B", "A", sa2)
2949 ob2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", sb1.ClusterAddr().Port))
2950 var sb2 *Server
2951 for {
2952 sb2 = runGatewayServer(ob2)
2953 defer sb2.Shutdown()
2954
2955 checkClusterFormed(t, sb1, sb2)
2956
2957 waitForOutboundGateways(t, sb2, 1, time.Second)
2958 waitForInboundGateways(t, sb2, 0, time.Second)
2959 // For this test, we want the outbound to be to sa2, so if we don't have that,
2960 // restart sb2 until we get lucky.
2961 time.Sleep(100 * time.Millisecond)
2962 if sa2.numInboundGateways() == 0 {
2963 sb2.Shutdown()
2964 sb2 = nil
2965 } else {
2966 break
2967 }
2968 }
2969 if doLog {
2970 sb2.SetLogger(logger.NewTestLogger("[B2] - ", true), true, true)
2971 }
2972
2973 ch := make(chan bool, 1)
2974 cb := func(_ *nats.Msg) {
2975 ch <- true
2976 }
2977
2978 // Create a subscription on sa1 and sa2.
2979 ncsa1 := natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", oa1.Port))
2980 defer ncsa1.Close()
2981 sub1 := natsSub(t, ncsa1, "foo", cb)
2982 natsFlush(t, ncsa1)
2983
2984 ncsa2 := natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", oa2.Port))
2985 defer ncsa2.Close()
2986 sub2 := natsSub(t, ncsa2, "foo", cb)
2987 natsFlush(t, ncsa2)
2988
2989 // sa1 will have 1 local, one remote (from sa2), same for sa2.
2990 checkExpectedSubs(t, 2, sa1, sa2)
2991
2992 // Connect to sb2 and send 1 message
2993 ncsb2 := natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", ob2.Port))
2994 defer ncsb2.Close()
2995 natsPub(t, ncsb2, "foo", []byte("hello"))
2996 natsFlush(t, ncsb2)
2997
2998 for i := 0; i < 2; i++ {
2999 waitCh(t, ch, "Did not get our message")
3000 }
3001
3002 // Unsubscribe sub2, and send 1, should still get it.
3003 natsUnsub(t, sub2)
3004 natsFlush(t, ncsa2)
3005 natsPub(t, ncsb2, "foo", []byte("hello"))
3006 natsFlush(t, ncsb2)
3007 waitCh(t, ch, "Did not get our message")
3008
3009 // Unsubscribe sub1, all server's sublist should be empty
3010 sub1.Unsubscribe()
3011 natsFlush(t, ncsa1)
3012
3013 checkExpectedSubs(t, 0, sa1, sa2, sb1, sb2)
3014
3015 // Create queue subs
3016 total := 100
3017 c1 := int32(0)
3018 c2 := int32(0)
3019 c3 := int32(0)
3020 tc := int32(0)
3021 natsQueueSub(t, ncsa1, "foo", "bar", func(_ *nats.Msg) {
3022 atomic.AddInt32(&c1, 1)
3023 if c := atomic.AddInt32(&tc, 1); int(c) == total {
3024 ch <- true
3025 }
3026 })
3027 natsFlush(t, ncsa1)
3028 natsQueueSub(t, ncsa2, "foo", "bar", func(_ *nats.Msg) {
3029 atomic.AddInt32(&c2, 1)
3030 if c := atomic.AddInt32(&tc, 1); int(c) == total {
3031 ch <- true
3032 }
3033 })
3034 natsFlush(t, ncsa2)
3035 checkExpectedSubs(t, 2, sa1, sa2)
3036
3037 qsubOnB2 := natsQueueSub(t, ncsb2, "foo", "bar", func(_ *nats.Msg) {
3038 atomic.AddInt32(&c3, 1)
3039 if c := atomic.AddInt32(&tc, 1); int(c) == total {
3040 ch <- true
3041 }
3042 })
3043 natsFlush(t, ncsb2)
3044 checkExpectedSubs(t, 1, sb2)
3045
3046 checkForRegisteredQSubInterest(t, sb1, "A", globalAccountName, "foo", 1, time.Second)
3047
3048 // Publish all messages. The queue sub on cluster B should receive all
3049 // messages.
3050 for i := 0; i < total; i++ {
3051 natsPub(t, ncsb2, "foo", []byte("msg"))
3052 }
3053 natsFlush(t, ncsb2)
3054
3055 waitCh(t, ch, "Did not get all our queue messages")
3056 if n := int(atomic.LoadInt32(&c1)); n != 0 {
3057 t.Fatalf("No message should have been received by qsub1, got %v", n)
3058 }
3059 if n := int(atomic.LoadInt32(&c2)); n != 0 {
3060 t.Fatalf("No message should have been received by qsub2, got %v", n)
3061 }
3062 if n := int(atomic.LoadInt32(&c3)); n != total {
3063 t.Fatalf("All messages should have been delivered to qsub on B, got %v", n)
3064 }
3065
3066 // Reset counters
3067 atomic.StoreInt32(&c1, 0)
3068 atomic.StoreInt32(&c2, 0)
3069 atomic.StoreInt32(&c3, 0)
3070 atomic.StoreInt32(&tc, 0)
3071
3072 // Now send from cluster A, messages should be distributed to qsubs on A.
3073 for i := 0; i < total; i++ {
3074 natsPub(t, ncsa1, "foo", []byte("msg"))
3075 }
3076 natsFlush(t, ncsa1)
3077
3078 expectedLow := int(float32(total/2) * 0.6)
3079 expectedHigh := int(float32(total/2) * 1.4)
3080 checkCount := func(t *testing.T, count *int32) {
3081 t.Helper()
3082 c := int(atomic.LoadInt32(count))
3083 if c < expectedLow || c > expectedHigh {
3084 t.Fatalf("Expected value to be between %v/%v, got %v", expectedLow, expectedHigh, c)
3085 }
3086 }
3087 waitCh(t, ch, "Did not get all our queue messages")
3088 checkCount(t, &c1)
3089 checkCount(t, &c2)
3090
3091 // Now unsubscribe sub on B and reset counters
3092 natsUnsub(t, qsubOnB2)
3093 checkExpectedSubs(t, 0, sb2)
3094 atomic.StoreInt32(&c1, 0)
3095 atomic.StoreInt32(&c2, 0)
3096 atomic.StoreInt32(&c3, 0)
3097 atomic.StoreInt32(&tc, 0)
3098 // Publish from cluster B, messages should be delivered to cluster A.
3099 for i := 0; i < total; i++ {
3100 natsPub(t, ncsb2, "foo", []byte("msg"))
3101 }
3102 natsFlush(t, ncsb2)
3103
3104 waitCh(t, ch, "Did not get all our queue messages")
3105 if n := int(atomic.LoadInt32(&c3)); n != 0 {
3106 t.Fatalf("There should not have been messages on unsubscribed sub, got %v", n)
3107 }
3108 checkCount(t, &c1)
3109 checkCount(t, &c2)
3110 }
3111
3112 func TestGatewayMsgSentOnlyOnce(t *testing.T) {
3113 o2 := testDefaultOptionsForGateway("B")
3114 s2 := runGatewayServer(o2)
3115 defer s2.Shutdown()
3116
3117 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
3118 s1 := runGatewayServer(o1)
3119 defer s1.Shutdown()
3120
3121 waitForOutboundGateways(t, s1, 1, time.Second)
3122 waitForOutboundGateways(t, s2, 1, time.Second)
3123
3124 s2Url := fmt.Sprintf("nats://127.0.0.1:%d", o2.Port)
3125 nc2 := natsConnect(t, s2Url)
3126 defer nc2.Close()
3127
3128 s1Url := fmt.Sprintf("nats://127.0.0.1:%d", o1.Port)
3129 nc1 := natsConnect(t, s1Url)
3130 defer nc1.Close()
3131
3132 ch := make(chan bool, 1)
3133 count := int32(0)
3134 expected := int32(4)
3135 cb := func(_ *nats.Msg) {
3136 if c := atomic.AddInt32(&count, 1); c == expected {
3137 ch <- true
3138 }
3139 }
3140
3141 // On s1, create 2 plain subs, 2 queue members for group
3142 // "bar" and 1 for group "baz".
3143 natsSub(t, nc1, ">", cb)
3144 natsSub(t, nc1, "foo", cb)
3145 natsQueueSub(t, nc1, "foo", "bar", cb)
3146 natsQueueSub(t, nc1, "foo", "bar", cb)
3147 natsQueueSub(t, nc1, "foo", "baz", cb)
3148 natsFlush(t, nc1)
3149
3150 // Ensure subs registered in S1
3151 checkExpectedSubs(t, 5, s1)
3152
3153 // Also need to wait for qsubs to be registered on s2.
3154 checkForRegisteredQSubInterest(t, s2, "A", globalAccountName, "foo", 2, time.Second)
3155
3156 // From s2, send 1 message, s1 should receive 1 only,
3157 // and total we should get the callback notified 4 times.
3158 natsPub(t, nc2, "foo", []byte("hello"))
3159 natsFlush(t, nc2)
3160
3161 waitCh(t, ch, "Did not get our messages")
3162 // Verifiy that count is still 4
3163 if c := atomic.LoadInt32(&count); c != expected {
3164 t.Fatalf("Expected %v messages, got %v", expected, c)
3165 }
3166 // Check s2 outbound connection stats. It should say that it
3167 // sent only 1 message.
3168 c := s2.getOutboundGatewayConnection("A")
3169 if c == nil {
3170 t.Fatalf("S2 outbound gateway not found")
3171 }
3172 c.mu.Lock()
3173 out := c.outMsgs
3174 c.mu.Unlock()
3175 if out != 1 {
3176 t.Fatalf("Expected s2's outbound gateway to have sent a single message, got %v", out)
3177 }
3178 // Now check s1's inbound gateway
3179 s1.gateway.RLock()
3180 c = nil
3181 for _, ci := range s1.gateway.in {
3182 c = ci
3183 break
3184 }
3185 s1.gateway.RUnlock()
3186 if c == nil {
3187 t.Fatalf("S1 inbound gateway not found")
3188 }
3189 if in := atomic.LoadInt64(&c.inMsgs); in != 1 {
3190 t.Fatalf("Expected s1's inbound gateway to have received a single message, got %v", in)
3191 }
3192 }
3193
3194 type checkErrorLogger struct {
3195 DummyLogger
3196 checkErrorStr string
3197 gotError bool
3198 }
3199
3200 func (l *checkErrorLogger) Errorf(format string, args ...any) {
3201 l.DummyLogger.Errorf(format, args...)
3202 l.Lock()
3203 if strings.Contains(l.Msg, l.checkErrorStr) {
3204 l.gotError = true
3205 }
3206 l.Unlock()
3207 }
3208
3209 func TestGatewayRoutedServerWithoutGatewayConfigured(t *testing.T) {
3210 o2 := testDefaultOptionsForGateway("B")
3211 s2 := runGatewayServer(o2)
3212 defer s2.Shutdown()
3213
3214 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
3215 s1 := runGatewayServer(o1)
3216 defer s1.Shutdown()
3217
3218 waitForOutboundGateways(t, s1, 1, time.Second)
3219 waitForOutboundGateways(t, s2, 1, time.Second)
3220
3221 o3 := DefaultOptions()
3222 o3.NoSystemAccount = true
3223 o3.Cluster.Name = "B"
3224 o3.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", s2.ClusterAddr().Port))
3225 s3 := New(o3)
3226 defer s3.Shutdown()
3227 l := &checkErrorLogger{checkErrorStr: "not configured"}
3228 s3.SetLogger(l, true, true)
3229 wg := sync.WaitGroup{}
3230 wg.Add(1)
3231 go func() {
3232 s3.Start()
3233 wg.Done()
3234 }()
3235
3236 checkClusterFormed(t, s2, s3)
3237
3238 // Check that server s3 does not panic when being notified
3239 // about the A gateway, but report an error.
3240 deadline := time.Now().Add(2 * time.Second)
3241 gotIt := false
3242 for time.Now().Before(deadline) {
3243 l.Lock()
3244 gotIt = l.gotError
3245 l.Unlock()
3246 if gotIt {
3247 break
3248 }
3249 time.Sleep(15 * time.Millisecond)
3250 }
3251 if !gotIt {
3252 t.Fatalf("Should have reported error about gateway not configured")
3253 }
3254
3255 s3.Shutdown()
3256 wg.Wait()
3257 }
3258
3259 func TestGatewaySendsToNonLocalSubs(t *testing.T) {
3260 ob1 := testDefaultOptionsForGateway("B")
3261 sb1 := runGatewayServer(ob1)
3262 defer sb1.Shutdown()
3263
3264 oa1 := testGatewayOptionsFromToWithServers(t, "A", "B", sb1)
3265 sa1 := runGatewayServer(oa1)
3266 defer sa1.Shutdown()
3267
3268 waitForOutboundGateways(t, sa1, 1, time.Second)
3269 waitForOutboundGateways(t, sb1, 1, time.Second)
3270
3271 waitForInboundGateways(t, sa1, 1, time.Second)
3272 waitForInboundGateways(t, sb1, 1, time.Second)
3273
3274 oa2 := testGatewayOptionsFromToWithServers(t, "A", "B", sb1)
3275 oa2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", sa1.ClusterAddr().Port))
3276 sa2 := runGatewayServer(oa2)
3277 defer sa2.Shutdown()
3278
3279 checkClusterFormed(t, sa1, sa2)
3280
3281 waitForOutboundGateways(t, sa2, 1, time.Second)
3282 waitForInboundGateways(t, sb1, 2, time.Second)
3283
3284 ch := make(chan bool, 1)
3285 // Create an interest of sa2
3286 ncSub := natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", oa2.Port))
3287 defer ncSub.Close()
3288 natsSub(t, ncSub, "foo", func(_ *nats.Msg) { ch <- true })
3289 natsFlush(t, ncSub)
3290 checkExpectedSubs(t, 1, sa1, sa2)
3291
3292 // Produce a message from sb1, make sure it can be received.
3293 ncPub := natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", ob1.Port))
3294 defer ncPub.Close()
3295 natsPub(t, ncPub, "foo", []byte("hello"))
3296 waitCh(t, ch, "Did not get our message")
3297
3298 ncSub.Close()
3299 ncPub.Close()
3300 checkExpectedSubs(t, 0, sa1, sa2)
3301
3302 // Now create sb2 that has a route to sb1 and gateway connects to sa2.
3303 ob2 := testGatewayOptionsFromToWithServers(t, "B", "A", sa2)
3304 ob2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", sb1.ClusterAddr().Port))
3305 sb2 := runGatewayServer(ob2)
3306 defer sb2.Shutdown()
3307
3308 checkClusterFormed(t, sb1, sb2)
3309 waitForOutboundGateways(t, sb2, 1, time.Second)
3310
3311 ncSub = natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", oa1.Port))
3312 defer ncSub.Close()
3313 natsSub(t, ncSub, "foo", func(_ *nats.Msg) { ch <- true })
3314 natsFlush(t, ncSub)
3315 checkExpectedSubs(t, 1, sa1, sa2)
3316
3317 ncPub = natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", ob2.Port))
3318 defer ncPub.Close()
3319 natsPub(t, ncPub, "foo", []byte("hello"))
3320 waitCh(t, ch, "Did not get our message")
3321 }
3322
3323 func TestGatewayUnknownGatewayCommand(t *testing.T) {
3324 o1 := testDefaultOptionsForGateway("A")
3325 s1 := runGatewayServer(o1)
3326 defer s1.Shutdown()
3327
3328 l := &checkErrorLogger{checkErrorStr: "Unknown command"}
3329 s1.SetLogger(l, true, true)
3330
3331 o2 := testDefaultOptionsForGateway("A")
3332 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", s1.ClusterAddr().Port))
3333 s2 := runGatewayServer(o2)
3334 defer s2.Shutdown()
3335
3336 checkClusterFormed(t, s1, s2)
3337
3338 var route *client
3339 s2.mu.Lock()
3340 if r := getFirstRoute(s2); r != nil {
3341 route = r
3342 }
3343 s2.mu.Unlock()
3344
3345 route.mu.Lock()
3346 info := &Info{
3347 Gateway: "B",
3348 GatewayCmd: 255,
3349 }
3350 b, _ := json.Marshal(info)
3351 route.enqueueProto([]byte(fmt.Sprintf(InfoProto, b)))
3352 route.mu.Unlock()
3353
3354 checkFor(t, time.Second, 15*time.Millisecond, func() error {
3355 l.Lock()
3356 gotIt := l.gotError
3357 l.Unlock()
3358 if gotIt {
3359 return nil
3360 }
3361 return fmt.Errorf("Did not get expected error")
3362 })
3363 }
3364
3365 func TestGatewayRandomIP(t *testing.T) {
3366 ob := testDefaultOptionsForGateway("B")
3367 sb := runGatewayServer(ob)
3368 defer sb.Shutdown()
3369
3370 oa := testGatewayOptionsFromToWithURLs(t, "A", "B",
3371 []string{
3372 "nats://noport",
3373 fmt.Sprintf("nats://localhost:%d", sb.GatewayAddr().Port),
3374 })
3375 // Create a dummy resolver that returns error since we
3376 // don't provide any IP. The code should then use the configured
3377 // url (localhost:port) and try with that, which in this case
3378 // should work.
3379 oa.Gateway.resolver = &myDummyDNSResolver{}
3380 sa := runGatewayServer(oa)
3381 defer sa.Shutdown()
3382
3383 waitForOutboundGateways(t, sa, 1, 2*time.Second)
3384 waitForOutboundGateways(t, sb, 1, 2*time.Second)
3385 }
3386
3387 func TestGatewaySendQSubsBufSize(t *testing.T) {
3388 for _, test := range []struct {
3389 name string
3390 bufSize int
3391 }{
3392 {
3393 name: "Bufsize 45, more than one at a time",
3394 bufSize: 45,
3395 },
3396 {
3397 name: "Bufsize 15, one at a time",
3398 bufSize: 15,
3399 },
3400 {
3401 name: "Bufsize 0, default to maxBufSize, all at once",
3402 bufSize: 0,
3403 },
3404 } {
3405 t.Run(test.name, func(t *testing.T) {
3406
3407 o2 := testDefaultOptionsForGateway("B")
3408 o2.Gateway.sendQSubsBufSize = test.bufSize
3409 s2 := runGatewayServer(o2)
3410 defer s2.Shutdown()
3411
3412 s2Url := fmt.Sprintf("nats://%s:%d", o2.Host, o2.Port)
3413 nc := natsConnect(t, s2Url)
3414 defer nc.Close()
3415 natsQueueSub(t, nc, "foo", "bar", func(_ *nats.Msg) {})
3416 natsQueueSub(t, nc, "foo", "baz", func(_ *nats.Msg) {})
3417 natsQueueSub(t, nc, "foo", "bat", func(_ *nats.Msg) {})
3418 natsQueueSub(t, nc, "foo", "bax", func(_ *nats.Msg) {})
3419
3420 checkExpectedSubs(t, 4, s2)
3421
3422 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
3423 s1 := runGatewayServer(o1)
3424 defer s1.Shutdown()
3425
3426 waitForOutboundGateways(t, s1, 1, time.Second)
3427 waitForOutboundGateways(t, s2, 1, time.Second)
3428
3429 checkForRegisteredQSubInterest(t, s1, "B", globalAccountName, "foo", 4, time.Second)
3430
3431 // Make sure we have the 4 we expected
3432 c := s1.getOutboundGatewayConnection("B")
3433 ei, _ := c.gw.outsim.Load(globalAccountName)
3434 if ei == nil {
3435 t.Fatalf("No interest found")
3436 }
3437 sl := ei.(*outsie).sl
3438 r := sl.Match("foo")
3439 if len(r.qsubs) != 4 {
3440 t.Fatalf("Expected 4 groups, got %v", len(r.qsubs))
3441 }
3442 var gotBar, gotBaz, gotBat, gotBax bool
3443 for _, qs := range r.qsubs {
3444 if len(qs) != 1 {
3445 t.Fatalf("Unexpected number of subs for group %s: %v", qs[0].queue, len(qs))
3446 }
3447 q := qs[0].queue
3448 switch string(q) {
3449 case "bar":
3450 gotBar = true
3451 case "baz":
3452 gotBaz = true
3453 case "bat":
3454 gotBat = true
3455 case "bax":
3456 gotBax = true
3457 default:
3458 t.Fatalf("Unexpected group name: %s", q)
3459 }
3460 }
3461 if !gotBar || !gotBaz || !gotBat || !gotBax {
3462 t.Fatalf("Did not get all we wanted: bar=%v baz=%v bat=%v bax=%v",
3463 gotBar, gotBaz, gotBat, gotBax)
3464 }
3465
3466 nc.Close()
3467 s1.Shutdown()
3468 s2.Shutdown()
3469
3470 waitForOutboundGateways(t, s1, 0, time.Second)
3471 waitForOutboundGateways(t, s2, 0, time.Second)
3472 })
3473 }
3474 }
3475
3476 func TestGatewayRaceBetweenPubAndSub(t *testing.T) {
3477 o2 := testDefaultOptionsForGateway("B")
3478 s2 := runGatewayServer(o2)
3479 defer s2.Shutdown()
3480
3481 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
3482 s1 := runGatewayServer(o1)
3483 defer s1.Shutdown()
3484
3485 waitForOutboundGateways(t, s1, 1, time.Second)
3486 waitForOutboundGateways(t, s2, 1, time.Second)
3487
3488 s2Url := fmt.Sprintf("nats://127.0.0.1:%d", o2.Port)
3489 nc2 := natsConnect(t, s2Url)
3490 defer nc2.Close()
3491
3492 s1Url := fmt.Sprintf("nats://127.0.0.1:%d", o1.Port)
3493 var ncaa [5]*nats.Conn
3494 var nca = ncaa[:0]
3495 for i := 0; i < 5; i++ {
3496 nc := natsConnect(t, s1Url)
3497 defer nc.Close()
3498 nca = append(nca, nc)
3499 }
3500
3501 ch := make(chan bool, 1)
3502 wg := sync.WaitGroup{}
3503 wg.Add(5)
3504 for _, nc := range nca {
3505 nc := nc
3506 go func(n *nats.Conn) {
3507 defer wg.Done()
3508 for {
3509 n.Publish("foo", []byte("hello"))
3510 select {
3511 case <-ch:
3512 return
3513 default:
3514 }
3515 }
3516 }(nc)
3517 }
3518 time.Sleep(100 * time.Millisecond)
3519 natsQueueSub(t, nc2, "foo", "bar", func(m *nats.Msg) {
3520 natsUnsub(t, m.Sub)
3521 close(ch)
3522 })
3523 wg.Wait()
3524 }
3525
3526 // Returns the first (if any) of the inbound connections for this name.
3527 func getInboundGatewayConnection(s *Server, name string) *client {
3528 var gwsa [4]*client
3529 var gws = gwsa[:0]
3530 s.getInboundGatewayConnections(&gws)
3531 for _, gw := range gws {
3532 gw.mu.Lock()
3533 ok := gw.gw.name == name
3534 gw.mu.Unlock()
3535 if ok {
3536 return gw
3537 }
3538 }
3539 return nil
3540 }
3541
3542 func TestGatewaySendAllSubs(t *testing.T) {
3543 GatewayDoNotForceInterestOnlyMode(true)
3544 defer GatewayDoNotForceInterestOnlyMode(false)
3545
3546 gatewayMaxRUnsubBeforeSwitch = 100
3547 defer func() { gatewayMaxRUnsubBeforeSwitch = defaultGatewayMaxRUnsubBeforeSwitch }()
3548
3549 ob := testDefaultOptionsForGateway("B")
3550 sb := runGatewayServer(ob)
3551 defer sb.Shutdown()
3552
3553 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
3554 sa := runGatewayServer(oa)
3555 defer sa.Shutdown()
3556
3557 oc := testGatewayOptionsFromToWithServers(t, "C", "B", sb)
3558 sc := runGatewayServer(oc)
3559 defer sc.Shutdown()
3560
3561 waitForOutboundGateways(t, sa, 2, time.Second)
3562 waitForOutboundGateways(t, sb, 2, time.Second)
3563 waitForOutboundGateways(t, sc, 2, time.Second)
3564 waitForInboundGateways(t, sa, 2, time.Second)
3565 waitForInboundGateways(t, sb, 2, time.Second)
3566 waitForInboundGateways(t, sc, 2, time.Second)
3567
3568 // On A, create a sub to register some interest
3569 aURL := fmt.Sprintf("nats://%s:%d", oa.Host, oa.Port)
3570 ncA := natsConnect(t, aURL)
3571 defer ncA.Close()
3572 natsSub(t, ncA, "sub.on.a.*", func(m *nats.Msg) {})
3573 natsFlush(t, ncA)
3574 checkExpectedSubs(t, 1, sa)
3575
3576 // On C, have some sub activity while it receives
3577 // unwanted messages and switches to interestOnly mode.
3578 cURL := fmt.Sprintf("nats://%s:%d", oc.Host, oc.Port)
3579 ncC := natsConnect(t, cURL)
3580 defer ncC.Close()
3581 wg := sync.WaitGroup{}
3582 wg.Add(2)
3583 done := make(chan bool)
3584 consCount := 0
3585 accsCount := 0
3586 go func() {
3587 defer wg.Done()
3588 for i := 0; ; i++ {
3589 // Create subs and qsubs on same subject
3590 natsSub(t, ncC, fmt.Sprintf("foo.%d", i+1), func(_ *nats.Msg) {})
3591 natsQueueSub(t, ncC, fmt.Sprintf("foo.%d", i+1), fmt.Sprintf("bar.%d", i+1), func(_ *nats.Msg) {})
3592 // Create psubs and qsubs on unique subjects
3593 natsSub(t, ncC, fmt.Sprintf("foox.%d", i+1), func(_ *nats.Msg) {})
3594 natsQueueSub(t, ncC, fmt.Sprintf("fooy.%d", i+1), fmt.Sprintf("bar.%d", i+1), func(_ *nats.Msg) {})
3595 consCount += 4
3596 // Register account
3597 sc.RegisterAccount(fmt.Sprintf("acc.%d", i+1))
3598 accsCount++
3599 select {
3600 case <-done:
3601 return
3602 case <-time.After(15 * time.Millisecond):
3603 }
3604 }
3605 }()
3606
3607 // From B publish on subjects for which C has an interest
3608 bURL := fmt.Sprintf("nats://%s:%d", ob.Host, ob.Port)
3609 ncB := natsConnect(t, bURL)
3610 defer ncB.Close()
3611
3612 go func() {
3613 defer wg.Done()
3614 time.Sleep(10 * time.Millisecond)
3615 for {
3616 for i := 0; i < 10; i++ {
3617 natsPub(t, ncB, fmt.Sprintf("foo.%d", i+1), []byte("hello"))
3618 }
3619 select {
3620 case <-done:
3621 return
3622 case <-time.After(5 * time.Millisecond):
3623 }
3624 }
3625 }()
3626
3627 // From B, send a lot of messages that A is interested in,
3628 // but not C.
3629 // TODO(ik): May need to change that if we change the threshold
3630 // for when the switch happens.
3631 total := 300
3632 for i := 0; i < total; i++ {
3633 if err := ncB.Publish(fmt.Sprintf("sub.on.a.%d", i), []byte("hi")); err != nil {
3634 t.Fatalf("Error waiting for reply: %v", err)
3635 }
3636 }
3637 close(done)
3638
3639 // Normally, C would receive a message for each req inbox and
3640 // would send and RS- on that to B, making both have an unbounded
3641 // growth of the no-interest map. But after a certain amount
3642 // of RS-, C will send all its sub for the given account and
3643 // instruct B to send only if there is explicit interest.
3644 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
3645 // Check C inbound connection from B
3646 c := getInboundGatewayConnection(sc, "B")
3647 c.mu.Lock()
3648 var switchedMode bool
3649 e := c.gw.insim[globalAccountName]
3650 if e != nil {
3651 switchedMode = e.ni == nil && e.mode == InterestOnly
3652 }
3653 c.mu.Unlock()
3654 if !switchedMode {
3655 return fmt.Errorf("C has still not switched mode")
3656 }
3657 return nil
3658 })
3659 checkGWInterestOnlyMode(t, sb, "C", globalAccountName)
3660 wg.Wait()
3661
3662 // Check consCount and accsCount on C
3663 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
3664 sc.gateway.pasi.Lock()
3665 scount := len(sc.gateway.pasi.m[globalAccountName])
3666 sc.gateway.pasi.Unlock()
3667 if scount != consCount {
3668 return fmt.Errorf("Expected %v consumers for global account, got %v", consCount, scount)
3669 }
3670 acount := sc.numAccounts()
3671 if acount != accsCount+1 {
3672 return fmt.Errorf("Expected %v accounts, got %v", accsCount+1, acount)
3673 }
3674 return nil
3675 })
3676
3677 // Also, after all that, if a sub is created on C, it should
3678 // be sent to B (but not A). Check that this is the case.
3679 // So first send from A on the subject that we are going to
3680 // use for this new sub.
3681 natsPub(t, ncA, "newsub", []byte("hello"))
3682 natsFlush(t, ncA)
3683 aOutboundToC := sa.getOutboundGatewayConnection("C")
3684 checkForSubjectNoInterest(t, aOutboundToC, globalAccountName, "newsub", true, 2*time.Second)
3685
3686 newSubSub := natsSub(t, ncC, "newsub", func(_ *nats.Msg) {})
3687 natsFlush(t, ncC)
3688 checkExpectedSubs(t, consCount+1)
3689 checkFor(t, time.Second, 15*time.Millisecond, func() error {
3690 c := sb.getOutboundGatewayConnection("C")
3691 ei, _ := c.gw.outsim.Load(globalAccountName)
3692 if ei != nil {
3693 sl := ei.(*outsie).sl
3694 r := sl.Match("newsub")
3695 if len(r.psubs) == 1 {
3696 return nil
3697 }
3698 }
3699 return fmt.Errorf("Newsub not registered on B")
3700 })
3701 checkForSubjectNoInterest(t, aOutboundToC, globalAccountName, "newsub", false, 2*time.Second)
3702
3703 natsUnsub(t, newSubSub)
3704 natsFlush(t, ncC)
3705 checkExpectedSubs(t, consCount)
3706 checkFor(t, time.Second, 15*time.Millisecond, func() error {
3707 c := sb.getOutboundGatewayConnection("C")
3708 ei, _ := c.gw.outsim.Load(globalAccountName)
3709 if ei != nil {
3710 sl := ei.(*outsie).sl
3711 r := sl.Match("newsub")
3712 if len(r.psubs) == 0 {
3713 return nil
3714 }
3715 }
3716 return fmt.Errorf("Newsub still registered on B")
3717 })
3718 }
3719
3720 func TestGatewaySendAllSubsBadProtocol(t *testing.T) {
3721 ob := testDefaultOptionsForGateway("B")
3722 sb := runGatewayServer(ob)
3723 defer sb.Shutdown()
3724
3725 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
3726 sa := runGatewayServer(oa)
3727 defer sa.Shutdown()
3728
3729 waitForOutboundGateways(t, sa, 1, time.Second)
3730 waitForOutboundGateways(t, sb, 1, time.Second)
3731 waitForInboundGateways(t, sa, 1, time.Second)
3732 waitForInboundGateways(t, sb, 1, time.Second)
3733
3734 // For this test, make sure to use inbound from A so
3735 // A will reconnect when we send bad proto that
3736 // causes connection to be closed.
3737 c := getInboundGatewayConnection(sa, "B")
3738 // Mock an invalid protocol (account name missing)
3739 info := &Info{
3740 Gateway: "B",
3741 GatewayCmd: gatewayCmdAllSubsStart,
3742 }
3743 b, _ := json.Marshal(info)
3744 c.mu.Lock()
3745 c.enqueueProto([]byte(fmt.Sprintf("INFO %s\r\n", b)))
3746 c.mu.Unlock()
3747
3748 orgConn := c
3749 checkFor(t, 3*time.Second, 100*time.Millisecond, func() error {
3750 curConn := getInboundGatewayConnection(sa, "B")
3751 if orgConn == curConn {
3752 return fmt.Errorf("Not reconnected")
3753 }
3754 return nil
3755 })
3756
3757 waitForOutboundGateways(t, sa, 1, 2*time.Second)
3758 waitForOutboundGateways(t, sb, 1, 2*time.Second)
3759
3760 // Refresh
3761 c = nil
3762 checkFor(t, 3*time.Second, 15*time.Millisecond, func() error {
3763 c = getInboundGatewayConnection(sa, "B")
3764 if c == nil {
3765 return fmt.Errorf("Did not reconnect")
3766 }
3767 return nil
3768 })
3769 // Do correct start
3770 info.GatewayCmdPayload = []byte(globalAccountName)
3771 b, _ = json.Marshal(info)
3772 c.mu.Lock()
3773 c.enqueueProto([]byte(fmt.Sprintf("INFO %s\r\n", b)))
3774 c.mu.Unlock()
3775 // But incorrect end.
3776 info.GatewayCmd = gatewayCmdAllSubsComplete
3777 info.GatewayCmdPayload = nil
3778 b, _ = json.Marshal(info)
3779 c.mu.Lock()
3780 c.enqueueProto([]byte(fmt.Sprintf("INFO %s\r\n", b)))
3781 c.mu.Unlock()
3782
3783 orgConn = c
3784 checkFor(t, 3*time.Second, 100*time.Millisecond, func() error {
3785 curConn := getInboundGatewayConnection(sa, "B")
3786 if orgConn == curConn {
3787 return fmt.Errorf("Not reconnected")
3788 }
3789 return nil
3790 })
3791 }
3792
3793 func TestGatewayRaceOnClose(t *testing.T) {
3794 ob := testDefaultOptionsForGateway("B")
3795 sb := runGatewayServer(ob)
3796 defer sb.Shutdown()
3797
3798 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
3799 sa := runGatewayServer(oa)
3800 defer sa.Shutdown()
3801
3802 waitForOutboundGateways(t, sa, 1, time.Second)
3803 waitForOutboundGateways(t, sb, 1, time.Second)
3804 waitForInboundGateways(t, sa, 1, time.Second)
3805 waitForInboundGateways(t, sb, 1, time.Second)
3806
3807 bURL := fmt.Sprintf("nats://%s:%d", ob.Host, ob.Port)
3808 ncB := natsConnect(t, bURL, nats.NoReconnect())
3809 defer ncB.Close()
3810
3811 wg := sync.WaitGroup{}
3812 wg.Add(1)
3813 go func() {
3814 defer wg.Done()
3815 cb := func(_ *nats.Msg) {}
3816 for {
3817 // Expect failure at one point and just return.
3818 qsub, err := ncB.QueueSubscribe("foo", "bar", cb)
3819 if err != nil {
3820 return
3821 }
3822 if err := qsub.Unsubscribe(); err != nil {
3823 return
3824 }
3825 }
3826 }()
3827 // Wait a bit and kill B
3828 time.Sleep(200 * time.Millisecond)
3829 sb.Shutdown()
3830 wg.Wait()
3831 }
3832
3833 // Similar to TestNewRoutesServiceImport but with 2 GW servers instead
3834 // of a cluster of 2 servers.
3835 func TestGatewayServiceImport(t *testing.T) {
3836 GatewayDoNotForceInterestOnlyMode(true)
3837 defer GatewayDoNotForceInterestOnlyMode(false)
3838
3839 oa := testDefaultOptionsForGateway("A")
3840 setAccountUserPassInOptions(oa, "$foo", "clientA", "password")
3841 setAccountUserPassInOptions(oa, "$bar", "yyyyyyy", "password")
3842 sa := runGatewayServer(oa)
3843 defer sa.Shutdown()
3844
3845 ob := testGatewayOptionsFromToWithServers(t, "B", "A", sa)
3846 setAccountUserPassInOptions(ob, "$foo", "clientBFoo", "password")
3847 setAccountUserPassInOptions(ob, "$bar", "clientB", "password")
3848 sb := runGatewayServer(ob)
3849 defer sb.Shutdown()
3850
3851 waitForOutboundGateways(t, sa, 1, time.Second)
3852 waitForOutboundGateways(t, sb, 1, time.Second)
3853 waitForInboundGateways(t, sa, 1, time.Second)
3854 waitForInboundGateways(t, sb, 1, time.Second)
3855
3856 // Get accounts
3857 fooA, _ := sa.LookupAccount("$foo")
3858 barA, _ := sa.LookupAccount("$bar")
3859 fooB, _ := sb.LookupAccount("$foo")
3860 barB, _ := sb.LookupAccount("$bar")
3861
3862 // Add in the service export for the requests. Make it public.
3863 fooA.AddServiceExport("test.request", nil)
3864 fooB.AddServiceExport("test.request", nil)
3865
3866 // Add import abilities to server B's bar account from foo.
3867 if err := barB.AddServiceImport(fooB, "foo.request", "test.request"); err != nil {
3868 t.Fatalf("Error adding service import: %v", err)
3869 }
3870 // Same on A.
3871 if err := barA.AddServiceImport(fooA, "foo.request", "test.request"); err != nil {
3872 t.Fatalf("Error adding service import: %v", err)
3873 }
3874
3875 // clientA will be connected to srvA and be the service endpoint and responder.
3876 aURL := fmt.Sprintf("nats://clientA:[email protected]:%d", oa.Port)
3877 clientA := natsConnect(t, aURL)
3878 defer clientA.Close()
3879
3880 subA := natsSubSync(t, clientA, "test.request")
3881 natsFlush(t, clientA)
3882
3883 // Now setup client B on srvB who will do a sub from account $bar
3884 // that should map account $foo's foo subject.
3885 bURL := fmt.Sprintf("nats://clientB:[email protected]:%d", ob.Port)
3886 clientB := natsConnect(t, bURL)
3887 defer clientB.Close()
3888
3889 subB := natsSubSync(t, clientB, "reply")
3890 natsFlush(t, clientB)
3891
3892 for i := 1; i <= 2; i++ {
3893 // Send the request from clientB on foo.request,
3894 natsPubReq(t, clientB, "foo.request", "reply", []byte("hi"))
3895 natsFlush(t, clientB)
3896
3897 // Expect the request on A
3898 msg, err := subA.NextMsg(time.Second)
3899 if err != nil {
3900 t.Fatalf("subA failed to get request: %v", err)
3901 }
3902 if msg.Subject != "test.request" || string(msg.Data) != "hi" {
3903 t.Fatalf("Unexpected message: %v", msg)
3904 }
3905 if msg.Reply == "reply" {
3906 t.Fatalf("Expected randomized reply, but got original")
3907 }
3908
3909 // Check for duplicate message
3910 if msg, err := subA.NextMsg(250 * time.Millisecond); err != nats.ErrTimeout {
3911 t.Fatalf("Unexpected msg: %v", msg)
3912 }
3913
3914 // Send reply
3915 natsPub(t, clientA, msg.Reply, []byte("ok"))
3916 natsFlush(t, clientA)
3917
3918 msg, err = subB.NextMsg(time.Second)
3919 if err != nil {
3920 t.Fatalf("subB failed to get reply: %v", err)
3921 }
3922 if msg.Subject != "reply" || string(msg.Data) != "ok" {
3923 t.Fatalf("Unexpected message: %v", msg)
3924 }
3925
3926 // Check for duplicate message
3927 if msg, err := subB.NextMsg(250 * time.Millisecond); err != nats.ErrTimeout {
3928 t.Fatalf("Unexpected msg: %v", msg)
3929 }
3930
3931 expected := int64(i * 2)
3932 vz, _ := sa.Varz(nil)
3933 if vz.OutMsgs != expected {
3934 t.Fatalf("Expected %d outMsgs for A, got %v", expected, vz.OutMsgs)
3935 }
3936
3937 // For B, we expect it to send to gateway on the two subjects: test.request
3938 // and foo.request then send the reply to the client and optimistically
3939 // to the other gateway.
3940 if i == 1 {
3941 expected = 4
3942 } else {
3943 // The second time, one of the accounts will be suppressed and the reply going
3944 // back so we should only get 2 more messages.
3945 expected = 6
3946 }
3947 vz, _ = sb.Varz(nil)
3948 if vz.OutMsgs != expected {
3949 t.Fatalf("Expected %d outMsgs for B, got %v", expected, vz.OutMsgs)
3950 }
3951 }
3952
3953 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
3954 if ts := fooA.TotalSubs(); ts != 1 {
3955 return fmt.Errorf("Expected one sub to be left on fooA, but got %d", ts)
3956 }
3957 return nil
3958 })
3959
3960 // Speed up exiration
3961 err := fooA.SetServiceExportResponseThreshold("test.request", 50*time.Millisecond)
3962 if err != nil {
3963 t.Fatalf("Error setting response threshold: %v", err)
3964 }
3965
3966 // Send 100 requests from clientB on foo.request,
3967 for i := 0; i < 100; i++ {
3968 natsPubReq(t, clientB, "foo.request", "reply", []byte("hi"))
3969 }
3970 natsFlush(t, clientB)
3971
3972 // Consume the requests, but don't reply to them...
3973 for i := 0; i < 100; i++ {
3974 if _, err := subA.NextMsg(time.Second); err != nil {
3975 t.Fatalf("subA did not receive request: %v", err)
3976 }
3977 }
3978
3979 // These reply subjects will be dangling off of $foo account on serverA.
3980 // Remove our service endpoint and wait for the dangling replies to go to zero.
3981 natsUnsub(t, subA)
3982 natsFlush(t, clientA)
3983
3984 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
3985 if ts := fooA.TotalSubs(); ts != 0 {
3986 return fmt.Errorf("Number of subs is %d, should be zero", ts)
3987 }
3988 return nil
3989 })
3990
3991 // Repeat similar test but without the small TTL and verify
3992 // that if B is shutdown, the dangling subs for replies are
3993 // cleared from the account sublist.
3994 err = fooA.SetServiceExportResponseThreshold("test.request", 10*time.Second)
3995 if err != nil {
3996 t.Fatalf("Error setting response threshold: %v", err)
3997 }
3998
3999 subA = natsSubSync(t, clientA, "test.request")
4000 natsFlush(t, clientA)
4001
4002 // Send 100 requests from clientB on foo.request,
4003 for i := 0; i < 100; i++ {
4004 natsPubReq(t, clientB, "foo.request", "reply", []byte("hi"))
4005 }
4006 natsFlush(t, clientB)
4007
4008 // Consume the requests, but don't reply to them...
4009 for i := 0; i < 100; i++ {
4010 if _, err := subA.NextMsg(time.Second); err != nil {
4011 t.Fatalf("subA did not receive request: %v", err)
4012 }
4013 }
4014
4015 // Shutdown B
4016 clientB.Close()
4017 sb.Shutdown()
4018
4019 // Close our last sub
4020 natsUnsub(t, subA)
4021 natsFlush(t, clientA)
4022
4023 // Verify that they are gone before the 10 sec TTL
4024 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
4025 if ts := fooA.TotalSubs(); ts != 0 {
4026 return fmt.Errorf("Number of subs is %d, should be zero", ts)
4027 }
4028 return nil
4029 })
4030
4031 // Check that this all work in interest-only mode
4032 sb = runGatewayServer(ob)
4033 defer sb.Shutdown()
4034
4035 fooB, _ = sb.LookupAccount("$foo")
4036 barB, _ = sb.LookupAccount("$bar")
4037
4038 // Add in the service export for the requests. Make it public.
4039 fooB.AddServiceExport("test.request", nil)
4040 // Add import abilities to server B's bar account from foo.
4041 if err := barB.AddServiceImport(fooB, "foo.request", "test.request"); err != nil {
4042 t.Fatalf("Error adding service import: %v", err)
4043 }
4044
4045 waitForOutboundGateways(t, sa, 1, 2*time.Second)
4046 waitForOutboundGateways(t, sb, 1, 2*time.Second)
4047 waitForInboundGateways(t, sa, 1, 2*time.Second)
4048 waitForInboundGateways(t, sb, 1, 2*time.Second)
4049
4050 // We need at least a subscription on A otherwise when publishing
4051 // to subjects with no interest we would simply get an A-
4052 natsSubSync(t, clientA, "not.used")
4053
4054 // Create a client on B that will use account $foo
4055 bURL = fmt.Sprintf("nats://clientBFoo:[email protected]:%d", ob.Port)
4056 clientB = natsConnect(t, bURL)
4057 defer clientB.Close()
4058
4059 // First flood with subjects that remote gw is not interested
4060 // so we switch to interest-only.
4061 for i := 0; i < 1100; i++ {
4062 natsPub(t, clientB, fmt.Sprintf("no.interest.%d", i), []byte("hello"))
4063 }
4064 natsFlush(t, clientB)
4065
4066 checkGWInterestOnlyMode(t, sb, "A", "$foo")
4067
4068 // Go back to clientB on $bar.
4069 clientB.Close()
4070 bURL = fmt.Sprintf("nats://clientB:[email protected]:%d", ob.Port)
4071 clientB = natsConnect(t, bURL)
4072 defer clientB.Close()
4073
4074 subA = natsSubSync(t, clientA, "test.request")
4075 natsFlush(t, clientA)
4076
4077 subB = natsSubSync(t, clientB, "reply")
4078 natsFlush(t, clientB)
4079
4080 // Sine it is interest-only, B should receive an interest
4081 // on $foo test.request
4082 checkGWInterestOnlyModeInterestOn(t, sb, "A", "$foo", "test.request")
4083
4084 // Send the request from clientB on foo.request,
4085 natsPubReq(t, clientB, "foo.request", "reply", []byte("hi"))
4086 natsFlush(t, clientB)
4087
4088 // Expect the request on A
4089 msg, err := subA.NextMsg(time.Second)
4090 if err != nil {
4091 t.Fatalf("subA failed to get request: %v", err)
4092 }
4093 if msg.Subject != "test.request" || string(msg.Data) != "hi" {
4094 t.Fatalf("Unexpected message: %v", msg)
4095 }
4096 if msg.Reply == "reply" {
4097 t.Fatalf("Expected randomized reply, but got original")
4098 }
4099
4100 // Check for duplicate message
4101 if msg, err := subA.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
4102 t.Fatalf("Unexpected msg: %v", msg)
4103 }
4104
4105 // Send reply
4106 natsPub(t, clientA, msg.Reply, []byte("ok"))
4107 natsFlush(t, clientA)
4108
4109 msg, err = subB.NextMsg(time.Second)
4110 if err != nil {
4111 t.Fatalf("subB failed to get reply: %v", err)
4112 }
4113 if msg.Subject != "reply" || string(msg.Data) != "ok" {
4114 t.Fatalf("Unexpected message: %v", msg)
4115 }
4116
4117 // Check for duplicate message
4118 if msg, err := subB.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
4119 t.Fatalf("Unexpected msg: %v", msg)
4120 }
4121 }
4122
4123 func TestGatewayServiceImportWithQueue(t *testing.T) {
4124 GatewayDoNotForceInterestOnlyMode(true)
4125 defer GatewayDoNotForceInterestOnlyMode(false)
4126
4127 oa := testDefaultOptionsForGateway("A")
4128 setAccountUserPassInOptions(oa, "$foo", "clientA", "password")
4129 setAccountUserPassInOptions(oa, "$bar", "yyyyyyy", "password")
4130 sa := runGatewayServer(oa)
4131 defer sa.Shutdown()
4132
4133 ob := testGatewayOptionsFromToWithServers(t, "B", "A", sa)
4134 setAccountUserPassInOptions(ob, "$foo", "clientBFoo", "password")
4135 setAccountUserPassInOptions(ob, "$bar", "clientB", "password")
4136 sb := runGatewayServer(ob)
4137 defer sb.Shutdown()
4138
4139 waitForOutboundGateways(t, sa, 1, time.Second)
4140 waitForOutboundGateways(t, sb, 1, time.Second)
4141 waitForInboundGateways(t, sa, 1, time.Second)
4142 waitForInboundGateways(t, sb, 1, time.Second)
4143
4144 // Get accounts
4145 fooA, _ := sa.LookupAccount("$foo")
4146 barA, _ := sa.LookupAccount("$bar")
4147 fooB, _ := sb.LookupAccount("$foo")
4148 barB, _ := sb.LookupAccount("$bar")
4149
4150 // Add in the service export for the requests. Make it public.
4151 fooA.AddServiceExport("test.request", nil)
4152 fooB.AddServiceExport("test.request", nil)
4153
4154 // Add import abilities to server B's bar account from foo.
4155 if err := barB.AddServiceImport(fooB, "foo.request", "test.request"); err != nil {
4156 t.Fatalf("Error adding service import: %v", err)
4157 }
4158 // Same on A.
4159 if err := barA.AddServiceImport(fooA, "foo.request", "test.request"); err != nil {
4160 t.Fatalf("Error adding service import: %v", err)
4161 }
4162
4163 // clientA will be connected to srvA and be the service endpoint and responder.
4164 aURL := fmt.Sprintf("nats://clientA:[email protected]:%d", oa.Port)
4165 clientA := natsConnect(t, aURL)
4166 defer clientA.Close()
4167
4168 subA := natsQueueSubSync(t, clientA, "test.request", "queue")
4169 natsFlush(t, clientA)
4170
4171 // Now setup client B on srvB who will do a sub from account $bar
4172 // that should map account $foo's foo subject.
4173 bURL := fmt.Sprintf("nats://clientB:[email protected]:%d", ob.Port)
4174 clientB := natsConnect(t, bURL)
4175 defer clientB.Close()
4176
4177 subB := natsQueueSubSync(t, clientB, "reply", "queue2")
4178 natsFlush(t, clientB)
4179
4180 // Wait for queue interest on test.request from A to be registered
4181 // on server B.
4182 checkForRegisteredQSubInterest(t, sb, "A", "$foo", "test.request", 1, time.Second)
4183
4184 for i := 0; i < 2; i++ {
4185 // Send the request from clientB on foo.request,
4186 natsPubReq(t, clientB, "foo.request", "reply", []byte("hi"))
4187 natsFlush(t, clientB)
4188
4189 // Expect the request on A
4190 msg, err := subA.NextMsg(time.Second)
4191 if err != nil {
4192 t.Fatalf("subA failed to get request: %v", err)
4193 }
4194 if msg.Subject != "test.request" || string(msg.Data) != "hi" {
4195 t.Fatalf("Unexpected message: %v", msg)
4196 }
4197 if msg.Reply == "reply" {
4198 t.Fatalf("Expected randomized reply, but got original")
4199 }
4200 // Check for duplicate message
4201 if msg, err := subA.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
4202 t.Fatalf("Unexpected msg: %v", msg)
4203 }
4204
4205 // Send reply
4206 natsPub(t, clientA, msg.Reply, []byte("ok"))
4207 natsFlush(t, clientA)
4208
4209 msg, err = subB.NextMsg(time.Second)
4210 if err != nil {
4211 t.Fatalf("subB failed to get reply: %v", err)
4212 }
4213 if msg.Subject != "reply" || string(msg.Data) != "ok" {
4214 t.Fatalf("Unexpected message: %v", msg)
4215 }
4216 // Check for duplicate message
4217 if msg, err := subB.NextMsg(250 * time.Millisecond); err != nats.ErrTimeout {
4218 t.Fatalf("Unexpected msg: %v", msg)
4219 }
4220
4221 expected := int64((i + 1) * 2)
4222 vz, _ := sa.Varz(nil)
4223 if vz.OutMsgs != expected {
4224 t.Fatalf("Expected %d outMsgs for A, got %v", expected, vz.OutMsgs)
4225 }
4226
4227 // For B, we expect it to send to gateway on the two subjects: test.request
4228 // and foo.request then send the reply to the client and optimistically
4229 // to the other gateway.
4230 if i == 0 {
4231 expected = 4
4232 } else {
4233 // The second time, one of the accounts will be suppressed and the reply going
4234 // back so we should get only 2 more messages.
4235 expected = 6
4236 }
4237 vz, _ = sb.Varz(nil)
4238 if vz.OutMsgs != expected {
4239 t.Fatalf("Expected %d outMsgs for B, got %v", expected, vz.OutMsgs)
4240 }
4241 }
4242
4243 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
4244 if ts := fooA.TotalSubs(); ts != 1 {
4245 return fmt.Errorf("Expected one sub to be left on fooA, but got %d", ts)
4246 }
4247 return nil
4248 })
4249
4250 // Speed up exiration
4251 err := fooA.SetServiceExportResponseThreshold("test.request", 10*time.Millisecond)
4252 if err != nil {
4253 t.Fatalf("Error setting response threshold: %v", err)
4254 }
4255
4256 // Send 100 requests from clientB on foo.request,
4257 for i := 0; i < 100; i++ {
4258 natsPubReq(t, clientB, "foo.request", "reply", []byte("hi"))
4259 }
4260 natsFlush(t, clientB)
4261
4262 // Consume the requests, but don't reply to them...
4263 for i := 0; i < 100; i++ {
4264 if _, err := subA.NextMsg(time.Second); err != nil {
4265 t.Fatalf("subA did not receive request: %v", err)
4266 }
4267 }
4268
4269 // These reply subjects will be dangling off of $foo account on serverA.
4270 // Remove our service endpoint and wait for the dangling replies to go to zero.
4271 natsUnsub(t, subA)
4272 natsFlush(t, clientA)
4273
4274 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
4275 if ts := fooA.TotalSubs(); ts != 0 {
4276 return fmt.Errorf("Number of subs is %d, should be zero", ts)
4277 }
4278 return nil
4279 })
4280 checkForRegisteredQSubInterest(t, sb, "A", "$foo", "test.request", 0, time.Second)
4281
4282 // Repeat similar test but without the small TTL and verify
4283 // that if B is shutdown, the dangling subs for replies are
4284 // cleared from the account sublist.
4285 err = fooA.SetServiceExportResponseThreshold("test.request", 10*time.Second)
4286 if err != nil {
4287 t.Fatalf("Error setting response threshold: %v", err)
4288 }
4289
4290 subA = natsQueueSubSync(t, clientA, "test.request", "queue")
4291 natsFlush(t, clientA)
4292 checkForRegisteredQSubInterest(t, sb, "A", "$foo", "test.request", 1, time.Second)
4293
4294 // Send 100 requests from clientB on foo.request,
4295 for i := 0; i < 100; i++ {
4296 natsPubReq(t, clientB, "foo.request", "reply", []byte("hi"))
4297 }
4298 natsFlush(t, clientB)
4299
4300 // Consume the requests, but don't reply to them...
4301 for i := 0; i < 100; i++ {
4302 if _, err := subA.NextMsg(time.Second); err != nil {
4303 t.Fatalf("subA did not receive request %d: %v", i+1, err)
4304 }
4305 }
4306
4307 // Shutdown B
4308 clientB.Close()
4309 sb.Shutdown()
4310
4311 // Close our last sub
4312 natsUnsub(t, subA)
4313 natsFlush(t, clientA)
4314
4315 // Verify that they are gone before the 10 sec TTL
4316 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
4317 if ts := fooA.TotalSubs(); ts != 0 {
4318 return fmt.Errorf("Number of subs is %d, should be zero", ts)
4319 }
4320 return nil
4321 })
4322
4323 // Check that this all work in interest-only mode
4324 sb = runGatewayServer(ob)
4325 defer sb.Shutdown()
4326
4327 fooB, _ = sb.LookupAccount("$foo")
4328 barB, _ = sb.LookupAccount("$bar")
4329
4330 // Add in the service export for the requests. Make it public.
4331 fooB.AddServiceExport("test.request", nil)
4332 // Add import abilities to server B's bar account from foo.
4333 if err := barB.AddServiceImport(fooB, "foo.request", "test.request"); err != nil {
4334 t.Fatalf("Error adding service import: %v", err)
4335 }
4336
4337 waitForOutboundGateways(t, sa, 1, 2*time.Second)
4338 waitForOutboundGateways(t, sb, 1, 2*time.Second)
4339 waitForInboundGateways(t, sa, 1, 2*time.Second)
4340 waitForInboundGateways(t, sb, 1, 2*time.Second)
4341
4342 // We need at least a subscription on A otherwise when publishing
4343 // to subjects with no interest we would simply get an A-
4344 natsSubSync(t, clientA, "not.used")
4345
4346 // Create a client on B that will use account $foo
4347 bURL = fmt.Sprintf("nats://clientBFoo:[email protected]:%d", ob.Port)
4348 clientB = natsConnect(t, bURL)
4349 defer clientB.Close()
4350
4351 // First flood with subjects that remote gw is not interested
4352 // so we switch to interest-only.
4353 for i := 0; i < 1100; i++ {
4354 natsPub(t, clientB, fmt.Sprintf("no.interest.%d", i), []byte("hello"))
4355 }
4356 natsFlush(t, clientB)
4357
4358 checkGWInterestOnlyMode(t, sb, "A", "$foo")
4359
4360 // Go back to clientB on $bar.
4361 clientB.Close()
4362 bURL = fmt.Sprintf("nats://clientB:[email protected]:%d", ob.Port)
4363 clientB = natsConnect(t, bURL)
4364 defer clientB.Close()
4365
4366 subA = natsSubSync(t, clientA, "test.request")
4367 natsFlush(t, clientA)
4368
4369 subB = natsSubSync(t, clientB, "reply")
4370 natsFlush(t, clientB)
4371
4372 // Sine it is interest-only, B should receive an interest
4373 // on $foo test.request
4374 checkGWInterestOnlyModeInterestOn(t, sb, "A", "$foo", "test.request")
4375
4376 // Send the request from clientB on foo.request,
4377 natsPubReq(t, clientB, "foo.request", "reply", []byte("hi"))
4378 natsFlush(t, clientB)
4379
4380 // Expect the request on A
4381 msg, err := subA.NextMsg(time.Second)
4382 if err != nil {
4383 t.Fatalf("subA failed to get request: %v", err)
4384 }
4385 if msg.Subject != "test.request" || string(msg.Data) != "hi" {
4386 t.Fatalf("Unexpected message: %v", msg)
4387 }
4388 if msg.Reply == "reply" {
4389 t.Fatalf("Expected randomized reply, but got original")
4390 }
4391
4392 // Check for duplicate message
4393 if msg, err := subA.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
4394 t.Fatalf("Unexpected msg: %v", msg)
4395 }
4396
4397 // Send reply
4398 natsPub(t, clientA, msg.Reply, []byte("ok"))
4399 natsFlush(t, clientA)
4400
4401 msg, err = subB.NextMsg(time.Second)
4402 if err != nil {
4403 t.Fatalf("subB failed to get reply: %v", err)
4404 }
4405 if msg.Subject != "reply" || string(msg.Data) != "ok" {
4406 t.Fatalf("Unexpected message: %v", msg)
4407 }
4408
4409 // Check for duplicate message
4410 if msg, err := subB.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
4411 t.Fatalf("Unexpected msg: %v", msg)
4412 }
4413 }
4414
4415 func ensureGWConnectTo(t *testing.T, s *Server, remoteGWName string, remoteGWServer *Server) {
4416 t.Helper()
4417 var good bool
4418 for i := 0; !good && (i < 3); i++ {
4419 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
4420 if s.numOutboundGateways() == 0 {
4421 return fmt.Errorf("Still no gw outbound connection")
4422 }
4423 return nil
4424 })
4425 ogc := s.getOutboundGatewayConnection(remoteGWName)
4426 ogc.mu.Lock()
4427 name := ogc.opts.Name
4428 nc := ogc.nc
4429 ogc.mu.Unlock()
4430 if name != remoteGWServer.ID() {
4431 rg := s.getRemoteGateway(remoteGWName)
4432 goodURL := remoteGWServer.getGatewayURL()
4433 rg.Lock()
4434 for u := range rg.urls {
4435 if u != goodURL {
4436 delete(rg.urls, u)
4437 }
4438 }
4439 rg.Unlock()
4440 if nc != nil {
4441 nc.Close()
4442 }
4443 } else {
4444 good = true
4445 }
4446 }
4447 if !good {
4448 t.Fatalf("Could not ensure that server connects to remote gateway %q at URL %q",
4449 remoteGWName, remoteGWServer.getGatewayURL())
4450 }
4451 }
4452
4453 func TestGatewayServiceImportComplexSetup(t *testing.T) {
4454 // This test will have following setup:
4455 //
4456 // |- responder (subs to "$foo test.request")
4457 // | (sends to "$foo _R_.xxxx")
4458 // route v
4459 // [A1]<----------------->[A2]
4460 // ^ |^ |
4461 // |gw| \______gw________ gw|
4462 // | v \ v
4463 // [B1]<----------------->[B2]
4464 // ^ route
4465 // |
4466 // |_ requestor (sends "$bar foo.request reply")
4467 //
4468
4469 // Setup first A1 and B1 to ensure that they have GWs
4470 // connections as described above.
4471
4472 oa1 := testDefaultOptionsForGateway("A")
4473 setAccountUserPassInOptions(oa1, "$foo", "clientA", "password")
4474 setAccountUserPassInOptions(oa1, "$bar", "yyyyyyy", "password")
4475 sa1 := runGatewayServer(oa1)
4476 defer sa1.Shutdown()
4477
4478 ob1 := testGatewayOptionsFromToWithServers(t, "B", "A", sa1)
4479 setAccountUserPassInOptions(ob1, "$foo", "xxxxxxx", "password")
4480 setAccountUserPassInOptions(ob1, "$bar", "clientB", "password")
4481 sb1 := runGatewayServer(ob1)
4482 defer sb1.Shutdown()
4483
4484 waitForOutboundGateways(t, sa1, 1, time.Second)
4485 waitForOutboundGateways(t, sb1, 1, time.Second)
4486
4487 waitForInboundGateways(t, sa1, 1, time.Second)
4488 waitForInboundGateways(t, sb1, 1, time.Second)
4489
4490 ob2 := testGatewayOptionsFromToWithServers(t, "B", "A", sa1)
4491 ob2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", sb1.ClusterAddr().Port))
4492 setAccountUserPassInOptions(ob2, "$foo", "clientBFoo", "password")
4493 setAccountUserPassInOptions(ob2, "$bar", "clientB", "password")
4494 ob2.gatewaysSolicitDelay = time.Nanosecond // 0 would be default, so nano to connect asap
4495 sb2 := runGatewayServer(ob2)
4496 defer sb2.Shutdown()
4497
4498 waitForOutboundGateways(t, sa1, 1, time.Second)
4499 waitForOutboundGateways(t, sb1, 1, time.Second)
4500 waitForOutboundGateways(t, sb2, 1, 2*time.Second)
4501
4502 waitForInboundGateways(t, sa1, 2, time.Second)
4503 waitForInboundGateways(t, sb1, 1, time.Second)
4504 waitForInboundGateways(t, sb2, 0, time.Second)
4505
4506 oa2 := testGatewayOptionsFromToWithServers(t, "A", "B", sb2)
4507 oa2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", sa1.ClusterAddr().Port))
4508 setAccountUserPassInOptions(oa2, "$foo", "clientA", "password")
4509 setAccountUserPassInOptions(oa2, "$bar", "yyyyyyy", "password")
4510 oa2.gatewaysSolicitDelay = time.Nanosecond // 0 would be default, so nano to connect asap
4511 sa2 := runGatewayServer(oa2)
4512 defer sa2.Shutdown()
4513
4514 ensureGWConnectTo(t, sa2, "B", sb2)
4515
4516 checkClusterFormed(t, sa1, sa2)
4517 checkClusterFormed(t, sb1, sb2)
4518
4519 waitForOutboundGateways(t, sa1, 1, time.Second)
4520 waitForOutboundGateways(t, sb1, 1, time.Second)
4521 waitForOutboundGateways(t, sb2, 1, time.Second)
4522 waitForOutboundGateways(t, sa2, 1, 2*time.Second)
4523
4524 waitForInboundGateways(t, sa1, 2, time.Second)
4525 waitForInboundGateways(t, sb1, 1, time.Second)
4526 waitForInboundGateways(t, sb2, 1, 2*time.Second)
4527 waitForInboundGateways(t, sa2, 0, time.Second)
4528
4529 // Verification that we have what we wanted
4530 c := sa2.getOutboundGatewayConnection("B")
4531 if c == nil || c.opts.Name != sb2.ID() {
4532 t.Fatalf("A2 does not have outbound to B2")
4533 }
4534 c = getInboundGatewayConnection(sa2, "B")
4535 if c != nil {
4536 t.Fatalf("Bad setup")
4537 }
4538 c = sb2.getOutboundGatewayConnection("A")
4539 if c == nil || c.opts.Name != sa1.ID() {
4540 t.Fatalf("B2 does not have outbound to A1")
4541 }
4542 c = getInboundGatewayConnection(sb2, "A")
4543 if c == nil || c.opts.Name != sa2.ID() {
4544 t.Fatalf("Bad setup")
4545 }
4546
4547 // Ok, so now that we have proper setup, do actual test!
4548
4549 // Get accounts
4550 fooA1, _ := sa1.LookupAccount("$foo")
4551 barA1, _ := sa1.LookupAccount("$bar")
4552 fooA2, _ := sa2.LookupAccount("$foo")
4553 barA2, _ := sa2.LookupAccount("$bar")
4554
4555 fooB1, _ := sb1.LookupAccount("$foo")
4556 barB1, _ := sb1.LookupAccount("$bar")
4557 fooB2, _ := sb2.LookupAccount("$foo")
4558 barB2, _ := sb2.LookupAccount("$bar")
4559
4560 // Add in the service export for the requests. Make it public.
4561 fooA1.AddServiceExport("test.request", nil)
4562 fooA2.AddServiceExport("test.request", nil)
4563 fooB1.AddServiceExport("test.request", nil)
4564 fooB2.AddServiceExport("test.request", nil)
4565
4566 // Add import abilities to server B's bar account from foo.
4567 if err := barB1.AddServiceImport(fooB1, "foo.request", "test.request"); err != nil {
4568 t.Fatalf("Error adding service import: %v", err)
4569 }
4570 if err := barB2.AddServiceImport(fooB2, "foo.request", "test.request"); err != nil {
4571 t.Fatalf("Error adding service import: %v", err)
4572 }
4573 // Same on A.
4574 if err := barA1.AddServiceImport(fooA1, "foo.request", "test.request"); err != nil {
4575 t.Fatalf("Error adding service import: %v", err)
4576 }
4577 if err := barA2.AddServiceImport(fooA2, "foo.request", "test.request"); err != nil {
4578 t.Fatalf("Error adding service import: %v", err)
4579 }
4580
4581 // clientA will be connected to A2 and be the service endpoint and responder.
4582 a2URL := fmt.Sprintf("nats://clientA:[email protected]:%d", oa2.Port)
4583 clientA := natsConnect(t, a2URL)
4584 defer clientA.Close()
4585
4586 subA := natsSubSync(t, clientA, "test.request")
4587 natsFlush(t, clientA)
4588
4589 // Now setup client B on B1 who will do a sub from account $bar
4590 // that should map account $foo's foo subject.
4591 b1URL := fmt.Sprintf("nats://clientB:[email protected]:%d", ob1.Port)
4592 clientB := natsConnect(t, b1URL)
4593 defer clientB.Close()
4594
4595 subB := natsSubSync(t, clientB, "reply")
4596 natsFlush(t, clientB)
4597
4598 var msg *nats.Msg
4599 var err error
4600 for attempts := 1; attempts <= 2; attempts++ {
4601 // Send the request from clientB on foo.request,
4602 natsPubReq(t, clientB, "foo.request", "reply", []byte("hi"))
4603 natsFlush(t, clientB)
4604
4605 // Expect the request on A
4606 msg, err = subA.NextMsg(time.Second)
4607 if err != nil {
4608 if attempts == 1 {
4609 // Since we are in interestOnly mode, it is possible
4610 // that server B did not receive the subscription
4611 // interest yet, so try again.
4612 continue
4613 }
4614 t.Fatalf("subA failed to get request: %v", err)
4615 }
4616 if msg.Subject != "test.request" || string(msg.Data) != "hi" {
4617 t.Fatalf("Unexpected message: %v", msg)
4618 }
4619 if msg.Reply == "reply" {
4620 t.Fatalf("Expected randomized reply, but got original")
4621 }
4622 }
4623 // Make sure we don't receive a second copy
4624 if msg, err := subA.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
4625 t.Fatalf("Received unexpected message: %v", msg)
4626 }
4627
4628 // Send reply
4629 natsPub(t, clientA, msg.Reply, []byte("ok"))
4630 natsFlush(t, clientA)
4631
4632 msg, err = subB.NextMsg(time.Second)
4633 if err != nil {
4634 t.Fatalf("subB failed to get reply: %v", err)
4635 }
4636 if msg.Subject != "reply" || string(msg.Data) != "ok" {
4637 t.Fatalf("Unexpected message: %v", msg)
4638 }
4639 // Make sure we don't receive a second copy
4640 if msg, err := subB.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
4641 t.Fatalf("Received unexpected message: %v", msg)
4642 }
4643
4644 checkSubs := func(t *testing.T, acc *Account, srvName string, expected int) {
4645 t.Helper()
4646 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
4647 if ts := acc.TotalSubs(); ts != expected {
4648 return fmt.Errorf("Number of subs is %d on acc=%s srv=%s, should be %v", ts, acc.Name, srvName, expected)
4649 }
4650 return nil
4651 })
4652 }
4653 checkSubs(t, fooA1, "A1", 1)
4654 checkSubs(t, barA1, "A1", 1)
4655 checkSubs(t, fooA2, "A2", 1)
4656 checkSubs(t, barA2, "A2", 1)
4657 checkSubs(t, fooB1, "B1", 1)
4658 checkSubs(t, barB1, "B1", 2)
4659 checkSubs(t, fooB2, "B2", 1)
4660 checkSubs(t, barB2, "B2", 2)
4661
4662 // Speed up exiration
4663 err = fooA2.SetServiceExportResponseThreshold("test.request", 10*time.Millisecond)
4664 if err != nil {
4665 t.Fatalf("Error setting response threshold: %v", err)
4666 }
4667 err = fooB1.SetServiceExportResponseThreshold("test.request", 10*time.Millisecond)
4668 if err != nil {
4669 t.Fatalf("Error setting response threshold: %v", err)
4670 }
4671
4672 // Send 100 requests from clientB on foo.request,
4673 for i := 0; i < 100; i++ {
4674 natsPubReq(t, clientB, "foo.request", "reply", []byte("hi"))
4675 }
4676 natsFlush(t, clientB)
4677
4678 // Consume the requests, but don't reply to them...
4679 for i := 0; i < 100; i++ {
4680 if _, err := subA.NextMsg(time.Second); err != nil {
4681 t.Fatalf("subA did not receive request: %v", err)
4682 }
4683 }
4684
4685 // Unsubsribe all and ensure counts go to 0.
4686 natsUnsub(t, subA)
4687 natsFlush(t, clientA)
4688 natsUnsub(t, subB)
4689 natsFlush(t, clientB)
4690
4691 // We should expire because ttl.
4692 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
4693 if nr := len(fooA1.exports.responses); nr != 0 {
4694 return fmt.Errorf("Number of responses is %d", nr)
4695 }
4696 return nil
4697 })
4698
4699 checkSubs(t, fooA1, "A1", 0)
4700 checkSubs(t, fooA2, "A2", 0)
4701 checkSubs(t, fooB1, "B1", 1)
4702 checkSubs(t, fooB2, "B2", 1)
4703
4704 checkSubs(t, barA1, "A1", 1)
4705 checkSubs(t, barA2, "A2", 1)
4706 checkSubs(t, barB1, "B1", 1)
4707 checkSubs(t, barB2, "B2", 1)
4708
4709 // Check that this all work in interest-only mode.
4710
4711 // We need at least a subscription on B2 otherwise when publishing
4712 // to subjects with no interest we would simply get an A-
4713 b2URL := fmt.Sprintf("nats://clientBFoo:[email protected]:%d", ob2.Port)
4714 clientB2 := natsConnect(t, b2URL)
4715 defer clientB2.Close()
4716 natsSubSync(t, clientB2, "not.used")
4717 natsFlush(t, clientB2)
4718
4719 // Make A2 flood B2 with subjects that B2 is not interested in.
4720 for i := 0; i < 1100; i++ {
4721 natsPub(t, clientA, fmt.Sprintf("no.interest.%d", i), []byte("hello"))
4722 }
4723 natsFlush(t, clientA)
4724 // Wait for B2 to switch to interest-only
4725 checkGWInterestOnlyMode(t, sa2, "B", "$foo")
4726
4727 subA = natsSubSync(t, clientA, "test.request")
4728 natsFlush(t, clientA)
4729
4730 subB = natsSubSync(t, clientB, "reply")
4731 natsFlush(t, clientB)
4732
4733 for attempts := 1; attempts <= 2; attempts++ {
4734 // Send the request from clientB on foo.request,
4735 natsPubReq(t, clientB, "foo.request", "reply", []byte("hi"))
4736 natsFlush(t, clientB)
4737
4738 // Expect the request on A
4739 msg, err = subA.NextMsg(time.Second)
4740 if err != nil {
4741 if attempts == 1 {
4742 // Since we are in interestOnly mode, it is possible
4743 // that server B did not receive the subscription
4744 // interest yet, so try again.
4745 continue
4746 }
4747 t.Fatalf("subA failed to get request: %v", err)
4748 }
4749 if msg.Subject != "test.request" || string(msg.Data) != "hi" {
4750 t.Fatalf("Unexpected message: %v", msg)
4751 }
4752 if msg.Reply == "reply" {
4753 t.Fatalf("Expected randomized reply, but got original")
4754 }
4755 }
4756
4757 // Check for duplicate message
4758 if msg, err := subA.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
4759 t.Fatalf("Unexpected msg: %v", msg)
4760 }
4761
4762 // Send reply
4763 natsPub(t, clientA, msg.Reply, []byte("ok"))
4764 natsFlush(t, clientA)
4765
4766 msg, err = subB.NextMsg(time.Second)
4767 if err != nil {
4768 t.Fatalf("subB failed to get reply: %v", err)
4769 }
4770 if msg.Subject != "reply" || string(msg.Data) != "ok" {
4771 t.Fatalf("Unexpected message: %v", msg)
4772 }
4773
4774 // Check for duplicate message
4775 if msg, err := subB.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
4776 t.Fatalf("Unexpected msg: %v", msg)
4777 }
4778 }
4779
4780 func TestGatewayServiceExportWithWildcards(t *testing.T) {
4781 // This test will have following setup:
4782 //
4783 // |- responder
4784 // |
4785 // route v
4786 // [A1]<----------------->[A2]
4787 // ^ |^ |
4788 // |gw| \______gw________ gw|
4789 // | v \ v
4790 // [B1]<----------------->[B2]
4791 // ^ route
4792 // |
4793 // |_ requestor
4794 //
4795
4796 for _, test := range []struct {
4797 name string
4798 public bool
4799 }{
4800 {
4801 name: "public",
4802 public: true,
4803 },
4804 {
4805 name: "private",
4806 public: false,
4807 },
4808 } {
4809 t.Run(test.name, func(t *testing.T) {
4810
4811 // Setup first A1 and B1 to ensure that they have GWs
4812 // connections as described above.
4813
4814 oa1 := testDefaultOptionsForGateway("A")
4815 setAccountUserPassInOptions(oa1, "$foo", "clientA", "password")
4816 setAccountUserPassInOptions(oa1, "$bar", "yyyyyyy", "password")
4817 sa1 := runGatewayServer(oa1)
4818 defer sa1.Shutdown()
4819
4820 ob1 := testGatewayOptionsFromToWithServers(t, "B", "A", sa1)
4821 setAccountUserPassInOptions(ob1, "$foo", "xxxxxxx", "password")
4822 setAccountUserPassInOptions(ob1, "$bar", "clientB", "password")
4823 sb1 := runGatewayServer(ob1)
4824 defer sb1.Shutdown()
4825
4826 waitForOutboundGateways(t, sa1, 1, time.Second)
4827 waitForOutboundGateways(t, sb1, 1, time.Second)
4828
4829 waitForInboundGateways(t, sa1, 1, time.Second)
4830 waitForInboundGateways(t, sb1, 1, time.Second)
4831
4832 ob2 := testGatewayOptionsFromToWithServers(t, "B", "A", sa1)
4833 ob2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", sb1.ClusterAddr().Port))
4834 setAccountUserPassInOptions(ob2, "$foo", "clientBFoo", "password")
4835 setAccountUserPassInOptions(ob2, "$bar", "clientB", "password")
4836 ob2.gatewaysSolicitDelay = time.Nanosecond // 0 would be default, so nano to connect asap
4837 sb2 := runGatewayServer(ob2)
4838 defer sb2.Shutdown()
4839
4840 waitForOutboundGateways(t, sa1, 1, time.Second)
4841 waitForOutboundGateways(t, sb1, 1, time.Second)
4842 waitForOutboundGateways(t, sb2, 1, 2*time.Second)
4843
4844 waitForInboundGateways(t, sa1, 2, time.Second)
4845 waitForInboundGateways(t, sb1, 1, time.Second)
4846 waitForInboundGateways(t, sb2, 0, time.Second)
4847
4848 oa2 := testGatewayOptionsFromToWithServers(t, "A", "B", sb2)
4849 oa2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", sa1.ClusterAddr().Port))
4850 setAccountUserPassInOptions(oa2, "$foo", "clientA", "password")
4851 setAccountUserPassInOptions(oa2, "$bar", "yyyyyyy", "password")
4852 oa2.gatewaysSolicitDelay = time.Nanosecond // 0 would be default, so nano to connect asap
4853 sa2 := runGatewayServer(oa2)
4854 defer sa2.Shutdown()
4855
4856 ensureGWConnectTo(t, sa2, "B", sb2)
4857
4858 checkClusterFormed(t, sa1, sa2)
4859 checkClusterFormed(t, sb1, sb2)
4860
4861 waitForOutboundGateways(t, sa1, 1, time.Second)
4862 waitForOutboundGateways(t, sb1, 1, time.Second)
4863 waitForOutboundGateways(t, sb2, 1, time.Second)
4864 waitForOutboundGateways(t, sa2, 1, 2*time.Second)
4865
4866 waitForInboundGateways(t, sa1, 2, time.Second)
4867 waitForInboundGateways(t, sb1, 1, time.Second)
4868 waitForInboundGateways(t, sb2, 1, 2*time.Second)
4869 waitForInboundGateways(t, sa2, 0, time.Second)
4870
4871 // Verification that we have what we wanted
4872 c := sa2.getOutboundGatewayConnection("B")
4873 if c == nil || c.opts.Name != sb2.ID() {
4874 t.Fatalf("A2 does not have outbound to B2")
4875 }
4876 c = getInboundGatewayConnection(sa2, "B")
4877 if c != nil {
4878 t.Fatalf("Bad setup")
4879 }
4880 c = sb2.getOutboundGatewayConnection("A")
4881 if c == nil || c.opts.Name != sa1.ID() {
4882 t.Fatalf("B2 does not have outbound to A1")
4883 }
4884 c = getInboundGatewayConnection(sb2, "A")
4885 if c == nil || c.opts.Name != sa2.ID() {
4886 t.Fatalf("Bad setup")
4887 }
4888
4889 // Ok, so now that we have proper setup, do actual test!
4890
4891 // Get accounts
4892 fooA1, _ := sa1.LookupAccount("$foo")
4893 barA1, _ := sa1.LookupAccount("$bar")
4894 fooA2, _ := sa2.LookupAccount("$foo")
4895 barA2, _ := sa2.LookupAccount("$bar")
4896
4897 fooB1, _ := sb1.LookupAccount("$foo")
4898 barB1, _ := sb1.LookupAccount("$bar")
4899 fooB2, _ := sb2.LookupAccount("$foo")
4900 barB2, _ := sb2.LookupAccount("$bar")
4901
4902 var accs []*Account
4903 // Add in the service export for the requests.
4904 if !test.public {
4905 accs = []*Account{barA1}
4906 }
4907 require_NoError(t, fooA1.AddServiceExport("ngs.update.*", accs))
4908 if !test.public {
4909 accs = []*Account{barA2}
4910 }
4911 require_NoError(t, fooA2.AddServiceExport("ngs.update.*", accs))
4912 if !test.public {
4913 accs = []*Account{barB1}
4914 }
4915 require_NoError(t, fooB1.AddServiceExport("ngs.update.*", accs))
4916 if !test.public {
4917 accs = []*Account{barB2}
4918 }
4919 require_NoError(t, fooB2.AddServiceExport("ngs.update.*", accs))
4920
4921 // Add import abilities to server B's bar account from foo.
4922 if err := barB1.AddServiceImport(fooB1, "ngs.update", "ngs.update.$bar"); err != nil {
4923 t.Fatalf("Error adding service import: %v", err)
4924 }
4925 if err := barB2.AddServiceImport(fooB2, "ngs.update", "ngs.update.$bar"); err != nil {
4926 t.Fatalf("Error adding service import: %v", err)
4927 }
4928 // Same on A.
4929 if err := barA1.AddServiceImport(fooA1, "ngs.update", "ngs.update.$bar"); err != nil {
4930 t.Fatalf("Error adding service import: %v", err)
4931 }
4932 if err := barA2.AddServiceImport(fooA2, "ngs.update", "ngs.update.$bar"); err != nil {
4933 t.Fatalf("Error adding service import: %v", err)
4934 }
4935
4936 // clientA will be connected to A2 and be the service endpoint and responder.
4937 a2URL := fmt.Sprintf("nats://clientA:[email protected]:%d", oa2.Port)
4938 clientA := natsConnect(t, a2URL)
4939 defer clientA.Close()
4940
4941 subA := natsSubSync(t, clientA, "ngs.update.$bar")
4942 natsFlush(t, clientA)
4943
4944 // Now setup client B on B1 who will do a sub from account $bar
4945 // that should map account $foo's foo subject.
4946 b1URL := fmt.Sprintf("nats://clientB:[email protected]:%d", ob1.Port)
4947 clientB := natsConnect(t, b1URL)
4948 defer clientB.Close()
4949
4950 subB := natsSubSync(t, clientB, "reply")
4951 natsFlush(t, clientB)
4952
4953 // Ensure the subscription is known by the server we're connected to.
4954 time.Sleep(100 * time.Millisecond)
4955
4956 var msg *nats.Msg
4957 var err error
4958 for attempts := 1; attempts <= 2; attempts++ {
4959 // Send the request from clientB on foo.request,
4960 natsPubReq(t, clientB, "ngs.update", "reply", []byte("hi"))
4961 natsFlush(t, clientB)
4962
4963 // Expect the request on A
4964 msg, err = subA.NextMsg(time.Second)
4965 if err != nil {
4966 if attempts == 1 {
4967 // Since we are in interestOnly mode, it is possible
4968 // that server B did not receive the subscription
4969 // interest yet, so try again.
4970 continue
4971 }
4972 t.Fatalf("subA failed to get request: %v", err)
4973 }
4974 if msg.Subject != "ngs.update.$bar" || string(msg.Data) != "hi" {
4975 t.Fatalf("Unexpected message: %v", msg)
4976 }
4977 if msg.Reply == "reply" {
4978 t.Fatalf("Expected randomized reply, but got original")
4979 }
4980 }
4981 // Make sure we don't receive a second copy
4982 if msg, err := subA.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
4983 t.Fatalf("Received unexpected message: %v", msg)
4984 }
4985
4986 // Send reply
4987 natsPub(t, clientA, msg.Reply, []byte("ok"))
4988 natsFlush(t, clientA)
4989
4990 msg, err = subB.NextMsg(time.Second)
4991 if err != nil {
4992 t.Fatalf("subB failed to get reply: %v", err)
4993 }
4994 if msg.Subject != "reply" || string(msg.Data) != "ok" {
4995 t.Fatalf("Unexpected message: %v", msg)
4996 }
4997 // Make sure we don't receive a second copy
4998 if msg, err := subB.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
4999 t.Fatalf("Received unexpected message: %v", msg)
5000 }
5001
5002 checkSubs := func(t *testing.T, acc *Account, srvName string, expected int) {
5003 t.Helper()
5004 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
5005 if ts := acc.TotalSubs(); ts != expected {
5006 return fmt.Errorf("Number of subs is %d on acc=%s srv=%s, should be %v", ts, acc.Name, srvName, expected)
5007 }
5008 return nil
5009 })
5010 }
5011 checkSubs(t, fooA1, "A1", 1)
5012 checkSubs(t, barA1, "A1", 1)
5013 checkSubs(t, fooA2, "A2", 1)
5014 checkSubs(t, barA2, "A2", 1)
5015 checkSubs(t, fooB1, "B1", 1)
5016 checkSubs(t, barB1, "B1", 2)
5017 checkSubs(t, fooB2, "B2", 1)
5018 checkSubs(t, barB2, "B2", 2)
5019
5020 // Speed up expiration
5021 err = fooA1.SetServiceExportResponseThreshold("ngs.update.*", 10*time.Millisecond)
5022 if err != nil {
5023 t.Fatalf("Error setting response threshold: %v", err)
5024 }
5025 err = fooB1.SetServiceExportResponseThreshold("ngs.update.*", 10*time.Millisecond)
5026 if err != nil {
5027 t.Fatalf("Error setting response threshold: %v", err)
5028 }
5029
5030 // Send 100 requests from clientB on foo.request,
5031 for i := 0; i < 100; i++ {
5032 natsPubReq(t, clientB, "ngs.update", "reply", []byte("hi"))
5033 }
5034 natsFlush(t, clientB)
5035
5036 // Consume the requests, but don't reply to them...
5037 for i := 0; i < 100; i++ {
5038 if _, err := subA.NextMsg(time.Second); err != nil {
5039 t.Fatalf("subA did not receive request: %v", err)
5040 }
5041 }
5042
5043 // Unsubscribe all and ensure counts go to 0.
5044 natsUnsub(t, subA)
5045 natsFlush(t, clientA)
5046 natsUnsub(t, subB)
5047 natsFlush(t, clientB)
5048
5049 // We should expire because ttl.
5050 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
5051 if nr := len(fooA1.exports.responses); nr != 0 {
5052 return fmt.Errorf("Number of responses is %d", nr)
5053 }
5054 return nil
5055 })
5056
5057 checkSubs(t, fooA1, "A1", 0)
5058 checkSubs(t, fooA2, "A2", 0)
5059 checkSubs(t, fooB1, "B1", 1)
5060 checkSubs(t, fooB2, "B2", 1)
5061
5062 checkSubs(t, barA1, "A1", 1)
5063 checkSubs(t, barA2, "A2", 1)
5064 checkSubs(t, barB1, "B1", 1)
5065 checkSubs(t, barB2, "B2", 1)
5066
5067 // Check that this all work in interest-only mode.
5068
5069 // We need at least a subscription on B2 otherwise when publishing
5070 // to subjects with no interest we would simply get an A-
5071 b2URL := fmt.Sprintf("nats://clientBFoo:[email protected]:%d", ob2.Port)
5072 clientB2 := natsConnect(t, b2URL)
5073 defer clientB2.Close()
5074 natsSubSync(t, clientB2, "not.used")
5075 natsFlush(t, clientB2)
5076
5077 // Make A2 flood B2 with subjects that B2 is not interested in.
5078 for i := 0; i < 1100; i++ {
5079 natsPub(t, clientA, fmt.Sprintf("no.interest.%d", i), []byte("hello"))
5080 }
5081 natsFlush(t, clientA)
5082
5083 // Wait for B2 to switch to interest-only
5084 checkGWInterestOnlyMode(t, sa2, "B", "$foo")
5085
5086 subA = natsSubSync(t, clientA, "ngs.update.*")
5087 natsFlush(t, clientA)
5088
5089 subB = natsSubSync(t, clientB, "reply")
5090 natsFlush(t, clientB)
5091
5092 // Ensure the subscription is known by the server we're connected to.
5093 time.Sleep(100 * time.Millisecond)
5094
5095 for attempts := 1; attempts <= 2; attempts++ {
5096 // Send the request from clientB on foo.request,
5097 natsPubReq(t, clientB, "ngs.update", "reply", []byte("hi"))
5098 natsFlush(t, clientB)
5099
5100 // Expect the request on A
5101 msg, err = subA.NextMsg(time.Second)
5102 if err != nil {
5103 if attempts == 1 {
5104 // Since we are in interestOnly mode, it is possible
5105 // that server B did not receive the subscription
5106 // interest yet, so try again.
5107 continue
5108 }
5109 t.Fatalf("subA failed to get request: %v", err)
5110 }
5111 if msg.Subject != "ngs.update.$bar" || string(msg.Data) != "hi" {
5112 t.Fatalf("Unexpected message: %v", msg)
5113 }
5114 if msg.Reply == "reply" {
5115 t.Fatalf("Expected randomized reply, but got original")
5116 }
5117 }
5118
5119 // Check for duplicate message
5120 if msg, err := subA.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
5121 t.Fatalf("Unexpected msg: %v", msg)
5122 }
5123
5124 // Send reply
5125 natsPub(t, clientA, msg.Reply, []byte("ok"))
5126 natsFlush(t, clientA)
5127
5128 msg, err = subB.NextMsg(time.Second)
5129 if err != nil {
5130 t.Fatalf("subB failed to get reply: %v", err)
5131 }
5132 if msg.Subject != "reply" || string(msg.Data) != "ok" {
5133 t.Fatalf("Unexpected message: %v", msg)
5134 }
5135
5136 // Check for duplicate message
5137 if msg, err := subB.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
5138 t.Fatalf("Unexpected msg: %v", msg)
5139 }
5140 })
5141 }
5142 }
5143
5144 // NOTE: if this fails for you and says only has <10 outbound, make sure ulimit for open files > 256.
5145 func TestGatewayMemUsage(t *testing.T) {
5146 // Try to clean up.
5147 runtime.GC()
5148 var m runtime.MemStats
5149 runtime.ReadMemStats(&m)
5150 pta := m.TotalAlloc
5151
5152 o := testDefaultOptionsForGateway("A")
5153 s := runGatewayServer(o)
5154 defer s.Shutdown()
5155
5156 var servers []*Server
5157 servers = append(servers, s)
5158
5159 numServers := 10
5160 for i := 0; i < numServers; i++ {
5161 rn := fmt.Sprintf("RG_%d", i+1)
5162 o := testGatewayOptionsFromToWithServers(t, rn, "A", s)
5163 s := runGatewayServer(o)
5164 defer s.Shutdown()
5165 servers = append(servers, s)
5166 }
5167
5168 // Each server should have an outbound
5169 for _, s := range servers {
5170 waitForOutboundGateways(t, s, numServers, 2*time.Second)
5171 }
5172 // The first started server should have numServers inbounds (since
5173 // they all connect to it).
5174 waitForInboundGateways(t, s, numServers, 2*time.Second)
5175
5176 // Calculate in MB what we are using now.
5177 const max = 50 * 1024 * 1024 // 50MB
5178 runtime.ReadMemStats(&m)
5179 used := m.TotalAlloc - pta
5180 if used > max {
5181 t.Fatalf("Cluster using too much memory, expect < 50MB, got %dMB", used/(1024*1024))
5182 }
5183
5184 for _, s := range servers {
5185 s.Shutdown()
5186 }
5187 }
5188
5189 func TestGatewayMapReplyOnlyForRecentSub(t *testing.T) {
5190 o2 := testDefaultOptionsForGateway("B")
5191 s2 := runGatewayServer(o2)
5192 defer s2.Shutdown()
5193
5194 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
5195 s1 := runGatewayServer(o1)
5196 defer s1.Shutdown()
5197
5198 waitForOutboundGateways(t, s1, 1, time.Second)
5199 waitForOutboundGateways(t, s2, 1, time.Second)
5200
5201 // Change s1's recent sub expiration default value
5202 s1.mu.Lock()
5203 s1.gateway.pasi.Lock()
5204 s1.gateway.recSubExp = 100 * time.Millisecond
5205 s1.gateway.pasi.Unlock()
5206 s1.mu.Unlock()
5207
5208 // Setup a replier on s2
5209 nc2 := natsConnect(t, fmt.Sprintf("nats://%s:%d", o2.Host, o2.Port))
5210 defer nc2.Close()
5211 errCh := make(chan error, 1)
5212 natsSub(t, nc2, "foo", func(m *nats.Msg) {
5213 // Send reply regardless..
5214 nc2.Publish(m.Reply, []byte("reply"))
5215 // Check that reply given to application is not mapped.
5216 if !strings.HasPrefix(m.Reply, nats.InboxPrefix) {
5217 errCh <- fmt.Errorf("Reply expected to have normal inbox, got %v", m.Reply)
5218 return
5219 }
5220 errCh <- nil
5221 })
5222 natsFlush(t, nc2)
5223 checkExpectedSubs(t, 1, s2)
5224
5225 // Create requestor on s1
5226 nc1 := natsConnect(t, fmt.Sprintf("nats://%s:%d", o1.Host, o1.Port))
5227 defer nc1.Close()
5228 // Send first request, reply should be mapped
5229 nc1.Request("foo", []byte("msg1"), time.Second)
5230 // Wait more than the recent sub expiration (that we have set to 100ms)
5231 time.Sleep(200 * time.Millisecond)
5232 // Send second request (reply should not be mapped)
5233 nc1.Request("foo", []byte("msg2"), time.Second)
5234
5235 select {
5236 case e := <-errCh:
5237 if e != nil {
5238 t.Fatal(e.Error())
5239 }
5240 case <-time.After(time.Second):
5241 t.Fatalf("Did not get replies")
5242 }
5243 }
5244
5245 type delayedWriteConn struct {
5246 sync.Mutex
5247 net.Conn
5248 bytes [][]byte
5249 delay bool
5250 wg sync.WaitGroup
5251 }
5252
5253 func (c *delayedWriteConn) Write(b []byte) (int, error) {
5254 c.Lock()
5255 defer c.Unlock()
5256 if c.delay || len(c.bytes) > 0 {
5257 c.bytes = append(c.bytes, append([]byte(nil), b...))
5258 c.wg.Add(1)
5259 go func() {
5260 defer c.wg.Done()
5261 c.Lock()
5262 defer c.Unlock()
5263 if c.delay {
5264 c.Unlock()
5265 time.Sleep(100 * time.Millisecond)
5266 c.Lock()
5267 }
5268 if len(c.bytes) > 0 {
5269 b = c.bytes[0]
5270 c.bytes = c.bytes[1:]
5271 c.Conn.Write(b)
5272 }
5273 }()
5274 return len(b), nil
5275 }
5276 return c.Conn.Write(b)
5277 }
5278
5279 // This test uses a single account and makes sure that when
5280 // a reply subject is prefixed with $GR it comes back to
5281 // the origin cluster and delivered to proper reply subject
5282 // there, but also to subscribers on that reply subject
5283 // on the other cluster.
5284 func TestGatewaySendReplyAcrossGateways(t *testing.T) {
5285 for _, test := range []struct {
5286 name string
5287 poolSize int
5288 peracc bool
5289 }{
5290 {"no pooling", -1, false},
5291 {"pooling", 5, false},
5292 {"per account", 0, true},
5293 } {
5294 t.Run(test.name, func(t *testing.T) {
5295 ob := testDefaultOptionsForGateway("B")
5296 ob.Accounts = []*Account{NewAccount("ACC")}
5297 ob.Users = []*User{{Username: "user", Password: "pwd", Account: ob.Accounts[0]}}
5298 sb := runGatewayServer(ob)
5299 defer sb.Shutdown()
5300
5301 oa1 := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
5302 oa1.Cluster.PoolSize = test.poolSize
5303 if test.peracc {
5304 oa1.Cluster.PinnedAccounts = []string{"ACC"}
5305 }
5306 oa1.Accounts = []*Account{NewAccount("ACC")}
5307 oa1.Users = []*User{{Username: "user", Password: "pwd", Account: oa1.Accounts[0]}}
5308 sa1 := runGatewayServer(oa1)
5309 defer sa1.Shutdown()
5310
5311 waitForOutboundGateways(t, sb, 1, time.Second)
5312 waitForInboundGateways(t, sb, 1, time.Second)
5313 waitForOutboundGateways(t, sa1, 1, time.Second)
5314 waitForInboundGateways(t, sa1, 1, time.Second)
5315
5316 // Now start another server in cluster "A". This will allow us
5317 // to test the reply from cluster "B" coming back directly to
5318 // the server where the request originates, and indirectly through
5319 // route.
5320 oa2 := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
5321 oa2.Cluster.PoolSize = test.poolSize
5322 if test.peracc {
5323 oa2.Cluster.PinnedAccounts = []string{"ACC"}
5324 }
5325 oa2.Accounts = []*Account{NewAccount("ACC")}
5326 oa2.Users = []*User{{Username: "user", Password: "pwd", Account: oa2.Accounts[0]}}
5327 oa2.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", oa1.Cluster.Host, oa1.Cluster.Port))
5328 sa2 := runGatewayServer(oa2)
5329 defer sa2.Shutdown()
5330
5331 waitForOutboundGateways(t, sa2, 1, time.Second)
5332 waitForInboundGateways(t, sb, 2, time.Second)
5333 checkClusterFormed(t, sa1, sa2)
5334
5335 replySubj := "bar"
5336
5337 // Setup a responder on sb
5338 ncb := natsConnect(t, fmt.Sprintf("nats://user:pwd@%s:%d", ob.Host, ob.Port))
5339 defer ncb.Close()
5340 natsSub(t, ncb, "foo", func(m *nats.Msg) {
5341 m.Respond([]byte("reply"))
5342 })
5343 // Set a subscription on the reply subject on sb
5344 subSB := natsSubSync(t, ncb, replySubj)
5345 natsFlush(t, ncb)
5346 checkExpectedSubs(t, 2, sb)
5347
5348 testReqReply := func(t *testing.T, host string, port int, createSubOnA bool) {
5349 t.Helper()
5350 nca := natsConnect(t, fmt.Sprintf("nats://user:pwd@%s:%d", host, port))
5351 defer nca.Close()
5352 if createSubOnA {
5353 subSA := natsSubSync(t, nca, replySubj)
5354 natsPubReq(t, nca, "foo", replySubj, []byte("hello"))
5355 natsNexMsg(t, subSA, time.Second)
5356 // Check for duplicates
5357 if _, err := subSA.NextMsg(50 * time.Millisecond); err == nil {
5358 t.Fatalf("Received duplicate message on subSA!")
5359 }
5360 } else {
5361 natsPubReq(t, nca, "foo", replySubj, []byte("hello"))
5362 }
5363 natsNexMsg(t, subSB, time.Second)
5364 // Check for duplicates
5365 if _, err := subSB.NextMsg(50 * time.Millisecond); err == nil {
5366 t.Fatalf("Received duplicate message on subSB!")
5367 }
5368 }
5369 // Create requestor on sa1 to check for direct reply from GW:
5370 testReqReply(t, oa1.Host, oa1.Port, true)
5371 // Wait for subscription to be gone...
5372 checkExpectedSubs(t, 0, sa1)
5373 // Now create requestor on sa2, it will receive reply through sa1.
5374 testReqReply(t, oa2.Host, oa2.Port, true)
5375 checkExpectedSubs(t, 0, sa1)
5376 checkExpectedSubs(t, 0, sa2)
5377
5378 // Now issue requests but without any interest in the requestor's
5379 // origin cluster and make sure the other cluster gets the reply.
5380 testReqReply(t, oa1.Host, oa1.Port, false)
5381 testReqReply(t, oa2.Host, oa2.Port, false)
5382
5383 // There is a possible race between sa2 sending the RS+ for the
5384 // subscription on the reply subject, and the GW reply making it
5385 // to sa1 before the RS+ is processed there.
5386 // We are going to force this race by making the route connection
5387 // block as needed.
5388
5389 acc, _ := sa2.LookupAccount("ACC")
5390 acc.mu.RLock()
5391 api := acc.routePoolIdx
5392 acc.mu.RUnlock()
5393
5394 var route *client
5395 sa2.mu.Lock()
5396 if test.peracc {
5397 if conns, ok := sa2.accRoutes["ACC"]; ok {
5398 for _, r := range conns {
5399 route = r
5400 break
5401 }
5402 }
5403 } else if test.poolSize > 0 {
5404 sa2.forEachRoute(func(r *client) {
5405 r.mu.Lock()
5406 if r.route.poolIdx == api {
5407 route = r
5408 }
5409 r.mu.Unlock()
5410 })
5411 } else if r := getFirstRoute(sa2); r != nil {
5412 route = r
5413 }
5414 sa2.mu.Unlock()
5415 route.mu.Lock()
5416 routeConn := &delayedWriteConn{
5417 Conn: route.nc,
5418 wg: sync.WaitGroup{},
5419 }
5420 route.nc = routeConn
5421 route.mu.Unlock()
5422
5423 delayRoute := func() {
5424 routeConn.Lock()
5425 routeConn.delay = true
5426 routeConn.Unlock()
5427 }
5428 stopDelayRoute := func() {
5429 routeConn.Lock()
5430 routeConn.delay = false
5431 wg := &routeConn.wg
5432 routeConn.Unlock()
5433 wg.Wait()
5434 }
5435
5436 delayRoute()
5437 testReqReply(t, oa2.Host, oa2.Port, true)
5438 stopDelayRoute()
5439
5440 // Same test but now we have a local interest on the reply subject
5441 // on sa1 to make sure that interest there does not prevent sending
5442 // the RMSG to sa2, which is the origin of the request.
5443 checkExpectedSubs(t, 0, sa1)
5444 checkExpectedSubs(t, 0, sa2)
5445 nca1 := natsConnect(t, fmt.Sprintf("nats://user:pwd@%s:%d", oa1.Host, oa1.Port))
5446 defer nca1.Close()
5447 subSA1 := natsSubSync(t, nca1, replySubj)
5448 natsFlush(t, nca1)
5449 checkExpectedSubs(t, 1, sa1)
5450 checkExpectedSubs(t, 1, sa2)
5451
5452 delayRoute()
5453 testReqReply(t, oa2.Host, oa2.Port, true)
5454 stopDelayRoute()
5455
5456 natsNexMsg(t, subSA1, time.Second)
5457 })
5458 }
5459 }
5460
5461 // This test will have a requestor on cluster A and responder
5462 // on cluster B, but when the responder sends the response,
5463 // it will also have a reply subject to receive a response
5464 // for the response.
5465 func TestGatewayPingPongReplyAcrossGateways(t *testing.T) {
5466 ob := testDefaultOptionsForGateway("B")
5467 ob.Accounts = []*Account{NewAccount("ACC")}
5468 ob.Users = []*User{{Username: "user", Password: "pwd", Account: ob.Accounts[0]}}
5469 sb := runGatewayServer(ob)
5470 defer sb.Shutdown()
5471
5472 oa1 := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
5473 oa1.Accounts = []*Account{NewAccount("ACC")}
5474 oa1.Users = []*User{{Username: "user", Password: "pwd", Account: oa1.Accounts[0]}}
5475 sa1 := runGatewayServer(oa1)
5476 defer sa1.Shutdown()
5477
5478 waitForOutboundGateways(t, sb, 1, time.Second)
5479 waitForInboundGateways(t, sb, 1, time.Second)
5480 waitForOutboundGateways(t, sa1, 1, time.Second)
5481 waitForInboundGateways(t, sa1, 1, time.Second)
5482
5483 // Now start another server in cluster "A". This will allow us
5484 // to test the reply from cluster "B" coming back directly to
5485 // the server where the request originates, and indirectly through
5486 // route.
5487 oa2 := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
5488 oa2.Accounts = []*Account{NewAccount("ACC")}
5489 oa2.Users = []*User{{Username: "user", Password: "pwd", Account: oa2.Accounts[0]}}
5490 oa2.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", oa1.Cluster.Host, oa1.Cluster.Port))
5491 sa2 := runGatewayServer(oa2)
5492 defer sa2.Shutdown()
5493
5494 waitForOutboundGateways(t, sa2, 1, time.Second)
5495 waitForInboundGateways(t, sb, 2, time.Second)
5496 checkClusterFormed(t, sa1, sa2)
5497
5498 // Setup a responder on sb
5499 ncb := natsConnect(t, fmt.Sprintf("nats://user:pwd@%s:%d", ob.Host, ob.Port))
5500 defer ncb.Close()
5501 sbReplySubj := "sbreply"
5502 subSB := natsSubSync(t, ncb, sbReplySubj)
5503 natsSub(t, ncb, "foo", func(m *nats.Msg) {
5504 ncb.PublishRequest(m.Reply, sbReplySubj, []byte("sb reply"))
5505 })
5506 natsFlush(t, ncb)
5507 checkExpectedSubs(t, 2, sb)
5508
5509 testReqReply := func(t *testing.T, host string, port int) {
5510 t.Helper()
5511 nca := natsConnect(t, fmt.Sprintf("nats://user:pwd@%s:%d", host, port))
5512 defer nca.Close()
5513 msg, err := nca.Request("foo", []byte("sa request"), time.Second)
5514 if err != nil {
5515 t.Fatalf("Did not get response: %v", err)
5516 }
5517 // Check response from sb, it should have content "sb reply" and
5518 // reply subject should not have GW prefix
5519 if string(msg.Data) != "sb reply" || msg.Reply != sbReplySubj {
5520 t.Fatalf("Unexpected message from sb: %+v", msg)
5521 }
5522 // Now send our own reply:
5523 nca.Publish(msg.Reply, []byte("sa reply"))
5524 // And make sure that subS2 receives it...
5525 msg = natsNexMsg(t, subSB, time.Second)
5526 if string(msg.Data) != "sa reply" || msg.Reply != _EMPTY_ {
5527 t.Fatalf("Unexpected message from sa: %v", msg)
5528 }
5529 }
5530 // Create requestor on sa1 to check for direct reply from GW:
5531 testReqReply(t, oa1.Host, oa1.Port)
5532 // Now from sa2 to see reply coming from route (sa1)
5533 testReqReply(t, oa2.Host, oa2.Port)
5534 }
5535
5536 // Similar to TestGatewaySendReplyAcrossGateways, but this time
5537 // with service import.
5538 func TestGatewaySendReplyAcrossGatewaysServiceImport(t *testing.T) {
5539 ob := testDefaultOptionsForGateway("B")
5540 setAccountUserPassInOptions(ob, "$foo", "clientBFoo", "password")
5541 setAccountUserPassInOptions(ob, "$bar", "clientBBar", "password")
5542 sb := runGatewayServer(ob)
5543 defer sb.Shutdown()
5544
5545 oa1 := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
5546 oa1.Cluster.PoolSize = 1
5547 setAccountUserPassInOptions(oa1, "$foo", "clientAFoo", "password")
5548 setAccountUserPassInOptions(oa1, "$bar", "clientABar", "password")
5549 sa1 := runGatewayServer(oa1)
5550 defer sa1.Shutdown()
5551
5552 waitForOutboundGateways(t, sb, 1, time.Second)
5553 waitForInboundGateways(t, sb, 1, time.Second)
5554 waitForOutboundGateways(t, sa1, 1, time.Second)
5555 waitForInboundGateways(t, sa1, 1, time.Second)
5556
5557 oa2 := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
5558 oa2.Cluster.PoolSize = 1
5559 setAccountUserPassInOptions(oa2, "$foo", "clientAFoo", "password")
5560 setAccountUserPassInOptions(oa2, "$bar", "clientABar", "password")
5561 oa2.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", oa1.Cluster.Host, oa1.Cluster.Port))
5562 sa2 := runGatewayServer(oa2)
5563 defer sa2.Shutdown()
5564
5565 oa3 := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
5566 oa3.Cluster.PoolSize = 1
5567 setAccountUserPassInOptions(oa3, "$foo", "clientAFoo", "password")
5568 setAccountUserPassInOptions(oa3, "$bar", "clientABar", "password")
5569 oa3.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", oa1.Cluster.Host, oa1.Cluster.Port))
5570 sa3 := runGatewayServer(oa3)
5571 defer sa3.Shutdown()
5572
5573 waitForOutboundGateways(t, sa2, 1, time.Second)
5574 waitForOutboundGateways(t, sa3, 1, time.Second)
5575 waitForInboundGateways(t, sb, 3, time.Second)
5576 checkClusterFormed(t, sa1, sa2, sa3)
5577
5578 // Setup account on B
5579 fooB, _ := sb.LookupAccount("$foo")
5580 // Add in the service export for the requests. Make it public.
5581 fooB.AddServiceExport("foo.request", nil)
5582
5583 // Setup accounts on sa1, sa2 and sa3
5584 setupAccsOnA := func(s *Server) {
5585 // Get accounts
5586 fooA, _ := s.LookupAccount("$foo")
5587 barA, _ := s.LookupAccount("$bar")
5588 // Add in the service export for the requests. Make it public.
5589 fooA.AddServiceExport("foo.request", nil)
5590 // Add import abilities to server A's bar account from foo.
5591 if err := barA.AddServiceImport(fooA, "bar.request", "foo.request"); err != nil {
5592 t.Fatalf("Error adding service import: %v", err)
5593 }
5594 }
5595 setupAccsOnA(sa1)
5596 setupAccsOnA(sa2)
5597 setupAccsOnA(sa3)
5598
5599 // clientB will be connected to sb and be the service endpoint and responder.
5600 bURL := fmt.Sprintf("nats://clientBFoo:[email protected]:%d", ob.Port)
5601 clientBFoo := natsConnect(t, bURL)
5602 defer clientBFoo.Close()
5603 subBFoo := natsSubSync(t, clientBFoo, "foo.request")
5604 natsFlush(t, clientBFoo)
5605
5606 // Create another client on B for account $bar that will listen to
5607 // the reply subject.
5608 bURL = fmt.Sprintf("nats://clientBBar:[email protected]:%d", ob.Port)
5609 clientBBar := natsConnect(t, bURL)
5610 defer clientBBar.Close()
5611 replySubj := "reply"
5612 subBReply := natsSubSync(t, clientBBar, replySubj)
5613 natsFlush(t, clientBBar)
5614
5615 testServiceImport := func(t *testing.T, host string, port int) {
5616 t.Helper()
5617 bURL := fmt.Sprintf("nats://clientABar:password@%s:%d", host, port)
5618 clientABar := natsConnect(t, bURL)
5619 defer clientABar.Close()
5620 subAReply := natsSubSync(t, clientABar, replySubj)
5621 natsFlush(t, clientABar)
5622
5623 // Send the request from clientA on bar.request, which
5624 // will be translated to foo.request and sent over.
5625 natsPubReq(t, clientABar, "bar.request", replySubj, []byte("hi"))
5626 natsFlush(t, clientABar)
5627
5628 // Expect the request to be received on subAFoo
5629 msg, err := subBFoo.NextMsg(time.Second)
5630 if err != nil {
5631 t.Fatalf("subBFoo failed to get request: %v", err)
5632 }
5633 if msg.Subject != "foo.request" || string(msg.Data) != "hi" {
5634 t.Fatalf("Unexpected message: %v", msg)
5635 }
5636 if msg.Reply == replySubj {
5637 t.Fatalf("Expected randomized reply, but got original")
5638 }
5639
5640 // Check for duplicate message
5641 if msg, err := subBFoo.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
5642 t.Fatalf("Unexpected msg: %v", msg)
5643 }
5644
5645 // Send reply
5646 natsPub(t, clientBFoo, msg.Reply, []byte("ok-42"))
5647 natsFlush(t, clientBFoo)
5648
5649 // Now check that the subscription on the reply receives the message...
5650 checkReply := func(t *testing.T, sub *nats.Subscription) {
5651 t.Helper()
5652 msg, err = sub.NextMsg(time.Second)
5653 if err != nil {
5654 t.Fatalf("sub failed to get reply: %v", err)
5655 }
5656 if msg.Subject != replySubj || string(msg.Data) != "ok-42" {
5657 t.Fatalf("Unexpected message: %v", msg)
5658 }
5659 }
5660 // Check subscription on A (where the request originated)
5661 checkReply(t, subAReply)
5662 // And the subscription on B (where the responder is located)
5663 checkReply(t, subBReply)
5664 }
5665
5666 // We check the service import with GW working ok with either
5667 // direct connection between the responder's server to the
5668 // requestor's server and also through routes.
5669 testServiceImport(t, oa1.Host, oa1.Port)
5670 testServiceImport(t, oa2.Host, oa2.Port)
5671 // sa1 is the one receiving the reply from GW between B and A.
5672 // Check that the server routes directly to the server
5673 // with the interest.
5674 checkRoute := func(t *testing.T, s *Server, expected int64) {
5675 t.Helper()
5676 s.mu.Lock()
5677 defer s.mu.Unlock()
5678 s.forEachRoute(func(r *client) {
5679 r.mu.Lock()
5680 if r.route.remoteID != sa1.ID() {
5681 r.mu.Unlock()
5682 return
5683 }
5684 inMsgs := atomic.LoadInt64(&r.inMsgs)
5685 r.mu.Unlock()
5686 if inMsgs != expected {
5687 t.Fatalf("Expected %v incoming msgs, got %v", expected, inMsgs)
5688 }
5689 })
5690 }
5691 // Wait a bit to make sure that we don't have a loop that
5692 // cause messages to be routed more than needed.
5693 time.Sleep(100 * time.Millisecond)
5694 checkRoute(t, sa2, 1)
5695 checkRoute(t, sa3, 0)
5696
5697 testServiceImport(t, oa3.Host, oa3.Port)
5698 // Wait a bit to make sure that we don't have a loop that
5699 // cause messages to be routed more than needed.
5700 time.Sleep(100 * time.Millisecond)
5701 checkRoute(t, sa2, 1)
5702 checkRoute(t, sa3, 1)
5703 }
5704
5705 func TestGatewayClientsDontReceiveMsgsOnGWPrefix(t *testing.T) {
5706 ob := testDefaultOptionsForGateway("B")
5707 sb := runGatewayServer(ob)
5708 defer sb.Shutdown()
5709
5710 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
5711 sa := runGatewayServer(oa)
5712 defer sa.Shutdown()
5713
5714 waitForOutboundGateways(t, sa, 1, time.Second)
5715 waitForInboundGateways(t, sa, 1, time.Second)
5716 waitForOutboundGateways(t, sb, 1, time.Second)
5717 waitForInboundGateways(t, sb, 1, time.Second)
5718
5719 // Setup a responder on sb
5720 ncb := natsConnect(t, fmt.Sprintf("nats://%s:%d", ob.Host, ob.Port))
5721 defer ncb.Close()
5722 natsSub(t, ncb, "foo", func(m *nats.Msg) {
5723 if strings.HasPrefix(m.Reply, gwReplyPrefix) {
5724 m.Respond([]byte(fmt.Sprintf("-ERR: received request with mapped reply subject %q", m.Reply)))
5725 } else {
5726 m.Respond([]byte("+OK: reply"))
5727 }
5728 })
5729 // And create a sub on ">" that should not get the $GR reply.
5730 subSB := natsSubSync(t, ncb, ">")
5731 natsFlush(t, ncb)
5732 checkExpectedSubs(t, 2, sb)
5733
5734 nca := natsConnect(t, fmt.Sprintf("nats://%s:%d", oa.Host, oa.Port))
5735 defer nca.Close()
5736 msg, err := nca.Request("foo", []byte("request"), time.Second)
5737 if err != nil {
5738 t.Fatalf("Did not get response: %v", err)
5739 }
5740 if string(msg.Data) != "+OK: reply" {
5741 t.Fatalf("Error from responder: %q", msg.Data)
5742 }
5743
5744 // subSB would have also received the request, so drop that one.
5745 msg = natsNexMsg(t, subSB, time.Second)
5746 if string(msg.Data) != "request" {
5747 t.Fatalf("Wrong request: %q", msg.Data)
5748 }
5749 // Once sa gets the direct reply, it should resend the reply
5750 // with normal subject. So subSB should get the message with
5751 // a subject that does not start with $GNR prefix.
5752 msg = natsNexMsg(t, subSB, time.Second)
5753 if string(msg.Data) != "+OK: reply" || strings.HasPrefix(msg.Subject, gwReplyPrefix) {
5754 t.Fatalf("Unexpected message from sa: %v", msg)
5755 }
5756 // Check no more message...
5757 if m, err := subSB.NextMsg(100 * time.Millisecond); m != nil || err == nil {
5758 t.Fatalf("Expected only 1 message, got %+v", m)
5759 }
5760 }
5761
5762 func TestGatewayNoAccInterestThenQSubThenRegularSub(t *testing.T) {
5763 GatewayDoNotForceInterestOnlyMode(true)
5764 defer GatewayDoNotForceInterestOnlyMode(false)
5765
5766 ob := testDefaultOptionsForGateway("B")
5767 sb := runGatewayServer(ob)
5768 defer sb.Shutdown()
5769
5770 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
5771 sa := runGatewayServer(oa)
5772 defer sa.Shutdown()
5773
5774 waitForOutboundGateways(t, sa, 1, time.Second)
5775 waitForInboundGateways(t, sa, 1, time.Second)
5776 waitForOutboundGateways(t, sb, 1, time.Second)
5777 waitForInboundGateways(t, sb, 1, time.Second)
5778
5779 // Connect on A and send a message
5780 ncA := natsConnect(t, fmt.Sprintf("nats://%s:%d", oa.Host, oa.Port))
5781 defer ncA.Close()
5782 natsPub(t, ncA, "foo", []byte("hello"))
5783 natsFlush(t, ncA)
5784
5785 // expect an A- on return
5786 gwb := sa.getOutboundGatewayConnection("B")
5787 checkForAccountNoInterest(t, gwb, globalAccountName, true, time.Second)
5788
5789 // Create a connection o B, and create a queue sub first
5790 ncB := natsConnect(t, fmt.Sprintf("nats://%s:%d", ob.Host, ob.Port))
5791 defer ncB.Close()
5792 qsub := natsQueueSubSync(t, ncB, "bar", "queue")
5793 natsFlush(t, ncB)
5794
5795 // A should have received a queue interest
5796 checkForRegisteredQSubInterest(t, sa, "B", globalAccountName, "bar", 1, time.Second)
5797
5798 // Now on B, create a regular sub
5799 sub := natsSubSync(t, ncB, "baz")
5800 natsFlush(t, ncB)
5801
5802 // From A now, produce a message on each subject and
5803 // expect both subs to receive their message.
5804 msgForQSub := []byte("msg_qsub")
5805 natsPub(t, ncA, "bar", msgForQSub)
5806 natsFlush(t, ncA)
5807
5808 if msg := natsNexMsg(t, qsub, time.Second); !bytes.Equal(msgForQSub, msg.Data) {
5809 t.Fatalf("Expected msg for queue sub to be %q, got %q", msgForQSub, msg.Data)
5810 }
5811
5812 // Publish for the regular sub
5813 msgForSub := []byte("msg_sub")
5814 natsPub(t, ncA, "baz", msgForSub)
5815 natsFlush(t, ncA)
5816
5817 if msg := natsNexMsg(t, sub, time.Second); !bytes.Equal(msgForSub, msg.Data) {
5818 t.Fatalf("Expected msg for sub to be %q, got %q", msgForSub, msg.Data)
5819 }
5820 }
5821
5822 // Similar to TestGatewayNoAccInterestThenQSubThenRegularSub but simulate
5823 // older incorrect behavior.
5824 func TestGatewayHandleUnexpectedASubUnsub(t *testing.T) {
5825 GatewayDoNotForceInterestOnlyMode(true)
5826 defer GatewayDoNotForceInterestOnlyMode(false)
5827
5828 ob := testDefaultOptionsForGateway("B")
5829 sb := runGatewayServer(ob)
5830 defer sb.Shutdown()
5831
5832 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
5833 sa := runGatewayServer(oa)
5834 defer sa.Shutdown()
5835
5836 waitForOutboundGateways(t, sa, 1, time.Second)
5837 waitForInboundGateways(t, sa, 1, time.Second)
5838 waitForOutboundGateways(t, sb, 1, time.Second)
5839 waitForInboundGateways(t, sb, 1, time.Second)
5840
5841 // Connect on A and send a message
5842 ncA := natsConnect(t, fmt.Sprintf("nats://%s:%d", oa.Host, oa.Port))
5843 defer ncA.Close()
5844 natsPub(t, ncA, "foo", []byte("hello"))
5845 natsFlush(t, ncA)
5846
5847 // expect an A- on return
5848 gwb := sa.getOutboundGatewayConnection("B")
5849 checkForAccountNoInterest(t, gwb, globalAccountName, true, time.Second)
5850
5851 // Create a connection o B, and create a queue sub first
5852 ncB := natsConnect(t, fmt.Sprintf("nats://%s:%d", ob.Host, ob.Port))
5853 defer ncB.Close()
5854 qsub := natsQueueSubSync(t, ncB, "bar", "queue")
5855 natsFlush(t, ncB)
5856
5857 // A should have received a queue interest
5858 checkForRegisteredQSubInterest(t, sa, "B", globalAccountName, "bar", 1, time.Second)
5859
5860 // Now on B, create a regular sub
5861 sub := natsSubSync(t, ncB, "baz")
5862 natsFlush(t, ncB)
5863 // and reproduce old, wrong, behavior that would have resulted in sending an A-
5864 gwA := getInboundGatewayConnection(sb, "A")
5865 gwA.mu.Lock()
5866 gwA.enqueueProto([]byte("A- $G\r\n"))
5867 gwA.mu.Unlock()
5868
5869 // From A now, produce a message on each subject and
5870 // expect both subs to receive their message.
5871 msgForQSub := []byte("msg_qsub")
5872 natsPub(t, ncA, "bar", msgForQSub)
5873 natsFlush(t, ncA)
5874
5875 if msg := natsNexMsg(t, qsub, time.Second); !bytes.Equal(msgForQSub, msg.Data) {
5876 t.Fatalf("Expected msg for queue sub to be %q, got %q", msgForQSub, msg.Data)
5877 }
5878
5879 // Publish for the regular sub
5880 msgForSub := []byte("msg_sub")
5881 natsPub(t, ncA, "baz", msgForSub)
5882 natsFlush(t, ncA)
5883
5884 if msg := natsNexMsg(t, sub, time.Second); !bytes.Equal(msgForSub, msg.Data) {
5885 t.Fatalf("Expected msg for sub to be %q, got %q", msgForSub, msg.Data)
5886 }
5887
5888 // Remove all subs on B.
5889 qsub.Unsubscribe()
5890 sub.Unsubscribe()
5891 ncB.Flush()
5892
5893 // Produce a message from A expect A-
5894 natsPub(t, ncA, "foo", []byte("hello"))
5895 natsFlush(t, ncA)
5896
5897 // expect an A- on return
5898 checkForAccountNoInterest(t, gwb, globalAccountName, true, time.Second)
5899
5900 // Simulate B sending another A-, on A account no interest should remain same.
5901 gwA.mu.Lock()
5902 gwA.enqueueProto([]byte("A- $G\r\n"))
5903 gwA.mu.Unlock()
5904
5905 checkForAccountNoInterest(t, gwb, globalAccountName, true, time.Second)
5906
5907 // Create a queue sub on B
5908 qsub = natsQueueSubSync(t, ncB, "bar", "queue")
5909 natsFlush(t, ncB)
5910
5911 checkForRegisteredQSubInterest(t, sa, "B", globalAccountName, "bar", 1, time.Second)
5912
5913 // Make B send an A+ and verify that we sitll have the registered qsub interest
5914 gwA.mu.Lock()
5915 gwA.enqueueProto([]byte("A+ $G\r\n"))
5916 gwA.mu.Unlock()
5917
5918 // Give a chance to A to possibly misbehave when receiving this proto
5919 time.Sleep(250 * time.Millisecond)
5920 // Now check interest is still there
5921 checkForRegisteredQSubInterest(t, sa, "B", globalAccountName, "bar", 1, time.Second)
5922
5923 qsub.Unsubscribe()
5924 natsFlush(t, ncB)
5925 checkForRegisteredQSubInterest(t, sa, "B", globalAccountName, "bar", 0, time.Second)
5926
5927 // Send A-, server A should set entry to nil
5928 gwA.mu.Lock()
5929 gwA.enqueueProto([]byte("A- $G\r\n"))
5930 gwA.mu.Unlock()
5931 checkForAccountNoInterest(t, gwb, globalAccountName, true, time.Second)
5932
5933 // Send A+ and entry should be removed since there is no longer reason to
5934 // keep the entry.
5935 gwA.mu.Lock()
5936 gwA.enqueueProto([]byte("A+ $G\r\n"))
5937 gwA.mu.Unlock()
5938 checkForAccountNoInterest(t, gwb, globalAccountName, false, time.Second)
5939
5940 // Last A+ should not change because account already removed from map.
5941 gwA.mu.Lock()
5942 gwA.enqueueProto([]byte("A+ $G\r\n"))
5943 gwA.mu.Unlock()
5944 checkForAccountNoInterest(t, gwb, globalAccountName, false, time.Second)
5945 }
5946
5947 type captureGWInterestSwitchLogger struct {
5948 DummyLogger
5949 imss []string
5950 }
5951
5952 func (l *captureGWInterestSwitchLogger) Debugf(format string, args ...any) {
5953 l.Lock()
5954 msg := fmt.Sprintf(format, args...)
5955 if strings.Contains(msg, fmt.Sprintf("switching account %q to %s mode", globalAccountName, InterestOnly)) ||
5956 strings.Contains(msg, fmt.Sprintf("switching account %q to %s mode complete", globalAccountName, InterestOnly)) {
5957 l.imss = append(l.imss, msg)
5958 }
5959 l.Unlock()
5960 }
5961
5962 func TestGatewayLogAccountInterestModeSwitch(t *testing.T) {
5963 GatewayDoNotForceInterestOnlyMode(true)
5964 defer GatewayDoNotForceInterestOnlyMode(false)
5965
5966 ob := testDefaultOptionsForGateway("B")
5967 sb := runGatewayServer(ob)
5968 defer sb.Shutdown()
5969
5970 logB := &captureGWInterestSwitchLogger{}
5971 sb.SetLogger(logB, true, true)
5972
5973 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
5974 sa := runGatewayServer(oa)
5975 defer sa.Shutdown()
5976
5977 logA := &captureGWInterestSwitchLogger{}
5978 sa.SetLogger(logA, true, true)
5979
5980 waitForOutboundGateways(t, sa, 1, 2*time.Second)
5981 waitForInboundGateways(t, sa, 1, 2*time.Second)
5982 waitForOutboundGateways(t, sb, 1, 2*time.Second)
5983 waitForInboundGateways(t, sb, 1, 2*time.Second)
5984
5985 ncB := natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", ob.Port))
5986 defer ncB.Close()
5987 natsSubSync(t, ncB, "foo")
5988 natsFlush(t, ncB)
5989
5990 ncA := natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", oa.Port))
5991 defer ncA.Close()
5992 for i := 0; i < gatewayMaxRUnsubBeforeSwitch+10; i++ {
5993 subj := fmt.Sprintf("bar.%d", i)
5994 natsPub(t, ncA, subj, []byte("hello"))
5995 }
5996 natsFlush(t, ncA)
5997
5998 gwA := getInboundGatewayConnection(sb, "A")
5999 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
6000 mode := Optimistic
6001 gwA.mu.Lock()
6002 e := gwA.gw.insim[globalAccountName]
6003 if e != nil {
6004 mode = e.mode
6005 }
6006 gwA.mu.Unlock()
6007 if mode != InterestOnly {
6008 return fmt.Errorf("not switched yet")
6009 }
6010 return nil
6011 })
6012
6013 checkGWInterestOnlyMode(t, sa, "B", globalAccountName)
6014
6015 checkLog := func(t *testing.T, l *captureGWInterestSwitchLogger) {
6016 t.Helper()
6017 l.Lock()
6018 logs := append([]string(nil), l.imss...)
6019 l.Unlock()
6020
6021 if len(logs) != 2 {
6022 t.Fatalf("Expected 2 logs about switching to interest-only, got %v", logs)
6023 }
6024 if !strings.Contains(logs[0], "switching account") {
6025 t.Fatalf("First log statement should have been about switching, got %v", logs[0])
6026 }
6027 if !strings.Contains(logs[1], "complete") {
6028 t.Fatalf("Second log statement should have been about having switched, got %v", logs[1])
6029 }
6030 }
6031 checkLog(t, logB)
6032 checkLog(t, logA)
6033
6034 // Clear log of server B
6035 logB.Lock()
6036 logB.imss = nil
6037 logB.Unlock()
6038
6039 // Force a switch on B to inbound gateway from A and make sure that it is
6040 // a no-op since this gateway connection has already been switched.
6041 sb.switchAccountToInterestMode(globalAccountName)
6042
6043 logB.Lock()
6044 didSwitch := len(logB.imss) > 0
6045 logB.Unlock()
6046 if didSwitch {
6047 t.Fatalf("Attempted to switch while it was already in interest mode only")
6048 }
6049 }
6050
6051 func TestGatewayAccountInterestModeSwitchOnlyOncePerAccount(t *testing.T) {
6052 GatewayDoNotForceInterestOnlyMode(true)
6053 defer GatewayDoNotForceInterestOnlyMode(false)
6054
6055 ob := testDefaultOptionsForGateway("B")
6056 sb := runGatewayServer(ob)
6057 defer sb.Shutdown()
6058
6059 logB := &captureGWInterestSwitchLogger{}
6060 sb.SetLogger(logB, true, true)
6061
6062 nc := natsConnect(t, sb.ClientURL())
6063 defer nc.Close()
6064 natsSubSync(t, nc, "foo")
6065 natsQueueSubSync(t, nc, "bar", "baz")
6066
6067 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
6068 sa := runGatewayServer(oa)
6069 defer sa.Shutdown()
6070
6071 waitForOutboundGateways(t, sa, 1, 2*time.Second)
6072 waitForInboundGateways(t, sa, 1, 2*time.Second)
6073 waitForOutboundGateways(t, sb, 1, 2*time.Second)
6074 waitForInboundGateways(t, sb, 1, 2*time.Second)
6075
6076 wg := sync.WaitGroup{}
6077 total := 20
6078 wg.Add(total)
6079 for i := 0; i < total; i++ {
6080 go func() {
6081 sb.switchAccountToInterestMode(globalAccountName)
6082 wg.Done()
6083 }()
6084 }
6085 wg.Wait()
6086 time.Sleep(50 * time.Millisecond)
6087 logB.Lock()
6088 nl := len(logB.imss)
6089 logB.Unlock()
6090 // There should be a trace for switching and when switch is complete
6091 if nl != 2 {
6092 t.Fatalf("Attempted to switch account too many times, number lines=%v", nl)
6093 }
6094 }
6095
6096 func TestGatewaySingleOutbound(t *testing.T) {
6097 l, err := natsListen("tcp", "127.0.0.1:0")
6098 if err != nil {
6099 t.Fatalf("Error on listen: %v", err)
6100 }
6101 defer l.Close()
6102 port := l.Addr().(*net.TCPAddr).Port
6103
6104 oa := testGatewayOptionsFromToWithTLS(t, "A", "B", []string{fmt.Sprintf("nats://127.0.0.1:%d", port)})
6105 oa.Gateway.TLSTimeout = 0.1
6106 sa := runGatewayServer(oa)
6107 defer sa.Shutdown()
6108
6109 // Wait a bit for reconnections
6110 time.Sleep(500 * time.Millisecond)
6111
6112 // Now prepare gateway B to take place of the bare listener.
6113 ob := testGatewayOptionsWithTLS(t, "B")
6114 // There is a risk that when stopping the listener and starting
6115 // the actual server, that port is being reused by some other process.
6116 ob.Gateway.Port = port
6117 l.Close()
6118 sb := runGatewayServer(ob)
6119 defer sb.Shutdown()
6120
6121 // To make sure that we don't fail, bump the TLSTimeout now.
6122 cfg := sa.getRemoteGateway("B")
6123 cfg.Lock()
6124 cfg.TLSTimeout = 2.0
6125 cfg.Unlock()
6126
6127 waitForOutboundGateways(t, sa, 1, time.Second)
6128 sa.gateway.Lock()
6129 lm := len(sa.gateway.out)
6130 sa.gateway.Unlock()
6131 if lm != 1 {
6132 t.Fatalf("Expected 1 outbound, got %v", lm)
6133 }
6134 }
6135
6136 func TestGatewayReplyMapTracking(t *testing.T) {
6137 // Increase the recSubExp value on servers so we have time
6138 // to check the replies mapping structures.
6139 subExp := 400 * time.Millisecond
6140 setRecSub := func(s *Server) {
6141 s.gateway.pasi.Lock()
6142 s.gateway.recSubExp = subExp
6143 s.gateway.pasi.Unlock()
6144 }
6145
6146 ob := testDefaultOptionsForGateway("B")
6147 sb := runGatewayServer(ob)
6148 defer sb.Shutdown()
6149 setRecSub(sb)
6150
6151 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
6152 sa := runGatewayServer(oa)
6153 defer sa.Shutdown()
6154 setRecSub(sa)
6155
6156 waitForOutboundGateways(t, sa, 1, 2*time.Second)
6157 waitForInboundGateways(t, sa, 1, 2*time.Second)
6158 waitForOutboundGateways(t, sb, 1, 2*time.Second)
6159 waitForInboundGateways(t, sb, 1, 2*time.Second)
6160
6161 ncb := natsConnect(t, sb.ClientURL())
6162 defer ncb.Close()
6163 count := 0
6164 total := 100
6165 ch := make(chan bool, 1)
6166 natsSub(t, ncb, "foo", func(m *nats.Msg) {
6167 m.Respond([]byte("reply"))
6168 if count++; count == total {
6169 ch <- true
6170 }
6171 })
6172 natsFlush(t, ncb)
6173
6174 var bc *client
6175 sb.mu.Lock()
6176 for _, c := range sb.clients {
6177 bc = c
6178 break
6179 }
6180 sb.mu.Unlock()
6181
6182 nca := natsConnect(t, sa.ClientURL())
6183 defer nca.Close()
6184
6185 replySub := natsSubSync(t, nca, "bar.>")
6186 for i := 0; i < total; i++ {
6187 nca.PublishRequest("foo", fmt.Sprintf("bar.%d", i), []byte("request"))
6188 }
6189
6190 waitCh(t, ch, "Did not receive all requests")
6191
6192 check := func(t *testing.T, expectedIndicator int32, expectLenMap int, expectedSrvMapEmpty bool) {
6193 t.Helper()
6194 bc.mu.Lock()
6195 mapIndicator := atomic.LoadInt32(&bc.gwReplyMapping.check)
6196 var lenMap int
6197 if bc.gwReplyMapping.mapping != nil {
6198 lenMap = len(bc.gwReplyMapping.mapping)
6199 }
6200 bc.mu.Unlock()
6201 if mapIndicator != expectedIndicator {
6202 t.Fatalf("Client should map indicator should be %v, got %v", expectedIndicator, mapIndicator)
6203 }
6204 if lenMap != expectLenMap {
6205 t.Fatalf("Client map should have %v entries, got %v", expectLenMap, lenMap)
6206 }
6207 srvMapEmpty := true
6208 sb.gwrm.m.Range(func(_, _ any) bool {
6209 srvMapEmpty = false
6210 return false
6211 })
6212 if srvMapEmpty != expectedSrvMapEmpty {
6213 t.Fatalf("Expected server map to be empty=%v, got %v", expectedSrvMapEmpty, srvMapEmpty)
6214 }
6215 }
6216 // Check that indicator is set and that there "total" entries in the map
6217 // and that srv map is not empty
6218 check(t, 1, total, false)
6219
6220 // Receive all replies
6221 for i := 0; i < total; i++ {
6222 natsNexMsg(t, replySub, time.Second)
6223 }
6224
6225 // Wait until entries expire
6226 time.Sleep(2*subExp + 100*time.Millisecond)
6227
6228 // Now check again.
6229 check(t, 0, 0, true)
6230 }
6231
6232 func TestGatewayNoAccountUnsubWhenServiceReplyInUse(t *testing.T) {
6233 oa := testDefaultOptionsForGateway("A")
6234 setAccountUserPassInOptions(oa, "$foo", "clientFoo", "password")
6235 setAccountUserPassInOptions(oa, "$bar", "clientBar", "password")
6236 sa := runGatewayServer(oa)
6237 defer sa.Shutdown()
6238
6239 ob := testGatewayOptionsFromToWithServers(t, "B", "A", sa)
6240 setAccountUserPassInOptions(ob, "$foo", "clientFoo", "password")
6241 setAccountUserPassInOptions(ob, "$bar", "clientBar", "password")
6242 sb := runGatewayServer(ob)
6243 defer sb.Shutdown()
6244
6245 waitForOutboundGateways(t, sa, 1, time.Second)
6246 waitForOutboundGateways(t, sb, 1, time.Second)
6247 waitForInboundGateways(t, sa, 1, time.Second)
6248 waitForInboundGateways(t, sb, 1, time.Second)
6249
6250 // Get accounts
6251 fooA, _ := sa.LookupAccount("$foo")
6252 barA, _ := sa.LookupAccount("$bar")
6253 fooB, _ := sb.LookupAccount("$foo")
6254 barB, _ := sb.LookupAccount("$bar")
6255
6256 // Add in the service export for the requests. Make it public.
6257 fooA.AddServiceExport("test.request", nil)
6258 fooB.AddServiceExport("test.request", nil)
6259
6260 // Add import abilities to server B's bar account from foo.
6261 if err := barB.AddServiceImport(fooB, "foo.request", "test.request"); err != nil {
6262 t.Fatalf("Error adding service import: %v", err)
6263 }
6264 // Same on A.
6265 if err := barA.AddServiceImport(fooA, "foo.request", "test.request"); err != nil {
6266 t.Fatalf("Error adding service import: %v", err)
6267 }
6268
6269 // clientA will be connected to srvA and be the service endpoint and responder.
6270 aURL := fmt.Sprintf("nats://clientFoo:[email protected]:%d", oa.Port)
6271 clientA := natsConnect(t, aURL)
6272 defer clientA.Close()
6273
6274 natsSub(t, clientA, "test.request", func(m *nats.Msg) {
6275 m.Respond([]byte("reply"))
6276 })
6277 natsFlush(t, clientA)
6278
6279 // Now setup client B on srvB who will send the requests.
6280 bURL := fmt.Sprintf("nats://clientBar:[email protected]:%d", ob.Port)
6281 clientB := natsConnect(t, bURL)
6282 defer clientB.Close()
6283
6284 if _, err := clientB.Request("foo.request", []byte("request"), time.Second); err != nil {
6285 t.Fatalf("Did not get the reply: %v", err)
6286 }
6287
6288 quitCh := make(chan bool, 1)
6289 wg := sync.WaitGroup{}
6290 wg.Add(1)
6291 go func() {
6292 defer wg.Done()
6293
6294 for {
6295 select {
6296 case <-quitCh:
6297 return
6298 default:
6299 clientA.Publish("any.subject", []byte("any message"))
6300 time.Sleep(time.Millisecond)
6301 }
6302 }
6303 }()
6304 for i := 0; i < 1000; i++ {
6305 if _, err := clientB.Request("foo.request", []byte("request"), time.Second); err != nil {
6306 t.Fatalf("Did not get the reply: %v", err)
6307 }
6308 }
6309 close(quitCh)
6310 wg.Wait()
6311 }
6312
6313 func TestGatewayCloseTLSConnection(t *testing.T) {
6314 oa := testGatewayOptionsWithTLS(t, "A")
6315 oa.DisableShortFirstPing = true
6316 oa.Gateway.TLSConfig.ClientAuth = tls.NoClientCert
6317 oa.Gateway.TLSTimeout = 100
6318 sa := runGatewayServer(oa)
6319 defer sa.Shutdown()
6320
6321 ob1 := testGatewayOptionsFromToWithTLS(t, "B", "A", []string{fmt.Sprintf("nats://127.0.0.1:%d", sa.GatewayAddr().Port)})
6322 sb1 := runGatewayServer(ob1)
6323 defer sb1.Shutdown()
6324
6325 waitForOutboundGateways(t, sa, 1, 2*time.Second)
6326 waitForInboundGateways(t, sa, 1, 2*time.Second)
6327 waitForOutboundGateways(t, sb1, 1, 2*time.Second)
6328 waitForInboundGateways(t, sb1, 1, 2*time.Second)
6329
6330 endpoint := net.JoinHostPort(oa.Gateway.Host, fmt.Sprintf("%d", oa.Gateway.Port))
6331 conn, err := net.DialTimeout("tcp", endpoint, 2*time.Second)
6332 if err != nil {
6333 t.Fatalf("Unexpected error on dial: %v", err)
6334 }
6335 defer conn.Close()
6336
6337 tlsConn := tls.Client(conn, &tls.Config{InsecureSkipVerify: true})
6338 defer tlsConn.Close()
6339 if err := tlsConn.Handshake(); err != nil {
6340 t.Fatalf("Unexpected error during handshake: %v", err)
6341 }
6342 connectOp := []byte("CONNECT {\"name\":\"serverID\",\"verbose\":false,\"pedantic\":false,\"tls_required\":true,\"gateway\":\"B\"}\r\n")
6343 if _, err := tlsConn.Write(connectOp); err != nil {
6344 t.Fatalf("Unexpected error writing CONNECT: %v", err)
6345 }
6346 infoOp := []byte("INFO {\"server_id\":\"serverID\",\"tls_required\":true,\"gateway\":\"B\",\"gateway_nrp\":true}\r\n")
6347 if _, err := tlsConn.Write(infoOp); err != nil {
6348 t.Fatalf("Unexpected error writing CONNECT: %v", err)
6349 }
6350 if _, err := tlsConn.Write([]byte("PING\r\n")); err != nil {
6351 t.Fatalf("Unexpected error writing PING: %v", err)
6352 }
6353
6354 // Get gw connection
6355 var gw *client
6356 checkFor(t, time.Second, 15*time.Millisecond, func() error {
6357 sa.gateway.RLock()
6358 for _, g := range sa.gateway.in {
6359 g.mu.Lock()
6360 if g.opts.Name == "serverID" {
6361 gw = g
6362 }
6363 g.mu.Unlock()
6364 break
6365 }
6366 sa.gateway.RUnlock()
6367 if gw == nil {
6368 return fmt.Errorf("No gw registered yet")
6369 }
6370 return nil
6371 })
6372 // Fill the buffer. We want to timeout on write so that nc.Close()
6373 // would block due to a write that cannot complete.
6374 buf := make([]byte, 64*1024)
6375 done := false
6376 for !done {
6377 gw.nc.SetWriteDeadline(time.Now().Add(time.Second))
6378 if _, err := gw.nc.Write(buf); err != nil {
6379 done = true
6380 }
6381 gw.nc.SetWriteDeadline(time.Time{})
6382 }
6383 ch := make(chan bool)
6384 go func() {
6385 select {
6386 case <-ch:
6387 return
6388 case <-time.After(3 * time.Second):
6389 fmt.Println("!!!! closeConnection is blocked, test will hang !!!")
6390 return
6391 }
6392 }()
6393 // Close the gateway
6394 gw.closeConnection(SlowConsumerWriteDeadline)
6395 ch <- true
6396 }
6397
6398 func TestGatewayNoCrashOnInvalidSubject(t *testing.T) {
6399 ob := testDefaultOptionsForGateway("B")
6400 sb := runGatewayServer(ob)
6401 defer sb.Shutdown()
6402
6403 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
6404 sa := runGatewayServer(oa)
6405 defer sa.Shutdown()
6406
6407 waitForOutboundGateways(t, sa, 1, 2*time.Second)
6408 waitForInboundGateways(t, sa, 1, 2*time.Second)
6409 waitForOutboundGateways(t, sb, 1, 2*time.Second)
6410 waitForInboundGateways(t, sb, 1, 2*time.Second)
6411
6412 ncB := natsConnect(t, sb.ClientURL())
6413 defer ncB.Close()
6414
6415 natsSubSync(t, ncB, "foo")
6416 natsFlush(t, ncB)
6417
6418 ncA := natsConnect(t, sa.ClientURL())
6419 defer ncA.Close()
6420
6421 // Send on an invalid subject. Since there is interest on B,
6422 // we will receive an RS- instead of A-
6423 natsPub(t, ncA, "bar..baz", []byte("bad subject"))
6424 natsFlush(t, ncA)
6425
6426 // Now create on B a sub on a wildcard subject
6427 sub := natsSubSync(t, ncB, "bar.*")
6428 natsFlush(t, ncB)
6429
6430 // Server should not have crashed...
6431 natsPub(t, ncA, "bar.baz", []byte("valid subject"))
6432 if _, err := sub.NextMsg(time.Second); err != nil {
6433 t.Fatalf("Error getting message: %v", err)
6434 }
6435 }
6436
6437 func TestGatewayUpdateURLsFromRemoteCluster(t *testing.T) {
6438 ob1 := testDefaultOptionsForGateway("B")
6439 sb1 := RunServer(ob1)
6440 defer sb1.Shutdown()
6441
6442 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb1)
6443 sa := RunServer(oa)
6444 defer sa.Shutdown()
6445
6446 waitForOutboundGateways(t, sa, 1, 2*time.Second)
6447 waitForOutboundGateways(t, sb1, 1, 2*time.Second)
6448
6449 // Add a server to cluster B.
6450 ob2 := testDefaultOptionsForGateway("B")
6451 ob2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", ob1.Cluster.Port))
6452 sb2 := RunServer(ob2)
6453 defer sb2.Shutdown()
6454
6455 checkClusterFormed(t, sb1, sb2)
6456 waitForOutboundGateways(t, sb2, 1, 2*time.Second)
6457 waitForInboundGateways(t, sa, 2, 2*time.Second)
6458
6459 pmap := make(map[int]string)
6460 pmap[ob1.Gateway.Port] = "B1"
6461 pmap[ob2.Gateway.Port] = "B2"
6462
6463 checkURLs := func(eurls map[string]string) {
6464 t.Helper()
6465 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
6466 rg := sa.getRemoteGateway("B")
6467 urls := rg.getURLsAsStrings()
6468 for _, u := range urls {
6469 if _, ok := eurls[u]; !ok {
6470 _, sport, _ := net.SplitHostPort(u)
6471 port, _ := strconv.Atoi(sport)
6472 return fmt.Errorf("URL %q (%s) should not be in the list of urls (%q)", u, pmap[port], eurls)
6473 }
6474 }
6475 return nil
6476 })
6477 }
6478 expected := make(map[string]string)
6479 expected[fmt.Sprintf("127.0.0.1:%d", ob1.Gateway.Port)] = "B1"
6480 expected[fmt.Sprintf("127.0.0.1:%d", ob2.Gateway.Port)] = "B2"
6481 checkURLs(expected)
6482
6483 // Add another in cluster B
6484 ob3 := testDefaultOptionsForGateway("B")
6485 ob3.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", ob1.Cluster.Port))
6486 sb3 := RunServer(ob3)
6487 defer sb3.Shutdown()
6488
6489 checkClusterFormed(t, sb1, sb2, sb3)
6490 waitForOutboundGateways(t, sb3, 1, 2*time.Second)
6491 waitForInboundGateways(t, sa, 3, 2*time.Second)
6492
6493 pmap[ob3.Gateway.Port] = "B3"
6494
6495 expected = make(map[string]string)
6496 expected[fmt.Sprintf("127.0.0.1:%d", ob1.Gateway.Port)] = "B1"
6497 expected[fmt.Sprintf("127.0.0.1:%d", ob2.Gateway.Port)] = "B2"
6498 expected[fmt.Sprintf("127.0.0.1:%d", ob3.Gateway.Port)] = "B3"
6499 checkURLs(expected)
6500
6501 // Now stop server SB2, which should cause SA to remove it from its list.
6502 sb2.Shutdown()
6503
6504 expected = make(map[string]string)
6505 expected[fmt.Sprintf("127.0.0.1:%d", ob1.Gateway.Port)] = "B1"
6506 expected[fmt.Sprintf("127.0.0.1:%d", ob3.Gateway.Port)] = "B3"
6507 checkURLs(expected)
6508 }
6509
6510 type capturePingConn struct {
6511 net.Conn
6512 ch chan struct{}
6513 }
6514
6515 func (c *capturePingConn) Write(b []byte) (int, error) {
6516 if bytes.Contains(b, []byte(pingProto)) {
6517 select {
6518 case c.ch <- struct{}{}:
6519 default:
6520 }
6521 }
6522 return c.Conn.Write(b)
6523 }
6524
6525 func TestGatewayPings(t *testing.T) {
6526 gatewayMaxPingInterval = 50 * time.Millisecond
6527 defer func() { gatewayMaxPingInterval = gwMaxPingInterval }()
6528
6529 ob := testDefaultOptionsForGateway("B")
6530 sb := RunServer(ob)
6531 defer sb.Shutdown()
6532
6533 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
6534 sa := RunServer(oa)
6535 defer sa.Shutdown()
6536
6537 waitForInboundGateways(t, sa, 1, 2*time.Second)
6538 waitForOutboundGateways(t, sa, 1, 2*time.Second)
6539 waitForInboundGateways(t, sb, 1, 2*time.Second)
6540 waitForOutboundGateways(t, sb, 1, 2*time.Second)
6541
6542 c := sa.getOutboundGatewayConnection("B")
6543 ch := make(chan struct{}, 1)
6544 c.mu.Lock()
6545 c.nc = &capturePingConn{c.nc, ch}
6546 c.mu.Unlock()
6547
6548 for i := 0; i < 5; i++ {
6549 select {
6550 case <-ch:
6551 case <-time.After(250 * time.Millisecond):
6552 t.Fatalf("Did not send PING")
6553 }
6554 }
6555 }
6556
6557 func TestGatewayTLSConfigReload(t *testing.T) {
6558 template := `
6559 listen: 127.0.0.1:-1
6560 gateway {
6561 name: "A"
6562 listen: "127.0.0.1:-1"
6563 tls {
6564 cert_file: "../test/configs/certs/server-cert.pem"
6565 key_file: "../test/configs/certs/server-key.pem"
6566 %s
6567 timeout: 2
6568 }
6569 }
6570 `
6571 confA := createConfFile(t, []byte(fmt.Sprintf(template, "")))
6572
6573 srvA, optsA := RunServerWithConfig(confA)
6574 defer srvA.Shutdown()
6575
6576 optsB := testGatewayOptionsFromToWithTLS(t, "B", "A", []string{fmt.Sprintf("nats://127.0.0.1:%d", optsA.Gateway.Port)})
6577 srvB := runGatewayServer(optsB)
6578 defer srvB.Shutdown()
6579
6580 waitForGatewayFailedConnect(t, srvB, "A", true, time.Second)
6581
6582 reloadUpdateConfig(t, srvA, confA, fmt.Sprintf(template, `ca_file: "../test/configs/certs/ca.pem"`))
6583
6584 waitForInboundGateways(t, srvA, 1, time.Second)
6585 waitForOutboundGateways(t, srvA, 1, time.Second)
6586 waitForInboundGateways(t, srvB, 1, time.Second)
6587 waitForOutboundGateways(t, srvB, 1, time.Second)
6588 }
6589
6590 func TestGatewayTLSConfigReloadForRemote(t *testing.T) {
6591 SetGatewaysSolicitDelay(5 * time.Millisecond)
6592 defer ResetGatewaysSolicitDelay()
6593
6594 optsA := testGatewayOptionsWithTLS(t, "A")
6595 srvA := runGatewayServer(optsA)
6596 defer srvA.Shutdown()
6597
6598 template := `
6599 listen: 127.0.0.1:-1
6600 gateway {
6601 name: "B"
6602 listen: "127.0.0.1:-1"
6603 tls {
6604 cert_file: "../test/configs/certs/server-cert.pem"
6605 key_file: "../test/configs/certs/server-key.pem"
6606 ca_file: "../test/configs/certs/ca.pem"
6607 timeout: 2
6608 }
6609 gateways [
6610 {
6611 name: "A"
6612 url: "nats://127.0.0.1:%d"
6613 tls {
6614 cert_file: "../test/configs/certs/server-cert.pem"
6615 key_file: "../test/configs/certs/server-key.pem"
6616 %s
6617 timeout: 2
6618 }
6619 }
6620 ]
6621 }
6622 `
6623 confB := createConfFile(t, []byte(fmt.Sprintf(template, optsA.Gateway.Port, "")))
6624
6625 srvB, _ := RunServerWithConfig(confB)
6626 defer srvB.Shutdown()
6627
6628 waitForGatewayFailedConnect(t, srvB, "A", true, time.Second)
6629
6630 reloadUpdateConfig(t, srvB, confB, fmt.Sprintf(template, optsA.Gateway.Port, `ca_file: "../test/configs/certs/ca.pem"`))
6631
6632 waitForInboundGateways(t, srvA, 1, time.Second)
6633 waitForOutboundGateways(t, srvA, 1, time.Second)
6634 waitForInboundGateways(t, srvB, 1, time.Second)
6635 waitForOutboundGateways(t, srvB, 1, time.Second)
6636 }
6637
6638 func TestGatewayTLSConfigReloadForImplicitRemote(t *testing.T) {
6639 SetGatewaysSolicitDelay(5 * time.Millisecond)
6640 defer ResetGatewaysSolicitDelay()
6641
6642 template := `
6643 listen: 127.0.0.1:-1
6644 gateway {
6645 name: "A"
6646 listen: "127.0.0.1:-1"
6647 tls {
6648 cert_file: "../test/configs/certs/srva-cert.pem"
6649 key_file: "../test/configs/certs/srva-key.pem"
6650 %s
6651 verify: true
6652 }
6653 }
6654 `
6655 confA := createConfFile(t, fmt.Appendf(nil, template, `ca_file: "../test/configs/certs/ca.pem"`))
6656 srvA, optsA := RunServerWithConfig(confA)
6657 defer srvA.Shutdown()
6658
6659 optsB := testGatewayOptionsFromToWithTLS(t, "B", "A", []string{fmt.Sprintf("nats://127.0.0.1:%d", optsA.Gateway.Port)})
6660 srvB := runGatewayServer(optsB)
6661 defer srvB.Shutdown()
6662
6663 waitForInboundGateways(t, srvA, 1, time.Second)
6664 waitForOutboundGateways(t, srvA, 1, time.Second)
6665 waitForInboundGateways(t, srvB, 1, time.Second)
6666 waitForOutboundGateways(t, srvB, 1, time.Second)
6667
6668 // We will verify that the config reload of the tls{} block is applied to
6669 // the implicit remote (from A to B) by removing the ca_file.
6670 reloadUpdateConfig(t, srvA, confA, fmt.Sprintf(template, ""))
6671
6672 // Get the remote from A to B
6673 cfg := srvA.getRemoteGateway("B")
6674 require_NotNil(t, cfg)
6675 cfg.Lock()
6676 tc := cfg.TLSConfig
6677 cfg.Unlock()
6678 require_NotNil(t, tc)
6679 // The CA should have been removed.
6680 require_True(t, tc.ClientCAs == nil)
6681
6682 // Reset the connection attempts, since we are going to close the connection
6683 // from A to B and make sure that connection keeps failing.
6684 cfg.resetConnAttempts()
6685
6686 // Get the outbound connection and close it.
6687 c := srvA.getOutboundGatewayConnection("B")
6688 require_NotNil(t, c)
6689 c.mu.Lock()
6690 c.nc.Close()
6691 c.mu.Unlock()
6692
6693 // Verify that we fail to connect from A to B now.
6694 waitForGatewayFailedConnect(t, srvA, "B", true, time.Second)
6695 }
6696
6697 func TestGatewayTLSPinnedCertsReloadDisconnectsPeers(t *testing.T) {
6698 SetGatewaysSolicitDelay(5 * time.Millisecond)
6699 defer ResetGatewaysSolicitDelay()
6700
6701 const (
6702 pinnedSrvA = "[\"c5d58200425185accb67cdca400d823ef20300a1ee09e5b38c668be8bd20256e\"]"
6703 pinnedSrvB = "[\"0e35d0ab7dee2683105f841c4a51953ec493ceb62503d26f38902d301111562c\"]"
6704 )
6705
6706 template := `
6707 listen: 127.0.0.1:-1
6708 gateway {
6709 name: "A"
6710 listen: "127.0.0.1:-1"
6711 tls {
6712 cert_file: "../test/configs/certs/srva-cert.pem"
6713 key_file: "../test/configs/certs/srva-key.pem"
6714 ca_file: "../test/configs/certs/ca.pem"
6715 verify: true
6716 pinned_certs: %s
6717 timeout: 2
6718 }
6719 }
6720 `
6721 confA := createConfFile(t, []byte(fmt.Sprintf(template, pinnedSrvB)))
6722 srvA, optsA := RunServerWithConfig(confA)
6723 defer srvA.Shutdown()
6724
6725 optsB := testGatewayOptionsFromToWithTLS(t, "B", "A", []string{fmt.Sprintf("nats://127.0.0.1:%d", optsA.Gateway.Port)})
6726 srvB := runGatewayServer(optsB)
6727 defer srvB.Shutdown()
6728
6729 waitForInboundGateways(t, srvA, 1, time.Second)
6730 waitForOutboundGateways(t, srvA, 1, time.Second)
6731 waitForInboundGateways(t, srvB, 1, time.Second)
6732 waitForOutboundGateways(t, srvB, 1, time.Second)
6733
6734 // Change the pinned cert. Expect the gateway to disconnect
6735 reloadUpdateConfig(t, srvA, confA, fmt.Sprintf(template, pinnedSrvA))
6736 waitForInboundGateways(t, srvA, 0, time.Second)
6737 waitForOutboundGateways(t, srvA, 0, time.Second)
6738 waitForInboundGateways(t, srvB, 0, time.Second)
6739 waitForOutboundGateways(t, srvB, 0, time.Second)
6740 waitForGatewayFailedConnect(t, srvB, "A", true, time.Second)
6741
6742 // Reload with empty pinned cert. Expect gateway to reconnect.
6743 reloadUpdateConfig(t, srvA, confA, fmt.Sprintf(template, "[]"))
6744 waitForInboundGateways(t, srvA, 1, time.Second)
6745 waitForOutboundGateways(t, srvA, 1, time.Second)
6746 waitForInboundGateways(t, srvB, 1, time.Second)
6747 waitForOutboundGateways(t, srvB, 1, time.Second)
6748
6749 // Reset pinned cert to server B. Expect gate to remain connected.
6750 reloadUpdateConfig(t, srvA, confA, fmt.Sprintf(template, pinnedSrvB))
6751 waitForInboundGateways(t, srvA, 1, time.Second)
6752 waitForOutboundGateways(t, srvA, 1, time.Second)
6753 waitForInboundGateways(t, srvB, 1, time.Second)
6754 waitForOutboundGateways(t, srvB, 1, time.Second)
6755
6756 }
6757
6758 func TestGatewayAuthDiscovered(t *testing.T) {
6759 SetGatewaysSolicitDelay(5 * time.Millisecond)
6760 defer ResetGatewaysSolicitDelay()
6761
6762 confA := createConfFile(t, []byte(`
6763 listen: 127.0.0.1:-1
6764 gateway {
6765 name: "A"
6766 listen: 127.0.0.1:-1
6767 authorization: { user: gwuser, password: changeme }
6768 }
6769 `))
6770 srvA, optsA := RunServerWithConfig(confA)
6771 defer srvA.Shutdown()
6772
6773 confB := createConfFile(t, []byte(fmt.Sprintf(`
6774 listen: 127.0.0.1:-1
6775 gateway {
6776 name: "B"
6777 listen: 127.0.0.1:-1
6778 authorization: { user: gwuser, password: changeme }
6779 gateways: [
6780 { name: A, url: nats://gwuser:[email protected]:%d }
6781 ]
6782 }
6783 `, optsA.Gateway.Port)))
6784 srvB, _ := RunServerWithConfig(confB)
6785 defer srvB.Shutdown()
6786
6787 waitForInboundGateways(t, srvA, 1, time.Second)
6788 waitForOutboundGateways(t, srvA, 1, time.Second)
6789 waitForInboundGateways(t, srvB, 1, time.Second)
6790 waitForOutboundGateways(t, srvB, 1, time.Second)
6791 }
6792
6793 func TestGatewayTLSCertificateImplicitAllowPass(t *testing.T) {
6794 testGatewayTLSCertificateImplicitAllow(t, true)
6795 }
6796
6797 func TestGatewayTLSCertificateImplicitAllowFail(t *testing.T) {
6798 testGatewayTLSCertificateImplicitAllow(t, false)
6799 }
6800
6801 func testGatewayTLSCertificateImplicitAllow(t *testing.T, pass bool) {
6802 // Base config for the servers
6803 cfg := createTempFile(t, "cfg")
6804 cfg.WriteString(fmt.Sprintf(`
6805 gateway {
6806 tls {
6807 cert_file = "../test/configs/certs/tlsauth/server.pem"
6808 key_file = "../test/configs/certs/tlsauth/server-key.pem"
6809 ca_file = "../test/configs/certs/tlsauth/ca.pem"
6810 verify_cert_and_check_known_urls = true
6811 insecure = %t
6812 timeout = 1
6813 }
6814 }
6815 `, !pass)) // set insecure to skip verification on the outgoing end
6816 if err := cfg.Sync(); err != nil {
6817 t.Fatal(err)
6818 }
6819 cfg.Close()
6820
6821 optsA := LoadConfig(cfg.Name())
6822 optsB := LoadConfig(cfg.Name())
6823
6824 urlA := "nats://localhost:9995"
6825 urlB := "nats://localhost:9996"
6826 if !pass {
6827 urlA = "nats://127.0.0.1:9995"
6828 urlB = "nats://127.0.0.1:9996"
6829 }
6830
6831 gwA, err := url.Parse(urlA)
6832 if err != nil {
6833 t.Fatal(err)
6834 }
6835 gwB, err := url.Parse(urlB)
6836 if err != nil {
6837 t.Fatal(err)
6838 }
6839
6840 optsA.Host = "127.0.0.1"
6841 optsA.Port = -1
6842 optsA.Gateway.Name = "A"
6843 optsA.Gateway.Port = 9995
6844 optsA.Gateway.resolver = &localhostResolver{}
6845
6846 optsB.Host = "127.0.0.1"
6847 optsB.Port = -1
6848 optsB.Gateway.Name = "B"
6849 optsB.Gateway.Port = 9996
6850 optsB.Gateway.resolver = &localhostResolver{}
6851
6852 gateways := make([]*RemoteGatewayOpts, 2)
6853 gateways[0] = &RemoteGatewayOpts{
6854 Name: optsA.Gateway.Name,
6855 URLs: []*url.URL{gwA},
6856 }
6857 gateways[1] = &RemoteGatewayOpts{
6858 Name: optsB.Gateway.Name,
6859 URLs: []*url.URL{gwB},
6860 }
6861
6862 optsA.Gateway.Gateways = gateways
6863 optsB.Gateway.Gateways = gateways
6864
6865 SetGatewaysSolicitDelay(100 * time.Millisecond)
6866 defer ResetGatewaysSolicitDelay()
6867
6868 srvA := RunServer(optsA)
6869 defer srvA.Shutdown()
6870
6871 srvB := RunServer(optsB)
6872 defer srvB.Shutdown()
6873
6874 if pass {
6875 waitForOutboundGateways(t, srvA, 1, 5*time.Second)
6876 waitForOutboundGateways(t, srvB, 1, 5*time.Second)
6877 } else {
6878 time.Sleep(1 * time.Second) // the fail case uses the IP, so a short wait is sufficient
6879 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
6880 if srvA.NumOutboundGateways() != 0 || srvB.NumOutboundGateways() != 0 {
6881 return fmt.Errorf("No outbound gateway connection expected")
6882 }
6883 return nil
6884 })
6885 }
6886 }
6887
6888 func TestGatewayURLsNotRemovedOnDuplicateRoute(t *testing.T) {
6889 // For this test, we need to have servers in cluster B creating routes
6890 // to each other to help produce the "duplicate route" situation, so
6891 // we are forced to use deterministic ports.
6892 getEphemeralPort := func() int {
6893 t.Helper()
6894 l, err := net.Listen("tcp", "127.0.0.1:0")
6895 if err != nil {
6896 t.Fatalf("Error getting a port: %v", err)
6897 }
6898 p := l.Addr().(*net.TCPAddr).Port
6899 l.Close()
6900 return p
6901 }
6902 p1 := getEphemeralPort()
6903 p2 := getEphemeralPort()
6904 routeURLs := fmt.Sprintf("nats://127.0.0.1:%d,nats://127.0.0.1:%d", p1, p2)
6905
6906 ob1 := testDefaultOptionsForGateway("B")
6907 ob1.Cluster.Port = p1
6908 ob1.Routes = RoutesFromStr(routeURLs)
6909 sb1 := RunServer(ob1)
6910 defer sb1.Shutdown()
6911
6912 ob2 := testDefaultOptionsForGateway("B")
6913 ob2.Cluster.Port = p2
6914 ob2.Routes = RoutesFromStr(routeURLs)
6915 sb2 := RunServer(ob2)
6916 defer sb2.Shutdown()
6917
6918 checkClusterFormed(t, sb1, sb2)
6919
6920 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb1)
6921 sa := RunServer(oa)
6922 defer sa.Shutdown()
6923
6924 waitForOutboundGateways(t, sb1, 1, 2*time.Second)
6925 waitForOutboundGateways(t, sb2, 1, 2*time.Second)
6926 waitForOutboundGateways(t, sa, 1, 2*time.Second)
6927 waitForInboundGateways(t, sa, 2, 2*time.Second)
6928
6929 checkURLs := func(s *Server) {
6930 t.Helper()
6931 s.mu.Lock()
6932 urls := s.gateway.URLs.getAsStringSlice()
6933 s.mu.Unlock()
6934 if len(urls) != 2 {
6935 t.Fatalf("Expected 2 urls, got %v", urls)
6936 }
6937 }
6938 checkURLs(sb1)
6939 checkURLs(sb2)
6940
6941 // As for sa, we should have both sb1 and sb2 urls in its outbound urls map
6942 c := sa.getOutboundGatewayConnection("B")
6943 if c == nil {
6944 t.Fatal("No outound connection found!")
6945 }
6946 c.mu.Lock()
6947 urls := c.gw.cfg.urls
6948 c.mu.Unlock()
6949 if len(urls) != 2 {
6950 t.Fatalf("Expected 2 urls to B, got %v", urls)
6951 }
6952 }
6953
6954 func TestGatewayDuplicateServerName(t *testing.T) {
6955 // We will have 2 servers per cluster names "nats1" and "nats2", and have
6956 // the servers in the second cluster with the same name, but we will make
6957 // sure to connect "A/nats1" to "B/nats2" and "A/nats2" to "B/nats1" and
6958 // verify that we still discover the duplicate names.
6959 ob1 := testDefaultOptionsForGateway("B")
6960 ob1.ServerName = "nats1"
6961 sb1 := RunServer(ob1)
6962 defer sb1.Shutdown()
6963
6964 ob2 := testDefaultOptionsForGateway("B")
6965 ob2.ServerName = "nats2"
6966 ob2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", ob1.Cluster.Port))
6967 sb2 := RunServer(ob2)
6968 defer sb2.Shutdown()
6969
6970 checkClusterFormed(t, sb1, sb2)
6971
6972 oa1 := testGatewayOptionsFromToWithServers(t, "A", "B", sb2)
6973 oa1.ServerName = "nats1"
6974 // Needed later in the test
6975 oa1.Gateway.RejectUnknown = true
6976 sa1 := RunServer(oa1)
6977 defer sa1.Shutdown()
6978 sa1l := &captureErrorLogger{errCh: make(chan string, 100)}
6979 sa1.SetLogger(sa1l, false, false)
6980
6981 oa2 := testGatewayOptionsFromToWithServers(t, "A", "B", sb1)
6982 oa2.ServerName = "nats2"
6983 // Needed later in the test
6984 oa2.Gateway.RejectUnknown = true
6985 oa2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", oa1.Cluster.Port))
6986 sa2 := RunServer(oa2)
6987 defer sa2.Shutdown()
6988 sa2l := &captureErrorLogger{errCh: make(chan string, 100)}
6989 sa2.SetLogger(sa2l, false, false)
6990
6991 checkClusterFormed(t, sa1, sa2)
6992
6993 checkForDupError := func(errCh chan string) {
6994 t.Helper()
6995 timeout := time.NewTimer(time.Second)
6996 for done := false; !done; {
6997 select {
6998 case err := <-errCh:
6999 if strings.Contains(err, "server has a duplicate name") {
7000 done = true
7001 }
7002 case <-timeout.C:
7003 t.Fatal("Did not get error about servers in super-cluster with same name")
7004 }
7005 }
7006 }
7007
7008 // Since only servers from "A" have configured outbound to
7009 // cluster "B", only servers on "A" are expected to report error.
7010 for _, errCh := range []chan string{sa1l.errCh, sa2l.errCh} {
7011 checkForDupError(errCh)
7012 }
7013
7014 // So now we are going to fix names and wait for the super cluster to form.
7015 sa2.Shutdown()
7016 sa1.Shutdown()
7017
7018 // Drain the error channels
7019 for _, errCh := range []chan string{sa1l.errCh, sa2l.errCh} {
7020 for done := false; !done; {
7021 select {
7022 case <-errCh:
7023 default:
7024 done = true
7025 }
7026 }
7027 }
7028
7029 oa1.ServerName = "a_nats1"
7030 oa2.ServerName = "a_nats2"
7031 sa1 = RunServer(oa1)
7032 defer sa1.Shutdown()
7033 sa2 = RunServer(oa2)
7034 defer sa2.Shutdown()
7035
7036 checkClusterFormed(t, sa1, sa2)
7037
7038 waitForOutboundGateways(t, sa1, 1, 2*time.Second)
7039 waitForOutboundGateways(t, sa2, 1, 2*time.Second)
7040 waitForOutboundGateways(t, sb1, 1, 2*time.Second)
7041 waitForOutboundGateways(t, sb2, 1, 2*time.Second)
7042
7043 // Now add a server on cluster B (that does not have outbound
7044 // gateway connections explicitly defined) and use the name
7045 // of one of the cluster A's server. We should get an error.
7046 ob3 := testDefaultOptionsForGateway("B")
7047 ob3.ServerName = "a_nats2"
7048 ob3.Accounts = []*Account{NewAccount("sys")}
7049 ob3.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", ob2.Cluster.Port))
7050 sb3 := RunServer(ob3)
7051 defer sb3.Shutdown()
7052 sb3l := &captureErrorLogger{errCh: make(chan string, 100)}
7053 sb3.SetLogger(sb3l, false, false)
7054
7055 checkClusterFormed(t, sb1, sb2, sb3)
7056
7057 // It should report the error when trying to create the GW connection
7058 checkForDupError(sb3l.errCh)
7059
7060 // Stop this node
7061 sb3.Shutdown()
7062 checkClusterFormed(t, sb1, sb2)
7063
7064 // Now create a GW "C" with a server that uses the same name than one of
7065 // the server on "A", say "a_nats2".
7066 // This server will connect to "B", and "B" will gossip "A" back to "C"
7067 // and "C" will then try to connect to "A", but "A" rejects unknown, so
7068 // connection will be refused. However, we want to make sure that the
7069 // duplicate server name is still detected.
7070 oc := testGatewayOptionsFromToWithServers(t, "C", "B", sb1)
7071 oc.ServerName = "a_nats2"
7072 oc.Accounts = []*Account{NewAccount("sys")}
7073 sc := RunServer(oc)
7074 defer sc.Shutdown()
7075 scl := &captureErrorLogger{errCh: make(chan string, 100)}
7076 sc.SetLogger(scl, false, false)
7077
7078 // It should report the error when trying to create the GW connection
7079 // to cluster "A"
7080 checkForDupError(scl.errCh)
7081 }
7082
7083 func TestGatewayNoPanicOnStartupWithMonitoring(t *testing.T) {
7084 o := testDefaultOptionsForGateway("B")
7085 o.HTTPHost = "127.0.0.1"
7086 o.HTTPPort = 8888
7087 s, err := NewServer(o)
7088 require_NoError(t, err)
7089
7090 wg := sync.WaitGroup{}
7091 wg.Add(1)
7092 go func() {
7093 defer wg.Done()
7094
7095 time.Sleep(50 * time.Millisecond)
7096 s.Start()
7097 s.WaitForShutdown()
7098 }()
7099
7100 for {
7101 g, err := s.Gatewayz(nil)
7102 if err != nil {
7103 continue
7104 }
7105 if g.Port != 0 && g.Port != s.GatewayAddr().Port {
7106 t.Fatalf("Unexpected port: %v vs %v", g.Port, s.GatewayAddr().Port)
7107 }
7108 break
7109 }
7110 s.Shutdown()
7111 wg.Wait()
7112 }
7113
7114 func TestGatewaySwitchToInterestOnlyModeImmediately(t *testing.T) {
7115 o2 := testDefaultOptionsForGateway("B")
7116 // Add users to cause s2 to require auth. Will add an account with user later.
7117 o2.Users = append([]*User(nil), &User{Username: "test", Password: "pwd"})
7118 s2 := runGatewayServer(o2)
7119 defer s2.Shutdown()
7120
7121 o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
7122 setAccountUserPassInOptions(o1, "$foo", "ivan", "password")
7123 s1 := runGatewayServer(o1)
7124 defer s1.Shutdown()
7125
7126 waitForOutboundGateways(t, s1, 1, time.Second)
7127 waitForOutboundGateways(t, s2, 1, time.Second)
7128
7129 s1Url := fmt.Sprintf("nats://ivan:[email protected]:%d", o1.Port)
7130 nc := natsConnect(t, s1Url)
7131 defer nc.Close()
7132 natsPub(t, nc, "foo", []byte("hello"))
7133 natsFlush(t, nc)
7134
7135 checkCount := func(t *testing.T, c *client, expected int) {
7136 t.Helper()
7137 c.mu.Lock()
7138 out := c.outMsgs
7139 c.mu.Unlock()
7140 if int(out) != expected {
7141 t.Fatalf("Expected %d message(s) to be sent over, got %v", expected, out)
7142 }
7143 }
7144 // No message should be sent
7145 gwcb := s1.getOutboundGatewayConnection("B")
7146 checkCount(t, gwcb, 0)
7147
7148 // Check that we are in interest-only mode, but in this case, since s2 does
7149 // have the account, we should have the account not even present in the map.
7150 checkGWInterestOnlyModeOrNotPresent(t, s1, "B", "$foo", true)
7151
7152 // Add account to S2 and a client.
7153 s2FooAcc, err := s2.RegisterAccount("$foo")
7154 if err != nil {
7155 t.Fatalf("Error registering account: %v", err)
7156 }
7157 s2.mu.Lock()
7158 s2.users["ivan"] = &User{Account: s2FooAcc, Username: "ivan", Password: "password"}
7159 s2.mu.Unlock()
7160 s2Url := fmt.Sprintf("nats://ivan:[email protected]:%d", o2.Port)
7161 ncS2 := natsConnect(t, s2Url)
7162 defer ncS2.Close()
7163 natsSubSync(t, ncS2, "asub")
7164 // This time we will have the account in the map and it will be interest-only
7165 checkGWInterestOnlyMode(t, s1, "B", "$foo")
7166
7167 // Now publish a message, still should not go because the sub is on "asub"
7168 natsPub(t, nc, "foo", []byte("hello"))
7169 natsFlush(t, nc)
7170 checkCount(t, gwcb, 0)
7171
7172 natsSubSync(t, ncS2, "foo")
7173 natsFlush(t, ncS2)
7174
7175 checkGWInterestOnlyModeInterestOn(t, s1, "B", "$foo", "foo")
7176
7177 // Publish on foo
7178 natsPub(t, nc, "foo", []byte("hello"))
7179 natsFlush(t, nc)
7180 checkCount(t, gwcb, 1)
7181 }
7182
7183 func TestGatewaySlowConsumer(t *testing.T) {
7184 gatewayMaxPingInterval = 50 * time.Millisecond
7185 defer func() { gatewayMaxPingInterval = gwMaxPingInterval }()
7186
7187 ob := testDefaultOptionsForGateway("B")
7188 sb := RunServer(ob)
7189 defer sb.Shutdown()
7190
7191 oa := testGatewayOptionsFromToWithServers(t, "A", "B", sb)
7192 sa := RunServer(oa)
7193 defer sa.Shutdown()
7194
7195 waitForInboundGateways(t, sa, 1, 2*time.Second)
7196 waitForOutboundGateways(t, sa, 1, 2*time.Second)
7197 waitForInboundGateways(t, sb, 1, 2*time.Second)
7198 waitForOutboundGateways(t, sb, 1, 2*time.Second)
7199
7200 c := sa.getOutboundGatewayConnection("B")
7201 c.mu.Lock()
7202 c.out.wdl = time.Nanosecond
7203 c.mu.Unlock()
7204
7205 <-time.After(250 * time.Millisecond)
7206 got := sa.NumSlowConsumersGateways()
7207 expected := uint64(1)
7208 if got != 1 {
7209 t.Errorf("got: %d, expected: %d", got, expected)
7210 }
7211 got = sb.NumSlowConsumersGateways()
7212 expected = 0
7213 if got != expected {
7214 t.Errorf("got: %d, expected: %d", got, expected)
7215 }
7216 }
7217
7218 // https://github.com/nats-io/nats-server/issues/5187
7219 func TestGatewayConnectEvents(t *testing.T) {
7220 checkEvents := func(t *testing.T, name string, queue bool) {
7221 t.Run(name, func(t *testing.T) {
7222 ca := createClusterEx(t, true, 5*time.Millisecond, true, "A", 2)
7223 defer shutdownCluster(ca)
7224
7225 cb := createClusterEx(t, true, 5*time.Millisecond, true, "B", 2, ca)
7226 defer shutdownCluster(cb)
7227
7228 sysA, err := nats.Connect(ca.randomServer().ClientURL(), nats.UserInfo("sys", "pass"))
7229 require_NoError(t, err)
7230 defer sysA.Close()
7231
7232 var sub1 *nats.Subscription
7233 if queue {
7234 sub1, err = sysA.QueueSubscribeSync("$SYS.ACCOUNT.FOO.CONNECT", "myqueue")
7235 } else {
7236 sub1, err = sysA.SubscribeSync("$SYS.ACCOUNT.FOO.CONNECT")
7237 }
7238 require_NoError(t, err)
7239
7240 cA, err := nats.Connect(ca.randomServer().ClientURL(), nats.UserInfo("foo", "pass"))
7241 require_NoError(t, err)
7242 defer cA.Close()
7243
7244 msg, err := sub1.NextMsg(time.Second)
7245 require_NoError(t, err)
7246 require_Equal(t, msg.Subject, "$SYS.ACCOUNT.FOO.CONNECT")
7247
7248 cB, err := nats.Connect(cb.randomServer().ClientURL(), nats.UserInfo("foo", "pass"))
7249 require_NoError(t, err)
7250 defer cB.Close()
7251
7252 msg, err = sub1.NextMsg(time.Second)
7253 require_NoError(t, err)
7254 require_Equal(t, msg.Subject, "$SYS.ACCOUNT.FOO.CONNECT")
7255 })
7256 }
7257
7258 checkEvents(t, "Unqueued", false)
7259 checkEvents(t, "Queued", true)
7260 }
7261
7262 func disconnectInboundGateways(s *Server) {
7263 s.gateway.RLock()
7264 in := s.gateway.in
7265 s.gateway.RUnlock()
7266
7267 s.gateway.RLock()
7268 for _, client := range in {
7269 s.gateway.RUnlock()
7270 client.closeConnection(ClientClosed)
7271 s.gateway.RLock()
7272 }
7273 s.gateway.RUnlock()
7274 }
7275
7276 type testMissingOCSPStapleLogger struct {
7277 DummyLogger
7278 ch chan string
7279 }
7280
7281 func (l *testMissingOCSPStapleLogger) Errorf(format string, v ...any) {
7282 msg := fmt.Sprintf(format, v...)
7283 if strings.Contains(msg, "peer missing OCSP Staple") {
7284 select {
7285 case l.ch <- msg:
7286 default:
7287 }
7288 }
7289 }
7290
7291 func TestGatewayOCSPMissingPeerStapleIssue(t *testing.T) {
7292 const (
7293 caCert = "../test/configs/certs/ocsp/ca-cert.pem"
7294 caKey = "../test/configs/certs/ocsp/ca-key.pem"
7295 )
7296 ctx, cancel := context.WithCancel(context.Background())
7297 defer cancel()
7298 ocspr := NewOCSPResponderCustomTimeout(t, caCert, caKey, 10*time.Minute)
7299 defer ocspr.Shutdown(ctx)
7300 addr := fmt.Sprintf("http://%s", ocspr.Addr)
7301
7302 // Node A
7303 SetOCSPStatus(t, addr, "../test/configs/certs/ocsp/server-status-request-url-01-cert.pem", ocsp.Good)
7304 SetOCSPStatus(t, addr, "../test/configs/certs/ocsp/server-status-request-url-02-cert.pem", ocsp.Good)
7305
7306 // Node B
7307 SetOCSPStatus(t, addr, "../test/configs/certs/ocsp/server-status-request-url-03-cert.pem", ocsp.Good)
7308 SetOCSPStatus(t, addr, "../test/configs/certs/ocsp/server-status-request-url-04-cert.pem", ocsp.Good)
7309
7310 // Node C
7311 SetOCSPStatus(t, addr, "../test/configs/certs/ocsp/server-status-request-url-05-cert.pem", ocsp.Good)
7312 SetOCSPStatus(t, addr, "../test/configs/certs/ocsp/server-status-request-url-06-cert.pem", ocsp.Good)
7313
7314 // Node A rotated certs
7315 SetOCSPStatus(t, addr, "../test/configs/certs/ocsp/server-status-request-url-07-cert.pem", ocsp.Good)
7316 SetOCSPStatus(t, addr, "../test/configs/certs/ocsp/server-status-request-url-08-cert.pem", ocsp.Good)
7317
7318 // Store Dirs
7319 storeDirA := t.TempDir()
7320 storeDirB := t.TempDir()
7321 storeDirC := t.TempDir()
7322
7323 // Gateway server configuration
7324 srvConfA := `
7325 host: "127.0.0.1"
7326 port: -1
7327
7328 server_name: "AAA"
7329
7330 ocsp { mode = always }
7331
7332 system_account = sys
7333 accounts {
7334 sys { users = [{ user: sys, pass: sys }]}
7335 guest { users = [{ user: guest, pass: guest }]}
7336 }
7337 no_auth_user = guest
7338
7339 store_dir: '%s'
7340 gateway {
7341 name: A
7342 host: "127.0.0.1"
7343 port: -1
7344 advertise: "127.0.0.1"
7345
7346 tls {
7347 cert_file: "../test/configs/certs/ocsp/server-status-request-url-02-cert.pem"
7348 key_file: "../test/configs/certs/ocsp/server-status-request-url-02-key.pem"
7349 ca_file: "../test/configs/certs/ocsp/ca-cert.pem"
7350 timeout: 5
7351 }
7352 }
7353 `
7354 srvConfA = fmt.Sprintf(srvConfA, storeDirA)
7355 sconfA := createConfFile(t, []byte(srvConfA))
7356 srvA, optsA := RunServerWithConfig(sconfA)
7357 defer srvA.Shutdown()
7358
7359 // Gateway B connects to Gateway A.
7360 srvConfB := `
7361 host: "127.0.0.1"
7362 port: -1
7363
7364 server_name: "BBB"
7365
7366 ocsp { mode = always }
7367
7368 system_account = sys
7369 accounts {
7370 sys { users = [{ user: sys, pass: sys }]}
7371 guest { users = [{ user: guest, pass: guest }]}
7372 }
7373 no_auth_user = guest
7374
7375 store_dir: '%s'
7376 gateway {
7377 name: B
7378 host: "127.0.0.1"
7379 advertise: "127.0.0.1"
7380 port: -1
7381 gateways: [{
7382 name: "A"
7383 url: "nats://127.0.0.1:%d"
7384 }]
7385
7386 tls {
7387 cert_file: "../test/configs/certs/ocsp/server-status-request-url-04-cert.pem"
7388 key_file: "../test/configs/certs/ocsp/server-status-request-url-04-key.pem"
7389 ca_file: "../test/configs/certs/ocsp/ca-cert.pem"
7390 timeout: 5
7391 }
7392 }
7393 `
7394 srvConfB = fmt.Sprintf(srvConfB, storeDirB, optsA.Gateway.Port)
7395 conf := createConfFile(t, []byte(srvConfB))
7396 srvB, optsB := RunServerWithConfig(conf)
7397 defer srvB.Shutdown()
7398
7399 // Client connects to server A.
7400 cA, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", optsA.Port),
7401 nats.ErrorHandler(noOpErrHandler),
7402 )
7403 if err != nil {
7404 t.Fatal(err)
7405 }
7406 defer cA.Close()
7407
7408 // Wait for connectivity between A and B.
7409 waitForOutboundGateways(t, srvB, 1, 5*time.Second)
7410
7411 // Gateway C also connects to Gateway A.
7412 srvConfC := `
7413 host: "127.0.0.1"
7414 port: -1
7415
7416 server_name: "CCC"
7417
7418 ocsp { mode = always }
7419
7420 system_account = sys
7421 accounts {
7422 sys { users = [{ user: sys, pass: sys }]}
7423 guest { users = [{ user: guest, pass: guest }]}
7424 }
7425 no_auth_user = guest
7426
7427 store_dir: '%s'
7428 gateway {
7429 name: C
7430 host: "127.0.0.1"
7431 advertise: "127.0.0.1"
7432 port: -1
7433 gateways: [{name: "A", url: "nats://127.0.0.1:%d" }]
7434
7435 tls {
7436 cert_file: "../test/configs/certs/ocsp/server-status-request-url-06-cert.pem"
7437 key_file: "../test/configs/certs/ocsp/server-status-request-url-06-key.pem"
7438 ca_file: "../test/configs/certs/ocsp/ca-cert.pem"
7439 timeout: 5
7440 }
7441 }
7442 `
7443 srvConfC = fmt.Sprintf(srvConfC, storeDirC, optsA.Gateway.Port)
7444 conf = createConfFile(t, []byte(srvConfC))
7445 srvC, optsC := RunServerWithConfig(conf)
7446 defer srvC.Shutdown()
7447
7448 ////////////////////////////////////////////////////////////////////////////
7449 // //
7450 // A and B are connected at this point and A is starting with certs that //
7451 // will be rotated.
7452 // //
7453 ////////////////////////////////////////////////////////////////////////////
7454 cB, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", optsB.Port),
7455 nats.ErrorHandler(noOpErrHandler),
7456 )
7457 require_NoError(t, err)
7458 defer cB.Close()
7459
7460 cC, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", optsC.Port),
7461 nats.ErrorHandler(noOpErrHandler),
7462 )
7463 require_NoError(t, err)
7464 defer cC.Close()
7465
7466 _, err = cA.Subscribe("foo", func(m *nats.Msg) {
7467 m.Respond(nil)
7468 })
7469 require_NoError(t, err)
7470
7471 cA.Flush()
7472
7473 _, err = cB.Subscribe("bar", func(m *nats.Msg) {
7474 m.Respond(nil)
7475 })
7476 require_NoError(t, err)
7477 cB.Flush()
7478
7479 waitForOutboundGateways(t, srvB, 1, 10*time.Second)
7480 waitForOutboundGateways(t, srvC, 2, 10*time.Second)
7481
7482 /////////////////////////////////////////////////////////////////////////////////
7483 // //
7484 // Switch all the certs from server A, all OCSP monitors should be restarted //
7485 // so it should have new staples. //
7486 // //
7487 /////////////////////////////////////////////////////////////////////////////////
7488 srvConfA = `
7489 host: "127.0.0.1"
7490 port: -1
7491
7492 server_name: "AAA"
7493
7494 ocsp { mode = always }
7495
7496 system_account = sys
7497 accounts {
7498 sys { users = [{ user: sys, pass: sys }]}
7499 guest { users = [{ user: guest, pass: guest }]}
7500 }
7501 no_auth_user = guest
7502
7503 store_dir: '%s'
7504 gateway {
7505 name: A
7506 host: "127.0.0.1"
7507 port: -1
7508 advertise: "127.0.0.1"
7509
7510 tls {
7511 cert_file: "../test/configs/certs/ocsp/server-status-request-url-08-cert.pem"
7512 key_file: "../test/configs/certs/ocsp/server-status-request-url-08-key.pem"
7513 ca_file: "../test/configs/certs/ocsp/ca-cert.pem"
7514 timeout: 5
7515
7516 }
7517 }
7518 `
7519
7520 srvConfA = fmt.Sprintf(srvConfA, storeDirA)
7521 if err := os.WriteFile(sconfA, []byte(srvConfA), 0666); err != nil {
7522 t.Fatalf("Error writing config: %v", err)
7523 }
7524 if err := srvA.Reload(); err != nil {
7525 t.Fatal(err)
7526 }
7527 waitForOutboundGateways(t, srvA, 2, 5*time.Second)
7528 waitForOutboundGateways(t, srvB, 2, 5*time.Second)
7529 waitForOutboundGateways(t, srvC, 2, 5*time.Second)
7530
7531 // Now clients connect to C can communicate with B and A.
7532 _, err = cC.Request("foo", nil, 2*time.Second)
7533 require_NoError(t, err)
7534
7535 _, err = cC.Request("bar", nil, 2*time.Second)
7536 require_NoError(t, err)
7537
7538 // Reload and disconnect very fast trying to produce the race.
7539 ctx, cancel = context.WithTimeout(context.Background(), 15*time.Second)
7540 defer cancel()
7541
7542 // Swap logger from server to capture the missing peer log.
7543 lA := &testMissingOCSPStapleLogger{ch: make(chan string, 30)}
7544 srvA.SetLogger(lA, false, false)
7545
7546 lB := &testMissingOCSPStapleLogger{ch: make(chan string, 30)}
7547 srvB.SetLogger(lB, false, false)
7548
7549 lC := &testMissingOCSPStapleLogger{ch: make(chan string, 30)}
7550 srvC.SetLogger(lC, false, false)
7551
7552 // Start with a reload from the last server that connected directly to A.
7553 err = srvC.Reload()
7554 require_NoError(t, err)
7555
7556 // Stress reconnections and reloading servers without getting
7557 // missing OCSP peer staple errors.
7558 var wg sync.WaitGroup
7559
7560 wg.Add(1)
7561 go func() {
7562 for range time.NewTicker(500 * time.Millisecond).C {
7563 select {
7564 case <-ctx.Done():
7565 wg.Done()
7566 return
7567 default:
7568 }
7569 disconnectInboundGateways(srvA)
7570 }
7571 }()
7572
7573 wg.Add(1)
7574 go func() {
7575 for range time.NewTicker(500 * time.Millisecond).C {
7576 select {
7577 case <-ctx.Done():
7578 wg.Done()
7579 return
7580 default:
7581 }
7582 disconnectInboundGateways(srvB)
7583 }
7584 }()
7585
7586 wg.Add(1)
7587 go func() {
7588 for range time.NewTicker(500 * time.Millisecond).C {
7589 select {
7590 case <-ctx.Done():
7591 wg.Done()
7592 return
7593 default:
7594 }
7595 disconnectInboundGateways(srvC)
7596 }
7597 }()
7598
7599 wg.Add(1)
7600 go func() {
7601 for range time.NewTicker(700 * time.Millisecond).C {
7602 select {
7603 case <-ctx.Done():
7604 wg.Done()
7605 return
7606 default:
7607 }
7608 srvC.Reload()
7609 }
7610 }()
7611
7612 wg.Add(1)
7613 go func() {
7614 for range time.NewTicker(800 * time.Millisecond).C {
7615 select {
7616 case <-ctx.Done():
7617 wg.Done()
7618 return
7619 default:
7620 }
7621 srvB.Reload()
7622 }
7623 }()
7624
7625 wg.Add(1)
7626 go func() {
7627 for range time.NewTicker(900 * time.Millisecond).C {
7628 select {
7629 case <-ctx.Done():
7630 wg.Done()
7631 return
7632 default:
7633 }
7634 srvA.Reload()
7635 }
7636 }()
7637
7638 select {
7639 case <-ctx.Done():
7640 case msg := <-lA.ch:
7641 t.Fatalf("Server A: Got OCSP Staple error: %v", msg)
7642 case msg := <-lB.ch:
7643 t.Fatalf("Server B: Got OCSP Staple error: %v", msg)
7644 case msg := <-lC.ch:
7645 t.Fatalf("Server C: Got OCSP Staple error: %v", msg)
7646 }
7647 waitForOutboundGateways(t, srvA, 2, 5*time.Second)
7648 waitForOutboundGateways(t, srvB, 2, 5*time.Second)
7649 waitForOutboundGateways(t, srvC, 2, 5*time.Second)
7650 wg.Wait()
7651 }
7652
7653 func TestGatewayOutboundDetectsStaleConnectionIfNoInfo(t *testing.T) {
7654 l, err := net.Listen("tcp", "127.0.0.1:0")
7655 require_NoError(t, err)
7656 defer l.Close()
7657
7658 ch := make(chan struct{})
7659 wg := sync.WaitGroup{}
7660 wg.Add(1)
7661 go func() {
7662 defer wg.Done()
7663 c, err := l.Accept()
7664 if err != nil {
7665 return
7666 }
7667 defer c.Close()
7668 <-ch
7669 }()
7670
7671 url := fmt.Sprintf("nats://%s", l.Addr())
7672 o := testGatewayOptionsFromToWithURLs(t, "A", "B", []string{url})
7673 o.gatewaysSolicitDelay = time.Millisecond
7674 o.DisableShortFirstPing = false
7675 o.PingInterval = 50 * time.Millisecond
7676 o.MaxPingsOut = 3
7677 o.NoLog = false
7678 s, err := NewServer(o)
7679 require_NoError(t, err)
7680 defer s.Shutdown()
7681
7682 log := &captureDebugLogger{dbgCh: make(chan string, 100)}
7683 s.SetLogger(log, true, false)
7684 s.Start()
7685
7686 timeout := time.NewTimer(time.Second)
7687 defer timeout.Stop()
7688 for done := false; !done; {
7689 select {
7690 case dbg := <-log.dbgCh:
7691 // The server should not send PING because the accept side expects
7692 // the CONNECT as the first protocol (otherwise it would be a parse
7693 // error if that were to happen).
7694 if strings.Contains(dbg, "Ping Timer") {
7695 t.Fatalf("The server should not have sent a ping, got %q", dbg)
7696 }
7697 // However, it should detect at one point that the connection is
7698 // stale and close it.
7699 if strings.Contains(dbg, "Stale") {
7700 done = true
7701 }
7702 case <-timeout.C:
7703 t.Fatalf("Did not capture the stale connection condition")
7704 }
7705 }
7706
7707 s.Shutdown()
7708 close(ch)
7709 wg.Wait()
7710 s.WaitForShutdown()
7711 }
7712
7713 func TestGatewayConfigureWriteDeadline(t *testing.T) {
7714 o1 := testDefaultOptionsForGateway("B")
7715 o1.Gateway.WriteDeadline = 5 * time.Second
7716 s1 := runGatewayServer(o1)
7717 defer s1.Shutdown()
7718
7719 o2 := testGatewayOptionsFromToWithServers(t, "A", "B", s1)
7720 s2 := runGatewayServer(o2)
7721 defer s2.Shutdown()
7722
7723 waitForOutboundGateways(t, s2, 1, time.Second)
7724 waitForInboundGateways(t, s1, 1, time.Second)
7725 waitForOutboundGateways(t, s1, 1, time.Second)
7726
7727 s1.mu.RLock()
7728 defer s1.mu.RUnlock()
7729
7730 s1.gateway.RLock()
7731 defer s1.gateway.RUnlock()
7732
7733 for _, r := range s1.gateway.out {
7734 r.mu.Lock()
7735 wdl := r.out.wdl
7736 r.mu.Unlock()
7737 require_Equal(t, wdl, 5*time.Second)
7738 }
7739
7740 for _, r := range s1.gateway.in {
7741 r.mu.Lock()
7742 wdl := r.out.wdl
7743 r.mu.Unlock()
7744 require_Equal(t, wdl, 5*time.Second)
7745 }
7746 }
7747
7748 func TestGatewayConfigureWriteTimeoutPolicy(t *testing.T) {
7749 for name, policy := range map[string]WriteTimeoutPolicy{
7750 "Default": WriteTimeoutPolicyDefault,
7751 "Retry": WriteTimeoutPolicyRetry,
7752 "Close": WriteTimeoutPolicyClose,
7753 } {
7754 t.Run(name, func(t *testing.T) {
7755 o1 := testDefaultOptionsForGateway("B")
7756 o1.Gateway.WriteTimeout = policy
7757 s1 := runGatewayServer(o1)
7758 defer s1.Shutdown()
7759
7760 o2 := testGatewayOptionsFromToWithServers(t, "A", "B", s1)
7761 s2 := runGatewayServer(o2)
7762 defer s2.Shutdown()
7763
7764 waitForOutboundGateways(t, s2, 1, time.Second)
7765 waitForInboundGateways(t, s1, 1, time.Second)
7766 waitForOutboundGateways(t, s1, 1, time.Second)
7767
7768 s1.mu.RLock()
7769 defer s1.mu.RUnlock()
7770
7771 s1.gateway.RLock()
7772 defer s1.gateway.RUnlock()
7773
7774 for _, r := range s1.gateway.out {
7775 if policy == WriteTimeoutPolicyDefault {
7776 require_Equal(t, r.out.wtp, WriteTimeoutPolicyRetry)
7777 } else {
7778 require_Equal(t, r.out.wtp, policy)
7779 }
7780 }
7781
7782 for _, r := range s1.gateway.in {
7783 if policy == WriteTimeoutPolicyDefault {
7784 require_Equal(t, r.out.wtp, WriteTimeoutPolicyRetry)
7785 } else {
7786 require_Equal(t, r.out.wtp, policy)
7787 }
7788 }
7789 })
7790 }
7791 }
7792
7793 func TestGatewayProcessRSubNoBlockingAccountFetch(t *testing.T) {
7794 createAccountPubKey := func() string {
7795 kp, err := nkeys.CreateAccount()
7796 require_NoError(t, err)
7797 pubkey, err := kp.PublicKey()
7798 require_NoError(t, err)
7799 return pubkey
7800 }
7801 sysPub := createAccountPubKey()
7802 accPub := createAccountPubKey()
7803 dir := t.TempDir()
7804 conf := createConfFile(t, []byte(fmt.Sprintf(`
7805 listen: 127.0.0.1:-1
7806 server_name: srv
7807 operator: %s
7808 system_account: %s
7809 resolver: {
7810 type: cache
7811 dir: '%s'
7812 timeout: "2s"
7813 }
7814 gateway: {
7815 name: "clust-B"
7816 listen: 127.0.0.1:-1
7817 }
7818 `, ojwt, sysPub, dir)))
7819 s, _ := RunServerWithConfig(conf)
7820 defer s.Shutdown()
7821
7822 // Set up a mock gateway client.
7823 c := s.createInternalAccountClient()
7824 c.mu.Lock()
7825 c.gw = &gateway{}
7826 c.gw.outsim = &sync.Map{}
7827 c.nc = &net.IPConn{}
7828 c.mu.Unlock()
7829
7830 // Receiving a R+ should not be blocking, since we're in the gateway's readLoop.
7831 start := time.Now()
7832 require_NoError(t, c.processGatewayRSub(fmt.Appendf(nil, "%s subj queue 0", accPub)))
7833 ei, ok := c.gw.outsim.Load(accPub)
7834 require_True(t, ok)
7835 require_True(t, ei.(*outsie).sl.CacheEnabled())
7836 c.mu.Lock()
7837 subs := len(c.subs)
7838 c.mu.Unlock()
7839 require_Len(t, subs, 1)
7840 require_LessThan(t, time.Since(start), 100*time.Millisecond)
7841
7842 // Receiving a R- should not be blocking, since we're in the gateway's readLoop.
7843 start = time.Now()
7844 require_NoError(t, c.processGatewayRUnsub(fmt.Appendf(nil, "%s subj queue", accPub)))
7845 c.mu.Lock()
7846 subs = len(c.subs)
7847 c.mu.Unlock()
7848 require_Len(t, subs, 0)
7849 require_LessThan(t, time.Since(start), 100*time.Millisecond)
7850
7851 c2 := s.createInternalAccountClient()
7852 c2.mu.Lock()
7853 c2.gw = &gateway{}
7854 c2.gw.outsim = &sync.Map{}
7855 c2.nc = &net.IPConn{}
7856 c2.mu.Unlock()
7857
7858 require_NoError(t, c2.processGatewayRUnsub(fmt.Appendf(nil, "%s subj", accPub)))
7859 ei, ok = c2.gw.outsim.Load(accPub)
7860 require_True(t, ok)
7861 require_True(t, ei.(*outsie).sl.CacheEnabled())
7862 }