timeout.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. # Copyright (c) 2009-2010 Denis Bilenko. See LICENSE for details.
  2. """
  3. Timeouts.
  4. Many functions in :mod:`gevent` have a *timeout* argument that allows
  5. limiting the time the function will block. When that is not available,
  6. the :class:`Timeout` class and :func:`with_timeout` function in this
  7. module add timeouts to arbitrary code.
  8. .. warning::
  9. Timeouts can only work when the greenlet switches to the hub.
  10. If a blocking function is called or an intense calculation is ongoing during
  11. which no switches occur, :class:`Timeout` is powerless.
  12. """
  13. from gevent._compat import string_types
  14. from gevent.hub import getcurrent, _NONE, get_hub
  15. __all__ = ['Timeout',
  16. 'with_timeout']
  17. class _FakeTimer(object):
  18. # An object that mimics the API of get_hub().loop.timer, but
  19. # without allocating any native resources. This is useful for timeouts
  20. # that will never expire.
  21. # Also partially mimics the API of Timeout itself for use in _start_new_or_dummy
  22. pending = False
  23. active = False
  24. def start(self, *args, **kwargs):
  25. # pylint:disable=unused-argument
  26. raise AssertionError("non-expiring timer cannot be started")
  27. def stop(self):
  28. return
  29. def cancel(self):
  30. return
  31. _FakeTimer = _FakeTimer()
  32. class Timeout(BaseException):
  33. """
  34. Raise *exception* in the current greenlet after given time period::
  35. timeout = Timeout(seconds, exception)
  36. timeout.start()
  37. try:
  38. ... # exception will be raised here, after *seconds* passed since start() call
  39. finally:
  40. timeout.cancel()
  41. .. note:: If the code that the timeout was protecting finishes
  42. executing before the timeout elapses, be sure to ``cancel`` the
  43. timeout so it is not unexpectedly raised in the future. Even if
  44. it is raised, it is a best practice to cancel it. This
  45. ``try/finally`` construct or a ``with`` statement is a
  46. recommended pattern.
  47. When *exception* is omitted or ``None``, the :class:`Timeout` instance itself is raised:
  48. >>> import gevent
  49. >>> gevent.Timeout(0.1).start()
  50. >>> gevent.sleep(0.2) #doctest: +IGNORE_EXCEPTION_DETAIL
  51. Traceback (most recent call last):
  52. ...
  53. Timeout: 0.1 seconds
  54. To simplify starting and canceling timeouts, the ``with`` statement can be used::
  55. with gevent.Timeout(seconds, exception) as timeout:
  56. pass # ... code block ...
  57. This is equivalent to the try/finally block above with one additional feature:
  58. if *exception* is the literal ``False``, the timeout is still raised, but the context manager
  59. suppresses it, so the code outside the with-block won't see it.
  60. This is handy for adding a timeout to the functions that don't
  61. support a *timeout* parameter themselves::
  62. data = None
  63. with gevent.Timeout(5, False):
  64. data = mysock.makefile().readline()
  65. if data is None:
  66. ... # 5 seconds passed without reading a line
  67. else:
  68. ... # a line was read within 5 seconds
  69. .. caution:: If ``readline()`` above catches and doesn't re-raise :class:`BaseException`
  70. (for example, with a bare ``except:``), then your timeout will fail to function and control
  71. won't be returned to you when you expect.
  72. When catching timeouts, keep in mind that the one you catch may
  73. not be the one you have set (a calling function may have set its
  74. own timeout); if you going to silence a timeout, always check that
  75. it's the instance you need::
  76. timeout = Timeout(1)
  77. timeout.start()
  78. try:
  79. ...
  80. except Timeout as t:
  81. if t is not timeout:
  82. raise # not my timeout
  83. If the *seconds* argument is not given or is ``None`` (e.g.,
  84. ``Timeout()``), then the timeout will never expire and never raise
  85. *exception*. This is convenient for creating functions which take
  86. an optional timeout parameter of their own. (Note that this is not the same thing
  87. as a *seconds* value of 0.)
  88. .. caution::
  89. A *seconds* value less than 0.0 (e.g., -1) is poorly defined. In the future,
  90. support for negative values is likely to do the same thing as a value
  91. if ``None``.
  92. .. versionchanged:: 1.1b2
  93. If *seconds* is not given or is ``None``, no longer allocate a libev
  94. timer that will never be started.
  95. .. versionchanged:: 1.1
  96. Add warning about negative *seconds* values.
  97. """
  98. def __init__(self, seconds=None, exception=None, ref=True, priority=-1, _use_timer=True):
  99. BaseException.__init__(self)
  100. self.seconds = seconds
  101. self.exception = exception
  102. if seconds is None or not _use_timer:
  103. # Avoid going through the timer codepath if no timeout is
  104. # desired; this avoids some CFFI interactions on PyPy that can lead to a
  105. # RuntimeError if this implementation is used during an `import` statement. See
  106. # https://bitbucket.org/pypy/pypy/issues/2089/crash-in-pypy-260-linux64-with-gevent-11b1
  107. # and https://github.com/gevent/gevent/issues/618.
  108. # Plus, in general, it should be more efficient
  109. self.timer = _FakeTimer
  110. else:
  111. self.timer = get_hub().loop.timer(seconds or 0.0, ref=ref, priority=priority)
  112. def start(self):
  113. """Schedule the timeout."""
  114. assert not self.pending, '%r is already started; to restart it, cancel it first' % self
  115. if self.seconds is None: # "fake" timeout (never expires)
  116. return
  117. if self.exception is None or self.exception is False or isinstance(self.exception, string_types):
  118. # timeout that raises self
  119. self.timer.start(getcurrent().throw, self)
  120. else: # regular timeout with user-provided exception
  121. self.timer.start(getcurrent().throw, self.exception)
  122. @classmethod
  123. def start_new(cls, timeout=None, exception=None, ref=True):
  124. """Create a started :class:`Timeout`.
  125. This is a shortcut, the exact action depends on *timeout*'s type:
  126. * If *timeout* is a :class:`Timeout`, then call its :meth:`start` method
  127. if it's not already begun.
  128. * Otherwise, create a new :class:`Timeout` instance, passing (*timeout*, *exception*) as
  129. arguments, then call its :meth:`start` method.
  130. Returns the :class:`Timeout` instance.
  131. """
  132. if isinstance(timeout, Timeout):
  133. if not timeout.pending:
  134. timeout.start()
  135. return timeout
  136. timeout = cls(timeout, exception, ref=ref)
  137. timeout.start()
  138. return timeout
  139. @staticmethod
  140. def _start_new_or_dummy(timeout, exception=None):
  141. # Internal use only in 1.1
  142. # Return an object with a 'cancel' method; if timeout is None,
  143. # this will be a shared instance object that does nothing. Otherwise,
  144. # return an actual Timeout. Because negative values are hard to reason about,
  145. # and are often used as sentinels in Python APIs, in the future it's likely
  146. # that a negative timeout will also return the shared instance.
  147. # This saves the previously common idiom of 'timer = Timeout.start_new(t) if t is not None else None'
  148. # followed by 'if timer is not None: timer.cancel()'.
  149. # That idiom was used to avoid any object allocations.
  150. # A staticmethod is slightly faster under CPython, compared to a classmethod;
  151. # under PyPy in synthetic benchmarks it makes no difference.
  152. if timeout is None:
  153. return _FakeTimer
  154. return Timeout.start_new(timeout, exception)
  155. @property
  156. def pending(self):
  157. """Return True if the timeout is scheduled to be raised."""
  158. return self.timer.pending or self.timer.active
  159. def cancel(self):
  160. """If the timeout is pending, cancel it. Otherwise, do nothing."""
  161. self.timer.stop()
  162. def __repr__(self):
  163. classname = type(self).__name__
  164. if self.pending:
  165. pending = ' pending'
  166. else:
  167. pending = ''
  168. if self.exception is None:
  169. exception = ''
  170. else:
  171. exception = ' exception=%r' % self.exception
  172. return '<%s at %s seconds=%s%s%s>' % (classname, hex(id(self)), self.seconds, exception, pending)
  173. def __str__(self):
  174. """
  175. >>> raise Timeout #doctest: +IGNORE_EXCEPTION_DETAIL
  176. Traceback (most recent call last):
  177. ...
  178. Timeout
  179. """
  180. if self.seconds is None:
  181. return ''
  182. suffix = '' if self.seconds == 1 else 's'
  183. if self.exception is None:
  184. return '%s second%s' % (self.seconds, suffix)
  185. if self.exception is False:
  186. return '%s second%s (silent)' % (self.seconds, suffix)
  187. return '%s second%s: %s' % (self.seconds, suffix, self.exception)
  188. def __enter__(self):
  189. if not self.pending:
  190. self.start()
  191. return self
  192. def __exit__(self, typ, value, tb):
  193. self.cancel()
  194. if value is self and self.exception is False:
  195. return True
  196. def with_timeout(seconds, function, *args, **kwds):
  197. """Wrap a call to *function* with a timeout; if the called
  198. function fails to return before the timeout, cancel it and return a
  199. flag value, provided by *timeout_value* keyword argument.
  200. If timeout expires but *timeout_value* is not provided, raise :class:`Timeout`.
  201. Keyword argument *timeout_value* is not passed to *function*.
  202. """
  203. timeout_value = kwds.pop("timeout_value", _NONE)
  204. timeout = Timeout.start_new(seconds)
  205. try:
  206. try:
  207. return function(*args, **kwds)
  208. except Timeout as ex:
  209. if ex is timeout and timeout_value is not _NONE:
  210. return timeout_value
  211. raise
  212. finally:
  213. timeout.cancel()