conn.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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. if u.Opaque != "" {
  234. return nil, fmt.Errorf("invalid redis URL, url is opaque: %s", rawurl)
  235. }
  236. // As per the IANA draft spec, the host defaults to localhost and
  237. // the port defaults to 6379.
  238. host, port, err := net.SplitHostPort(u.Host)
  239. if err != nil {
  240. // assume port is missing
  241. host = u.Host
  242. port = "6379"
  243. }
  244. if host == "" {
  245. host = "localhost"
  246. }
  247. address := net.JoinHostPort(host, port)
  248. if u.User != nil {
  249. password, isSet := u.User.Password()
  250. if isSet {
  251. options = append(options, DialPassword(password))
  252. }
  253. }
  254. match := pathDBRegexp.FindStringSubmatch(u.Path)
  255. if len(match) == 2 {
  256. db := 0
  257. if len(match[1]) > 0 {
  258. db, err = strconv.Atoi(match[1])
  259. if err != nil {
  260. return nil, fmt.Errorf("invalid database: %s", u.Path[1:])
  261. }
  262. }
  263. if db != 0 {
  264. options = append(options, DialDatabase(db))
  265. }
  266. } else if u.Path != "" {
  267. return nil, fmt.Errorf("invalid database: %s", u.Path[1:])
  268. }
  269. options = append(options, DialUseTLS(u.Scheme == "rediss"))
  270. return Dial("tcp", address, options...)
  271. }
  272. // NewConn returns a new Redigo connection for the given net connection.
  273. func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn {
  274. return &conn{
  275. conn: netConn,
  276. bw: bufio.NewWriter(netConn),
  277. br: bufio.NewReader(netConn),
  278. readTimeout: readTimeout,
  279. writeTimeout: writeTimeout,
  280. }
  281. }
  282. func (c *conn) Close() error {
  283. c.mu.Lock()
  284. err := c.err
  285. if c.err == nil {
  286. c.err = errors.New("redigo: closed")
  287. err = c.conn.Close()
  288. }
  289. c.mu.Unlock()
  290. return err
  291. }
  292. func (c *conn) fatal(err error) error {
  293. c.mu.Lock()
  294. if c.err == nil {
  295. c.err = err
  296. // Close connection to force errors on subsequent calls and to unblock
  297. // other reader or writer.
  298. c.conn.Close()
  299. }
  300. c.mu.Unlock()
  301. return err
  302. }
  303. func (c *conn) Err() error {
  304. c.mu.Lock()
  305. err := c.err
  306. c.mu.Unlock()
  307. return err
  308. }
  309. func (c *conn) writeLen(prefix byte, n int) error {
  310. c.lenScratch[len(c.lenScratch)-1] = '\n'
  311. c.lenScratch[len(c.lenScratch)-2] = '\r'
  312. i := len(c.lenScratch) - 3
  313. for {
  314. c.lenScratch[i] = byte('0' + n%10)
  315. i -= 1
  316. n = n / 10
  317. if n == 0 {
  318. break
  319. }
  320. }
  321. c.lenScratch[i] = prefix
  322. _, err := c.bw.Write(c.lenScratch[i:])
  323. return err
  324. }
  325. func (c *conn) writeString(s string) error {
  326. c.writeLen('$', len(s))
  327. c.bw.WriteString(s)
  328. _, err := c.bw.WriteString("\r\n")
  329. return err
  330. }
  331. func (c *conn) writeBytes(p []byte) error {
  332. c.writeLen('$', len(p))
  333. c.bw.Write(p)
  334. _, err := c.bw.WriteString("\r\n")
  335. return err
  336. }
  337. func (c *conn) writeInt64(n int64) error {
  338. return c.writeBytes(strconv.AppendInt(c.numScratch[:0], n, 10))
  339. }
  340. func (c *conn) writeFloat64(n float64) error {
  341. return c.writeBytes(strconv.AppendFloat(c.numScratch[:0], n, 'g', -1, 64))
  342. }
  343. func (c *conn) writeCommand(cmd string, args []interface{}) error {
  344. c.writeLen('*', 1+len(args))
  345. if err := c.writeString(cmd); err != nil {
  346. return err
  347. }
  348. for _, arg := range args {
  349. if err := c.writeArg(arg, true); err != nil {
  350. return err
  351. }
  352. }
  353. return nil
  354. }
  355. func (c *conn) writeArg(arg interface{}, argumentTypeOK bool) (err error) {
  356. switch arg := arg.(type) {
  357. case string:
  358. return c.writeString(arg)
  359. case []byte:
  360. return c.writeBytes(arg)
  361. case int:
  362. return c.writeInt64(int64(arg))
  363. case int64:
  364. return c.writeInt64(arg)
  365. case float64:
  366. return c.writeFloat64(arg)
  367. case bool:
  368. if arg {
  369. return c.writeString("1")
  370. } else {
  371. return c.writeString("0")
  372. }
  373. case nil:
  374. return c.writeString("")
  375. case Argument:
  376. if argumentTypeOK {
  377. return c.writeArg(arg.RedisArg(), false)
  378. }
  379. // See comment in default clause below.
  380. var buf bytes.Buffer
  381. fmt.Fprint(&buf, arg)
  382. return c.writeBytes(buf.Bytes())
  383. default:
  384. // This default clause is intended to handle builtin numeric types.
  385. // The function should return an error for other types, but this is not
  386. // done for compatibility with previous versions of the package.
  387. var buf bytes.Buffer
  388. fmt.Fprint(&buf, arg)
  389. return c.writeBytes(buf.Bytes())
  390. }
  391. }
  392. type protocolError string
  393. func (pe protocolError) Error() string {
  394. return fmt.Sprintf("redigo: %s (possible server error or unsupported concurrent read by application)", string(pe))
  395. }
  396. // readLine reads a line of input from the RESP stream.
  397. func (c *conn) readLine() ([]byte, error) {
  398. // To avoid allocations, attempt to read the line using ReadSlice. This
  399. // call typically succeeds. The known case where the call fails is when
  400. // reading the output from the MONITOR command.
  401. p, err := c.br.ReadSlice('\n')
  402. if err == bufio.ErrBufferFull {
  403. // The line does not fit in the bufio.Reader's buffer. Fall back to
  404. // allocating a buffer for the line.
  405. buf := append([]byte{}, p...)
  406. for err == bufio.ErrBufferFull {
  407. p, err = c.br.ReadSlice('\n')
  408. buf = append(buf, p...)
  409. }
  410. p = buf
  411. }
  412. if err != nil {
  413. return nil, err
  414. }
  415. i := len(p) - 2
  416. if i < 0 || p[i] != '\r' {
  417. return nil, protocolError("bad response line terminator")
  418. }
  419. return p[:i], nil
  420. }
  421. // parseLen parses bulk string and array lengths.
  422. func parseLen(p []byte) (int, error) {
  423. if len(p) == 0 {
  424. return -1, protocolError("malformed length")
  425. }
  426. if p[0] == '-' && len(p) == 2 && p[1] == '1' {
  427. // handle $-1 and $-1 null replies.
  428. return -1, nil
  429. }
  430. var n int
  431. for _, b := range p {
  432. n *= 10
  433. if b < '0' || b > '9' {
  434. return -1, protocolError("illegal bytes in length")
  435. }
  436. n += int(b - '0')
  437. }
  438. return n, nil
  439. }
  440. // parseInt parses an integer reply.
  441. func parseInt(p []byte) (interface{}, error) {
  442. if len(p) == 0 {
  443. return 0, protocolError("malformed integer")
  444. }
  445. var negate bool
  446. if p[0] == '-' {
  447. negate = true
  448. p = p[1:]
  449. if len(p) == 0 {
  450. return 0, protocolError("malformed integer")
  451. }
  452. }
  453. var n int64
  454. for _, b := range p {
  455. n *= 10
  456. if b < '0' || b > '9' {
  457. return 0, protocolError("illegal bytes in length")
  458. }
  459. n += int64(b - '0')
  460. }
  461. if negate {
  462. n = -n
  463. }
  464. return n, nil
  465. }
  466. var (
  467. okReply interface{} = "OK"
  468. pongReply interface{} = "PONG"
  469. )
  470. func (c *conn) readReply() (interface{}, error) {
  471. line, err := c.readLine()
  472. if err != nil {
  473. return nil, err
  474. }
  475. if len(line) == 0 {
  476. return nil, protocolError("short response line")
  477. }
  478. switch line[0] {
  479. case '+':
  480. switch {
  481. case len(line) == 3 && line[1] == 'O' && line[2] == 'K':
  482. // Avoid allocation for frequent "+OK" response.
  483. return okReply, nil
  484. case len(line) == 5 && line[1] == 'P' && line[2] == 'O' && line[3] == 'N' && line[4] == 'G':
  485. // Avoid allocation in PING command benchmarks :)
  486. return pongReply, nil
  487. default:
  488. return string(line[1:]), nil
  489. }
  490. case '-':
  491. return Error(string(line[1:])), nil
  492. case ':':
  493. return parseInt(line[1:])
  494. case '$':
  495. n, err := parseLen(line[1:])
  496. if n < 0 || err != nil {
  497. return nil, err
  498. }
  499. p := make([]byte, n)
  500. _, err = io.ReadFull(c.br, p)
  501. if err != nil {
  502. return nil, err
  503. }
  504. if line, err := c.readLine(); err != nil {
  505. return nil, err
  506. } else if len(line) != 0 {
  507. return nil, protocolError("bad bulk string format")
  508. }
  509. return p, nil
  510. case '*':
  511. n, err := parseLen(line[1:])
  512. if n < 0 || err != nil {
  513. return nil, err
  514. }
  515. r := make([]interface{}, n)
  516. for i := range r {
  517. r[i], err = c.readReply()
  518. if err != nil {
  519. return nil, err
  520. }
  521. }
  522. return r, nil
  523. }
  524. return nil, protocolError("unexpected response line")
  525. }
  526. func (c *conn) Send(cmd string, args ...interface{}) error {
  527. c.mu.Lock()
  528. c.pending += 1
  529. c.mu.Unlock()
  530. if c.writeTimeout != 0 {
  531. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  532. }
  533. if err := c.writeCommand(cmd, args); err != nil {
  534. return c.fatal(err)
  535. }
  536. return nil
  537. }
  538. func (c *conn) Flush() error {
  539. if c.writeTimeout != 0 {
  540. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  541. }
  542. if err := c.bw.Flush(); err != nil {
  543. return c.fatal(err)
  544. }
  545. return nil
  546. }
  547. func (c *conn) Receive() (interface{}, error) {
  548. return c.ReceiveWithTimeout(c.readTimeout)
  549. }
  550. func (c *conn) ReceiveWithTimeout(timeout time.Duration) (reply interface{}, err error) {
  551. var deadline time.Time
  552. if timeout != 0 {
  553. deadline = time.Now().Add(timeout)
  554. }
  555. c.conn.SetReadDeadline(deadline)
  556. if reply, err = c.readReply(); err != nil {
  557. return nil, c.fatal(err)
  558. }
  559. // When using pub/sub, the number of receives can be greater than the
  560. // number of sends. To enable normal use of the connection after
  561. // unsubscribing from all channels, we do not decrement pending to a
  562. // negative value.
  563. //
  564. // The pending field is decremented after the reply is read to handle the
  565. // case where Receive is called before Send.
  566. c.mu.Lock()
  567. if c.pending > 0 {
  568. c.pending -= 1
  569. }
  570. c.mu.Unlock()
  571. if err, ok := reply.(Error); ok {
  572. return nil, err
  573. }
  574. return
  575. }
  576. func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
  577. return c.DoWithTimeout(c.readTimeout, cmd, args...)
  578. }
  579. func (c *conn) DoWithTimeout(readTimeout time.Duration, cmd string, args ...interface{}) (interface{}, error) {
  580. c.mu.Lock()
  581. pending := c.pending
  582. c.pending = 0
  583. c.mu.Unlock()
  584. if cmd == "" && pending == 0 {
  585. return nil, nil
  586. }
  587. if c.writeTimeout != 0 {
  588. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  589. }
  590. if cmd != "" {
  591. if err := c.writeCommand(cmd, args); err != nil {
  592. return nil, c.fatal(err)
  593. }
  594. }
  595. if err := c.bw.Flush(); err != nil {
  596. return nil, c.fatal(err)
  597. }
  598. var deadline time.Time
  599. if readTimeout != 0 {
  600. deadline = time.Now().Add(readTimeout)
  601. }
  602. c.conn.SetReadDeadline(deadline)
  603. if cmd == "" {
  604. reply := make([]interface{}, pending)
  605. for i := range reply {
  606. r, e := c.readReply()
  607. if e != nil {
  608. return nil, c.fatal(e)
  609. }
  610. reply[i] = r
  611. }
  612. return reply, nil
  613. }
  614. var err error
  615. var reply interface{}
  616. for i := 0; i <= pending; i++ {
  617. var e error
  618. if reply, e = c.readReply(); e != nil {
  619. return nil, c.fatal(e)
  620. }
  621. if e, ok := reply.(Error); ok && err == nil {
  622. err = e
  623. }
  624. }
  625. return reply, err
  626. }