-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconn_accept.go
290 lines (246 loc) · 6.07 KB
/
conn_accept.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
// Copyright (C) 2018 Kun Zhong All rights reserved.
// Use of this source code is governed by a Licensed under the Apache License, Version 2.0 (the "License");
package grpcx
import (
"bufio"
"errors"
"fmt"
"net"
"reflect"
"sync"
"time"
xlog "github.com/pigogo/grpcx/grpclog"
"golang.org/x/net/context"
)
var (
errKeyExist = errors.New("key exist")
)
// Conn is a network connection to a given address.
type Conn interface {
withSession(id int64, val Stream) (func(), error)
sessionOf(id int64) Stream
context() context.Context
send(head *PackHeader, m interface{}, maxMsgSize int) error
close()
gracefulClose() <-chan struct{}
}
type connAccept struct {
id int64
ctx context.Context
mux sync.RWMutex
opts options
connMap map[int64]Stream
maxStreamID int64
conn net.Conn
lastAliveTime time.Time
lastPoneTime time.Time
closed bool
tick *time.Ticker
graceDone chan struct{}
onPacket func(head *PackHeader, body []byte, conn Conn) error
onClose func(int64)
}
func newAcceptConn(id int64, opts options, conn net.Conn, onPacket func(head *PackHeader, body []byte, conn Conn) error, onClose func(id int64)) Conn {
aconn := &connAccept{
id: id,
opts: opts,
conn: conn,
connMap: make(map[int64]Stream),
onPacket: onPacket,
onClose: onClose,
}
aconn.ctx = withConnID(context.Background(), id)
go aconn.read()
if opts.keepalivePeriod > 0 {
aconn.tick = time.NewTicker(opts.keepalivePeriod)
go aconn.aliveLook()
}
return aconn
}
func (aconn *connAccept) close() {
aconn.mux.Lock()
defer aconn.mux.Unlock()
if aconn.closed {
return
}
aconn.closed = true
if aconn.opts.connPlugin != nil {
aconn.opts.connPlugin.OnPreDisconnect(aconn)
}
aconn.conn.Close()
if aconn.opts.connPlugin != nil {
aconn.opts.connPlugin.OnPostDisconnect(aconn)
}
aconn.closeGraceDone()
if aconn.tick != nil {
aconn.tick.Stop()
aconn.tick = nil
}
}
func (aconn *connAccept) onclose() {
aconn.mux.Lock()
defer aconn.mux.Unlock()
if aconn.closed {
return
}
aconn.closed = true
aconn.conn.Close()
if aconn.opts.connPlugin != nil {
aconn.opts.connPlugin.OnPostDisconnect(aconn)
}
aconn.onClose(aconn.id)
aconn.closeGraceDone()
if aconn.tick != nil {
aconn.tick.Stop()
aconn.tick = nil
}
}
func (aconn *connAccept) closeGraceDone() {
defer func() {
recover()
}()
close(aconn.graceDone)
}
func (aconn *connAccept) context() context.Context {
return aconn.ctx
}
func (aconn *connAccept) gracefulClose() <-chan struct{} {
aconn.mux.Lock()
defer aconn.mux.Unlock()
if aconn.closed {
graceDone := make(chan struct{})
close(graceDone)
return graceDone
}
if aconn.graceDone != nil {
return aconn.graceDone
}
aconn.graceDone = make(chan struct{})
aconn.notifyGoaway()
return aconn.graceDone
}
func (aconn *connAccept) withSession(id int64, session Stream) (func(), error) {
aconn.mux.Lock()
defer aconn.mux.Unlock()
/*if aconn.draining { todo:
xlog.Info("grpcx: withSession connAccept when connection is draining")
return nil, errDraining
}*/
if _, ok := aconn.connMap[id]; ok {
xlog.Warningf("grpcx: connAccept session is exist:%v", id)
return nil, errKeyExist
}
aconn.connMap[id] = session
return func() {
aconn.mux.Lock()
defer aconn.mux.Unlock()
delete(aconn.connMap, id)
}, nil
}
func (aconn *connAccept) sessionOf(id int64) Stream {
aconn.mux.RLock()
defer aconn.mux.RUnlock()
return aconn.connMap[id]
}
func (aconn *connAccept) send(head *PackHeader, m interface{}, maxMsgSize int) error {
mtype := reflect.TypeOf(m)
cbuf := getBufferFromPool(mtype)
defer func() {
putBufferToPool(mtype, cbuf)
}()
_, err := encodeNetmsg(aconn.opts.codec, aconn.opts.cp, head, m, cbuf, maxMsgSize)
if err != nil {
return err
}
return aconn.write(cbuf.Bytes())
}
func (aconn *connAccept) write(out []byte) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
if err != nil {
aconn.onclose()
}
}()
if aconn.opts.writeTimeout > 0 {
aconn.conn.SetWriteDeadline(time.Now().Add(aconn.opts.writeTimeout))
}
_, err = aconn.conn.Write(out)
return err
}
func (aconn *connAccept) read() (err error) {
defer func() {
if e := recover(); e != nil || err != nil {
xlog.Infof("grpcx: connAccept read exist with recover error:%v error:%v", e, err)
}
aconn.onclose()
}()
var (
reader = bufio.NewReaderSize(aconn.conn, int(aconn.opts.readerWindowSize))
header *PackHeader
msg []byte
)
for {
if aconn.opts.readTimeout > 0 {
aconn.conn.SetReadDeadline(time.Now().Add(aconn.opts.readTimeout))
}
header, msg, err = parseAndRecvMsg(reader, aconn.opts.dc, aconn.opts.maxReceiveMessageSize)
if err != nil {
return err
}
if header.Ptype == PackType_PING {
go aconn.handlePingPacket(header, msg)
continue
}
if aconn.maxStreamID < header.Sessionid {
aconn.maxStreamID = header.Sessionid
} else {
//todo:
}
aconn.onPacket(header, msg, aconn)
}
}
func (aconn *connAccept) notifyGoaway() {
goawayHead := &PackHeader{
Ptype: PackType_GoAway,
Sessionid: aconn.maxStreamID,
}
if aconn.send(goawayHead, nil, defaultSendMessageSize) != nil {
aconn.closeGraceDone()
}
}
func (aconn *connAccept) aliveLook() {
tick := aconn.tick
for {
_, ok := <-tick.C
if !ok {
return
}
aconn.mux.Lock()
//timeout
if time.Since(aconn.lastAliveTime) > aconn.opts.keepalivePeriod {
aconn.mux.Unlock()
xlog.Warningf("grpcx: aliveLook connection timeout:%v", aconn.conn.RemoteAddr())
if aconn.opts.connPlugin != nil {
aconn.opts.connPlugin.OnPreDisconnect(aconn)
}
aconn.onclose()
return
}
aconn.mux.Unlock()
}
}
func (aconn *connAccept) handlePingPacket(head *PackHeader, p []byte) {
aconn.mux.Lock()
defer aconn.mux.Unlock()
head.Ptype = PackType_PONG
aconn.lastAliveTime = time.Now()
if time.Since(aconn.lastPoneTime) < time.Millisecond*300 {
return
}
aconn.lastPoneTime = aconn.lastAliveTime
if e := aconn.send(head, nil, defaultSendMessageSize); e != nil {
xlog.Warningf("grpcx: connAccept.handlePingPacket failed to send Pong: %v", e)
}
}