conn.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. "errors"
  19. "fmt"
  20. "io"
  21. "net"
  22. "strconv"
  23. "sync"
  24. "time"
  25. )
  26. // conn is the low-level implementation of Conn
  27. type conn struct {
  28. // Shared
  29. mu sync.Mutex
  30. pending int
  31. err error
  32. conn net.Conn
  33. // Read
  34. readTimeout time.Duration
  35. br *bufio.Reader
  36. // Write
  37. writeTimeout time.Duration
  38. bw *bufio.Writer
  39. // Scratch space for formatting argument length.
  40. // '*' or '$', length, "\r\n"
  41. lenScratch [32]byte
  42. // Scratch space for formatting integers and floats.
  43. numScratch [40]byte
  44. }
  45. // DialTimeout acts like Dial but takes timeouts for establishing the
  46. // connection to the server, writing a command and reading a reply.
  47. //
  48. // DialTimeout is deprecated.
  49. func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error) {
  50. return Dial(network, address,
  51. DialConnectTimeout(connectTimeout),
  52. DialReadTimeout(readTimeout),
  53. DialWriteTimeout(writeTimeout))
  54. }
  55. // DialOption specifies an option for dialing a Redis server.
  56. type DialOption struct {
  57. f func(*dialOptions)
  58. }
  59. type dialOptions struct {
  60. readTimeout time.Duration
  61. writeTimeout time.Duration
  62. dial func(network, addr string) (net.Conn, error)
  63. db int
  64. password string
  65. }
  66. // DialReadTimeout specifies the timeout for reading a single command reply.
  67. func DialReadTimeout(d time.Duration) DialOption {
  68. return DialOption{func(do *dialOptions) {
  69. do.readTimeout = d
  70. }}
  71. }
  72. // DialWriteTimeout specifies the timeout for writing a single command.
  73. func DialWriteTimeout(d time.Duration) DialOption {
  74. return DialOption{func(do *dialOptions) {
  75. do.writeTimeout = d
  76. }}
  77. }
  78. // DialConnectTimeout specifies the timeout for connecting to the Redis server.
  79. func DialConnectTimeout(d time.Duration) DialOption {
  80. return DialOption{func(do *dialOptions) {
  81. dialer := net.Dialer{Timeout: d}
  82. do.dial = dialer.Dial
  83. }}
  84. }
  85. // DialNetDial specifies a custom dial function for creating TCP
  86. // connections. If this option is left out, then net.Dial is
  87. // used. DialNetDial overrides DialConnectTimeout.
  88. func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption {
  89. return DialOption{func(do *dialOptions) {
  90. do.dial = dial
  91. }}
  92. }
  93. // DialDatabase specifies the database to select when dialing a connection.
  94. func DialDatabase(db int) DialOption {
  95. return DialOption{func(do *dialOptions) {
  96. do.db = db
  97. }}
  98. }
  99. // Dial connects to the Redis server at the given network and
  100. // address using the specified options.
  101. func Dial(network, address string, options ...DialOption) (Conn, error) {
  102. do := dialOptions{
  103. dial: net.Dial,
  104. }
  105. for _, option := range options {
  106. option.f(&do)
  107. }
  108. netConn, err := do.dial(network, address)
  109. if err != nil {
  110. return nil, err
  111. }
  112. c := &conn{
  113. conn: netConn,
  114. bw: bufio.NewWriter(netConn),
  115. br: bufio.NewReader(netConn),
  116. readTimeout: do.readTimeout,
  117. writeTimeout: do.writeTimeout,
  118. }
  119. if do.password != "" {
  120. if _, err := c.Do("AUTH", do.password); err != nil {
  121. netConn.Close()
  122. return nil, err
  123. }
  124. }
  125. if do.db != 0 {
  126. if _, err := c.Do("SELECT", do.db); err != nil {
  127. netConn.Close()
  128. return nil, err
  129. }
  130. }
  131. return c, nil
  132. }
  133. // NewConn returns a new Redigo connection for the given net connection.
  134. func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn {
  135. return &conn{
  136. conn: netConn,
  137. bw: bufio.NewWriter(netConn),
  138. br: bufio.NewReader(netConn),
  139. readTimeout: readTimeout,
  140. writeTimeout: writeTimeout,
  141. }
  142. }
  143. func (c *conn) Close() error {
  144. c.mu.Lock()
  145. err := c.err
  146. if c.err == nil {
  147. c.err = errors.New("redigo: closed")
  148. err = c.conn.Close()
  149. }
  150. c.mu.Unlock()
  151. return err
  152. }
  153. func (c *conn) fatal(err error) error {
  154. c.mu.Lock()
  155. if c.err == nil {
  156. c.err = err
  157. // Close connection to force errors on subsequent calls and to unblock
  158. // other reader or writer.
  159. c.conn.Close()
  160. }
  161. c.mu.Unlock()
  162. return err
  163. }
  164. func (c *conn) Err() error {
  165. c.mu.Lock()
  166. err := c.err
  167. c.mu.Unlock()
  168. return err
  169. }
  170. func (c *conn) writeLen(prefix byte, n int) error {
  171. c.lenScratch[len(c.lenScratch)-1] = '\n'
  172. c.lenScratch[len(c.lenScratch)-2] = '\r'
  173. i := len(c.lenScratch) - 3
  174. for {
  175. c.lenScratch[i] = byte('0' + n%10)
  176. i -= 1
  177. n = n / 10
  178. if n == 0 {
  179. break
  180. }
  181. }
  182. c.lenScratch[i] = prefix
  183. _, err := c.bw.Write(c.lenScratch[i:])
  184. return err
  185. }
  186. func (c *conn) writeString(s string) error {
  187. c.writeLen('$', len(s))
  188. c.bw.WriteString(s)
  189. _, err := c.bw.WriteString("\r\n")
  190. return err
  191. }
  192. func (c *conn) writeBytes(p []byte) error {
  193. c.writeLen('$', len(p))
  194. c.bw.Write(p)
  195. _, err := c.bw.WriteString("\r\n")
  196. return err
  197. }
  198. func (c *conn) writeInt64(n int64) error {
  199. return c.writeBytes(strconv.AppendInt(c.numScratch[:0], n, 10))
  200. }
  201. func (c *conn) writeFloat64(n float64) error {
  202. return c.writeBytes(strconv.AppendFloat(c.numScratch[:0], n, 'g', -1, 64))
  203. }
  204. func (c *conn) writeCommand(cmd string, args []interface{}) (err error) {
  205. c.writeLen('*', 1+len(args))
  206. err = c.writeString(cmd)
  207. for _, arg := range args {
  208. if err != nil {
  209. break
  210. }
  211. switch arg := arg.(type) {
  212. case string:
  213. err = c.writeString(arg)
  214. case []byte:
  215. err = c.writeBytes(arg)
  216. case int:
  217. err = c.writeInt64(int64(arg))
  218. case int64:
  219. err = c.writeInt64(arg)
  220. case float64:
  221. err = c.writeFloat64(arg)
  222. case bool:
  223. if arg {
  224. err = c.writeString("1")
  225. } else {
  226. err = c.writeString("0")
  227. }
  228. case nil:
  229. err = c.writeString("")
  230. default:
  231. var buf bytes.Buffer
  232. fmt.Fprint(&buf, arg)
  233. err = c.writeBytes(buf.Bytes())
  234. }
  235. }
  236. return err
  237. }
  238. type protocolError string
  239. func (pe protocolError) Error() string {
  240. return fmt.Sprintf("redigo: %s (possible server error or unsupported concurrent read by application)", string(pe))
  241. }
  242. func (c *conn) readLine() ([]byte, error) {
  243. p, err := c.br.ReadSlice('\n')
  244. if err == bufio.ErrBufferFull {
  245. return nil, protocolError("long response line")
  246. }
  247. if err != nil {
  248. return nil, err
  249. }
  250. i := len(p) - 2
  251. if i < 0 || p[i] != '\r' {
  252. return nil, protocolError("bad response line terminator")
  253. }
  254. return p[:i], nil
  255. }
  256. // parseLen parses bulk string and array lengths.
  257. func parseLen(p []byte) (int, error) {
  258. if len(p) == 0 {
  259. return -1, protocolError("malformed length")
  260. }
  261. if p[0] == '-' && len(p) == 2 && p[1] == '1' {
  262. // handle $-1 and $-1 null replies.
  263. return -1, nil
  264. }
  265. var n int
  266. for _, b := range p {
  267. n *= 10
  268. if b < '0' || b > '9' {
  269. return -1, protocolError("illegal bytes in length")
  270. }
  271. n += int(b - '0')
  272. }
  273. return n, nil
  274. }
  275. // parseInt parses an integer reply.
  276. func parseInt(p []byte) (interface{}, error) {
  277. if len(p) == 0 {
  278. return 0, protocolError("malformed integer")
  279. }
  280. var negate bool
  281. if p[0] == '-' {
  282. negate = true
  283. p = p[1:]
  284. if len(p) == 0 {
  285. return 0, protocolError("malformed integer")
  286. }
  287. }
  288. var n int64
  289. for _, b := range p {
  290. n *= 10
  291. if b < '0' || b > '9' {
  292. return 0, protocolError("illegal bytes in length")
  293. }
  294. n += int64(b - '0')
  295. }
  296. if negate {
  297. n = -n
  298. }
  299. return n, nil
  300. }
  301. var (
  302. okReply interface{} = "OK"
  303. pongReply interface{} = "PONG"
  304. )
  305. func (c *conn) readReply() (interface{}, error) {
  306. line, err := c.readLine()
  307. if err != nil {
  308. return nil, err
  309. }
  310. if len(line) == 0 {
  311. return nil, protocolError("short response line")
  312. }
  313. switch line[0] {
  314. case '+':
  315. switch {
  316. case len(line) == 3 && line[1] == 'O' && line[2] == 'K':
  317. // Avoid allocation for frequent "+OK" response.
  318. return okReply, nil
  319. case len(line) == 5 && line[1] == 'P' && line[2] == 'O' && line[3] == 'N' && line[4] == 'G':
  320. // Avoid allocation in PING command benchmarks :)
  321. return pongReply, nil
  322. default:
  323. return string(line[1:]), nil
  324. }
  325. case '-':
  326. return Error(string(line[1:])), nil
  327. case ':':
  328. return parseInt(line[1:])
  329. case '$':
  330. n, err := parseLen(line[1:])
  331. if n < 0 || err != nil {
  332. return nil, err
  333. }
  334. p := make([]byte, n)
  335. _, err = io.ReadFull(c.br, p)
  336. if err != nil {
  337. return nil, err
  338. }
  339. if line, err := c.readLine(); err != nil {
  340. return nil, err
  341. } else if len(line) != 0 {
  342. return nil, protocolError("bad bulk string format")
  343. }
  344. return p, nil
  345. case '*':
  346. n, err := parseLen(line[1:])
  347. if n < 0 || err != nil {
  348. return nil, err
  349. }
  350. r := make([]interface{}, n)
  351. for i := range r {
  352. r[i], err = c.readReply()
  353. if err != nil {
  354. return nil, err
  355. }
  356. }
  357. return r, nil
  358. }
  359. return nil, protocolError("unexpected response line")
  360. }
  361. func (c *conn) Send(cmd string, args ...interface{}) error {
  362. c.mu.Lock()
  363. c.pending += 1
  364. c.mu.Unlock()
  365. if c.writeTimeout != 0 {
  366. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  367. }
  368. if err := c.writeCommand(cmd, args); err != nil {
  369. return c.fatal(err)
  370. }
  371. return nil
  372. }
  373. func (c *conn) Flush() error {
  374. if c.writeTimeout != 0 {
  375. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  376. }
  377. if err := c.bw.Flush(); err != nil {
  378. return c.fatal(err)
  379. }
  380. return nil
  381. }
  382. func (c *conn) Receive() (reply interface{}, err error) {
  383. if c.readTimeout != 0 {
  384. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  385. }
  386. if reply, err = c.readReply(); err != nil {
  387. return nil, c.fatal(err)
  388. }
  389. // When using pub/sub, the number of receives can be greater than the
  390. // number of sends. To enable normal use of the connection after
  391. // unsubscribing from all channels, we do not decrement pending to a
  392. // negative value.
  393. //
  394. // The pending field is decremented after the reply is read to handle the
  395. // case where Receive is called before Send.
  396. c.mu.Lock()
  397. if c.pending > 0 {
  398. c.pending -= 1
  399. }
  400. c.mu.Unlock()
  401. if err, ok := reply.(Error); ok {
  402. return nil, err
  403. }
  404. return
  405. }
  406. func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
  407. c.mu.Lock()
  408. pending := c.pending
  409. c.pending = 0
  410. c.mu.Unlock()
  411. if cmd == "" && pending == 0 {
  412. return nil, nil
  413. }
  414. if c.writeTimeout != 0 {
  415. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  416. }
  417. if cmd != "" {
  418. if err := c.writeCommand(cmd, args); err != nil {
  419. return nil, c.fatal(err)
  420. }
  421. }
  422. if err := c.bw.Flush(); err != nil {
  423. return nil, c.fatal(err)
  424. }
  425. if c.readTimeout != 0 {
  426. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  427. }
  428. if cmd == "" {
  429. reply := make([]interface{}, pending)
  430. for i := range reply {
  431. r, e := c.readReply()
  432. if e != nil {
  433. return nil, c.fatal(e)
  434. }
  435. reply[i] = r
  436. }
  437. return reply, nil
  438. }
  439. var err error
  440. var reply interface{}
  441. for i := 0; i <= pending; i++ {
  442. var e error
  443. if reply, e = c.readReply(); e != nil {
  444. return nil, c.fatal(e)
  445. }
  446. if e, ok := reply.(Error); ok && err == nil {
  447. err = e
  448. }
  449. }
  450. return reply, err
  451. }