timeout.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. # Copyright (c) 2009-2010 Denis Bilenko, denis.bilenko at gmail com
  2. # Copyright (c) 2010 Eventlet Contributors (see AUTHORS)
  3. # and licensed under the MIT license:
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. # THE SOFTWARE.
  22. import functools
  23. import inspect
  24. import eventlet
  25. from eventlet.support import greenlets as greenlet
  26. from eventlet.hubs import get_hub
  27. __all__ = ['Timeout', 'with_timeout', 'wrap_is_timeout', 'is_timeout']
  28. _MISSING = object()
  29. # deriving from BaseException so that "except Exception as e" doesn't catch
  30. # Timeout exceptions.
  31. class Timeout(BaseException):
  32. """Raises *exception* in the current greenthread after *timeout* seconds.
  33. When *exception* is omitted or ``None``, the :class:`Timeout` instance
  34. itself is raised. If *seconds* is None, the timer is not scheduled, and is
  35. only useful if you're planning to raise it directly.
  36. Timeout objects are context managers, and so can be used in with statements.
  37. When used in a with statement, if *exception* is ``False``, the timeout is
  38. still raised, but the context manager suppresses it, so the code outside the
  39. with-block won't see it.
  40. """
  41. def __init__(self, seconds=None, exception=None):
  42. self.seconds = seconds
  43. self.exception = exception
  44. self.timer = None
  45. self.start()
  46. def start(self):
  47. """Schedule the timeout. This is called on construction, so
  48. it should not be called explicitly, unless the timer has been
  49. canceled."""
  50. assert not self.pending, \
  51. '%r is already started; to restart it, cancel it first' % self
  52. if self.seconds is None: # "fake" timeout (never expires)
  53. self.timer = None
  54. elif self.exception is None or isinstance(self.exception, bool): # timeout that raises self
  55. self.timer = get_hub().schedule_call_global(
  56. self.seconds, greenlet.getcurrent().throw, self)
  57. else: # regular timeout with user-provided exception
  58. self.timer = get_hub().schedule_call_global(
  59. self.seconds, greenlet.getcurrent().throw, self.exception)
  60. return self
  61. @property
  62. def pending(self):
  63. """True if the timeout is scheduled to be raised."""
  64. if self.timer is not None:
  65. return self.timer.pending
  66. else:
  67. return False
  68. def cancel(self):
  69. """If the timeout is pending, cancel it. If not using
  70. Timeouts in ``with`` statements, always call cancel() in a
  71. ``finally`` after the block of code that is getting timed out.
  72. If not canceled, the timeout will be raised later on, in some
  73. unexpected section of the application."""
  74. if self.timer is not None:
  75. self.timer.cancel()
  76. self.timer = None
  77. def __repr__(self):
  78. classname = self.__class__.__name__
  79. if self.pending:
  80. pending = ' pending'
  81. else:
  82. pending = ''
  83. if self.exception is None:
  84. exception = ''
  85. else:
  86. exception = ' exception=%r' % self.exception
  87. return '<%s at %s seconds=%s%s%s>' % (
  88. classname, hex(id(self)), self.seconds, exception, pending)
  89. def __str__(self):
  90. """
  91. >>> raise Timeout # doctest: +IGNORE_EXCEPTION_DETAIL
  92. Traceback (most recent call last):
  93. ...
  94. Timeout
  95. """
  96. if self.seconds is None:
  97. return ''
  98. if self.seconds == 1:
  99. suffix = ''
  100. else:
  101. suffix = 's'
  102. if self.exception is None or self.exception is True:
  103. return '%s second%s' % (self.seconds, suffix)
  104. elif self.exception is False:
  105. return '%s second%s (silent)' % (self.seconds, suffix)
  106. else:
  107. return '%s second%s (%s)' % (self.seconds, suffix, self.exception)
  108. def __enter__(self):
  109. if self.timer is None:
  110. self.start()
  111. return self
  112. def __exit__(self, typ, value, tb):
  113. self.cancel()
  114. if value is self and self.exception is False:
  115. return True
  116. @property
  117. def is_timeout(self):
  118. return True
  119. def with_timeout(seconds, function, *args, **kwds):
  120. """Wrap a call to some (yielding) function with a timeout; if the called
  121. function fails to return before the timeout, cancel it and return a flag
  122. value.
  123. """
  124. timeout_value = kwds.pop("timeout_value", _MISSING)
  125. timeout = Timeout(seconds)
  126. try:
  127. try:
  128. return function(*args, **kwds)
  129. except Timeout as ex:
  130. if ex is timeout and timeout_value is not _MISSING:
  131. return timeout_value
  132. raise
  133. finally:
  134. timeout.cancel()
  135. def wrap_is_timeout(base):
  136. '''Adds `.is_timeout=True` attribute to objects returned by `base()`.
  137. When `base` is class, attribute is added as read-only property. Returns `base`.
  138. Otherwise, it returns a function that sets attribute on result of `base()` call.
  139. Wrappers make best effort to be transparent.
  140. '''
  141. if inspect.isclass(base):
  142. base.is_timeout = property(lambda _: True)
  143. return base
  144. @functools.wraps(base)
  145. def fun(*args, **kwargs):
  146. ex = base(*args, **kwargs)
  147. ex.is_timeout = True
  148. return ex
  149. return fun
  150. if isinstance(__builtins__, dict): # seen when running tests on py310, but HOW??
  151. _timeout_err = __builtins__.get('TimeoutError', Timeout)
  152. else:
  153. _timeout_err = getattr(__builtins__, 'TimeoutError', Timeout)
  154. def is_timeout(obj):
  155. return bool(getattr(obj, 'is_timeout', False)) or isinstance(obj, _timeout_err)