pool.go 15 KB

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