memcache.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. "net"
  22. "os"
  23. "strings"
  24. "sync"
  25. "time"
  26. )
  27. // Similar to:
  28. // http://code.google.com/appengine/docs/go/memcache/reference.html
  29. var (
  30. // ErrCacheMiss means that a Get failed because the item wasn't present.
  31. ErrCacheMiss = os.NewError("memcache: cache miss")
  32. // ErrCASConflict means that a CompareAndSwap call failed due to the
  33. // cached value being modified between the Get and the CompareAndSwap.
  34. // If the cached value was simply evicted rather than replaced,
  35. // ErrNotStored will be returned instead.
  36. ErrCASConflict = os.NewError("memcache: compare-and-swap conflict")
  37. // ErrNotStored means that a conditional write operation (i.e. Add or
  38. // CompareAndSwap) failed because the condition was not satisfied.
  39. ErrNotStored = os.NewError("memcache: item not stored")
  40. // ErrServer means that a server error occurred.
  41. ErrServerError = os.NewError("memcache: server error")
  42. // ErrNoStats means that no statistics were available.
  43. ErrNoStats = os.NewError("memcache: no statistics available")
  44. // ErrMalformedKey is returned when an invalid key is used.
  45. // Keys must be at maximum 250 bytes long, ASCII, and not
  46. // contain whitespace or control characters.
  47. ErrMalformedKey = os.NewError("malformed: key is too long or contains invalid characters")
  48. // ErrNoServers is returned when no servers are configured or available.
  49. ErrNoServers = os.NewError("memcache: no servers configured or available")
  50. )
  51. // DefaultTimeoutNanos is the default socket read/write timeout, in nanoseconds.
  52. const DefaultTimeoutNanos = 100e6 // 100 ms
  53. const (
  54. buffered = 8 // arbitrary buffered channel size, for readability
  55. maxIdleConnsPerAddr = 2 // TODO(bradfitz): make this configurable?
  56. )
  57. // resumableError returns true if err is only a protocol-level cache error.
  58. // This is used to determine whether or not a server connection should
  59. // be re-used or not. If an error occurs, by default we don't reuse the
  60. // connection, unless it was just a cache error.
  61. func resumableError(err os.Error) bool {
  62. switch err {
  63. case ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrMalformedKey:
  64. return true
  65. }
  66. return false
  67. }
  68. func legalKey(key string) bool {
  69. if len(key) > 250 {
  70. return false
  71. }
  72. for i := 0; i < len(key); i++ {
  73. if key[i] <= ' ' || key[i] > 0x7e {
  74. return false
  75. }
  76. }
  77. return true
  78. }
  79. var (
  80. crlf = []byte("\r\n")
  81. resultStored = []byte("STORED\r\n")
  82. resultNotStored = []byte("NOT_STORED\r\n")
  83. resultExists = []byte("EXISTS\r\n")
  84. resultNotFound = []byte("NOT_FOUND\r\n")
  85. resultDeleted = []byte("DELETED\r\n")
  86. resultEnd = []byte("END\r\n")
  87. )
  88. // New returns a memcache client using the provided server(s)
  89. // with equal weight. If a server is listed multiple times,
  90. // it gets a proportional amount of weight.
  91. func New(server ...string) *Client {
  92. ss := new(ServerList)
  93. ss.SetServers(server...)
  94. return NewFromSelector(ss)
  95. }
  96. // NewFromSelector returns a new Client using the provided ServerSelector.
  97. func NewFromSelector(ss ServerSelector) *Client {
  98. return &Client{selector: ss}
  99. }
  100. // Client is a memcache client.
  101. // It is safe for unlocked use by multiple concurrent goroutines.
  102. type Client struct {
  103. // TimeoutNanos specifies the socket read/write timeout.
  104. // If zero, DefaultTimeoutNanos is used.
  105. TimeoutNanos int64
  106. selector ServerSelector
  107. lk sync.Mutex
  108. freeconn map[net.Addr][]*conn
  109. }
  110. // Item is an item to be got or stored in a memcached server.
  111. type Item struct {
  112. // Key is the Item's key (250 bytes maximum).
  113. Key string
  114. // Value is the Item's value.
  115. Value []byte
  116. // Object is the Item's value for use with a Codec.
  117. Object interface{}
  118. // Flags are server-opaque flags whose semantics are entirely up to the
  119. // App Engine app.
  120. Flags uint32
  121. // Expiration is the cache expiration time, in seconds: either a relative
  122. // time from now (up to 1 month), or an absolute Unix epoch time.
  123. // Zero means the Item has no expiration time.
  124. Expiration int32
  125. // Compare and swap ID.
  126. casid uint64
  127. }
  128. // conn is a connection to a server.
  129. type conn struct {
  130. nc net.Conn
  131. rw *bufio.ReadWriter
  132. addr net.Addr
  133. c *Client
  134. }
  135. // release returns this connection back to the client's free pool
  136. func (cn *conn) release() {
  137. cn.c.putFreeConn(cn.addr, cn)
  138. }
  139. // condRelease releases this connection if the error pointed to by err
  140. // is is nil (not an error) or is only a protocol level error (e.g. a
  141. // cache miss). The purpose is to not recycle TCP connections that
  142. // are bad.
  143. func (cn *conn) condRelease(err *os.Error) {
  144. if *err == nil || resumableError(*err) {
  145. cn.release()
  146. }
  147. }
  148. func (c *Client) putFreeConn(addr net.Addr, cn *conn) {
  149. c.lk.Lock()
  150. defer c.lk.Unlock()
  151. if c.freeconn == nil {
  152. c.freeconn = make(map[net.Addr][]*conn)
  153. }
  154. freelist := c.freeconn[addr]
  155. if len(freelist) >= maxIdleConnsPerAddr {
  156. cn.nc.Close()
  157. return
  158. }
  159. c.freeconn[addr] = append(freelist, cn)
  160. }
  161. func (c *Client) getFreeConn(addr net.Addr) (cn *conn, ok bool) {
  162. c.lk.Lock()
  163. defer c.lk.Unlock()
  164. if c.freeconn == nil {
  165. return nil, false
  166. }
  167. freelist, ok := c.freeconn[addr]
  168. if !ok || len(freelist) == 0 {
  169. return nil, false
  170. }
  171. cn = freelist[len(freelist)-1]
  172. c.freeconn[addr] = freelist[:len(freelist)-1]
  173. return cn, true
  174. }
  175. func (c *Client) netTimeoutNs() int64 {
  176. if c.TimeoutNanos != 0 {
  177. return c.TimeoutNanos
  178. }
  179. return DefaultTimeoutNanos
  180. }
  181. // ConnectTimeoutError is the error type used when it takes
  182. // too long to connect to the desired host. This level of
  183. // detail can generally be ignored.
  184. type ConnectTimeoutError struct {
  185. Addr net.Addr
  186. }
  187. func (cte *ConnectTimeoutError) String() string {
  188. return "memcache: connect timeout to " + cte.Addr.String()
  189. }
  190. func (c *Client) dial(addr net.Addr) (net.Conn, os.Error) {
  191. type connError struct {
  192. cn net.Conn
  193. err os.Error
  194. }
  195. ch := make(chan connError)
  196. go func() {
  197. nc, err := net.Dial(addr.Network(), addr.String())
  198. ch <- connError{nc, err}
  199. }()
  200. select {
  201. case ce := <-ch:
  202. return ce.cn, ce.err
  203. case <-time.After(c.netTimeoutNs()):
  204. // Too slow. Fall through.
  205. }
  206. // Close the conn if it does end up finally coming in
  207. go func() {
  208. ce := <-ch
  209. if ce.err == nil {
  210. ce.cn.Close()
  211. }
  212. }()
  213. return nil, &ConnectTimeoutError{addr}
  214. }
  215. func (c *Client) getConn(addr net.Addr) (*conn, os.Error) {
  216. cn, ok := c.getFreeConn(addr)
  217. if ok {
  218. return cn, nil
  219. }
  220. nc, err := c.dial(addr)
  221. if err != nil {
  222. return nil, err
  223. }
  224. nc.SetTimeout(c.netTimeoutNs())
  225. return &conn{
  226. nc: nc,
  227. addr: addr,
  228. rw: bufio.NewReadWriter(bufio.NewReader(nc), bufio.NewWriter(nc)),
  229. c: c,
  230. }, nil
  231. }
  232. func (c *Client) onItem(item *Item, fn func(*Client, *bufio.ReadWriter, *Item) os.Error) os.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. // Get gets the item for the given key. ErrCacheMiss is returned for a
  248. // memcache cache miss. The key must be at most 250 bytes in length.
  249. func (c *Client) Get(key string) (item *Item, err os.Error) {
  250. err = c.withKeyAddr(key, func(addr net.Addr) os.Error {
  251. return c.getFromAddr(addr, []string{key}, func(it *Item) { item = it })
  252. })
  253. if err == nil && item == nil {
  254. err = ErrCacheMiss
  255. }
  256. return
  257. }
  258. func (c *Client) withKeyAddr(key string, fn func(net.Addr) os.Error) (err os.Error) {
  259. if !legalKey(key) {
  260. return ErrMalformedKey
  261. }
  262. addr, err := c.selector.PickServer(key)
  263. if err != nil {
  264. return err
  265. }
  266. return fn(addr)
  267. }
  268. func (c *Client) withAddrRw(addr net.Addr, fn func(*bufio.ReadWriter) os.Error) (err os.Error) {
  269. cn, err := c.getConn(addr)
  270. if err != nil {
  271. return err
  272. }
  273. defer cn.condRelease(&err)
  274. return fn(cn.rw)
  275. }
  276. func (c *Client) withKeyRw(key string, fn func(*bufio.ReadWriter) os.Error) os.Error {
  277. return c.withKeyAddr(key, func(addr net.Addr) os.Error {
  278. return c.withAddrRw(addr, fn)
  279. })
  280. }
  281. func (c *Client) getFromAddr(addr net.Addr, keys []string, cb func(*Item)) os.Error {
  282. return c.withAddrRw(addr, func(rw *bufio.ReadWriter) os.Error {
  283. if _, err := fmt.Fprintf(rw, "gets %s\r\n", strings.Join(keys, " ")); err != nil {
  284. return err
  285. }
  286. if err := rw.Flush(); err != nil {
  287. return err
  288. }
  289. if err := parseGetResponse(rw.Reader, cb); err != nil {
  290. return err
  291. }
  292. return nil
  293. })
  294. }
  295. // GetMulti is a batch version of Get. The returned map from keys to
  296. // items may have fewer elements than the input slice, due to memcache
  297. // cache misses. Each key must be at most 250 bytes in length.
  298. // If no error is returned, the returned map will also be non-nil.
  299. func (c *Client) GetMulti(keys []string) (map[string]*Item, os.Error) {
  300. var lk sync.Mutex
  301. m := make(map[string]*Item)
  302. addItemToMap := func(it *Item) {
  303. lk.Lock()
  304. defer lk.Unlock()
  305. m[it.Key] = it
  306. }
  307. keyMap := make(map[net.Addr][]string)
  308. for _, key := range keys {
  309. if !legalKey(key) {
  310. return nil, ErrMalformedKey
  311. }
  312. addr, err := c.selector.PickServer(key)
  313. if err != nil {
  314. return nil, err
  315. }
  316. keyMap[addr] = append(keyMap[addr], key)
  317. }
  318. ch := make(chan os.Error, buffered)
  319. for addr, keys := range keyMap {
  320. go func(addr net.Addr, keys []string) {
  321. ch <- c.getFromAddr(addr, keys, addItemToMap)
  322. }(addr, keys)
  323. }
  324. var err os.Error
  325. for _ = range keyMap {
  326. if ge := <-ch; ge != nil {
  327. err = ge
  328. }
  329. }
  330. return m, err
  331. }
  332. // parseGetResponse reads a GET response from r and calls cb for each
  333. // read and allocated Item
  334. func parseGetResponse(r *bufio.Reader, cb func(*Item)) os.Error {
  335. for {
  336. line, err := r.ReadSlice('\n')
  337. if err != nil {
  338. return err
  339. }
  340. if bytes.Equal(line, resultEnd) {
  341. return nil
  342. }
  343. it := new(Item)
  344. var size int
  345. n, err := fmt.Sscanf(string(line), "VALUE %s %d %d %d\r\n",
  346. &it.Key, &it.Flags, &size, &it.casid)
  347. if err != nil {
  348. return err
  349. }
  350. if n != 4 {
  351. return fmt.Errorf("memcache: unexpected line in get response: %q", string(line))
  352. }
  353. it.Value, err = ioutil.ReadAll(io.LimitReader(r, int64(size)+2))
  354. if err != nil {
  355. return err
  356. }
  357. if !bytes.HasSuffix(it.Value, crlf) {
  358. return fmt.Errorf("memcache: corrupt get result read")
  359. }
  360. it.Value = it.Value[:size]
  361. cb(it)
  362. }
  363. panic("unreached")
  364. }
  365. // Set writes the given item, unconditionally.
  366. func (c *Client) Set(item *Item) os.Error {
  367. return c.onItem(item, (*Client).set)
  368. }
  369. func (c *Client) set(rw *bufio.ReadWriter, item *Item) os.Error {
  370. return c.populateOne(rw, "set", item)
  371. }
  372. // Add writes the given item, if no value already exists for its
  373. // key. ErrNotStored is returned if that condition is not met.
  374. func (c *Client) Add(item *Item) os.Error {
  375. return c.onItem(item, (*Client).add)
  376. }
  377. func (c *Client) add(rw *bufio.ReadWriter, item *Item) os.Error {
  378. return c.populateOne(rw, "add", item)
  379. }
  380. // CompareAndSwap writes the given item that was previously returned
  381. // by Get, if the value was neither modified or evicted between the
  382. // Get and the CompareAndSwap calls. The item's Key should not change
  383. // between calls but all other item fields may differ. ErrCASConflict
  384. // is returned if the value was modified in between the
  385. // calls. ErrNotStored is returned if the value was evicted in between
  386. // the calls.
  387. func (c *Client) CompareAndSwap(item *Item) os.Error {
  388. return c.onItem(item, (*Client).cas)
  389. }
  390. func (c *Client) cas(rw *bufio.ReadWriter, item *Item) os.Error {
  391. return c.populateOne(rw, "cas", item)
  392. }
  393. func (c *Client) populateOne(rw *bufio.ReadWriter, verb string, item *Item) os.Error {
  394. if !legalKey(item.Key) {
  395. return ErrMalformedKey
  396. }
  397. var err os.Error
  398. if verb == "cas" {
  399. _, err = fmt.Fprintf(rw, "%s %s %d %d %d %d %d\r\n",
  400. verb, item.Key, item.Flags, item.Expiration, len(item.Value), item.casid)
  401. } else {
  402. _, err = fmt.Fprintf(rw, "%s %s %d %d %d %d\r\n",
  403. verb, item.Key, item.Flags, item.Expiration, len(item.Value))
  404. }
  405. if err != nil {
  406. return err
  407. }
  408. if _, err = rw.Write(item.Value); err != nil {
  409. return err
  410. }
  411. if _, err := rw.Write(crlf); err != nil {
  412. return err
  413. }
  414. if err := rw.Flush(); err != nil {
  415. return err
  416. }
  417. line, err := rw.ReadSlice('\n')
  418. if err != nil {
  419. return err
  420. }
  421. switch {
  422. case bytes.Equal(line, resultStored):
  423. return nil
  424. case bytes.Equal(line, resultNotStored):
  425. return ErrNotStored
  426. case bytes.Equal(line, resultExists):
  427. return ErrCASConflict
  428. case bytes.Equal(line, resultNotFound):
  429. return ErrCacheMiss
  430. }
  431. return fmt.Errorf("memcache: unexpected response line from %q: %q", verb, string(line))
  432. }
  433. func writeExpectf(rw *bufio.ReadWriter, expect []byte, format string, args ...interface{}) os.Error {
  434. _, err := fmt.Fprintf(rw, format, args...)
  435. if err != nil {
  436. return err
  437. }
  438. if err := rw.Flush(); err != nil {
  439. return err
  440. }
  441. line, err := rw.ReadSlice('\n')
  442. if err != nil {
  443. return err
  444. }
  445. switch {
  446. case bytes.Equal(line, expect):
  447. return nil
  448. case bytes.Equal(line, resultNotStored):
  449. return ErrNotStored
  450. case bytes.Equal(line, resultExists):
  451. return ErrCASConflict
  452. case bytes.Equal(line, resultNotFound):
  453. return ErrCacheMiss
  454. }
  455. return fmt.Errorf("memcache: unexpected response line: %q", string(line))
  456. }
  457. // Delete deletes the item with the provided key. The error ErrCacheMiss is
  458. // returned if the item didn't already exist in the cache.
  459. func (c *Client) Delete(key string) os.Error {
  460. return c.withKeyRw(key, func(rw *bufio.ReadWriter) os.Error {
  461. return writeExpectf(rw, resultDeleted, "delete %s\r\n", key)
  462. })
  463. }