pool_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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. if active := p.ActiveCount(); active != open {
  84. d.t.Errorf("%s: active=%d, want %d", message, active, open)
  85. }
  86. if idle := p.IdleCount(); idle != open-inuse {
  87. d.t.Errorf("%s: idle=%d, want %d", message, idle, open-inuse)
  88. }
  89. d.mu.Unlock()
  90. }
  91. func TestPoolReuse(t *testing.T) {
  92. d := poolDialer{t: t}
  93. p := &redis.Pool{
  94. MaxIdle: 2,
  95. Dial: d.dial,
  96. }
  97. for i := 0; i < 10; i++ {
  98. c1 := p.Get()
  99. c1.Do("PING")
  100. c2 := p.Get()
  101. c2.Do("PING")
  102. c1.Close()
  103. c2.Close()
  104. }
  105. d.check("before close", p, 2, 2, 0)
  106. p.Close()
  107. d.check("after close", p, 2, 0, 0)
  108. }
  109. func TestPoolMaxIdle(t *testing.T) {
  110. d := poolDialer{t: t}
  111. p := &redis.Pool{
  112. MaxIdle: 2,
  113. Dial: d.dial,
  114. }
  115. defer p.Close()
  116. for i := 0; i < 10; i++ {
  117. c1 := p.Get()
  118. c1.Do("PING")
  119. c2 := p.Get()
  120. c2.Do("PING")
  121. c3 := p.Get()
  122. c3.Do("PING")
  123. c1.Close()
  124. c2.Close()
  125. c3.Close()
  126. }
  127. d.check("before close", p, 12, 2, 0)
  128. p.Close()
  129. d.check("after close", p, 12, 0, 0)
  130. }
  131. func TestPoolError(t *testing.T) {
  132. d := poolDialer{t: t}
  133. p := &redis.Pool{
  134. MaxIdle: 2,
  135. Dial: d.dial,
  136. }
  137. defer p.Close()
  138. c := p.Get()
  139. c.Do("ERR", io.EOF)
  140. if c.Err() == nil {
  141. t.Errorf("expected c.Err() != nil")
  142. }
  143. c.Close()
  144. c = p.Get()
  145. c.Do("ERR", io.EOF)
  146. c.Close()
  147. d.check(".", p, 2, 0, 0)
  148. }
  149. func TestPoolClose(t *testing.T) {
  150. d := poolDialer{t: t}
  151. p := &redis.Pool{
  152. MaxIdle: 2,
  153. Dial: d.dial,
  154. }
  155. defer p.Close()
  156. c1 := p.Get()
  157. c1.Do("PING")
  158. c2 := p.Get()
  159. c2.Do("PING")
  160. c3 := p.Get()
  161. c3.Do("PING")
  162. c1.Close()
  163. if _, err := c1.Do("PING"); err == nil {
  164. t.Errorf("expected error after connection closed")
  165. }
  166. c2.Close()
  167. c2.Close()
  168. p.Close()
  169. d.check("after pool close", p, 3, 1, 1)
  170. if _, err := c1.Do("PING"); err == nil {
  171. t.Errorf("expected error after connection and pool closed")
  172. }
  173. c3.Close()
  174. d.check("after conn close", p, 3, 0, 0)
  175. c1 = p.Get()
  176. if _, err := c1.Do("PING"); err == nil {
  177. t.Errorf("expected error after pool closed")
  178. }
  179. }
  180. func TestPoolTimeout(t *testing.T) {
  181. d := poolDialer{t: t}
  182. p := &redis.Pool{
  183. MaxIdle: 2,
  184. IdleTimeout: 300 * time.Second,
  185. Dial: d.dial,
  186. }
  187. defer p.Close()
  188. now := time.Now()
  189. redis.SetNowFunc(func() time.Time { return now })
  190. defer redis.SetNowFunc(time.Now)
  191. c := p.Get()
  192. c.Do("PING")
  193. c.Close()
  194. d.check("1", p, 1, 1, 0)
  195. now = now.Add(p.IdleTimeout)
  196. c = p.Get()
  197. c.Do("PING")
  198. c.Close()
  199. d.check("2", p, 2, 1, 0)
  200. }
  201. func TestPoolConcurrenSendReceive(t *testing.T) {
  202. p := &redis.Pool{
  203. Dial: redis.DialDefaultServer,
  204. }
  205. defer p.Close()
  206. c := p.Get()
  207. done := make(chan error, 1)
  208. go func() {
  209. _, err := c.Receive()
  210. done <- err
  211. }()
  212. c.Send("PING")
  213. c.Flush()
  214. err := <-done
  215. if err != nil {
  216. t.Fatalf("Receive() returned error %v", err)
  217. }
  218. _, err = c.Do("")
  219. if err != nil {
  220. t.Fatalf("Do() returned error %v", err)
  221. }
  222. c.Close()
  223. }
  224. func TestPoolBorrowCheck(t *testing.T) {
  225. d := poolDialer{t: t}
  226. p := &redis.Pool{
  227. MaxIdle: 2,
  228. Dial: d.dial,
  229. TestOnBorrow: func(redis.Conn, time.Time) error { return redis.Error("BLAH") },
  230. }
  231. defer p.Close()
  232. for i := 0; i < 10; i++ {
  233. c := p.Get()
  234. c.Do("PING")
  235. c.Close()
  236. }
  237. d.check("1", p, 10, 1, 0)
  238. }
  239. func TestPoolMaxActive(t *testing.T) {
  240. d := poolDialer{t: t}
  241. p := &redis.Pool{
  242. MaxIdle: 2,
  243. MaxActive: 2,
  244. Dial: d.dial,
  245. }
  246. defer p.Close()
  247. c1 := p.Get()
  248. c1.Do("PING")
  249. c2 := p.Get()
  250. c2.Do("PING")
  251. d.check("1", p, 2, 2, 2)
  252. c3 := p.Get()
  253. if _, err := c3.Do("PING"); err != redis.ErrPoolExhausted {
  254. t.Errorf("expected pool exhausted")
  255. }
  256. c3.Close()
  257. d.check("2", p, 2, 2, 2)
  258. c2.Close()
  259. d.check("3", p, 2, 2, 1)
  260. c3 = p.Get()
  261. if _, err := c3.Do("PING"); err != nil {
  262. t.Errorf("expected good channel, err=%v", err)
  263. }
  264. c3.Close()
  265. d.check("4", p, 2, 2, 1)
  266. }
  267. func TestPoolMonitorCleanup(t *testing.T) {
  268. d := poolDialer{t: t}
  269. p := &redis.Pool{
  270. MaxIdle: 2,
  271. MaxActive: 2,
  272. Dial: d.dial,
  273. }
  274. defer p.Close()
  275. c := p.Get()
  276. c.Send("MONITOR")
  277. c.Close()
  278. d.check("", p, 1, 0, 0)
  279. }
  280. func TestPoolPubSubCleanup(t *testing.T) {
  281. d := poolDialer{t: t}
  282. p := &redis.Pool{
  283. MaxIdle: 2,
  284. MaxActive: 2,
  285. Dial: d.dial,
  286. }
  287. defer p.Close()
  288. c := p.Get()
  289. c.Send("SUBSCRIBE", "x")
  290. c.Close()
  291. want := []string{"SUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", "ECHO"}
  292. if !reflect.DeepEqual(d.commands, want) {
  293. t.Errorf("got commands %v, want %v", d.commands, want)
  294. }
  295. d.commands = nil
  296. c = p.Get()
  297. c.Send("PSUBSCRIBE", "x*")
  298. c.Close()
  299. want = []string{"PSUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", "ECHO"}
  300. if !reflect.DeepEqual(d.commands, want) {
  301. t.Errorf("got commands %v, want %v", d.commands, want)
  302. }
  303. d.commands = nil
  304. }
  305. func TestPoolTransactionCleanup(t *testing.T) {
  306. d := poolDialer{t: t}
  307. p := &redis.Pool{
  308. MaxIdle: 2,
  309. MaxActive: 2,
  310. Dial: d.dial,
  311. }
  312. defer p.Close()
  313. c := p.Get()
  314. c.Do("WATCH", "key")
  315. c.Do("PING")
  316. c.Close()
  317. want := []string{"WATCH", "PING", "UNWATCH"}
  318. if !reflect.DeepEqual(d.commands, want) {
  319. t.Errorf("got commands %v, want %v", d.commands, want)
  320. }
  321. d.commands = nil
  322. c = p.Get()
  323. c.Do("WATCH", "key")
  324. c.Do("UNWATCH")
  325. c.Do("PING")
  326. c.Close()
  327. want = []string{"WATCH", "UNWATCH", "PING"}
  328. if !reflect.DeepEqual(d.commands, want) {
  329. t.Errorf("got commands %v, want %v", d.commands, want)
  330. }
  331. d.commands = nil
  332. c = p.Get()
  333. c.Do("WATCH", "key")
  334. c.Do("MULTI")
  335. c.Do("PING")
  336. c.Close()
  337. want = []string{"WATCH", "MULTI", "PING", "DISCARD"}
  338. if !reflect.DeepEqual(d.commands, want) {
  339. t.Errorf("got commands %v, want %v", d.commands, want)
  340. }
  341. d.commands = nil
  342. c = p.Get()
  343. c.Do("WATCH", "key")
  344. c.Do("MULTI")
  345. c.Do("DISCARD")
  346. c.Do("PING")
  347. c.Close()
  348. want = []string{"WATCH", "MULTI", "DISCARD", "PING"}
  349. if !reflect.DeepEqual(d.commands, want) {
  350. t.Errorf("got commands %v, want %v", d.commands, want)
  351. }
  352. d.commands = nil
  353. c = p.Get()
  354. c.Do("WATCH", "key")
  355. c.Do("MULTI")
  356. c.Do("EXEC")
  357. c.Do("PING")
  358. c.Close()
  359. want = []string{"WATCH", "MULTI", "EXEC", "PING"}
  360. if !reflect.DeepEqual(d.commands, want) {
  361. t.Errorf("got commands %v, want %v", d.commands, want)
  362. }
  363. d.commands = nil
  364. }
  365. func startGoroutines(p *redis.Pool, cmd string, args ...interface{}) chan error {
  366. errs := make(chan error, 10)
  367. for i := 0; i < cap(errs); i++ {
  368. go func() {
  369. c := p.Get()
  370. _, err := c.Do(cmd, args...)
  371. c.Close()
  372. errs <- err
  373. }()
  374. }
  375. // Wait for goroutines to block.
  376. time.Sleep(time.Second / 4)
  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. // Borrowing requires us to iterate over the idle connections, unlock the pool,
  507. // and perform a blocking operation to check the connection still works. If
  508. // TestOnBorrow fails, we must reacquire the lock and continue iteration. This
  509. // test ensures that iteration will work correctly if multiple threads are
  510. // iterating simultaneously.
  511. func TestLocking_TestOnBorrowFails_PoolDoesntCrash(t *testing.T) {
  512. const count = 100
  513. // First we'll Create a pool where the pilfering of idle connections fails.
  514. d := poolDialer{t: t}
  515. p := &redis.Pool{
  516. MaxIdle: count,
  517. MaxActive: count,
  518. Dial: d.dial,
  519. TestOnBorrow: func(c redis.Conn, t time.Time) error {
  520. return errors.New("No way back into the real world.")
  521. },
  522. }
  523. defer p.Close()
  524. // Fill the pool with idle connections.
  525. conns := make([]redis.Conn, count)
  526. for i := range conns {
  527. conns[i] = p.Get()
  528. }
  529. for i := range conns {
  530. conns[i].Close()
  531. }
  532. // Spawn a bunch of goroutines to thrash the pool.
  533. var wg sync.WaitGroup
  534. wg.Add(count)
  535. for i := 0; i < count; i++ {
  536. go func() {
  537. c := p.Get()
  538. if c.Err() != nil {
  539. t.Errorf("pool get failed: %v", c.Err())
  540. }
  541. c.Close()
  542. wg.Done()
  543. }()
  544. }
  545. wg.Wait()
  546. if d.dialed != count*2 {
  547. t.Errorf("Expected %d dials, got %d", count*2, d.dialed)
  548. }
  549. }
  550. func BenchmarkPoolGet(b *testing.B) {
  551. b.StopTimer()
  552. p := redis.Pool{Dial: redis.DialDefaultServer, MaxIdle: 2}
  553. c := p.Get()
  554. if err := c.Err(); err != nil {
  555. b.Fatal(err)
  556. }
  557. c.Close()
  558. defer p.Close()
  559. b.StartTimer()
  560. for i := 0; i < b.N; i++ {
  561. c = p.Get()
  562. c.Close()
  563. }
  564. }
  565. func BenchmarkPoolGetErr(b *testing.B) {
  566. b.StopTimer()
  567. p := redis.Pool{Dial: redis.DialDefaultServer, MaxIdle: 2}
  568. c := p.Get()
  569. if err := c.Err(); err != nil {
  570. b.Fatal(err)
  571. }
  572. c.Close()
  573. defer p.Close()
  574. b.StartTimer()
  575. for i := 0; i < b.N; i++ {
  576. c = p.Get()
  577. if err := c.Err(); err != nil {
  578. b.Fatal(err)
  579. }
  580. c.Close()
  581. }
  582. }
  583. func BenchmarkPoolGetPing(b *testing.B) {
  584. b.StopTimer()
  585. p := redis.Pool{Dial: redis.DialDefaultServer, MaxIdle: 2}
  586. c := p.Get()
  587. if err := c.Err(); err != nil {
  588. b.Fatal(err)
  589. }
  590. c.Close()
  591. defer p.Close()
  592. b.StartTimer()
  593. for i := 0; i < b.N; i++ {
  594. c = p.Get()
  595. if _, err := c.Do("PING"); err != nil {
  596. b.Fatal(err)
  597. }
  598. c.Close()
  599. }
  600. }