Debian Codegraph @

test/norace_test.go

raw
1 // Copyright 2019-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 //go:build !race && !skip_no_race_tests && !skip_no_race_1_tests
15
16 package test
17
18 import (
19 "context"
20 crand "crypto/rand"
21 "encoding/json"
22 "fmt"
23 "net"
24 "net/url"
25 "os"
26 "regexp"
27 "runtime"
28 "strconv"
29 "sync"
30 "testing"
31 "time"
32
33 "github.com/nats-io/nats-server/v2/server"
34 "github.com/nats-io/nats.go"
35 "github.com/nats-io/nuid"
36 )
37
38 // IMPORTANT: Tests in this file are not executed when running with the -race flag.
39 // The test name should be prefixed with TestNoRace so we can run only
40 // those tests: go test -run=TestNoRace ...
41
42 func TestNoRaceRouteSendSubs(t *testing.T) {
43 template := `
44 port: -1
45 write_deadline: "2s"
46 cluster {
47 port: -1
48 pool_size: -1
49 compression: disabled
50 %s
51 }
52 no_sys_acc: true
53 `
54 cfa := createConfFile(t, []byte(fmt.Sprintf(template, "")))
55 srvA, optsA := RunServerWithConfig(cfa)
56 srvA.Shutdown()
57 optsA.DisableShortFirstPing = true
58 srvA = RunServer(optsA)
59 defer srvA.Shutdown()
60
61 cfb := createConfFile(t, []byte(fmt.Sprintf(template, "")))
62 srvB, optsB := RunServerWithConfig(cfb)
63 srvB.Shutdown()
64 optsB.DisableShortFirstPing = true
65 srvB = RunServer(optsB)
66 defer srvB.Shutdown()
67
68 clientA := createClientConn(t, optsA.Host, optsA.Port)
69 defer clientA.Close()
70
71 clientASend, clientAExpect := setupConn(t, clientA)
72 clientASend("PING\r\n")
73 clientAExpect(pongRe)
74
75 clientB := createClientConn(t, optsB.Host, optsB.Port)
76 defer clientB.Close()
77
78 clientBSend, clientBExpect := setupConn(t, clientB)
79 clientBSend("PING\r\n")
80 clientBExpect(pongRe)
81
82 // total number of subscriptions per server
83 totalPerServer := 100000
84 for i := 0; i < totalPerServer/2; i++ {
85 proto := fmt.Sprintf("SUB foo.%d %d\r\n", i, i*2+1)
86 clientASend(proto)
87 clientBSend(proto)
88 proto = fmt.Sprintf("SUB bar.%d queue.%d %d\r\n", i, i, i*2+2)
89 clientASend(proto)
90 clientBSend(proto)
91 }
92 clientASend("PING\r\n")
93 clientAExpect(pongRe)
94 clientBSend("PING\r\n")
95 clientBExpect(pongRe)
96
97 if err := checkExpectedSubs(totalPerServer, srvA, srvB); err != nil {
98 t.Fatal(err.Error())
99 }
100
101 routes := fmt.Sprintf(`
102 routes: [
103 "nats://%s:%d"
104 ]
105 `, optsA.Cluster.Host, optsA.Cluster.Port)
106 if err := os.WriteFile(cfb, []byte(fmt.Sprintf(template, routes)), 0600); err != nil {
107 t.Fatalf("Error rewriting B's config file: %v", err)
108 }
109 if err := srvB.Reload(); err != nil {
110 t.Fatalf("Error on reload: %v", err)
111 }
112
113 checkClusterFormed(t, srvA, srvB)
114 if err := checkExpectedSubs(2*totalPerServer, srvA, srvB); err != nil {
115 t.Fatal(err.Error())
116 }
117
118 checkSlowConsumers := func(t *testing.T) {
119 t.Helper()
120 if srvB.NumSlowConsumers() != 0 || srvA.NumSlowConsumers() != 0 {
121 t.Fatalf("Expected no slow consumers, got %d for srvA and %df for srvB",
122 srvA.NumSlowConsumers(), srvB.NumSlowConsumers())
123 }
124 }
125 checkSlowConsumers(t)
126
127 type sender struct {
128 c net.Conn
129 sf sendFun
130 ef expectFun
131 }
132 var senders []*sender
133 createSenders := func(t *testing.T, host string, port int) {
134 t.Helper()
135 for i := 0; i < 25; i++ {
136 s := &sender{}
137 s.c = createClientConn(t, host, port)
138 s.sf, s.ef = setupConn(t, s.c)
139 s.sf("PING\r\n")
140 s.ef(pongRe)
141 senders = append(senders, s)
142 }
143 }
144 createSenders(t, optsA.Host, optsA.Port)
145 createSenders(t, optsB.Host, optsB.Port)
146 for _, s := range senders {
147 defer s.c.Close()
148 }
149
150 // Now create SUBs on A and B for "ping.replies" and simulate
151 // that there are thousands of replies being sent on
152 // both sides.
153 createSubOnReplies := func(t *testing.T, host string, port int) net.Conn {
154 t.Helper()
155 c := createClientConn(t, host, port)
156 send, expect := setupConn(t, c)
157 send("SUB ping.replies 123456789\r\nPING\r\n")
158 expect(pongRe)
159 return c
160 }
161 requestorOnA := createSubOnReplies(t, optsA.Host, optsA.Port)
162 defer requestorOnA.Close()
163
164 requestorOnB := createSubOnReplies(t, optsB.Host, optsB.Port)
165 defer requestorOnB.Close()
166
167 if err := checkExpectedSubs(2*totalPerServer+2, srvA, srvB); err != nil {
168 t.Fatal(err.Error())
169 }
170
171 totalReplies := 120000
172 payload := sizedBytes(400)
173 expectedBytes := (len(fmt.Sprintf("MSG ping.replies 123456789 %d\r\n\r\n", len(payload))) + len(payload)) * totalReplies
174 ch := make(chan error, 2)
175 recvReplies := func(c net.Conn) {
176 var buf [32 * 1024]byte
177
178 for total := 0; total < expectedBytes; {
179 n, err := c.Read(buf[:])
180 if err != nil {
181 ch <- fmt.Errorf("read error: %v", err)
182 return
183 }
184 total += n
185 }
186 ch <- nil
187 }
188 go recvReplies(requestorOnA)
189 go recvReplies(requestorOnB)
190
191 wg := sync.WaitGroup{}
192 wg.Add(len(senders))
193 replyMsg := fmt.Sprintf("PUB ping.replies %d\r\n%s\r\n", len(payload), payload)
194 for _, s := range senders {
195 go func(s *sender, count int) {
196 defer wg.Done()
197 for i := 0; i < count; i++ {
198 s.sf(replyMsg)
199 }
200 s.sf("PING\r\n")
201 s.ef(pongRe)
202 }(s, totalReplies/len(senders))
203 }
204
205 for i := 0; i < 2; i++ {
206 select {
207 case e := <-ch:
208 if e != nil {
209 t.Fatalf("Error: %v", e)
210 }
211 case <-time.After(10 * time.Second):
212 t.Fatalf("Did not receive all %v replies", totalReplies)
213 }
214 }
215 checkSlowConsumers(t)
216 wg.Wait()
217 checkSlowConsumers(t)
218
219 // Let's remove the route and do a config reload.
220 // Otherwise, on test shutdown the client close
221 // will cause the server to try to send unsubs and
222 // this can delay the test.
223 if err := os.WriteFile(cfb, []byte(fmt.Sprintf(template, "")), 0600); err != nil {
224 t.Fatalf("Error rewriting B's config file: %v", err)
225 }
226 if err := srvB.Reload(); err != nil {
227 t.Fatalf("Error on reload: %v", err)
228 }
229 }
230
231 func TestNoRaceDynamicResponsePermsMemory(t *testing.T) {
232 srv, opts := RunServerWithConfig("./configs/authorization.conf")
233 defer srv.Shutdown()
234
235 // We will test the timeout to make sure that we are not showing excessive growth
236 // when a reply subject is not utilized by the responder.
237
238 // Alice can do anything, so she will be our requestor
239 rc := createClientConn(t, opts.Host, opts.Port)
240 defer rc.Close()
241 expectAuthRequired(t, rc)
242 doAuthConnect(t, rc, "", "alice", DefaultPass)
243 expectResult(t, rc, okRe)
244
245 // MY_STREAM_SERVICE has an expiration of 10ms for the response permissions.
246 c := createClientConn(t, opts.Host, opts.Port)
247 defer c.Close()
248 expectAuthRequired(t, c)
249 doAuthConnect(t, c, "", "svcb", DefaultPass)
250 expectResult(t, c, okRe)
251
252 sendProto(t, c, "SUB my.service.req 1\r\n")
253 expectResult(t, c, okRe)
254
255 var m runtime.MemStats
256
257 runtime.GC()
258 runtime.ReadMemStats(&m)
259 pta := m.TotalAlloc
260
261 // Need this so we do not blow the allocs on expectResult which makes 32k each time.
262 expBuf := make([]byte, 32768)
263 expect := func(c net.Conn, re *regexp.Regexp) {
264 t.Helper()
265 c.SetReadDeadline(time.Now().Add(2 * time.Second))
266 n, _ := c.Read(expBuf)
267 c.SetReadDeadline(time.Time{})
268 buf := expBuf[:n]
269 if !re.Match(buf) {
270 t.Fatalf("Response did not match expected: \n\tReceived:'%q'\n\tExpected:'%s'", buf, re)
271 }
272 }
273
274 // Now send off some requests. We will not answer them and this will build up reply
275 // permissions in the server.
276 for i := 0; i < 10000; i++ {
277 pub := fmt.Sprintf("PUB my.service.req resp.%d 2\r\nok\r\n", i)
278 sendProto(t, rc, pub)
279 expect(rc, okRe)
280 expect(c, msgRe)
281 }
282
283 const max = 20 * 1024 * 1024 // 20MB
284 checkFor(t, time.Second, 25*time.Millisecond, func() error {
285 runtime.GC()
286 runtime.ReadMemStats(&m)
287 used := m.TotalAlloc - pta
288 if used > max {
289 return fmt.Errorf("Using too much memory, expect < 20MB, got %dMB", used/(1024*1024))
290 }
291 return nil
292 })
293 }
294
295 func TestNoRaceLargeClusterMem(t *testing.T) {
296 // Try to clean up.
297 runtime.GC()
298 var m runtime.MemStats
299 runtime.ReadMemStats(&m)
300 pta := m.TotalAlloc
301
302 opts := func() *server.Options {
303 o := DefaultTestOptions
304 o.Host = "127.0.0.1"
305 o.Port = -1
306 o.Cluster.Host = o.Host
307 o.Cluster.Port = -1
308 return &o
309 }
310
311 var servers []*server.Server
312
313 // Create seed first.
314 o := opts()
315 s := RunServer(o)
316 servers = append(servers, s)
317
318 // For connecting to seed server above.
319 routeAddr := fmt.Sprintf("nats-route://%s:%d", o.Cluster.Host, o.Cluster.Port)
320 rurl, _ := url.Parse(routeAddr)
321 routes := []*url.URL{rurl}
322
323 numServers := 15
324
325 for i := 1; i < numServers; i++ {
326 o := opts()
327 o.Routes = routes
328 s := RunServer(o)
329 servers = append(servers, s)
330 }
331 checkClusterFormed(t, servers...)
332
333 // Calculate in MB what we are using now.
334 const max = 80 * 1024 * 1024 // 80MB
335 runtime.ReadMemStats(&m)
336 used := m.TotalAlloc - pta
337 if used > max {
338 t.Fatalf("Cluster using too much memory, expect < 80MB, got %dMB", used/(1024*1024))
339 }
340
341 for _, s := range servers {
342 s.Shutdown()
343 }
344 }
345
346 // Make sure we have the correct remote state when dealing with queue subscribers
347 // across many client connections.
348 func TestNoRaceQueueSubWeightOrderMultipleConnections(t *testing.T) {
349 opts, err := server.ProcessConfigFile("./configs/new_cluster.conf")
350 if err != nil {
351 t.Fatalf("Error processing config file: %v", err)
352 }
353 opts.DisableShortFirstPing = true
354 s := RunServer(opts)
355 defer s.Shutdown()
356
357 // Create 100 connections to s
358 url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
359 clients := make([]*nats.Conn, 0, 100)
360 for i := 0; i < 100; i++ {
361 nc, err := nats.Connect(url, nats.NoReconnect())
362 if err != nil {
363 t.Fatalf("Error connecting: %v", err)
364 }
365 defer nc.Close()
366 clients = append(clients, nc)
367 }
368
369 rc := createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
370 defer rc.Close()
371
372 routeID := "RTEST_NEW:22"
373 routeSend, routeExpect := setupRouteEx(t, rc, opts, routeID)
374
375 info := checkInfoMsg(t, rc)
376
377 info.ID = routeID
378 info.Name = routeID
379
380 b, err := json.Marshal(info)
381 if err != nil {
382 t.Fatalf("Could not marshal test route info: %v", err)
383 }
384 // Send our INFO and wait for a PONG. This will prevent a race
385 // where server will have started processing queue subscriptions
386 // and then processes the route's INFO (sending its current subs)
387 // followed by updates.
388 routeSend(fmt.Sprintf("INFO %s\r\nPING\r\n", b))
389 routeExpect(pongRe)
390
391 start := make(chan bool)
392 for _, nc := range clients {
393 go func(nc *nats.Conn) {
394 <-start
395 // Now create 100 identical queue subscribers on each connection.
396 for i := 0; i < 100; i++ {
397 if _, err := nc.QueueSubscribe("foo", "bar", func(_ *nats.Msg) {}); err != nil {
398 return
399 }
400 }
401 nc.Flush()
402 }(nc)
403 }
404 close(start)
405
406 // We did have this where we wanted to get every update, but now with optimizations
407 // we just want to make sure we always are increasing and that a previous update to
408 // a lesser queue weight is never delivered for this test.
409 maxExpected := 10000
410 updates := 0
411 for qw := 0; qw < maxExpected; {
412 buf := routeExpect(rsubRe)
413 matches := rsubRe.FindAllSubmatch(buf, -1)
414 for _, m := range matches {
415 if len(m) != 5 {
416 t.Fatalf("Expected a weight for the queue group")
417 }
418 nqw, err := strconv.Atoi(string(m[4]))
419 if err != nil {
420 t.Fatalf("Got an error converting queue weight: %v", err)
421 }
422 // Make sure the new value only increases, ok to skip since we will
423 // optimize this now, but needs to always be increasing.
424 if nqw <= qw {
425 t.Fatalf("Was expecting increasing queue weight after %d, got %d", qw, nqw)
426 }
427 qw = nqw
428 updates++
429 }
430 }
431 if updates >= maxExpected {
432 t.Fatalf("Was not expecting all %v updates to be received", maxExpected)
433 }
434 }
435
436 func TestNoRaceClusterLeaksSubscriptions(t *testing.T) {
437 srvA, srvB, optsA, optsB := runServers(t)
438 defer srvA.Shutdown()
439 defer srvB.Shutdown()
440
441 checkClusterFormed(t, srvA, srvB)
442
443 urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, optsA.Port)
444 urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, optsB.Port)
445
446 numResponses := 100
447 repliers := make([]*nats.Conn, 0, numResponses)
448
449 var noOpErrHandler = func(_ *nats.Conn, _ *nats.Subscription, _ error) {}
450
451 // Create 100 repliers
452 for i := 0; i < 50; i++ {
453 nc1, _ := nats.Connect(urlA)
454 defer nc1.Close()
455 nc1.SetErrorHandler(noOpErrHandler)
456 nc2, _ := nats.Connect(urlB)
457 defer nc2.Close()
458 nc2.SetErrorHandler(noOpErrHandler)
459 repliers = append(repliers, nc1, nc2)
460 nc1.Subscribe("test.reply", func(m *nats.Msg) {
461 m.Respond([]byte("{\"sender\": 22 }"))
462 })
463 nc2.Subscribe("test.reply", func(m *nats.Msg) {
464 m.Respond([]byte("{\"sender\": 33 }"))
465 })
466 nc1.Flush()
467 nc2.Flush()
468 }
469
470 servers := fmt.Sprintf("%s, %s", urlA, urlB)
471 req := sizedBytes(8 * 1024)
472
473 // Now run a requestor in a loop, creating and tearing down each time to
474 // simulate running a modified nats-req.
475 doReq := func() {
476 msgs := make(chan *nats.Msg, 1)
477 inbox := nats.NewInbox()
478 grp := nuid.Next()
479 // Create 8 queue Subscribers for responses.
480 for i := 0; i < 8; i++ {
481 nc, _ := nats.Connect(servers)
482 nc.SetErrorHandler(noOpErrHandler)
483 nc.ChanQueueSubscribe(inbox, grp, msgs)
484 nc.Flush()
485 defer nc.Close()
486 }
487 nc, _ := nats.Connect(servers)
488 nc.SetErrorHandler(noOpErrHandler)
489 nc.PublishRequest("test.reply", inbox, req)
490 defer nc.Close()
491
492 ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
493 defer cancel()
494
495 var received int
496 for {
497 select {
498 case <-msgs:
499 received++
500 if received >= numResponses {
501 return
502 }
503 case <-ctx.Done():
504 return
505 }
506 }
507 }
508
509 var wg sync.WaitGroup
510
511 doRequests := func(n int) {
512 for i := 0; i < n; i++ {
513 doReq()
514 }
515 wg.Done()
516 }
517
518 concurrent := 10
519 wg.Add(concurrent)
520 for i := 0; i < concurrent; i++ {
521 go doRequests(10)
522 }
523 wg.Wait()
524
525 // Close responders too, should have zero(0) subs attached to routes.
526 for _, nc := range repliers {
527 nc.Close()
528 }
529
530 // Make sure no clients remain. This is to make sure the test is correct and that
531 // we have closed all the client connections.
532 checkFor(t, time.Second, 10*time.Millisecond, func() error {
533 v1, _ := srvA.Varz(nil)
534 v2, _ := srvB.Varz(nil)
535 if v1.Connections != 0 || v2.Connections != 0 {
536 return fmt.Errorf("We have lingering client connections %d:%d", v1.Connections, v2.Connections)
537 }
538 return nil
539 })
540
541 loadRoutez := func() (*server.Routez, *server.Routez) {
542 v1, err := srvA.Routez(&server.RoutezOptions{Subscriptions: true})
543 if err != nil {
544 t.Fatalf("Error getting Routez: %v", err)
545 }
546 v2, err := srvB.Routez(&server.RoutezOptions{Subscriptions: true})
547 if err != nil {
548 t.Fatalf("Error getting Routez: %v", err)
549 }
550 return v1, v2
551 }
552
553 checkFor(t, time.Second, 10*time.Millisecond, func() error {
554 r1, r2 := loadRoutez()
555 if r1.Routes[0].NumSubs != 0 {
556 return fmt.Errorf("Leaked %d subs: %+v", r1.Routes[0].NumSubs, r1.Routes[0].Subs)
557 }
558 if r2.Routes[0].NumSubs != 0 {
559 return fmt.Errorf("Leaked %d subs: %+v", r2.Routes[0].NumSubs, r2.Routes[0].Subs)
560 }
561 return nil
562 })
563 }
564
565 func TestNoRaceLeafNodeSmapUpdate(t *testing.T) {
566 s, opts := runLeafServer()
567 defer s.Shutdown()
568
569 // Create a client on leaf server
570 c := createClientConn(t, opts.Host, opts.Port)
571 defer c.Close()
572 csend, cexpect := setupConn(t, c)
573
574 numSubs := make(chan int, 1)
575 doneCh := make(chan struct{}, 1)
576 wg := sync.WaitGroup{}
577 wg.Add(1)
578
579 go func() {
580 defer wg.Done()
581 for i := 1; ; i++ {
582 csend(fmt.Sprintf("SUB foo.%d %d\r\n", i, i))
583 select {
584 case <-doneCh:
585 numSubs <- i
586 return
587 default:
588 }
589 }
590 }()
591
592 time.Sleep(5 * time.Millisecond)
593 // Create leaf node
594 lc := createLeafConn(t, opts.LeafNode.Host, opts.LeafNode.Port)
595 defer lc.Close()
596
597 setupConn(t, lc)
598 checkLeafNodeConnected(t, s)
599
600 close(doneCh)
601 ns := <-numSubs
602 csend("PING\r\n")
603 cexpect(pongRe)
604 wg.Wait()
605
606 // Make sure we receive as many LS+ protocols (since all subs are unique).
607 // But we also have to count for LDS subject.
608 // There may be so many protocols and partials, that expectNumberOfProtos may
609 // not work. Do a manual search here.
610 checkLS := func(proto string, expected int) {
611 t.Helper()
612 p := []byte(proto)
613 cur := 0
614 buf := make([]byte, 32768)
615 for ls := 0; ls < expected; {
616 lc.SetReadDeadline(time.Now().Add(2 * time.Second))
617 n, err := lc.Read(buf)
618 lc.SetReadDeadline(time.Time{})
619 if err == nil && n > 0 {
620 for i := 0; i < n; i++ {
621 if buf[i] == p[cur] {
622 cur++
623 if cur == len(p) {
624 ls++
625 cur = 0
626 }
627 } else {
628 cur = 0
629 }
630 }
631 }
632 if err != nil || ls > expected {
633 t.Fatalf("Expected %v %sgot %v, err: %v", expected, proto, ls, err)
634 }
635 }
636 }
637 checkLS("LS+ ", ns+1)
638
639 // Now unsub all those subs...
640 for i := 1; i <= ns; i++ {
641 csend(fmt.Sprintf("UNSUB %d\r\n", i))
642 }
643 csend("PING\r\n")
644 cexpect(pongRe)
645
646 // Expect that many LS-
647 checkLS("LS- ", ns)
648 }
649
650 func TestNoRaceSlowProxy(t *testing.T) {
651 t.Skip()
652
653 opts := DefaultTestOptions
654 opts.Port = -1
655 s := RunServer(&opts)
656 defer s.Shutdown()
657
658 rttTarget := 22 * time.Millisecond
659 bwTarget := 10 * 1024 * 1024 / 8 // 10mbit
660
661 sp := newSlowProxy(rttTarget, bwTarget, bwTarget, &opts)
662 defer sp.stop()
663
664 nc, err := nats.Connect(sp.clientURL())
665 if err != nil {
666 t.Fatalf("Unexpected error: %v", err)
667 }
668 defer nc.Close()
669
670 doRTT := func() time.Duration {
671 t.Helper()
672 const samples = 5
673 var total time.Duration
674 for i := 0; i < samples; i++ {
675 rtt, _ := nc.RTT()
676 total += rtt
677 }
678 return total / samples
679 }
680
681 rtt := doRTT()
682 if rtt < rttTarget || rtt > (rttTarget*3/2) {
683 t.Fatalf("rtt is out of range, target of %v, actual %v", rttTarget, rtt)
684 }
685
686 // Now test send BW.
687 const payloadSize = 64 * 1024
688 var payload [payloadSize]byte
689 crand.Read(payload[:])
690
691 // 5MB total.
692 bytesSent := (5 * 1024 * 1024)
693 toSend := bytesSent / payloadSize
694
695 start := time.Now()
696 for i := 0; i < toSend; i++ {
697 nc.Publish("z", payload[:])
698 }
699 nc.Flush()
700 tt := time.Since(start)
701 bps := float64(bytesSent) / tt.Seconds()
702 min, max := float64(bwTarget)*0.8, float64(bwTarget)*1.25
703 if bps < min || bps > max {
704 t.Fatalf("bps is off, target is %v, actual is %v", bwTarget, bps)
705 }
706 }