pool.go 14 KB

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