| 1 |
package pool |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"fmt" |
| 6 |
"net" |
| 7 |
"sync" |
| 8 |
"sync/atomic" |
| 9 |
"time" |
| 10 |
|
| 11 |
"gopkg.in/redis.v5/internal" |
| 12 |
) |
| 13 |
|
| 14 |
var ( |
| 15 |
ErrClosed = errors.New("redis: client is closed") |
| 16 |
ErrPoolTimeout = errors.New("redis: connection pool timeout") |
| 17 |
errConnStale = errors.New("connection is stale") |
| 18 |
) |
| 19 |
|
| 20 |
var timers = sync.Pool{ |
| 21 |
New: func() interface{} { |
| 22 |
t := time.NewTimer(time.Hour) |
| 23 |
t.Stop() |
| 24 |
return t |
| 25 |
}, |
| 26 |
} |
| 27 |
|
| 28 |
// Stats contains pool state information and accumulated stats. |
| 29 |
type Stats struct { |
| 30 |
Requests uint32 // number of times a connection was requested by the pool |
| 31 |
Hits uint32 // number of times free connection was found in the pool |
| 32 |
Timeouts uint32 // number of times a wait timeout occurred |
| 33 |
|
| 34 |
TotalConns uint32 // the number of total connections in the pool |
| 35 |
FreeConns uint32 // the number of free connections in the pool |
| 36 |
} |
| 37 |
|
| 38 |
type Pooler interface { |
| 39 |
Get() (*Conn, bool, error) |
| 40 |
Put(*Conn) error |
| 41 |
Remove(*Conn, error) error |
| 42 |
Len() int |
| 43 |
FreeLen() int |
| 44 |
Stats() *Stats |
| 45 |
Close() error |
| 46 |
} |
| 47 |
|
| 48 |
type dialer func() (net.Conn, error) |
| 49 |
|
| 50 |
type ConnPool struct { |
| 51 |
dial dialer |
| 52 |
OnClose func(*Conn) error |
| 53 |
|
| 54 |
poolTimeout time.Duration |
| 55 |
idleTimeout time.Duration |
| 56 |
|
| 57 |
queue chan struct{} |
| 58 |
|
| 59 |
connsMu sync.Mutex |
| 60 |
conns []*Conn |
| 61 |
|
| 62 |
freeConnsMu sync.Mutex |
| 63 |
freeConns []*Conn |
| 64 |
|
| 65 |
stats Stats |
| 66 |
|
| 67 |
_closed int32 // atomic |
| 68 |
lastErr atomic.Value |
| 69 |
} |
| 70 |
|
| 71 |
var _ Pooler = (*ConnPool)(nil) |
| 72 |
|
| 73 |
func NewConnPool(dial dialer, poolSize int, poolTimeout, idleTimeout, idleCheckFrequency time.Duration) *ConnPool { |
| 74 |
p := &ConnPool{ |
| 75 |
dial: dial, |
| 76 |
|
| 77 |
poolTimeout: poolTimeout, |
| 78 |
idleTimeout: idleTimeout, |
| 79 |
|
| 80 |
queue: make(chan struct{}, poolSize), |
| 81 |
conns: make([]*Conn, 0, poolSize), |
| 82 |
freeConns: make([]*Conn, 0, poolSize), |
| 83 |
} |
| 84 |
if idleTimeout > 0 && idleCheckFrequency > 0 { |
| 85 |
go p.reaper(idleCheckFrequency) |
| 86 |
} |
| 87 |
return p |
| 88 |
} |
| 89 |
|
| 90 |
func (p *ConnPool) NewConn() (*Conn, error) { |
| 91 |
netConn, err := p.dial() |
| 92 |
if err != nil { |
| 93 |
return nil, err |
| 94 |
} |
| 95 |
return NewConn(netConn), nil |
| 96 |
} |
| 97 |
|
| 98 |
func (p *ConnPool) PopFree() *Conn { |
| 99 |
timer := timers.Get().(*time.Timer) |
| 100 |
timer.Reset(p.poolTimeout) |
| 101 |
|
| 102 |
select { |
| 103 |
case p.queue <- struct{}{}: |
| 104 |
if !timer.Stop() { |
| 105 |
<-timer.C |
| 106 |
} |
| 107 |
timers.Put(timer) |
| 108 |
case <-timer.C: |
| 109 |
timers.Put(timer) |
| 110 |
atomic.AddUint32(&p.stats.Timeouts, 1) |
| 111 |
return nil |
| 112 |
} |
| 113 |
|
| 114 |
p.freeConnsMu.Lock() |
| 115 |
cn := p.popFree() |
| 116 |
p.freeConnsMu.Unlock() |
| 117 |
|
| 118 |
if cn == nil { |
| 119 |
<-p.queue |
| 120 |
} |
| 121 |
return cn |
| 122 |
} |
| 123 |
|
| 124 |
func (p *ConnPool) popFree() *Conn { |
| 125 |
if len(p.freeConns) == 0 { |
| 126 |
return nil |
| 127 |
} |
| 128 |
|
| 129 |
idx := len(p.freeConns) - 1 |
| 130 |
cn := p.freeConns[idx] |
| 131 |
p.freeConns = p.freeConns[:idx] |
| 132 |
return cn |
| 133 |
} |
| 134 |
|
| 135 |
// Get returns existed connection from the pool or creates a new one. |
| 136 |
func (p *ConnPool) Get() (*Conn, bool, error) { |
| 137 |
if p.closed() { |
| 138 |
return nil, false, ErrClosed |
| 139 |
} |
| 140 |
|
| 141 |
atomic.AddUint32(&p.stats.Requests, 1) |
| 142 |
|
| 143 |
timer := timers.Get().(*time.Timer) |
| 144 |
timer.Reset(p.poolTimeout) |
| 145 |
|
| 146 |
select { |
| 147 |
case p.queue <- struct{}{}: |
| 148 |
if !timer.Stop() { |
| 149 |
<-timer.C |
| 150 |
} |
| 151 |
timers.Put(timer) |
| 152 |
case <-timer.C: |
| 153 |
timers.Put(timer) |
| 154 |
atomic.AddUint32(&p.stats.Timeouts, 1) |
| 155 |
return nil, false, ErrPoolTimeout |
| 156 |
} |
| 157 |
|
| 158 |
for { |
| 159 |
p.freeConnsMu.Lock() |
| 160 |
cn := p.popFree() |
| 161 |
p.freeConnsMu.Unlock() |
| 162 |
|
| 163 |
if cn == nil { |
| 164 |
break |
| 165 |
} |
| 166 |
|
| 167 |
if cn.IsStale(p.idleTimeout) { |
| 168 |
p.remove(cn, errConnStale) |
| 169 |
continue |
| 170 |
} |
| 171 |
|
| 172 |
atomic.AddUint32(&p.stats.Hits, 1) |
| 173 |
return cn, false, nil |
| 174 |
} |
| 175 |
|
| 176 |
newcn, err := p.NewConn() |
| 177 |
if err != nil { |
| 178 |
<-p.queue |
| 179 |
return nil, false, err |
| 180 |
} |
| 181 |
|
| 182 |
p.connsMu.Lock() |
| 183 |
p.conns = append(p.conns, newcn) |
| 184 |
p.connsMu.Unlock() |
| 185 |
|
| 186 |
return newcn, true, nil |
| 187 |
} |
| 188 |
|
| 189 |
func (p *ConnPool) Put(cn *Conn) error { |
| 190 |
if data := cn.Rd.PeekBuffered(); data != nil { |
| 191 |
err := fmt.Errorf("connection has unread data: %q", data) |
| 192 |
internal.Logf(err.Error()) |
| 193 |
return p.Remove(cn, err) |
| 194 |
} |
| 195 |
p.freeConnsMu.Lock() |
| 196 |
p.freeConns = append(p.freeConns, cn) |
| 197 |
p.freeConnsMu.Unlock() |
| 198 |
<-p.queue |
| 199 |
return nil |
| 200 |
} |
| 201 |
|
| 202 |
func (p *ConnPool) Remove(cn *Conn, reason error) error { |
| 203 |
p.remove(cn, reason) |
| 204 |
<-p.queue |
| 205 |
return nil |
| 206 |
} |
| 207 |
|
| 208 |
func (p *ConnPool) remove(cn *Conn, reason error) { |
| 209 |
_ = p.closeConn(cn, reason) |
| 210 |
|
| 211 |
p.connsMu.Lock() |
| 212 |
for i, c := range p.conns { |
| 213 |
if c == cn { |
| 214 |
p.conns = append(p.conns[:i], p.conns[i+1:]...) |
| 215 |
break |
| 216 |
} |
| 217 |
} |
| 218 |
p.connsMu.Unlock() |
| 219 |
} |
| 220 |
|
| 221 |
// Len returns total number of connections. |
| 222 |
func (p *ConnPool) Len() int { |
| 223 |
p.connsMu.Lock() |
| 224 |
l := len(p.conns) |
| 225 |
p.connsMu.Unlock() |
| 226 |
return l |
| 227 |
} |
| 228 |
|
| 229 |
// FreeLen returns number of free connections. |
| 230 |
func (p *ConnPool) FreeLen() int { |
| 231 |
p.freeConnsMu.Lock() |
| 232 |
l := len(p.freeConns) |
| 233 |
p.freeConnsMu.Unlock() |
| 234 |
return l |
| 235 |
} |
| 236 |
|
| 237 |
func (p *ConnPool) Stats() *Stats { |
| 238 |
return &Stats{ |
| 239 |
Requests: atomic.LoadUint32(&p.stats.Requests), |
| 240 |
Hits: atomic.LoadUint32(&p.stats.Hits), |
| 241 |
Timeouts: atomic.LoadUint32(&p.stats.Timeouts), |
| 242 |
TotalConns: uint32(p.Len()), |
| 243 |
FreeConns: uint32(p.FreeLen()), |
| 244 |
} |
| 245 |
} |
| 246 |
|
| 247 |
func (p *ConnPool) closed() bool { |
| 248 |
return atomic.LoadInt32(&p._closed) == 1 |
| 249 |
} |
| 250 |
|
| 251 |
func (p *ConnPool) Close() error { |
| 252 |
if !atomic.CompareAndSwapInt32(&p._closed, 0, 1) { |
| 253 |
return ErrClosed |
| 254 |
} |
| 255 |
|
| 256 |
p.connsMu.Lock() |
| 257 |
var firstErr error |
| 258 |
for _, cn := range p.conns { |
| 259 |
if cn == nil { |
| 260 |
continue |
| 261 |
} |
| 262 |
if err := p.closeConn(cn, ErrClosed); err != nil && firstErr == nil { |
| 263 |
firstErr = err |
| 264 |
} |
| 265 |
} |
| 266 |
p.conns = nil |
| 267 |
p.connsMu.Unlock() |
| 268 |
|
| 269 |
p.freeConnsMu.Lock() |
| 270 |
p.freeConns = nil |
| 271 |
p.freeConnsMu.Unlock() |
| 272 |
|
| 273 |
return firstErr |
| 274 |
} |
| 275 |
|
| 276 |
func (p *ConnPool) closeConn(cn *Conn, reason error) error { |
| 277 |
if p.OnClose != nil { |
| 278 |
_ = p.OnClose(cn) |
| 279 |
} |
| 280 |
return cn.Close() |
| 281 |
} |
| 282 |
|
| 283 |
func (p *ConnPool) reapStaleConn() bool { |
| 284 |
if len(p.freeConns) == 0 { |
| 285 |
return false |
| 286 |
} |
| 287 |
|
| 288 |
cn := p.freeConns[0] |
| 289 |
if !cn.IsStale(p.idleTimeout) { |
| 290 |
return false |
| 291 |
} |
| 292 |
|
| 293 |
p.remove(cn, errConnStale) |
| 294 |
p.freeConns = append(p.freeConns[:0], p.freeConns[1:]...) |
| 295 |
|
| 296 |
return true |
| 297 |
} |
| 298 |
|
| 299 |
func (p *ConnPool) ReapStaleConns() (int, error) { |
| 300 |
var n int |
| 301 |
for { |
| 302 |
p.queue <- struct{}{} |
| 303 |
p.freeConnsMu.Lock() |
| 304 |
|
| 305 |
reaped := p.reapStaleConn() |
| 306 |
|
| 307 |
p.freeConnsMu.Unlock() |
| 308 |
<-p.queue |
| 309 |
|
| 310 |
if reaped { |
| 311 |
n++ |
| 312 |
} else { |
| 313 |
break |
| 314 |
} |
| 315 |
} |
| 316 |
return n, nil |
| 317 |
} |
| 318 |
|
| 319 |
func (p *ConnPool) reaper(frequency time.Duration) { |
| 320 |
ticker := time.NewTicker(frequency) |
| 321 |
defer ticker.Stop() |
| 322 |
|
| 323 |
for _ = range ticker.C { |
| 324 |
if p.closed() { |
| 325 |
break |
| 326 |
} |
| 327 |
n, err := p.ReapStaleConns() |
| 328 |
if err != nil { |
| 329 |
internal.Logf("ReapStaleConns failed: %s", err) |
| 330 |
continue |
| 331 |
} |
| 332 |
s := p.Stats() |
| 333 |
internal.Logf( |
| 334 |
"reaper: removed %d stale conns (TotalConns=%d FreeConns=%d Requests=%d Hits=%d Timeouts=%d)", |
| 335 |
n, s.TotalConns, s.FreeConns, s.Requests, s.Hits, s.Timeouts, |
| 336 |
) |
| 337 |
} |
| 338 |
} |
| 339 |
|
| 340 |
//------------------------------------------------------------------------------ |
| 341 |
|
| 342 |
var idleCheckFrequency atomic.Value |
| 343 |
|
| 344 |
func SetIdleCheckFrequency(d time.Duration) { |
| 345 |
idleCheckFrequency.Store(d) |
| 346 |
} |
| 347 |
|
| 348 |
func getIdleCheckFrequency() time.Duration { |
| 349 |
v := idleCheckFrequency.Load() |
| 350 |
if v == nil { |
| 351 |
return time.Minute |
| 352 |
} |
| 353 |
return v.(time.Duration) |
| 354 |
} |