pool.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. "context"
  18. "crypto/rand"
  19. "crypto/sha1"
  20. "errors"
  21. "io"
  22. "strconv"
  23. "sync"
  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. errConnClosed = errors.New("redigo: connection closed")
  37. )
  38. // Pool maintains a pool of connections. The application calls the Get method
  39. // to get a connection from the pool and the connection's Close method to
  40. // return the connection's resources to the pool.
  41. //
  42. // The following example shows how to use a pool in a web application. The
  43. // application creates a pool at application startup and makes it available to
  44. // request handlers using a package level variable. The pool configuration used
  45. // here is an example, not a recommendation.
  46. //
  47. // func newPool(addr string) *redis.Pool {
  48. // return &redis.Pool{
  49. // MaxIdle: 3,
  50. // IdleTimeout: 240 * time.Second,
  51. // // Dial or DialContext must be set. When both are set, DialContext takes precedence over Dial.
  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. // DialContext is an application supplied function for creating and configuring a
  121. // connection with the given context.
  122. //
  123. // The connection returned from Dial must not be in a special state
  124. // (subscribed to pubsub channel, transaction started, ...).
  125. DialContext func(ctx context.Context) (Conn, error)
  126. // TestOnBorrow is an optional application supplied function for checking
  127. // the health of an idle connection before the connection is used again by
  128. // the application. Argument t is the time that the connection was returned
  129. // to the pool. If the function returns an error, then the connection is
  130. // closed.
  131. TestOnBorrow func(c Conn, t time.Time) error
  132. // Maximum number of idle connections in the pool.
  133. MaxIdle int
  134. // Maximum number of connections allocated by the pool at a given time.
  135. // When zero, there is no limit on the number of connections in the pool.
  136. MaxActive int
  137. // Close connections after remaining idle for this duration. If the value
  138. // is zero, then idle connections are not closed. Applications should set
  139. // the timeout to a value less than the server's timeout.
  140. IdleTimeout time.Duration
  141. // If Wait is true and the pool is at the MaxActive limit, then Get() waits
  142. // for a connection to be returned to the pool before returning.
  143. Wait bool
  144. // Close connections older than this duration. If the value is zero, then
  145. // the pool does not close connections based on age.
  146. MaxConnLifetime time.Duration
  147. mu sync.Mutex // mu protects the following fields
  148. closed bool // set to true when the pool is closed.
  149. active int // the number of open connections in the pool
  150. initOnce sync.Once // the init ch once func
  151. ch chan struct{} // limits open connections when p.Wait is true
  152. idle idleList // idle connections
  153. waitCount int64 // total number of connections waited for.
  154. waitDuration time.Duration // total time waited for new connections.
  155. }
  156. // NewPool creates a new pool.
  157. //
  158. // Deprecated: Initialize the Pool directly as shown in the example.
  159. func NewPool(newFn func() (Conn, error), maxIdle int) *Pool {
  160. return &Pool{Dial: newFn, MaxIdle: maxIdle}
  161. }
  162. // Get gets a connection. The application must close the returned connection.
  163. // This method always returns a valid connection so that applications can defer
  164. // error handling to the first use of the connection. If there is an error
  165. // getting an underlying connection, then the connection Err, Do, Send, Flush
  166. // and Receive methods return that error.
  167. func (p *Pool) Get() Conn {
  168. // GetContext returns errorConn in the first argument when an error occurs.
  169. c, _ := p.GetContext(context.Background())
  170. return c
  171. }
  172. // GetContext gets a connection using the provided context.
  173. //
  174. // The provided Context must be non-nil. If the context expires before the
  175. // connection is complete, an error is returned. Any expiration on the context
  176. // will not affect the returned connection.
  177. //
  178. // If the function completes without error, then the application must close the
  179. // returned connection.
  180. func (p *Pool) GetContext(ctx context.Context) (Conn, error) {
  181. // Wait until there is a vacant connection in the pool.
  182. waited, err := p.waitVacantConn(ctx)
  183. if err != nil {
  184. return errorConn{err}, err
  185. }
  186. p.mu.Lock()
  187. if waited > 0 {
  188. p.waitCount++
  189. p.waitDuration += waited
  190. }
  191. // Prune stale connections at the back of the idle list.
  192. if p.IdleTimeout > 0 {
  193. n := p.idle.count
  194. for i := 0; i < n && p.idle.back != nil && p.idle.back.t.Add(p.IdleTimeout).Before(nowFunc()); i++ {
  195. pc := p.idle.back
  196. p.idle.popBack()
  197. p.mu.Unlock()
  198. pc.c.Close()
  199. p.mu.Lock()
  200. p.active--
  201. }
  202. }
  203. // Get idle connection from the front of idle list.
  204. for p.idle.front != nil {
  205. pc := p.idle.front
  206. p.idle.popFront()
  207. p.mu.Unlock()
  208. if (p.TestOnBorrow == nil || p.TestOnBorrow(pc.c, pc.t) == nil) &&
  209. (p.MaxConnLifetime == 0 || nowFunc().Sub(pc.created) < p.MaxConnLifetime) {
  210. return &activeConn{p: p, pc: pc}, nil
  211. }
  212. pc.c.Close()
  213. p.mu.Lock()
  214. p.active--
  215. }
  216. // Check for pool closed before dialing a new connection.
  217. if p.closed {
  218. p.mu.Unlock()
  219. err := errors.New("redigo: get on closed pool")
  220. return errorConn{err}, err
  221. }
  222. // Handle limit for p.Wait == false.
  223. if !p.Wait && p.MaxActive > 0 && p.active >= p.MaxActive {
  224. p.mu.Unlock()
  225. return errorConn{ErrPoolExhausted}, ErrPoolExhausted
  226. }
  227. p.active++
  228. p.mu.Unlock()
  229. c, err := p.dial(ctx)
  230. if err != nil {
  231. p.mu.Lock()
  232. p.active--
  233. if p.ch != nil && !p.closed {
  234. p.ch <- struct{}{}
  235. }
  236. p.mu.Unlock()
  237. return errorConn{err}, err
  238. }
  239. return &activeConn{p: p, pc: &poolConn{c: c, created: nowFunc()}}, nil
  240. }
  241. // PoolStats contains pool statistics.
  242. type PoolStats struct {
  243. // ActiveCount is the number of connections in the pool. The count includes
  244. // idle connections and connections in use.
  245. ActiveCount int
  246. // IdleCount is the number of idle connections in the pool.
  247. IdleCount int
  248. // WaitCount is the total number of connections waited for.
  249. // This value is currently not guaranteed to be 100% accurate.
  250. WaitCount int64
  251. // WaitDuration is the total time blocked waiting for a new connection.
  252. // This value is currently not guaranteed to be 100% accurate.
  253. WaitDuration time.Duration
  254. }
  255. // Stats returns pool's statistics.
  256. func (p *Pool) Stats() PoolStats {
  257. p.mu.Lock()
  258. stats := PoolStats{
  259. ActiveCount: p.active,
  260. IdleCount: p.idle.count,
  261. WaitCount: p.waitCount,
  262. WaitDuration: p.waitDuration,
  263. }
  264. p.mu.Unlock()
  265. return stats
  266. }
  267. // ActiveCount returns the number of connections in the pool. The count
  268. // includes idle connections and connections in use.
  269. func (p *Pool) ActiveCount() int {
  270. p.mu.Lock()
  271. active := p.active
  272. p.mu.Unlock()
  273. return active
  274. }
  275. // IdleCount returns the number of idle connections in the pool.
  276. func (p *Pool) IdleCount() int {
  277. p.mu.Lock()
  278. idle := p.idle.count
  279. p.mu.Unlock()
  280. return idle
  281. }
  282. // Close releases the resources used by the pool.
  283. func (p *Pool) Close() error {
  284. p.mu.Lock()
  285. if p.closed {
  286. p.mu.Unlock()
  287. return nil
  288. }
  289. p.closed = true
  290. p.active -= p.idle.count
  291. pc := p.idle.front
  292. p.idle.count = 0
  293. p.idle.front, p.idle.back = nil, nil
  294. if p.ch != nil {
  295. close(p.ch)
  296. }
  297. p.mu.Unlock()
  298. for ; pc != nil; pc = pc.next {
  299. pc.c.Close()
  300. }
  301. return nil
  302. }
  303. func (p *Pool) lazyInit() {
  304. p.initOnce.Do(func() {
  305. p.ch = make(chan struct{}, p.MaxActive)
  306. if p.closed {
  307. close(p.ch)
  308. } else {
  309. for i := 0; i < p.MaxActive; i++ {
  310. p.ch <- struct{}{}
  311. }
  312. }
  313. })
  314. }
  315. // waitVacantConn waits for a vacant connection in pool if waiting
  316. // is enabled and pool size is limited, otherwise returns instantly.
  317. // If ctx expires before that, an error is returned.
  318. //
  319. // If there were no vacant connection in the pool right away it returns the time spent waiting
  320. // for that connection to appear in the pool.
  321. func (p *Pool) waitVacantConn(ctx context.Context) (waited time.Duration, err error) {
  322. if !p.Wait || p.MaxActive <= 0 {
  323. // No wait or no connection limit.
  324. return 0, nil
  325. }
  326. p.lazyInit()
  327. // wait indicates if we believe it will block so its not 100% accurate
  328. // however for stats it should be good enough.
  329. wait := len(p.ch) == 0
  330. var start time.Time
  331. if wait {
  332. start = time.Now()
  333. }
  334. select {
  335. case <-p.ch:
  336. // Additionally check that context hasn't expired while we were waiting,
  337. // because `select` picks a random `case` if several of them are "ready".
  338. select {
  339. case <-ctx.Done():
  340. p.ch <- struct{}{}
  341. return 0, ctx.Err()
  342. default:
  343. }
  344. case <-ctx.Done():
  345. return 0, ctx.Err()
  346. }
  347. if wait {
  348. return time.Since(start), nil
  349. }
  350. return 0, nil
  351. }
  352. func (p *Pool) dial(ctx context.Context) (Conn, error) {
  353. if p.DialContext != nil {
  354. return p.DialContext(ctx)
  355. }
  356. if p.Dial != nil {
  357. return p.Dial()
  358. }
  359. return nil, errors.New("redigo: must pass Dial or DialContext to pool")
  360. }
  361. func (p *Pool) put(pc *poolConn, forceClose bool) error {
  362. p.mu.Lock()
  363. if !p.closed && !forceClose {
  364. pc.t = nowFunc()
  365. p.idle.pushFront(pc)
  366. if p.idle.count > p.MaxIdle {
  367. pc = p.idle.back
  368. p.idle.popBack()
  369. } else {
  370. pc = nil
  371. }
  372. }
  373. if pc != nil {
  374. p.mu.Unlock()
  375. pc.c.Close()
  376. p.mu.Lock()
  377. p.active--
  378. }
  379. if p.ch != nil && !p.closed {
  380. p.ch <- struct{}{}
  381. }
  382. p.mu.Unlock()
  383. return nil
  384. }
  385. type activeConn struct {
  386. p *Pool
  387. pc *poolConn
  388. state int
  389. }
  390. var (
  391. sentinel []byte
  392. sentinelOnce sync.Once
  393. )
  394. func initSentinel() {
  395. p := make([]byte, 64)
  396. if _, err := rand.Read(p); err == nil {
  397. sentinel = p
  398. } else {
  399. h := sha1.New()
  400. io.WriteString(h, "Oops, rand failed. Use time instead.") // nolint: errcheck
  401. io.WriteString(h, strconv.FormatInt(time.Now().UnixNano(), 10)) // nolint: errcheck
  402. sentinel = h.Sum(nil)
  403. }
  404. }
  405. func (ac *activeConn) firstError(errs ...error) error {
  406. for _, err := range errs[:len(errs)-1] {
  407. if err != nil {
  408. return err
  409. }
  410. }
  411. return errs[len(errs)-1]
  412. }
  413. func (ac *activeConn) Close() (err error) {
  414. pc := ac.pc
  415. if pc == nil {
  416. return nil
  417. }
  418. ac.pc = nil
  419. if ac.state&connectionMultiState != 0 {
  420. err = pc.c.Send("DISCARD")
  421. ac.state &^= (connectionMultiState | connectionWatchState)
  422. } else if ac.state&connectionWatchState != 0 {
  423. err = pc.c.Send("UNWATCH")
  424. ac.state &^= connectionWatchState
  425. }
  426. if ac.state&connectionSubscribeState != 0 {
  427. err = ac.firstError(err,
  428. pc.c.Send("UNSUBSCRIBE"),
  429. pc.c.Send("PUNSUBSCRIBE"),
  430. )
  431. // To detect the end of the message stream, ask the server to echo
  432. // a sentinel value and read until we see that value.
  433. sentinelOnce.Do(initSentinel)
  434. err = ac.firstError(err,
  435. pc.c.Send("ECHO", sentinel),
  436. pc.c.Flush(),
  437. )
  438. for {
  439. p, err2 := pc.c.Receive()
  440. if err2 != nil {
  441. err = ac.firstError(err, err2)
  442. break
  443. }
  444. if p, ok := p.([]byte); ok && bytes.Equal(p, sentinel) {
  445. ac.state &^= connectionSubscribeState
  446. break
  447. }
  448. }
  449. }
  450. _, err2 := pc.c.Do("")
  451. return ac.firstError(
  452. err,
  453. err2,
  454. ac.p.put(pc, ac.state != 0 || pc.c.Err() != nil),
  455. )
  456. }
  457. func (ac *activeConn) Err() error {
  458. pc := ac.pc
  459. if pc == nil {
  460. return errConnClosed
  461. }
  462. return pc.c.Err()
  463. }
  464. func (ac *activeConn) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  465. pc := ac.pc
  466. if pc == nil {
  467. return nil, errConnClosed
  468. }
  469. ci := lookupCommandInfo(commandName)
  470. ac.state = (ac.state | ci.Set) &^ ci.Clear
  471. return pc.c.Do(commandName, args...)
  472. }
  473. func (ac *activeConn) DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (reply interface{}, err error) {
  474. pc := ac.pc
  475. if pc == nil {
  476. return nil, errConnClosed
  477. }
  478. cwt, ok := pc.c.(ConnWithTimeout)
  479. if !ok {
  480. return nil, errTimeoutNotSupported
  481. }
  482. ci := lookupCommandInfo(commandName)
  483. ac.state = (ac.state | ci.Set) &^ ci.Clear
  484. return cwt.DoWithTimeout(timeout, commandName, args...)
  485. }
  486. func (ac *activeConn) Send(commandName string, args ...interface{}) error {
  487. pc := ac.pc
  488. if pc == nil {
  489. return errConnClosed
  490. }
  491. ci := lookupCommandInfo(commandName)
  492. ac.state = (ac.state | ci.Set) &^ ci.Clear
  493. return pc.c.Send(commandName, args...)
  494. }
  495. func (ac *activeConn) Flush() error {
  496. pc := ac.pc
  497. if pc == nil {
  498. return errConnClosed
  499. }
  500. return pc.c.Flush()
  501. }
  502. func (ac *activeConn) Receive() (reply interface{}, err error) {
  503. pc := ac.pc
  504. if pc == nil {
  505. return nil, errConnClosed
  506. }
  507. return pc.c.Receive()
  508. }
  509. func (ac *activeConn) ReceiveWithTimeout(timeout time.Duration) (reply interface{}, err error) {
  510. pc := ac.pc
  511. if pc == nil {
  512. return nil, errConnClosed
  513. }
  514. cwt, ok := pc.c.(ConnWithTimeout)
  515. if !ok {
  516. return nil, errTimeoutNotSupported
  517. }
  518. return cwt.ReceiveWithTimeout(timeout)
  519. }
  520. type errorConn struct{ err error }
  521. func (ec errorConn) Do(string, ...interface{}) (interface{}, error) { return nil, ec.err }
  522. func (ec errorConn) DoWithTimeout(time.Duration, string, ...interface{}) (interface{}, error) {
  523. return nil, ec.err
  524. }
  525. func (ec errorConn) Send(string, ...interface{}) error { return ec.err }
  526. func (ec errorConn) Err() error { return ec.err }
  527. func (ec errorConn) Close() error { return nil }
  528. func (ec errorConn) Flush() error { return ec.err }
  529. func (ec errorConn) Receive() (interface{}, error) { return nil, ec.err }
  530. func (ec errorConn) ReceiveWithTimeout(time.Duration) (interface{}, error) { return nil, ec.err }
  531. type idleList struct {
  532. count int
  533. front, back *poolConn
  534. }
  535. type poolConn struct {
  536. c Conn
  537. t time.Time
  538. created time.Time
  539. next, prev *poolConn
  540. }
  541. func (l *idleList) pushFront(pc *poolConn) {
  542. pc.next = l.front
  543. pc.prev = nil
  544. if l.count == 0 {
  545. l.back = pc
  546. } else {
  547. l.front.prev = pc
  548. }
  549. l.front = pc
  550. l.count++
  551. }
  552. func (l *idleList) popFront() {
  553. pc := l.front
  554. l.count--
  555. if l.count == 0 {
  556. l.front, l.back = nil, nil
  557. } else {
  558. pc.next.prev = nil
  559. l.front = pc.next
  560. }
  561. pc.next, pc.prev = nil, nil
  562. }
  563. func (l *idleList) popBack() {
  564. pc := l.back
  565. l.count--
  566. if l.count == 0 {
  567. l.front, l.back = nil, nil
  568. } else {
  569. pc.prev.next = nil
  570. l.back = pc.prev
  571. }
  572. pc.next, pc.prev = nil, nil
  573. }