memcache.go 16 KB

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