本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

688 lines
19KB

  1. /*
  2. Copyright 2011 Google Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package memcache provides a client for the memcached cache server.
  14. package memcache
  15. import (
  16. "bufio"
  17. "bytes"
  18. "errors"
  19. "fmt"
  20. "io"
  21. "net"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "time"
  26. )
  27. // Similar to:
  28. // https://godoc.org/google.golang.org/appengine/memcache
  29. var (
  30. // ErrCacheMiss means that a Get failed because the item wasn't present.
  31. ErrCacheMiss = errors.New("memcache: cache miss")
  32. // ErrCASConflict means that a CompareAndSwap call failed due to the
  33. // cached value being modified between the Get and the CompareAndSwap.
  34. // If the cached value was simply evicted rather than replaced,
  35. // ErrNotStored will be returned instead.
  36. ErrCASConflict = errors.New("memcache: compare-and-swap conflict")
  37. // ErrNotStored means that a conditional write operation (i.e. Add or
  38. // CompareAndSwap) failed because the condition was not satisfied.
  39. ErrNotStored = errors.New("memcache: item not stored")
  40. // ErrServer means that a server error occurred.
  41. ErrServerError = errors.New("memcache: server error")
  42. // ErrNoStats means that no statistics were available.
  43. ErrNoStats = errors.New("memcache: no statistics available")
  44. // ErrMalformedKey is returned when an invalid key is used.
  45. // Keys must be at maximum 250 bytes long and not
  46. // contain whitespace or control characters.
  47. ErrMalformedKey = errors.New("malformed: key is too long or contains invalid characters")
  48. // ErrNoServers is returned when no servers are configured or available.
  49. ErrNoServers = errors.New("memcache: no servers configured or available")
  50. )
  51. const (
  52. // DefaultTimeout is the default socket read/write timeout.
  53. DefaultTimeout = 100 * time.Millisecond
  54. // DefaultMaxIdleConns is the default maximum number of idle connections
  55. // kept for any single address.
  56. DefaultMaxIdleConns = 2
  57. )
  58. const buffered = 8 // arbitrary buffered channel size, for readability
  59. // resumableError returns true if err is only a protocol-level cache error.
  60. // This is used to determine whether or not a server connection should
  61. // be re-used or not. If an error occurs, by default we don't reuse the
  62. // connection, unless it was just a cache error.
  63. func resumableError(err error) bool {
  64. switch err {
  65. case ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrMalformedKey:
  66. return true
  67. }
  68. return false
  69. }
  70. func legalKey(key string) bool {
  71. if len(key) > 250 {
  72. return false
  73. }
  74. for i := 0; i < len(key); i++ {
  75. if key[i] <= ' ' || key[i] == 0x7f {
  76. return false
  77. }
  78. }
  79. return true
  80. }
  81. var (
  82. crlf = []byte("\r\n")
  83. space = []byte(" ")
  84. resultOK = []byte("OK\r\n")
  85. resultStored = []byte("STORED\r\n")
  86. resultNotStored = []byte("NOT_STORED\r\n")
  87. resultExists = []byte("EXISTS\r\n")
  88. resultNotFound = []byte("NOT_FOUND\r\n")
  89. resultDeleted = []byte("DELETED\r\n")
  90. resultEnd = []byte("END\r\n")
  91. resultOk = []byte("OK\r\n")
  92. resultTouched = []byte("TOUCHED\r\n")
  93. resultClientErrorPrefix = []byte("CLIENT_ERROR ")
  94. )
  95. // New returns a memcache client using the provided server(s)
  96. // with equal weight. If a server is listed multiple times,
  97. // it gets a proportional amount of weight.
  98. func New(server ...string) *Client {
  99. ss := new(ServerList)
  100. ss.SetServers(server...)
  101. return NewFromSelector(ss)
  102. }
  103. // NewFromSelector returns a new Client using the provided ServerSelector.
  104. func NewFromSelector(ss ServerSelector) *Client {
  105. return &Client{selector: ss}
  106. }
  107. // Client is a memcache client.
  108. // It is safe for unlocked use by multiple concurrent goroutines.
  109. type Client struct {
  110. // Timeout specifies the socket read/write timeout.
  111. // If zero, DefaultTimeout is used.
  112. Timeout time.Duration
  113. // MaxIdleConns specifies the maximum number of idle connections that will
  114. // be maintained per address. If less than one, DefaultMaxIdleConns will be
  115. // used.
  116. //
  117. // Consider your expected traffic rates and latency carefully. This should
  118. // be set to a number higher than your peak parallel requests.
  119. MaxIdleConns int
  120. selector ServerSelector
  121. lk sync.Mutex
  122. freeconn map[string][]*conn
  123. }
  124. // Item is an item to be got or stored in a memcached server.
  125. type Item struct {
  126. // Key is the Item's key (250 bytes maximum).
  127. Key string
  128. // Value is the Item's value.
  129. Value []byte
  130. // Flags are server-opaque flags whose semantics are entirely
  131. // up to the app.
  132. Flags uint32
  133. // Expiration is the cache expiration time, in seconds: either a relative
  134. // time from now (up to 1 month), or an absolute Unix epoch time.
  135. // Zero means the Item has no expiration time.
  136. Expiration int32
  137. // Compare and swap ID.
  138. casid uint64
  139. }
  140. // conn is a connection to a server.
  141. type conn struct {
  142. nc net.Conn
  143. rw *bufio.ReadWriter
  144. addr net.Addr
  145. c *Client
  146. }
  147. // release returns this connection back to the client's free pool
  148. func (cn *conn) release() {
  149. cn.c.putFreeConn(cn.addr, cn)
  150. }
  151. func (cn *conn) extendDeadline() {
  152. cn.nc.SetDeadline(time.Now().Add(cn.c.netTimeout()))
  153. }
  154. // condRelease releases this connection if the error pointed to by err
  155. // is nil (not an error) or is only a protocol level error (e.g. a
  156. // cache miss). The purpose is to not recycle TCP connections that
  157. // are bad.
  158. func (cn *conn) condRelease(err *error) {
  159. if *err == nil || resumableError(*err) {
  160. cn.release()
  161. } else {
  162. cn.nc.Close()
  163. }
  164. }
  165. func (c *Client) putFreeConn(addr net.Addr, cn *conn) {
  166. c.lk.Lock()
  167. defer c.lk.Unlock()
  168. if c.freeconn == nil {
  169. c.freeconn = make(map[string][]*conn)
  170. }
  171. freelist := c.freeconn[addr.String()]
  172. if len(freelist) >= c.maxIdleConns() {
  173. cn.nc.Close()
  174. return
  175. }
  176. c.freeconn[addr.String()] = append(freelist, cn)
  177. }
  178. func (c *Client) getFreeConn(addr net.Addr) (cn *conn, ok bool) {
  179. c.lk.Lock()
  180. defer c.lk.Unlock()
  181. if c.freeconn == nil {
  182. return nil, false
  183. }
  184. freelist, ok := c.freeconn[addr.String()]
  185. if !ok || len(freelist) == 0 {
  186. return nil, false
  187. }
  188. cn = freelist[len(freelist)-1]
  189. c.freeconn[addr.String()] = freelist[:len(freelist)-1]
  190. return cn, true
  191. }
  192. func (c *Client) netTimeout() time.Duration {
  193. if c.Timeout != 0 {
  194. return c.Timeout
  195. }
  196. return DefaultTimeout
  197. }
  198. func (c *Client) maxIdleConns() int {
  199. if c.MaxIdleConns > 0 {
  200. return c.MaxIdleConns
  201. }
  202. return DefaultMaxIdleConns
  203. }
  204. // ConnectTimeoutError is the error type used when it takes
  205. // too long to connect to the desired host. This level of
  206. // detail can generally be ignored.
  207. type ConnectTimeoutError struct {
  208. Addr net.Addr
  209. }
  210. func (cte *ConnectTimeoutError) Error() string {
  211. return "memcache: connect timeout to " + cte.Addr.String()
  212. }
  213. func (c *Client) dial(addr net.Addr) (net.Conn, error) {
  214. type connError struct {
  215. cn net.Conn
  216. err error
  217. }
  218. nc, err := net.DialTimeout(addr.Network(), addr.String(), c.netTimeout())
  219. if err == nil {
  220. return nc, nil
  221. }
  222. if ne, ok := err.(net.Error); ok && ne.Timeout() {
  223. return nil, &ConnectTimeoutError{addr}
  224. }
  225. return nil, err
  226. }
  227. func (c *Client) getConn(addr net.Addr) (*conn, error) {
  228. cn, ok := c.getFreeConn(addr)
  229. if ok {
  230. cn.extendDeadline()
  231. return cn, nil
  232. }
  233. nc, err := c.dial(addr)
  234. if err != nil {
  235. return nil, err
  236. }
  237. cn = &conn{
  238. nc: nc,
  239. addr: addr,
  240. rw: bufio.NewReadWriter(bufio.NewReader(nc), bufio.NewWriter(nc)),
  241. c: c,
  242. }
  243. cn.extendDeadline()
  244. return cn, nil
  245. }
  246. func (c *Client) onItem(item *Item, fn func(*Client, *bufio.ReadWriter, *Item) error) error {
  247. addr, err := c.selector.PickServer(item.Key)
  248. if err != nil {
  249. return err
  250. }
  251. cn, err := c.getConn(addr)
  252. if err != nil {
  253. return err
  254. }
  255. defer cn.condRelease(&err)
  256. if err = fn(c, cn.rw, item); err != nil {
  257. return err
  258. }
  259. return nil
  260. }
  261. func (c *Client) FlushAll() error {
  262. return c.selector.Each(c.flushAllFromAddr)
  263. }
  264. // Get gets the item for the given key. ErrCacheMiss is returned for a
  265. // memcache cache miss. The key must be at most 250 bytes in length.
  266. func (c *Client) Get(key string) (item *Item, err error) {
  267. err = c.withKeyAddr(key, func(addr net.Addr) error {
  268. return c.getFromAddr(addr, []string{key}, func(it *Item) { item = it })
  269. })
  270. if err == nil && item == nil {
  271. err = ErrCacheMiss
  272. }
  273. return
  274. }
  275. // Touch updates the expiry for the given key. The seconds parameter is either
  276. // a Unix timestamp or, if seconds is less than 1 month, the number of seconds
  277. // into the future at which time the item will expire. Zero means the item has
  278. // no expiration time. ErrCacheMiss is returned if the key is not in the cache.
  279. // The key must be at most 250 bytes in length.
  280. func (c *Client) Touch(key string, seconds int32) (err error) {
  281. return c.withKeyAddr(key, func(addr net.Addr) error {
  282. return c.touchFromAddr(addr, []string{key}, seconds)
  283. })
  284. }
  285. func (c *Client) withKeyAddr(key string, fn func(net.Addr) error) (err error) {
  286. if !legalKey(key) {
  287. return ErrMalformedKey
  288. }
  289. addr, err := c.selector.PickServer(key)
  290. if err != nil {
  291. return err
  292. }
  293. return fn(addr)
  294. }
  295. func (c *Client) withAddrRw(addr net.Addr, fn func(*bufio.ReadWriter) error) (err error) {
  296. cn, err := c.getConn(addr)
  297. if err != nil {
  298. return err
  299. }
  300. defer cn.condRelease(&err)
  301. return fn(cn.rw)
  302. }
  303. func (c *Client) withKeyRw(key string, fn func(*bufio.ReadWriter) error) error {
  304. return c.withKeyAddr(key, func(addr net.Addr) error {
  305. return c.withAddrRw(addr, fn)
  306. })
  307. }
  308. func (c *Client) getFromAddr(addr net.Addr, keys []string, cb func(*Item)) error {
  309. return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
  310. if _, err := fmt.Fprintf(rw, "gets %s\r\n", strings.Join(keys, " ")); err != nil {
  311. return err
  312. }
  313. if err := rw.Flush(); err != nil {
  314. return err
  315. }
  316. if err := parseGetResponse(rw.Reader, cb); err != nil {
  317. return err
  318. }
  319. return nil
  320. })
  321. }
  322. // flushAllFromAddr send the flush_all command to the given addr
  323. func (c *Client) flushAllFromAddr(addr net.Addr) error {
  324. return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
  325. if _, err := fmt.Fprintf(rw, "flush_all\r\n"); err != nil {
  326. return err
  327. }
  328. if err := rw.Flush(); err != nil {
  329. return err
  330. }
  331. line, err := rw.ReadSlice('\n')
  332. if err != nil {
  333. return err
  334. }
  335. switch {
  336. case bytes.Equal(line, resultOk):
  337. break
  338. default:
  339. return fmt.Errorf("memcache: unexpected response line from flush_all: %q", string(line))
  340. }
  341. return nil
  342. })
  343. }
  344. func (c *Client) touchFromAddr(addr net.Addr, keys []string, expiration int32) error {
  345. return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
  346. for _, key := range keys {
  347. if _, err := fmt.Fprintf(rw, "touch %s %d\r\n", key, expiration); err != nil {
  348. return err
  349. }
  350. if err := rw.Flush(); err != nil {
  351. return err
  352. }
  353. line, err := rw.ReadSlice('\n')
  354. if err != nil {
  355. return err
  356. }
  357. switch {
  358. case bytes.Equal(line, resultTouched):
  359. break
  360. case bytes.Equal(line, resultNotFound):
  361. return ErrCacheMiss
  362. default:
  363. return fmt.Errorf("memcache: unexpected response line from touch: %q", string(line))
  364. }
  365. }
  366. return nil
  367. })
  368. }
  369. // GetMulti is a batch version of Get. The returned map from keys to
  370. // items may have fewer elements than the input slice, due to memcache
  371. // cache misses. Each key must be at most 250 bytes in length.
  372. // If no error is returned, the returned map will also be non-nil.
  373. func (c *Client) GetMulti(keys []string) (map[string]*Item, error) {
  374. var lk sync.Mutex
  375. m := make(map[string]*Item)
  376. addItemToMap := func(it *Item) {
  377. lk.Lock()
  378. defer lk.Unlock()
  379. m[it.Key] = it
  380. }
  381. keyMap := make(map[net.Addr][]string)
  382. for _, key := range keys {
  383. if !legalKey(key) {
  384. return nil, ErrMalformedKey
  385. }
  386. addr, err := c.selector.PickServer(key)
  387. if err != nil {
  388. return nil, err
  389. }
  390. keyMap[addr] = append(keyMap[addr], key)
  391. }
  392. ch := make(chan error, buffered)
  393. for addr, keys := range keyMap {
  394. go func(addr net.Addr, keys []string) {
  395. ch <- c.getFromAddr(addr, keys, addItemToMap)
  396. }(addr, keys)
  397. }
  398. var err error
  399. for _ = range keyMap {
  400. if ge := <-ch; ge != nil {
  401. err = ge
  402. }
  403. }
  404. return m, err
  405. }
  406. // parseGetResponse reads a GET response from r and calls cb for each
  407. // read and allocated Item
  408. func parseGetResponse(r *bufio.Reader, cb func(*Item)) error {
  409. for {
  410. line, err := r.ReadSlice('\n')
  411. if err != nil {
  412. return err
  413. }
  414. if bytes.Equal(line, resultEnd) {
  415. return nil
  416. }
  417. it := new(Item)
  418. size, err := scanGetResponseLine(line, it)
  419. if err != nil {
  420. return err
  421. }
  422. it.Value = make([]byte, size+2)
  423. _, err = io.ReadFull(r, it.Value)
  424. if err != nil {
  425. it.Value = nil
  426. return err
  427. }
  428. if !bytes.HasSuffix(it.Value, crlf) {
  429. it.Value = nil
  430. return fmt.Errorf("memcache: corrupt get result read")
  431. }
  432. it.Value = it.Value[:size]
  433. cb(it)
  434. }
  435. }
  436. // scanGetResponseLine populates it and returns the declared size of the item.
  437. // It does not read the bytes of the item.
  438. func scanGetResponseLine(line []byte, it *Item) (size int, err error) {
  439. pattern := "VALUE %s %d %d %d\r\n"
  440. dest := []interface{}{&it.Key, &it.Flags, &size, &it.casid}
  441. if bytes.Count(line, space) == 3 {
  442. pattern = "VALUE %s %d %d\r\n"
  443. dest = dest[:3]
  444. }
  445. n, err := fmt.Sscanf(string(line), pattern, dest...)
  446. if err != nil || n != len(dest) {
  447. return -1, fmt.Errorf("memcache: unexpected line in get response: %q", line)
  448. }
  449. return size, nil
  450. }
  451. // Set writes the given item, unconditionally.
  452. func (c *Client) Set(item *Item) error {
  453. return c.onItem(item, (*Client).set)
  454. }
  455. func (c *Client) set(rw *bufio.ReadWriter, item *Item) error {
  456. return c.populateOne(rw, "set", item)
  457. }
  458. // Add writes the given item, if no value already exists for its
  459. // key. ErrNotStored is returned if that condition is not met.
  460. func (c *Client) Add(item *Item) error {
  461. return c.onItem(item, (*Client).add)
  462. }
  463. func (c *Client) add(rw *bufio.ReadWriter, item *Item) error {
  464. return c.populateOne(rw, "add", item)
  465. }
  466. // Replace writes the given item, but only if the server *does*
  467. // already hold data for this key
  468. func (c *Client) Replace(item *Item) error {
  469. return c.onItem(item, (*Client).replace)
  470. }
  471. func (c *Client) replace(rw *bufio.ReadWriter, item *Item) error {
  472. return c.populateOne(rw, "replace", item)
  473. }
  474. // CompareAndSwap writes the given item that was previously returned
  475. // by Get, if the value was neither modified or evicted between the
  476. // Get and the CompareAndSwap calls. The item's Key should not change
  477. // between calls but all other item fields may differ. ErrCASConflict
  478. // is returned if the value was modified in between the
  479. // calls. ErrNotStored is returned if the value was evicted in between
  480. // the calls.
  481. func (c *Client) CompareAndSwap(item *Item) error {
  482. return c.onItem(item, (*Client).cas)
  483. }
  484. func (c *Client) cas(rw *bufio.ReadWriter, item *Item) error {
  485. return c.populateOne(rw, "cas", item)
  486. }
  487. func (c *Client) populateOne(rw *bufio.ReadWriter, verb string, item *Item) error {
  488. if !legalKey(item.Key) {
  489. return ErrMalformedKey
  490. }
  491. var err error
  492. if verb == "cas" {
  493. _, err = fmt.Fprintf(rw, "%s %s %d %d %d %d\r\n",
  494. verb, item.Key, item.Flags, item.Expiration, len(item.Value), item.casid)
  495. } else {
  496. _, err = fmt.Fprintf(rw, "%s %s %d %d %d\r\n",
  497. verb, item.Key, item.Flags, item.Expiration, len(item.Value))
  498. }
  499. if err != nil {
  500. return err
  501. }
  502. if _, err = rw.Write(item.Value); err != nil {
  503. return err
  504. }
  505. if _, err := rw.Write(crlf); err != nil {
  506. return err
  507. }
  508. if err := rw.Flush(); err != nil {
  509. return err
  510. }
  511. line, err := rw.ReadSlice('\n')
  512. if err != nil {
  513. return err
  514. }
  515. switch {
  516. case bytes.Equal(line, resultStored):
  517. return nil
  518. case bytes.Equal(line, resultNotStored):
  519. return ErrNotStored
  520. case bytes.Equal(line, resultExists):
  521. return ErrCASConflict
  522. case bytes.Equal(line, resultNotFound):
  523. return ErrCacheMiss
  524. }
  525. return fmt.Errorf("memcache: unexpected response line from %q: %q", verb, string(line))
  526. }
  527. func writeReadLine(rw *bufio.ReadWriter, format string, args ...interface{}) ([]byte, error) {
  528. _, err := fmt.Fprintf(rw, format, args...)
  529. if err != nil {
  530. return nil, err
  531. }
  532. if err := rw.Flush(); err != nil {
  533. return nil, err
  534. }
  535. line, err := rw.ReadSlice('\n')
  536. return line, err
  537. }
  538. func writeExpectf(rw *bufio.ReadWriter, expect []byte, format string, args ...interface{}) error {
  539. line, err := writeReadLine(rw, format, args...)
  540. if err != nil {
  541. return err
  542. }
  543. switch {
  544. case bytes.Equal(line, resultOK):
  545. return nil
  546. case bytes.Equal(line, expect):
  547. return nil
  548. case bytes.Equal(line, resultNotStored):
  549. return ErrNotStored
  550. case bytes.Equal(line, resultExists):
  551. return ErrCASConflict
  552. case bytes.Equal(line, resultNotFound):
  553. return ErrCacheMiss
  554. }
  555. return fmt.Errorf("memcache: unexpected response line: %q", string(line))
  556. }
  557. // Delete deletes the item with the provided key. The error ErrCacheMiss is
  558. // returned if the item didn't already exist in the cache.
  559. func (c *Client) Delete(key string) error {
  560. return c.withKeyRw(key, func(rw *bufio.ReadWriter) error {
  561. return writeExpectf(rw, resultDeleted, "delete %s\r\n", key)
  562. })
  563. }
  564. // DeleteAll deletes all items in the cache.
  565. func (c *Client) DeleteAll() error {
  566. return c.withKeyRw("", func(rw *bufio.ReadWriter) error {
  567. return writeExpectf(rw, resultDeleted, "flush_all\r\n")
  568. })
  569. }
  570. // Increment atomically increments key by delta. The return value is
  571. // the new value after being incremented or an error. If the value
  572. // didn't exist in memcached the error is ErrCacheMiss. The value in
  573. // memcached must be an decimal number, or an error will be returned.
  574. // On 64-bit overflow, the new value wraps around.
  575. func (c *Client) Increment(key string, delta uint64) (newValue uint64, err error) {
  576. return c.incrDecr("incr", key, delta)
  577. }
  578. // Decrement atomically decrements key by delta. The return value is
  579. // the new value after being decremented or an error. If the value
  580. // didn't exist in memcached the error is ErrCacheMiss. The value in
  581. // memcached must be an decimal number, or an error will be returned.
  582. // On underflow, the new value is capped at zero and does not wrap
  583. // around.
  584. func (c *Client) Decrement(key string, delta uint64) (newValue uint64, err error) {
  585. return c.incrDecr("decr", key, delta)
  586. }
  587. func (c *Client) incrDecr(verb, key string, delta uint64) (uint64, error) {
  588. var val uint64
  589. err := c.withKeyRw(key, func(rw *bufio.ReadWriter) error {
  590. line, err := writeReadLine(rw, "%s %s %d\r\n", verb, key, delta)
  591. if err != nil {
  592. return err
  593. }
  594. switch {
  595. case bytes.Equal(line, resultNotFound):
  596. return ErrCacheMiss
  597. case bytes.HasPrefix(line, resultClientErrorPrefix):
  598. errMsg := line[len(resultClientErrorPrefix) : len(line)-2]
  599. return errors.New("memcache: client error: " + string(errMsg))
  600. }
  601. val, err = strconv.ParseUint(string(line[:len(line)-2]), 10, 64)
  602. if err != nil {
  603. return err
  604. }
  605. return nil
  606. })
  607. return val, err
  608. }
上海开阖软件有限公司 沪ICP备12045867号-1