retry.py 21 KB

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