retry.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. from __future__ import absolute_import
  2. import email
  3. import logging
  4. import re
  5. import time
  6. import warnings
  7. from collections import namedtuple
  8. from itertools import takewhile
  9. from ..exceptions import (
  10. ConnectTimeoutError,
  11. InvalidHeader,
  12. MaxRetryError,
  13. ProtocolError,
  14. ProxyError,
  15. ReadTimeoutError,
  16. ResponseError,
  17. )
  18. from ..packages import six
  19. log = logging.getLogger(__name__)
  20. # Data structure for representing the metadata of requests that result in a retry.
  21. RequestHistory = namedtuple(
  22. "RequestHistory", ["method", "url", "error", "status", "redirect_location"]
  23. )
  24. # TODO: In v2 we can remove this sentinel and metaclass with deprecated options.
  25. _Default = object()
  26. class _RetryMeta(type):
  27. @property
  28. def DEFAULT_METHOD_WHITELIST(cls):
  29. warnings.warn(
  30. "Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and "
  31. "will be removed in v2.0. Use 'Retry.DEFAULT_METHODS_ALLOWED' instead",
  32. DeprecationWarning,
  33. )
  34. return cls.DEFAULT_ALLOWED_METHODS
  35. @DEFAULT_METHOD_WHITELIST.setter
  36. def DEFAULT_METHOD_WHITELIST(cls, value):
  37. warnings.warn(
  38. "Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and "
  39. "will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead",
  40. DeprecationWarning,
  41. )
  42. cls.DEFAULT_ALLOWED_METHODS = value
  43. @property
  44. def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls):
  45. warnings.warn(
  46. "Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and "
  47. "will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead",
  48. DeprecationWarning,
  49. )
  50. return cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT
  51. @DEFAULT_REDIRECT_HEADERS_BLACKLIST.setter
  52. def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls, value):
  53. warnings.warn(
  54. "Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and "
  55. "will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead",
  56. DeprecationWarning,
  57. )
  58. cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT = value
  59. @six.add_metaclass(_RetryMeta)
  60. class Retry(object):
  61. """Retry configuration.
  62. Each retry attempt will create a new Retry object with updated values, so
  63. they can be safely reused.
  64. Retries can be defined as a default for a pool::
  65. retries = Retry(connect=5, read=2, redirect=5)
  66. http = PoolManager(retries=retries)
  67. response = http.request('GET', 'http://example.com/')
  68. Or per-request (which overrides the default for the pool)::
  69. response = http.request('GET', 'http://example.com/', retries=Retry(10))
  70. Retries can be disabled by passing ``False``::
  71. response = http.request('GET', 'http://example.com/', retries=False)
  72. Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless
  73. retries are disabled, in which case the causing exception will be raised.
  74. :param int total:
  75. Total number of retries to allow. Takes precedence over other counts.
  76. Set to ``None`` to remove this constraint and fall back on other
  77. counts.
  78. Set to ``0`` to fail on the first retry.
  79. Set to ``False`` to disable and imply ``raise_on_redirect=False``.
  80. :param int connect:
  81. How many connection-related errors to retry on.
  82. These are errors raised before the request is sent to the remote server,
  83. which we assume has not triggered the server to process the request.
  84. Set to ``0`` to fail on the first retry of this type.
  85. :param int read:
  86. How many times to retry on read errors.
  87. These errors are raised after the request was sent to the server, so the
  88. request may have side-effects.
  89. Set to ``0`` to fail on the first retry of this type.
  90. :param int redirect:
  91. How many redirects to perform. Limit this to avoid infinite redirect
  92. loops.
  93. A redirect is a HTTP response with a status code 301, 302, 303, 307 or
  94. 308.
  95. Set to ``0`` to fail on the first retry of this type.
  96. Set to ``False`` to disable and imply ``raise_on_redirect=False``.
  97. :param int status:
  98. How many times to retry on bad status codes.
  99. These are retries made on responses, where status code matches
  100. ``status_forcelist``.
  101. Set to ``0`` to fail on the first retry of this type.
  102. :param int other:
  103. How many times to retry on other errors.
  104. Other errors are errors that are not connect, read, redirect or status errors.
  105. These errors might be raised after the request was sent to the server, so the
  106. request might have side-effects.
  107. Set to ``0`` to fail on the first retry of this type.
  108. If ``total`` is not set, it's a good idea to set this to 0 to account
  109. for unexpected edge cases and avoid infinite retry loops.
  110. :param iterable allowed_methods:
  111. Set of uppercased HTTP method verbs that we should retry on.
  112. By default, we only retry on methods which are considered to be
  113. idempotent (multiple requests with the same parameters end with the
  114. same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`.
  115. Set to a ``False`` value to retry on any verb.
  116. .. warning::
  117. Previously this parameter was named ``method_whitelist``, that
  118. usage is deprecated in v1.26.0 and will be removed in v2.0.
  119. :param iterable status_forcelist:
  120. A set of integer HTTP status codes that we should force a retry on.
  121. A retry is initiated if the request method is in ``allowed_methods``
  122. and the response status code is in ``status_forcelist``.
  123. By default, this is disabled with ``None``.
  124. :param float backoff_factor:
  125. A backoff factor to apply between attempts after the second try
  126. (most errors are resolved immediately by a second try without a
  127. delay). urllib3 will sleep for::
  128. {backoff factor} * (2 ** ({number of total retries} - 1))
  129. seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep
  130. for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer
  131. than :attr:`Retry.BACKOFF_MAX`.
  132. By default, backoff is disabled (set to 0).
  133. :param bool raise_on_redirect: Whether, if the number of redirects is
  134. exhausted, to raise a MaxRetryError, or to return a response with a
  135. response code in the 3xx range.
  136. :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:
  137. whether we should raise an exception, or return a response,
  138. if status falls in ``status_forcelist`` range and retries have
  139. been exhausted.
  140. :param tuple history: The history of the request encountered during
  141. each call to :meth:`~Retry.increment`. The list is in the order
  142. the requests occurred. Each list item is of class :class:`RequestHistory`.
  143. :param bool respect_retry_after_header:
  144. Whether to respect Retry-After header on status codes defined as
  145. :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.
  146. :param iterable remove_headers_on_redirect:
  147. Sequence of headers to remove from the request when a response
  148. indicating a redirect is returned before firing off the redirected
  149. request.
  150. """
  151. #: Default methods to be used for ``allowed_methods``
  152. DEFAULT_ALLOWED_METHODS = frozenset(
  153. ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"]
  154. )
  155. #: Default status codes to be used for ``status_forcelist``
  156. RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])
  157. #: Default headers to be used for ``remove_headers_on_redirect``
  158. DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset(["Authorization"])
  159. #: Maximum backoff time.
  160. BACKOFF_MAX = 120
  161. def __init__(
  162. self,
  163. total=10,
  164. connect=None,
  165. read=None,
  166. redirect=None,
  167. status=None,
  168. other=None,
  169. allowed_methods=_Default,
  170. status_forcelist=None,
  171. backoff_factor=0,
  172. raise_on_redirect=True,
  173. raise_on_status=True,
  174. history=None,
  175. respect_retry_after_header=True,
  176. remove_headers_on_redirect=_Default,
  177. # TODO: Deprecated, remove in v2.0
  178. method_whitelist=_Default,
  179. ):
  180. if method_whitelist is not _Default:
  181. if allowed_methods is not _Default:
  182. raise ValueError(
  183. "Using both 'allowed_methods' and "
  184. "'method_whitelist' together is not allowed. "
  185. "Instead only use 'allowed_methods'"
  186. )
  187. warnings.warn(
  188. "Using 'method_whitelist' with Retry is deprecated and "
  189. "will be removed in v2.0. Use 'allowed_methods' instead",
  190. DeprecationWarning,
  191. stacklevel=2,
  192. )
  193. allowed_methods = method_whitelist
  194. if allowed_methods is _Default:
  195. allowed_methods = self.DEFAULT_ALLOWED_METHODS
  196. if remove_headers_on_redirect is _Default:
  197. remove_headers_on_redirect = self.DEFAULT_REMOVE_HEADERS_ON_REDIRECT
  198. self.total = total
  199. self.connect = connect
  200. self.read = read
  201. self.status = status
  202. self.other = other
  203. if redirect is False or total is False:
  204. redirect = 0
  205. raise_on_redirect = False
  206. self.redirect = redirect
  207. self.status_forcelist = status_forcelist or set()
  208. self.allowed_methods = allowed_methods
  209. self.backoff_factor = backoff_factor
  210. self.raise_on_redirect = raise_on_redirect
  211. self.raise_on_status = raise_on_status
  212. self.history = history or tuple()
  213. self.respect_retry_after_header = respect_retry_after_header
  214. self.remove_headers_on_redirect = frozenset(
  215. [h.lower() for h in remove_headers_on_redirect]
  216. )
  217. def new(self, **kw):
  218. params = dict(
  219. total=self.total,
  220. connect=self.connect,
  221. read=self.read,
  222. redirect=self.redirect,
  223. status=self.status,
  224. other=self.other,
  225. status_forcelist=self.status_forcelist,
  226. backoff_factor=self.backoff_factor,
  227. raise_on_redirect=self.raise_on_redirect,
  228. raise_on_status=self.raise_on_status,
  229. history=self.history,
  230. remove_headers_on_redirect=self.remove_headers_on_redirect,
  231. respect_retry_after_header=self.respect_retry_after_header,
  232. )
  233. # TODO: If already given in **kw we use what's given to us
  234. # If not given we need to figure out what to pass. We decide
  235. # based on whether our class has the 'method_whitelist' property
  236. # and if so we pass the deprecated 'method_whitelist' otherwise
  237. # we use 'allowed_methods'. Remove in v2.0
  238. if "method_whitelist" not in kw and "allowed_methods" not in kw:
  239. if "method_whitelist" in self.__dict__:
  240. warnings.warn(
  241. "Using 'method_whitelist' with Retry is deprecated and "
  242. "will be removed in v2.0. Use 'allowed_methods' instead",
  243. DeprecationWarning,
  244. )
  245. params["method_whitelist"] = self.allowed_methods
  246. else:
  247. params["allowed_methods"] = self.allowed_methods
  248. params.update(kw)
  249. return type(self)(**params)
  250. @classmethod
  251. def from_int(cls, retries, redirect=True, default=None):
  252. """ Backwards-compatibility for the old retries format."""
  253. if retries is None:
  254. retries = default if default is not None else cls.DEFAULT
  255. if isinstance(retries, Retry):
  256. return retries
  257. redirect = bool(redirect) and None
  258. new_retries = cls(retries, redirect=redirect)
  259. log.debug("Converted retries value: %r -> %r", retries, new_retries)
  260. return new_retries
  261. def get_backoff_time(self):
  262. """Formula for computing the current backoff
  263. :rtype: float
  264. """
  265. # We want to consider only the last consecutive errors sequence (Ignore redirects).
  266. consecutive_errors_len = len(
  267. list(
  268. takewhile(lambda x: x.redirect_location is None, reversed(self.history))
  269. )
  270. )
  271. if consecutive_errors_len <= 1:
  272. return 0
  273. backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))
  274. return min(self.BACKOFF_MAX, backoff_value)
  275. def parse_retry_after(self, retry_after):
  276. # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4
  277. if re.match(r"^\s*[0-9]+\s*$", retry_after):
  278. seconds = int(retry_after)
  279. else:
  280. retry_date_tuple = email.utils.parsedate_tz(retry_after)
  281. if retry_date_tuple is None:
  282. raise InvalidHeader("Invalid Retry-After header: %s" % retry_after)
  283. if retry_date_tuple[9] is None: # Python 2
  284. # Assume UTC if no timezone was specified
  285. # On Python2.7, parsedate_tz returns None for a timezone offset
  286. # instead of 0 if no timezone is given, where mktime_tz treats
  287. # a None timezone offset as local time.
  288. retry_date_tuple = retry_date_tuple[:9] + (0,) + retry_date_tuple[10:]
  289. retry_date = email.utils.mktime_tz(retry_date_tuple)
  290. seconds = retry_date - time.time()
  291. if seconds < 0:
  292. seconds = 0
  293. return seconds
  294. def get_retry_after(self, response):
  295. """ Get the value of Retry-After in seconds. """
  296. retry_after = response.getheader("Retry-After")
  297. if retry_after is None:
  298. return None
  299. return self.parse_retry_after(retry_after)
  300. def sleep_for_retry(self, response=None):
  301. retry_after = self.get_retry_after(response)
  302. if retry_after:
  303. time.sleep(retry_after)
  304. return True
  305. return False
  306. def _sleep_backoff(self):
  307. backoff = self.get_backoff_time()
  308. if backoff <= 0:
  309. return
  310. time.sleep(backoff)
  311. def sleep(self, response=None):
  312. """Sleep between retry attempts.
  313. This method will respect a server's ``Retry-After`` response header
  314. and sleep the duration of the time requested. If that is not present, it
  315. will use an exponential backoff. By default, the backoff factor is 0 and
  316. this method will return immediately.
  317. """
  318. if self.respect_retry_after_header and response:
  319. slept = self.sleep_for_retry(response)
  320. if slept:
  321. return
  322. self._sleep_backoff()
  323. def _is_connection_error(self, err):
  324. """Errors when we're fairly sure that the server did not receive the
  325. request, so it should be safe to retry.
  326. """
  327. if isinstance(err, ProxyError):
  328. err = err.original_error
  329. return isinstance(err, ConnectTimeoutError)
  330. def _is_read_error(self, err):
  331. """Errors that occur after the request has been started, so we should
  332. assume that the server began processing it.
  333. """
  334. return isinstance(err, (ReadTimeoutError, ProtocolError))
  335. def _is_method_retryable(self, method):
  336. """Checks if a given HTTP method should be retried upon, depending if
  337. it is included in the allowed_methods
  338. """
  339. # TODO: For now favor if the Retry implementation sets its own method_whitelist
  340. # property outside of our constructor to avoid breaking custom implementations.
  341. if "method_whitelist" in self.__dict__:
  342. warnings.warn(
  343. "Using 'method_whitelist' with Retry is deprecated and "
  344. "will be removed in v2.0. Use 'allowed_methods' instead",
  345. DeprecationWarning,
  346. )
  347. allowed_methods = self.method_whitelist
  348. else:
  349. allowed_methods = self.allowed_methods
  350. if allowed_methods and method.upper() not in allowed_methods:
  351. return False
  352. return True
  353. def is_retry(self, method, status_code, has_retry_after=False):
  354. """Is this method/status code retryable? (Based on allowlists and control
  355. variables such as the number of total retries to allow, whether to
  356. respect the Retry-After header, whether this header is present, and
  357. whether the returned status code is on the list of status codes to
  358. be retried upon on the presence of the aforementioned header)
  359. """
  360. if not self._is_method_retryable(method):
  361. return False
  362. if self.status_forcelist and status_code in self.status_forcelist:
  363. return True
  364. return (
  365. self.total
  366. and self.respect_retry_after_header
  367. and has_retry_after
  368. and (status_code in self.RETRY_AFTER_STATUS_CODES)
  369. )
  370. def is_exhausted(self):
  371. """ Are we out of retries? """
  372. retry_counts = (
  373. self.total,
  374. self.connect,
  375. self.read,
  376. self.redirect,
  377. self.status,
  378. self.other,
  379. )
  380. retry_counts = list(filter(None, retry_counts))
  381. if not retry_counts:
  382. return False
  383. return min(retry_counts) < 0
  384. def increment(
  385. self,
  386. method=None,
  387. url=None,
  388. response=None,
  389. error=None,
  390. _pool=None,
  391. _stacktrace=None,
  392. ):
  393. """Return a new Retry object with incremented retry counters.
  394. :param response: A response object, or None, if the server did not
  395. return a response.
  396. :type response: :class:`~urllib3.response.HTTPResponse`
  397. :param Exception error: An error encountered during the request, or
  398. None if the response was received successfully.
  399. :return: A new ``Retry`` object.
  400. """
  401. if self.total is False and error:
  402. # Disabled, indicate to re-raise the error.
  403. raise six.reraise(type(error), error, _stacktrace)
  404. total = self.total
  405. if total is not None:
  406. total -= 1
  407. connect = self.connect
  408. read = self.read
  409. redirect = self.redirect
  410. status_count = self.status
  411. other = self.other
  412. cause = "unknown"
  413. status = None
  414. redirect_location = None
  415. if error and self._is_connection_error(error):
  416. # Connect retry?
  417. if connect is False:
  418. raise six.reraise(type(error), error, _stacktrace)
  419. elif connect is not None:
  420. connect -= 1
  421. elif error and self._is_read_error(error):
  422. # Read retry?
  423. if read is False or not self._is_method_retryable(method):
  424. raise six.reraise(type(error), error, _stacktrace)
  425. elif read is not None:
  426. read -= 1
  427. elif error:
  428. # Other retry?
  429. if other is not None:
  430. other -= 1
  431. elif response and response.get_redirect_location():
  432. # Redirect retry?
  433. if redirect is not None:
  434. redirect -= 1
  435. cause = "too many redirects"
  436. redirect_location = response.get_redirect_location()
  437. status = response.status
  438. else:
  439. # Incrementing because of a server error like a 500 in
  440. # status_forcelist and the given method is in the allowed_methods
  441. cause = ResponseError.GENERIC_ERROR
  442. if response and response.status:
  443. if status_count is not None:
  444. status_count -= 1
  445. cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)
  446. status = response.status
  447. history = self.history + (
  448. RequestHistory(method, url, error, status, redirect_location),
  449. )
  450. new_retry = self.new(
  451. total=total,
  452. connect=connect,
  453. read=read,
  454. redirect=redirect,
  455. status=status_count,
  456. other=other,
  457. history=history,
  458. )
  459. if new_retry.is_exhausted():
  460. raise MaxRetryError(_pool, url, error or ResponseError(cause))
  461. log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)
  462. return new_retry
  463. def __repr__(self):
  464. return (
  465. "{cls.__name__}(total={self.total}, connect={self.connect}, "
  466. "read={self.read}, redirect={self.redirect}, status={self.status})"
  467. ).format(cls=type(self), self=self)
  468. def __getattr__(self, item):
  469. if item == "method_whitelist":
  470. # TODO: Remove this deprecated alias in v2.0
  471. warnings.warn(
  472. "Using 'method_whitelist' with Retry is deprecated and "
  473. "will be removed in v2.0. Use 'allowed_methods' instead",
  474. DeprecationWarning,
  475. )
  476. return self.allowed_methods
  477. try:
  478. return getattr(super(Retry, self), item)
  479. except AttributeError:
  480. return getattr(Retry, item)
  481. # For backwards compatibility (equivalent to pre-v1.9):
  482. Retry.DEFAULT = Retry(3)