memcache.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. func (c *Client) Touch(key string, seconds int32) (err error) {
  270. return c.withKeyAddr(key, func(addr net.Addr) error {
  271. return c.touchFromAddr(addr, []string{key}, seconds)
  272. })
  273. }
  274. func (c *Client) withKeyAddr(key string, fn func(net.Addr) error) (err error) {
  275. if !legalKey(key) {
  276. return ErrMalformedKey
  277. }
  278. addr, err := c.selector.PickServer(key)
  279. if err != nil {
  280. return err
  281. }
  282. return fn(addr)
  283. }
  284. func (c *Client) withAddrRw(addr net.Addr, fn func(*bufio.ReadWriter) error) (err error) {
  285. cn, err := c.getConn(addr)
  286. if err != nil {
  287. return err
  288. }
  289. defer cn.condRelease(&err)
  290. return fn(cn.rw)
  291. }
  292. func (c *Client) withKeyRw(key string, fn func(*bufio.ReadWriter) error) error {
  293. return c.withKeyAddr(key, func(addr net.Addr) error {
  294. return c.withAddrRw(addr, fn)
  295. })
  296. }
  297. func (c *Client) getFromAddr(addr net.Addr, keys []string, cb func(*Item)) error {
  298. return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
  299. if _, err := fmt.Fprintf(rw, "gets %s\r\n", strings.Join(keys, " ")); err != nil {
  300. return err
  301. }
  302. if err := rw.Flush(); err != nil {
  303. return err
  304. }
  305. if err := parseGetResponse(rw.Reader, cb); err != nil {
  306. return err
  307. }
  308. return nil
  309. })
  310. }
  311. func (c *Client) touchFromAddr(addr net.Addr, keys []string, expiration int32) error {
  312. return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
  313. for _, key := range keys {
  314. if _, err := fmt.Fprintf(rw, "touch %s %d\r\n", key, expiration); err != nil {
  315. return err
  316. }
  317. if err := rw.Flush(); err != nil {
  318. return err
  319. }
  320. line, err := rw.ReadSlice('\n')
  321. if err != nil {
  322. return err
  323. }
  324. switch {
  325. case bytes.Equal(line, resultTouched):
  326. break
  327. case bytes.Equal(line, resultNotFound):
  328. return ErrCacheMiss
  329. default:
  330. return fmt.Errorf("memcache: unexpected response line from touch: %q", string(line))
  331. }
  332. }
  333. return nil
  334. })
  335. }
  336. // GetMulti is a batch version of Get. The returned map from keys to
  337. // items may have fewer elements than the input slice, due to memcache
  338. // cache misses. Each key must be at most 250 bytes in length.
  339. // If no error is returned, the returned map will also be non-nil.
  340. func (c *Client) GetMulti(keys []string) (map[string]*Item, error) {
  341. var lk sync.Mutex
  342. m := make(map[string]*Item)
  343. addItemToMap := func(it *Item) {
  344. lk.Lock()
  345. defer lk.Unlock()
  346. m[it.Key] = it
  347. }
  348. keyMap := make(map[net.Addr][]string)
  349. for _, key := range keys {
  350. if !legalKey(key) {
  351. return nil, ErrMalformedKey
  352. }
  353. addr, err := c.selector.PickServer(key)
  354. if err != nil {
  355. return nil, err
  356. }
  357. keyMap[addr] = append(keyMap[addr], key)
  358. }
  359. ch := make(chan error, buffered)
  360. for addr, keys := range keyMap {
  361. go func(addr net.Addr, keys []string) {
  362. ch <- c.getFromAddr(addr, keys, addItemToMap)
  363. }(addr, keys)
  364. }
  365. var err error
  366. for _ = range keyMap {
  367. if ge := <-ch; ge != nil {
  368. err = ge
  369. }
  370. }
  371. return m, err
  372. }
  373. // parseGetResponse reads a GET response from r and calls cb for each
  374. // read and allocated Item
  375. func parseGetResponse(r *bufio.Reader, cb func(*Item)) error {
  376. for {
  377. line, err := r.ReadSlice('\n')
  378. if err != nil {
  379. return err
  380. }
  381. if bytes.Equal(line, resultEnd) {
  382. return nil
  383. }
  384. it := new(Item)
  385. size, err := scanGetResponseLine(line, it)
  386. if err != nil {
  387. return err
  388. }
  389. it.Value, err = ioutil.ReadAll(io.LimitReader(r, int64(size)+2))
  390. if err != nil {
  391. return err
  392. }
  393. if !bytes.HasSuffix(it.Value, crlf) {
  394. return fmt.Errorf("memcache: corrupt get result read")
  395. }
  396. it.Value = it.Value[:size]
  397. cb(it)
  398. }
  399. panic("unreached")
  400. }
  401. // scanGetResponseLine populates it and returns the declared size of the item.
  402. // It does not read the bytes of the item.
  403. func scanGetResponseLine(line []byte, it *Item) (size int, err error) {
  404. pattern := "VALUE %s %d %d %d\r\n"
  405. dest := []interface{}{&it.Key, &it.Flags, &size, &it.casid}
  406. if bytes.Count(line, space) == 3 {
  407. pattern = "VALUE %s %d %d\r\n"
  408. dest = dest[:3]
  409. }
  410. n, err := fmt.Sscanf(string(line), pattern, dest...)
  411. if err != nil || n != len(dest) {
  412. return -1, fmt.Errorf("memcache: unexpected line in get response: %q", line)
  413. }
  414. return size, nil
  415. }
  416. // Set writes the given item, unconditionally.
  417. func (c *Client) Set(item *Item) error {
  418. return c.onItem(item, (*Client).set)
  419. }
  420. func (c *Client) set(rw *bufio.ReadWriter, item *Item) error {
  421. return c.populateOne(rw, "set", item)
  422. }
  423. // Add writes the given item, if no value already exists for its
  424. // key. ErrNotStored is returned if that condition is not met.
  425. func (c *Client) Add(item *Item) error {
  426. return c.onItem(item, (*Client).add)
  427. }
  428. func (c *Client) add(rw *bufio.ReadWriter, item *Item) error {
  429. return c.populateOne(rw, "add", item)
  430. }
  431. // CompareAndSwap writes the given item that was previously returned
  432. // by Get, if the value was neither modified or evicted between the
  433. // Get and the CompareAndSwap calls. The item's Key should not change
  434. // between calls but all other item fields may differ. ErrCASConflict
  435. // is returned if the value was modified in between the
  436. // calls. ErrNotStored is returned if the value was evicted in between
  437. // the calls.
  438. func (c *Client) CompareAndSwap(item *Item) error {
  439. return c.onItem(item, (*Client).cas)
  440. }
  441. func (c *Client) cas(rw *bufio.ReadWriter, item *Item) error {
  442. return c.populateOne(rw, "cas", item)
  443. }
  444. func (c *Client) populateOne(rw *bufio.ReadWriter, verb string, item *Item) error {
  445. if !legalKey(item.Key) {
  446. return ErrMalformedKey
  447. }
  448. var err error
  449. if verb == "cas" {
  450. _, err = fmt.Fprintf(rw, "%s %s %d %d %d %d\r\n",
  451. verb, item.Key, item.Flags, item.Expiration, len(item.Value), item.casid)
  452. } else {
  453. _, err = fmt.Fprintf(rw, "%s %s %d %d %d\r\n",
  454. verb, item.Key, item.Flags, item.Expiration, len(item.Value))
  455. }
  456. if err != nil {
  457. return err
  458. }
  459. if _, err = rw.Write(item.Value); err != nil {
  460. return err
  461. }
  462. if _, err := rw.Write(crlf); err != nil {
  463. return err
  464. }
  465. if err := rw.Flush(); err != nil {
  466. return err
  467. }
  468. line, err := rw.ReadSlice('\n')
  469. if err != nil {
  470. return err
  471. }
  472. switch {
  473. case bytes.Equal(line, resultStored):
  474. return nil
  475. case bytes.Equal(line, resultNotStored):
  476. return ErrNotStored
  477. case bytes.Equal(line, resultExists):
  478. return ErrCASConflict
  479. case bytes.Equal(line, resultNotFound):
  480. return ErrCacheMiss
  481. }
  482. return fmt.Errorf("memcache: unexpected response line from %q: %q", verb, string(line))
  483. }
  484. func writeReadLine(rw *bufio.ReadWriter, format string, args ...interface{}) ([]byte, error) {
  485. _, err := fmt.Fprintf(rw, format, args...)
  486. if err != nil {
  487. return nil, err
  488. }
  489. if err := rw.Flush(); err != nil {
  490. return nil, err
  491. }
  492. line, err := rw.ReadSlice('\n')
  493. return line, err
  494. }
  495. func writeExpectf(rw *bufio.ReadWriter, expect []byte, format string, args ...interface{}) error {
  496. line, err := writeReadLine(rw, format, args...)
  497. if err != nil {
  498. return err
  499. }
  500. switch {
  501. case bytes.Equal(line, expect):
  502. return nil
  503. case bytes.Equal(line, resultNotStored):
  504. return ErrNotStored
  505. case bytes.Equal(line, resultExists):
  506. return ErrCASConflict
  507. case bytes.Equal(line, resultNotFound):
  508. return ErrCacheMiss
  509. }
  510. return fmt.Errorf("memcache: unexpected response line: %q", string(line))
  511. }
  512. // Delete deletes the item with the provided key. The error ErrCacheMiss is
  513. // returned if the item didn't already exist in the cache.
  514. func (c *Client) Delete(key string) error {
  515. return c.withKeyRw(key, func(rw *bufio.ReadWriter) error {
  516. return writeExpectf(rw, resultDeleted, "delete %s\r\n", key)
  517. })
  518. }
  519. // Increment atomically increments key by delta. The return value is
  520. // the new value after being incremented or an error. If the value
  521. // didn't exist in memcached the error is ErrCacheMiss. The value in
  522. // memcached must be an decimal number, or an error will be returned.
  523. // On 64-bit overflow, the new value wraps around.
  524. func (c *Client) Increment(key string, delta uint64) (newValue uint64, err error) {
  525. return c.incrDecr("incr", key, delta)
  526. }
  527. // Decrement atomically decrements key by delta. The return value is
  528. // the new value after being decremented or an error. If the value
  529. // didn't exist in memcached the error is ErrCacheMiss. The value in
  530. // memcached must be an decimal number, or an error will be returned.
  531. // On underflow, the new value is capped at zero and does not wrap
  532. // around.
  533. func (c *Client) Decrement(key string, delta uint64) (newValue uint64, err error) {
  534. return c.incrDecr("decr", key, delta)
  535. }
  536. func (c *Client) incrDecr(verb, key string, delta uint64) (uint64, error) {
  537. var val uint64
  538. err := c.withKeyRw(key, func(rw *bufio.ReadWriter) error {
  539. line, err := writeReadLine(rw, "%s %s %d\r\n", verb, key, delta)
  540. if err != nil {
  541. return err
  542. }
  543. switch {
  544. case bytes.Equal(line, resultNotFound):
  545. return ErrCacheMiss
  546. case bytes.HasPrefix(line, resultClientErrorPrefix):
  547. errMsg := line[len(resultClientErrorPrefix) : len(line)-2]
  548. return errors.New("memcache: client error: " + string(errMsg))
  549. }
  550. val, err = strconv.ParseUint(string(line[:len(line)-2]), 10, 64)
  551. if err != nil {
  552. return err
  553. }
  554. return nil
  555. })
  556. return val, err
  557. }