retry.py 15 KB

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