pool_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. // Copyright 2011 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_test
  15. import (
  16. "errors"
  17. "io"
  18. "reflect"
  19. "sync"
  20. "testing"
  21. "time"
  22. "github.com/garyburd/redigo/redis"
  23. )
  24. type poolTestConn struct {
  25. d *poolDialer
  26. err error
  27. redis.Conn
  28. }
  29. func (c *poolTestConn) Close() error {
  30. c.d.mu.Lock()
  31. c.d.open -= 1
  32. c.d.mu.Unlock()
  33. return c.Conn.Close()
  34. }
  35. func (c *poolTestConn) Err() error { return c.err }
  36. func (c *poolTestConn) Do(commandName string, args ...interface{}) (interface{}, error) {
  37. if commandName == "ERR" {
  38. c.err = args[0].(error)
  39. commandName = "PING"
  40. }
  41. if commandName != "" {
  42. c.d.commands = append(c.d.commands, commandName)
  43. }
  44. return c.Conn.Do(commandName, args...)
  45. }
  46. func (c *poolTestConn) Send(commandName string, args ...interface{}) error {
  47. c.d.commands = append(c.d.commands, commandName)
  48. return c.Conn.Send(commandName, args...)
  49. }
  50. type poolDialer struct {
  51. mu sync.Mutex
  52. t *testing.T
  53. dialed int
  54. open int
  55. commands []string
  56. dialErr error
  57. }
  58. func (d *poolDialer) dial() (redis.Conn, error) {
  59. d.mu.Lock()
  60. d.dialed += 1
  61. dialErr := d.dialErr
  62. d.mu.Unlock()
  63. if dialErr != nil {
  64. return nil, d.dialErr
  65. }
  66. c, err := redis.DialDefaultServer()
  67. if err != nil {
  68. return nil, err
  69. }
  70. d.mu.Lock()
  71. d.open += 1
  72. d.mu.Unlock()
  73. return &poolTestConn{d: d, Conn: c}, nil
  74. }
  75. func (d *poolDialer) check(message string, p *redis.Pool, dialed, open, inuse int) {
  76. d.mu.Lock()
  77. if d.dialed != dialed {
  78. d.t.Errorf("%s: dialed=%d, want %d", message, d.dialed, dialed)
  79. }
  80. if d.open != open {
  81. d.t.Errorf("%s: open=%d, want %d", message, d.open, open)
  82. }
  83. stats := p.Stats()
  84. if stats.ActiveCount != open {
  85. d.t.Errorf("%s: active=%d, want %d", message, stats.ActiveCount, open)
  86. }
  87. if stats.IdleCount != open-inuse {
  88. d.t.Errorf("%s: idle=%d, want %d", message, stats.IdleCount, open-inuse)
  89. }
  90. d.mu.Unlock()
  91. }
  92. func TestPoolReuse(t *testing.T) {
  93. d := poolDialer{t: t}
  94. p := &redis.Pool{
  95. MaxIdle: 2,
  96. Dial: d.dial,
  97. }
  98. for i := 0; i < 10; i++ {
  99. c1 := p.Get()
  100. c1.Do("PING")
  101. c2 := p.Get()
  102. c2.Do("PING")
  103. c1.Close()
  104. c2.Close()
  105. }
  106. d.check("before close", p, 2, 2, 0)
  107. p.Close()
  108. d.check("after close", p, 2, 0, 0)
  109. }
  110. func TestPoolMaxIdle(t *testing.T) {
  111. d := poolDialer{t: t}
  112. p := &redis.Pool{
  113. MaxIdle: 2,
  114. Dial: d.dial,
  115. }
  116. defer p.Close()
  117. for i := 0; i < 10; i++ {
  118. c1 := p.Get()
  119. c1.Do("PING")
  120. c2 := p.Get()
  121. c2.Do("PING")
  122. c3 := p.Get()
  123. c3.Do("PING")
  124. c1.Close()
  125. c2.Close()
  126. c3.Close()
  127. }
  128. d.check("before close", p, 12, 2, 0)
  129. p.Close()
  130. d.check("after close", p, 12, 0, 0)
  131. }
  132. func TestPoolError(t *testing.T) {
  133. d := poolDialer{t: t}
  134. p := &redis.Pool{
  135. MaxIdle: 2,
  136. Dial: d.dial,
  137. }
  138. defer p.Close()
  139. c := p.Get()
  140. c.Do("ERR", io.EOF)
  141. if c.Err() == nil {
  142. t.Errorf("expected c.Err() != nil")
  143. }
  144. c.Close()
  145. c = p.Get()
  146. c.Do("ERR", io.EOF)
  147. c.Close()
  148. d.check(".", p, 2, 0, 0)
  149. }
  150. func TestPoolClose(t *testing.T) {
  151. d := poolDialer{t: t}
  152. p := &redis.Pool{
  153. MaxIdle: 2,
  154. Dial: d.dial,
  155. }
  156. defer p.Close()
  157. c1 := p.Get()
  158. c1.Do("PING")
  159. c2 := p.Get()
  160. c2.Do("PING")
  161. c3 := p.Get()
  162. c3.Do("PING")
  163. c1.Close()
  164. if _, err := c1.Do("PING"); err == nil {
  165. t.Errorf("expected error after connection closed")
  166. }
  167. c2.Close()
  168. c2.Close()
  169. p.Close()
  170. d.check("after pool close", p, 3, 1, 1)
  171. if _, err := c1.Do("PING"); err == nil {
  172. t.Errorf("expected error after connection and pool closed")
  173. }
  174. c3.Close()
  175. d.check("after conn close", p, 3, 0, 0)
  176. c1 = p.Get()
  177. if _, err := c1.Do("PING"); err == nil {
  178. t.Errorf("expected error after pool closed")
  179. }
  180. }
  181. func TestPoolTimeout(t *testing.T) {
  182. d := poolDialer{t: t}
  183. p := &redis.Pool{
  184. MaxIdle: 2,
  185. IdleTimeout: 300 * time.Second,
  186. Dial: d.dial,
  187. }
  188. defer p.Close()
  189. now := time.Now()
  190. redis.SetNowFunc(func() time.Time { return now })
  191. defer redis.SetNowFunc(time.Now)
  192. c := p.Get()
  193. c.Do("PING")
  194. c.Close()
  195. d.check("1", p, 1, 1, 0)
  196. now = now.Add(p.IdleTimeout)
  197. c = p.Get()
  198. c.Do("PING")
  199. c.Close()
  200. d.check("2", p, 2, 1, 0)
  201. }
  202. func TestPoolConcurrenSendReceive(t *testing.T) {
  203. p := &redis.Pool{
  204. Dial: redis.DialDefaultServer,
  205. }
  206. defer p.Close()
  207. c := p.Get()
  208. done := make(chan error, 1)
  209. go func() {
  210. _, err := c.Receive()
  211. done <- err
  212. }()
  213. c.Send("PING")
  214. c.Flush()
  215. err := <-done
  216. if err != nil {
  217. t.Fatalf("Receive() returned error %v", err)
  218. }
  219. _, err = c.Do("")
  220. if err != nil {
  221. t.Fatalf("Do() returned error %v", err)
  222. }
  223. c.Close()
  224. }
  225. func TestPoolBorrowCheck(t *testing.T) {
  226. d := poolDialer{t: t}
  227. p := &redis.Pool{
  228. MaxIdle: 2,
  229. Dial: d.dial,
  230. TestOnBorrow: func(redis.Conn, time.Time) error { return redis.Error("BLAH") },
  231. }
  232. defer p.Close()
  233. for i := 0; i < 10; i++ {
  234. c := p.Get()
  235. c.Do("PING")
  236. c.Close()
  237. }
  238. d.check("1", p, 10, 1, 0)
  239. }
  240. func TestPoolMaxActive(t *testing.T) {
  241. d := poolDialer{t: t}
  242. p := &redis.Pool{
  243. MaxIdle: 2,
  244. MaxActive: 2,
  245. Dial: d.dial,
  246. }
  247. defer p.Close()
  248. c1 := p.Get()
  249. c1.Do("PING")
  250. c2 := p.Get()
  251. c2.Do("PING")
  252. d.check("1", p, 2, 2, 2)
  253. c3 := p.Get()
  254. if _, err := c3.Do("PING"); err != redis.ErrPoolExhausted {
  255. t.Errorf("expected pool exhausted")
  256. }
  257. c3.Close()
  258. d.check("2", p, 2, 2, 2)
  259. c2.Close()
  260. d.check("3", p, 2, 2, 1)
  261. c3 = p.Get()
  262. if _, err := c3.Do("PING"); err != nil {
  263. t.Errorf("expected good channel, err=%v", err)
  264. }
  265. c3.Close()
  266. d.check("4", p, 2, 2, 1)
  267. }
  268. func TestPoolMonitorCleanup(t *testing.T) {
  269. d := poolDialer{t: t}
  270. p := &redis.Pool{
  271. MaxIdle: 2,
  272. MaxActive: 2,
  273. Dial: d.dial,
  274. }
  275. defer p.Close()
  276. c := p.Get()
  277. c.Send("MONITOR")
  278. c.Close()
  279. d.check("", p, 1, 0, 0)
  280. }
  281. func TestPoolPubSubCleanup(t *testing.T) {
  282. d := poolDialer{t: t}
  283. p := &redis.Pool{
  284. MaxIdle: 2,
  285. MaxActive: 2,
  286. Dial: d.dial,
  287. }
  288. defer p.Close()
  289. c := p.Get()
  290. c.Send("SUBSCRIBE", "x")
  291. c.Close()
  292. want := []string{"SUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", "ECHO"}
  293. if !reflect.DeepEqual(d.commands, want) {
  294. t.Errorf("got commands %v, want %v", d.commands, want)
  295. }
  296. d.commands = nil
  297. c = p.Get()
  298. c.Send("PSUBSCRIBE", "x*")
  299. c.Close()
  300. want = []string{"PSUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", "ECHO"}
  301. if !reflect.DeepEqual(d.commands, want) {
  302. t.Errorf("got commands %v, want %v", d.commands, want)
  303. }
  304. d.commands = nil
  305. }
  306. func TestPoolTransactionCleanup(t *testing.T) {
  307. d := poolDialer{t: t}
  308. p := &redis.Pool{
  309. MaxIdle: 2,
  310. MaxActive: 2,
  311. Dial: d.dial,
  312. }
  313. defer p.Close()
  314. c := p.Get()
  315. c.Do("WATCH", "key")
  316. c.Do("PING")
  317. c.Close()
  318. want := []string{"WATCH", "PING", "UNWATCH"}
  319. if !reflect.DeepEqual(d.commands, want) {
  320. t.Errorf("got commands %v, want %v", d.commands, want)
  321. }
  322. d.commands = nil
  323. c = p.Get()
  324. c.Do("WATCH", "key")
  325. c.Do("UNWATCH")
  326. c.Do("PING")
  327. c.Close()
  328. want = []string{"WATCH", "UNWATCH", "PING"}
  329. if !reflect.DeepEqual(d.commands, want) {
  330. t.Errorf("got commands %v, want %v", d.commands, want)
  331. }
  332. d.commands = nil
  333. c = p.Get()
  334. c.Do("WATCH", "key")
  335. c.Do("MULTI")
  336. c.Do("PING")
  337. c.Close()
  338. want = []string{"WATCH", "MULTI", "PING", "DISCARD"}
  339. if !reflect.DeepEqual(d.commands, want) {
  340. t.Errorf("got commands %v, want %v", d.commands, want)
  341. }
  342. d.commands = nil
  343. c = p.Get()
  344. c.Do("WATCH", "key")
  345. c.Do("MULTI")
  346. c.Do("DISCARD")
  347. c.Do("PING")
  348. c.Close()
  349. want = []string{"WATCH", "MULTI", "DISCARD", "PING"}
  350. if !reflect.DeepEqual(d.commands, want) {
  351. t.Errorf("got commands %v, want %v", d.commands, want)
  352. }
  353. d.commands = nil
  354. c = p.Get()
  355. c.Do("WATCH", "key")
  356. c.Do("MULTI")
  357. c.Do("EXEC")
  358. c.Do("PING")
  359. c.Close()
  360. want = []string{"WATCH", "MULTI", "EXEC", "PING"}
  361. if !reflect.DeepEqual(d.commands, want) {
  362. t.Errorf("got commands %v, want %v", d.commands, want)
  363. }
  364. d.commands = nil
  365. }
  366. func startGoroutines(p *redis.Pool, cmd string, args ...interface{}) chan error {
  367. errs := make(chan error, 10)
  368. for i := 0; i < cap(errs); i++ {
  369. go func() {
  370. c := p.Get()
  371. _, err := c.Do(cmd, args...)
  372. c.Close()
  373. errs <- err
  374. }()
  375. }
  376. // Wait for goroutines to block.
  377. time.Sleep(time.Second / 4)
  378. return errs
  379. }
  380. func TestWaitPool(t *testing.T) {
  381. d := poolDialer{t: t}
  382. p := &redis.Pool{
  383. MaxIdle: 1,
  384. MaxActive: 1,
  385. Dial: d.dial,
  386. Wait: true,
  387. }
  388. defer p.Close()
  389. c := p.Get()
  390. errs := startGoroutines(p, "PING")
  391. d.check("before close", p, 1, 1, 1)
  392. c.Close()
  393. timeout := time.After(2 * time.Second)
  394. for i := 0; i < cap(errs); i++ {
  395. select {
  396. case err := <-errs:
  397. if err != nil {
  398. t.Fatal(err)
  399. }
  400. case <-timeout:
  401. t.Fatalf("timeout waiting for blocked goroutine %d", i)
  402. }
  403. }
  404. d.check("done", p, 1, 1, 0)
  405. }
  406. func TestWaitPoolClose(t *testing.T) {
  407. d := poolDialer{t: t}
  408. p := &redis.Pool{
  409. MaxIdle: 1,
  410. MaxActive: 1,
  411. Dial: d.dial,
  412. Wait: true,
  413. }
  414. defer p.Close()
  415. c := p.Get()
  416. if _, err := c.Do("PING"); err != nil {
  417. t.Fatal(err)
  418. }
  419. errs := startGoroutines(p, "PING")
  420. d.check("before close", p, 1, 1, 1)
  421. p.Close()
  422. timeout := time.After(2 * time.Second)
  423. for i := 0; i < cap(errs); i++ {
  424. select {
  425. case err := <-errs:
  426. switch err {
  427. case nil:
  428. t.Fatal("blocked goroutine did not get error")
  429. case redis.ErrPoolExhausted:
  430. t.Fatal("blocked goroutine got pool exhausted error")
  431. }
  432. case <-timeout:
  433. t.Fatal("timeout waiting for blocked goroutine")
  434. }
  435. }
  436. c.Close()
  437. d.check("done", p, 1, 0, 0)
  438. }
  439. func TestWaitPoolCommandError(t *testing.T) {
  440. testErr := errors.New("test")
  441. d := poolDialer{t: t}
  442. p := &redis.Pool{
  443. MaxIdle: 1,
  444. MaxActive: 1,
  445. Dial: d.dial,
  446. Wait: true,
  447. }
  448. defer p.Close()
  449. c := p.Get()
  450. errs := startGoroutines(p, "ERR", testErr)
  451. d.check("before close", p, 1, 1, 1)
  452. c.Close()
  453. timeout := time.After(2 * time.Second)
  454. for i := 0; i < cap(errs); i++ {
  455. select {
  456. case err := <-errs:
  457. if err != nil {
  458. t.Fatal(err)
  459. }
  460. case <-timeout:
  461. t.Fatalf("timeout waiting for blocked goroutine %d", i)
  462. }
  463. }
  464. d.check("done", p, cap(errs), 0, 0)
  465. }
  466. func TestWaitPoolDialError(t *testing.T) {
  467. testErr := errors.New("test")
  468. d := poolDialer{t: t}
  469. p := &redis.Pool{
  470. MaxIdle: 1,
  471. MaxActive: 1,
  472. Dial: d.dial,
  473. Wait: true,
  474. }
  475. defer p.Close()
  476. c := p.Get()
  477. errs := startGoroutines(p, "ERR", testErr)
  478. d.check("before close", p, 1, 1, 1)
  479. d.dialErr = errors.New("dial")
  480. c.Close()
  481. nilCount := 0
  482. errCount := 0
  483. timeout := time.After(2 * time.Second)
  484. for i := 0; i < cap(errs); i++ {
  485. select {
  486. case err := <-errs:
  487. switch err {
  488. case nil:
  489. nilCount++
  490. case d.dialErr:
  491. errCount++
  492. default:
  493. t.Fatalf("expected dial error or nil, got %v", err)
  494. }
  495. case <-timeout:
  496. t.Fatalf("timeout waiting for blocked goroutine %d", i)
  497. }
  498. }
  499. if nilCount != 1 {
  500. t.Errorf("expected one nil error, got %d", nilCount)
  501. }
  502. if errCount != cap(errs)-1 {
  503. t.Errorf("expected %d dial errors, got %d", cap(errs)-1, errCount)
  504. }
  505. d.check("done", p, cap(errs), 0, 0)
  506. }
  507. // Borrowing requires us to iterate over the idle connections, unlock the pool,
  508. // and perform a blocking operation to check the connection still works. If
  509. // TestOnBorrow fails, we must reacquire the lock and continue iteration. This
  510. // test ensures that iteration will work correctly if multiple threads are
  511. // iterating simultaneously.
  512. func TestLocking_TestOnBorrowFails_PoolDoesntCrash(t *testing.T) {
  513. const count = 100
  514. // First we'll Create a pool where the pilfering of idle connections fails.
  515. d := poolDialer{t: t}
  516. p := &redis.Pool{
  517. MaxIdle: count,
  518. MaxActive: count,
  519. Dial: d.dial,
  520. TestOnBorrow: func(c redis.Conn, t time.Time) error {
  521. return errors.New("No way back into the real world.")
  522. },
  523. }
  524. defer p.Close()
  525. // Fill the pool with idle connections.
  526. conns := make([]redis.Conn, count)
  527. for i := range conns {
  528. conns[i] = p.Get()
  529. }
  530. for i := range conns {
  531. conns[i].Close()
  532. }
  533. // Spawn a bunch of goroutines to thrash the pool.
  534. var wg sync.WaitGroup
  535. wg.Add(count)
  536. for i := 0; i < count; i++ {
  537. go func() {
  538. c := p.Get()
  539. if c.Err() != nil {
  540. t.Errorf("pool get failed: %v", c.Err())
  541. }
  542. c.Close()
  543. wg.Done()
  544. }()
  545. }
  546. wg.Wait()
  547. if d.dialed != count*2 {
  548. t.Errorf("Expected %d dials, got %d", count*2, d.dialed)
  549. }
  550. }
  551. func BenchmarkPoolGet(b *testing.B) {
  552. b.StopTimer()
  553. p := redis.Pool{Dial: redis.DialDefaultServer, MaxIdle: 2}
  554. c := p.Get()
  555. if err := c.Err(); err != nil {
  556. b.Fatal(err)
  557. }
  558. c.Close()
  559. defer p.Close()
  560. b.StartTimer()
  561. for i := 0; i < b.N; i++ {
  562. c = p.Get()
  563. c.Close()
  564. }
  565. }
  566. func BenchmarkPoolGetErr(b *testing.B) {
  567. b.StopTimer()
  568. p := redis.Pool{Dial: redis.DialDefaultServer, MaxIdle: 2}
  569. c := p.Get()
  570. if err := c.Err(); err != nil {
  571. b.Fatal(err)
  572. }
  573. c.Close()
  574. defer p.Close()
  575. b.StartTimer()
  576. for i := 0; i < b.N; i++ {
  577. c = p.Get()
  578. if err := c.Err(); err != nil {
  579. b.Fatal(err)
  580. }
  581. c.Close()
  582. }
  583. }
  584. func BenchmarkPoolGetPing(b *testing.B) {
  585. b.StopTimer()
  586. p := redis.Pool{Dial: redis.DialDefaultServer, MaxIdle: 2}
  587. c := p.Get()
  588. if err := c.Err(); err != nil {
  589. b.Fatal(err)
  590. }
  591. c.Close()
  592. defer p.Close()
  593. b.StartTimer()
  594. for i := 0; i < b.N; i++ {
  595. c = p.Get()
  596. if _, err := c.Do("PING"); err != nil {
  597. b.Fatal(err)
  598. }
  599. c.Close()
  600. }
  601. }