-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection_pool.go
368 lines (338 loc) · 7.37 KB
/
connection_pool.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
package memcached
import (
"bufio"
"context"
"log"
"net"
"strings"
"sync"
"time"
"github.com/pkg/errors"
)
type connectionPool struct {
*Server
cl *Client
mu sync.RWMutex
freeConns []*conn
numOpen int
openerCh chan struct{}
connRequests map[uint64]chan connRequest
nextRequest uint64
cleanerCh chan struct{}
connectErrorCount int64
connectErrorPeriod time.Time
closed bool
}
type connRequest struct {
*conn
err error
}
func (cp *connectionPool) maybeOpenNewConnections() {
if cp.closed {
return
}
numRequests := len(cp.connRequests)
if cp.cl.maxOpen > 0 {
numCanOpen := cp.cl.maxOpen - cp.numOpen
if numRequests > numCanOpen {
numRequests = numCanOpen
}
}
for numRequests > 0 {
cp.numOpen++
numRequests--
cp.openerCh <- struct{}{}
}
}
func (cp *connectionPool) opener() {
for range cp.openerCh {
cp.openNewConnection()
}
}
func (cp *connectionPool) openNewConnection() {
var closed bool
cp.mu.RLock()
closed = cp.closed
cp.mu.RUnlock()
if closed {
cp.mu.Lock()
cp.numOpen--
cp.mu.Unlock()
return
}
c, err := cp.newConn()
if err != nil {
cp.mu.Lock()
defer cp.mu.Unlock()
cp.numOpen--
cp.maybeOpenNewConnections()
return
}
if err = cp.putConn(c, nil); err != nil {
cp.cl.logf("Failed putConn: %v", err)
}
}
func (cp *connectionPool) newConn() (*conn, error) {
network := "tcp"
if strings.Contains(cp.Server.Host, "/") {
network = "unix"
}
c := new(conn)
c.cl = cp.cl
c.createdAt = time.Now()
var err error
c.Conn, err = net.DialTimeout(network, cp.getAddr(), cp.cl.connectTimeout)
if err != nil {
return nil, errors.Wrapf(ErrConnect, "Failed DialTimeout: %v", err)
}
if tcpconn, ok := c.Conn.(*net.TCPConn); ok {
if err = tcpconn.SetKeepAlive(true); err != nil {
return nil, errors.Wrap(err, "Failed SetKeepAlive")
}
if err = tcpconn.SetKeepAlivePeriod(c.cl.keepAlivePeriod); err != nil {
return nil, errors.Wrap(err, "Failed SetKeepAlivePeriod")
}
}
c.buffered = bufio.ReadWriter{
Reader: bufio.NewReader(c),
Writer: bufio.NewWriter(c),
}
c.isAlive = true
return c, nil
}
func (cp *connectionPool) putConn(c *conn, err error) error {
cp.mu.Lock()
if needCloseConn(err) ||
!cp.putConnLocked(c, nil) {
cp.numOpen--
cp.mu.Unlock()
c.close()
return err
}
cp.mu.Unlock()
return err
}
func (cp *connectionPool) circuitBreaker(err error) bool {
if !cp.cl.failover {
return false
}
if errors.Cause(err) != ErrConnect {
return false
}
cp.mu.Lock()
defer cp.mu.Unlock()
now := time.Now()
if cp.connectErrorPeriod.After(now) {
cp.connectErrorPeriod = now.Add(cp.cl.tryReconnectPeriod)
cp.connectErrorCount = 0
}
cp.connectErrorCount++
return cp.connectErrorCount >= cp.cl.maxErrorCount
}
func (cp *connectionPool) putConnLocked(c *conn, err error) bool {
if cp.closed {
return false
}
if cp.cl.maxOpen > 0 && cp.cl.maxOpen < cp.numOpen {
return false
}
if len(cp.connRequests) > 0 {
var req chan connRequest
var reqKey uint64
for reqKey, req = range cp.connRequests {
break
}
delete(cp.connRequests, reqKey)
req <- connRequest{
conn: c,
err: err,
}
} else {
cp.freeConns = append(cp.freeConns, c)
cp.startCleanerLocked()
}
return true
}
func (cp *connectionPool) conn(ctx context.Context) (*conn, error) {
cn, err := cp._conn(ctx, true)
if err == nil {
return cn, nil
}
if errors.Cause(err) == ErrBadConn {
return cp._conn(ctx, false)
}
return cn, err
}
func (cp *connectionPool) _conn(ctx context.Context, useFreeConn bool) (*conn, error) {
cp.mu.Lock()
if cp.closed {
cp.mu.Unlock()
return nil, ErrMemcachedClosed
}
// Check if the context is expired.
select {
default:
case <-ctx.Done():
cp.mu.Unlock()
return nil, errors.Wrap(ctx.Err(), "the context is expired")
}
lifetime := cp.cl.maxLifetime
var c *conn
numFree := len(cp.freeConns)
if useFreeConn && numFree > 0 {
c = cp.freeConns[0]
copy(cp.freeConns, cp.freeConns[1:])
cp.freeConns = cp.freeConns[:numFree-1]
cp.mu.Unlock()
if c.expired(lifetime) {
cp.mu.Lock()
cp.numOpen--
cp.mu.Unlock()
c.close()
return nil, ErrBadConn
}
// c.tryReconnect()
err := c.reset()
return c, errors.Wrap(err, "Failed reset")
}
if cp.cl.maxOpen > 0 && cp.cl.maxOpen <= cp.numOpen {
req := make(chan connRequest, 1)
reqKey := cp.nextRequest
cp.nextRequest++
cp.connRequests[reqKey] = req
cp.mu.Unlock()
select {
// timeout
case <-ctx.Done():
// Remove the connection request and ensure no value has been sent
// on it after removing.
cp.mu.Lock()
delete(cp.connRequests, reqKey)
cp.mu.Unlock()
select {
case ret, ok := <-req:
if ok {
if err := cp.putConn(ret.conn, ret.err); err != nil {
return c, errors.Wrap(err, "Failed putConn")
}
}
default:
}
return nil, errors.Wrap(ctx.Err(), "Deadline of connRequests exceeded")
case ret, ok := <-req:
if !ok {
return nil, ErrMemcachedClosed
}
if ret.err != nil {
return ret.conn, errors.Wrap(ret.err, "Response has an error")
}
// ret.conn.tryReconnect()
err := ret.conn.reset()
return ret.conn, errors.Wrap(err, "Failed reset in response")
}
}
cp.numOpen++
cp.mu.Unlock()
newCn, err := cp.newConn()
if err != nil {
cp.mu.Lock()
defer cp.mu.Unlock()
cp.numOpen--
cp.maybeOpenNewConnections()
return nil, errors.Wrap(err, "Failed newConn")
}
err = newCn.reset()
return newCn, errors.Wrap(err, "Failed reset of new conn")
}
func (cp *connectionPool) needStartCleaner() bool {
return cp.cl.maxLifetime > 0 &&
cp.numOpen > 0 &&
cp.cleanerCh == nil
}
// startCleanerLocked starts connectionCleaner if needed.
func (cp *connectionPool) startCleanerLocked() {
if cp.needStartCleaner() {
cp.cleanerCh = make(chan struct{}, 1)
go cp.connectionCleaner()
}
}
func (cp *connectionPool) connectionCleaner() {
const minInterval = time.Second
d := cp.cl.maxLifetime
if d < minInterval {
d = minInterval
}
t := time.NewTimer(d)
for {
select {
case <-t.C:
case <-cp.cleanerCh: // maxLifetime was changed or memcached was closed.
}
cp.mu.Lock()
d = cp.cl.maxLifetime
if cp.closed || cp.numOpen == 0 || d <= 0 {
cp.cleanerCh = nil
cp.mu.Unlock()
return
}
expiredSince := time.Now().Add(-d)
var closing []*conn
for i := 0; i < len(cp.freeConns); i++ {
c := cp.freeConns[i]
if c.createdAt.Before(expiredSince) {
closing = append(closing, c)
last := len(cp.freeConns) - 1
cp.freeConns[i] = cp.freeConns[last]
cp.freeConns[last] = nil
cp.freeConns = cp.freeConns[:last]
cp.numOpen--
i--
}
}
cp.mu.Unlock()
for _, c := range closing {
if err := c.close(); err != nil {
log.Println("Failed conn.close", err)
}
}
if d < minInterval {
d = minInterval
}
t.Reset(d)
}
}
func (cp *connectionPool) close() error {
cp.mu.Lock()
if cp.closed {
cp.mu.Unlock()
return nil
}
close(cp.openerCh)
if cp.cleanerCh != nil {
close(cp.cleanerCh)
}
for _, cr := range cp.connRequests {
close(cr)
}
cp.closed = true
cp.mu.Unlock()
var err error
for _, c := range cp.freeConns {
if err1 := c.close(); err1 != nil {
err = err1
}
}
cp.mu.Lock()
cp.freeConns = nil
cp.numOpen = 0
cp.mu.Unlock()
return err
}
func needCloseConn(err error) bool {
if err == nil {
return false
}
errcause := errors.Cause(err)
return errcause == ErrBadConn ||
errcause == ErrServer
}