retry.py 14 KB

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