|
1
|
|
|
import time |
|
2
|
|
|
from logging import getLogger |
|
3
|
|
|
|
|
4
|
|
|
from aspectlib import Aspect |
|
5
|
|
|
|
|
6
|
|
|
logger = getLogger(__name__) |
|
7
|
|
|
|
|
8
|
|
|
|
|
9
|
|
|
def retry(func=None, retries=5, backoff=None, exceptions=(IOError, OSError, EOFError), cleanup=None, sleep=time.sleep): |
|
10
|
|
|
""" |
|
11
|
|
|
Decorator that retries the call ``retries`` times if ``func`` raises ``exceptions``. Can use a ``backoff`` function |
|
12
|
|
|
to sleep till next retry. |
|
13
|
|
|
|
|
14
|
|
|
Example:: |
|
15
|
|
|
|
|
16
|
|
|
>>> should_fail = lambda foo=[1,2,3]: foo and foo.pop() |
|
17
|
|
|
>>> @retry |
|
18
|
|
|
... def flaky_func(): |
|
19
|
|
|
... if should_fail(): |
|
20
|
|
|
... raise OSError('Tough luck!') |
|
21
|
|
|
... print("Success!") |
|
22
|
|
|
... |
|
23
|
|
|
>>> flaky_func() |
|
24
|
|
|
Success! |
|
25
|
|
|
|
|
26
|
|
|
If it reaches the retry limit:: |
|
27
|
|
|
|
|
28
|
|
|
>>> @retry |
|
29
|
|
|
... def bad_func(): |
|
30
|
|
|
... raise OSError('Tough luck!') |
|
31
|
|
|
... |
|
32
|
|
|
>>> bad_func() |
|
33
|
|
|
Traceback (most recent call last): |
|
34
|
|
|
... |
|
35
|
|
|
OSError: Tough luck! |
|
36
|
|
|
|
|
37
|
|
|
""" |
|
38
|
|
|
|
|
39
|
|
|
@Aspect(bind=True) |
|
40
|
|
|
def retry_aspect(cutpoint, *args, **kwargs): |
|
41
|
|
|
for count in range(retries + 1): |
|
42
|
|
|
try: |
|
43
|
|
|
if count and cleanup: |
|
44
|
|
|
cleanup(*args, **kwargs) |
|
45
|
|
|
yield |
|
46
|
|
|
break |
|
47
|
|
|
except exceptions as exc: |
|
48
|
|
|
if count == retries: |
|
49
|
|
|
raise |
|
50
|
|
|
if not backoff: |
|
51
|
|
|
timeout = 0 |
|
52
|
|
|
elif isinstance(backoff, (int, float)): |
|
53
|
|
|
timeout = backoff |
|
54
|
|
|
else: |
|
55
|
|
|
timeout = backoff(count) |
|
56
|
|
|
logger.exception("%s(%s, %s) raised exception %s. %s retries left. Sleeping %s secs.", |
|
57
|
|
|
cutpoint.__name__, args, kwargs, exc, retries - count, timeout) |
|
58
|
|
|
sleep(timeout) |
|
59
|
|
|
|
|
60
|
|
|
return retry_aspect if func is None else retry_aspect(func) |
|
61
|
|
|
|
|
62
|
|
|
|
|
63
|
|
|
def exponential_backoff(count): |
|
64
|
|
|
""" |
|
65
|
|
|
Wait 2**N seconds. |
|
66
|
|
|
""" |
|
67
|
|
|
return 2 ** count |
|
68
|
|
|
retry.exponential_backoff = exponential_backoff |
|
69
|
|
|
|
|
70
|
|
|
|
|
71
|
|
|
def straight_backoff(count): |
|
72
|
|
|
""" |
|
73
|
|
|
Wait 1, 2, 5 seconds. All retries after the 3rd retry will wait 5*N-5 seconds. |
|
74
|
|
|
""" |
|
75
|
|
|
return (1, 2, 5)[count] if count < 3 else 5 * count - 5 |
|
76
|
|
|
retry.straight_backoff = straight_backoff |
|
77
|
|
|
|
|
78
|
|
|
|
|
79
|
|
|
def flat_backoff(count): |
|
80
|
|
|
""" |
|
81
|
|
|
Wait 1, 2, 5, 10, 15, 30 and 60 seconds. All retries after the 5th retry will wait 60 seconds. |
|
82
|
|
|
""" |
|
83
|
|
|
return (1, 2, 5, 10, 15, 30, 60)[count if count < 6 else -1] |
|
84
|
|
|
retry.flat_backoff = flat_backoff |
|
85
|
|
|
|