Debian Codegraph @

udp/udp_linux_test.go

raw
1 //go:build linux && !android && !e2e_testing
2
3 package udp
4
5 import (
6 "errors"
7 "fmt"
8 "log/slog"
9 "net"
10 "net/netip"
11 "os"
12 "runtime"
13 "sync/atomic"
14 "testing"
15 "time"
16
17 "golang.org/x/sys/unix"
18 )
19
20 func testLogger() *slog.Logger {
21 return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
22 }
23
24 // TestShutdownWakesAfterRx_Mechanism exercises the kernel quirk our teardown
25 // relies on: once a socket has received a packet, shutdown(2) wakes a blocked
26 // recvmmsg with n>=1/Len==0 (not n==0). recvmmsg must turn that into net.ErrClosed
27 // once Close set closed, so a parked reader exits instead of spinning.
28 func TestShutdownWakesAfterRx_Mechanism(t *testing.T) {
29 c, err := NewListener(testLogger(), netip.MustParseAddr("127.0.0.1"), 0, true, 64)
30 if err != nil {
31 t.Fatalf("NewListener: %v", err)
32 }
33 sc := c.(*StdConn)
34 addr, err := sc.LocalAddr()
35 if err != nil {
36 t.Fatalf("LocalAddr: %v", err)
37 }
38 msgs, _, _ := sc.PrepareRawMessages(sc.batch)
39
40 // Receive a real packet so the socket has carried data.
41 send, err := net.Dial("udp", addr.String())
42 if err != nil {
43 t.Fatalf("dial: %v", err)
44 }
45 if _, err := send.Write([]byte("hello")); err != nil {
46 t.Fatalf("write: %v", err)
47 }
48 time.Sleep(50 * time.Millisecond)
49 n, err := sc.recvmmsg(msgs)
50 t.Logf("drain of real packet: n=%d err=%v msgs[0].Len=%d", n, err, msgs[0].Len)
51 _ = send.Close()
52
53 // Block a reader on the now-empty queue, then tear down as Close() does.
54 // recvmmsg must return net.ErrClosed (not hang, not spin) even post-rx.
55 done := make(chan error, 1)
56 go func() {
57 _, err := sc.recvmmsg(msgs)
58 done <- err
59 }()
60 time.Sleep(150 * time.Millisecond) // let it park in recvmmsg
61
62 sc.closed.Store(true)
63 if serr := unix.Shutdown(sc.sysFd, unix.SHUT_RDWR); serr != nil {
64 t.Logf("shutdown returned %v (expected ENOTCONN on unconnected UDP)", serr)
65 }
66
67 select {
68 case err := <-done:
69 if !errors.Is(err, net.ErrClosed) {
70 t.Errorf("recvmmsg after post-rx shutdown returned %v, want net.ErrClosed", err)
71 }
72 case <-time.After(2 * time.Second):
73 t.Fatalf("HANG: recvmmsg did not return after shutdown following a received packet")
74 }
75 _ = unix.Close(sc.sysFd)
76 }
77
78 // TestListenOutTeardown_TrafficPatterns reproduces the field report: a blocking
79 // reader must tear down cleanly on Close() regardless of what the socket has
80 // carried. The three cases the report called out:
81 //
82 // no traffic ever -> works (shutdown wakes recvmmsg with n==0)
83 // ping once, then idle -> historically HUNG: once the socket has received a
84 // packet, shutdown(2) wakes recvmmsg with n>=1/Len==0,
85 // which an n==0-only teardown check misses
86 // continuous traffic -> works (a real packet is always arriving)
87 //
88 // All three must return within the deadline; a hang dumps goroutines so the
89 // stuck reader is visible.
90 func TestListenOutTeardown_TrafficPatterns(t *testing.T) {
91 cases := []struct {
92 name string
93 traffic func(send net.Conn, stop <-chan struct{})
94 }{
95 {"no_traffic_ever", func(net.Conn, <-chan struct{}) {}},
96 {"ping_once_then_idle", func(send net.Conn, _ <-chan struct{}) {
97 _, _ = send.Write([]byte("hello"))
98 }},
99 {"continuous", func(send net.Conn, stop <-chan struct{}) {
100 for {
101 select {
102 case <-stop:
103 return
104 default:
105 _, _ = send.Write([]byte("hello"))
106 time.Sleep(2 * time.Millisecond)
107 }
108 }
109 }},
110 }
111
112 // batch 1 exercises the recvmsg path, batch 64 the recvmmsg path; both must
113 // tear down cleanly.
114 for _, batch := range []int{1, 64} {
115 for _, tc := range cases {
116 t.Run(fmt.Sprintf("batch%d/%s", batch, tc.name), func(t *testing.T) {
117 runTeardownCase(t, batch, tc.name, tc.traffic)
118 })
119 }
120 }
121 }
122
123 func runTeardownCase(t *testing.T, batch int, name string, traffic func(send net.Conn, stop <-chan struct{})) {
124 c, err := NewListener(testLogger(), netip.MustParseAddr("127.0.0.1"), 0, true, batch)
125 if err != nil {
126 t.Fatalf("NewListener: %v", err)
127 }
128 sc := c.(*StdConn)
129 addr, err := sc.LocalAddr()
130 if err != nil {
131 t.Fatalf("LocalAddr: %v", err)
132 }
133
134 var received atomic.Int64
135 loopDone := make(chan error, 1)
136 go func() {
137 loopDone <- sc.ListenOut(func(netip.AddrPort, []byte) {
138 received.Add(1)
139 })
140 }()
141
142 send, err := net.Dial("udp", addr.String())
143 if err != nil {
144 t.Fatalf("dial: %v", err)
145 }
146 defer send.Close()
147
148 stop := make(chan struct{})
149 trafficDone := make(chan struct{})
150 go func() {
151 traffic(send, stop)
152 close(trafficDone)
153 }()
154
155 // Let the pattern run and, for the idle case, the reader park again on an
156 // empty queue with the socket already having received a packet.
157 time.Sleep(500 * time.Millisecond)
158
159 start := time.Now()
160 if err := sc.Close(); err != nil {
161 t.Fatalf("Close: %v", err)
162 }
163 close(stop)
164
165 select {
166 case err := <-loopDone:
167 // Clean teardown surfaces as net.ErrClosed (propagated like the other
168 // platforms); the caller absorbs it via its closed flag.
169 if err != nil && !errors.Is(err, net.ErrClosed) {
170 t.Fatalf("%s: ListenOut returned unexpected error on teardown: %v", name, err)
171 }
172 t.Logf("%s: closed in %v (received %d packets)", name, time.Since(start), received.Load())
173 case <-time.After(3 * time.Second):
174 buf := make([]byte, 1<<20)
175 n := runtime.Stack(buf, true)
176 t.Fatalf("%s: HANG, ListenOut did not return within 3s of Close\n%s", name, buf[:n])
177 }
178 <-trafficDone
179 }