base.py 54 KB

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