conn.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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. "bufio"
  17. "bytes"
  18. "crypto/tls"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "net"
  23. "net/url"
  24. "regexp"
  25. "strconv"
  26. "sync"
  27. "time"
  28. )
  29. var (
  30. _ ConnWithTimeout = (*conn)(nil)
  31. )
  32. // conn is the low-level implementation of Conn
  33. type conn struct {
  34. // Shared
  35. mu sync.Mutex
  36. pending int
  37. err error
  38. conn net.Conn
  39. // Read
  40. readTimeout time.Duration
  41. br *bufio.Reader
  42. // Write
  43. writeTimeout time.Duration
  44. bw *bufio.Writer
  45. // Scratch space for formatting argument length.
  46. // '*' or '$', length, "\r\n"
  47. lenScratch [32]byte
  48. // Scratch space for formatting integers and floats.
  49. numScratch [40]byte
  50. }
  51. // DialTimeout acts like Dial but takes timeouts for establishing the
  52. // connection to the server, writing a command and reading a reply.
  53. //
  54. // Deprecated: Use Dial with options instead.
  55. func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error) {
  56. return Dial(network, address,
  57. DialConnectTimeout(connectTimeout),
  58. DialReadTimeout(readTimeout),
  59. DialWriteTimeout(writeTimeout))
  60. }
  61. // DialOption specifies an option for dialing a Redis server.
  62. type DialOption struct {
  63. f func(*dialOptions)
  64. }
  65. type dialOptions struct {
  66. readTimeout time.Duration
  67. writeTimeout time.Duration
  68. dialer *net.Dialer
  69. dial func(network, addr string) (net.Conn, error)
  70. db int
  71. password string
  72. clientName string
  73. useTLS bool
  74. skipVerify bool
  75. tlsConfig *tls.Config
  76. }
  77. // DialReadTimeout specifies the timeout for reading a single command reply.
  78. func DialReadTimeout(d time.Duration) DialOption {
  79. return DialOption{func(do *dialOptions) {
  80. do.readTimeout = d
  81. }}
  82. }
  83. // DialWriteTimeout specifies the timeout for writing a single command.
  84. func DialWriteTimeout(d time.Duration) DialOption {
  85. return DialOption{func(do *dialOptions) {
  86. do.writeTimeout = d
  87. }}
  88. }
  89. // DialConnectTimeout specifies the timeout for connecting to the Redis server when
  90. // no DialNetDial option is specified.
  91. func DialConnectTimeout(d time.Duration) DialOption {
  92. return DialOption{func(do *dialOptions) {
  93. do.dialer.Timeout = d
  94. }}
  95. }
  96. // DialKeepAlive specifies the keep-alive period for TCP connections to the Redis server
  97. // when no DialNetDial option is specified.
  98. // If zero, keep-alives are not enabled. If no DialKeepAlive option is specified then
  99. // the default of 5 minutes is used to ensure that half-closed TCP sessions are detected.
  100. func DialKeepAlive(d time.Duration) DialOption {
  101. return DialOption{func(do *dialOptions) {
  102. do.dialer.KeepAlive = d
  103. }}
  104. }
  105. // DialNetDial specifies a custom dial function for creating TCP
  106. // connections, otherwise a net.Dialer customized via the other options is used.
  107. // DialNetDial overrides DialConnectTimeout and DialKeepAlive.
  108. func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption {
  109. return DialOption{func(do *dialOptions) {
  110. do.dial = dial
  111. }}
  112. }
  113. // DialDatabase specifies the database to select when dialing a connection.
  114. func DialDatabase(db int) DialOption {
  115. return DialOption{func(do *dialOptions) {
  116. do.db = db
  117. }}
  118. }
  119. // DialPassword specifies the password to use when connecting to
  120. // the Redis server.
  121. func DialPassword(password string) DialOption {
  122. return DialOption{func(do *dialOptions) {
  123. do.password = password
  124. }}
  125. }
  126. // DialClientName specifies a client name to be used
  127. // by the Redis server connection.
  128. func DialClientName(name string) DialOption {
  129. return DialOption{func(do *dialOptions) {
  130. do.clientName = name
  131. }}
  132. }
  133. // DialTLSConfig specifies the config to use when a TLS connection is dialed.
  134. // Has no effect when not dialing a TLS connection.
  135. func DialTLSConfig(c *tls.Config) DialOption {
  136. return DialOption{func(do *dialOptions) {
  137. do.tlsConfig = c
  138. }}
  139. }
  140. // DialTLSSkipVerify disables server name verification when connecting over
  141. // TLS. Has no effect when not dialing a TLS connection.
  142. func DialTLSSkipVerify(skip bool) DialOption {
  143. return DialOption{func(do *dialOptions) {
  144. do.skipVerify = skip
  145. }}
  146. }
  147. // DialUseTLS specifies whether TLS should be used when connecting to the
  148. // server. This option is ignore by DialURL.
  149. func DialUseTLS(useTLS bool) DialOption {
  150. return DialOption{func(do *dialOptions) {
  151. do.useTLS = useTLS
  152. }}
  153. }
  154. // Dial connects to the Redis server at the given network and
  155. // address using the specified options.
  156. func Dial(network, address string, options ...DialOption) (Conn, error) {
  157. do := dialOptions{
  158. dialer: &net.Dialer{
  159. KeepAlive: time.Minute * 5,
  160. },
  161. }
  162. for _, option := range options {
  163. option.f(&do)
  164. }
  165. if do.dial == nil {
  166. do.dial = do.dialer.Dial
  167. }
  168. netConn, err := do.dial(network, address)
  169. if err != nil {
  170. return nil, err
  171. }
  172. if do.useTLS {
  173. var tlsConfig *tls.Config
  174. if do.tlsConfig == nil {
  175. tlsConfig = &tls.Config{InsecureSkipVerify: do.skipVerify}
  176. } else {
  177. tlsConfig = cloneTLSConfig(do.tlsConfig)
  178. }
  179. if tlsConfig.ServerName == "" {
  180. host, _, err := net.SplitHostPort(address)
  181. if err != nil {
  182. netConn.Close()
  183. return nil, err
  184. }
  185. tlsConfig.ServerName = host
  186. }
  187. tlsConn := tls.Client(netConn, tlsConfig)
  188. if err := tlsConn.Handshake(); err != nil {
  189. netConn.Close()
  190. return nil, err
  191. }
  192. netConn = tlsConn
  193. }
  194. c := &conn{
  195. conn: netConn,
  196. bw: bufio.NewWriter(netConn),
  197. br: bufio.NewReader(netConn),
  198. readTimeout: do.readTimeout,
  199. writeTimeout: do.writeTimeout,
  200. }
  201. if do.password != "" {
  202. if _, err := c.Do("AUTH", do.password); err != nil {
  203. netConn.Close()
  204. return nil, err
  205. }
  206. }
  207. if do.clientName != "" {
  208. if _, err := c.Do("CLIENT", "SETNAME", do.clientName); err != nil {
  209. netConn.Close()
  210. return nil, err
  211. }
  212. }
  213. if do.db != 0 {
  214. if _, err := c.Do("SELECT", do.db); err != nil {
  215. netConn.Close()
  216. return nil, err
  217. }
  218. }
  219. return c, nil
  220. }
  221. var pathDBRegexp = regexp.MustCompile(`/(\d*)\z`)
  222. // DialURL connects to a Redis server at the given URL using the Redis
  223. // URI scheme. URLs should follow the draft IANA specification for the
  224. // scheme (https://www.iana.org/assignments/uri-schemes/prov/redis).
  225. func DialURL(rawurl string, options ...DialOption) (Conn, error) {
  226. u, err := url.Parse(rawurl)
  227. if err != nil {
  228. return nil, err
  229. }
  230. if u.Scheme != "redis" && u.Scheme != "rediss" {
  231. return nil, fmt.Errorf("invalid redis URL scheme: %s", u.Scheme)
  232. }
  233. // As per the IANA draft spec, the host defaults to localhost and
  234. // the port defaults to 6379.
  235. host, port, err := net.SplitHostPort(u.Host)
  236. if err != nil {
  237. // assume port is missing
  238. host = u.Host
  239. port = "6379"
  240. }
  241. if host == "" {
  242. host = "localhost"
  243. }
  244. address := net.JoinHostPort(host, port)
  245. if u.User != nil {
  246. password, isSet := u.User.Password()
  247. if isSet {
  248. options = append(options, DialPassword(password))
  249. }
  250. }
  251. match := pathDBRegexp.FindStringSubmatch(u.Path)
  252. if len(match) == 2 {
  253. db := 0
  254. if len(match[1]) > 0 {
  255. db, err = strconv.Atoi(match[1])
  256. if err != nil {
  257. return nil, fmt.Errorf("invalid database: %s", u.Path[1:])
  258. }
  259. }
  260. if db != 0 {
  261. options = append(options, DialDatabase(db))
  262. }
  263. } else if u.Path != "" {
  264. return nil, fmt.Errorf("invalid database: %s", u.Path[1:])
  265. }
  266. options = append(options, DialUseTLS(u.Scheme == "rediss"))
  267. return Dial("tcp", address, options...)
  268. }
  269. // NewConn returns a new Redigo connection for the given net connection.
  270. func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn {
  271. return &conn{
  272. conn: netConn,
  273. bw: bufio.NewWriter(netConn),
  274. br: bufio.NewReader(netConn),
  275. readTimeout: readTimeout,
  276. writeTimeout: writeTimeout,
  277. }
  278. }
  279. func (c *conn) Close() error {
  280. c.mu.Lock()
  281. err := c.err
  282. if c.err == nil {
  283. c.err = errors.New("redigo: closed")
  284. err = c.conn.Close()
  285. }
  286. c.mu.Unlock()
  287. return err
  288. }
  289. func (c *conn) fatal(err error) error {
  290. c.mu.Lock()
  291. if c.err == nil {
  292. c.err = err
  293. // Close connection to force errors on subsequent calls and to unblock
  294. // other reader or writer.
  295. c.conn.Close()
  296. }
  297. c.mu.Unlock()
  298. return err
  299. }
  300. func (c *conn) Err() error {
  301. c.mu.Lock()
  302. err := c.err
  303. c.mu.Unlock()
  304. return err
  305. }
  306. func (c *conn) writeLen(prefix byte, n int) error {
  307. c.lenScratch[len(c.lenScratch)-1] = '\n'
  308. c.lenScratch[len(c.lenScratch)-2] = '\r'
  309. i := len(c.lenScratch) - 3
  310. for {
  311. c.lenScratch[i] = byte('0' + n%10)
  312. i -= 1
  313. n = n / 10
  314. if n == 0 {
  315. break
  316. }
  317. }
  318. c.lenScratch[i] = prefix
  319. _, err := c.bw.Write(c.lenScratch[i:])
  320. return err
  321. }
  322. func (c *conn) writeString(s string) error {
  323. c.writeLen('$', len(s))
  324. c.bw.WriteString(s)
  325. _, err := c.bw.WriteString("\r\n")
  326. return err
  327. }
  328. func (c *conn) writeBytes(p []byte) error {
  329. c.writeLen('$', len(p))
  330. c.bw.Write(p)
  331. _, err := c.bw.WriteString("\r\n")
  332. return err
  333. }
  334. func (c *conn) writeInt64(n int64) error {
  335. return c.writeBytes(strconv.AppendInt(c.numScratch[:0], n, 10))
  336. }
  337. func (c *conn) writeFloat64(n float64) error {
  338. return c.writeBytes(strconv.AppendFloat(c.numScratch[:0], n, 'g', -1, 64))
  339. }
  340. func (c *conn) writeCommand(cmd string, args []interface{}) error {
  341. c.writeLen('*', 1+len(args))
  342. if err := c.writeString(cmd); err != nil {
  343. return err
  344. }
  345. for _, arg := range args {
  346. if err := c.writeArg(arg, true); err != nil {
  347. return err
  348. }
  349. }
  350. return nil
  351. }
  352. func (c *conn) writeArg(arg interface{}, argumentTypeOK bool) (err error) {
  353. switch arg := arg.(type) {
  354. case string:
  355. return c.writeString(arg)
  356. case []byte:
  357. return c.writeBytes(arg)
  358. case int:
  359. return c.writeInt64(int64(arg))
  360. case int64:
  361. return c.writeInt64(arg)
  362. case float64:
  363. return c.writeFloat64(arg)
  364. case bool:
  365. if arg {
  366. return c.writeString("1")
  367. } else {
  368. return c.writeString("0")
  369. }
  370. case nil:
  371. return c.writeString("")
  372. case Argument:
  373. if argumentTypeOK {
  374. return c.writeArg(arg.RedisArg(), false)
  375. }
  376. // See comment in default clause below.
  377. var buf bytes.Buffer
  378. fmt.Fprint(&buf, arg)
  379. return c.writeBytes(buf.Bytes())
  380. default:
  381. // This default clause is intended to handle builtin numeric types.
  382. // The function should return an error for other types, but this is not
  383. // done for compatibility with previous versions of the package.
  384. var buf bytes.Buffer
  385. fmt.Fprint(&buf, arg)
  386. return c.writeBytes(buf.Bytes())
  387. }
  388. }
  389. type protocolError string
  390. func (pe protocolError) Error() string {
  391. return fmt.Sprintf("redigo: %s (possible server error or unsupported concurrent read by application)", string(pe))
  392. }
  393. // readLine reads a line of input from the RESP stream.
  394. func (c *conn) readLine() ([]byte, error) {
  395. // To avoid allocations, attempt to read the line using ReadSlice. This
  396. // call typically succeeds. The known case where the call fails is when
  397. // reading the output from the MONITOR command.
  398. p, err := c.br.ReadSlice('\n')
  399. if err == bufio.ErrBufferFull {
  400. // The line does not fit in the bufio.Reader's buffer. Fall back to
  401. // allocating a buffer for the line.
  402. buf := append([]byte{}, p...)
  403. for err == bufio.ErrBufferFull {
  404. p, err = c.br.ReadSlice('\n')
  405. buf = append(buf, p...)
  406. }
  407. p = buf
  408. }
  409. if err != nil {
  410. return nil, err
  411. }
  412. i := len(p) - 2
  413. if i < 0 || p[i] != '\r' {
  414. return nil, protocolError("bad response line terminator")
  415. }
  416. return p[:i], nil
  417. }
  418. // parseLen parses bulk string and array lengths.
  419. func parseLen(p []byte) (int, error) {
  420. if len(p) == 0 {
  421. return -1, protocolError("malformed length")
  422. }
  423. if p[0] == '-' && len(p) == 2 && p[1] == '1' {
  424. // handle $-1 and $-1 null replies.
  425. return -1, nil
  426. }
  427. var n int
  428. for _, b := range p {
  429. n *= 10
  430. if b < '0' || b > '9' {
  431. return -1, protocolError("illegal bytes in length")
  432. }
  433. n += int(b - '0')
  434. }
  435. return n, nil
  436. }
  437. // parseInt parses an integer reply.
  438. func parseInt(p []byte) (interface{}, error) {
  439. if len(p) == 0 {
  440. return 0, protocolError("malformed integer")
  441. }
  442. var negate bool
  443. if p[0] == '-' {
  444. negate = true
  445. p = p[1:]
  446. if len(p) == 0 {
  447. return 0, protocolError("malformed integer")
  448. }
  449. }
  450. var n int64
  451. for _, b := range p {
  452. n *= 10
  453. if b < '0' || b > '9' {
  454. return 0, protocolError("illegal bytes in length")
  455. }
  456. n += int64(b - '0')
  457. }
  458. if negate {
  459. n = -n
  460. }
  461. return n, nil
  462. }
  463. var (
  464. okReply interface{} = "OK"
  465. pongReply interface{} = "PONG"
  466. )
  467. func (c *conn) readReply() (interface{}, error) {
  468. line, err := c.readLine()
  469. if err != nil {
  470. return nil, err
  471. }
  472. if len(line) == 0 {
  473. return nil, protocolError("short response line")
  474. }
  475. switch line[0] {
  476. case '+':
  477. switch {
  478. case len(line) == 3 && line[1] == 'O' && line[2] == 'K':
  479. // Avoid allocation for frequent "+OK" response.
  480. return okReply, nil
  481. case len(line) == 5 && line[1] == 'P' && line[2] == 'O' && line[3] == 'N' && line[4] == 'G':
  482. // Avoid allocation in PING command benchmarks :)
  483. return pongReply, nil
  484. default:
  485. return string(line[1:]), nil
  486. }
  487. case '-':
  488. return Error(string(line[1:])), nil
  489. case ':':
  490. return parseInt(line[1:])
  491. case '$':
  492. n, err := parseLen(line[1:])
  493. if n < 0 || err != nil {
  494. return nil, err
  495. }
  496. p := make([]byte, n)
  497. _, err = io.ReadFull(c.br, p)
  498. if err != nil {
  499. return nil, err
  500. }
  501. if line, err := c.readLine(); err != nil {
  502. return nil, err
  503. } else if len(line) != 0 {
  504. return nil, protocolError("bad bulk string format")
  505. }
  506. return p, nil
  507. case '*':
  508. n, err := parseLen(line[1:])
  509. if n < 0 || err != nil {
  510. return nil, err
  511. }
  512. r := make([]interface{}, n)
  513. for i := range r {
  514. r[i], err = c.readReply()
  515. if err != nil {
  516. return nil, err
  517. }
  518. }
  519. return r, nil
  520. }
  521. return nil, protocolError("unexpected response line")
  522. }
  523. func (c *conn) Send(cmd string, args ...interface{}) error {
  524. c.mu.Lock()
  525. c.pending += 1
  526. c.mu.Unlock()
  527. if c.writeTimeout != 0 {
  528. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  529. }
  530. if err := c.writeCommand(cmd, args); err != nil {
  531. return c.fatal(err)
  532. }
  533. return nil
  534. }
  535. func (c *conn) Flush() error {
  536. if c.writeTimeout != 0 {
  537. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  538. }
  539. if err := c.bw.Flush(); err != nil {
  540. return c.fatal(err)
  541. }
  542. return nil
  543. }
  544. func (c *conn) Receive() (interface{}, error) {
  545. return c.ReceiveWithTimeout(c.readTimeout)
  546. }
  547. func (c *conn) ReceiveWithTimeout(timeout time.Duration) (reply interface{}, err error) {
  548. var deadline time.Time
  549. if timeout != 0 {
  550. deadline = time.Now().Add(timeout)
  551. }
  552. c.conn.SetReadDeadline(deadline)
  553. if reply, err = c.readReply(); err != nil {
  554. return nil, c.fatal(err)
  555. }
  556. // When using pub/sub, the number of receives can be greater than the
  557. // number of sends. To enable normal use of the connection after
  558. // unsubscribing from all channels, we do not decrement pending to a
  559. // negative value.
  560. //
  561. // The pending field is decremented after the reply is read to handle the
  562. // case where Receive is called before Send.
  563. c.mu.Lock()
  564. if c.pending > 0 {
  565. c.pending -= 1
  566. }
  567. c.mu.Unlock()
  568. if err, ok := reply.(Error); ok {
  569. return nil, err
  570. }
  571. return
  572. }
  573. func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
  574. return c.DoWithTimeout(c.readTimeout, cmd, args...)
  575. }
  576. func (c *conn) DoWithTimeout(readTimeout time.Duration, cmd string, args ...interface{}) (interface{}, error) {
  577. c.mu.Lock()
  578. pending := c.pending
  579. c.pending = 0
  580. c.mu.Unlock()
  581. if cmd == "" && pending == 0 {
  582. return nil, nil
  583. }
  584. if c.writeTimeout != 0 {
  585. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  586. }
  587. if cmd != "" {
  588. if err := c.writeCommand(cmd, args); err != nil {
  589. return nil, c.fatal(err)
  590. }
  591. }
  592. if err := c.bw.Flush(); err != nil {
  593. return nil, c.fatal(err)
  594. }
  595. var deadline time.Time
  596. if readTimeout != 0 {
  597. deadline = time.Now().Add(readTimeout)
  598. }
  599. c.conn.SetReadDeadline(deadline)
  600. if cmd == "" {
  601. reply := make([]interface{}, pending)
  602. for i := range reply {
  603. r, e := c.readReply()
  604. if e != nil {
  605. return nil, c.fatal(e)
  606. }
  607. reply[i] = r
  608. }
  609. return reply, nil
  610. }
  611. var err error
  612. var reply interface{}
  613. for i := 0; i <= pending; i++ {
  614. var e error
  615. if reply, e = c.readReply(); e != nil {
  616. return nil, c.fatal(e)
  617. }
  618. if e, ok := reply.(Error); ok && err == nil {
  619. err = e
  620. }
  621. }
  622. return reply, err
  623. }