memcache.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. # -*- test-case-name: twisted.test.test_memcache -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Memcache client protocol. Memcached is a caching server, storing data in the
  6. form of pairs key/value, and memcache is the protocol to talk with it.
  7. To connect to a server, create a factory for L{MemCacheProtocol}::
  8. from twisted.internet import reactor, protocol
  9. from twisted.protocols.memcache import MemCacheProtocol, DEFAULT_PORT
  10. d = protocol.ClientCreator(reactor, MemCacheProtocol
  11. ).connectTCP("localhost", DEFAULT_PORT)
  12. def doSomething(proto):
  13. # Here you call the memcache operations
  14. return proto.set("mykey", "a lot of data")
  15. d.addCallback(doSomething)
  16. reactor.run()
  17. All the operations of the memcache protocol are present, but
  18. L{MemCacheProtocol.set} and L{MemCacheProtocol.get} are the more important.
  19. See U{http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt} for
  20. more information about the protocol.
  21. """
  22. from __future__ import absolute_import, division
  23. from collections import deque
  24. from twisted.protocols.basic import LineReceiver
  25. from twisted.protocols.policies import TimeoutMixin
  26. from twisted.internet.defer import Deferred, fail, TimeoutError
  27. from twisted.python import log
  28. from twisted.python.compat import (
  29. intToBytes, iteritems, nativeString, networkString)
  30. DEFAULT_PORT = 11211
  31. class NoSuchCommand(Exception):
  32. """
  33. Exception raised when a non existent command is called.
  34. """
  35. class ClientError(Exception):
  36. """
  37. Error caused by an invalid client call.
  38. """
  39. class ServerError(Exception):
  40. """
  41. Problem happening on the server.
  42. """
  43. class Command(object):
  44. """
  45. Wrap a client action into an object, that holds the values used in the
  46. protocol.
  47. @ivar _deferred: the L{Deferred} object that will be fired when the result
  48. arrives.
  49. @type _deferred: L{Deferred}
  50. @ivar command: name of the command sent to the server.
  51. @type command: L{bytes}
  52. """
  53. def __init__(self, command, **kwargs):
  54. """
  55. Create a command.
  56. @param command: the name of the command.
  57. @type command: L{bytes}
  58. @param kwargs: this values will be stored as attributes of the object
  59. for future use
  60. """
  61. self.command = command
  62. self._deferred = Deferred()
  63. for k, v in kwargs.items():
  64. setattr(self, k, v)
  65. def success(self, value):
  66. """
  67. Shortcut method to fire the underlying deferred.
  68. """
  69. self._deferred.callback(value)
  70. def fail(self, error):
  71. """
  72. Make the underlying deferred fails.
  73. """
  74. self._deferred.errback(error)
  75. class MemCacheProtocol(LineReceiver, TimeoutMixin):
  76. """
  77. MemCache protocol: connect to a memcached server to store/retrieve values.
  78. @ivar persistentTimeOut: the timeout period used to wait for a response.
  79. @type persistentTimeOut: L{int}
  80. @ivar _current: current list of requests waiting for an answer from the
  81. server.
  82. @type _current: L{deque} of L{Command}
  83. @ivar _lenExpected: amount of data expected in raw mode, when reading for
  84. a value.
  85. @type _lenExpected: L{int}
  86. @ivar _getBuffer: current buffer of data, used to store temporary data
  87. when reading in raw mode.
  88. @type _getBuffer: L{list}
  89. @ivar _bufferLength: the total amount of bytes in C{_getBuffer}.
  90. @type _bufferLength: L{int}
  91. @ivar _disconnected: indicate if the connectionLost has been called or not.
  92. @type _disconnected: L{bool}
  93. """
  94. MAX_KEY_LENGTH = 250
  95. _disconnected = False
  96. def __init__(self, timeOut=60):
  97. """
  98. Create the protocol.
  99. @param timeOut: the timeout to wait before detecting that the
  100. connection is dead and close it. It's expressed in seconds.
  101. @type timeOut: L{int}
  102. """
  103. self._current = deque()
  104. self._lenExpected = None
  105. self._getBuffer = None
  106. self._bufferLength = None
  107. self.persistentTimeOut = self.timeOut = timeOut
  108. def _cancelCommands(self, reason):
  109. """
  110. Cancel all the outstanding commands, making them fail with C{reason}.
  111. """
  112. while self._current:
  113. cmd = self._current.popleft()
  114. cmd.fail(reason)
  115. def timeoutConnection(self):
  116. """
  117. Close the connection in case of timeout.
  118. """
  119. self._cancelCommands(TimeoutError("Connection timeout"))
  120. self.transport.loseConnection()
  121. def connectionLost(self, reason):
  122. """
  123. Cause any outstanding commands to fail.
  124. """
  125. self._disconnected = True
  126. self._cancelCommands(reason)
  127. LineReceiver.connectionLost(self, reason)
  128. def sendLine(self, line):
  129. """
  130. Override sendLine to add a timeout to response.
  131. """
  132. if not self._current:
  133. self.setTimeout(self.persistentTimeOut)
  134. LineReceiver.sendLine(self, line)
  135. def rawDataReceived(self, data):
  136. """
  137. Collect data for a get.
  138. """
  139. self.resetTimeout()
  140. self._getBuffer.append(data)
  141. self._bufferLength += len(data)
  142. if self._bufferLength >= self._lenExpected + 2:
  143. data = b"".join(self._getBuffer)
  144. buf = data[:self._lenExpected]
  145. rem = data[self._lenExpected + 2:]
  146. val = buf
  147. self._lenExpected = None
  148. self._getBuffer = None
  149. self._bufferLength = None
  150. cmd = self._current[0]
  151. if cmd.multiple:
  152. flags, cas = cmd.values[cmd.currentKey]
  153. cmd.values[cmd.currentKey] = (flags, cas, val)
  154. else:
  155. cmd.value = val
  156. self.setLineMode(rem)
  157. def cmd_STORED(self):
  158. """
  159. Manage a success response to a set operation.
  160. """
  161. self._current.popleft().success(True)
  162. def cmd_NOT_STORED(self):
  163. """
  164. Manage a specific 'not stored' response to a set operation: this is not
  165. an error, but some condition wasn't met.
  166. """
  167. self._current.popleft().success(False)
  168. def cmd_END(self):
  169. """
  170. This the end token to a get or a stat operation.
  171. """
  172. cmd = self._current.popleft()
  173. if cmd.command == b"get":
  174. if cmd.multiple:
  175. values = {key: val[::2] for key, val in iteritems(cmd.values)}
  176. cmd.success(values)
  177. else:
  178. cmd.success((cmd.flags, cmd.value))
  179. elif cmd.command == b"gets":
  180. if cmd.multiple:
  181. cmd.success(cmd.values)
  182. else:
  183. cmd.success((cmd.flags, cmd.cas, cmd.value))
  184. elif cmd.command == b"stats":
  185. cmd.success(cmd.values)
  186. else:
  187. raise RuntimeError(
  188. "Unexpected END response to %s command" %
  189. (nativeString(cmd.command),))
  190. def cmd_NOT_FOUND(self):
  191. """
  192. Manage error response for incr/decr/delete.
  193. """
  194. self._current.popleft().success(False)
  195. def cmd_VALUE(self, line):
  196. """
  197. Prepare the reading a value after a get.
  198. """
  199. cmd = self._current[0]
  200. if cmd.command == b"get":
  201. key, flags, length = line.split()
  202. cas = b""
  203. else:
  204. key, flags, length, cas = line.split()
  205. self._lenExpected = int(length)
  206. self._getBuffer = []
  207. self._bufferLength = 0
  208. if cmd.multiple:
  209. if key not in cmd.keys:
  210. raise RuntimeError("Unexpected commands answer.")
  211. cmd.currentKey = key
  212. cmd.values[key] = [int(flags), cas]
  213. else:
  214. if cmd.key != key:
  215. raise RuntimeError("Unexpected commands answer.")
  216. cmd.flags = int(flags)
  217. cmd.cas = cas
  218. self.setRawMode()
  219. def cmd_STAT(self, line):
  220. """
  221. Reception of one stat line.
  222. """
  223. cmd = self._current[0]
  224. key, val = line.split(b" ", 1)
  225. cmd.values[key] = val
  226. def cmd_VERSION(self, versionData):
  227. """
  228. Read version token.
  229. """
  230. self._current.popleft().success(versionData)
  231. def cmd_ERROR(self):
  232. """
  233. A non-existent command has been sent.
  234. """
  235. log.err("Non-existent command sent.")
  236. cmd = self._current.popleft()
  237. cmd.fail(NoSuchCommand())
  238. def cmd_CLIENT_ERROR(self, errText):
  239. """
  240. An invalid input as been sent.
  241. """
  242. errText = repr(errText)
  243. log.err("Invalid input: " + errText)
  244. cmd = self._current.popleft()
  245. cmd.fail(ClientError(errText))
  246. def cmd_SERVER_ERROR(self, errText):
  247. """
  248. An error has happened server-side.
  249. """
  250. errText = repr(errText)
  251. log.err("Server error: " + errText)
  252. cmd = self._current.popleft()
  253. cmd.fail(ServerError(errText))
  254. def cmd_DELETED(self):
  255. """
  256. A delete command has completed successfully.
  257. """
  258. self._current.popleft().success(True)
  259. def cmd_OK(self):
  260. """
  261. The last command has been completed.
  262. """
  263. self._current.popleft().success(True)
  264. def cmd_EXISTS(self):
  265. """
  266. A C{checkAndSet} update has failed.
  267. """
  268. self._current.popleft().success(False)
  269. def lineReceived(self, line):
  270. """
  271. Receive line commands from the server.
  272. """
  273. self.resetTimeout()
  274. token = line.split(b" ", 1)[0]
  275. # First manage standard commands without space
  276. cmd = getattr(self, "cmd_" + nativeString(token), None)
  277. if cmd is not None:
  278. args = line.split(b" ", 1)[1:]
  279. if args:
  280. cmd(args[0])
  281. else:
  282. cmd()
  283. else:
  284. # Then manage commands with space in it
  285. line = line.replace(b" ", b"_")
  286. cmd = getattr(self, "cmd_" + nativeString(line), None)
  287. if cmd is not None:
  288. cmd()
  289. else:
  290. # Increment/Decrement response
  291. cmd = self._current.popleft()
  292. val = int(line)
  293. cmd.success(val)
  294. if not self._current:
  295. # No pending request, remove timeout
  296. self.setTimeout(None)
  297. def increment(self, key, val=1):
  298. """
  299. Increment the value of C{key} by given value (default to 1).
  300. C{key} must be consistent with an int. Return the new value.
  301. @param key: the key to modify.
  302. @type key: L{bytes}
  303. @param val: the value to increment.
  304. @type val: L{int}
  305. @return: a deferred with will be called back with the new value
  306. associated with the key (after the increment).
  307. @rtype: L{Deferred}
  308. """
  309. return self._incrdecr(b"incr", key, val)
  310. def decrement(self, key, val=1):
  311. """
  312. Decrement the value of C{key} by given value (default to 1).
  313. C{key} must be consistent with an int. Return the new value, coerced to
  314. 0 if negative.
  315. @param key: the key to modify.
  316. @type key: L{bytes}
  317. @param val: the value to decrement.
  318. @type val: L{int}
  319. @return: a deferred with will be called back with the new value
  320. associated with the key (after the decrement).
  321. @rtype: L{Deferred}
  322. """
  323. return self._incrdecr(b"decr", key, val)
  324. def _incrdecr(self, cmd, key, val):
  325. """
  326. Internal wrapper for incr/decr.
  327. """
  328. if self._disconnected:
  329. return fail(RuntimeError("not connected"))
  330. if not isinstance(key, bytes):
  331. return fail(ClientError(
  332. "Invalid type for key: %s, expecting bytes" % (type(key),)))
  333. if len(key) > self.MAX_KEY_LENGTH:
  334. return fail(ClientError("Key too long"))
  335. fullcmd = b" ".join([cmd, key, intToBytes(int(val))])
  336. self.sendLine(fullcmd)
  337. cmdObj = Command(cmd, key=key)
  338. self._current.append(cmdObj)
  339. return cmdObj._deferred
  340. def replace(self, key, val, flags=0, expireTime=0):
  341. """
  342. Replace the given C{key}. It must already exist in the server.
  343. @param key: the key to replace.
  344. @type key: L{bytes}
  345. @param val: the new value associated with the key.
  346. @type val: L{bytes}
  347. @param flags: the flags to store with the key.
  348. @type flags: L{int}
  349. @param expireTime: if different from 0, the relative time in seconds
  350. when the key will be deleted from the store.
  351. @type expireTime: L{int}
  352. @return: a deferred that will fire with C{True} if the operation has
  353. succeeded, and C{False} with the key didn't previously exist.
  354. @rtype: L{Deferred}
  355. """
  356. return self._set(b"replace", key, val, flags, expireTime, b"")
  357. def add(self, key, val, flags=0, expireTime=0):
  358. """
  359. Add the given C{key}. It must not exist in the server.
  360. @param key: the key to add.
  361. @type key: L{bytes}
  362. @param val: the value associated with the key.
  363. @type val: L{bytes}
  364. @param flags: the flags to store with the key.
  365. @type flags: L{int}
  366. @param expireTime: if different from 0, the relative time in seconds
  367. when the key will be deleted from the store.
  368. @type expireTime: L{int}
  369. @return: a deferred that will fire with C{True} if the operation has
  370. succeeded, and C{False} with the key already exists.
  371. @rtype: L{Deferred}
  372. """
  373. return self._set(b"add", key, val, flags, expireTime, b"")
  374. def set(self, key, val, flags=0, expireTime=0):
  375. """
  376. Set the given C{key}.
  377. @param key: the key to set.
  378. @type key: L{bytes}
  379. @param val: the value associated with the key.
  380. @type val: L{bytes}
  381. @param flags: the flags to store with the key.
  382. @type flags: L{int}
  383. @param expireTime: if different from 0, the relative time in seconds
  384. when the key will be deleted from the store.
  385. @type expireTime: L{int}
  386. @return: a deferred that will fire with C{True} if the operation has
  387. succeeded.
  388. @rtype: L{Deferred}
  389. """
  390. return self._set(b"set", key, val, flags, expireTime, b"")
  391. def checkAndSet(self, key, val, cas, flags=0, expireTime=0):
  392. """
  393. Change the content of C{key} only if the C{cas} value matches the
  394. current one associated with the key. Use this to store a value which
  395. hasn't been modified since last time you fetched it.
  396. @param key: The key to set.
  397. @type key: L{bytes}
  398. @param val: The value associated with the key.
  399. @type val: L{bytes}
  400. @param cas: Unique 64-bit value returned by previous call of C{get}.
  401. @type cas: L{bytes}
  402. @param flags: The flags to store with the key.
  403. @type flags: L{int}
  404. @param expireTime: If different from 0, the relative time in seconds
  405. when the key will be deleted from the store.
  406. @type expireTime: L{int}
  407. @return: A deferred that will fire with C{True} if the operation has
  408. succeeded, C{False} otherwise.
  409. @rtype: L{Deferred}
  410. """
  411. return self._set(b"cas", key, val, flags, expireTime, cas)
  412. def _set(self, cmd, key, val, flags, expireTime, cas):
  413. """
  414. Internal wrapper for setting values.
  415. """
  416. if self._disconnected:
  417. return fail(RuntimeError("not connected"))
  418. if not isinstance(key, bytes):
  419. return fail(ClientError(
  420. "Invalid type for key: %s, expecting bytes" % (type(key),)))
  421. if len(key) > self.MAX_KEY_LENGTH:
  422. return fail(ClientError("Key too long"))
  423. if not isinstance(val, bytes):
  424. return fail(ClientError(
  425. "Invalid type for value: %s, expecting bytes" %
  426. (type(val),)))
  427. if cas:
  428. cas = b" " + cas
  429. length = len(val)
  430. fullcmd = b" ".join([
  431. cmd, key,
  432. networkString("%d %d %d" % (flags, expireTime, length))]) + cas
  433. self.sendLine(fullcmd)
  434. self.sendLine(val)
  435. cmdObj = Command(cmd, key=key, flags=flags, length=length)
  436. self._current.append(cmdObj)
  437. return cmdObj._deferred
  438. def append(self, key, val):
  439. """
  440. Append given data to the value of an existing key.
  441. @param key: The key to modify.
  442. @type key: L{bytes}
  443. @param val: The value to append to the current value associated with
  444. the key.
  445. @type val: L{bytes}
  446. @return: A deferred that will fire with C{True} if the operation has
  447. succeeded, C{False} otherwise.
  448. @rtype: L{Deferred}
  449. """
  450. # Even if flags and expTime values are ignored, we have to pass them
  451. return self._set(b"append", key, val, 0, 0, b"")
  452. def prepend(self, key, val):
  453. """
  454. Prepend given data to the value of an existing key.
  455. @param key: The key to modify.
  456. @type key: L{bytes}
  457. @param val: The value to prepend to the current value associated with
  458. the key.
  459. @type val: L{bytes}
  460. @return: A deferred that will fire with C{True} if the operation has
  461. succeeded, C{False} otherwise.
  462. @rtype: L{Deferred}
  463. """
  464. # Even if flags and expTime values are ignored, we have to pass them
  465. return self._set(b"prepend", key, val, 0, 0, b"")
  466. def get(self, key, withIdentifier=False):
  467. """
  468. Get the given C{key}. It doesn't support multiple keys. If
  469. C{withIdentifier} is set to C{True}, the command issued is a C{gets},
  470. that will return the current identifier associated with the value. This
  471. identifier has to be used when issuing C{checkAndSet} update later,
  472. using the corresponding method.
  473. @param key: The key to retrieve.
  474. @type key: L{bytes}
  475. @param withIdentifier: If set to C{True}, retrieve the current
  476. identifier along with the value and the flags.
  477. @type withIdentifier: L{bool}
  478. @return: A deferred that will fire with the tuple (flags, value) if
  479. C{withIdentifier} is C{False}, or (flags, cas identifier, value)
  480. if C{True}. If the server indicates there is no value
  481. associated with C{key}, the returned value will be L{None} and
  482. the returned flags will be C{0}.
  483. @rtype: L{Deferred}
  484. """
  485. return self._get([key], withIdentifier, False)
  486. def getMultiple(self, keys, withIdentifier=False):
  487. """
  488. Get the given list of C{keys}. If C{withIdentifier} is set to C{True},
  489. the command issued is a C{gets}, that will return the identifiers
  490. associated with each values. This identifier has to be used when
  491. issuing C{checkAndSet} update later, using the corresponding method.
  492. @param keys: The keys to retrieve.
  493. @type keys: L{list} of L{bytes}
  494. @param withIdentifier: If set to C{True}, retrieve the identifiers
  495. along with the values and the flags.
  496. @type withIdentifier: L{bool}
  497. @return: A deferred that will fire with a dictionary with the elements
  498. of C{keys} as keys and the tuples (flags, value) as values if
  499. C{withIdentifier} is C{False}, or (flags, cas identifier, value) if
  500. C{True}. If the server indicates there is no value associated with
  501. C{key}, the returned values will be L{None} and the returned flags
  502. will be C{0}.
  503. @rtype: L{Deferred}
  504. @since: 9.0
  505. """
  506. return self._get(keys, withIdentifier, True)
  507. def _get(self, keys, withIdentifier, multiple):
  508. """
  509. Helper method for C{get} and C{getMultiple}.
  510. """
  511. keys = list(keys)
  512. if self._disconnected:
  513. return fail(RuntimeError("not connected"))
  514. for key in keys:
  515. if not isinstance(key, bytes):
  516. return fail(ClientError(
  517. "Invalid type for key: %s, expecting bytes" %
  518. (type(key),)))
  519. if len(key) > self.MAX_KEY_LENGTH:
  520. return fail(ClientError("Key too long"))
  521. if withIdentifier:
  522. cmd = b"gets"
  523. else:
  524. cmd = b"get"
  525. fullcmd = b" ".join([cmd] + keys)
  526. self.sendLine(fullcmd)
  527. if multiple:
  528. values = dict([(key, (0, b"", None)) for key in keys])
  529. cmdObj = Command(cmd, keys=keys, values=values, multiple=True)
  530. else:
  531. cmdObj = Command(cmd, key=keys[0], value=None, flags=0, cas=b"",
  532. multiple=False)
  533. self._current.append(cmdObj)
  534. return cmdObj._deferred
  535. def stats(self, arg=None):
  536. """
  537. Get some stats from the server. It will be available as a dict.
  538. @param arg: An optional additional string which will be sent along
  539. with the I{stats} command. The interpretation of this value by
  540. the server is left undefined by the memcache protocol
  541. specification.
  542. @type arg: L{None} or L{bytes}
  543. @return: a deferred that will fire with a L{dict} of the available
  544. statistics.
  545. @rtype: L{Deferred}
  546. """
  547. if arg:
  548. cmd = b"stats " + arg
  549. else:
  550. cmd = b"stats"
  551. if self._disconnected:
  552. return fail(RuntimeError("not connected"))
  553. self.sendLine(cmd)
  554. cmdObj = Command(b"stats", values={})
  555. self._current.append(cmdObj)
  556. return cmdObj._deferred
  557. def version(self):
  558. """
  559. Get the version of the server.
  560. @return: a deferred that will fire with the string value of the
  561. version.
  562. @rtype: L{Deferred}
  563. """
  564. if self._disconnected:
  565. return fail(RuntimeError("not connected"))
  566. self.sendLine(b"version")
  567. cmdObj = Command(b"version")
  568. self._current.append(cmdObj)
  569. return cmdObj._deferred
  570. def delete(self, key):
  571. """
  572. Delete an existing C{key}.
  573. @param key: the key to delete.
  574. @type key: L{bytes}
  575. @return: a deferred that will be called back with C{True} if the key
  576. was successfully deleted, or C{False} if not.
  577. @rtype: L{Deferred}
  578. """
  579. if self._disconnected:
  580. return fail(RuntimeError("not connected"))
  581. if not isinstance(key, bytes):
  582. return fail(ClientError(
  583. "Invalid type for key: %s, expecting bytes" % (type(key),)))
  584. self.sendLine(b"delete " + key)
  585. cmdObj = Command(b"delete", key=key)
  586. self._current.append(cmdObj)
  587. return cmdObj._deferred
  588. def flushAll(self):
  589. """
  590. Flush all cached values.
  591. @return: a deferred that will be called back with C{True} when the
  592. operation has succeeded.
  593. @rtype: L{Deferred}
  594. """
  595. if self._disconnected:
  596. return fail(RuntimeError("not connected"))
  597. self.sendLine(b"flush_all")
  598. cmdObj = Command(b"flush_all")
  599. self._current.append(cmdObj)
  600. return cmdObj._deferred
  601. __all__ = ["MemCacheProtocol", "DEFAULT_PORT", "NoSuchCommand", "ClientError",
  602. "ServerError"]