memcache.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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 collections import deque
  23. from twisted.internet.defer import Deferred, TimeoutError, fail
  24. from twisted.protocols.basic import LineReceiver
  25. from twisted.protocols.policies import TimeoutMixin
  26. from twisted.python import log
  27. from twisted.python.compat import nativeString, networkString
  28. DEFAULT_PORT = 11211
  29. class NoSuchCommand(Exception):
  30. """
  31. Exception raised when a non existent command is called.
  32. """
  33. class ClientError(Exception):
  34. """
  35. Error caused by an invalid client call.
  36. """
  37. class ServerError(Exception):
  38. """
  39. Problem happening on the server.
  40. """
  41. class Command:
  42. """
  43. Wrap a client action into an object, that holds the values used in the
  44. protocol.
  45. @ivar _deferred: the L{Deferred} object that will be fired when the result
  46. arrives.
  47. @type _deferred: L{Deferred}
  48. @ivar command: name of the command sent to the server.
  49. @type command: L{bytes}
  50. """
  51. def __init__(self, command, **kwargs):
  52. """
  53. Create a command.
  54. @param command: the name of the command.
  55. @type command: L{bytes}
  56. @param kwargs: this values will be stored as attributes of the object
  57. for future use
  58. """
  59. self.command = command
  60. self._deferred = Deferred()
  61. for k, v in kwargs.items():
  62. setattr(self, k, v)
  63. def success(self, value):
  64. """
  65. Shortcut method to fire the underlying deferred.
  66. """
  67. self._deferred.callback(value)
  68. def fail(self, error):
  69. """
  70. Make the underlying deferred fails.
  71. """
  72. self._deferred.errback(error)
  73. class MemCacheProtocol(LineReceiver, TimeoutMixin):
  74. """
  75. MemCache protocol: connect to a memcached server to store/retrieve values.
  76. @ivar persistentTimeOut: the timeout period used to wait for a response.
  77. @type persistentTimeOut: L{int}
  78. @ivar _current: current list of requests waiting for an answer from the
  79. server.
  80. @type _current: L{deque} of L{Command}
  81. @ivar _lenExpected: amount of data expected in raw mode, when reading for
  82. a value.
  83. @type _lenExpected: L{int}
  84. @ivar _getBuffer: current buffer of data, used to store temporary data
  85. when reading in raw mode.
  86. @type _getBuffer: L{list}
  87. @ivar _bufferLength: the total amount of bytes in C{_getBuffer}.
  88. @type _bufferLength: L{int}
  89. @ivar _disconnected: indicate if the connectionLost has been called or not.
  90. @type _disconnected: L{bool}
  91. """
  92. MAX_KEY_LENGTH = 250
  93. _disconnected = False
  94. def __init__(self, timeOut=60):
  95. """
  96. Create the protocol.
  97. @param timeOut: the timeout to wait before detecting that the
  98. connection is dead and close it. It's expressed in seconds.
  99. @type timeOut: L{int}
  100. """
  101. self._current = deque()
  102. self._lenExpected = None
  103. self._getBuffer = None
  104. self._bufferLength = None
  105. self.persistentTimeOut = self.timeOut = timeOut
  106. def _cancelCommands(self, reason):
  107. """
  108. Cancel all the outstanding commands, making them fail with C{reason}.
  109. """
  110. while self._current:
  111. cmd = self._current.popleft()
  112. cmd.fail(reason)
  113. def timeoutConnection(self):
  114. """
  115. Close the connection in case of timeout.
  116. """
  117. self._cancelCommands(TimeoutError("Connection timeout"))
  118. self.transport.loseConnection()
  119. def connectionLost(self, reason):
  120. """
  121. Cause any outstanding commands to fail.
  122. """
  123. self._disconnected = True
  124. self._cancelCommands(reason)
  125. LineReceiver.connectionLost(self, reason)
  126. def sendLine(self, line):
  127. """
  128. Override sendLine to add a timeout to response.
  129. """
  130. if not self._current:
  131. self.setTimeout(self.persistentTimeOut)
  132. LineReceiver.sendLine(self, line)
  133. def rawDataReceived(self, data):
  134. """
  135. Collect data for a get.
  136. """
  137. self.resetTimeout()
  138. self._getBuffer.append(data)
  139. self._bufferLength += len(data)
  140. if self._bufferLength >= self._lenExpected + 2:
  141. data = b"".join(self._getBuffer)
  142. buf = data[: self._lenExpected]
  143. rem = data[self._lenExpected + 2 :]
  144. val = buf
  145. self._lenExpected = None
  146. self._getBuffer = None
  147. self._bufferLength = None
  148. cmd = self._current[0]
  149. if cmd.multiple:
  150. flags, cas = cmd.values[cmd.currentKey]
  151. cmd.values[cmd.currentKey] = (flags, cas, val)
  152. else:
  153. cmd.value = val
  154. self.setLineMode(rem)
  155. def cmd_STORED(self):
  156. """
  157. Manage a success response to a set operation.
  158. """
  159. self._current.popleft().success(True)
  160. def cmd_NOT_STORED(self):
  161. """
  162. Manage a specific 'not stored' response to a set operation: this is not
  163. an error, but some condition wasn't met.
  164. """
  165. self._current.popleft().success(False)
  166. def cmd_END(self):
  167. """
  168. This the end token to a get or a stat operation.
  169. """
  170. cmd = self._current.popleft()
  171. if cmd.command == b"get":
  172. if cmd.multiple:
  173. values = {key: val[::2] for key, val in cmd.values.items()}
  174. cmd.success(values)
  175. else:
  176. cmd.success((cmd.flags, cmd.value))
  177. elif cmd.command == b"gets":
  178. if cmd.multiple:
  179. cmd.success(cmd.values)
  180. else:
  181. cmd.success((cmd.flags, cmd.cas, cmd.value))
  182. elif cmd.command == b"stats":
  183. cmd.success(cmd.values)
  184. else:
  185. raise RuntimeError(
  186. "Unexpected END response to {} command".format(
  187. nativeString(cmd.command)
  188. )
  189. )
  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(
  332. ClientError(f"Invalid type for key: {type(key)}, expecting bytes")
  333. )
  334. if len(key) > self.MAX_KEY_LENGTH:
  335. return fail(ClientError("Key too long"))
  336. fullcmd = b" ".join([cmd, key, b"%d" % (int(val),)])
  337. self.sendLine(fullcmd)
  338. cmdObj = Command(cmd, key=key)
  339. self._current.append(cmdObj)
  340. return cmdObj._deferred
  341. def replace(self, key, val, flags=0, expireTime=0):
  342. """
  343. Replace the given C{key}. It must already exist in the server.
  344. @param key: the key to replace.
  345. @type key: L{bytes}
  346. @param val: the new value associated with the key.
  347. @type val: L{bytes}
  348. @param flags: the flags to store with the key.
  349. @type flags: L{int}
  350. @param expireTime: if different from 0, the relative time in seconds
  351. when the key will be deleted from the store.
  352. @type expireTime: L{int}
  353. @return: a deferred that will fire with C{True} if the operation has
  354. succeeded, and C{False} with the key didn't previously exist.
  355. @rtype: L{Deferred}
  356. """
  357. return self._set(b"replace", key, val, flags, expireTime, b"")
  358. def add(self, key, val, flags=0, expireTime=0):
  359. """
  360. Add the given C{key}. It must not exist in the server.
  361. @param key: the key to add.
  362. @type key: L{bytes}
  363. @param val: the value associated with the key.
  364. @type val: L{bytes}
  365. @param flags: the flags to store with the key.
  366. @type flags: L{int}
  367. @param expireTime: if different from 0, the relative time in seconds
  368. when the key will be deleted from the store.
  369. @type expireTime: L{int}
  370. @return: a deferred that will fire with C{True} if the operation has
  371. succeeded, and C{False} with the key already exists.
  372. @rtype: L{Deferred}
  373. """
  374. return self._set(b"add", key, val, flags, expireTime, b"")
  375. def set(self, key, val, flags=0, expireTime=0):
  376. """
  377. Set the given C{key}.
  378. @param key: the key to set.
  379. @type key: L{bytes}
  380. @param val: the value associated with the key.
  381. @type val: L{bytes}
  382. @param flags: the flags to store with the key.
  383. @type flags: L{int}
  384. @param expireTime: if different from 0, the relative time in seconds
  385. when the key will be deleted from the store.
  386. @type expireTime: L{int}
  387. @return: a deferred that will fire with C{True} if the operation has
  388. succeeded.
  389. @rtype: L{Deferred}
  390. """
  391. return self._set(b"set", key, val, flags, expireTime, b"")
  392. def checkAndSet(self, key, val, cas, flags=0, expireTime=0):
  393. """
  394. Change the content of C{key} only if the C{cas} value matches the
  395. current one associated with the key. Use this to store a value which
  396. hasn't been modified since last time you fetched it.
  397. @param key: The key to set.
  398. @type key: L{bytes}
  399. @param val: The value associated with the key.
  400. @type val: L{bytes}
  401. @param cas: Unique 64-bit value returned by previous call of C{get}.
  402. @type cas: L{bytes}
  403. @param flags: The flags to store with the key.
  404. @type flags: L{int}
  405. @param expireTime: If different from 0, the relative time in seconds
  406. when the key will be deleted from the store.
  407. @type expireTime: L{int}
  408. @return: A deferred that will fire with C{True} if the operation has
  409. succeeded, C{False} otherwise.
  410. @rtype: L{Deferred}
  411. """
  412. return self._set(b"cas", key, val, flags, expireTime, cas)
  413. def _set(self, cmd, key, val, flags, expireTime, cas):
  414. """
  415. Internal wrapper for setting values.
  416. """
  417. if self._disconnected:
  418. return fail(RuntimeError("not connected"))
  419. if not isinstance(key, bytes):
  420. return fail(
  421. ClientError(f"Invalid type for key: {type(key)}, expecting bytes")
  422. )
  423. if len(key) > self.MAX_KEY_LENGTH:
  424. return fail(ClientError("Key too long"))
  425. if not isinstance(val, bytes):
  426. return fail(
  427. ClientError(f"Invalid type for value: {type(val)}, expecting bytes")
  428. )
  429. if cas:
  430. cas = b" " + cas
  431. length = len(val)
  432. fullcmd = (
  433. b" ".join(
  434. [cmd, key, networkString("%d %d %d" % (flags, expireTime, length))]
  435. )
  436. + cas
  437. )
  438. self.sendLine(fullcmd)
  439. self.sendLine(val)
  440. cmdObj = Command(cmd, key=key, flags=flags, length=length)
  441. self._current.append(cmdObj)
  442. return cmdObj._deferred
  443. def append(self, key, val):
  444. """
  445. Append given data to the value of an existing key.
  446. @param key: The key to modify.
  447. @type key: L{bytes}
  448. @param val: The value to append to the current value associated with
  449. the key.
  450. @type val: L{bytes}
  451. @return: A deferred that will fire with C{True} if the operation has
  452. succeeded, C{False} otherwise.
  453. @rtype: L{Deferred}
  454. """
  455. # Even if flags and expTime values are ignored, we have to pass them
  456. return self._set(b"append", key, val, 0, 0, b"")
  457. def prepend(self, key, val):
  458. """
  459. Prepend given data to the value of an existing key.
  460. @param key: The key to modify.
  461. @type key: L{bytes}
  462. @param val: The value to prepend to the current value associated with
  463. the key.
  464. @type val: L{bytes}
  465. @return: A deferred that will fire with C{True} if the operation has
  466. succeeded, C{False} otherwise.
  467. @rtype: L{Deferred}
  468. """
  469. # Even if flags and expTime values are ignored, we have to pass them
  470. return self._set(b"prepend", key, val, 0, 0, b"")
  471. def get(self, key, withIdentifier=False):
  472. """
  473. Get the given C{key}. It doesn't support multiple keys. If
  474. C{withIdentifier} is set to C{True}, the command issued is a C{gets},
  475. that will return the current identifier associated with the value. This
  476. identifier has to be used when issuing C{checkAndSet} update later,
  477. using the corresponding method.
  478. @param key: The key to retrieve.
  479. @type key: L{bytes}
  480. @param withIdentifier: If set to C{True}, retrieve the current
  481. identifier along with the value and the flags.
  482. @type withIdentifier: L{bool}
  483. @return: A deferred that will fire with the tuple (flags, value) if
  484. C{withIdentifier} is C{False}, or (flags, cas identifier, value)
  485. if C{True}. If the server indicates there is no value
  486. associated with C{key}, the returned value will be L{None} and
  487. the returned flags will be C{0}.
  488. @rtype: L{Deferred}
  489. """
  490. return self._get([key], withIdentifier, False)
  491. def getMultiple(self, keys, withIdentifier=False):
  492. """
  493. Get the given list of C{keys}. If C{withIdentifier} is set to C{True},
  494. the command issued is a C{gets}, that will return the identifiers
  495. associated with each values. This identifier has to be used when
  496. issuing C{checkAndSet} update later, using the corresponding method.
  497. @param keys: The keys to retrieve.
  498. @type keys: L{list} of L{bytes}
  499. @param withIdentifier: If set to C{True}, retrieve the identifiers
  500. along with the values and the flags.
  501. @type withIdentifier: L{bool}
  502. @return: A deferred that will fire with a dictionary with the elements
  503. of C{keys} as keys and the tuples (flags, value) as values if
  504. C{withIdentifier} is C{False}, or (flags, cas identifier, value) if
  505. C{True}. If the server indicates there is no value associated with
  506. C{key}, the returned values will be L{None} and the returned flags
  507. will be C{0}.
  508. @rtype: L{Deferred}
  509. @since: 9.0
  510. """
  511. return self._get(keys, withIdentifier, True)
  512. def _get(self, keys, withIdentifier, multiple):
  513. """
  514. Helper method for C{get} and C{getMultiple}.
  515. """
  516. keys = list(keys)
  517. if self._disconnected:
  518. return fail(RuntimeError("not connected"))
  519. for key in keys:
  520. if not isinstance(key, bytes):
  521. return fail(
  522. ClientError(f"Invalid type for key: {type(key)}, expecting bytes")
  523. )
  524. if len(key) > self.MAX_KEY_LENGTH:
  525. return fail(ClientError("Key too long"))
  526. if withIdentifier:
  527. cmd = b"gets"
  528. else:
  529. cmd = b"get"
  530. fullcmd = b" ".join([cmd] + keys)
  531. self.sendLine(fullcmd)
  532. if multiple:
  533. values = {key: (0, b"", None) for key in keys}
  534. cmdObj = Command(cmd, keys=keys, values=values, multiple=True)
  535. else:
  536. cmdObj = Command(
  537. cmd, key=keys[0], value=None, flags=0, cas=b"", multiple=False
  538. )
  539. self._current.append(cmdObj)
  540. return cmdObj._deferred
  541. def stats(self, arg=None):
  542. """
  543. Get some stats from the server. It will be available as a dict.
  544. @param arg: An optional additional string which will be sent along
  545. with the I{stats} command. The interpretation of this value by
  546. the server is left undefined by the memcache protocol
  547. specification.
  548. @type arg: L{None} or L{bytes}
  549. @return: a deferred that will fire with a L{dict} of the available
  550. statistics.
  551. @rtype: L{Deferred}
  552. """
  553. if arg:
  554. cmd = b"stats " + arg
  555. else:
  556. cmd = b"stats"
  557. if self._disconnected:
  558. return fail(RuntimeError("not connected"))
  559. self.sendLine(cmd)
  560. cmdObj = Command(b"stats", values={})
  561. self._current.append(cmdObj)
  562. return cmdObj._deferred
  563. def version(self):
  564. """
  565. Get the version of the server.
  566. @return: a deferred that will fire with the string value of the
  567. version.
  568. @rtype: L{Deferred}
  569. """
  570. if self._disconnected:
  571. return fail(RuntimeError("not connected"))
  572. self.sendLine(b"version")
  573. cmdObj = Command(b"version")
  574. self._current.append(cmdObj)
  575. return cmdObj._deferred
  576. def delete(self, key):
  577. """
  578. Delete an existing C{key}.
  579. @param key: the key to delete.
  580. @type key: L{bytes}
  581. @return: a deferred that will be called back with C{True} if the key
  582. was successfully deleted, or C{False} if not.
  583. @rtype: L{Deferred}
  584. """
  585. if self._disconnected:
  586. return fail(RuntimeError("not connected"))
  587. if not isinstance(key, bytes):
  588. return fail(
  589. ClientError(f"Invalid type for key: {type(key)}, expecting bytes")
  590. )
  591. self.sendLine(b"delete " + key)
  592. cmdObj = Command(b"delete", key=key)
  593. self._current.append(cmdObj)
  594. return cmdObj._deferred
  595. def flushAll(self):
  596. """
  597. Flush all cached values.
  598. @return: a deferred that will be called back with C{True} when the
  599. operation has succeeded.
  600. @rtype: L{Deferred}
  601. """
  602. if self._disconnected:
  603. return fail(RuntimeError("not connected"))
  604. self.sendLine(b"flush_all")
  605. cmdObj = Command(b"flush_all")
  606. self._current.append(cmdObj)
  607. return cmdObj._deferred
  608. __all__ = [
  609. "MemCacheProtocol",
  610. "DEFAULT_PORT",
  611. "NoSuchCommand",
  612. "ClientError",
  613. "ServerError",
  614. ]