| OLD | NEW |
| (Empty) | |
| 1 # Copyright 2014 The Chromium 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 |
| 5 """ |
| 6 Function/method decorators that provide timeout and retry logic. |
| 7 """ |
| 8 |
| 9 import functools |
| 10 |
| 11 from pylib.device import errors |
| 12 from pylib.utils import reraiser_thread |
| 13 from pylib.utils import timeout_retry |
| 14 |
| 15 |
| 16 def WithTimeoutAndRetries(f): |
| 17 """ A decorator that handles timeouts and retries. |
| 18 """ |
| 19 @functools.wraps(f) |
| 20 def TimeoutRetryWrapper(*args, **kwargs): |
| 21 # handle retries and timeouts |
| 22 timeout = kwargs.get('timeout') |
| 23 retries = kwargs.get('retries') |
| 24 |
| 25 # Check for exactly None s.t. zero values are valid. |
| 26 if timeout is None: |
| 27 raise TypeError("%s requires a 'timeout' parameter" % f.__name__) |
| 28 if retries is None: |
| 29 raise TypeError("%s requires a 'retries' parameter" % f.__name__) |
| 30 |
| 31 def impl(): |
| 32 return f(*args, **kwargs) |
| 33 try: |
| 34 return timeout_retry.Run(impl, timeout, retries) |
| 35 except reraiser_thread.TimeoutError as e: |
| 36 raise errors.CommandTimeoutError(str(e)) |
| 37 return TimeoutRetryWrapper |
| 38 |
| 39 |
| 40 def WithTimeoutAndRetriesDefaults(default_timeout, default_retries): |
| 41 """ A decorator that handles timeouts and retries using the provided |
| 42 default timeout and retry values if they aren't specified as a kwarg. |
| 43 """ |
| 44 def decorator(f): |
| 45 @functools.wraps(f) |
| 46 def TimeoutRetryWrapper(*args, **kwargs): |
| 47 kwargs['timeout'] = kwargs.get('timeout', default_timeout) |
| 48 kwargs['retries'] = kwargs.get('retries', default_retries) |
| 49 return WithTimeoutAndRetries(f)(*args, **kwargs) |
| 50 return TimeoutRetryWrapper |
| 51 return decorator |
| 52 |
| 53 |
| 54 def WithTimeoutAndRetriesFromInstance( |
| 55 default_timeout_name, default_retries_name): |
| 56 """ Returns a decorator that handles timeouts and retries using default |
| 57 timeout and retry values from the object if they aren't specified as a |
| 58 kwarg. |
| 59 """ |
| 60 def decorator(f): |
| 61 @functools.wraps(f) |
| 62 def TimeoutRetryWrapper(device, *args, **kwargs): |
| 63 kwargs['timeout'] = kwargs.get( |
| 64 'timeout', getattr(device, default_timeout_name)) |
| 65 kwargs['retries'] = kwargs.get( |
| 66 'retries', getattr(device, default_retries_name)) |
| 67 return WithTimeoutAndRetries(f)(device, *args, **kwargs) |
| 68 return TimeoutRetryWrapper |
| 69 return decorator |
| 70 |
| OLD | NEW |