memcache.go 18 KB

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