pool_test.go 14 KB

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