conn.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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. "context"
  19. "fmt"
  20. "io"
  21. "net"
  22. "net/url"
  23. "regexp"
  24. "strconv"
  25. "sync"
  26. "time"
  27. "go-common/library/stat"
  28. "github.com/pkg/errors"
  29. )
  30. var stats = stat.Cache
  31. // conn is the low-level implementation of Conn
  32. type conn struct {
  33. // Shared
  34. mu sync.Mutex
  35. pending int
  36. err error
  37. conn net.Conn
  38. // Read
  39. readTimeout time.Duration
  40. br *bufio.Reader
  41. // Write
  42. writeTimeout time.Duration
  43. bw *bufio.Writer
  44. // Scratch space for formatting argument length.
  45. // '*' or '$', length, "\r\n"
  46. lenScratch [32]byte
  47. // Scratch space for formatting integers and floats.
  48. numScratch [40]byte
  49. // stat func,default prom
  50. stat func(string, *error) func()
  51. }
  52. func statfunc(cmd string, err *error) func() {
  53. now := time.Now()
  54. return func() {
  55. stats.Timing(fmt.Sprintf("redis:%s", cmd), int64(time.Since(now)/time.Millisecond))
  56. if err != nil {
  57. if msg := formatErr(*err); msg != "" {
  58. stats.Incr("redis", msg)
  59. }
  60. }
  61. }
  62. }
  63. // DialTimeout acts like Dial but takes timeouts for establishing the
  64. // connection to the server, writing a command and reading a reply.
  65. //
  66. // Deprecated: Use Dial with options instead.
  67. func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error) {
  68. return Dial(network, address,
  69. DialConnectTimeout(connectTimeout),
  70. DialReadTimeout(readTimeout),
  71. DialWriteTimeout(writeTimeout))
  72. }
  73. // DialOption specifies an option for dialing a Redis server.
  74. type DialOption struct {
  75. f func(*dialOptions)
  76. }
  77. type dialOptions struct {
  78. readTimeout time.Duration
  79. writeTimeout time.Duration
  80. dial func(network, addr string) (net.Conn, error)
  81. db int
  82. password string
  83. stat func(string, *error) func()
  84. }
  85. // DialStats specifies stat func for stats.default statfunc.
  86. func DialStats(fn func(string, *error) func()) DialOption {
  87. return DialOption{func(do *dialOptions) {
  88. do.stat = fn
  89. }}
  90. }
  91. // DialReadTimeout specifies the timeout for reading a single command reply.
  92. func DialReadTimeout(d time.Duration) DialOption {
  93. return DialOption{func(do *dialOptions) {
  94. do.readTimeout = d
  95. }}
  96. }
  97. // DialWriteTimeout specifies the timeout for writing a single command.
  98. func DialWriteTimeout(d time.Duration) DialOption {
  99. return DialOption{func(do *dialOptions) {
  100. do.writeTimeout = d
  101. }}
  102. }
  103. // DialConnectTimeout specifies the timeout for connecting to the Redis server.
  104. func DialConnectTimeout(d time.Duration) DialOption {
  105. return DialOption{func(do *dialOptions) {
  106. dialer := net.Dialer{Timeout: d}
  107. do.dial = dialer.Dial
  108. }}
  109. }
  110. // DialNetDial specifies a custom dial function for creating TCP
  111. // connections. If this option is left out, then net.Dial is
  112. // used. DialNetDial overrides DialConnectTimeout.
  113. func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption {
  114. return DialOption{func(do *dialOptions) {
  115. do.dial = dial
  116. }}
  117. }
  118. // DialDatabase specifies the database to select when dialing a connection.
  119. func DialDatabase(db int) DialOption {
  120. return DialOption{func(do *dialOptions) {
  121. do.db = db
  122. }}
  123. }
  124. // DialPassword specifies the password to use when connecting to
  125. // the Redis server.
  126. func DialPassword(password string) DialOption {
  127. return DialOption{func(do *dialOptions) {
  128. do.password = password
  129. }}
  130. }
  131. // Dial connects to the Redis server at the given network and
  132. // address using the specified options.
  133. func Dial(network, address string, options ...DialOption) (Conn, error) {
  134. do := dialOptions{
  135. dial: net.Dial,
  136. }
  137. for _, option := range options {
  138. option.f(&do)
  139. }
  140. netConn, err := do.dial(network, address)
  141. if err != nil {
  142. return nil, errors.WithStack(err)
  143. }
  144. c := &conn{
  145. conn: netConn,
  146. bw: bufio.NewWriter(netConn),
  147. br: bufio.NewReader(netConn),
  148. readTimeout: do.readTimeout,
  149. writeTimeout: do.writeTimeout,
  150. stat: statfunc,
  151. }
  152. if do.password != "" {
  153. if _, err := c.Do("AUTH", do.password); err != nil {
  154. netConn.Close()
  155. return nil, errors.WithStack(err)
  156. }
  157. }
  158. if do.db != 0 {
  159. if _, err := c.Do("SELECT", do.db); err != nil {
  160. netConn.Close()
  161. return nil, errors.WithStack(err)
  162. }
  163. }
  164. if do.stat != nil {
  165. c.stat = do.stat
  166. }
  167. return c, nil
  168. }
  169. var pathDBRegexp = regexp.MustCompile(`/(\d+)\z`)
  170. // DialURL connects to a Redis server at the given URL using the Redis
  171. // URI scheme. URLs should follow the draft IANA specification for the
  172. // scheme (https://www.iana.org/assignments/uri-schemes/prov/redis).
  173. func DialURL(rawurl string, options ...DialOption) (Conn, error) {
  174. u, err := url.Parse(rawurl)
  175. if err != nil {
  176. return nil, errors.WithStack(err)
  177. }
  178. if u.Scheme != "redis" {
  179. return nil, fmt.Errorf("invalid redis URL scheme: %s", u.Scheme)
  180. }
  181. // As per the IANA draft spec, the host defaults to localhost and
  182. // the port defaults to 6379.
  183. host, port, err := net.SplitHostPort(u.Host)
  184. if err != nil {
  185. // assume port is missing
  186. host = u.Host
  187. port = "6379"
  188. }
  189. if host == "" {
  190. host = "localhost"
  191. }
  192. address := net.JoinHostPort(host, port)
  193. if u.User != nil {
  194. password, isSet := u.User.Password()
  195. if isSet {
  196. options = append(options, DialPassword(password))
  197. }
  198. }
  199. match := pathDBRegexp.FindStringSubmatch(u.Path)
  200. if len(match) == 2 {
  201. db, err := strconv.Atoi(match[1])
  202. if err != nil {
  203. return nil, errors.Errorf("invalid database: %s", u.Path[1:])
  204. }
  205. if db != 0 {
  206. options = append(options, DialDatabase(db))
  207. }
  208. } else if u.Path != "" {
  209. return nil, errors.Errorf("invalid database: %s", u.Path[1:])
  210. }
  211. return Dial("tcp", address, options...)
  212. }
  213. // NewConn new a redis conn.
  214. func NewConn(c *Config) (cn Conn, err error) {
  215. cnop := DialConnectTimeout(time.Duration(c.DialTimeout))
  216. rdop := DialReadTimeout(time.Duration(c.ReadTimeout))
  217. wrop := DialWriteTimeout(time.Duration(c.WriteTimeout))
  218. auop := DialPassword(c.Auth)
  219. // new conn
  220. cn, err = Dial(c.Proto, c.Addr, cnop, rdop, wrop, auop)
  221. return
  222. }
  223. func (c *conn) Close() error {
  224. c.mu.Lock()
  225. err := c.err
  226. if c.err == nil {
  227. c.err = errors.New("redigo: closed")
  228. err = c.conn.Close()
  229. }
  230. c.mu.Unlock()
  231. return err
  232. }
  233. func (c *conn) fatal(err error) error {
  234. c.mu.Lock()
  235. if c.err == nil {
  236. c.err = err
  237. // Close connection to force errors on subsequent calls and to unblock
  238. // other reader or writer.
  239. c.conn.Close()
  240. }
  241. c.mu.Unlock()
  242. return errors.WithStack(c.err)
  243. }
  244. func (c *conn) Err() error {
  245. c.mu.Lock()
  246. err := c.err
  247. c.mu.Unlock()
  248. return err
  249. }
  250. func (c *conn) writeLen(prefix byte, n int) error {
  251. c.lenScratch[len(c.lenScratch)-1] = '\n'
  252. c.lenScratch[len(c.lenScratch)-2] = '\r'
  253. i := len(c.lenScratch) - 3
  254. for {
  255. c.lenScratch[i] = byte('0' + n%10)
  256. i--
  257. n = n / 10
  258. if n == 0 {
  259. break
  260. }
  261. }
  262. c.lenScratch[i] = prefix
  263. _, err := c.bw.Write(c.lenScratch[i:])
  264. return errors.WithStack(err)
  265. }
  266. func (c *conn) writeString(s string) error {
  267. c.writeLen('$', len(s))
  268. c.bw.WriteString(s)
  269. _, err := c.bw.WriteString("\r\n")
  270. return errors.WithStack(err)
  271. }
  272. func (c *conn) writeBytes(p []byte) error {
  273. c.writeLen('$', len(p))
  274. c.bw.Write(p)
  275. _, err := c.bw.WriteString("\r\n")
  276. return errors.WithStack(err)
  277. }
  278. func (c *conn) writeInt64(n int64) error {
  279. return errors.WithStack(c.writeBytes(strconv.AppendInt(c.numScratch[:0], n, 10)))
  280. }
  281. func (c *conn) writeFloat64(n float64) error {
  282. return errors.WithStack(c.writeBytes(strconv.AppendFloat(c.numScratch[:0], n, 'g', -1, 64)))
  283. }
  284. func (c *conn) writeCommand(cmd string, args []interface{}) (err error) {
  285. if c.writeTimeout != 0 {
  286. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  287. }
  288. c.writeLen('*', 1+len(args))
  289. err = c.writeString(cmd)
  290. for _, arg := range args {
  291. if err != nil {
  292. break
  293. }
  294. switch arg := arg.(type) {
  295. case string:
  296. err = c.writeString(arg)
  297. case []byte:
  298. err = c.writeBytes(arg)
  299. case int:
  300. err = c.writeInt64(int64(arg))
  301. case int64:
  302. err = c.writeInt64(arg)
  303. case float64:
  304. err = c.writeFloat64(arg)
  305. case bool:
  306. if arg {
  307. err = c.writeString("1")
  308. } else {
  309. err = c.writeString("0")
  310. }
  311. case nil:
  312. err = c.writeString("")
  313. default:
  314. var buf bytes.Buffer
  315. fmt.Fprint(&buf, arg)
  316. err = errors.WithStack(c.writeBytes(buf.Bytes()))
  317. }
  318. }
  319. return err
  320. }
  321. type protocolError string
  322. func (pe protocolError) Error() string {
  323. return fmt.Sprintf("redigo: %s (possible server error or unsupported concurrent read by application)", string(pe))
  324. }
  325. func (c *conn) readLine() ([]byte, error) {
  326. p, err := c.br.ReadSlice('\n')
  327. if err == bufio.ErrBufferFull {
  328. return nil, errors.WithStack(protocolError("long response line"))
  329. }
  330. if err != nil {
  331. return nil, err
  332. }
  333. i := len(p) - 2
  334. if i < 0 || p[i] != '\r' {
  335. return nil, errors.WithStack(protocolError("bad response line terminator"))
  336. }
  337. return p[:i], nil
  338. }
  339. // parseLen parses bulk string and array lengths.
  340. func parseLen(p []byte) (int, error) {
  341. if len(p) == 0 {
  342. return -1, errors.WithStack(protocolError("malformed length"))
  343. }
  344. if p[0] == '-' && len(p) == 2 && p[1] == '1' {
  345. // handle $-1 and $-1 null replies.
  346. return -1, nil
  347. }
  348. var n int
  349. for _, b := range p {
  350. n *= 10
  351. if b < '0' || b > '9' {
  352. return -1, errors.WithStack(protocolError("illegal bytes in length"))
  353. }
  354. n += int(b - '0')
  355. }
  356. return n, nil
  357. }
  358. // parseInt parses an integer reply.
  359. func parseInt(p []byte) (interface{}, error) {
  360. if len(p) == 0 {
  361. return 0, errors.WithStack(protocolError("malformed integer"))
  362. }
  363. var negate bool
  364. if p[0] == '-' {
  365. negate = true
  366. p = p[1:]
  367. if len(p) == 0 {
  368. return 0, errors.WithStack(protocolError("malformed integer"))
  369. }
  370. }
  371. var n int64
  372. for _, b := range p {
  373. n *= 10
  374. if b < '0' || b > '9' {
  375. return 0, errors.WithStack(protocolError("illegal bytes in length"))
  376. }
  377. n += int64(b - '0')
  378. }
  379. if negate {
  380. n = -n
  381. }
  382. return n, nil
  383. }
  384. var (
  385. okReply interface{} = "OK"
  386. pongReply interface{} = "PONG"
  387. )
  388. func (c *conn) readReply() (interface{}, error) {
  389. line, err := c.readLine()
  390. if err != nil {
  391. return nil, err
  392. }
  393. if len(line) == 0 {
  394. return nil, errors.WithStack(protocolError("short response line"))
  395. }
  396. switch line[0] {
  397. case '+':
  398. switch {
  399. case len(line) == 3 && line[1] == 'O' && line[2] == 'K':
  400. // Avoid allocation for frequent "+OK" response.
  401. return okReply, nil
  402. case len(line) == 5 && line[1] == 'P' && line[2] == 'O' && line[3] == 'N' && line[4] == 'G':
  403. // Avoid allocation in PING command benchmarks :)
  404. return pongReply, nil
  405. default:
  406. return string(line[1:]), nil
  407. }
  408. case '-':
  409. return Error(string(line[1:])), nil
  410. case ':':
  411. return parseInt(line[1:])
  412. case '$':
  413. n, err := parseLen(line[1:])
  414. if n < 0 || err != nil {
  415. return nil, err
  416. }
  417. p := make([]byte, n)
  418. _, err = io.ReadFull(c.br, p)
  419. if err != nil {
  420. return nil, errors.WithStack(err)
  421. }
  422. if line1, err := c.readLine(); err != nil {
  423. return nil, err
  424. } else if len(line1) != 0 {
  425. return nil, errors.WithStack(protocolError("bad bulk string format"))
  426. }
  427. return p, nil
  428. case '*':
  429. n, err := parseLen(line[1:])
  430. if n < 0 || err != nil {
  431. return nil, err
  432. }
  433. r := make([]interface{}, n)
  434. for i := range r {
  435. r[i], err = c.readReply()
  436. if err != nil {
  437. return nil, err
  438. }
  439. }
  440. return r, nil
  441. }
  442. return nil, errors.WithStack(protocolError("unexpected response line"))
  443. }
  444. func (c *conn) Send(cmd string, args ...interface{}) (err error) {
  445. c.mu.Lock()
  446. c.pending++
  447. c.mu.Unlock()
  448. if err = c.writeCommand(cmd, args); err != nil {
  449. c.fatal(err)
  450. }
  451. return err
  452. }
  453. func (c *conn) Flush() (err error) {
  454. if c.writeTimeout != 0 {
  455. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  456. }
  457. if err = c.bw.Flush(); err != nil {
  458. c.fatal(err)
  459. }
  460. return err
  461. }
  462. func (c *conn) Receive() (reply interface{}, err error) {
  463. if c.readTimeout != 0 {
  464. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  465. }
  466. if reply, err = c.readReply(); err != nil {
  467. return nil, c.fatal(err)
  468. }
  469. // When using pub/sub, the number of receives can be greater than the
  470. // number of sends. To enable normal use of the connection after
  471. // unsubscribing from all channels, we do not decrement pending to a
  472. // negative value.
  473. //
  474. // The pending field is decremented after the reply is read to handle the
  475. // case where Receive is called before Send.
  476. c.mu.Lock()
  477. if c.pending > 0 {
  478. c.pending--
  479. }
  480. c.mu.Unlock()
  481. if err, ok := reply.(Error); ok {
  482. return nil, err
  483. }
  484. return
  485. }
  486. func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
  487. c.mu.Lock()
  488. pending := c.pending
  489. c.pending = 0
  490. c.mu.Unlock()
  491. if cmd == "" && pending == 0 {
  492. return nil, nil
  493. }
  494. var err error
  495. defer c.stat(cmd, &err)()
  496. if cmd != "" {
  497. err = c.writeCommand(cmd, args)
  498. }
  499. if err == nil {
  500. err = errors.WithStack(c.bw.Flush())
  501. }
  502. if err != nil {
  503. return nil, c.fatal(err)
  504. }
  505. if c.readTimeout != 0 {
  506. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  507. }
  508. if cmd == "" {
  509. reply := make([]interface{}, pending)
  510. for i := range reply {
  511. var r interface{}
  512. r, err = c.readReply()
  513. if err != nil {
  514. break
  515. }
  516. reply[i] = r
  517. }
  518. if err != nil {
  519. return nil, c.fatal(err)
  520. }
  521. return reply, nil
  522. }
  523. var reply interface{}
  524. for i := 0; i <= pending; i++ {
  525. var e error
  526. if reply, e = c.readReply(); e != nil {
  527. return nil, c.fatal(e)
  528. }
  529. if e, ok := reply.(Error); ok && err == nil {
  530. err = e
  531. }
  532. }
  533. return reply, err
  534. }
  535. // WithContext FIXME: implement WithContext
  536. func (c *conn) WithContext(ctx context.Context) Conn { return c }