base.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. # Copyright 2012 Pinterest.com
  2. #
  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. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import errno
  15. import platform
  16. import socket
  17. import six
  18. from pymemcache import pool
  19. from pymemcache.serde import LegacyWrappingSerde
  20. from pymemcache.exceptions import (
  21. MemcacheClientError,
  22. MemcacheUnknownCommandError,
  23. MemcacheIllegalInputError,
  24. MemcacheServerError,
  25. MemcacheUnknownError,
  26. MemcacheUnexpectedCloseError
  27. )
  28. RECV_SIZE = 4096
  29. VALID_STORE_RESULTS = {
  30. b'set': (b'STORED', b'NOT_STORED'),
  31. b'add': (b'STORED', b'NOT_STORED'),
  32. b'replace': (b'STORED', b'NOT_STORED'),
  33. b'append': (b'STORED', b'NOT_STORED'),
  34. b'prepend': (b'STORED', b'NOT_STORED'),
  35. b'cas': (b'STORED', b'EXISTS', b'NOT_FOUND'),
  36. }
  37. SOCKET_KEEPALIVE_SUPPORTED_SYSTEM = {
  38. 'Linux',
  39. }
  40. STORE_RESULTS_VALUE = {
  41. b'STORED': True,
  42. b'NOT_STORED': False,
  43. b'NOT_FOUND': None,
  44. b'EXISTS': False
  45. }
  46. # Some of the values returned by the "stats" command
  47. # need mapping into native Python types
  48. def _parse_bool_int(value):
  49. return int(value) != 0
  50. def _parse_bool_string_is_yes(value):
  51. return value == b'yes'
  52. def _parse_float(value):
  53. return float(value.replace(b':', b'.'))
  54. def _parse_hex(value):
  55. return int(value, 8)
  56. STAT_TYPES = {
  57. # General stats
  58. b'version': six.binary_type,
  59. b'rusage_user': _parse_float,
  60. b'rusage_system': _parse_float,
  61. b'hash_is_expanding': _parse_bool_int,
  62. b'slab_reassign_running': _parse_bool_int,
  63. # Settings stats
  64. b'inter': six.binary_type,
  65. b'growth_factor': float,
  66. b'stat_key_prefix': six.binary_type,
  67. b'umask': _parse_hex,
  68. b'detail_enabled': _parse_bool_int,
  69. b'cas_enabled': _parse_bool_int,
  70. b'auth_enabled_sasl': _parse_bool_string_is_yes,
  71. b'maxconns_fast': _parse_bool_int,
  72. b'slab_reassign': _parse_bool_int,
  73. b'slab_automove': _parse_bool_int,
  74. }
  75. # Common helper functions.
  76. def check_key_helper(key, allow_unicode_keys, key_prefix=b''):
  77. """Checks key and add key_prefix."""
  78. if allow_unicode_keys:
  79. if isinstance(key, six.text_type):
  80. key = key.encode('utf8')
  81. elif isinstance(key, six.string_types):
  82. try:
  83. if isinstance(key, six.binary_type):
  84. key = key.decode().encode('ascii')
  85. else:
  86. key = key.encode('ascii')
  87. except (UnicodeEncodeError, UnicodeDecodeError):
  88. raise MemcacheIllegalInputError("Non-ASCII key: %r" % key)
  89. key = key_prefix + key
  90. parts = key.split()
  91. if len(key) > 250:
  92. raise MemcacheIllegalInputError("Key is too long: %r" % key)
  93. # second statement catches leading or trailing whitespace
  94. elif len(parts) > 1 or (parts and parts[0] != key):
  95. raise MemcacheIllegalInputError("Key contains whitespace: %r" % key)
  96. elif b'\00' in key:
  97. raise MemcacheIllegalInputError("Key contains null: %r" % key)
  98. return key
  99. def normalize_server_spec(server):
  100. if isinstance(server, tuple) or server is None:
  101. return server
  102. if isinstance(server, list):
  103. return tuple(server) # Assume [host, port] provided.
  104. if not isinstance(server, six.string_types):
  105. raise ValueError('Unknown server provided: %r' % server)
  106. if server.startswith('unix:'):
  107. return server[5:]
  108. if server.startswith('/'):
  109. return server
  110. if ':' not in server or server.endswith(']'):
  111. host, port = server, 11211
  112. else:
  113. host, port = server.rsplit(':', 1)
  114. port = int(port)
  115. if host.startswith('['):
  116. host = host.strip('[]')
  117. return (host, port)
  118. class KeepaliveOpts(object):
  119. """
  120. A configuration structure to define the socket keepalive.
  121. This structure must be passed to a client. The client will configure
  122. its socket keepalive by using the elements of the structure.
  123. Args:
  124. idle: The time (in seconds) the connection needs to remain idle
  125. before TCP starts sending keepalive probes. Should be a positive
  126. integer most greater than zero.
  127. intvl: The time (in seconds) between individual keepalive probes.
  128. Should be a positive integer most greater than zero.
  129. cnt: The maximum number of keepalive probes TCP should send before
  130. dropping the connection. Should be a positive integer most greater
  131. than zero.
  132. """
  133. __slots__ = ('idle', 'intvl', 'cnt')
  134. def __init__(self, idle=1, intvl=1, cnt=5):
  135. if idle < 1:
  136. raise ValueError(
  137. "The idle parameter must be greater or equal to 1.")
  138. self.idle = idle
  139. if intvl < 1:
  140. raise ValueError(
  141. "The intvl parameter must be greater or equal to 1.")
  142. self.intvl = intvl
  143. if cnt < 1:
  144. raise ValueError(
  145. "The cnt parameter must be greater or equal to 1.")
  146. self.cnt = cnt
  147. class Client(object):
  148. """
  149. A client for a single memcached server.
  150. *Server Connection*
  151. The ``server`` parameter controls how the client connects to the memcached
  152. server. You can either use a (host, port) tuple for a TCP connection or a
  153. string containing the path to a UNIX domain socket.
  154. The ``connect_timeout`` and ``timeout`` parameters can be used to set
  155. socket timeout values. By default, timeouts are disabled.
  156. When the ``no_delay`` flag is set, the ``TCP_NODELAY`` socket option will
  157. also be set. This only applies to TCP-based connections.
  158. Lastly, the ``socket_module`` allows you to specify an alternate socket
  159. implementation (such as `gevent.socket`_).
  160. .. _gevent.socket: http://www.gevent.org/api/gevent.socket.html
  161. *Keys and Values*
  162. Keys must have a __str__() method which should return a str with no more
  163. than 250 ASCII characters and no whitespace or control characters. Unicode
  164. strings must be encoded (as UTF-8, for example) unless they consist only
  165. of ASCII characters that are neither whitespace nor control characters.
  166. Values must have a __str__() method to convert themselves to a byte
  167. string. Unicode objects can be a problem since str() on a Unicode object
  168. will attempt to encode it as ASCII (which will fail if the value contains
  169. code points larger than U+127). You can fix this with a serializer or by
  170. just calling encode on the string (using UTF-8, for instance).
  171. If you intend to use anything but str as a value, it is a good idea to use
  172. a serializer. The pymemcache.serde library has an already implemented
  173. serializer which pickles and unpickles data.
  174. *Serialization and Deserialization*
  175. The constructor takes an optional object, the "serializer/deserializer"
  176. ("serde"), which is responsible for both serialization and deserialization
  177. of objects. That object must satisfy the serializer interface by providing
  178. two methods: `serialize` and `deserialize`. `serialize` takes two
  179. arguments, a key and a value, and returns a tuple of two elements, the
  180. serialized value, and an integer in the range 0-65535 (the "flags").
  181. `deserialize` takes three parameters, a key, value, and flags, and returns
  182. the deserialized value.
  183. Here is an example using JSON for non-str values:
  184. .. code-block:: python
  185. class JSONSerde(object):
  186. def serialize(self, key, value):
  187. if isinstance(value, str):
  188. return value, 1
  189. return json.dumps(value), 2
  190. def deserialize(self, key, value, flags):
  191. if flags == 1:
  192. return value
  193. if flags == 2:
  194. return json.loads(value)
  195. raise Exception("Unknown flags for value: {1}".format(flags))
  196. .. note::
  197. Most write operations allow the caller to provide a ``flags`` value to
  198. support advanced interaction with the server. This will **override** the
  199. "flags" value returned by the serializer and should therefore only be
  200. used when you have a complete understanding of how the value should be
  201. serialized, stored, and deserialized.
  202. *Error Handling*
  203. All of the methods in this class that talk to memcached can throw one of
  204. the following exceptions:
  205. * :class:`pymemcache.exceptions.MemcacheUnknownCommandError`
  206. * :class:`pymemcache.exceptions.MemcacheClientError`
  207. * :class:`pymemcache.exceptions.MemcacheServerError`
  208. * :class:`pymemcache.exceptions.MemcacheUnknownError`
  209. * :class:`pymemcache.exceptions.MemcacheUnexpectedCloseError`
  210. * :class:`pymemcache.exceptions.MemcacheIllegalInputError`
  211. * :class:`socket.timeout`
  212. * :class:`socket.error`
  213. Instances of this class maintain a persistent connection to memcached
  214. which is terminated when any of these exceptions are raised. The next
  215. call to a method on the object will result in a new connection being made
  216. to memcached.
  217. """
  218. def __init__(self,
  219. server,
  220. serde=None,
  221. serializer=None,
  222. deserializer=None,
  223. connect_timeout=None,
  224. timeout=None,
  225. no_delay=False,
  226. ignore_exc=False,
  227. socket_module=socket,
  228. socket_keepalive=None,
  229. key_prefix=b'',
  230. default_noreply=True,
  231. allow_unicode_keys=False,
  232. encoding='ascii',
  233. tls_context=None):
  234. """
  235. Constructor.
  236. Args:
  237. server: tuple(hostname, port) or string containing a UNIX socket path.
  238. serde: optional seralizer object, see notes in the class docs.
  239. serializer: deprecated serialization function
  240. deserializer: deprecated deserialization function
  241. connect_timeout: optional float, seconds to wait for a connection to
  242. the memcached server. Defaults to "forever" (uses the underlying
  243. default socket timeout, which can be very long).
  244. timeout: optional float, seconds to wait for send or recv calls on
  245. the socket connected to memcached. Defaults to "forever" (uses the
  246. underlying default socket timeout, which can be very long).
  247. no_delay: optional bool, set the TCP_NODELAY flag, which may help
  248. with performance in some cases. Defaults to False.
  249. ignore_exc: optional bool, True to cause the "get", "gets",
  250. "get_many" and "gets_many" calls to treat any errors as cache
  251. misses. Defaults to False.
  252. socket_module: socket module to use, e.g. gevent.socket. Defaults to
  253. the standard library's socket module.
  254. socket_keepalive: Activate the socket keepalive feature by passing
  255. a KeepaliveOpts structure in this parameter. Disabled by default
  256. (None). This feature is only supported on Linux platforms.
  257. key_prefix: Prefix of key. You can use this as namespace. Defaults
  258. to b''.
  259. default_noreply: bool, the default value for 'noreply' as passed to
  260. store commands (except from cas, incr, and decr, which default to
  261. False).
  262. allow_unicode_keys: bool, support unicode (utf8) keys
  263. encoding: optional str, controls data encoding (defaults to 'ascii').
  264. Notes:
  265. The constructor does not make a connection to memcached. The first
  266. call to a method on the object will do that.
  267. """
  268. self.server = normalize_server_spec(server)
  269. self.serde = serde or LegacyWrappingSerde(serializer, deserializer)
  270. self.connect_timeout = connect_timeout
  271. self.timeout = timeout
  272. self.no_delay = no_delay
  273. self.ignore_exc = ignore_exc
  274. self.socket_module = socket_module
  275. self.socket_keepalive = socket_keepalive
  276. user_system = platform.system()
  277. if self.socket_keepalive is not None:
  278. if user_system not in SOCKET_KEEPALIVE_SUPPORTED_SYSTEM:
  279. raise SystemError(
  280. "Pymemcache's socket keepalive mechaniss doesn't "
  281. "support your system ({user_system}). If "
  282. "you see this message it mean that you tried to "
  283. "configure your socket keepalive on an unsupported "
  284. "system. To fix the problem pass `socket_"
  285. "keepalive=False` or use a supported system. "
  286. "Supported systems are: {systems}".format(
  287. user_system=user_system,
  288. systems=", ".join(sorted(
  289. SOCKET_KEEPALIVE_SUPPORTED_SYSTEM))
  290. )
  291. )
  292. if not isinstance(self.socket_keepalive, KeepaliveOpts):
  293. raise ValueError(
  294. "Unsupported keepalive options. If you see this message "
  295. "it means that you passed an unsupported object within "
  296. "the param `socket_keepalive`. To fix it "
  297. "please instantiate and pass to socket_keepalive a "
  298. "KeepaliveOpts object. That's the only supported type "
  299. "of structure."
  300. )
  301. self.sock = None
  302. if isinstance(key_prefix, six.text_type):
  303. key_prefix = key_prefix.encode('ascii')
  304. if not isinstance(key_prefix, six.binary_type):
  305. raise TypeError("key_prefix should be bytes.")
  306. self.key_prefix = key_prefix
  307. self.default_noreply = default_noreply
  308. self.allow_unicode_keys = allow_unicode_keys
  309. self.encoding = encoding
  310. self.tls_context = tls_context
  311. def check_key(self, key):
  312. """Checks key and add key_prefix."""
  313. return check_key_helper(key, allow_unicode_keys=self.allow_unicode_keys,
  314. key_prefix=self.key_prefix)
  315. def _connect(self):
  316. self.close()
  317. s = self.socket_module
  318. if not isinstance(self.server, tuple):
  319. sockaddr = self.server
  320. sock = s.socket(s.AF_UNIX, s.SOCK_STREAM)
  321. else:
  322. sock = None
  323. error = None
  324. host, port = self.server
  325. info = s.getaddrinfo(host, port, s.AF_UNSPEC, s.SOCK_STREAM,
  326. s.IPPROTO_TCP)
  327. for family, socktype, proto, _, sockaddr in info:
  328. try:
  329. sock = s.socket(family, socktype, proto)
  330. if self.no_delay:
  331. sock.setsockopt(s.IPPROTO_TCP, s.TCP_NODELAY, 1)
  332. if self.tls_context:
  333. context = self.tls_context
  334. sock = context.wrap_socket(sock, server_hostname=host)
  335. except Exception as e:
  336. error = e
  337. if sock is not None:
  338. sock.close()
  339. sock = None
  340. else:
  341. break
  342. if error is not None:
  343. raise error
  344. try:
  345. sock.settimeout(self.connect_timeout)
  346. if self.socket_keepalive is not None:
  347. sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
  348. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE,
  349. self.socket_keepalive.idle)
  350. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL,
  351. self.socket_keepalive.intvl)
  352. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT,
  353. self.socket_keepalive.cnt)
  354. sock.connect(sockaddr)
  355. sock.settimeout(self.timeout)
  356. except Exception:
  357. sock.close()
  358. raise
  359. self.sock = sock
  360. def close(self):
  361. """Close the connection to memcached, if it is open. The next call to a
  362. method that requires a connection will re-open it."""
  363. if self.sock is not None:
  364. try:
  365. self.sock.close()
  366. except Exception:
  367. pass
  368. finally:
  369. self.sock = None
  370. disconnect_all = close
  371. def set(self, key, value, expire=0, noreply=None, flags=None):
  372. """
  373. The memcached "set" command.
  374. Args:
  375. key: str, see class docs for details.
  376. value: str, see class docs for details.
  377. expire: optional int, number of seconds until the item is expired
  378. from the cache, or zero for no expiry (the default).
  379. noreply: optional bool, True to not wait for the reply (defaults to
  380. self.default_noreply).
  381. flags: optional int, arbitrary bit field used for server-specific
  382. flags
  383. Returns:
  384. If no exception is raised, always returns True. If an exception is
  385. raised, the set may or may not have occurred. If noreply is True,
  386. then a successful return does not guarantee a successful set.
  387. """
  388. if noreply is None:
  389. noreply = self.default_noreply
  390. return self._store_cmd(b'set', {key: value}, expire, noreply,
  391. flags=flags)[key]
  392. def set_many(self, values, expire=0, noreply=None, flags=None):
  393. """
  394. A convenience function for setting multiple values.
  395. Args:
  396. values: dict(str, str), a dict of keys and values, see class docs
  397. for details.
  398. expire: optional int, number of seconds until the item is expired
  399. from the cache, or zero for no expiry (the default).
  400. noreply: optional bool, True to not wait for the reply (defaults to
  401. self.default_noreply).
  402. flags: optional int, arbitrary bit field used for server-specific
  403. flags
  404. Returns:
  405. Returns a list of keys that failed to be inserted.
  406. If noreply is True, always returns empty list.
  407. """
  408. if noreply is None:
  409. noreply = self.default_noreply
  410. result = self._store_cmd(b'set', values, expire, noreply, flags=flags)
  411. return [k for k, v in six.iteritems(result) if not v]
  412. set_multi = set_many
  413. def add(self, key, value, expire=0, noreply=None, flags=None):
  414. """
  415. The memcached "add" command.
  416. Args:
  417. key: str, see class docs for details.
  418. value: str, see class docs for details.
  419. expire: optional int, number of seconds until the item is expired
  420. from the cache, or zero for no expiry (the default).
  421. noreply: optional bool, True to not wait for the reply (defaults to
  422. self.default_noreply).
  423. flags: optional int, arbitrary bit field used for server-specific
  424. flags
  425. Returns:
  426. If ``noreply`` is True (or if it is unset and ``self.default_noreply``
  427. is True), the return value is always True. Otherwise the return value
  428. is True if the value was stored, and False if it was not (because
  429. the key already existed).
  430. """
  431. if noreply is None:
  432. noreply = self.default_noreply
  433. return self._store_cmd(b'add', {key: value}, expire, noreply,
  434. flags=flags)[key]
  435. def replace(self, key, value, expire=0, noreply=None, flags=None):
  436. """
  437. The memcached "replace" command.
  438. Args:
  439. key: str, see class docs for details.
  440. value: str, see class docs for details.
  441. expire: optional int, number of seconds until the item is expired
  442. from the cache, or zero for no expiry (the default).
  443. noreply: optional bool, True to not wait for the reply (defaults to
  444. self.default_noreply).
  445. flags: optional int, arbitrary bit field used for server-specific
  446. flags
  447. Returns:
  448. If ``noreply`` is True (or if it is unset and ``self.default_noreply``
  449. is True), the return value is always True. Otherwise returns True if
  450. the value was stored and False if it wasn't (because the key didn't
  451. already exist).
  452. """
  453. if noreply is None:
  454. noreply = self.default_noreply
  455. return self._store_cmd(b'replace', {key: value}, expire, noreply,
  456. flags=flags)[key]
  457. def append(self, key, value, expire=0, noreply=None, flags=None):
  458. """
  459. The memcached "append" command.
  460. Args:
  461. key: str, see class docs for details.
  462. value: str, see class docs for details.
  463. expire: optional int, number of seconds until the item is expired
  464. from the cache, or zero for no expiry (the default).
  465. noreply: optional bool, True to not wait for the reply (defaults to
  466. self.default_noreply).
  467. flags: optional int, arbitrary bit field used for server-specific
  468. flags
  469. Returns:
  470. True.
  471. """
  472. if noreply is None:
  473. noreply = self.default_noreply
  474. return self._store_cmd(b'append', {key: value}, expire, noreply,
  475. flags=flags)[key]
  476. def prepend(self, key, value, expire=0, noreply=None, flags=None):
  477. """
  478. The memcached "prepend" command.
  479. Args:
  480. key: str, see class docs for details.
  481. value: str, see class docs for details.
  482. expire: optional int, number of seconds until the item is expired
  483. from the cache, or zero for no expiry (the default).
  484. noreply: optional bool, True to not wait for the reply (defaults to
  485. self.default_noreply).
  486. flags: optional int, arbitrary bit field used for server-specific
  487. flags
  488. Returns:
  489. True.
  490. """
  491. if noreply is None:
  492. noreply = self.default_noreply
  493. return self._store_cmd(b'prepend', {key: value}, expire, noreply,
  494. flags=flags)[key]
  495. def cas(self, key, value, cas, expire=0, noreply=False, flags=None):
  496. """
  497. The memcached "cas" command.
  498. Args:
  499. key: str, see class docs for details.
  500. value: str, see class docs for details.
  501. cas: int or str that only contains the characters '0'-'9'.
  502. expire: optional int, number of seconds until the item is expired
  503. from the cache, or zero for no expiry (the default).
  504. noreply: optional bool, False to wait for the reply (the default).
  505. flags: optional int, arbitrary bit field used for server-specific
  506. flags
  507. Returns:
  508. If ``noreply`` is True (or if it is unset and ``self.default_noreply``
  509. is True), the return value is always True. Otherwise returns None if
  510. the key didn't exist, False if it existed but had a different cas
  511. value and True if it existed and was changed.
  512. """
  513. cas = self._check_cas(cas)
  514. return self._store_cmd(b'cas', {key: value}, expire, noreply,
  515. flags=flags, cas=cas)[key]
  516. def get(self, key, default=None):
  517. """
  518. The memcached "get" command, but only for one key, as a convenience.
  519. Args:
  520. key: str, see class docs for details.
  521. default: value that will be returned if the key was not found.
  522. Returns:
  523. The value for the key, or default if the key wasn't found.
  524. """
  525. return self._fetch_cmd(b'get', [key], False).get(key, default)
  526. def get_many(self, keys):
  527. """
  528. The memcached "get" command.
  529. Args:
  530. keys: list(str), see class docs for details.
  531. Returns:
  532. A dict in which the keys are elements of the "keys" argument list
  533. and the values are values from the cache. The dict may contain all,
  534. some or none of the given keys.
  535. """
  536. if not keys:
  537. return {}
  538. return self._fetch_cmd(b'get', keys, False)
  539. get_multi = get_many
  540. def gets(self, key, default=None, cas_default=None):
  541. """
  542. The memcached "gets" command for one key, as a convenience.
  543. Args:
  544. key: str, see class docs for details.
  545. default: value that will be returned if the key was not found.
  546. cas_default: same behaviour as default argument.
  547. Returns:
  548. A tuple of (value, cas)
  549. or (default, cas_defaults) if the key was not found.
  550. """
  551. defaults = (default, cas_default)
  552. return self._fetch_cmd(b'gets', [key], True).get(key, defaults)
  553. def gets_many(self, keys):
  554. """
  555. The memcached "gets" command.
  556. Args:
  557. keys: list(str), see class docs for details.
  558. Returns:
  559. A dict in which the keys are elements of the "keys" argument list and
  560. the values are tuples of (value, cas) from the cache. The dict may
  561. contain all, some or none of the given keys.
  562. """
  563. if not keys:
  564. return {}
  565. return self._fetch_cmd(b'gets', keys, True)
  566. def delete(self, key, noreply=None):
  567. """
  568. The memcached "delete" command.
  569. Args:
  570. key: str, see class docs for details.
  571. noreply: optional bool, True to not wait for the reply (defaults to
  572. self.default_noreply).
  573. Returns:
  574. If ``noreply`` is True (or if it is unset and ``self.default_noreply``
  575. is True), the return value is always True. Otherwise returns True if
  576. the key was deleted, and False if it wasn't found.
  577. """
  578. if noreply is None:
  579. noreply = self.default_noreply
  580. cmd = b'delete ' + self.check_key(key)
  581. if noreply:
  582. cmd += b' noreply'
  583. cmd += b'\r\n'
  584. results = self._misc_cmd([cmd], b'delete', noreply)
  585. if noreply:
  586. return True
  587. return results[0] == b'DELETED'
  588. def delete_many(self, keys, noreply=None):
  589. """
  590. A convenience function to delete multiple keys.
  591. Args:
  592. keys: list(str), the list of keys to delete.
  593. noreply: optional bool, True to not wait for the reply (defaults to
  594. self.default_noreply).
  595. Returns:
  596. True. If an exception is raised then all, some or none of the keys
  597. may have been deleted. Otherwise all the keys have been sent to
  598. memcache for deletion and if noreply is False, they have been
  599. acknowledged by memcache.
  600. """
  601. if not keys:
  602. return True
  603. if noreply is None:
  604. noreply = self.default_noreply
  605. cmds = []
  606. for key in keys:
  607. cmds.append(
  608. b'delete ' + self.check_key(key) +
  609. (b' noreply' if noreply else b'') +
  610. b'\r\n')
  611. self._misc_cmd(cmds, b'delete', noreply)
  612. return True
  613. delete_multi = delete_many
  614. def incr(self, key, value, noreply=False):
  615. """
  616. The memcached "incr" command.
  617. Args:
  618. key: str, see class docs for details.
  619. value: int, the amount by which to increment the value.
  620. noreply: optional bool, False to wait for the reply (the default).
  621. Returns:
  622. If noreply is True, always returns None. Otherwise returns the new
  623. value of the key, or None if the key wasn't found.
  624. """
  625. key = self.check_key(key)
  626. value = self._check_integer(value, "value")
  627. cmd = b'incr ' + key + b' ' + value
  628. if noreply:
  629. cmd += b' noreply'
  630. cmd += b'\r\n'
  631. results = self._misc_cmd([cmd], b'incr', noreply)
  632. if noreply:
  633. return None
  634. if results[0] == b'NOT_FOUND':
  635. return None
  636. return int(results[0])
  637. def decr(self, key, value, noreply=False):
  638. """
  639. The memcached "decr" command.
  640. Args:
  641. key: str, see class docs for details.
  642. value: int, the amount by which to decrement the value.
  643. noreply: optional bool, False to wait for the reply (the default).
  644. Returns:
  645. If noreply is True, always returns None. Otherwise returns the new
  646. value of the key, or None if the key wasn't found.
  647. """
  648. key = self.check_key(key)
  649. value = self._check_integer(value, "value")
  650. cmd = b'decr ' + key + b' ' + value
  651. if noreply:
  652. cmd += b' noreply'
  653. cmd += b'\r\n'
  654. results = self._misc_cmd([cmd], b'decr', noreply)
  655. if noreply:
  656. return None
  657. if results[0] == b'NOT_FOUND':
  658. return None
  659. return int(results[0])
  660. def touch(self, key, expire=0, noreply=None):
  661. """
  662. The memcached "touch" command.
  663. Args:
  664. key: str, see class docs for details.
  665. expire: optional int, number of seconds until the item is expired
  666. from the cache, or zero for no expiry (the default).
  667. noreply: optional bool, True to not wait for the reply (defaults to
  668. self.default_noreply).
  669. Returns:
  670. True if the expiration time was updated, False if the key wasn't
  671. found.
  672. """
  673. if noreply is None:
  674. noreply = self.default_noreply
  675. key = self.check_key(key)
  676. expire = self._check_integer(expire, "expire")
  677. cmd = b'touch ' + key + b' ' + expire
  678. if noreply:
  679. cmd += b' noreply'
  680. cmd += b'\r\n'
  681. results = self._misc_cmd([cmd], b'touch', noreply)
  682. if noreply:
  683. return True
  684. return results[0] == b'TOUCHED'
  685. def stats(self, *args):
  686. """
  687. The memcached "stats" command.
  688. The returned keys depend on what the "stats" command returns.
  689. A best effort is made to convert values to appropriate Python
  690. types, defaulting to strings when a conversion cannot be made.
  691. Args:
  692. *arg: extra string arguments to the "stats" command. See the
  693. memcached protocol documentation for more information.
  694. Returns:
  695. A dict of the returned stats.
  696. """
  697. result = self._fetch_cmd(b'stats', args, False)
  698. for key, value in six.iteritems(result):
  699. converter = STAT_TYPES.get(key, int)
  700. try:
  701. result[key] = converter(value)
  702. except Exception:
  703. pass
  704. return result
  705. def cache_memlimit(self, memlimit):
  706. """
  707. The memcached "cache_memlimit" command.
  708. Args:
  709. memlimit: int, the number of megabytes to set as the new cache memory
  710. limit.
  711. Returns:
  712. If no exception is raised, always returns True.
  713. """
  714. memlimit = self._check_integer(memlimit, "memlimit")
  715. self._fetch_cmd(b'cache_memlimit', [memlimit], False)
  716. return True
  717. def version(self):
  718. """
  719. The memcached "version" command.
  720. Returns:
  721. A string of the memcached version.
  722. """
  723. cmd = b"version\r\n"
  724. results = self._misc_cmd([cmd], b'version', False)
  725. before, _, after = results[0].partition(b' ')
  726. if before != b'VERSION':
  727. raise MemcacheUnknownError(
  728. "Received unexpected response: %s" % results[0])
  729. return after
  730. def flush_all(self, delay=0, noreply=None):
  731. """
  732. The memcached "flush_all" command.
  733. Args:
  734. delay: optional int, the number of seconds to wait before flushing,
  735. or zero to flush immediately (the default).
  736. noreply: optional bool, True to not wait for the reply (defaults to
  737. self.default_noreply).
  738. Returns:
  739. True.
  740. """
  741. if noreply is None:
  742. noreply = self.default_noreply
  743. delay = self._check_integer(delay, "delay")
  744. cmd = b'flush_all ' + delay
  745. if noreply:
  746. cmd += b' noreply'
  747. cmd += b'\r\n'
  748. results = self._misc_cmd([cmd], b'flush_all', noreply)
  749. if noreply:
  750. return True
  751. return results[0] == b'OK'
  752. def quit(self):
  753. """
  754. The memcached "quit" command.
  755. This will close the connection with memcached. Calling any other
  756. method on this object will re-open the connection, so this object can
  757. be re-used after quit.
  758. """
  759. cmd = b"quit\r\n"
  760. self._misc_cmd([cmd], b'quit', True)
  761. self.close()
  762. def shutdown(self, graceful=False):
  763. """
  764. The memcached "shutdown" command.
  765. This will request shutdown and eventual termination of the server,
  766. optionally preceded by a graceful stop of memcached's internal state
  767. machine. Note that the server needs to have been started with the
  768. shutdown protocol command enabled with the --enable-shutdown flag.
  769. Args:
  770. graceful: optional bool, True to request a graceful shutdown with
  771. SIGUSR1 (defaults to False, i.e. SIGINT shutdown).
  772. """
  773. cmd = b'shutdown'
  774. if graceful:
  775. cmd += b' graceful'
  776. cmd += b'\r\n'
  777. # The shutdown command raises a server-side error if the shutdown
  778. # protocol command is not enabled. Otherwise, a successful shutdown
  779. # is expected to close the remote end of the transport.
  780. try:
  781. self._misc_cmd([cmd], b'shutdown', False)
  782. except MemcacheUnexpectedCloseError:
  783. pass
  784. def _raise_errors(self, line, name):
  785. if line.startswith(b'ERROR'):
  786. raise MemcacheUnknownCommandError(name)
  787. if line.startswith(b'CLIENT_ERROR'):
  788. error = line[line.find(b' ') + 1:]
  789. raise MemcacheClientError(error)
  790. if line.startswith(b'SERVER_ERROR'):
  791. error = line[line.find(b' ') + 1:]
  792. raise MemcacheServerError(error)
  793. def _check_integer(self, value, name):
  794. """Check that a value is an integer and encode it as a binary string"""
  795. if not isinstance(value, six.integer_types):
  796. raise MemcacheIllegalInputError(
  797. '%s must be integer, got bad value: %r' % (name, value)
  798. )
  799. return six.text_type(value).encode(self.encoding)
  800. def _check_cas(self, cas):
  801. """Check that a value is a valid input for 'cas' -- either an int or a
  802. string containing only 0-9
  803. The value will be (re)encoded so that we can accept strings or bytes.
  804. """
  805. # convert non-binary values to binary
  806. if isinstance(cas, (six.integer_types, six.string_types)):
  807. try:
  808. cas = six.text_type(cas).encode(self.encoding)
  809. except UnicodeEncodeError:
  810. raise MemcacheIllegalInputError(
  811. 'non-ASCII cas value: %r' % cas)
  812. elif not isinstance(cas, six.binary_type):
  813. raise MemcacheIllegalInputError(
  814. 'cas must be integer, string, or bytes, got bad value: %r' % cas
  815. )
  816. if not cas.isdigit():
  817. raise MemcacheIllegalInputError(
  818. 'cas must only contain values in 0-9, got bad value: %r'
  819. % cas
  820. )
  821. return cas
  822. def _extract_value(self, expect_cas, line, buf, remapped_keys,
  823. prefixed_keys):
  824. """
  825. This function is abstracted from _fetch_cmd to support different ways
  826. of value extraction. In order to use this feature, _extract_value needs
  827. to be overridden in the subclass.
  828. """
  829. if expect_cas:
  830. _, key, flags, size, cas = line.split()
  831. else:
  832. try:
  833. _, key, flags, size = line.split()
  834. except Exception as e:
  835. raise ValueError("Unable to parse line %s: %s" % (line, e))
  836. value = None
  837. try:
  838. buf, value = _readvalue(self.sock, buf, int(size))
  839. except MemcacheUnexpectedCloseError:
  840. self.close()
  841. raise
  842. key = remapped_keys[key]
  843. value = self.serde.deserialize(key, value, int(flags))
  844. if expect_cas:
  845. return key, (value, cas), buf
  846. else:
  847. return key, value, buf
  848. def _fetch_cmd(self, name, keys, expect_cas):
  849. prefixed_keys = [self.check_key(k) for k in keys]
  850. remapped_keys = dict(zip(prefixed_keys, keys))
  851. # It is important for all keys to be listed in their original order.
  852. cmd = name
  853. if prefixed_keys:
  854. cmd += b' ' + b' '.join(prefixed_keys)
  855. cmd += b'\r\n'
  856. try:
  857. if self.sock is None:
  858. self._connect()
  859. self.sock.sendall(cmd)
  860. buf = b''
  861. line = None
  862. result = {}
  863. while True:
  864. try:
  865. buf, line = _readline(self.sock, buf)
  866. except MemcacheUnexpectedCloseError:
  867. self.close()
  868. raise
  869. self._raise_errors(line, name)
  870. if line == b'END' or line == b'OK':
  871. return result
  872. elif line.startswith(b'VALUE'):
  873. key, value, buf = self._extract_value(expect_cas, line, buf,
  874. remapped_keys,
  875. prefixed_keys)
  876. result[key] = value
  877. elif name == b'stats' and line.startswith(b'STAT'):
  878. key_value = line.split()
  879. result[key_value[1]] = key_value[2]
  880. elif name == b'stats' and line.startswith(b'ITEM'):
  881. # For 'stats cachedump' commands
  882. key_value = line.split()
  883. result[key_value[1]] = b' '.join(key_value[2:])
  884. else:
  885. raise MemcacheUnknownError(line[:32])
  886. except Exception:
  887. self.close()
  888. if self.ignore_exc:
  889. return {}
  890. raise
  891. def _store_cmd(self, name, values, expire, noreply, flags=None, cas=None):
  892. cmds = []
  893. keys = []
  894. extra = b''
  895. if cas is not None:
  896. extra += b' ' + cas
  897. if noreply:
  898. extra += b' noreply'
  899. expire = self._check_integer(expire, "expire")
  900. for key, data in six.iteritems(values):
  901. # must be able to reliably map responses back to the original order
  902. keys.append(key)
  903. key = self.check_key(key)
  904. data, data_flags = self.serde.serialize(key, data)
  905. # If 'flags' was explicitly provided, it overrides the value
  906. # returned by the serializer.
  907. if flags is not None:
  908. data_flags = flags
  909. if not isinstance(data, six.binary_type):
  910. try:
  911. data = six.text_type(data).encode(self.encoding)
  912. except UnicodeEncodeError as e:
  913. raise MemcacheIllegalInputError(
  914. "Data values must be binary-safe: %s" % e)
  915. cmds.append(name + b' ' + key + b' ' +
  916. six.text_type(data_flags).encode(self.encoding) +
  917. b' ' + expire +
  918. b' ' + six.text_type(len(data)).encode(self.encoding) +
  919. extra + b'\r\n' + data + b'\r\n')
  920. if self.sock is None:
  921. self._connect()
  922. try:
  923. self.sock.sendall(b''.join(cmds))
  924. if noreply:
  925. return {k: True for k in keys}
  926. results = {}
  927. buf = b''
  928. line = None
  929. for key in keys:
  930. try:
  931. buf, line = _readline(self.sock, buf)
  932. except MemcacheUnexpectedCloseError:
  933. self.close()
  934. raise
  935. self._raise_errors(line, name)
  936. if line in VALID_STORE_RESULTS[name]:
  937. results[key] = STORE_RESULTS_VALUE[line]
  938. else:
  939. raise MemcacheUnknownError(line[:32])
  940. return results
  941. except Exception:
  942. self.close()
  943. raise
  944. def _misc_cmd(self, cmds, cmd_name, noreply):
  945. if self.sock is None:
  946. self._connect()
  947. try:
  948. self.sock.sendall(b''.join(cmds))
  949. if noreply:
  950. return []
  951. results = []
  952. buf = b''
  953. line = None
  954. for cmd in cmds:
  955. try:
  956. buf, line = _readline(self.sock, buf)
  957. except MemcacheUnexpectedCloseError:
  958. self.close()
  959. raise
  960. self._raise_errors(line, cmd_name)
  961. results.append(line)
  962. return results
  963. except Exception:
  964. self.close()
  965. raise
  966. def __setitem__(self, key, value):
  967. self.set(key, value, noreply=True)
  968. def __getitem__(self, key):
  969. value = self.get(key)
  970. if value is None:
  971. raise KeyError
  972. return value
  973. def __delitem__(self, key):
  974. self.delete(key, noreply=True)
  975. class PooledClient(object):
  976. """A thread-safe pool of clients (with the same client api).
  977. Args:
  978. max_pool_size: maximum pool size to use (going above this amount
  979. triggers a runtime error), by default this is 2147483648L
  980. when not provided (or none).
  981. pool_idle_timeout: pooled connections are discarded if they have been
  982. unused for this many seconds. A value of 0 indicates
  983. that pooled connections are never discarded.
  984. lock_generator: a callback/type that takes no arguments that will
  985. be called to create a lock or semaphore that can
  986. protect the pool from concurrent access (for example a
  987. eventlet lock or semaphore could be used instead)
  988. Further arguments are interpreted as for :py:class:`.Client` constructor.
  989. Note: if `serde` is given, the same object will be used for *all* clients
  990. in the pool. Your serde object must therefore be thread-safe.
  991. """
  992. #: :class:`Client` class used to create new clients
  993. client_class = Client
  994. def __init__(self,
  995. server,
  996. serde=None,
  997. serializer=None,
  998. deserializer=None,
  999. connect_timeout=None,
  1000. timeout=None,
  1001. no_delay=False,
  1002. ignore_exc=False,
  1003. socket_module=socket,
  1004. socket_keepalive=None,
  1005. key_prefix=b'',
  1006. max_pool_size=None,
  1007. pool_idle_timeout=0,
  1008. lock_generator=None,
  1009. default_noreply=True,
  1010. allow_unicode_keys=False,
  1011. encoding='ascii',
  1012. tls_context=None):
  1013. self.server = normalize_server_spec(server)
  1014. self.serde = serde or LegacyWrappingSerde(serializer, deserializer)
  1015. self.connect_timeout = connect_timeout
  1016. self.timeout = timeout
  1017. self.no_delay = no_delay
  1018. self.ignore_exc = ignore_exc
  1019. self.socket_module = socket_module
  1020. self.socket_keepalive = socket_keepalive
  1021. self.default_noreply = default_noreply
  1022. self.allow_unicode_keys = allow_unicode_keys
  1023. if isinstance(key_prefix, six.text_type):
  1024. key_prefix = key_prefix.encode('ascii')
  1025. if not isinstance(key_prefix, six.binary_type):
  1026. raise TypeError("key_prefix should be bytes.")
  1027. self.key_prefix = key_prefix
  1028. self.client_pool = pool.ObjectPool(
  1029. self._create_client,
  1030. after_remove=lambda client: client.close(),
  1031. max_size=max_pool_size,
  1032. idle_timeout=pool_idle_timeout,
  1033. lock_generator=lock_generator)
  1034. self.encoding = encoding
  1035. self.tls_context = tls_context
  1036. def check_key(self, key):
  1037. """Checks key and add key_prefix."""
  1038. return check_key_helper(key, allow_unicode_keys=self.allow_unicode_keys,
  1039. key_prefix=self.key_prefix)
  1040. def _create_client(self):
  1041. return self.client_class(
  1042. self.server,
  1043. serde=self.serde,
  1044. connect_timeout=self.connect_timeout,
  1045. timeout=self.timeout,
  1046. no_delay=self.no_delay,
  1047. # We need to know when it fails *always* so that we
  1048. # can remove/destroy it from the pool...
  1049. ignore_exc=False,
  1050. socket_module=self.socket_module,
  1051. socket_keepalive=self.socket_keepalive,
  1052. key_prefix=self.key_prefix,
  1053. default_noreply=self.default_noreply,
  1054. allow_unicode_keys=self.allow_unicode_keys,
  1055. tls_context=self.tls_context)
  1056. def close(self):
  1057. self.client_pool.clear()
  1058. disconnect_all = close
  1059. def set(self, key, value, expire=0, noreply=None, flags=None):
  1060. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1061. return client.set(key, value, expire=expire, noreply=noreply,
  1062. flags=flags)
  1063. def set_many(self, values, expire=0, noreply=None, flags=None):
  1064. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1065. return client.set_many(values, expire=expire, noreply=noreply,
  1066. flags=flags)
  1067. set_multi = set_many
  1068. def replace(self, key, value, expire=0, noreply=None, flags=None):
  1069. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1070. return client.replace(key, value, expire=expire, noreply=noreply,
  1071. flags=flags)
  1072. def append(self, key, value, expire=0, noreply=None, flags=None):
  1073. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1074. return client.append(key, value, expire=expire, noreply=noreply,
  1075. flags=flags)
  1076. def prepend(self, key, value, expire=0, noreply=None, flags=None):
  1077. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1078. return client.prepend(key, value, expire=expire, noreply=noreply,
  1079. flags=flags)
  1080. def cas(self, key, value, cas, expire=0, noreply=False, flags=None):
  1081. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1082. return client.cas(key, value, cas,
  1083. expire=expire, noreply=noreply, flags=flags)
  1084. def get(self, key, default=None):
  1085. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1086. try:
  1087. return client.get(key, default)
  1088. except Exception:
  1089. if self.ignore_exc:
  1090. return None
  1091. else:
  1092. raise
  1093. def get_many(self, keys):
  1094. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1095. try:
  1096. return client.get_many(keys)
  1097. except Exception:
  1098. if self.ignore_exc:
  1099. return {}
  1100. else:
  1101. raise
  1102. get_multi = get_many
  1103. def gets(self, key):
  1104. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1105. try:
  1106. return client.gets(key)
  1107. except Exception:
  1108. if self.ignore_exc:
  1109. return (None, None)
  1110. else:
  1111. raise
  1112. def gets_many(self, keys):
  1113. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1114. try:
  1115. return client.gets_many(keys)
  1116. except Exception:
  1117. if self.ignore_exc:
  1118. return {}
  1119. else:
  1120. raise
  1121. def delete(self, key, noreply=None):
  1122. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1123. return client.delete(key, noreply=noreply)
  1124. def delete_many(self, keys, noreply=None):
  1125. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1126. return client.delete_many(keys, noreply=noreply)
  1127. delete_multi = delete_many
  1128. def add(self, key, value, expire=0, noreply=None, flags=None):
  1129. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1130. return client.add(key, value, expire=expire, noreply=noreply,
  1131. flags=flags)
  1132. def incr(self, key, value, noreply=False):
  1133. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1134. return client.incr(key, value, noreply=noreply)
  1135. def decr(self, key, value, noreply=False):
  1136. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1137. return client.decr(key, value, noreply=noreply)
  1138. def touch(self, key, expire=0, noreply=None):
  1139. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1140. return client.touch(key, expire=expire, noreply=noreply)
  1141. def stats(self, *args):
  1142. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1143. try:
  1144. return client.stats(*args)
  1145. except Exception:
  1146. if self.ignore_exc:
  1147. return {}
  1148. else:
  1149. raise
  1150. def version(self):
  1151. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1152. return client.version()
  1153. def flush_all(self, delay=0, noreply=None):
  1154. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1155. return client.flush_all(delay=delay, noreply=noreply)
  1156. def quit(self):
  1157. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1158. try:
  1159. client.quit()
  1160. finally:
  1161. self.client_pool.destroy(client)
  1162. def shutdown(self, graceful=False):
  1163. with self.client_pool.get_and_release(destroy_on_fail=True) as client:
  1164. client.shutdown(graceful)
  1165. def __setitem__(self, key, value):
  1166. self.set(key, value, noreply=True)
  1167. def __getitem__(self, key):
  1168. value = self.get(key)
  1169. if value is None:
  1170. raise KeyError
  1171. return value
  1172. def __delitem__(self, key):
  1173. self.delete(key, noreply=True)
  1174. def _readline(sock, buf):
  1175. """Read line of text from the socket.
  1176. Read a line of text (delimited by "\r\n") from the socket, and
  1177. return that line along with any trailing characters read from the
  1178. socket.
  1179. Args:
  1180. sock: Socket object, should be connected.
  1181. buf: String, zero or more characters, returned from an earlier
  1182. call to _readline or _readvalue (pass an empty string on the
  1183. first call).
  1184. Returns:
  1185. A tuple of (buf, line) where line is the full line read from the
  1186. socket (minus the "\r\n" characters) and buf is any trailing
  1187. characters read after the "\r\n" was found (which may be an empty
  1188. string).
  1189. """
  1190. chunks = []
  1191. last_char = b''
  1192. while True:
  1193. # We're reading in chunks, so "\r\n" could appear in one chunk,
  1194. # or across the boundary of two chunks, so we check for both
  1195. # cases.
  1196. # This case must appear first, since the buffer could have
  1197. # later \r\n characters in it and we want to get the first \r\n.
  1198. if last_char == b'\r' and buf[0:1] == b'\n':
  1199. # Strip the last character from the last chunk.
  1200. chunks[-1] = chunks[-1][:-1]
  1201. return buf[1:], b''.join(chunks)
  1202. elif buf.find(b'\r\n') != -1:
  1203. before, sep, after = buf.partition(b"\r\n")
  1204. chunks.append(before)
  1205. return after, b''.join(chunks)
  1206. if buf:
  1207. chunks.append(buf)
  1208. last_char = buf[-1:]
  1209. buf = _recv(sock, RECV_SIZE)
  1210. if not buf:
  1211. raise MemcacheUnexpectedCloseError()
  1212. def _readvalue(sock, buf, size):
  1213. """Read specified amount of bytes from the socket.
  1214. Read size bytes, followed by the "\r\n" characters, from the socket,
  1215. and return those bytes and any trailing bytes read after the "\r\n".
  1216. Args:
  1217. sock: Socket object, should be connected.
  1218. buf: String, zero or more characters, returned from an earlier
  1219. call to _readline or _readvalue (pass an empty string on the
  1220. first call).
  1221. size: Integer, number of bytes to read from the socket.
  1222. Returns:
  1223. A tuple of (buf, value) where value is the bytes read from the
  1224. socket (there will be exactly size bytes) and buf is trailing
  1225. characters read after the "\r\n" following the bytes (but not
  1226. including the \r\n).
  1227. """
  1228. chunks = []
  1229. rlen = size + 2
  1230. while rlen - len(buf) > 0:
  1231. if buf:
  1232. rlen -= len(buf)
  1233. chunks.append(buf)
  1234. buf = _recv(sock, RECV_SIZE)
  1235. if not buf:
  1236. raise MemcacheUnexpectedCloseError()
  1237. # Now we need to remove the \r\n from the end. There are two cases we care
  1238. # about: the \r\n is all in the last buffer, or only the \n is in the last
  1239. # buffer, and we need to remove the \r from the penultimate buffer.
  1240. if rlen == 1:
  1241. # replace the last chunk with the same string minus the last character,
  1242. # which is always '\r' in this case.
  1243. chunks[-1] = chunks[-1][:-1]
  1244. else:
  1245. # Just remove the "\r\n" from the latest chunk
  1246. chunks.append(buf[:rlen - 2])
  1247. return buf[rlen:], b''.join(chunks)
  1248. def _recv(sock, size):
  1249. """sock.recv() with retry on EINTR"""
  1250. while True:
  1251. try:
  1252. return sock.recv(size)
  1253. except IOError as e:
  1254. if e.errno != errno.EINTR:
  1255. raise