memcache.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. "fmt"
  19. "io"
  20. "io/ioutil"
  21. "log"
  22. "net"
  23. "os"
  24. "strings"
  25. "sync"
  26. )
  27. var _ = log.Printf
  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 = os.NewError("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 = os.NewError("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 = os.NewError("memcache: item not stored")
  41. // ErrServer means that a server error occurred.
  42. ErrServerError = os.NewError("memcache: server error")
  43. // ErrNoStats means that no statistics were available.
  44. ErrNoStats = os.NewError("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 = os.NewError("malformed: key is too long or contains invalid characters")
  49. // ErrNoServers is returned when no servers are configured or available.
  50. ErrNoServers = os.NewError("memcache: no servers configured or available")
  51. )
  52. const buffered = 8 // arbitrary buffered channel size
  53. // resumableError returns true if err is only a protocol-level cache error.
  54. // This is used to determine whether or not a server connection should
  55. // be re-used or not. If an error occurs, by default we don't reuse the
  56. // connection, unless it was just a cache error.
  57. func resumableError(err os.Error) bool {
  58. switch err {
  59. case ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrMalformedKey:
  60. return true
  61. }
  62. return false
  63. }
  64. func legalKey(key string) bool {
  65. if len(key) > 250 {
  66. return false
  67. }
  68. for i := 0; i < len(key); i++ {
  69. if key[i] <= ' ' || key[i] > 0x7e {
  70. return false
  71. }
  72. }
  73. return true
  74. }
  75. var (
  76. crlf = []byte("\r\n")
  77. resultStored = []byte("STORED\r\n")
  78. resultNotStored = []byte("NOT_STORED\r\n")
  79. resultExists = []byte("EXISTS\r\n")
  80. resultNotFound = []byte("NOT_FOUND\r\n")
  81. resultDeleted = []byte("DELETED\r\n")
  82. resultEnd = []byte("END\r\n")
  83. )
  84. // New returns a memcache client using the provided server(s)
  85. // with equal weight. If a server is listed multiple times,
  86. // it gets a proportional amount of weight.
  87. func New(server ...string) *Client {
  88. ss := new(ServerList)
  89. ss.SetServers(server...)
  90. return NewFromSelector(ss)
  91. }
  92. // NewFromSelector returns a new Client using the provided ServerSelector.
  93. func NewFromSelector(ss ServerSelector) *Client {
  94. return &Client{selector: ss}
  95. }
  96. // Client is a memcache client.
  97. // It is safe for unlocked use by multiple concurrent goroutines.
  98. type Client struct {
  99. selector ServerSelector
  100. }
  101. // Item is an item to be got or stored in a memcached server.
  102. type Item struct {
  103. // Key is the Item's key (250 bytes maximum).
  104. Key string
  105. // Value is the Item's value.
  106. Value []byte
  107. // Object is the Item's value for use with a Codec.
  108. Object interface{}
  109. // Flags are server-opaque flags whose semantics are entirely up to the
  110. // App Engine app.
  111. Flags uint32
  112. // Expiration is the cache expiration time, in seconds: either a relative
  113. // time from now (up to 1 month), or an absolute Unix epoch time.
  114. // Zero means the Item has no expiration time.
  115. Expiration int32
  116. // Compare and swap ID.
  117. casid uint64
  118. }
  119. // conn is a connection to a server.
  120. type conn struct {
  121. nc net.Conn
  122. rw *bufio.ReadWriter
  123. addr net.Addr
  124. c *Client
  125. }
  126. // release returns this connection back to the client's free pool
  127. func (cn *conn) release() {
  128. // TODO: return to client's free pool
  129. }
  130. // condRelease releases this connection if the error pointed to by err
  131. // is is nil (not an error) or is only a protocol level error (e.g. a
  132. // cache miss). The purpose is to not recycle TCP connections that
  133. // are bad.
  134. func (cn *conn) condRelease(err *os.Error) {
  135. if *err == nil || resumableError(*err) {
  136. cn.release()
  137. }
  138. }
  139. func (c *Client) getConn(addr net.Addr) (*conn, os.Error) {
  140. // TODO(bradfitz): get from a free pool
  141. nc, err := net.Dial(addr.Network(), addr.String())
  142. if err != nil {
  143. return nil, err
  144. }
  145. // TODO: set read/write timeouts
  146. return &conn{
  147. nc: nc,
  148. addr: addr,
  149. rw: bufio.NewReadWriter(bufio.NewReader(nc), bufio.NewWriter(nc)),
  150. c: c,
  151. }, nil
  152. }
  153. func (c *Client) onItem(item *Item, fn func(*Client, *bufio.ReadWriter, *Item) os.Error) os.Error {
  154. addr, err := c.selector.PickServer(item.Key)
  155. if err != nil {
  156. return err
  157. }
  158. cn, err := c.getConn(addr)
  159. if err != nil {
  160. return err
  161. }
  162. defer cn.condRelease(&err)
  163. if err := fn(c, cn.rw, item); err != nil {
  164. return err
  165. }
  166. return nil
  167. }
  168. // Get gets the item for the given key. ErrCacheMiss is returned for a
  169. // memcache cache miss. The key must be at most 250 bytes in length.
  170. func (c *Client) Get(key string) (item *Item, err os.Error) {
  171. err = c.withKeyAddr(key, func(addr net.Addr) os.Error {
  172. return c.getFromAddr(addr, []string{key}, func(it *Item) { item = it })
  173. })
  174. if err == nil && item == nil {
  175. err = ErrCacheMiss
  176. }
  177. return
  178. }
  179. func (c *Client) withKeyAddr(key string, fn func(net.Addr) os.Error) (err os.Error) {
  180. if !legalKey(key) {
  181. return ErrMalformedKey
  182. }
  183. addr, err := c.selector.PickServer(key)
  184. if err != nil {
  185. return err
  186. }
  187. return fn(addr)
  188. }
  189. func (c *Client) withAddrRw(addr net.Addr, fn func(*bufio.ReadWriter) os.Error) (err os.Error) {
  190. cn, err := c.getConn(addr)
  191. if err != nil {
  192. return err
  193. }
  194. defer cn.condRelease(&err)
  195. return fn(cn.rw)
  196. }
  197. func (c *Client) withKeyRw(key string, fn func(*bufio.ReadWriter) os.Error) os.Error {
  198. return c.withKeyAddr(key, func(addr net.Addr) os.Error {
  199. return c.withAddrRw(addr, fn)
  200. })
  201. }
  202. func (c *Client) getFromAddr(addr net.Addr, keys []string, cb func(*Item)) os.Error {
  203. return c.withAddrRw(addr, func(rw *bufio.ReadWriter) os.Error {
  204. if _, err := fmt.Fprintf(rw, "gets %s\r\n", strings.Join(keys, " ")); err != nil {
  205. return err
  206. }
  207. if err := rw.Flush(); err != nil {
  208. return err
  209. }
  210. if err := parseGetResponse(rw.Reader, cb); err != nil {
  211. return err
  212. }
  213. return nil
  214. })
  215. }
  216. // GetMulti is a batch version of Get. The returned map from keys to
  217. // items may have fewer elements than the input slice, due to memcache
  218. // cache misses. Each key must be at most 250 bytes in length.
  219. // If no error is returned, the returned map will also be non-nil.
  220. func (c *Client) GetMulti(keys []string) (map[string]*Item, os.Error) {
  221. var lk sync.Mutex
  222. m := make(map[string]*Item)
  223. addItemToMap := func(it *Item) {
  224. lk.Lock()
  225. defer lk.Unlock()
  226. m[it.Key] = it
  227. }
  228. keyMap := make(map[net.Addr][]string)
  229. for _, key := range keys {
  230. if !legalKey(key) {
  231. return nil, ErrMalformedKey
  232. }
  233. addr, err := c.selector.PickServer(key)
  234. if err != nil {
  235. return nil, err
  236. }
  237. keyMap[addr] = append(keyMap[addr], key)
  238. }
  239. ch := make(chan os.Error, buffered)
  240. for addr, keys := range keyMap {
  241. go func(addr net.Addr, keys []string) {
  242. ch <- c.getFromAddr(addr, keys, addItemToMap)
  243. }(addr, keys)
  244. }
  245. var err os.Error
  246. for _ = range keyMap {
  247. if ge := <-ch; ge != nil {
  248. err = ge
  249. }
  250. }
  251. return m, err
  252. }
  253. // parseGetResponse reads a GET response from r and calls cb for each
  254. // read and allocated Item
  255. func parseGetResponse(r *bufio.Reader, cb func(*Item)) os.Error {
  256. for {
  257. line, err := r.ReadSlice('\n')
  258. if err != nil {
  259. return err
  260. }
  261. if bytes.Equal(line, resultEnd) {
  262. return nil
  263. }
  264. it := new(Item)
  265. var size int
  266. n, err := fmt.Sscanf(string(line), "VALUE %s %d %d %d\r\n",
  267. &it.Key, &it.Flags, &size, &it.casid)
  268. if err != nil {
  269. return err
  270. }
  271. if n != 4 {
  272. return fmt.Errorf("memcache: unexpected line in get response: %q", string(line))
  273. }
  274. it.Value, err = ioutil.ReadAll(io.LimitReader(r, int64(size)+2))
  275. if err != nil {
  276. return err
  277. }
  278. if !bytes.HasSuffix(it.Value, crlf) {
  279. return fmt.Errorf("memcache: corrupt get result read")
  280. }
  281. it.Value = it.Value[:size]
  282. cb(it)
  283. }
  284. panic("unreached")
  285. }
  286. // Set writes the given item, unconditionally.
  287. func (c *Client) Set(item *Item) os.Error {
  288. return c.onItem(item, (*Client).set)
  289. }
  290. func (c *Client) set(rw *bufio.ReadWriter, item *Item) os.Error {
  291. return c.populateOne(rw, "set", item)
  292. }
  293. // Add writes the given item, if no value already exists for its
  294. // key. ErrNotStored is returned if that condition is not met.
  295. func (c *Client) Add(item *Item) os.Error {
  296. return c.onItem(item, (*Client).add)
  297. }
  298. func (c *Client) add(rw *bufio.ReadWriter, item *Item) os.Error {
  299. return c.populateOne(rw, "add", item)
  300. }
  301. // CompareAndSwap writes the given item that was previously returned
  302. // by Get, if the value was neither modified or evicted between the
  303. // Get and the CompareAndSwap calls. The item's Key should not change
  304. // between calls but all other item fields may differ. ErrCASConflict
  305. // is returned if the value was modified in between the
  306. // calls. ErrNotStored is returned if the value was evicted in between
  307. // the calls.
  308. func (c *Client) CompareAndSwap(item *Item) os.Error {
  309. return c.onItem(item, (*Client).cas)
  310. }
  311. func (c *Client) cas(rw *bufio.ReadWriter, item *Item) os.Error {
  312. return c.populateOne(rw, "cas", item)
  313. }
  314. func (c *Client) populateOne(rw *bufio.ReadWriter, verb string, item *Item) os.Error {
  315. if !legalKey(item.Key) {
  316. return ErrMalformedKey
  317. }
  318. var err os.Error
  319. if verb == "cas" {
  320. _, err = fmt.Fprintf(rw, "%s %s %d %d %d %d %d\r\n",
  321. verb, item.Key, item.Flags, item.Expiration, len(item.Value), item.casid)
  322. } else {
  323. _, err = fmt.Fprintf(rw, "%s %s %d %d %d %d\r\n",
  324. verb, item.Key, item.Flags, item.Expiration, len(item.Value))
  325. }
  326. if err != nil {
  327. return err
  328. }
  329. if _, err = rw.Write(item.Value); err != nil {
  330. return err
  331. }
  332. if _, err := rw.Write(crlf); 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, resultStored):
  344. return nil
  345. case bytes.Equal(line, resultNotStored):
  346. return ErrNotStored
  347. case bytes.Equal(line, resultExists):
  348. return ErrCASConflict
  349. case bytes.Equal(line, resultNotFound):
  350. return ErrCacheMiss
  351. }
  352. return fmt.Errorf("memcache: unexpected response line from %q: %q", verb, string(line))
  353. }
  354. func writeExpectf(rw *bufio.ReadWriter, expect []byte, format string, args ...interface{}) os.Error {
  355. _, err := fmt.Fprintf(rw, format, args...)
  356. if err != nil {
  357. return err
  358. }
  359. if err := rw.Flush(); err != nil {
  360. return err
  361. }
  362. line, err := rw.ReadSlice('\n')
  363. if err != nil {
  364. return err
  365. }
  366. switch {
  367. case bytes.Equal(line, expect):
  368. return nil
  369. case bytes.Equal(line, resultNotStored):
  370. return ErrNotStored
  371. case bytes.Equal(line, resultExists):
  372. return ErrCASConflict
  373. case bytes.Equal(line, resultNotFound):
  374. return ErrCacheMiss
  375. }
  376. return fmt.Errorf("memcache: unexpected response line: %q", string(line))
  377. }
  378. func (c *Client) Delete(key string) os.Error {
  379. return c.withKeyRw(key, func(rw *bufio.ReadWriter) os.Error {
  380. return writeExpectf(rw, resultDeleted, "delete %s\r\n", key)
  381. })
  382. }