You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

retry.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. from __future__ import absolute_import
  2. import time
  3. import logging
  4. from collections import namedtuple
  5. from itertools import takewhile
  6. import email
  7. import re
  8. from ..exceptions import (
  9. ConnectTimeoutError,
  10. MaxRetryError,
  11. ProtocolError,
  12. ReadTimeoutError,
  13. ResponseError,
  14. InvalidHeader,
  15. )
  16. from ..packages import six
  17. log = logging.getLogger(__name__)
  18. # Data structure for representing the metadata of requests that result in a retry.
  19. RequestHistory = namedtuple('RequestHistory', ["method", "url", "error",
  20. "status", "redirect_location"])
  21. class Retry(object):
  22. """ Retry configuration.
  23. Each retry attempt will create a new Retry object with updated values, so
  24. they can be safely reused.
  25. Retries can be defined as a default for a pool::
  26. retries = Retry(connect=5, read=2, redirect=5)
  27. http = PoolManager(retries=retries)
  28. response = http.request('GET', 'http://example.com/')
  29. Or per-request (which overrides the default for the pool)::
  30. response = http.request('GET', 'http://example.com/', retries=Retry(10))
  31. Retries can be disabled by passing ``False``::
  32. response = http.request('GET', 'http://example.com/', retries=False)
  33. Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless
  34. retries are disabled, in which case the causing exception will be raised.
  35. :param int total:
  36. Total number of retries to allow. Takes precedence over other counts.
  37. Set to ``None`` to remove this constraint and fall back on other
  38. counts. It's a good idea to set this to some sensibly-high value to
  39. account for unexpected edge cases and avoid infinite retry loops.
  40. Set to ``0`` to fail on the first retry.
  41. Set to ``False`` to disable and imply ``raise_on_redirect=False``.
  42. :param int connect:
  43. How many connection-related errors to retry on.
  44. These are errors raised before the request is sent to the remote server,
  45. which we assume has not triggered the server to process the request.
  46. Set to ``0`` to fail on the first retry of this type.
  47. :param int read:
  48. How many times to retry on read errors.
  49. These errors are raised after the request was sent to the server, so the
  50. request may have side-effects.
  51. Set to ``0`` to fail on the first retry of this type.
  52. :param int redirect:
  53. How many redirects to perform. Limit this to avoid infinite redirect
  54. loops.
  55. A redirect is a HTTP response with a status code 301, 302, 303, 307 or
  56. 308.
  57. Set to ``0`` to fail on the first retry of this type.
  58. Set to ``False`` to disable and imply ``raise_on_redirect=False``.
  59. :param int status:
  60. How many times to retry on bad status codes.
  61. These are retries made on responses, where status code matches
  62. ``status_forcelist``.
  63. Set to ``0`` to fail on the first retry of this type.
  64. :param iterable method_whitelist:
  65. Set of uppercased HTTP method verbs that we should retry on.
  66. By default, we only retry on methods which are considered to be
  67. idempotent (multiple requests with the same parameters end with the
  68. same state). See :attr:`Retry.DEFAULT_METHOD_WHITELIST`.
  69. Set to a ``False`` value to retry on any verb.
  70. :param iterable status_forcelist:
  71. A set of integer HTTP status codes that we should force a retry on.
  72. A retry is initiated if the request method is in ``method_whitelist``
  73. and the response status code is in ``status_forcelist``.
  74. By default, this is disabled with ``None``.
  75. :param float backoff_factor:
  76. A backoff factor to apply between attempts after the second try
  77. (most errors are resolved immediately by a second try without a
  78. delay). urllib3 will sleep for::
  79. {backoff factor} * (2 ^ ({number of total retries} - 1))
  80. seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep
  81. for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer
  82. than :attr:`Retry.BACKOFF_MAX`.
  83. By default, backoff is disabled (set to 0).
  84. :param bool raise_on_redirect: Whether, if the number of redirects is
  85. exhausted, to raise a MaxRetryError, or to return a response with a
  86. response code in the 3xx range.
  87. :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:
  88. whether we should raise an exception, or return a response,
  89. if status falls in ``status_forcelist`` range and retries have
  90. been exhausted.
  91. :param tuple history: The history of the request encountered during
  92. each call to :meth:`~Retry.increment`. The list is in the order
  93. the requests occurred. Each list item is of class :class:`RequestHistory`.
  94. :param bool respect_retry_after_header:
  95. Whether to respect Retry-After header on status codes defined as
  96. :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.
  97. """
  98. DEFAULT_METHOD_WHITELIST = frozenset([
  99. 'HEAD', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'])
  100. RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])
  101. #: Maximum backoff time.
  102. BACKOFF_MAX = 120
  103. def __init__(self, total=10, connect=None, read=None, redirect=None, status=None,
  104. method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None,
  105. backoff_factor=0, raise_on_redirect=True, raise_on_status=True,
  106. history=None, respect_retry_after_header=True):
  107. self.total = total
  108. self.connect = connect
  109. self.read = read
  110. self.status = status
  111. if redirect is False or total is False:
  112. redirect = 0
  113. raise_on_redirect = False
  114. self.redirect = redirect
  115. self.status_forcelist = status_forcelist or set()
  116. self.method_whitelist = method_whitelist
  117. self.backoff_factor = backoff_factor
  118. self.raise_on_redirect = raise_on_redirect
  119. self.raise_on_status = raise_on_status
  120. self.history = history or tuple()
  121. self.respect_retry_after_header = respect_retry_after_header
  122. def new(self, **kw):
  123. params = dict(
  124. total=self.total,
  125. connect=self.connect, read=self.read, redirect=self.redirect, status=self.status,
  126. method_whitelist=self.method_whitelist,
  127. status_forcelist=self.status_forcelist,
  128. backoff_factor=self.backoff_factor,
  129. raise_on_redirect=self.raise_on_redirect,
  130. raise_on_status=self.raise_on_status,
  131. history=self.history,
  132. )
  133. params.update(kw)
  134. return type(self)(**params)
  135. @classmethod
  136. def from_int(cls, retries, redirect=True, default=None):
  137. """ Backwards-compatibility for the old retries format."""
  138. if retries is None:
  139. retries = default if default is not None else cls.DEFAULT
  140. if isinstance(retries, Retry):
  141. return retries
  142. redirect = bool(redirect) and None
  143. new_retries = cls(retries, redirect=redirect)
  144. log.debug("Converted retries value: %r -> %r", retries, new_retries)
  145. return new_retries
  146. def get_backoff_time(self):
  147. """ Formula for computing the current backoff
  148. :rtype: float
  149. """
  150. # We want to consider only the last consecutive errors sequence (Ignore redirects).
  151. consecutive_errors_len = len(list(takewhile(lambda x: x.redirect_location is None,
  152. reversed(self.history))))
  153. if consecutive_errors_len <= 1:
  154. return 0
  155. backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))
  156. return min(self.BACKOFF_MAX, backoff_value)
  157. def parse_retry_after(self, retry_after):
  158. # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4
  159. if re.match(r"^\s*[0-9]+\s*$", retry_after):
  160. seconds = int(retry_after)
  161. else:
  162. retry_date_tuple = email.utils.parsedate(retry_after)
  163. if retry_date_tuple is None:
  164. raise InvalidHeader("Invalid Retry-After header: %s" % retry_after)
  165. retry_date = time.mktime(retry_date_tuple)
  166. seconds = retry_date - time.time()
  167. if seconds < 0:
  168. seconds = 0
  169. return seconds
  170. def get_retry_after(self, response):
  171. """ Get the value of Retry-After in seconds. """
  172. retry_after = response.getheader("Retry-After")
  173. if retry_after is None:
  174. return None
  175. return self.parse_retry_after(retry_after)
  176. def sleep_for_retry(self, response=None):
  177. retry_after = self.get_retry_after(response)
  178. if retry_after:
  179. time.sleep(retry_after)
  180. return True
  181. return False
  182. def _sleep_backoff(self):
  183. backoff = self.get_backoff_time()
  184. if backoff <= 0:
  185. return
  186. time.sleep(backoff)
  187. def sleep(self, response=None):
  188. """ Sleep between retry attempts.
  189. This method will respect a server's ``Retry-After`` response header
  190. and sleep the duration of the time requested. If that is not present, it
  191. will use an exponential backoff. By default, the backoff factor is 0 and
  192. this method will return immediately.
  193. """
  194. if response:
  195. slept = self.sleep_for_retry(response)
  196. if slept:
  197. return
  198. self._sleep_backoff()
  199. def _is_connection_error(self, err):
  200. """ Errors when we're fairly sure that the server did not receive the
  201. request, so it should be safe to retry.
  202. """
  203. return isinstance(err, ConnectTimeoutError)
  204. def _is_read_error(self, err):
  205. """ Errors that occur after the request has been started, so we should
  206. assume that the server began processing it.
  207. """
  208. return isinstance(err, (ReadTimeoutError, ProtocolError))
  209. def _is_method_retryable(self, method):
  210. """ Checks if a given HTTP method should be retried upon, depending if
  211. it is included on the method whitelist.
  212. """
  213. if self.method_whitelist and method.upper() not in self.method_whitelist:
  214. return False
  215. return True
  216. def is_retry(self, method, status_code, has_retry_after=False):
  217. """ Is this method/status code retryable? (Based on whitelists and control
  218. variables such as the number of total retries to allow, whether to
  219. respect the Retry-After header, whether this header is present, and
  220. whether the returned status code is on the list of status codes to
  221. be retried upon on the presence of the aforementioned header)
  222. """
  223. if not self._is_method_retryable(method):
  224. return False
  225. if self.status_forcelist and status_code in self.status_forcelist:
  226. return True
  227. return (self.total and self.respect_retry_after_header and
  228. has_retry_after and (status_code in self.RETRY_AFTER_STATUS_CODES))
  229. def is_exhausted(self):
  230. """ Are we out of retries? """
  231. retry_counts = (self.total, self.connect, self.read, self.redirect, self.status)
  232. retry_counts = list(filter(None, retry_counts))
  233. if not retry_counts:
  234. return False
  235. return min(retry_counts) < 0
  236. def increment(self, method=None, url=None, response=None, error=None,
  237. _pool=None, _stacktrace=None):
  238. """ Return a new Retry object with incremented retry counters.
  239. :param response: A response object, or None, if the server did not
  240. return a response.
  241. :type response: :class:`~urllib3.response.HTTPResponse`
  242. :param Exception error: An error encountered during the request, or
  243. None if the response was received successfully.
  244. :return: A new ``Retry`` object.
  245. """
  246. if self.total is False and error:
  247. # Disabled, indicate to re-raise the error.
  248. raise six.reraise(type(error), error, _stacktrace)
  249. total = self.total
  250. if total is not None:
  251. total -= 1
  252. connect = self.connect
  253. read = self.read
  254. redirect = self.redirect
  255. status_count = self.status
  256. cause = 'unknown'
  257. status = None
  258. redirect_location = None
  259. if error and self._is_connection_error(error):
  260. # Connect retry?
  261. if connect is False:
  262. raise six.reraise(type(error), error, _stacktrace)
  263. elif connect is not None:
  264. connect -= 1
  265. elif error and self._is_read_error(error):
  266. # Read retry?
  267. if read is False or not self._is_method_retryable(method):
  268. raise six.reraise(type(error), error, _stacktrace)
  269. elif read is not None:
  270. read -= 1
  271. elif response and response.get_redirect_location():
  272. # Redirect retry?
  273. if redirect is not None:
  274. redirect -= 1
  275. cause = 'too many redirects'
  276. redirect_location = response.get_redirect_location()
  277. status = response.status
  278. else:
  279. # Incrementing because of a server error like a 500 in
  280. # status_forcelist and a the given method is in the whitelist
  281. cause = ResponseError.GENERIC_ERROR
  282. if response and response.status:
  283. if status_count is not None:
  284. status_count -= 1
  285. cause = ResponseError.SPECIFIC_ERROR.format(
  286. status_code=response.status)
  287. status = response.status
  288. history = self.history + (RequestHistory(method, url, error, status, redirect_location),)
  289. new_retry = self.new(
  290. total=total,
  291. connect=connect, read=read, redirect=redirect, status=status_count,
  292. history=history)
  293. if new_retry.is_exhausted():
  294. raise MaxRetryError(_pool, url, error or ResponseError(cause))
  295. log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)
  296. return new_retry
  297. def __repr__(self):
  298. return ('{cls.__name__}(total={self.total}, connect={self.connect}, '
  299. 'read={self.read}, redirect={self.redirect}, status={self.status})').format(
  300. cls=type(self), self=self)
  301. # For backwards compatibility (equivalent to pre-v1.9):
  302. Retry.DEFAULT = Retry(3)