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