__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016-2018 Julien Danjou
  3. # Copyright 2017 Elisey Zanko
  4. # Copyright 2016 Étienne Bersac
  5. # Copyright 2016 Joshua Harlow
  6. # Copyright 2013-2014 Ray Holder
  7. #
  8. # Licensed under the Apache License, Version 2.0 (the "License");
  9. # you may not use this file except in compliance with the License.
  10. # You may obtain a copy of the License at
  11. #
  12. # http://www.apache.org/licenses/LICENSE-2.0
  13. #
  14. # Unless required by applicable law or agreed to in writing, software
  15. # distributed under the License is distributed on an "AS IS" BASIS,
  16. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. # See the License for the specific language governing permissions and
  18. # limitations under the License.
  19. try:
  20. import asyncio
  21. except ImportError:
  22. asyncio = None
  23. try:
  24. import tornado
  25. except ImportError:
  26. tornado = None
  27. import sys
  28. import threading
  29. from concurrent import futures
  30. import six
  31. from tenacity import _utils
  32. from tenacity import compat as _compat
  33. # Import all built-in retry strategies for easier usage.
  34. from .retry import retry_all # noqa
  35. from .retry import retry_always # noqa
  36. from .retry import retry_any # noqa
  37. from .retry import retry_if_exception # noqa
  38. from .retry import retry_if_exception_type # noqa
  39. from .retry import retry_if_not_result # noqa
  40. from .retry import retry_if_result # noqa
  41. from .retry import retry_never # noqa
  42. from .retry import retry_unless_exception_type # noqa
  43. from .retry import retry_if_exception_message # noqa
  44. from .retry import retry_if_not_exception_message # noqa
  45. # Import all nap strategies for easier usage.
  46. from .nap import sleep # noqa
  47. from .nap import sleep_using_event # noqa
  48. # Import all built-in stop strategies for easier usage.
  49. from .stop import stop_after_attempt # noqa
  50. from .stop import stop_after_delay # noqa
  51. from .stop import stop_all # noqa
  52. from .stop import stop_any # noqa
  53. from .stop import stop_never # noqa
  54. from .stop import stop_when_event_set # noqa
  55. # Import all built-in wait strategies for easier usage.
  56. from .wait import wait_chain # noqa
  57. from .wait import wait_combine # noqa
  58. from .wait import wait_exponential # noqa
  59. from .wait import wait_fixed # noqa
  60. from .wait import wait_incrementing # noqa
  61. from .wait import wait_none # noqa
  62. from .wait import wait_random # noqa
  63. from .wait import wait_random_exponential # noqa
  64. from .wait import wait_random_exponential as wait_full_jitter # noqa
  65. # Import all built-in before strategies for easier usage.
  66. from .before import before_log # noqa
  67. from .before import before_nothing # noqa
  68. # Import all built-in after strategies for easier usage.
  69. from .after import after_log # noqa
  70. from .after import after_nothing # noqa
  71. # Import all built-in after strategies for easier usage.
  72. from .before_sleep import before_sleep_log # noqa
  73. from .before_sleep import before_sleep_nothing # noqa
  74. def retry(*dargs, **dkw):
  75. """Wrap a function with a new `Retrying` object.
  76. :param dargs: positional arguments passed to Retrying object
  77. :param dkw: keyword arguments passed to the Retrying object
  78. """
  79. # support both @retry and @retry() as valid syntax
  80. if len(dargs) == 1 and callable(dargs[0]):
  81. return retry()(dargs[0])
  82. else:
  83. def wrap(f):
  84. if asyncio and asyncio.iscoroutinefunction(f):
  85. r = AsyncRetrying(*dargs, **dkw)
  86. elif tornado and hasattr(tornado.gen, 'is_coroutine_function') \
  87. and tornado.gen.is_coroutine_function(f):
  88. r = TornadoRetrying(*dargs, **dkw)
  89. else:
  90. r = Retrying(*dargs, **dkw)
  91. return r.wraps(f)
  92. return wrap
  93. class TryAgain(Exception):
  94. """Always retry the executed function when raised."""
  95. NO_RESULT = object()
  96. class DoAttempt(object):
  97. pass
  98. class DoSleep(float):
  99. pass
  100. class BaseAction(object):
  101. """Base class for representing actions to take by retry object.
  102. Concrete implementations must define:
  103. - __init__: to initialize all necessary fields
  104. - REPR_ATTRS: class variable specifying attributes to include in repr(self)
  105. - NAME: for identification in retry object methods and callbacks
  106. """
  107. REPR_FIELDS = ()
  108. NAME = None
  109. def __repr__(self):
  110. state_str = ', '.join('%s=%r' % (field, getattr(self, field))
  111. for field in self.REPR_FIELDS)
  112. return '%s(%s)' % (type(self).__name__, state_str)
  113. def __str__(self):
  114. return repr(self)
  115. class RetryAction(BaseAction):
  116. REPR_FIELDS = ('sleep',)
  117. NAME = 'retry'
  118. def __init__(self, sleep):
  119. self.sleep = float(sleep)
  120. _unset = object()
  121. class RetryError(Exception):
  122. """Encapsulates the last attempt instance right before giving up."""
  123. def __init__(self, last_attempt):
  124. self.last_attempt = last_attempt
  125. def reraise(self):
  126. if self.last_attempt.failed:
  127. raise self.last_attempt.result()
  128. raise self
  129. def __str__(self):
  130. return "{0}[{1}]".format(self.__class__.__name__, self.last_attempt)
  131. class BaseRetrying(object):
  132. def __init__(self,
  133. sleep=sleep,
  134. stop=stop_never, wait=wait_none(),
  135. retry=retry_if_exception_type(),
  136. before=before_nothing,
  137. after=after_nothing,
  138. before_sleep=None,
  139. reraise=False,
  140. retry_error_cls=RetryError,
  141. retry_error_callback=None):
  142. self.sleep = sleep
  143. self._stop = stop
  144. self._wait = wait
  145. self._retry = retry
  146. self._before = before
  147. self._after = after
  148. self._before_sleep = before_sleep
  149. self.reraise = reraise
  150. self._local = threading.local()
  151. self.retry_error_cls = retry_error_cls
  152. self._retry_error_callback = retry_error_callback
  153. # This attribute was moved to RetryCallState and is deprecated on
  154. # Retrying objects but kept for backward compatibility.
  155. self.fn = None
  156. @_utils.cached_property
  157. def stop(self):
  158. return _compat.stop_func_accept_retry_state(self._stop)
  159. @_utils.cached_property
  160. def wait(self):
  161. return _compat.wait_func_accept_retry_state(self._wait)
  162. @_utils.cached_property
  163. def retry(self):
  164. return _compat.retry_func_accept_retry_state(self._retry)
  165. @_utils.cached_property
  166. def before(self):
  167. return _compat.before_func_accept_retry_state(self._before)
  168. @_utils.cached_property
  169. def after(self):
  170. return _compat.after_func_accept_retry_state(self._after)
  171. @_utils.cached_property
  172. def before_sleep(self):
  173. return _compat.before_sleep_func_accept_retry_state(self._before_sleep)
  174. @_utils.cached_property
  175. def retry_error_callback(self):
  176. return _compat.retry_error_callback_accept_retry_state(
  177. self._retry_error_callback)
  178. def copy(self, sleep=_unset, stop=_unset, wait=_unset,
  179. retry=_unset, before=_unset, after=_unset, before_sleep=_unset,
  180. reraise=_unset):
  181. """Copy this object with some parameters changed if needed."""
  182. if before_sleep is _unset:
  183. before_sleep = self.before_sleep
  184. return self.__class__(
  185. sleep=self.sleep if sleep is _unset else sleep,
  186. stop=self.stop if stop is _unset else stop,
  187. wait=self.wait if wait is _unset else wait,
  188. retry=self.retry if retry is _unset else retry,
  189. before=self.before if before is _unset else before,
  190. after=self.after if after is _unset else after,
  191. before_sleep=before_sleep,
  192. reraise=self.reraise if after is _unset else reraise,
  193. )
  194. def __repr__(self):
  195. attrs = dict(
  196. _utils.visible_attrs(self, attrs={'me': id(self)}),
  197. __class__=self.__class__.__name__,
  198. )
  199. return ("<%(__class__)s object at 0x%(me)x (stop=%(stop)s, "
  200. "wait=%(wait)s, sleep=%(sleep)s, retry=%(retry)s, "
  201. "before=%(before)s, after=%(after)s)>") % (attrs)
  202. @property
  203. def statistics(self):
  204. """Return a dictionary of runtime statistics.
  205. This dictionary will be empty when the controller has never been
  206. ran. When it is running or has ran previously it should have (but
  207. may not) have useful and/or informational keys and values when
  208. running is underway and/or completed.
  209. .. warning:: The keys in this dictionary **should** be some what
  210. stable (not changing), but there existence **may**
  211. change between major releases as new statistics are
  212. gathered or removed so before accessing keys ensure that
  213. they actually exist and handle when they do not.
  214. .. note:: The values in this dictionary are local to the thread
  215. running call (so if multiple threads share the same retrying
  216. object - either directly or indirectly) they will each have
  217. there own view of statistics they have collected (in the
  218. future we may provide a way to aggregate the various
  219. statistics from each thread).
  220. """
  221. try:
  222. return self._local.statistics
  223. except AttributeError:
  224. self._local.statistics = {}
  225. return self._local.statistics
  226. def wraps(self, f):
  227. """Wrap a function for retrying.
  228. :param f: A function to wraps for retrying.
  229. """
  230. @_utils.wraps(f)
  231. def wrapped_f(*args, **kw):
  232. return self.call(f, *args, **kw)
  233. def retry_with(*args, **kwargs):
  234. return self.copy(*args, **kwargs).wraps(f)
  235. wrapped_f.retry = self
  236. wrapped_f.retry_with = retry_with
  237. return wrapped_f
  238. def begin(self, fn):
  239. self.statistics.clear()
  240. self.statistics['start_time'] = _utils.now()
  241. self.statistics['attempt_number'] = 1
  242. self.statistics['idle_for'] = 0
  243. self.fn = fn
  244. def iter(self, retry_state): # noqa
  245. fut = retry_state.outcome
  246. if fut is None:
  247. if self.before is not None:
  248. self.before(retry_state)
  249. return DoAttempt()
  250. is_explicit_retry = retry_state.outcome.failed \
  251. and isinstance(retry_state.outcome.exception(), TryAgain)
  252. if not (is_explicit_retry or self.retry(retry_state=retry_state)):
  253. return fut.result()
  254. if self.after is not None:
  255. self.after(retry_state=retry_state)
  256. self.statistics['delay_since_first_attempt'] = \
  257. retry_state.seconds_since_start
  258. if self.stop(retry_state=retry_state):
  259. if self.retry_error_callback:
  260. return self.retry_error_callback(retry_state=retry_state)
  261. retry_exc = self.retry_error_cls(fut)
  262. if self.reraise:
  263. raise retry_exc.reraise()
  264. six.raise_from(retry_exc, fut.exception())
  265. if self.wait:
  266. sleep = self.wait(retry_state=retry_state)
  267. else:
  268. sleep = 0.0
  269. retry_state.next_action = RetryAction(sleep)
  270. retry_state.idle_for += sleep
  271. self.statistics['idle_for'] += sleep
  272. self.statistics['attempt_number'] += 1
  273. if self.before_sleep is not None:
  274. self.before_sleep(retry_state=retry_state)
  275. return DoSleep(sleep)
  276. class Retrying(BaseRetrying):
  277. """Retrying controller."""
  278. def call(self, fn, *args, **kwargs):
  279. self.begin(fn)
  280. retry_state = RetryCallState(
  281. retry_object=self, fn=fn, args=args, kwargs=kwargs)
  282. while True:
  283. do = self.iter(retry_state=retry_state)
  284. if isinstance(do, DoAttempt):
  285. try:
  286. result = fn(*args, **kwargs)
  287. except BaseException:
  288. retry_state.set_exception(sys.exc_info())
  289. else:
  290. retry_state.set_result(result)
  291. elif isinstance(do, DoSleep):
  292. retry_state.prepare_for_next_attempt()
  293. self.sleep(do)
  294. else:
  295. return do
  296. __call__ = call
  297. class Future(futures.Future):
  298. """Encapsulates a (future or past) attempted call to a target function."""
  299. def __init__(self, attempt_number):
  300. super(Future, self).__init__()
  301. self.attempt_number = attempt_number
  302. @property
  303. def failed(self):
  304. """Return whether a exception is being held in this future."""
  305. return self.exception() is not None
  306. @classmethod
  307. def construct(cls, attempt_number, value, has_exception):
  308. """Construct a new Future object."""
  309. fut = cls(attempt_number)
  310. if has_exception:
  311. fut.set_exception(value)
  312. else:
  313. fut.set_result(value)
  314. return fut
  315. class RetryCallState(object):
  316. """State related to a single call wrapped with Retrying."""
  317. def __init__(self, retry_object, fn, args, kwargs):
  318. #: Retry call start timestamp
  319. self.start_time = _utils.now()
  320. #: Retry manager object
  321. self.retry_object = retry_object
  322. #: Function wrapped by this retry call
  323. self.fn = fn
  324. #: Arguments of the function wrapped by this retry call
  325. self.args = args
  326. #: Keyword arguments of the function wrapped by this retry call
  327. self.kwargs = kwargs
  328. #: The number of the current attempt
  329. self.attempt_number = 1
  330. #: Last outcome (result or exception) produced by the function
  331. self.outcome = None
  332. #: Timestamp of the last outcome
  333. self.outcome_timestamp = None
  334. #: Time spent sleeping in retries
  335. self.idle_for = 0
  336. #: Next action as decided by the retry manager
  337. self.next_action = None
  338. @property
  339. def seconds_since_start(self):
  340. if self.outcome_timestamp is None:
  341. return None
  342. return self.outcome_timestamp - self.start_time
  343. def prepare_for_next_attempt(self):
  344. self.outcome = None
  345. self.outcome_timestamp = None
  346. self.attempt_number += 1
  347. self.next_action = None
  348. def set_result(self, val):
  349. ts = _utils.now()
  350. fut = Future(self.attempt_number)
  351. fut.set_result(val)
  352. self.outcome, self.outcome_timestamp = fut, ts
  353. def set_exception(self, exc_info):
  354. ts = _utils.now()
  355. fut = Future(self.attempt_number)
  356. _utils.capture(fut, exc_info)
  357. self.outcome, self.outcome_timestamp = fut, ts
  358. if asyncio:
  359. from tenacity._asyncio import AsyncRetrying
  360. if tornado:
  361. from tenacity.tornadoweb import TornadoRetrying