memcache.go 17 KB

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