| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright (c) 2021 Ansible Project |
| 4 |
# |
| 5 |
# This code is part of Ansible, but is an independent component. |
| 6 |
# This particular file snippet, and this file snippet only, is BSD licensed. |
| 7 |
# Modules you write using this snippet, which is embedded dynamically by Ansible |
| 8 |
# still belong to the author of the module, and may assign their own license |
| 9 |
# to the complete work. |
| 10 |
# |
| 11 |
# Redistribution and use in source and binary forms, with or without modification, |
| 12 |
# are permitted provided that the following conditions are met: |
| 13 |
# |
| 14 |
# * Redistributions of source code must retain the above copyright |
| 15 |
# notice, this list of conditions and the following disclaimer. |
| 16 |
# * Redistributions in binary form must reproduce the above copyright notice, |
| 17 |
# this list of conditions and the following disclaimer in the documentation |
| 18 |
# and/or other materials provided with the distribution. |
| 19 |
# |
| 20 |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
| 21 |
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
| 22 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
| 23 |
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
| 24 |
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 25 |
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 26 |
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| 27 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE |
| 28 |
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 |
|
| 30 |
import functools |
| 31 |
import random |
| 32 |
import time |
| 33 |
|
| 34 |
|
| 35 |
class BackoffIterator: |
| 36 |
"""iterate sleep value based on the exponential or jitter back-off algorithm. |
| 37 |
Args: |
| 38 |
delay (int or float): initial delay. |
| 39 |
backoff (int or float): backoff multiplier e.g. value of 2 will double the delay each retry. |
| 40 |
max_delay (int or None): maximum amount of time to wait between retries. |
| 41 |
jitter (bool): if set to true, add jitter to the generate value. |
| 42 |
""" |
| 43 |
|
| 44 |
def __init__(self, delay, backoff, max_delay=None, jitter=False): |
| 45 |
self.delay = delay |
| 46 |
self.backoff = backoff |
| 47 |
self.max_delay = max_delay |
| 48 |
self.jitter = jitter |
| 49 |
|
| 50 |
def __iter__(self): |
| 51 |
self.current_delay = self.delay |
| 52 |
return self |
| 53 |
|
| 54 |
def __next__(self): |
| 55 |
return_value = self.current_delay if self.max_delay is None else min(self.current_delay, self.max_delay) |
| 56 |
if self.jitter: |
| 57 |
return_value = random.uniform(0.0, return_value) |
| 58 |
self.current_delay *= self.backoff |
| 59 |
return return_value |
| 60 |
|
| 61 |
|
| 62 |
def _retry_func( |
| 63 |
func, sleep_time_generator, retries, catch_extra_error_codes, found_f, status_code_from_except_f, base_class |
| 64 |
): |
| 65 |
counter = 0 |
| 66 |
for sleep_time in sleep_time_generator: |
| 67 |
try: |
| 68 |
return func() |
| 69 |
except Exception as exc: # pylint: disable=broad-except |
| 70 |
counter += 1 |
| 71 |
if counter == retries: |
| 72 |
raise |
| 73 |
if base_class and not isinstance(exc, base_class): |
| 74 |
raise |
| 75 |
status_code = status_code_from_except_f(exc) |
| 76 |
if found_f(status_code, catch_extra_error_codes): |
| 77 |
time.sleep(sleep_time) |
| 78 |
else: |
| 79 |
raise |
| 80 |
|
| 81 |
|
| 82 |
class CloudRetry: |
| 83 |
""" |
| 84 |
The base class to be used by other cloud providers to provide a backoff/retry decorator based on status codes. |
| 85 |
""" |
| 86 |
|
| 87 |
base_class = type(None) |
| 88 |
|
| 89 |
@staticmethod |
| 90 |
def status_code_from_exception(error): |
| 91 |
""" |
| 92 |
Returns the Error 'code' from an exception. |
| 93 |
Args: |
| 94 |
error: The Exception from which the error code is to be extracted. |
| 95 |
error will be an instance of class.base_class. |
| 96 |
""" |
| 97 |
raise NotImplementedError() |
| 98 |
|
| 99 |
@staticmethod |
| 100 |
def found(response_code, catch_extra_error_codes=None): |
| 101 |
def _is_iterable(): |
| 102 |
try: |
| 103 |
iter(catch_extra_error_codes) |
| 104 |
except TypeError: |
| 105 |
# not iterable |
| 106 |
return False |
| 107 |
else: |
| 108 |
# iterable |
| 109 |
return True |
| 110 |
|
| 111 |
return _is_iterable() and response_code in catch_extra_error_codes |
| 112 |
|
| 113 |
@classmethod |
| 114 |
def base_decorator(cls, retries, found, status_code_from_exception, catch_extra_error_codes, sleep_time_generator): |
| 115 |
def retry_decorator(func): |
| 116 |
@functools.wraps(func) |
| 117 |
def _retry_wrapper(*args, **kwargs): |
| 118 |
partial_func = functools.partial(func, *args, **kwargs) |
| 119 |
return _retry_func( |
| 120 |
func=partial_func, |
| 121 |
sleep_time_generator=sleep_time_generator, |
| 122 |
retries=retries, |
| 123 |
catch_extra_error_codes=catch_extra_error_codes, |
| 124 |
found_f=found, |
| 125 |
status_code_from_except_f=status_code_from_exception, |
| 126 |
base_class=cls.base_class, |
| 127 |
) |
| 128 |
|
| 129 |
return _retry_wrapper |
| 130 |
|
| 131 |
return retry_decorator |
| 132 |
|
| 133 |
@classmethod |
| 134 |
def exponential_backoff(cls, retries=10, delay=3, backoff=2, max_delay=60, catch_extra_error_codes=None): |
| 135 |
"""Wrap a callable with retry behavior. |
| 136 |
Args: |
| 137 |
retries (int): Number of times to retry a failed request before giving up |
| 138 |
default=10 |
| 139 |
delay (int or float): Initial delay between retries in seconds |
| 140 |
default=3 |
| 141 |
backoff (int or float): backoff multiplier e.g. value of 2 will double the delay each retry |
| 142 |
default=2 |
| 143 |
max_delay (int or None): maximum amount of time to wait between retries. |
| 144 |
default=60 |
| 145 |
catch_extra_error_codes: Additional error messages to catch, in addition to those which may be defined by a subclass of CloudRetry |
| 146 |
default=None |
| 147 |
Returns: |
| 148 |
Callable: A generator that calls the decorated function using an exponential backoff. |
| 149 |
""" |
| 150 |
sleep_time_generator = BackoffIterator(delay=delay, backoff=backoff, max_delay=max_delay) |
| 151 |
return cls.base_decorator( |
| 152 |
retries=retries, |
| 153 |
found=cls.found, |
| 154 |
status_code_from_exception=cls.status_code_from_exception, |
| 155 |
catch_extra_error_codes=catch_extra_error_codes, |
| 156 |
sleep_time_generator=sleep_time_generator, |
| 157 |
) |
| 158 |
|
| 159 |
@classmethod |
| 160 |
def jittered_backoff(cls, retries=10, delay=3, backoff=2.0, max_delay=60, catch_extra_error_codes=None): |
| 161 |
"""Wrap a callable with retry behavior. |
| 162 |
Args: |
| 163 |
retries (int): Number of times to retry a failed request before giving up |
| 164 |
default=10 |
| 165 |
delay (int or float): Initial delay between retries in seconds |
| 166 |
default=3 |
| 167 |
backoff (int or float): backoff multiplier e.g. value of 2 will double the delay each retry |
| 168 |
default=2.0 |
| 169 |
max_delay (int or None): maximum amount of time to wait between retries. |
| 170 |
default=60 |
| 171 |
catch_extra_error_codes: Additional error messages to catch, in addition to those which may be defined by a subclass of CloudRetry |
| 172 |
default=None |
| 173 |
Returns: |
| 174 |
Callable: A generator that calls the decorated function using using a jittered backoff strategy. |
| 175 |
""" |
| 176 |
sleep_time_generator = BackoffIterator(delay=delay, backoff=backoff, max_delay=max_delay, jitter=True) |
| 177 |
return cls.base_decorator( |
| 178 |
retries=retries, |
| 179 |
found=cls.found, |
| 180 |
status_code_from_exception=cls.status_code_from_exception, |
| 181 |
catch_extra_error_codes=catch_extra_error_codes, |
| 182 |
sleep_time_generator=sleep_time_generator, |
| 183 |
) |