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 | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 5 | import logging, random, signal, sys, time |
| 6 | |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 7 | from autotest_lib.client.common_lib import error |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 8 | |
| 9 | |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 10 | def handler(signum, frame): |
| 11 | """ |
| 12 | Register a handler for the timeout. |
| 13 | """ |
beeps | 60aec24 | 2013-06-26 14:47:48 -0700 | [diff] [blame] | 14 | raise error.TimeoutException('Call is timed out.') |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 15 | |
| 16 | |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 17 | def install_sigalarm_handler(new_handler): |
| 18 | """ |
| 19 | Try installing a sigalarm handler. |
| 20 | |
| 21 | In order to protect apache, wsgi intercepts any attempt to install a |
| 22 | sigalarm handler, so our function will feel the full force of a sigalarm |
| 23 | even if we try to install a pacifying signal handler. To avoid this we |
| 24 | need to confirm that the handler we tried to install really was installed. |
| 25 | |
| 26 | @param new_handler: The new handler to install. This must be a callable |
| 27 | object, or signal.SIG_IGN/SIG_DFL which correspond to |
| 28 | the numbers 1,0 respectively. |
| 29 | @return: True if the installation of new_handler succeeded, False otherwise. |
| 30 | """ |
| 31 | if (new_handler is None or |
| 32 | (not callable(new_handler) and |
| 33 | new_handler != signal.SIG_IGN and |
| 34 | new_handler != signal.SIG_DFL)): |
| 35 | logging.warning('Trying to install an invalid sigalarm handler.') |
| 36 | return False |
| 37 | |
| 38 | signal.signal(signal.SIGALRM, new_handler) |
| 39 | installed_handler = signal.getsignal(signal.SIGALRM) |
| 40 | return installed_handler == new_handler |
| 41 | |
| 42 | |
| 43 | def set_sigalarm_timeout(timeout_secs, default_timeout=60): |
| 44 | """ |
| 45 | Set the sigalarm timeout. |
| 46 | |
| 47 | This methods treats any timeout <= 0 as a possible error and falls back to |
| 48 | using it's default timeout, since negative timeouts can have 'alarming' |
| 49 | effects. Though 0 is a valid timeout, it is often used to cancel signals; in |
| 50 | order to set a sigalarm of 0 please call signal.alarm directly as there are |
| 51 | many situations where a 0 timeout is considered invalid. |
| 52 | |
| 53 | @param timeout_secs: The new timeout, in seconds. |
| 54 | @param default_timeout: The default timeout to use, if timeout <= 0. |
| 55 | @return: The old sigalarm timeout |
| 56 | """ |
| 57 | timeout_sec_n = int(timeout_secs) |
| 58 | if timeout_sec_n <= 0: |
| 59 | timeout_sec_n = int(default_timeout) |
| 60 | return signal.alarm(timeout_sec_n) |
| 61 | |
| 62 | |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 63 | def timeout(func, args=(), kwargs={}, timeout_sec=60.0, default_result=None): |
| 64 | """ |
| 65 | This function run the given function using the args, kwargs and |
| 66 | return the given default value if the timeout_sec is exceeded. |
| 67 | |
| 68 | @param func: function to be called. |
| 69 | @param args: arguments for function to be called. |
| 70 | @param kwargs: keyword arguments for function to be called. |
| 71 | @param timeout_sec: timeout setting for call to exit, in seconds. |
| 72 | @param default_result: default return value for the function call. |
| 73 | |
| 74 | @return 1: is_timeout 2: result of the function call. If |
| 75 | is_timeout is True, the call is timed out. If the |
| 76 | value is False, the call is finished on time. |
| 77 | """ |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 78 | old_alarm_sec = 0 |
| 79 | old_handler = signal.getsignal(signal.SIGALRM) |
| 80 | installed_handler = install_sigalarm_handler(handler) |
| 81 | if installed_handler: |
| 82 | old_alarm_sec = set_sigalarm_timeout(timeout_sec, default_timeout=60) |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 83 | |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 84 | # If old_timeout_time = 0 we either didn't install a handler, or sigalrm |
| 85 | # had a signal.SIG_DFL handler with 0 timeout. In the latter case we still |
| 86 | # need to restore the handler/timeout. |
| 87 | old_timeout_time = (time.time() + old_alarm_sec) if old_alarm_sec > 0 else 0 |
| 88 | |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 89 | try: |
| 90 | default_result = func(*args, **kwargs) |
| 91 | return False, default_result |
beeps | 60aec24 | 2013-06-26 14:47:48 -0700 | [diff] [blame] | 92 | except error.TimeoutException: |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 93 | return True, default_result |
| 94 | finally: |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 95 | # If we installed a sigalarm handler, cancel it since our function |
| 96 | # returned on time. If we can successfully restore the old handler, |
| 97 | # reset the old timeout, or, if the old timeout's deadline has passed, |
| 98 | # set the sigalarm to fire in one second. If the old_timeout_time is 0 |
| 99 | # we don't need to set the sigalarm timeout since we have already set it |
| 100 | # as a byproduct of cancelling the current signal. |
| 101 | if installed_handler: |
| 102 | signal.alarm(0) |
| 103 | if install_sigalarm_handler(old_handler) and old_timeout_time: |
| 104 | set_sigalarm_timeout(int(old_timeout_time - time.time()), |
| 105 | default_timeout=1) |
| 106 | |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 107 | |
| 108 | |
Fang Deng | 241ae6c | 2013-05-01 11:43:28 -0700 | [diff] [blame] | 109 | def retry(ExceptionToCheck, timeout_min=1.0, delay_sec=3, blacklist=None): |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 110 | """Retry calling the decorated function using a delay with jitter. |
| 111 | |
| 112 | Will raise RPC ValidationError exceptions from the decorated |
| 113 | function without retrying; a malformed RPC isn't going to |
Fang Deng | 241ae6c | 2013-05-01 11:43:28 -0700 | [diff] [blame] | 114 | magically become good. Will raise exceptions in blacklist as well. |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 115 | |
| 116 | original from: |
| 117 | http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ |
| 118 | |
| 119 | @param ExceptionToCheck: the exception to check. May be a tuple of |
| 120 | exceptions to check. |
| 121 | @param timeout_min: timeout in minutes until giving up. |
| 122 | @param delay_sec: pre-jittered delay between retries in seconds. Actual |
| 123 | delays will be centered around this value, ranging up to |
| 124 | 50% off this midpoint. |
Fang Deng | 241ae6c | 2013-05-01 11:43:28 -0700 | [diff] [blame] | 125 | @param blacklist: a list of exceptions that will be raised without retrying |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 126 | """ |
| 127 | def deco_retry(func): |
| 128 | random.seed() |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 129 | |
| 130 | |
| 131 | def delay(): |
| 132 | """ |
| 133 | 'Jitter' the delay, up to 50% in either direction. |
| 134 | """ |
| 135 | random_delay = random.uniform(.5 * delay_sec, 1.5 * delay_sec) |
| 136 | logging.warning('Retrying in %f seconds...', random_delay) |
| 137 | time.sleep(random_delay) |
| 138 | |
| 139 | |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 140 | def func_retry(*args, **kwargs): |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 141 | # Used to cache exception to be raised later. |
| 142 | exc_info = None |
| 143 | delayed_enabled = False |
Fang Deng | 241ae6c | 2013-05-01 11:43:28 -0700 | [diff] [blame] | 144 | exception_tuple = () if blacklist is None else tuple(blacklist) |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 145 | start_time = time.time() |
| 146 | remaining_time = timeout_min * 60 |
| 147 | |
| 148 | while remaining_time > 0: |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 149 | if delayed_enabled: |
| 150 | delay() |
| 151 | else: |
| 152 | delayed_enabled = True |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 153 | try: |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 154 | # Clear the cache |
| 155 | exc_info = None |
| 156 | is_timeout, result = timeout(func, args, kwargs, |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 157 | remaining_time) |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 158 | if not is_timeout: |
| 159 | return result |
Fang Deng | 241ae6c | 2013-05-01 11:43:28 -0700 | [diff] [blame] | 160 | except exception_tuple: |
| 161 | raise |
Tom Wai-Hong Tam | d5dde48 | 2014-11-21 05:11:23 +0800 | [diff] [blame^] | 162 | except error.CrosDynamicSuiteException: |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 163 | raise |
| 164 | except ExceptionToCheck as e: |
| 165 | logging.warning('%s(%s)', e.__class__, e) |
| 166 | # Cache the exception to be raised later. |
| 167 | exc_info = sys.exc_info() |
beeps | 445cb74 | 2013-06-25 16:05:12 -0700 | [diff] [blame] | 168 | |
| 169 | remaining_time = int(timeout_min*60 - |
| 170 | (time.time() - start_time)) |
| 171 | |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 172 | # The call must have timed out or raised ExceptionToCheck. |
| 173 | if not exc_info: |
beeps | 60aec24 | 2013-06-26 14:47:48 -0700 | [diff] [blame] | 174 | raise error.TimeoutException('Call is timed out.') |
Dan Shi | 6d31f80 | 2013-01-11 14:46:12 -0800 | [diff] [blame] | 175 | # Raise the cached exception with original backtrace. |
| 176 | raise exc_info[0], exc_info[1], exc_info[2] |
| 177 | |
| 178 | |
Chris Masone | 6f10908 | 2012-07-18 14:21:38 -0700 | [diff] [blame] | 179 | return func_retry # true decorator |
Fang Deng | 241ae6c | 2013-05-01 11:43:28 -0700 | [diff] [blame] | 180 | return deco_retry |