retry.py 15 KB

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