forked from mongodb/mongo-go-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
464 lines (396 loc) · 12.4 KB
/
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
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
// Copyright (C) MongoDB, Inc. 2017-present.
//
// 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
package topology
import (
"context"
"sync"
"sync/atomic"
"time"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/x/mongo/driver/address"
)
// ErrPoolConnected is returned from an attempt to connect an already connected pool
var ErrPoolConnected = PoolError("attempted to Connect to an already connected pool")
// ErrPoolDisconnected is returned from an attempt to Close an already disconnected
// or disconnecting pool.
var ErrPoolDisconnected = PoolError("attempted to check out a connection from closed connection pool")
// ErrConnectionClosed is returned from an attempt to use an already closed connection.
var ErrConnectionClosed = ConnectionError{ConnectionID: "<closed>", message: "connection is closed"}
// ErrWrongPool is return when a connection is returned to a pool it doesn't belong to.
var ErrWrongPool = PoolError("connection does not belong to this pool")
// ErrWaitQueueTimeout is returned when the request to get a connection from the pool timesout when on the wait queue
var ErrWaitQueueTimeout = PoolError("timed out while checking out a connection from connection pool")
// PoolError is an error returned from a Pool method.
type PoolError string
// maintainInterval is the interval at which the background routine to close stale connections will be run.
var maintainInterval = time.Minute
func (pe PoolError) Error() string { return string(pe) }
// poolConfig contains all aspects of the pool that can be configured
type poolConfig struct {
Address address.Address
MinPoolSize uint64
MaxPoolSize uint64 // MaxPoolSize is not used because handling the max number of connections in the pool is handled in server. This is only used for command monitoring
MaxIdleTime time.Duration
PoolMonitor *event.PoolMonitor
}
// checkOutResult is all the values that can be returned from a checkOut
type checkOutResult struct {
c *connection
err error
reason string
}
// pool is a wrapper of resource pool that follows the CMAP spec for connection pools
type pool struct {
address address.Address
opts []ConnectionOption
conns *resourcePool // pool for non-checked out connections
generation uint64 // must be accessed using atomic package
monitor *event.PoolMonitor
connected int32 // Must be accessed using the sync/atomic package.
nextid uint64
opened map[uint64]*connection // opened holds all of the currently open connections.
sync.Mutex
}
// connectionExpiredFunc checks if a given connection is stale and should be removed from the resource pool
func connectionExpiredFunc(v interface{}) bool {
if v == nil {
return true
}
c, ok := v.(*connection)
if !ok {
return true
}
var reason string
disconnected := atomic.LoadInt32(&c.pool.connected) != connected
if disconnected {
reason = event.ReasonPoolClosed
}
idle := c.expired()
if !disconnected && idle {
reason = event.ReasonIdle
}
stale := c.pool.stale(c)
if !disconnected && !idle && stale {
reason = event.ReasonStale
}
res := disconnected || stale || idle
if res && c.pool.monitor != nil {
c.pool.monitor.Event(&event.PoolEvent{
Type: event.ConnectionClosed,
Address: c.pool.address.String(),
ConnectionID: c.poolID,
Reason: reason,
})
}
return res
}
// connectionCloseFunc closes a given connection. If ctx is nil, the closing will occur in the background
func connectionCloseFunc(v interface{}) {
c, ok := v.(*connection)
if !ok || v == nil {
return
}
go func() { _ = c.pool.closeConnection(c) }()
}
// connectionInitFunc returns an init function for the resource pool that will make new connections for this pool
func (p *pool) connectionInitFunc() interface{} {
c, _, err := p.makeNewConnection(context.Background())
if err != nil {
return nil
}
go c.connect(context.Background())
return c
}
// newPool creates a new pool that will hold size number of idle connections. It will use the
// provided options when creating connections.
func newPool(config poolConfig, connOpts ...ConnectionOption) (*pool, error) {
opts := connOpts
if config.MaxIdleTime != time.Duration(0) {
opts = append(opts, WithIdleTimeout(func(_ time.Duration) time.Duration { return config.MaxIdleTime }))
}
pool := &pool{
address: config.Address,
monitor: config.PoolMonitor,
connected: disconnected,
opened: make(map[uint64]*connection),
opts: opts,
}
// we do not pass in config.MaxPoolSize because we manage the max size at this level rather than the resource pool level
rpc := resourcePoolConfig{
MinSize: config.MinPoolSize,
MaintainInterval: maintainInterval,
ExpiredFn: connectionExpiredFunc,
CloseFn: connectionCloseFunc,
InitFn: pool.connectionInitFunc,
}
if pool.monitor != nil {
pool.monitor.Event(&event.PoolEvent{
Type: event.PoolCreated,
PoolOptions: &event.MonitorPoolOptions{
MaxPoolSize: config.MaxPoolSize,
MinPoolSize: rpc.MinSize,
WaitQueueTimeoutMS: uint64(config.MaxIdleTime) / uint64(time.Millisecond),
},
Address: pool.address.String(),
})
}
rp, err := newResourcePool(rpc)
if err != nil {
return nil, err
}
pool.conns = rp
return pool, nil
}
// drain drains the pool by increasing the generation ID.
func (p *pool) drain() { atomic.AddUint64(&p.generation, 1) }
// stale checks if a given connection's generation is below the generation of the pool
func (p *pool) stale(c *connection) bool {
return c == nil || c.generation < atomic.LoadUint64(&p.generation)
}
// connect puts the pool into the connected state, allowing it to be used and will allow items to begin being processed from the wait queue
func (p *pool) connect() error {
if !atomic.CompareAndSwapInt32(&p.connected, disconnected, connected) {
return ErrPoolConnected
}
p.conns.initialize()
return nil
}
// disconnect disconnects the pool and closes all connections including those both in and out of the pool
func (p *pool) disconnect(ctx context.Context) error {
if !atomic.CompareAndSwapInt32(&p.connected, connected, disconnecting) {
return ErrPoolDisconnected
}
if ctx == nil {
ctx = context.Background()
}
p.conns.Close()
atomic.AddUint64(&p.generation, 1)
var err error
if dl, ok := ctx.Deadline(); ok {
// If we have a deadline then we interpret it as a request to gracefully shutdown. We wait
// until either all the connections have landed back in the pool (and have been closed) or
// until the timer is done.
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
timer := time.NewTimer(time.Now().Sub(dl))
defer timer.Stop()
for {
select {
case <-timer.C:
case <-ctx.Done():
case <-ticker.C: // Can we replace this with an actual signal channel? We will know when p.inflight hits zero from the close method.
p.Lock()
if len(p.opened) > 0 {
p.Unlock()
continue
}
p.Unlock()
}
break
}
}
// We copy the remaining connections into a slice, then iterate it to close them. This allows us
// to use a single function to actually clean up and close connections at the expense of a
// double iteration in the worse case.
p.Lock()
toClose := make([]*connection, 0, len(p.opened))
for _, pc := range p.opened {
toClose = append(toClose, pc)
}
p.Unlock()
for _, pc := range toClose {
if p.monitor != nil {
p.monitor.Event(&event.PoolEvent{
Type: event.ConnectionClosed,
Address: p.address.String(),
ConnectionID: pc.poolID,
Reason: event.ReasonPoolClosed,
})
}
_ = p.closeConnection(pc) // We don't care about errors while closing the connection.
}
atomic.StoreInt32(&p.connected, disconnected)
if p.monitor != nil {
p.monitor.Event(&event.PoolEvent{
Type: event.PoolClosedEvent,
Address: p.address.String(),
})
}
return err
}
// requires that p be locked
func (p *pool) makeNewConnection(ctx context.Context) (*connection, string, error) {
c, err := newConnection(ctx, p.address, p.opts...)
if err != nil {
return nil, event.ReasonConnectionErrored, err
}
c.pool = p
c.poolID = atomic.AddUint64(&p.nextid, 1)
c.generation = atomic.LoadUint64(&p.generation)
if p.monitor != nil {
p.monitor.Event(&event.PoolEvent{
Type: event.ConnectionCreated,
Address: p.address.String(),
ConnectionID: c.poolID,
})
}
if atomic.LoadInt32(&p.connected) != connected {
if p.monitor != nil {
p.monitor.Event(&event.PoolEvent{
Type: event.ConnectionClosed,
Address: p.address.String(),
ConnectionID: c.poolID,
Reason: event.ReasonPoolClosed,
})
}
_ = p.closeConnection(c) // The pool is disconnected or disconnecting, ignore the error from closing the connection.
return nil, event.ReasonPoolClosed, ErrPoolDisconnected
}
p.Lock()
p.opened[c.poolID] = c
p.Unlock()
return c, "", nil
}
// Checkout returns a connection from the pool
func (p *pool) get(ctx context.Context) (*connection, error) {
if ctx == nil {
ctx = context.Background()
}
if atomic.LoadInt32(&p.connected) != connected {
if p.monitor != nil {
p.monitor.Event(&event.PoolEvent{
Type: event.GetFailed,
Address: p.address.String(),
Reason: event.ReasonPoolClosed,
})
}
return nil, ErrPoolDisconnected
}
connVal := p.conns.Get()
if c, ok := connVal.(*connection); ok && connVal != nil {
// call connect if not connected
if atomic.LoadInt32(&c.connected) == initialized {
c.connect(ctx)
}
err := c.connectWait()
if err != nil {
if p.monitor != nil {
p.monitor.Event(&event.PoolEvent{
Type: event.GetFailed,
Address: p.address.String(),
Reason: event.ReasonConnectionErrored,
})
}
return nil, err
}
if p.monitor != nil {
p.monitor.Event(&event.PoolEvent{
Type: event.GetSucceeded,
Address: p.address.String(),
ConnectionID: c.poolID,
})
}
return c, nil
}
select {
case <-ctx.Done():
if p.monitor != nil {
p.monitor.Event(&event.PoolEvent{
Type: event.GetFailed,
Address: p.address.String(),
Reason: event.ReasonTimedOut,
})
}
return nil, ctx.Err()
default:
c, reason, err := p.makeNewConnection(ctx)
if err != nil {
if p.monitor != nil {
p.monitor.Event(&event.PoolEvent{
Type: event.GetFailed,
Address: p.address.String(),
Reason: reason,
})
}
return nil, err
}
c.connect(ctx)
// wait for conn to be connected
err = c.connectWait()
if err != nil {
if p.monitor != nil {
p.monitor.Event(&event.PoolEvent{
Type: event.GetFailed,
Address: p.address.String(),
Reason: reason,
})
}
return nil, err
}
if p.monitor != nil {
p.monitor.Event(&event.PoolEvent{
Type: event.GetSucceeded,
Address: p.address.String(),
ConnectionID: c.poolID,
})
}
return c, nil
}
}
// closeConnection closes a connection, not the pool itself. This method will actually closeConnection the connection,
// making it unusable, to instead return the connection to the pool, use put.
func (p *pool) closeConnection(c *connection) error {
if c.pool != p {
return ErrWrongPool
}
p.Lock()
delete(p.opened, c.poolID)
p.Unlock()
if !atomic.CompareAndSwapInt32(&c.connected, connected, disconnected) {
return nil // We're closing an already closed connection
}
err := c.nc.Close()
if err != nil {
return ConnectionError{ConnectionID: c.id, Wrapped: err, message: "failed to closeConnection net.Conn"}
}
return nil
}
// put returns a connection to this pool. If the pool is connected, the connection is not
// stale, and there is space in the cache, the connection is returned to the cache.
func (p *pool) put(c *connection) error {
if p.monitor != nil {
var cid uint64
var addr string
if c != nil {
cid = c.poolID
addr = c.addr.String()
}
p.monitor.Event(&event.PoolEvent{
Type: event.ConnectionReturned,
ConnectionID: cid,
Address: addr,
})
}
if c == nil {
return nil
}
if c.pool != p {
return ErrWrongPool
}
_ = p.conns.Put(c)
return nil
}
// clear clears the pool by incrementing the generation and then maintaining the pool
func (p *pool) clear() {
if p.monitor != nil {
p.monitor.Event(&event.PoolEvent{
Type: event.PoolCleared,
Address: p.address.String(),
})
}
p.drain()
p.conns.Maintain()
}