-
Notifications
You must be signed in to change notification settings - Fork 470
/
netpoll_unix_test.go
611 lines (554 loc) · 15.6 KB
/
netpoll_unix_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
// Copyright 2022 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !windows
// +build !windows
package netpoll
import (
"context"
"errors"
"fmt"
"os"
"runtime"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
)
func MustNil(t *testing.T, val interface{}) {
t.Helper()
Assert(t, val == nil, val)
if val != nil {
t.Fatal("assertion nil failed, val=", val)
}
}
func MustTrue(t *testing.T, cond bool) {
t.Helper()
if !cond {
t.Fatal("assertion true failed.")
}
}
func Equal(t *testing.T, got, expect interface{}) {
t.Helper()
if got != expect {
t.Fatalf("assertion equal failed, got=[%v], expect=[%v]", got, expect)
}
}
func Assert(t *testing.T, cond bool, val ...interface{}) {
t.Helper()
if !cond {
if len(val) > 0 {
val = append([]interface{}{"assertion failed:"}, val...)
t.Fatal(val...)
} else {
t.Fatal("assertion failed")
}
}
}
var testPort int32 = 10000
// getTestAddress return a unique port for every tests, so all tests will not share a same listener
func getTestAddress() string {
return fmt.Sprintf("127.0.0.1:%d", atomic.AddInt32(&testPort, 1))
}
func TestEqual(t *testing.T) {
var err error
MustNil(t, err)
MustTrue(t, err == nil)
Equal(t, err, nil)
Assert(t, err == nil, err)
}
func TestOnConnect(t *testing.T) {
network, address := "tcp", getTestAddress()
req, resp := "ping", "pong"
loop := newTestEventLoop(network, address,
func(ctx context.Context, connection Connection) error {
return nil
},
WithOnConnect(func(ctx context.Context, conn Connection) context.Context {
for {
input, err := conn.Reader().Next(len(req))
if errors.Is(err, ErrEOF) || errors.Is(err, ErrConnClosed) {
return ctx
}
MustNil(t, err)
Equal(t, string(input), req)
_, err = conn.Writer().WriteString(resp)
MustNil(t, err)
err = conn.Writer().Flush()
MustNil(t, err)
}
}),
)
conn, err := DialConnection(network, address, time.Second)
MustNil(t, err)
for i := 0; i < 1024; i++ {
_, err = conn.Writer().WriteString(req)
MustNil(t, err)
err = conn.Writer().Flush()
MustNil(t, err)
input, err := conn.Reader().Next(len(resp))
MustNil(t, err)
Equal(t, string(input), resp)
}
err = conn.Close()
MustNil(t, err)
err = loop.Shutdown(context.Background())
MustNil(t, err)
}
func TestOnConnectWrite(t *testing.T) {
network, address := "tcp", getTestAddress()
loop := newTestEventLoop(network, address,
func(ctx context.Context, connection Connection) error {
return nil
},
WithOnConnect(func(ctx context.Context, connection Connection) context.Context {
_, err := connection.Write([]byte("hello"))
MustNil(t, err)
return ctx
}),
)
conn, err := DialConnection(network, address, time.Second)
MustNil(t, err)
s, err := conn.Reader().ReadString(5)
MustNil(t, err)
MustTrue(t, s == "hello")
err = loop.Shutdown(context.Background())
MustNil(t, err)
}
func TestOnDisconnect(t *testing.T) {
type ctxKey struct{}
network, address := "tcp", getTestAddress()
var canceled, closed int32
var conns int32 = 100
req := "ping"
loop := newTestEventLoop(network, address,
func(ctx context.Context, connection Connection) error {
cancelFunc, _ := ctx.Value(ctxKey{}).(context.CancelFunc)
MustTrue(t, cancelFunc != nil)
Assert(t, ctx.Done() != nil)
buf, err := connection.Reader().Next(4) // should consumed all data
MustNil(t, err)
Equal(t, string(buf), req)
select {
case <-ctx.Done():
atomic.AddInt32(&canceled, 1)
case <-time.After(time.Second):
}
return nil
},
WithOnConnect(func(ctx context.Context, conn Connection) context.Context {
conn.AddCloseCallback(func(connection Connection) error {
atomic.AddInt32(&closed, 1)
return nil
})
ctx, cancel := context.WithCancel(ctx)
return context.WithValue(ctx, ctxKey{}, cancel)
}),
WithOnDisconnect(func(ctx context.Context, conn Connection) {
cancelFunc, _ := ctx.Value(ctxKey{}).(context.CancelFunc)
MustTrue(t, cancelFunc != nil)
cancelFunc()
}),
)
for i := int32(0); i < conns; i++ {
conn, err := DialConnection(network, address, time.Second)
MustNil(t, err)
_, err = conn.Writer().WriteString(req)
MustNil(t, err)
err = conn.Writer().Flush()
MustNil(t, err)
err = conn.Close()
MustNil(t, err)
}
for atomic.LoadInt32(&closed) < conns {
t.Logf("closed: %d, canceled: %d", atomic.LoadInt32(&closed), atomic.LoadInt32(&canceled))
runtime.Gosched()
}
Equal(t, atomic.LoadInt32(&closed), conns)
Equal(t, atomic.LoadInt32(&canceled), conns)
err := loop.Shutdown(context.Background())
MustNil(t, err)
}
func TestOnDisconnectWhenOnConnect(t *testing.T) {
type ctxPrepareKey struct{}
type ctxConnectKey struct{}
network, address := "tcp", getTestAddress()
var conns int32 = 100
var wg sync.WaitGroup
wg.Add(int(conns) * 3)
loop := newTestEventLoop(network, address,
func(ctx context.Context, connection Connection) error {
_, _ = connection.Reader().Next(connection.Reader().Len())
return nil
},
WithOnPrepare(func(connection Connection) context.Context {
defer wg.Done()
var counter int32
return context.WithValue(context.Background(), ctxPrepareKey{}, &counter)
}),
WithOnConnect(func(ctx context.Context, conn Connection) context.Context {
defer wg.Done()
t.Logf("OnConnect: %v", conn.RemoteAddr())
time.Sleep(time.Millisecond * 10) // wait for closed called
counter := ctx.Value(ctxPrepareKey{}).(*int32)
ok := atomic.CompareAndSwapInt32(counter, 0, 1)
Assert(t, ok)
return context.WithValue(ctx, ctxConnectKey{}, "123")
}),
WithOnDisconnect(func(ctx context.Context, conn Connection) {
defer wg.Done()
t.Logf("OnDisconnect: %v", conn.RemoteAddr())
counter, _ := ctx.Value(ctxPrepareKey{}).(*int32)
ok := atomic.CompareAndSwapInt32(counter, 1, 2)
Assert(t, ok)
v := ctx.Value(ctxConnectKey{}).(string)
Equal(t, v, "123")
}),
)
for i := int32(0); i < conns; i++ {
conn, err := DialConnection(network, address, time.Second)
MustNil(t, err)
err = conn.Close()
t.Logf("Close: %v", conn.LocalAddr())
MustNil(t, err)
}
wg.Wait()
err := loop.Shutdown(context.Background())
MustNil(t, err)
}
func TestGracefulExit(t *testing.T) {
network, address := "tcp", getTestAddress()
// exit without processing connections
eventLoop1 := newTestEventLoop(network, address,
func(ctx context.Context, connection Connection) error {
return nil
})
_, err := DialConnection(network, address, time.Second)
MustNil(t, err)
err = eventLoop1.Shutdown(context.Background())
MustNil(t, err)
// exit with processing connections
trigger := make(chan struct{})
eventLoop2 := newTestEventLoop(network, address,
func(ctx context.Context, connection Connection) error {
<-trigger
return nil
})
for i := 0; i < 10; i++ {
// connect success
conn, err := DialConnection(network, address, time.Second)
MustNil(t, err)
_, err = conn.Write(make([]byte, 16))
MustNil(t, err)
}
// shutdown timeout
ctx2, cancel2 := context.WithTimeout(context.Background(), time.Millisecond*100)
defer cancel2()
err = eventLoop2.Shutdown(ctx2)
MustTrue(t, err != nil)
Equal(t, err.Error(), ctx2.Err().Error())
// shutdown success
close(trigger)
err = eventLoop2.Shutdown(ctx2)
MustTrue(t, err == nil)
// exit with read connections
size := 16
eventLoop3 := newTestEventLoop(network, address,
func(ctx context.Context, connection Connection) error {
_, err := connection.Reader().Next(size)
MustNil(t, err)
return nil
})
for i := 0; i < 10; i++ {
conn, err := DialConnection(network, address, time.Second)
MustNil(t, err)
if i%2 == 0 {
_, err := conn.Write(make([]byte, size))
MustNil(t, err)
}
}
ctx3, cancel3 := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel3()
err = eventLoop3.Shutdown(ctx3)
MustNil(t, err)
}
func TestCloseCallbackWhenOnRequest(t *testing.T) {
network, address := "tcp", getTestAddress()
requested, closed := make(chan struct{}), make(chan struct{})
loop := newTestEventLoop(network, address,
func(ctx context.Context, connection Connection) error {
_, err := connection.Reader().Next(connection.Reader().Len())
MustNil(t, err)
err = connection.AddCloseCallback(func(connection Connection) error {
closed <- struct{}{}
return nil
})
MustNil(t, err)
requested <- struct{}{}
return nil
},
)
conn, err := DialConnection(network, address, time.Second)
MustNil(t, err)
_, err = conn.Writer().WriteString("hello")
MustNil(t, err)
err = conn.Writer().Flush()
MustNil(t, err)
<-requested
err = conn.Close()
MustNil(t, err)
<-closed
err = loop.Shutdown(context.Background())
MustNil(t, err)
}
func TestCloseCallbackWhenOnConnect(t *testing.T) {
network, address := "tcp", getTestAddress()
connected, closed := make(chan struct{}), make(chan struct{})
loop := newTestEventLoop(network, address,
nil,
WithOnConnect(func(ctx context.Context, connection Connection) context.Context {
err := connection.AddCloseCallback(func(connection Connection) error {
closed <- struct{}{}
return nil
})
MustNil(t, err)
connected <- struct{}{}
return ctx
}),
)
conn, err := DialConnection(network, address, time.Second)
MustNil(t, err)
err = conn.Close()
MustNil(t, err)
<-connected
<-closed
err = loop.Shutdown(context.Background())
MustNil(t, err)
}
func TestCloseConnWhenOnConnect(t *testing.T) {
network, address := "tcp", "localhost:8888"
conns := 10
var wg sync.WaitGroup
wg.Add(conns)
loop := newTestEventLoop(network, address,
nil,
WithOnConnect(func(ctx context.Context, connection Connection) context.Context {
defer wg.Done()
err := connection.Close()
MustNil(t, err)
return ctx
}),
)
for i := 0; i < conns; i++ {
wg.Add(1)
go func() {
defer wg.Done()
conn, err := DialConnection(network, address, time.Second)
if err != nil {
return
}
_, err = conn.Reader().Next(1)
Assert(t, errors.Is(err, ErrEOF))
err = conn.Close()
MustNil(t, err)
}()
}
wg.Wait()
err := loop.Shutdown(context.Background())
MustNil(t, err)
}
func TestServerReadAndClose(t *testing.T) {
network, address := "tcp", getTestAddress()
sendMsg := []byte("hello")
loop := newTestEventLoop(network, address,
func(ctx context.Context, connection Connection) error {
_, err := connection.Reader().Next(len(sendMsg))
MustNil(t, err)
err = connection.Close()
MustNil(t, err)
return nil
},
)
conn, err := DialConnection(network, address, time.Second)
MustNil(t, err)
_, err = conn.Writer().WriteBinary(sendMsg)
MustNil(t, err)
err = conn.Writer().Flush()
MustNil(t, err)
for conn.IsActive() {
runtime.Gosched() // wait for poller close connection
}
_, err = conn.Writer().WriteBinary(sendMsg)
MustNil(t, err)
err = conn.Writer().Flush()
Assert(t, errors.Is(err, ErrConnClosed), err)
err = loop.Shutdown(context.Background())
MustNil(t, err)
}
func TestServerPanicAndClose(t *testing.T) {
network, address := "tcp", getTestAddress()
sendMsg := []byte("hello")
var paniced int32
loop := newTestEventLoop(network, address,
func(ctx context.Context, connection Connection) error {
_, err := connection.Reader().Next(len(sendMsg))
MustNil(t, err)
atomic.StoreInt32(&paniced, 1)
panic("test")
},
)
conn, err := DialConnection(network, address, time.Second)
MustNil(t, err)
_, err = conn.Writer().WriteBinary(sendMsg)
MustNil(t, err)
err = conn.Writer().Flush()
MustNil(t, err)
for atomic.LoadInt32(&paniced) == 0 {
runtime.Gosched() // wait for poller close connection
}
for conn.IsActive() {
runtime.Gosched() // wait for poller close connection
}
err = loop.Shutdown(context.Background())
MustNil(t, err)
}
func TestClientWriteAndClose(t *testing.T) {
var (
network, address = "tcp", getTestAddress()
connnum = 10
packetsize, packetnum = 1000 * 5, 1
recvbytes int32 = 0
)
loop := newTestEventLoop(network, address,
func(ctx context.Context, connection Connection) error {
buf, err := connection.Reader().Next(connection.Reader().Len())
if errors.Is(err, ErrConnClosed) {
return err
}
MustNil(t, err)
atomic.AddInt32(&recvbytes, int32(len(buf)))
return nil
},
)
var wg sync.WaitGroup
for i := 0; i < connnum; i++ {
wg.Add(1)
go func() {
defer wg.Done()
conn, err := DialConnection(network, address, time.Second)
MustNil(t, err)
sendMsg := make([]byte, packetsize)
for j := 0; j < packetnum; j++ {
_, err = conn.Write(sendMsg)
MustNil(t, err)
}
err = conn.Close()
MustNil(t, err)
}()
}
wg.Wait()
exceptbytes := int32(packetsize * packetnum * connnum)
for atomic.LoadInt32(&recvbytes) != exceptbytes {
t.Logf("left %d bytes not received", exceptbytes-atomic.LoadInt32(&recvbytes))
runtime.Gosched()
}
err := loop.Shutdown(context.Background())
MustNil(t, err)
}
func TestServerAcceptWhenTooManyOpenFiles(t *testing.T) {
if os.Getenv("N_LOCAL") == "" {
t.Skip("Only test for debug purpose")
return
}
var originalRlimit syscall.Rlimit
err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &originalRlimit)
MustNil(t, err)
t.Logf("Original RLimit: %v", originalRlimit)
rlimit := syscall.Rlimit{Cur: 32, Max: originalRlimit.Max}
err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlimit)
MustNil(t, err)
err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit)
MustNil(t, err)
t.Logf("New RLimit: %v", rlimit)
defer func() { // reset
err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &originalRlimit)
MustNil(t, err)
}()
network, address := "tcp", getTestAddress()
var connected int32
loop := newTestEventLoop(network, address,
func(ctx context.Context, connection Connection) error {
buf, err := connection.Reader().Next(connection.Reader().Len())
connection.Writer().WriteBinary(buf)
connection.Writer().Flush()
return err
},
WithOnConnect(func(ctx context.Context, connection Connection) context.Context {
atomic.AddInt32(&connected, 1)
t.Logf("Conn[%s] accepted", connection.RemoteAddr())
return ctx
}),
WithOnDisconnect(func(ctx context.Context, connection Connection) {
t.Logf("Conn[%s] disconnected", connection.RemoteAddr())
}),
)
time.Sleep(time.Millisecond * 10)
// out of fds
files := make([]*os.File, 0)
for {
f, err := os.Open("/dev/null")
if err != nil {
Assert(t, isOutOfFdErr(errors.Unwrap(err)), err)
break
}
files = append(files, f)
}
go func() {
time.Sleep(time.Second * 10)
t.Logf("close all files")
for _, f := range files {
f.Close()
}
}()
// we should use telnet manually
connections := 1
for atomic.LoadInt32(&connected) < int32(connections) {
t.Logf("connected=%d", atomic.LoadInt32(&connected))
time.Sleep(time.Second)
}
time.Sleep(time.Second * 10)
err = loop.Shutdown(context.Background())
MustNil(t, err)
}
func createTestListener(network, address string) (Listener, error) {
for {
ln, err := CreateListener(network, address)
if err == nil {
return ln, nil
}
time.Sleep(time.Millisecond * 100)
}
}
func newTestEventLoop(network, address string, onRequest OnRequest, opts ...Option) EventLoop {
ln, err := createTestListener(network, address)
if err != nil {
panic(err)
}
elp, err := NewEventLoop(onRequest, opts...)
if err != nil {
panic(err)
}
go elp.Serve(ln)
return elp
}