blob: fde9d0b503b66c062f57bfa39464f5d100f84939 [file] [log] [blame]
Chris Masone6f109082012-07-18 14:21:38 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Dan Shi15d42312015-12-15 15:37:28 -08005import logging
6import random
7import signal
8import sys
9import threading
10import time
Matthew Sartoridb550112015-06-02 13:55:32 -070011
Chris Masone6f109082012-07-18 14:21:38 -070012from autotest_lib.client.common_lib import error
Chris Masone6f109082012-07-18 14:21:38 -070013
14
beeps445cb742013-06-25 16:05:12 -070015def install_sigalarm_handler(new_handler):
16 """
17 Try installing a sigalarm handler.
18
19 In order to protect apache, wsgi intercepts any attempt to install a
20 sigalarm handler, so our function will feel the full force of a sigalarm
21 even if we try to install a pacifying signal handler. To avoid this we
22 need to confirm that the handler we tried to install really was installed.
23
24 @param new_handler: The new handler to install. This must be a callable
25 object, or signal.SIG_IGN/SIG_DFL which correspond to
26 the numbers 1,0 respectively.
27 @return: True if the installation of new_handler succeeded, False otherwise.
28 """
29 if (new_handler is None or
30 (not callable(new_handler) and
31 new_handler != signal.SIG_IGN and
32 new_handler != signal.SIG_DFL)):
33 logging.warning('Trying to install an invalid sigalarm handler.')
34 return False
35
36 signal.signal(signal.SIGALRM, new_handler)
37 installed_handler = signal.getsignal(signal.SIGALRM)
38 return installed_handler == new_handler
39
40
41def set_sigalarm_timeout(timeout_secs, default_timeout=60):
42 """
43 Set the sigalarm timeout.
44
45 This methods treats any timeout <= 0 as a possible error and falls back to
46 using it's default timeout, since negative timeouts can have 'alarming'
47 effects. Though 0 is a valid timeout, it is often used to cancel signals; in
48 order to set a sigalarm of 0 please call signal.alarm directly as there are
49 many situations where a 0 timeout is considered invalid.
50
51 @param timeout_secs: The new timeout, in seconds.
52 @param default_timeout: The default timeout to use, if timeout <= 0.
53 @return: The old sigalarm timeout
54 """
55 timeout_sec_n = int(timeout_secs)
56 if timeout_sec_n <= 0:
57 timeout_sec_n = int(default_timeout)
58 return signal.alarm(timeout_sec_n)
59
60
Luigi Semenzato623d9812016-11-04 12:59:14 -070061def sigalarm_wrapper(message):
62 """
63 Raise a TimeoutException with the given message. Needed because the body
64 of a closure (lambda) can only be an expression, not a statement (such
65 as "raise") :P :P :P
66
67 @param message: the exception message.
68 """
69 raise error.TimeoutException(message)
70
71
72def custom_sigalarm_handler(func, timeout_sec):
73 """
74 Returns a sigalarm handler which produces an exception with a custom
75 error message (function name and timeout length) instead of a generic
76 one.
77
78 @param func: the function that may time out
79 @param timeout_sec: timeout length in seconds
80 """
81 name = func.__name__ if hasattr(func, "__name__") else "unnamed function"
82 message = "sigalarm timeout (%d seconds) in %s" % (timeout_sec, name)
83 return lambda signum, frame: sigalarm_wrapper(message)
84
85
Dan Shi6d31f802013-01-11 14:46:12 -080086def timeout(func, args=(), kwargs={}, timeout_sec=60.0, default_result=None):
87 """
88 This function run the given function using the args, kwargs and
89 return the given default value if the timeout_sec is exceeded.
90
91 @param func: function to be called.
92 @param args: arguments for function to be called.
93 @param kwargs: keyword arguments for function to be called.
94 @param timeout_sec: timeout setting for call to exit, in seconds.
95 @param default_result: default return value for the function call.
96
97 @return 1: is_timeout 2: result of the function call. If
98 is_timeout is True, the call is timed out. If the
99 value is False, the call is finished on time.
100 """
beeps445cb742013-06-25 16:05:12 -0700101 old_alarm_sec = 0
102 old_handler = signal.getsignal(signal.SIGALRM)
Luigi Semenzato623d9812016-11-04 12:59:14 -0700103 handler = custom_sigalarm_handler(func, timeout_sec)
beeps445cb742013-06-25 16:05:12 -0700104 installed_handler = install_sigalarm_handler(handler)
105 if installed_handler:
106 old_alarm_sec = set_sigalarm_timeout(timeout_sec, default_timeout=60)
Dan Shi6d31f802013-01-11 14:46:12 -0800107
beeps445cb742013-06-25 16:05:12 -0700108 # If old_timeout_time = 0 we either didn't install a handler, or sigalrm
109 # had a signal.SIG_DFL handler with 0 timeout. In the latter case we still
110 # need to restore the handler/timeout.
111 old_timeout_time = (time.time() + old_alarm_sec) if old_alarm_sec > 0 else 0
112
Dan Shi6d31f802013-01-11 14:46:12 -0800113 try:
114 default_result = func(*args, **kwargs)
115 return False, default_result
beeps60aec242013-06-26 14:47:48 -0700116 except error.TimeoutException:
Dan Shi6d31f802013-01-11 14:46:12 -0800117 return True, default_result
118 finally:
beeps445cb742013-06-25 16:05:12 -0700119 # If we installed a sigalarm handler, cancel it since our function
120 # returned on time. If we can successfully restore the old handler,
121 # reset the old timeout, or, if the old timeout's deadline has passed,
122 # set the sigalarm to fire in one second. If the old_timeout_time is 0
123 # we don't need to set the sigalarm timeout since we have already set it
124 # as a byproduct of cancelling the current signal.
125 if installed_handler:
126 signal.alarm(0)
127 if install_sigalarm_handler(old_handler) and old_timeout_time:
128 set_sigalarm_timeout(int(old_timeout_time - time.time()),
129 default_timeout=1)
130
Dan Shi6d31f802013-01-11 14:46:12 -0800131
132
xixuana96aff02016-03-29 14:22:08 -0700133def retry(ExceptionToCheck, timeout_min=1.0, delay_sec=3, blacklist=None,
Luigi Semenzato623d9812016-11-04 12:59:14 -0700134 exception_to_raise=None, label=None):
Chris Masone6f109082012-07-18 14:21:38 -0700135 """Retry calling the decorated function using a delay with jitter.
136
137 Will raise RPC ValidationError exceptions from the decorated
138 function without retrying; a malformed RPC isn't going to
Fang Deng241ae6c2013-05-01 11:43:28 -0700139 magically become good. Will raise exceptions in blacklist as well.
Chris Masone6f109082012-07-18 14:21:38 -0700140
Dan Shi15d42312015-12-15 15:37:28 -0800141 If the retry is done in a child thread, timeout may not be enforced as
142 signal only works in main thread. Therefore, the retry inside a child
143 thread may run longer than timeout or even hang.
144
Chris Masone6f109082012-07-18 14:21:38 -0700145 original from:
146 http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
147
148 @param ExceptionToCheck: the exception to check. May be a tuple of
149 exceptions to check.
150 @param timeout_min: timeout in minutes until giving up.
151 @param delay_sec: pre-jittered delay between retries in seconds. Actual
152 delays will be centered around this value, ranging up to
153 50% off this midpoint.
Luigi Semenzato623d9812016-11-04 12:59:14 -0700154 @param blacklist: a list of exceptions that will be raised without retrying.
xixuana96aff02016-03-29 14:22:08 -0700155 @param exception_to_raise: the exception to raise. Callers can specify the
Luigi Semenzato623d9812016-11-04 12:59:14 -0700156 exception they want to raise.
157 @param label: a label added to the exception message to help debug.
Chris Masone6f109082012-07-18 14:21:38 -0700158 """
159 def deco_retry(func):
Luigi Semenzato623d9812016-11-04 12:59:14 -0700160 """
161 Decorator wrapper.
162
163 @param func: the function to be retried and timed-out.
164 """
Chris Masone6f109082012-07-18 14:21:38 -0700165 random.seed()
Dan Shi6d31f802013-01-11 14:46:12 -0800166
167
168 def delay():
169 """
170 'Jitter' the delay, up to 50% in either direction.
171 """
172 random_delay = random.uniform(.5 * delay_sec, 1.5 * delay_sec)
173 logging.warning('Retrying in %f seconds...', random_delay)
174 time.sleep(random_delay)
175
176
Chris Masone6f109082012-07-18 14:21:38 -0700177 def func_retry(*args, **kwargs):
Luigi Semenzato623d9812016-11-04 12:59:14 -0700178 """
179 Used to cache exception to be raised later.
180 """
Dan Shi6d31f802013-01-11 14:46:12 -0800181 exc_info = None
182 delayed_enabled = False
Fang Deng241ae6c2013-05-01 11:43:28 -0700183 exception_tuple = () if blacklist is None else tuple(blacklist)
beeps445cb742013-06-25 16:05:12 -0700184 start_time = time.time()
185 remaining_time = timeout_min * 60
Dan Shi15d42312015-12-15 15:37:28 -0800186 is_main_thread = isinstance(threading.current_thread(),
187 threading._MainThread)
Luigi Semenzato623d9812016-11-04 12:59:14 -0700188 if label:
189 details = 'label="%s"' % label
190 elif hasattr(func, '__name__'):
191 details = 'function="%s()"' % func.__name__
192 else:
193 details = 'unknown function'
194
195 exception_message = ('retry exception (%s), timeout = %ds' %
196 (details, timeout_min * 60))
197
beeps445cb742013-06-25 16:05:12 -0700198 while remaining_time > 0:
Dan Shi6d31f802013-01-11 14:46:12 -0800199 if delayed_enabled:
200 delay()
201 else:
202 delayed_enabled = True
Chris Masone6f109082012-07-18 14:21:38 -0700203 try:
Dan Shi6d31f802013-01-11 14:46:12 -0800204 # Clear the cache
205 exc_info = None
Dan Shi15d42312015-12-15 15:37:28 -0800206 if is_main_thread:
207 is_timeout, result = timeout(func, args, kwargs,
208 remaining_time)
209 if not is_timeout:
210 return result
211 else:
212 return func(*args, **kwargs)
Fang Deng241ae6c2013-05-01 11:43:28 -0700213 except exception_tuple:
214 raise
Tom Wai-Hong Tamd5dde482014-11-21 05:11:23 +0800215 except error.CrosDynamicSuiteException:
Dan Shi6d31f802013-01-11 14:46:12 -0800216 raise
217 except ExceptionToCheck as e:
218 logging.warning('%s(%s)', e.__class__, e)
219 # Cache the exception to be raised later.
220 exc_info = sys.exc_info()
beeps445cb742013-06-25 16:05:12 -0700221
Luigi Semenzato623d9812016-11-04 12:59:14 -0700222 remaining_time = int(timeout_min * 60 -
beeps445cb742013-06-25 16:05:12 -0700223 (time.time() - start_time))
224
Dan Shi6d31f802013-01-11 14:46:12 -0800225 # The call must have timed out or raised ExceptionToCheck.
226 if not exc_info:
xixuana96aff02016-03-29 14:22:08 -0700227 if exception_to_raise:
Luigi Semenzato623d9812016-11-04 12:59:14 -0700228 raise exception_to_raise(exception_message)
xixuana96aff02016-03-29 14:22:08 -0700229 else:
Luigi Semenzato623d9812016-11-04 12:59:14 -0700230 raise error.TimeoutException(exception_message)
Dan Shi6d31f802013-01-11 14:46:12 -0800231 # Raise the cached exception with original backtrace.
xixuana96aff02016-03-29 14:22:08 -0700232 if exception_to_raise:
233 raise exception_to_raise('%s: %s' % (exc_info[0], exc_info[1]))
Dan Shi6d31f802013-01-11 14:46:12 -0800234 raise exc_info[0], exc_info[1], exc_info[2]
235
236
Chris Masone6f109082012-07-18 14:21:38 -0700237 return func_retry # true decorator
Fang Deng241ae6c2013-05-01 11:43:28 -0700238 return deco_retry