Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

retry.py 15KB

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