retry.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. :param iterable remove_headers_on_redirect:
  98. Sequence of headers to remove from the request when a response
  99. indicating a redirect is returned before firing off the redirected
  100. request.
  101. """
  102. DEFAULT_METHOD_WHITELIST = frozenset([
  103. 'HEAD', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'])
  104. RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])
  105. DEFAULT_REDIRECT_HEADERS_BLACKLIST = frozenset(['Authorization'])
  106. #: Maximum backoff time.
  107. BACKOFF_MAX = 120
  108. def __init__(self, total=10, connect=None, read=None, redirect=None, status=None,
  109. method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None,
  110. backoff_factor=0, raise_on_redirect=True, raise_on_status=True,
  111. history=None, respect_retry_after_header=True,
  112. remove_headers_on_redirect=DEFAULT_REDIRECT_HEADERS_BLACKLIST):
  113. self.total = total
  114. self.connect = connect
  115. self.read = read
  116. self.status = status
  117. if redirect is False or total is False:
  118. redirect = 0
  119. raise_on_redirect = False
  120. self.redirect = redirect
  121. self.status_forcelist = status_forcelist or set()
  122. self.method_whitelist = method_whitelist
  123. self.backoff_factor = backoff_factor
  124. self.raise_on_redirect = raise_on_redirect
  125. self.raise_on_status = raise_on_status
  126. self.history = history or tuple()
  127. self.respect_retry_after_header = respect_retry_after_header
  128. self.remove_headers_on_redirect = frozenset([
  129. h.lower() for h in remove_headers_on_redirect])
  130. def new(self, **kw):
  131. params = dict(
  132. total=self.total,
  133. connect=self.connect, read=self.read, redirect=self.redirect, status=self.status,
  134. method_whitelist=self.method_whitelist,
  135. status_forcelist=self.status_forcelist,
  136. backoff_factor=self.backoff_factor,
  137. raise_on_redirect=self.raise_on_redirect,
  138. raise_on_status=self.raise_on_status,
  139. history=self.history,
  140. remove_headers_on_redirect=self.remove_headers_on_redirect
  141. )
  142. params.update(kw)
  143. return type(self)(**params)
  144. @classmethod
  145. def from_int(cls, retries, redirect=True, default=None):
  146. """ Backwards-compatibility for the old retries format."""
  147. if retries is None:
  148. retries = default if default is not None else cls.DEFAULT
  149. if isinstance(retries, Retry):
  150. return retries
  151. redirect = bool(redirect) and None
  152. new_retries = cls(retries, redirect=redirect)
  153. log.debug("Converted retries value: %r -> %r", retries, new_retries)
  154. return new_retries
  155. def get_backoff_time(self):
  156. """ Formula for computing the current backoff
  157. :rtype: float
  158. """
  159. # We want to consider only the last consecutive errors sequence (Ignore redirects).
  160. consecutive_errors_len = len(list(takewhile(lambda x: x.redirect_location is None,
  161. reversed(self.history))))
  162. if consecutive_errors_len <= 1:
  163. return 0
  164. backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))
  165. return min(self.BACKOFF_MAX, backoff_value)
  166. def parse_retry_after(self, retry_after):
  167. # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4
  168. if re.match(r"^\s*[0-9]+\s*$", retry_after):
  169. seconds = int(retry_after)
  170. else:
  171. retry_date_tuple = email.utils.parsedate(retry_after)
  172. if retry_date_tuple is None:
  173. raise InvalidHeader("Invalid Retry-After header: %s" % retry_after)
  174. retry_date = time.mktime(retry_date_tuple)
  175. seconds = retry_date - time.time()
  176. if seconds < 0:
  177. seconds = 0
  178. return seconds
  179. def get_retry_after(self, response):
  180. """ Get the value of Retry-After in seconds. """
  181. retry_after = response.getheader("Retry-After")
  182. if retry_after is None:
  183. return None
  184. return self.parse_retry_after(retry_after)
  185. def sleep_for_retry(self, response=None):
  186. retry_after = self.get_retry_after(response)
  187. if retry_after:
  188. time.sleep(retry_after)
  189. return True
  190. return False
  191. def _sleep_backoff(self):
  192. backoff = self.get_backoff_time()
  193. if backoff <= 0:
  194. return
  195. time.sleep(backoff)
  196. def sleep(self, response=None):
  197. """ Sleep between retry attempts.
  198. This method will respect a server's ``Retry-After`` response header
  199. and sleep the duration of the time requested. If that is not present, it
  200. will use an exponential backoff. By default, the backoff factor is 0 and
  201. this method will return immediately.
  202. """
  203. if response:
  204. slept = self.sleep_for_retry(response)
  205. if slept:
  206. return
  207. self._sleep_backoff()
  208. def _is_connection_error(self, err):
  209. """ Errors when we're fairly sure that the server did not receive the
  210. request, so it should be safe to retry.
  211. """
  212. return isinstance(err, ConnectTimeoutError)
  213. def _is_read_error(self, err):
  214. """ Errors that occur after the request has been started, so we should
  215. assume that the server began processing it.
  216. """
  217. return isinstance(err, (ReadTimeoutError, ProtocolError))
  218. def _is_method_retryable(self, method):
  219. """ Checks if a given HTTP method should be retried upon, depending if
  220. it is included on the method whitelist.
  221. """
  222. if self.method_whitelist and method.upper() not in self.method_whitelist:
  223. return False
  224. return True
  225. def is_retry(self, method, status_code, has_retry_after=False):
  226. """ Is this method/status code retryable? (Based on whitelists and control
  227. variables such as the number of total retries to allow, whether to
  228. respect the Retry-After header, whether this header is present, and
  229. whether the returned status code is on the list of status codes to
  230. be retried upon on the presence of the aforementioned header)
  231. """
  232. if not self._is_method_retryable(method):
  233. return False
  234. if self.status_forcelist and status_code in self.status_forcelist:
  235. return True
  236. return (self.total and self.respect_retry_after_header and
  237. has_retry_after and (status_code in self.RETRY_AFTER_STATUS_CODES))
  238. def is_exhausted(self):
  239. """ Are we out of retries? """
  240. retry_counts = (self.total, self.connect, self.read, self.redirect, self.status)
  241. retry_counts = list(filter(None, retry_counts))
  242. if not retry_counts:
  243. return False
  244. return min(retry_counts) < 0
  245. def increment(self, method=None, url=None, response=None, error=None,
  246. _pool=None, _stacktrace=None):
  247. """ Return a new Retry object with incremented retry counters.
  248. :param response: A response object, or None, if the server did not
  249. return a response.
  250. :type response: :class:`~urllib3.response.HTTPResponse`
  251. :param Exception error: An error encountered during the request, or
  252. None if the response was received successfully.
  253. :return: A new ``Retry`` object.
  254. """
  255. if self.total is False and error:
  256. # Disabled, indicate to re-raise the error.
  257. raise six.reraise(type(error), error, _stacktrace)
  258. total = self.total
  259. if total is not None:
  260. total -= 1
  261. connect = self.connect
  262. read = self.read
  263. redirect = self.redirect
  264. status_count = self.status
  265. cause = 'unknown'
  266. status = None
  267. redirect_location = None
  268. if error and self._is_connection_error(error):
  269. # Connect retry?
  270. if connect is False:
  271. raise six.reraise(type(error), error, _stacktrace)
  272. elif connect is not None:
  273. connect -= 1
  274. elif error and self._is_read_error(error):
  275. # Read retry?
  276. if read is False or not self._is_method_retryable(method):
  277. raise six.reraise(type(error), error, _stacktrace)
  278. elif read is not None:
  279. read -= 1
  280. elif response and response.get_redirect_location():
  281. # Redirect retry?
  282. if redirect is not None:
  283. redirect -= 1
  284. cause = 'too many redirects'
  285. redirect_location = response.get_redirect_location()
  286. status = response.status
  287. else:
  288. # Incrementing because of a server error like a 500 in
  289. # status_forcelist and a the given method is in the whitelist
  290. cause = ResponseError.GENERIC_ERROR
  291. if response and response.status:
  292. if status_count is not None:
  293. status_count -= 1
  294. cause = ResponseError.SPECIFIC_ERROR.format(
  295. status_code=response.status)
  296. status = response.status
  297. history = self.history + (RequestHistory(method, url, error, status, redirect_location),)
  298. new_retry = self.new(
  299. total=total,
  300. connect=connect, read=read, redirect=redirect, status=status_count,
  301. history=history)
  302. if new_retry.is_exhausted():
  303. raise MaxRetryError(_pool, url, error or ResponseError(cause))
  304. log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)
  305. return new_retry
  306. def __repr__(self):
  307. return ('{cls.__name__}(total={self.total}, connect={self.connect}, '
  308. 'read={self.read}, redirect={self.redirect}, status={self.status})').format(
  309. cls=type(self), self=self)
  310. # For backwards compatibility (equivalent to pre-v1.9):
  311. Retry.DEFAULT = Retry(3)