forked from panjf2000/gnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheventloop_unix.go
273 lines (245 loc) · 5.95 KB
/
eventloop_unix.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
// Copyright 2019 Andy Pan. All rights reserved.
// Copyright 2018 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// +build linux darwin netbsd freebsd openbsd dragonfly
package gnet
import (
"net"
"sync/atomic"
"time"
"github.com/panjf2000/gnet/internal/netpoll"
"golang.org/x/sys/unix"
)
type eventloop struct {
idx int // loop index in the server loops list
svr *server // server in loop
codec ICodec // codec for TCP
packet []byte // read packet buffer
poller *netpoll.Poller // epoll or kqueue
connCount int32 // number of active connections in event-loop
connections map[int]*conn // loop connections fd -> conn
eventHandler EventHandler // user eventHandler
}
func (el *eventloop) plusConnCount() {
atomic.AddInt32(&el.connCount, 1)
}
func (el *eventloop) minusConnCount() {
atomic.AddInt32(&el.connCount, -1)
}
func (el *eventloop) loadConnCount() int32 {
return atomic.LoadInt32(&el.connCount)
}
func (el *eventloop) closeAllConns() {
// Close loops and all outstanding connections
for _, c := range el.connections {
_ = el.loopCloseConn(c, nil)
}
}
func (el *eventloop) loopRun() {
defer func() {
el.closeAllConns()
if el.idx == 0 && el.svr.opts.Ticker {
close(el.svr.ticktock)
}
el.svr.signalShutdown()
}()
if el.idx == 0 && el.svr.opts.Ticker {
go el.loopTicker()
}
el.svr.logger.Printf("event-loop:%d exits with error: %v\n", el.idx, el.poller.Polling(el.handleEvent))
}
func (el *eventloop) loopAccept(fd int) error {
if fd == el.svr.ln.fd {
if el.svr.ln.pconn != nil {
return el.loopReadUDP(fd)
}
nfd, sa, err := unix.Accept(fd)
if err != nil {
if err == unix.EAGAIN {
return nil
}
return err
}
if err = unix.SetNonblock(nfd, true); err != nil {
return err
}
c := newTCPConn(nfd, el, sa)
if err = el.poller.AddRead(c.fd); err == nil {
el.connections[c.fd] = c
el.plusConnCount()
return el.loopOpen(c)
}
return err
}
return nil
}
func (el *eventloop) loopOpen(c *conn) error {
c.opened = true
c.localAddr = el.svr.ln.lnaddr
c.remoteAddr = netpoll.SockaddrToTCPOrUnixAddr(c.sa)
out, action := el.eventHandler.OnOpened(c)
if el.svr.opts.TCPKeepAlive > 0 {
if _, ok := el.svr.ln.ln.(*net.TCPListener); ok {
_ = netpoll.SetKeepAlive(c.fd, int(el.svr.opts.TCPKeepAlive/time.Second))
}
}
if out != nil {
c.open(out)
}
if !c.outboundBuffer.IsEmpty() {
_ = el.poller.AddWrite(c.fd)
}
return el.handleAction(c, action)
}
func (el *eventloop) loopRead(c *conn) error {
n, err := unix.Read(c.fd, el.packet)
if n == 0 || err != nil {
if err == unix.EAGAIN {
return nil
}
return el.loopCloseConn(c, err)
}
c.buffer = el.packet[:n]
for inFrame, _ := c.read(); inFrame != nil; inFrame, _ = c.read() {
out, action := el.eventHandler.React(inFrame, c)
if out != nil {
outFrame, _ := el.codec.Encode(c, out)
el.eventHandler.PreWrite()
c.write(outFrame)
}
switch action {
case None:
case Close:
return el.loopCloseConn(c, nil)
case Shutdown:
return errServerShutdown
}
if !c.opened {
return nil
}
}
_, _ = c.inboundBuffer.Write(c.buffer)
return nil
}
func (el *eventloop) loopWrite(c *conn) error {
el.eventHandler.PreWrite()
head, tail := c.outboundBuffer.LazyReadAll()
n, err := unix.Write(c.fd, head)
if err != nil {
if err == unix.EAGAIN {
return nil
}
return el.loopCloseConn(c, err)
}
c.outboundBuffer.Shift(n)
if len(head) == n && tail != nil {
n, err = unix.Write(c.fd, tail)
if err != nil {
if err == unix.EAGAIN {
return nil
}
return el.loopCloseConn(c, err)
}
c.outboundBuffer.Shift(n)
}
if c.outboundBuffer.IsEmpty() {
_ = el.poller.ModRead(c.fd)
}
return nil
}
func (el *eventloop) loopCloseConn(c *conn, err error) error {
if !c.outboundBuffer.IsEmpty() && err == nil {
_ = el.loopWrite(c)
}
err0, err1 := el.poller.Delete(c.fd), unix.Close(c.fd)
if err0 == nil && err1 == nil {
delete(el.connections, c.fd)
el.minusConnCount()
switch el.eventHandler.OnClosed(c, err) {
case Shutdown:
return errServerShutdown
}
c.releaseTCP()
} else {
if err0 != nil {
el.svr.logger.Printf("failed to delete fd:%d from poller, error:%v\n", c.fd, err0)
}
if err1 != nil {
el.svr.logger.Printf("failed to close fd:%d, error:%v\n", c.fd, err1)
}
}
return nil
}
func (el *eventloop) loopWake(c *conn) error {
//if co, ok := el.connections[c.fd]; !ok || co != c {
// return nil // ignore stale wakes.
//}
out, action := el.eventHandler.React(nil, c)
if out != nil {
frame, _ := el.codec.Encode(c, out)
c.write(frame)
}
return el.handleAction(c, action)
}
func (el *eventloop) loopTicker() {
var (
delay time.Duration
open bool
err error
)
for {
err = el.poller.Trigger(func() (err error) {
delay, action := el.eventHandler.Tick()
el.svr.ticktock <- delay
switch action {
case None:
case Shutdown:
err = errServerShutdown
}
return
})
if err != nil {
el.svr.logger.Printf("failed to awake poller with error:%v, stopping ticker\n", err)
break
}
if delay, open = <-el.svr.ticktock; open {
time.Sleep(delay)
} else {
break
}
}
}
func (el *eventloop) handleAction(c *conn, action Action) error {
switch action {
case None:
return nil
case Close:
return el.loopCloseConn(c, nil)
case Shutdown:
return errServerShutdown
default:
return nil
}
}
func (el *eventloop) loopReadUDP(fd int) error {
n, sa, err := unix.Recvfrom(fd, el.packet, 0)
if err != nil || n == 0 {
if err != nil && err != unix.EAGAIN {
el.svr.logger.Printf("failed to read UDP packet from fd:%d, error:%v\n", fd, err)
}
return nil
}
c := newUDPConn(fd, el, sa)
out, action := el.eventHandler.React(el.packet[:n], c)
if out != nil {
el.eventHandler.PreWrite()
_ = c.sendTo(out)
}
switch action {
case Shutdown:
return errServerShutdown
}
c.releaseUDP()
return nil
}