pool.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. }
  148. // NewPool creates a new pool.
  149. //
  150. // Deprecated: Initialize the Pool directory as shown in the example.
  151. func NewPool(newFn func() (Conn, error), maxIdle int) *Pool {
  152. return &Pool{Dial: newFn, MaxIdle: maxIdle}
  153. }
  154. // Get gets a connection. The application must close the returned connection.
  155. // This method always returns a valid connection so that applications can defer
  156. // error handling to the first use of the connection. If there is an error
  157. // getting an underlying connection, then the connection Err, Do, Send, Flush
  158. // and Receive methods return that error.
  159. func (p *Pool) Get() Conn {
  160. pc, err := p.get(nil)
  161. if err != nil {
  162. return errorConn{err}
  163. }
  164. return &activeConn{p: p, pc: pc}
  165. }
  166. // PoolStats contains pool statistics.
  167. type PoolStats struct {
  168. // ActiveCount is the number of connections in the pool. The count includes
  169. // idle connections and connections in use.
  170. ActiveCount int
  171. // IdleCount is the number of idle connections in the pool.
  172. IdleCount int
  173. }
  174. // Stats returns pool's statistics.
  175. func (p *Pool) Stats() PoolStats {
  176. p.mu.Lock()
  177. stats := PoolStats{
  178. ActiveCount: p.active,
  179. IdleCount: p.idle.count,
  180. }
  181. p.mu.Unlock()
  182. return stats
  183. }
  184. // ActiveCount returns the number of connections in the pool. The count
  185. // includes idle connections and connections in use.
  186. func (p *Pool) ActiveCount() int {
  187. p.mu.Lock()
  188. active := p.active
  189. p.mu.Unlock()
  190. return active
  191. }
  192. // IdleCount returns the number of idle connections in the pool.
  193. func (p *Pool) IdleCount() int {
  194. p.mu.Lock()
  195. idle := p.idle.count
  196. p.mu.Unlock()
  197. return idle
  198. }
  199. // Close releases the resources used by the pool.
  200. func (p *Pool) Close() error {
  201. p.mu.Lock()
  202. if p.closed {
  203. p.mu.Unlock()
  204. return nil
  205. }
  206. p.closed = true
  207. p.active -= p.idle.count
  208. pc := p.idle.front
  209. p.idle.count = 0
  210. p.idle.front, p.idle.back = nil, nil
  211. if p.ch != nil {
  212. close(p.ch)
  213. }
  214. p.mu.Unlock()
  215. for ; pc != nil; pc = pc.next {
  216. pc.c.Close()
  217. }
  218. return nil
  219. }
  220. func (p *Pool) lazyInit() {
  221. // Fast path.
  222. if atomic.LoadUint32(&p.chInitialized) == 1 {
  223. return
  224. }
  225. // Slow path.
  226. p.mu.Lock()
  227. if p.chInitialized == 0 {
  228. p.ch = make(chan struct{}, p.MaxActive)
  229. if p.closed {
  230. close(p.ch)
  231. } else {
  232. for i := 0; i < p.MaxActive; i++ {
  233. p.ch <- struct{}{}
  234. }
  235. }
  236. atomic.StoreUint32(&p.chInitialized, 1)
  237. }
  238. p.mu.Unlock()
  239. }
  240. // get prunes stale connections and returns a connection from the idle list or
  241. // creates a new connection.
  242. func (p *Pool) get(ctx interface {
  243. Done() <-chan struct{}
  244. Err() error
  245. }) (*poolConn, error) {
  246. // Handle limit for p.Wait == true.
  247. if p.Wait && p.MaxActive > 0 {
  248. p.lazyInit()
  249. if ctx == nil {
  250. <-p.ch
  251. } else {
  252. select {
  253. case <-p.ch:
  254. case <-ctx.Done():
  255. return nil, ctx.Err()
  256. }
  257. }
  258. }
  259. p.mu.Lock()
  260. // Prune stale connections at the back of the idle list.
  261. if p.IdleTimeout > 0 {
  262. n := p.idle.count
  263. for i := 0; i < n && p.idle.back != nil && p.idle.back.t.Add(p.IdleTimeout).Before(nowFunc()); i++ {
  264. pc := p.idle.back
  265. p.idle.popBack()
  266. p.mu.Unlock()
  267. pc.c.Close()
  268. p.mu.Lock()
  269. p.active--
  270. }
  271. }
  272. // Get idle connection from the front of idle list.
  273. for p.idle.front != nil {
  274. pc := p.idle.front
  275. p.idle.popFront()
  276. p.mu.Unlock()
  277. if (p.TestOnBorrow == nil || p.TestOnBorrow(pc.c, pc.t) == nil) &&
  278. (p.MaxConnLifetime == 0 || nowFunc().Sub(pc.created) < p.MaxConnLifetime) {
  279. return pc, nil
  280. }
  281. pc.c.Close()
  282. p.mu.Lock()
  283. p.active--
  284. }
  285. // Check for pool closed before dialing a new connection.
  286. if p.closed {
  287. p.mu.Unlock()
  288. return nil, errors.New("redigo: get on closed pool")
  289. }
  290. // Handle limit for p.Wait == false.
  291. if !p.Wait && p.MaxActive > 0 && p.active >= p.MaxActive {
  292. p.mu.Unlock()
  293. return nil, ErrPoolExhausted
  294. }
  295. p.active++
  296. p.mu.Unlock()
  297. c, err := p.Dial()
  298. if err != nil {
  299. c = nil
  300. p.mu.Lock()
  301. p.active--
  302. if p.ch != nil && !p.closed {
  303. p.ch <- struct{}{}
  304. }
  305. p.mu.Unlock()
  306. }
  307. return &poolConn{c: c, created: nowFunc()}, err
  308. }
  309. func (p *Pool) put(pc *poolConn, forceClose bool) error {
  310. p.mu.Lock()
  311. if !p.closed && !forceClose {
  312. pc.t = nowFunc()
  313. p.idle.pushFront(pc)
  314. if p.idle.count > p.MaxIdle {
  315. pc = p.idle.back
  316. p.idle.popBack()
  317. } else {
  318. pc = nil
  319. }
  320. }
  321. if pc != nil {
  322. p.mu.Unlock()
  323. pc.c.Close()
  324. p.mu.Lock()
  325. p.active--
  326. }
  327. if p.ch != nil && !p.closed {
  328. p.ch <- struct{}{}
  329. }
  330. p.mu.Unlock()
  331. return nil
  332. }
  333. type activeConn struct {
  334. p *Pool
  335. pc *poolConn
  336. state int
  337. }
  338. var (
  339. sentinel []byte
  340. sentinelOnce sync.Once
  341. )
  342. func initSentinel() {
  343. p := make([]byte, 64)
  344. if _, err := rand.Read(p); err == nil {
  345. sentinel = p
  346. } else {
  347. h := sha1.New()
  348. io.WriteString(h, "Oops, rand failed. Use time instead.")
  349. io.WriteString(h, strconv.FormatInt(time.Now().UnixNano(), 10))
  350. sentinel = h.Sum(nil)
  351. }
  352. }
  353. func (ac *activeConn) Close() error {
  354. pc := ac.pc
  355. if pc == nil {
  356. return nil
  357. }
  358. ac.pc = nil
  359. if ac.state&connectionMultiState != 0 {
  360. pc.c.Send("DISCARD")
  361. ac.state &^= (connectionMultiState | connectionWatchState)
  362. } else if ac.state&connectionWatchState != 0 {
  363. pc.c.Send("UNWATCH")
  364. ac.state &^= connectionWatchState
  365. }
  366. if ac.state&connectionSubscribeState != 0 {
  367. pc.c.Send("UNSUBSCRIBE")
  368. pc.c.Send("PUNSUBSCRIBE")
  369. // To detect the end of the message stream, ask the server to echo
  370. // a sentinel value and read until we see that value.
  371. sentinelOnce.Do(initSentinel)
  372. pc.c.Send("ECHO", sentinel)
  373. pc.c.Flush()
  374. for {
  375. p, err := pc.c.Receive()
  376. if err != nil {
  377. break
  378. }
  379. if p, ok := p.([]byte); ok && bytes.Equal(p, sentinel) {
  380. ac.state &^= connectionSubscribeState
  381. break
  382. }
  383. }
  384. }
  385. pc.c.Do("")
  386. ac.p.put(pc, ac.state != 0 || pc.c.Err() != nil)
  387. return nil
  388. }
  389. func (ac *activeConn) Err() error {
  390. pc := ac.pc
  391. if pc == nil {
  392. return errConnClosed
  393. }
  394. return pc.c.Err()
  395. }
  396. func (ac *activeConn) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  397. pc := ac.pc
  398. if pc == nil {
  399. return nil, errConnClosed
  400. }
  401. ci := lookupCommandInfo(commandName)
  402. ac.state = (ac.state | ci.Set) &^ ci.Clear
  403. return pc.c.Do(commandName, args...)
  404. }
  405. func (ac *activeConn) DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (reply interface{}, err error) {
  406. pc := ac.pc
  407. if pc == nil {
  408. return nil, errConnClosed
  409. }
  410. cwt, ok := pc.c.(ConnWithTimeout)
  411. if !ok {
  412. return nil, errTimeoutNotSupported
  413. }
  414. ci := lookupCommandInfo(commandName)
  415. ac.state = (ac.state | ci.Set) &^ ci.Clear
  416. return cwt.DoWithTimeout(timeout, commandName, args...)
  417. }
  418. func (ac *activeConn) Send(commandName string, args ...interface{}) error {
  419. pc := ac.pc
  420. if pc == nil {
  421. return errConnClosed
  422. }
  423. ci := lookupCommandInfo(commandName)
  424. ac.state = (ac.state | ci.Set) &^ ci.Clear
  425. return pc.c.Send(commandName, args...)
  426. }
  427. func (ac *activeConn) Flush() error {
  428. pc := ac.pc
  429. if pc == nil {
  430. return errConnClosed
  431. }
  432. return pc.c.Flush()
  433. }
  434. func (ac *activeConn) Receive() (reply interface{}, err error) {
  435. pc := ac.pc
  436. if pc == nil {
  437. return nil, errConnClosed
  438. }
  439. return pc.c.Receive()
  440. }
  441. func (ac *activeConn) ReceiveWithTimeout(timeout time.Duration) (reply interface{}, err error) {
  442. pc := ac.pc
  443. if pc == nil {
  444. return nil, errConnClosed
  445. }
  446. cwt, ok := pc.c.(ConnWithTimeout)
  447. if !ok {
  448. return nil, errTimeoutNotSupported
  449. }
  450. return cwt.ReceiveWithTimeout(timeout)
  451. }
  452. type errorConn struct{ err error }
  453. func (ec errorConn) Do(string, ...interface{}) (interface{}, error) { return nil, ec.err }
  454. func (ec errorConn) DoWithTimeout(time.Duration, string, ...interface{}) (interface{}, error) {
  455. return nil, ec.err
  456. }
  457. func (ec errorConn) Send(string, ...interface{}) error { return ec.err }
  458. func (ec errorConn) Err() error { return ec.err }
  459. func (ec errorConn) Close() error { return nil }
  460. func (ec errorConn) Flush() error { return ec.err }
  461. func (ec errorConn) Receive() (interface{}, error) { return nil, ec.err }
  462. func (ec errorConn) ReceiveWithTimeout(time.Duration) (interface{}, error) { return nil, ec.err }
  463. type idleList struct {
  464. count int
  465. front, back *poolConn
  466. }
  467. type poolConn struct {
  468. c Conn
  469. t time.Time
  470. created time.Time
  471. next, prev *poolConn
  472. }
  473. func (l *idleList) pushFront(pc *poolConn) {
  474. pc.next = l.front
  475. pc.prev = nil
  476. if l.count == 0 {
  477. l.back = pc
  478. } else {
  479. l.front.prev = pc
  480. }
  481. l.front = pc
  482. l.count++
  483. return
  484. }
  485. func (l *idleList) popFront() {
  486. pc := l.front
  487. l.count--
  488. if l.count == 0 {
  489. l.front, l.back = nil, nil
  490. } else {
  491. pc.next.prev = nil
  492. l.front = pc.next
  493. }
  494. pc.next, pc.prev = nil, nil
  495. }
  496. func (l *idleList) popBack() {
  497. pc := l.back
  498. l.count--
  499. if l.count == 0 {
  500. l.front, l.back = nil, nil
  501. } else {
  502. pc.prev.next = nil
  503. l.back = pc.prev
  504. }
  505. pc.next, pc.prev = nil, nil
  506. }