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