forked from dropbox/godropbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_connection_pool.go
253 lines (215 loc) · 6.19 KB
/
simple_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
package net2
import (
"net"
"sync"
"sync/atomic"
"time"
"github.com/dropbox/godropbox/errors"
)
type idleConn struct {
conn net.Conn
keepUntil *time.Time
}
// A connection pool implementation where all connections are connected to the
// same (network, address).
type SimpleConnectionPool struct {
network string
address string
options ConnectionOptions
numActive int32 // atomic counter
isLameDuck int32 // atomic bool
mutex sync.Mutex
idleConns []*idleConn // guarded by mutex
}
// This returns a SimpleConnectionPool, where all connections are connected
// to (network, address)
func NewSimpleConnectionPool(options ConnectionOptions) ConnectionPool {
return &SimpleConnectionPool{
options: options,
idleConns: make([]*idleConn, 0, 0),
}
}
// See ConnectionPool for documentation.
func (p *SimpleConnectionPool) NumActive() int32 {
return atomic.LoadInt32(&p.numActive)
}
// This returns the number of alive idle connections. This method is not part
// of ConnectionPool's API. It is used only for testing.
func (p *SimpleConnectionPool) NumIdle() int {
p.mutex.Lock()
defer p.mutex.Unlock()
return len(p.idleConns)
}
// SimpleConnectionPool can only register a single (network, address) entry.
// Register should be call before any Get calls.
func (p *SimpleConnectionPool) Register(network string, address string) error {
if atomic.LoadInt32(&p.isLameDuck) == 1 {
return errors.Newf(
"Cannot register (%s, %s) to lame duck connection pool",
network,
address)
}
if p.network == "" && p.address == "" {
p.network = network
p.address = address
return nil
}
return errors.New("SimpleConnectionPool can only register one address")
}
// SimpleConnectionPool does not support Unregister.
func (p *SimpleConnectionPool) Unregister(
network string,
address string) error {
return errors.New("SimpleConnectionPool does not support Unregister")
}
func (p *SimpleConnectionPool) ListRegistered() []NetworkAddress {
result := make([]NetworkAddress, 0, 1)
if p.network != "" || p.address != "" {
result = append(
result,
NetworkAddress{
Network: p.network,
Address: p.address,
})
}
return result
}
// This gets an active connection from the connection pool. Note that network
// and address arguments are ignored (The connections with point to the
// network/address provided by the first Register call).
func (p *SimpleConnectionPool) Get(
network string,
address string) (ManagedConn, error) {
if p.network == "" && p.address == "" {
return nil, errors.Newf(
"(network, address) is not set for SimpleConnectionPool")
}
if atomic.LoadInt32(&p.isLameDuck) == 1 {
return nil, errors.Newf(
"Lame duck connection pool cannot return connections to (%s, %s)",
network,
address)
}
activeCount := atomic.AddInt32(&p.numActive, 1)
if p.options.MaxActiveConnections > 0 &&
activeCount > p.options.MaxActiveConnections {
atomic.AddInt32(&p.numActive, -1)
return nil, errors.Newf(
"Too many connections to %s",
address)
}
if conn := p.getIdleConn(); conn != nil {
return NewManagedConn(network, address, conn, p), nil
}
var conn net.Conn
var err error
if p.options.Dial == nil {
conn, err = net.Dial(network, address)
} else {
conn, err = p.options.Dial(network, address)
}
if err != nil {
return nil, errors.Wrap(err, "Dial error")
}
return NewManagedConn(network, address, conn, p), nil
}
// See ConnectionPool for documentation.
func (p *SimpleConnectionPool) Release(conn ManagedConn) error {
if pool, ok := conn.Owner().(*SimpleConnectionPool); !ok || pool != p {
return errors.New(
"Connection pool cannot take control of a connection owned " +
"by another connection pool")
}
atomic.AddInt32(&p.numActive, -1)
p.queueIdleConns(conn.RawConn())
return nil
}
// See ConnectionPool for documentation.
func (p *SimpleConnectionPool) Discard(conn ManagedConn) error {
if pool, ok := conn.Owner().(*SimpleConnectionPool); !ok || pool != p {
return errors.New(
"Connection pool cannot take control of a connection owned " +
"by another connection pool")
}
atomic.AddInt32(&p.numActive, -1)
if err := conn.RawConn().Close(); err != nil {
return errors.Wrap(err, "Failed to close connection")
}
return nil
}
// See ConnectionPool for documentation.
func (p *SimpleConnectionPool) EnterLameDuckMode() {
atomic.StoreInt32(&p.isLameDuck, 1)
p.mutex.Lock()
defer p.mutex.Unlock()
p.closeConns(p.idleConns)
p.idleConns = make([]*idleConn, 0, 0)
}
// This returns an idle connection, if there is one.
func (p *SimpleConnectionPool) getIdleConn() net.Conn {
now := p.getCurrentTime()
p.mutex.Lock()
defer p.mutex.Unlock()
var i int
for i = 0; i < len(p.idleConns); i++ {
idle := p.idleConns[i]
if idle.keepUntil == nil || now.Before(*idle.keepUntil) {
break
}
}
if i > 0 {
// Close all connections that have expired.
p.closeConns(p.idleConns[0 : i-1])
}
if i < len(p.idleConns) {
idle := p.idleConns[i]
p.idleConns = p.idleConns[i+1:]
return idle.conn
}
if len(p.idleConns) > 0 {
p.idleConns = make([]*idleConn, 0, 0)
}
return nil
}
// This adds an idle connection to the pool.
func (p *SimpleConnectionPool) queueIdleConns(conn net.Conn) {
if atomic.LoadInt32(&p.isLameDuck) == 1 {
conn.Close()
return
}
now := p.getCurrentTime()
var keepUntil *time.Time
if p.options.MaxIdleTime != nil {
// NOTE: Assign to temp variable first to work around compiler bug
x := now.Add(*p.options.MaxIdleTime)
keepUntil = &x
}
p.mutex.Lock()
defer p.mutex.Unlock()
p.idleConns = append(
p.idleConns,
&idleConn{
conn: conn,
keepUntil: keepUntil,
})
nIdleConns := uint32(len(p.idleConns))
if nIdleConns > p.options.MaxIdleConnections {
connsToClose := nIdleConns - p.options.MaxIdleConnections
p.closeConns(p.idleConns[0:connsToClose])
p.idleConns = p.idleConns[connsToClose:nIdleConns]
}
}
// Closes connections, at this point it is assumed that this connections
// are no longer referenced from the main idleConns slice.
func (p *SimpleConnectionPool) closeConns(conns []*idleConn) {
for _, conn := range conns {
conn.conn.Close()
}
}
func (p *SimpleConnectionPool) getCurrentTime() time.Time {
if p.options.NowFunc == nil {
return time.Now()
} else {
return p.options.NowFunc()
}
}