conn.go 11 KB

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