redis/internal/pool/pool.go

339 lines
6.2 KiB
Go
Raw Normal View History

package pool
import (
"errors"
"fmt"
2016-03-12 13:41:02 +03:00
"net"
2016-03-17 19:00:47 +03:00
"sync"
"sync/atomic"
"time"
2017-02-18 17:42:34 +03:00
"github.com/go-redis/redis/internal"
2016-04-09 14:52:01 +03:00
)
var (
ErrClosed = errors.New("redis: client is closed")
ErrPoolTimeout = errors.New("redis: connection pool timeout")
2016-04-06 13:13:03 +03:00
errConnStale = errors.New("connection is stale")
)
2016-03-17 19:00:47 +03:00
var timers = sync.Pool{
New: func() interface{} {
t := time.NewTimer(time.Hour)
t.Stop()
return t
2016-03-17 19:00:47 +03:00
},
}
// Stats contains pool state information and accumulated stats.
type Stats struct {
Requests uint32 // number of times a connection was requested by the pool
Hits uint32 // number of times free connection was found in the pool
Timeouts uint32 // number of times a wait timeout occurred
TotalConns uint32 // the number of total connections in the pool
FreeConns uint32 // the number of free connections in the pool
}
type Pooler interface {
2016-09-29 15:07:04 +03:00
Get() (*Conn, bool, error)
Put(*Conn) error
2016-03-17 19:00:47 +03:00
Remove(*Conn, error) error
Len() int
FreeLen() int
Stats() *Stats
Close() error
}
2016-03-12 13:41:02 +03:00
type dialer func() (net.Conn, error)
type ConnPool struct {
2016-12-16 16:43:37 +03:00
dial dialer
OnClose func(*Conn) error
poolTimeout time.Duration
idleTimeout time.Duration
2016-03-17 19:00:47 +03:00
queue chan struct{}
connsMu sync.Mutex
conns []*Conn
freeConnsMu sync.Mutex
freeConns []*Conn
stats Stats
2016-03-17 19:00:47 +03:00
_closed int32 // atomic
lastErr atomic.Value
}
var _ Pooler = (*ConnPool)(nil)
2016-03-17 19:00:47 +03:00
func NewConnPool(dial dialer, poolSize int, poolTimeout, idleTimeout, idleCheckFrequency time.Duration) *ConnPool {
p := &ConnPool{
2016-12-16 16:43:37 +03:00
dial: dial,
poolTimeout: poolTimeout,
idleTimeout: idleTimeout,
2016-03-17 19:00:47 +03:00
queue: make(chan struct{}, poolSize),
conns: make([]*Conn, 0, poolSize),
freeConns: make([]*Conn, 0, poolSize),
2016-03-12 15:42:12 +03:00
}
2016-03-17 19:00:47 +03:00
if idleTimeout > 0 && idleCheckFrequency > 0 {
go p.reaper(idleCheckFrequency)
}
2016-03-17 19:00:47 +03:00
return p
}
2016-03-15 15:04:35 +03:00
func (p *ConnPool) NewConn() (*Conn, error) {
2016-03-12 13:41:02 +03:00
netConn, err := p.dial()
if err != nil {
return nil, err
}
return NewConn(netConn), nil
}
2016-03-17 19:00:47 +03:00
func (p *ConnPool) PopFree() *Conn {
timer := timers.Get().(*time.Timer)
timer.Reset(p.poolTimeout)
2016-03-17 19:00:47 +03:00
select {
case p.queue <- struct{}{}:
if !timer.Stop() {
<-timer.C
}
2016-03-17 19:00:47 +03:00
timers.Put(timer)
case <-timer.C:
timers.Put(timer)
atomic.AddUint32(&p.stats.Timeouts, 1)
return nil
}
p.freeConnsMu.Lock()
cn := p.popFree()
p.freeConnsMu.Unlock()
if cn == nil {
<-p.queue
2016-03-17 19:00:47 +03:00
}
return cn
}
func (p *ConnPool) popFree() *Conn {
if len(p.freeConns) == 0 {
return nil
}
idx := len(p.freeConns) - 1
cn := p.freeConns[idx]
p.freeConns = p.freeConns[:idx]
return cn
}
// Get returns existed connection from the pool or creates a new one.
2016-09-29 15:07:04 +03:00
func (p *ConnPool) Get() (*Conn, bool, error) {
if p.closed() {
2016-09-29 15:07:04 +03:00
return nil, false, ErrClosed
}
atomic.AddUint32(&p.stats.Requests, 1)
2016-03-17 19:00:47 +03:00
timer := timers.Get().(*time.Timer)
timer.Reset(p.poolTimeout)
2016-03-17 19:00:47 +03:00
select {
case p.queue <- struct{}{}:
if !timer.Stop() {
<-timer.C
}
2016-03-17 19:00:47 +03:00
timers.Put(timer)
case <-timer.C:
timers.Put(timer)
atomic.AddUint32(&p.stats.Timeouts, 1)
2016-09-29 15:07:04 +03:00
return nil, false, ErrPoolTimeout
2016-03-17 19:00:47 +03:00
}
for {
p.freeConnsMu.Lock()
cn := p.popFree()
p.freeConnsMu.Unlock()
2016-03-17 19:00:47 +03:00
if cn == nil {
break
}
if cn.IsStale(p.idleTimeout) {
p.remove(cn, errConnStale)
continue
}
atomic.AddUint32(&p.stats.Hits, 1)
return cn, false, nil
2016-03-17 19:00:47 +03:00
}
newcn, err := p.NewConn()
if err != nil {
<-p.queue
2016-09-29 15:07:04 +03:00
return nil, false, err
}
2016-03-17 19:00:47 +03:00
p.connsMu.Lock()
p.conns = append(p.conns, newcn)
p.connsMu.Unlock()
2016-09-29 15:07:04 +03:00
return newcn, true, nil
}
func (p *ConnPool) Put(cn *Conn) error {
2016-07-02 15:52:10 +03:00
if data := cn.Rd.PeekBuffered(); data != nil {
err := fmt.Errorf("connection has unread data: %q", data)
2016-04-09 14:52:01 +03:00
internal.Logf(err.Error())
2016-03-17 19:00:47 +03:00
return p.Remove(cn, err)
}
2016-03-17 19:00:47 +03:00
p.freeConnsMu.Lock()
p.freeConns = append(p.freeConns, cn)
p.freeConnsMu.Unlock()
<-p.queue
return nil
}
2016-03-17 19:00:47 +03:00
func (p *ConnPool) Remove(cn *Conn, reason error) error {
p.remove(cn, reason)
<-p.queue
return nil
}
2016-03-17 19:00:47 +03:00
func (p *ConnPool) remove(cn *Conn, reason error) {
_ = p.closeConn(cn, reason)
p.connsMu.Lock()
2016-03-17 19:00:47 +03:00
for i, c := range p.conns {
if c == cn {
p.conns = append(p.conns[:i], p.conns[i+1:]...)
break
}
}
p.connsMu.Unlock()
2016-03-12 15:42:12 +03:00
}
// Len returns total number of connections.
func (p *ConnPool) Len() int {
2016-03-17 19:00:47 +03:00
p.connsMu.Lock()
l := len(p.conns)
p.connsMu.Unlock()
return l
}
// FreeLen returns number of free connections.
func (p *ConnPool) FreeLen() int {
2016-03-17 19:00:47 +03:00
p.freeConnsMu.Lock()
l := len(p.freeConns)
p.freeConnsMu.Unlock()
return l
}
func (p *ConnPool) Stats() *Stats {
return &Stats{
Requests: atomic.LoadUint32(&p.stats.Requests),
Hits: atomic.LoadUint32(&p.stats.Hits),
Timeouts: atomic.LoadUint32(&p.stats.Timeouts),
TotalConns: uint32(p.Len()),
FreeConns: uint32(p.FreeLen()),
}
}
func (p *ConnPool) closed() bool {
return atomic.LoadInt32(&p._closed) == 1
}
func (p *ConnPool) Close() error {
if !atomic.CompareAndSwapInt32(&p._closed, 0, 1) {
return ErrClosed
}
2016-03-17 19:00:47 +03:00
p.connsMu.Lock()
var firstErr error
2016-03-17 19:00:47 +03:00
for _, cn := range p.conns {
if cn == nil {
continue
}
if err := p.closeConn(cn, ErrClosed); err != nil && firstErr == nil {
firstErr = err
}
}
2016-03-17 19:00:47 +03:00
p.conns = nil
p.connsMu.Unlock()
p.freeConnsMu.Lock()
p.freeConns = nil
p.freeConnsMu.Unlock()
return firstErr
}
func (p *ConnPool) closeConn(cn *Conn, reason error) error {
if p.OnClose != nil {
_ = p.OnClose(cn)
}
return cn.Close()
}
func (p *ConnPool) reapStaleConn() bool {
2016-03-17 19:00:47 +03:00
if len(p.freeConns) == 0 {
return false
}
cn := p.freeConns[0]
if !cn.IsStale(p.idleTimeout) {
return false
}
p.remove(cn, errConnStale)
p.freeConns = append(p.freeConns[:0], p.freeConns[1:]...)
return true
}
func (p *ConnPool) ReapStaleConns() (int, error) {
var n int
for {
p.queue <- struct{}{}
p.freeConnsMu.Lock()
reaped := p.reapStaleConn()
2016-03-17 19:00:47 +03:00
p.freeConnsMu.Unlock()
<-p.queue
2016-03-17 19:00:47 +03:00
if reaped {
n++
} else {
2016-03-12 15:42:12 +03:00
break
}
2016-03-17 19:00:47 +03:00
}
return n, nil
2016-03-12 15:42:12 +03:00
}
func (p *ConnPool) reaper(frequency time.Duration) {
ticker := time.NewTicker(frequency)
defer ticker.Stop()
for _ = range ticker.C {
if p.closed() {
break
}
2016-03-12 15:42:12 +03:00
n, err := p.ReapStaleConns()
if err != nil {
2016-04-09 14:52:01 +03:00
internal.Logf("ReapStaleConns failed: %s", err)
2016-03-17 19:00:47 +03:00
continue
}
2016-03-17 19:00:47 +03:00
s := p.Stats()
2016-04-09 14:52:01 +03:00
internal.Logf(
2016-03-17 19:00:47 +03:00
"reaper: removed %d stale conns (TotalConns=%d FreeConns=%d Requests=%d Hits=%d Timeouts=%d)",
n, s.TotalConns, s.FreeConns, s.Requests, s.Hits, s.Timeouts,
)
}
}