timeout.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. from __future__ import absolute_import
  2. import time
  3. # The default socket timeout, used by httplib to indicate that no timeout was
  4. # specified by the user
  5. from socket import _GLOBAL_DEFAULT_TIMEOUT
  6. from ..exceptions import TimeoutStateError
  7. # A sentinel value to indicate that no timeout was specified by the user in
  8. # urllib3
  9. _Default = object()
  10. # Use time.monotonic if available.
  11. current_time = getattr(time, "monotonic", time.time)
  12. class Timeout(object):
  13. """Timeout configuration.
  14. Timeouts can be defined as a default for a pool:
  15. .. code-block:: python
  16. timeout = Timeout(connect=2.0, read=7.0)
  17. http = PoolManager(timeout=timeout)
  18. response = http.request('GET', 'http://example.com/')
  19. Or per-request (which overrides the default for the pool):
  20. .. code-block:: python
  21. response = http.request('GET', 'http://example.com/', timeout=Timeout(10))
  22. Timeouts can be disabled by setting all the parameters to ``None``:
  23. .. code-block:: python
  24. no_timeout = Timeout(connect=None, read=None)
  25. response = http.request('GET', 'http://example.com/, timeout=no_timeout)
  26. :param total:
  27. This combines the connect and read timeouts into one; the read timeout
  28. will be set to the time leftover from the connect attempt. In the
  29. event that both a connect timeout and a total are specified, or a read
  30. timeout and a total are specified, the shorter timeout will be applied.
  31. Defaults to None.
  32. :type total: int, float, or None
  33. :param connect:
  34. The maximum amount of time (in seconds) to wait for a connection
  35. attempt to a server to succeed. Omitting the parameter will default the
  36. connect timeout to the system default, probably `the global default
  37. timeout in socket.py
  38. <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.
  39. None will set an infinite timeout for connection attempts.
  40. :type connect: int, float, or None
  41. :param read:
  42. The maximum amount of time (in seconds) to wait between consecutive
  43. read operations for a response from the server. Omitting the parameter
  44. will default the read timeout to the system default, probably `the
  45. global default timeout in socket.py
  46. <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.
  47. None will set an infinite timeout.
  48. :type read: int, float, or None
  49. .. note::
  50. Many factors can affect the total amount of time for urllib3 to return
  51. an HTTP response.
  52. For example, Python's DNS resolver does not obey the timeout specified
  53. on the socket. Other factors that can affect total request time include
  54. high CPU load, high swap, the program running at a low priority level,
  55. or other behaviors.
  56. In addition, the read and total timeouts only measure the time between
  57. read operations on the socket connecting the client and the server,
  58. not the total amount of time for the request to return a complete
  59. response. For most requests, the timeout is raised because the server
  60. has not sent the first byte in the specified time. This is not always
  61. the case; if a server streams one byte every fifteen seconds, a timeout
  62. of 20 seconds will not trigger, even though the request will take
  63. several minutes to complete.
  64. If your goal is to cut off any request after a set amount of wall clock
  65. time, consider having a second "watcher" thread to cut off a slow
  66. request.
  67. """
  68. #: A sentinel object representing the default timeout value
  69. DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT
  70. def __init__(self, total=None, connect=_Default, read=_Default):
  71. self._connect = self._validate_timeout(connect, "connect")
  72. self._read = self._validate_timeout(read, "read")
  73. self.total = self._validate_timeout(total, "total")
  74. self._start_connect = None
  75. def __repr__(self):
  76. return "%s(connect=%r, read=%r, total=%r)" % (
  77. type(self).__name__,
  78. self._connect,
  79. self._read,
  80. self.total,
  81. )
  82. # __str__ provided for backwards compatibility
  83. __str__ = __repr__
  84. @classmethod
  85. def _validate_timeout(cls, value, name):
  86. """Check that a timeout attribute is valid.
  87. :param value: The timeout value to validate
  88. :param name: The name of the timeout attribute to validate. This is
  89. used to specify in error messages.
  90. :return: The validated and casted version of the given value.
  91. :raises ValueError: If it is a numeric value less than or equal to
  92. zero, or the type is not an integer, float, or None.
  93. """
  94. if value is _Default:
  95. return cls.DEFAULT_TIMEOUT
  96. if value is None or value is cls.DEFAULT_TIMEOUT:
  97. return value
  98. if isinstance(value, bool):
  99. raise ValueError(
  100. "Timeout cannot be a boolean value. It must "
  101. "be an int, float or None."
  102. )
  103. try:
  104. float(value)
  105. except (TypeError, ValueError):
  106. raise ValueError(
  107. "Timeout value %s was %s, but it must be an "
  108. "int, float or None." % (name, value)
  109. )
  110. try:
  111. if value <= 0:
  112. raise ValueError(
  113. "Attempted to set %s timeout to %s, but the "
  114. "timeout cannot be set to a value less "
  115. "than or equal to 0." % (name, value)
  116. )
  117. except TypeError:
  118. # Python 3
  119. raise ValueError(
  120. "Timeout value %s was %s, but it must be an "
  121. "int, float or None." % (name, value)
  122. )
  123. return value
  124. @classmethod
  125. def from_float(cls, timeout):
  126. """Create a new Timeout from a legacy timeout value.
  127. The timeout value used by httplib.py sets the same timeout on the
  128. connect(), and recv() socket requests. This creates a :class:`Timeout`
  129. object that sets the individual timeouts to the ``timeout`` value
  130. passed to this function.
  131. :param timeout: The legacy timeout value.
  132. :type timeout: integer, float, sentinel default object, or None
  133. :return: Timeout object
  134. :rtype: :class:`Timeout`
  135. """
  136. return Timeout(read=timeout, connect=timeout)
  137. def clone(self):
  138. """Create a copy of the timeout object
  139. Timeout properties are stored per-pool but each request needs a fresh
  140. Timeout object to ensure each one has its own start/stop configured.
  141. :return: a copy of the timeout object
  142. :rtype: :class:`Timeout`
  143. """
  144. # We can't use copy.deepcopy because that will also create a new object
  145. # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to
  146. # detect the user default.
  147. return Timeout(connect=self._connect, read=self._read, total=self.total)
  148. def start_connect(self):
  149. """Start the timeout clock, used during a connect() attempt
  150. :raises urllib3.exceptions.TimeoutStateError: if you attempt
  151. to start a timer that has been started already.
  152. """
  153. if self._start_connect is not None:
  154. raise TimeoutStateError("Timeout timer has already been started.")
  155. self._start_connect = current_time()
  156. return self._start_connect
  157. def get_connect_duration(self):
  158. """Gets the time elapsed since the call to :meth:`start_connect`.
  159. :return: Elapsed time in seconds.
  160. :rtype: float
  161. :raises urllib3.exceptions.TimeoutStateError: if you attempt
  162. to get duration for a timer that hasn't been started.
  163. """
  164. if self._start_connect is None:
  165. raise TimeoutStateError(
  166. "Can't get connect duration for timer that has not started."
  167. )
  168. return current_time() - self._start_connect
  169. @property
  170. def connect_timeout(self):
  171. """Get the value to use when setting a connection timeout.
  172. This will be a positive float or integer, the value None
  173. (never timeout), or the default system timeout.
  174. :return: Connect timeout.
  175. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
  176. """
  177. if self.total is None:
  178. return self._connect
  179. if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:
  180. return self.total
  181. return min(self._connect, self.total)
  182. @property
  183. def read_timeout(self):
  184. """Get the value for the read timeout.
  185. This assumes some time has elapsed in the connection timeout and
  186. computes the read timeout appropriately.
  187. If self.total is set, the read timeout is dependent on the amount of
  188. time taken by the connect timeout. If the connection time has not been
  189. established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be
  190. raised.
  191. :return: Value to use for the read timeout.
  192. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
  193. :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`
  194. has not yet been called on this object.
  195. """
  196. if (
  197. self.total is not None
  198. and self.total is not self.DEFAULT_TIMEOUT
  199. and self._read is not None
  200. and self._read is not self.DEFAULT_TIMEOUT
  201. ):
  202. # In case the connect timeout has not yet been established.
  203. if self._start_connect is None:
  204. return self._read
  205. return max(0, min(self.total - self.get_connect_duration(), self._read))
  206. elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:
  207. return max(0, self.total - self.get_connect_duration())
  208. else:
  209. return self._read