pool.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. // Copyright 2012 Gary Burd
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package redis
  15. import (
  16. "bytes"
  17. "crypto/rand"
  18. "crypto/sha1"
  19. "errors"
  20. "io"
  21. "strconv"
  22. "sync"
  23. "sync/atomic"
  24. "time"
  25. "github.com/garyburd/redigo/internal"
  26. )
  27. var (
  28. _ ConnWithTimeout = (*pooledConnection)(nil)
  29. _ ConnWithTimeout = (*errorConnection)(nil)
  30. )
  31. var nowFunc = time.Now // for testing
  32. // ErrPoolExhausted is returned from a pool connection method (Do, Send,
  33. // Receive, Flush, Err) when the maximum number of database connections in the
  34. // pool has been reached.
  35. var ErrPoolExhausted = errors.New("redigo: connection pool exhausted")
  36. var (
  37. errPoolClosed = errors.New("redigo: connection pool closed")
  38. errConnClosed = errors.New("redigo: connection closed")
  39. )
  40. // Pool maintains a pool of connections. The application calls the Get method
  41. // to get a connection from the pool and the connection's Close method to
  42. // return the connection's resources to the pool.
  43. //
  44. // The following example shows how to use a pool in a web application. The
  45. // application creates a pool at application startup and makes it available to
  46. // request handlers using a package level variable. The pool configuration used
  47. // here is an example, not a recommendation.
  48. //
  49. // func newPool(addr string) *redis.Pool {
  50. // return &redis.Pool{
  51. // MaxIdle: 3,
  52. // IdleTimeout: 240 * time.Second,
  53. // Dial: func () (redis.Conn, error) { return redis.Dial("tcp", addr) },
  54. // }
  55. // }
  56. //
  57. // var (
  58. // pool *redis.Pool
  59. // redisServer = flag.String("redisServer", ":6379", "")
  60. // )
  61. //
  62. // func main() {
  63. // flag.Parse()
  64. // pool = newPool(*redisServer)
  65. // ...
  66. // }
  67. //
  68. // A request handler gets a connection from the pool and closes the connection
  69. // when the handler is done:
  70. //
  71. // func serveHome(w http.ResponseWriter, r *http.Request) {
  72. // conn := pool.Get()
  73. // defer conn.Close()
  74. // ...
  75. // }
  76. //
  77. // Use the Dial function to authenticate connections with the AUTH command or
  78. // select a database with the SELECT command:
  79. //
  80. // pool := &redis.Pool{
  81. // // Other pool configuration not shown in this example.
  82. // Dial: func () (redis.Conn, error) {
  83. // c, err := redis.Dial("tcp", server)
  84. // if err != nil {
  85. // return nil, err
  86. // }
  87. // if _, err := c.Do("AUTH", password); err != nil {
  88. // c.Close()
  89. // return nil, err
  90. // }
  91. // if _, err := c.Do("SELECT", db); err != nil {
  92. // c.Close()
  93. // return nil, err
  94. // }
  95. // return c, nil
  96. // },
  97. // }
  98. //
  99. // Use the TestOnBorrow function to check the health of an idle connection
  100. // before the connection is returned to the application. This example PINGs
  101. // connections that have been idle more than a minute:
  102. //
  103. // pool := &redis.Pool{
  104. // // Other pool configuration not shown in this example.
  105. // TestOnBorrow: func(c redis.Conn, t time.Time) error {
  106. // if time.Since(t) < time.Minute {
  107. // return nil
  108. // }
  109. // _, err := c.Do("PING")
  110. // return err
  111. // },
  112. // }
  113. //
  114. type Pool struct {
  115. // Dial is an application supplied function for creating and configuring a
  116. // connection.
  117. //
  118. // The connection returned from Dial must not be in a special state
  119. // (subscribed to pubsub channel, transaction started, ...).
  120. Dial func() (Conn, error)
  121. // TestOnBorrow is an optional application supplied function for checking
  122. // the health of an idle connection before the connection is used again by
  123. // the application. Argument t is the time that the connection was returned
  124. // to the pool. If the function returns an error, then the connection is
  125. // closed.
  126. TestOnBorrow func(c Conn, t time.Time) error
  127. // Maximum number of idle connections in the pool.
  128. MaxIdle int
  129. // Maximum number of connections allocated by the pool at a given time.
  130. // When zero, there is no limit on the number of connections in the pool.
  131. MaxActive int
  132. // Close connections after remaining idle for this duration. If the value
  133. // is zero, then idle connections are not closed. Applications should set
  134. // the timeout to a value less than the server's timeout.
  135. IdleTimeout time.Duration
  136. // If Wait is true and the pool is at the MaxActive limit, then Get() waits
  137. // for a connection to be returned to the pool before returning.
  138. Wait bool
  139. chInitialized uint32 // set to 1 when field ch is initialized
  140. mu sync.Mutex // mu protects the following fields
  141. closed bool // set to true when the pool is closed.
  142. active int // the number of open connections in the pool
  143. ch chan struct{} // limits open connections when p.Wait is true
  144. idle idleList // idle connections
  145. }
  146. // NewPool creates a new pool.
  147. //
  148. // Deprecated: Initialize the Pool directory as shown in the example.
  149. func NewPool(newFn func() (Conn, error), maxIdle int) *Pool {
  150. return &Pool{Dial: newFn, MaxIdle: maxIdle}
  151. }
  152. // Get gets a connection. The application must close the returned connection.
  153. // This method always returns a valid connection so that applications can defer
  154. // error handling to the first use of the connection. If there is an error
  155. // getting an underlying connection, then the connection Err, Do, Send, Flush
  156. // and Receive methods return that error.
  157. func (p *Pool) Get() Conn {
  158. c, err := p.get(nil)
  159. if err != nil {
  160. return errorConnection{err}
  161. }
  162. return &pooledConnection{p: p, c: c}
  163. }
  164. // PoolStats contains pool statistics.
  165. type PoolStats struct {
  166. // ActiveCount is the number of connections in the pool. The count includes
  167. // idle connections and connections in use.
  168. ActiveCount int
  169. // IdleCount is the number of idle connections in the pool.
  170. IdleCount int
  171. }
  172. // Stats returns pool's statistics.
  173. func (p *Pool) Stats() PoolStats {
  174. p.mu.Lock()
  175. stats := PoolStats{
  176. ActiveCount: p.active,
  177. IdleCount: p.idle.count,
  178. }
  179. p.mu.Unlock()
  180. return stats
  181. }
  182. // ActiveCount returns the number of connections in the pool. The count
  183. // includes idle connections and connections in use.
  184. func (p *Pool) ActiveCount() int {
  185. p.mu.Lock()
  186. active := p.active
  187. p.mu.Unlock()
  188. return active
  189. }
  190. // IdleCount returns the number of idle connections in the pool.
  191. func (p *Pool) IdleCount() int {
  192. p.mu.Lock()
  193. idle := p.idle.count
  194. p.mu.Unlock()
  195. return idle
  196. }
  197. // Close releases the resources used by the pool.
  198. func (p *Pool) Close() error {
  199. p.mu.Lock()
  200. if p.closed {
  201. p.mu.Unlock()
  202. return nil
  203. }
  204. p.closed = true
  205. p.active -= p.idle.count
  206. ic := p.idle.front
  207. p.idle.count = 0
  208. p.idle.front, p.idle.back = nil, nil
  209. if p.ch != nil {
  210. close(p.ch)
  211. }
  212. p.mu.Unlock()
  213. for ; ic != nil; ic = ic.next {
  214. ic.c.Close()
  215. }
  216. return nil
  217. }
  218. func (p *Pool) lazyInit() {
  219. // Fast path.
  220. if atomic.LoadUint32(&p.chInitialized) == 1 {
  221. return
  222. }
  223. // Slow path.
  224. p.mu.Lock()
  225. if p.chInitialized == 0 {
  226. p.ch = make(chan struct{}, p.MaxActive)
  227. if p.closed {
  228. close(p.ch)
  229. } else {
  230. for i := 0; i < p.MaxActive; i++ {
  231. p.ch <- struct{}{}
  232. }
  233. }
  234. atomic.StoreUint32(&p.chInitialized, 1)
  235. }
  236. p.mu.Unlock()
  237. }
  238. // get prunes stale connections and returns a connection from the idle list or
  239. // creates a new connection.
  240. func (p *Pool) get(ctx interface {
  241. Done() <-chan struct{}
  242. Err() error
  243. }) (Conn, error) {
  244. // Handle limit for p.Wait == true.
  245. if p.Wait && p.MaxActive > 0 {
  246. p.lazyInit()
  247. if ctx == nil {
  248. <-p.ch
  249. } else {
  250. select {
  251. case <-p.ch:
  252. case <-ctx.Done():
  253. return nil, ctx.Err()
  254. }
  255. }
  256. }
  257. p.mu.Lock()
  258. // Prune stale connections at the back of the idle list.
  259. if p.IdleTimeout > 0 {
  260. n := p.idle.count
  261. for i := 0; i < n && p.idle.back != nil && p.idle.back.t.Add(p.IdleTimeout).Before(nowFunc()); i++ {
  262. c := p.idle.back.c
  263. p.idle.popBack()
  264. p.mu.Unlock()
  265. c.Close()
  266. p.mu.Lock()
  267. p.active--
  268. }
  269. }
  270. // Get idle connection from the front of idle list.
  271. for p.idle.front != nil {
  272. ic := p.idle.front
  273. p.idle.popFront()
  274. p.mu.Unlock()
  275. if p.TestOnBorrow == nil || p.TestOnBorrow(ic.c, ic.t) == nil {
  276. return ic.c, nil
  277. }
  278. ic.c.Close()
  279. p.mu.Lock()
  280. p.active--
  281. }
  282. // Check for pool closed before dialing a new connection.
  283. if p.closed {
  284. p.mu.Unlock()
  285. return nil, errors.New("redigo: get on closed pool")
  286. }
  287. // Handle limit for p.Wait == false.
  288. if !p.Wait && p.MaxActive > 0 && p.active >= p.MaxActive {
  289. p.mu.Unlock()
  290. return nil, ErrPoolExhausted
  291. }
  292. p.active++
  293. p.mu.Unlock()
  294. c, err := p.Dial()
  295. if err != nil {
  296. c = nil
  297. p.mu.Lock()
  298. p.active--
  299. if p.ch != nil && !p.closed {
  300. p.ch <- struct{}{}
  301. }
  302. p.mu.Unlock()
  303. }
  304. return c, err
  305. }
  306. func (p *Pool) put(c Conn, forceClose bool) error {
  307. p.mu.Lock()
  308. if !p.closed && !forceClose {
  309. p.idle.pushFront(&idleConn{t: nowFunc(), c: c})
  310. if p.idle.count > p.MaxIdle {
  311. c = p.idle.back.c
  312. p.idle.popBack()
  313. } else {
  314. c = nil
  315. }
  316. }
  317. if c != nil {
  318. p.mu.Unlock()
  319. c.Close()
  320. p.mu.Lock()
  321. p.active--
  322. }
  323. if p.ch != nil && !p.closed {
  324. p.ch <- struct{}{}
  325. }
  326. p.mu.Unlock()
  327. return nil
  328. }
  329. type pooledConnection struct {
  330. p *Pool
  331. c Conn
  332. state int
  333. }
  334. var (
  335. sentinel []byte
  336. sentinelOnce sync.Once
  337. )
  338. func initSentinel() {
  339. p := make([]byte, 64)
  340. if _, err := rand.Read(p); err == nil {
  341. sentinel = p
  342. } else {
  343. h := sha1.New()
  344. io.WriteString(h, "Oops, rand failed. Use time instead.")
  345. io.WriteString(h, strconv.FormatInt(time.Now().UnixNano(), 10))
  346. sentinel = h.Sum(nil)
  347. }
  348. }
  349. func (pc *pooledConnection) Close() error {
  350. c := pc.c
  351. if _, ok := c.(errorConnection); ok {
  352. return nil
  353. }
  354. pc.c = errorConnection{errConnClosed}
  355. if pc.state&internal.MultiState != 0 {
  356. c.Send("DISCARD")
  357. pc.state &^= (internal.MultiState | internal.WatchState)
  358. } else if pc.state&internal.WatchState != 0 {
  359. c.Send("UNWATCH")
  360. pc.state &^= internal.WatchState
  361. }
  362. if pc.state&internal.SubscribeState != 0 {
  363. c.Send("UNSUBSCRIBE")
  364. c.Send("PUNSUBSCRIBE")
  365. // To detect the end of the message stream, ask the server to echo
  366. // a sentinel value and read until we see that value.
  367. sentinelOnce.Do(initSentinel)
  368. c.Send("ECHO", sentinel)
  369. c.Flush()
  370. for {
  371. p, err := c.Receive()
  372. if err != nil {
  373. break
  374. }
  375. if p, ok := p.([]byte); ok && bytes.Equal(p, sentinel) {
  376. pc.state &^= internal.SubscribeState
  377. break
  378. }
  379. }
  380. }
  381. c.Do("")
  382. pc.p.put(c, pc.state != 0 || c.Err() != nil)
  383. return nil
  384. }
  385. func (pc *pooledConnection) Err() error {
  386. return pc.c.Err()
  387. }
  388. func (pc *pooledConnection) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  389. ci := internal.LookupCommandInfo(commandName)
  390. pc.state = (pc.state | ci.Set) &^ ci.Clear
  391. return pc.c.Do(commandName, args...)
  392. }
  393. func (pc *pooledConnection) DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (reply interface{}, err error) {
  394. cwt, ok := pc.c.(ConnWithTimeout)
  395. if !ok {
  396. return nil, errTimeoutNotSupported
  397. }
  398. ci := internal.LookupCommandInfo(commandName)
  399. pc.state = (pc.state | ci.Set) &^ ci.Clear
  400. return cwt.DoWithTimeout(timeout, commandName, args...)
  401. }
  402. func (pc *pooledConnection) Send(commandName string, args ...interface{}) error {
  403. ci := internal.LookupCommandInfo(commandName)
  404. pc.state = (pc.state | ci.Set) &^ ci.Clear
  405. return pc.c.Send(commandName, args...)
  406. }
  407. func (pc *pooledConnection) Flush() error {
  408. return pc.c.Flush()
  409. }
  410. func (pc *pooledConnection) Receive() (reply interface{}, err error) {
  411. return pc.c.Receive()
  412. }
  413. func (pc *pooledConnection) ReceiveWithTimeout(timeout time.Duration) (reply interface{}, err error) {
  414. cwt, ok := pc.c.(ConnWithTimeout)
  415. if !ok {
  416. return nil, errTimeoutNotSupported
  417. }
  418. return cwt.ReceiveWithTimeout(timeout)
  419. }
  420. type errorConnection struct{ err error }
  421. func (ec errorConnection) Do(string, ...interface{}) (interface{}, error) { return nil, ec.err }
  422. func (ec errorConnection) DoWithTimeout(time.Duration, string, ...interface{}) (interface{}, error) {
  423. return nil, ec.err
  424. }
  425. func (ec errorConnection) Send(string, ...interface{}) error { return ec.err }
  426. func (ec errorConnection) Err() error { return ec.err }
  427. func (ec errorConnection) Close() error { return nil }
  428. func (ec errorConnection) Flush() error { return ec.err }
  429. func (ec errorConnection) Receive() (interface{}, error) { return nil, ec.err }
  430. func (ec errorConnection) ReceiveWithTimeout(time.Duration) (interface{}, error) { return nil, ec.err }
  431. type idleList struct {
  432. count int
  433. front, back *idleConn
  434. }
  435. type idleConn struct {
  436. c Conn
  437. t time.Time
  438. next, prev *idleConn
  439. }
  440. func (l *idleList) pushFront(ic *idleConn) {
  441. ic.next = l.front
  442. ic.prev = nil
  443. if l.count == 0 {
  444. l.back = ic
  445. } else {
  446. l.front.prev = ic
  447. }
  448. l.front = ic
  449. l.count++
  450. return
  451. }
  452. func (l *idleList) popFront() {
  453. ic := l.front
  454. l.count--
  455. if l.count == 0 {
  456. l.front, l.back = nil, nil
  457. } else {
  458. ic.next.prev = nil
  459. l.front = ic.next
  460. }
  461. ic.next, ic.prev = nil, nil
  462. }
  463. func (l *idleList) popBack() {
  464. ic := l.back
  465. l.count--
  466. if l.count == 0 {
  467. l.front, l.back = nil, nil
  468. } else {
  469. ic.prev.next = nil
  470. l.back = ic.prev
  471. }
  472. ic.next, ic.prev = nil, nil
  473. }