Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 1 | # 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 Shi | 15d4231 | 2015-12-15 15:37:28 -0800 | [diff] [blame] | 5 | import logging |
| 6 | import random |
| 7 | import signal |
| 8 | import sys |
| 9 | import threading |
| 10 | import time |
Matthew Sartori | db55011 | 2015-06-02 13:55:32 -0700 | [diff] [blame] | 11 | |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 12 | from autotest_lib.client.common_lib import error |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 13 | |
| 14 | |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 15 | def 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 | |
| 41 | def 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 Semenzato | 623d981 | 2016-11-04 12:59:14 -0700 | [diff] [blame^] | 61 | def 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 | |
| 72 | def 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 Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 86 | def 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 | """ |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 101 | old_alarm_sec = 0 |
| 102 | old_handler = signal.getsignal(signal.SIGALRM) |
Luigi Semenzato | 623d981 | 2016-11-04 12:59:14 -0700 | [diff] [blame^] | 103 | handler = custom_sigalarm_handler(func, timeout_sec) |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 104 | installed_handler = install_sigalarm_handler(handler) |
| 105 | if installed_handler: |
| 106 | old_alarm_sec = set_sigalarm_timeout(timeout_sec, default_timeout=60) |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 107 | |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 108 | # 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 Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 113 | try: |
| 114 | default_result = func(*args, **kwargs) |
| 115 | return False, default_result |
beeps | 60aec24 | 2013-06-26 14:47:48 -0700 | [diff] [blame] | 116 | except error.TimeoutException: |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 117 | return True, default_result |
| 118 | finally: |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 119 | # 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 Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 131 | |
| 132 | |
xixuan | a96aff0 | 2016-03-29 14:22:08 -0700 | [diff] [blame] | 133 | def retry(ExceptionToCheck, timeout_min=1.0, delay_sec=3, blacklist=None, |
Luigi Semenzato | 623d981 | 2016-11-04 12:59:14 -0700 | [diff] [blame^] | 134 | exception_to_raise=None, label=None): |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 135 | """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 Deng | 241ae6c | 2013-05-01 11:43:28 -0700 | [diff] [blame] | 139 | magically become good. Will raise exceptions in blacklist as well. |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 140 | |
Dan Shi | 15d4231 | 2015-12-15 15:37:28 -0800 | [diff] [blame] | 141 | 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 Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 145 | 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 Semenzato | 623d981 | 2016-11-04 12:59:14 -0700 | [diff] [blame^] | 154 | @param blacklist: a list of exceptions that will be raised without retrying. |
xixuan | a96aff0 | 2016-03-29 14:22:08 -0700 | [diff] [blame] | 155 | @param exception_to_raise: the exception to raise. Callers can specify the |
Luigi Semenzato | 623d981 | 2016-11-04 12:59:14 -0700 | [diff] [blame^] | 156 | exception they want to raise. |
| 157 | @param label: a label added to the exception message to help debug. |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 158 | """ |
| 159 | def deco_retry(func): |
Luigi Semenzato | 623d981 | 2016-11-04 12:59:14 -0700 | [diff] [blame^] | 160 | """ |
| 161 | Decorator wrapper. |
| 162 | |
| 163 | @param func: the function to be retried and timed-out. |
| 164 | """ |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 165 | random.seed() |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 166 | |
| 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 Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 177 | def func_retry(*args, **kwargs): |
Luigi Semenzato | 623d981 | 2016-11-04 12:59:14 -0700 | [diff] [blame^] | 178 | """ |
| 179 | Used to cache exception to be raised later. |
| 180 | """ |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 181 | exc_info = None |
| 182 | delayed_enabled = False |
Fang Deng | 241ae6c | 2013-05-01 11:43:28 -0700 | [diff] [blame] | 183 | exception_tuple = () if blacklist is None else tuple(blacklist) |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 184 | start_time = time.time() |
| 185 | remaining_time = timeout_min * 60 |
Dan Shi | 15d4231 | 2015-12-15 15:37:28 -0800 | [diff] [blame] | 186 | is_main_thread = isinstance(threading.current_thread(), |
| 187 | threading._MainThread) |
Luigi Semenzato | 623d981 | 2016-11-04 12:59:14 -0700 | [diff] [blame^] | 188 | 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 | |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 198 | while remaining_time > 0: |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 199 | if delayed_enabled: |
| 200 | delay() |
| 201 | else: |
| 202 | delayed_enabled = True |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 203 | try: |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 204 | # Clear the cache |
| 205 | exc_info = None |
Dan Shi | 15d4231 | 2015-12-15 15:37:28 -0800 | [diff] [blame] | 206 | 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 Deng | 241ae6c | 2013-05-01 11:43:28 -0700 | [diff] [blame] | 213 | except exception_tuple: |
| 214 | raise |
Tom Wai-Hong Tam | d5dde48 | 2014-11-21 05:11:23 +0800 | [diff] [blame] | 215 | except error.CrosDynamicSuiteException: |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 216 | 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() |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 221 | |
Luigi Semenzato | 623d981 | 2016-11-04 12:59:14 -0700 | [diff] [blame^] | 222 | remaining_time = int(timeout_min * 60 - |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 223 | (time.time() - start_time)) |
| 224 | |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 225 | # The call must have timed out or raised ExceptionToCheck. |
| 226 | if not exc_info: |
xixuan | a96aff0 | 2016-03-29 14:22:08 -0700 | [diff] [blame] | 227 | if exception_to_raise: |
Luigi Semenzato | 623d981 | 2016-11-04 12:59:14 -0700 | [diff] [blame^] | 228 | raise exception_to_raise(exception_message) |
xixuan | a96aff0 | 2016-03-29 14:22:08 -0700 | [diff] [blame] | 229 | else: |
Luigi Semenzato | 623d981 | 2016-11-04 12:59:14 -0700 | [diff] [blame^] | 230 | raise error.TimeoutException(exception_message) |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 231 | # Raise the cached exception with original backtrace. |
xixuan | a96aff0 | 2016-03-29 14:22:08 -0700 | [diff] [blame] | 232 | if exception_to_raise: |
| 233 | raise exception_to_raise('%s: %s' % (exc_info[0], exc_info[1])) |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 234 | raise exc_info[0], exc_info[1], exc_info[2] |
| 235 | |
| 236 | |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 237 | return func_retry # true decorator |
Fang Deng | 241ae6c | 2013-05-01 11:43:28 -0700 | [diff] [blame] | 238 | return deco_retry |