timeout.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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.from eventlet.support import greenlets as greenlet
  22. from eventlet.support import greenlets as greenlet, BaseException
  23. from eventlet.hubs import get_hub
  24. __all__ = ['Timeout',
  25. 'with_timeout']
  26. _NONE = object()
  27. # deriving from BaseException so that "except Exception, e" doesn't catch
  28. # Timeout exceptions.
  29. class Timeout(BaseException):
  30. """Raises *exception* in the current greenthread after *timeout* seconds.
  31. When *exception* is omitted or ``None``, the :class:`Timeout` instance
  32. itself is raised. If *seconds* is None, the timer is not scheduled, and is
  33. only useful if you're planning to raise it directly.
  34. Timeout objects are context managers, and so can be used in with statements.
  35. When used in a with statement, if *exception* is ``False``, the timeout is
  36. still raised, but the context manager suppresses it, so the code outside the
  37. with-block won't see it.
  38. """
  39. def __init__(self, seconds=None, exception=None):
  40. self.seconds = seconds
  41. self.exception = exception
  42. self.timer = None
  43. self.start()
  44. def start(self):
  45. """Schedule the timeout. This is called on construction, so
  46. it should not be called explicitly, unless the timer has been
  47. canceled."""
  48. assert not self.pending, \
  49. '%r is already started; to restart it, cancel it first' % self
  50. if self.seconds is None: # "fake" timeout (never expires)
  51. self.timer = None
  52. elif self.exception is None or isinstance(self.exception, bool): # timeout that raises self
  53. self.timer = get_hub().schedule_call_global(
  54. self.seconds, greenlet.getcurrent().throw, self)
  55. else: # regular timeout with user-provided exception
  56. self.timer = get_hub().schedule_call_global(
  57. self.seconds, greenlet.getcurrent().throw, self.exception)
  58. return self
  59. @property
  60. def pending(self):
  61. """True if the timeout is scheduled to be raised."""
  62. if self.timer is not None:
  63. return self.timer.pending
  64. else:
  65. return False
  66. def cancel(self):
  67. """If the timeout is pending, cancel it. If not using
  68. Timeouts in ``with`` statements, always call cancel() in a
  69. ``finally`` after the block of code that is getting timed out.
  70. If not canceled, the timeout will be raised later on, in some
  71. unexpected section of the application."""
  72. if self.timer is not None:
  73. self.timer.cancel()
  74. self.timer = None
  75. def __repr__(self):
  76. try:
  77. classname = self.__class__.__name__
  78. except AttributeError: # Python < 2.5
  79. classname = 'Timeout'
  80. if self.pending:
  81. pending = ' pending'
  82. else:
  83. pending = ''
  84. if self.exception is None:
  85. exception = ''
  86. else:
  87. exception = ' exception=%r' % self.exception
  88. return '<%s at %s seconds=%s%s%s>' % (
  89. classname, hex(id(self)), self.seconds, exception, pending)
  90. def __str__(self):
  91. """
  92. >>> raise Timeout
  93. Traceback (most recent call last):
  94. ...
  95. Timeout
  96. """
  97. if self.seconds is None:
  98. return ''
  99. if self.seconds == 1:
  100. suffix = ''
  101. else:
  102. suffix = 's'
  103. if self.exception is None or self.exception is True:
  104. return '%s second%s' % (self.seconds, suffix)
  105. elif self.exception is False:
  106. return '%s second%s (silent)' % (self.seconds, suffix)
  107. else:
  108. return '%s second%s (%s)' % (self.seconds, suffix, self.exception)
  109. def __enter__(self):
  110. if self.timer is None:
  111. self.start()
  112. return self
  113. def __exit__(self, typ, value, tb):
  114. self.cancel()
  115. if value is self and self.exception is False:
  116. return True
  117. def with_timeout(seconds, function, *args, **kwds):
  118. """Wrap a call to some (yielding) function with a timeout; if the called
  119. function fails to return before the timeout, cancel it and return a flag
  120. value.
  121. """
  122. timeout_value = kwds.pop("timeout_value", _NONE)
  123. timeout = Timeout(seconds)
  124. try:
  125. try:
  126. return function(*args, **kwds)
  127. except Timeout, ex:
  128. if ex is timeout and timeout_value is not _NONE:
  129. return timeout_value
  130. raise
  131. finally:
  132. timeout.cancel()