memcache.go 18 KB

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