Debian Codegraph @

lib/ansible/module_utils/api.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # Copyright: (c) 2015, Brian Coca, <[email protected]>
8 #
9 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
10 """
11 This module adds shared support for generic api modules
12
13 In order to use this module, include it as part of a custom
14 module as shown below.
15
16 The 'api' module provides the following common argument specs:
17
18 * rate limit spec
19 - rate: number of requests per time unit (int)
20 - rate_limit: time window in which the limit is applied in seconds
21
22 * retry spec
23 - retries: number of attempts
24 - retry_pause: delay between attempts in seconds
25 """
26 from __future__ import annotations
27
28 import copy
29 import functools
30 import itertools
31 import secrets
32 import sys
33 import time
34 import typing as t
35
36
37 def rate_limit_argument_spec(spec=None):
38 """Creates an argument spec for working with rate limiting"""
39 arg_spec = (dict(
40 rate=dict(type='int'),
41 rate_limit=dict(type='int'),
42 ))
43 if spec:
44 arg_spec.update(spec)
45 return arg_spec
46
47
48 def retry_argument_spec(spec=None):
49 """Creates an argument spec for working with retrying"""
50 arg_spec = (dict(
51 retries=dict(type='int'),
52 retry_pause=dict(type='float', default=1),
53 ))
54 if spec:
55 arg_spec.update(spec)
56 return arg_spec
57
58
59 def basic_auth_argument_spec(spec=None):
60 arg_spec = (dict(
61 api_username=dict(type='str'),
62 api_password=dict(type='str', no_log=True),
63 api_url=dict(type='str'),
64 validate_certs=dict(type='bool', default=True)
65 ))
66 if spec:
67 arg_spec.update(spec)
68 return arg_spec
69
70
71 def rate_limit(rate=None, rate_limit=None):
72 """rate limiting decorator"""
73 minrate = None
74 if rate is not None and rate_limit is not None:
75 minrate = float(rate_limit) / float(rate)
76
77 def wrapper(f):
78 last = [0.0]
79
80 def ratelimited(*args, **kwargs):
81 if sys.version_info >= (3, 8):
82 real_time = time.process_time
83 else:
84 real_time = time.clock
85 if minrate is not None:
86 elapsed = real_time() - last[0]
87 left = minrate - elapsed
88 if left > 0:
89 time.sleep(left)
90 last[0] = real_time()
91 ret = f(*args, **kwargs)
92 return ret
93
94 return ratelimited
95 return wrapper
96
97
98 def retry(retries=None, retry_pause=1):
99 """Retry decorator"""
100 def wrapper(f):
101
102 def retried(*args, **kwargs):
103 retry_count = 0
104 if retries is not None:
105 ret = None
106 while True:
107 retry_count += 1
108 if retry_count >= retries:
109 raise Exception("Retry limit exceeded: %d" % retries)
110 try:
111 ret = f(*args, **kwargs)
112 except Exception:
113 pass
114 if ret:
115 break
116 time.sleep(retry_pause)
117 return ret
118
119 return retried
120 return wrapper
121
122
123 def generate_jittered_backoff(retries=10, delay_base=3, delay_threshold=60):
124 """The "Full Jitter" backoff strategy.
125
126 Ref: https://www.awsarchitectureblog.com/2015/03/backoff.html
127
128 :param retries: The number of delays to generate.
129 :param delay_base: The base time in seconds used to calculate the exponential backoff.
130 :param delay_threshold: The maximum time in seconds for any delay.
131 """
132 for retry in range(0, retries):
133 yield secrets.randbelow(min(delay_threshold, delay_base * 2 ** retry))
134
135
136 def retry_never(exception_or_result):
137 return False
138
139
140 def retry_with_delays_and_condition(backoff_iterator, should_retry_error=None):
141 """Generic retry decorator.
142
143 :param backoff_iterator: An iterable of delays in seconds.
144 :param should_retry_error: A callable that takes an exception of the decorated function and decides whether to retry or not (returns a bool).
145 """
146 def _emit_isolated_iterator_copies(original_iterator): # type: (t.Iterable[t.Any]) -> t.Generator
147 # Ref: https://stackoverflow.com/a/30232619/595220
148 _copiable_iterator, _first_iterator_copy = itertools.tee(original_iterator)
149 yield _first_iterator_copy
150 while True:
151 yield copy.copy(_copiable_iterator)
152 backoff_iterator_generator = _emit_isolated_iterator_copies(backoff_iterator)
153 del backoff_iterator # prevent accidental use elsewhere
154
155 if should_retry_error is None:
156 should_retry_error = retry_never
157
158 def function_wrapper(function):
159 @functools.wraps(function)
160 def run_function(*args, **kwargs):
161 """This assumes the function has not already been called.
162 If backoff_iterator is empty, we should still run the function a single time with no delay.
163 """
164 call_retryable_function = functools.partial(function, *args, **kwargs)
165
166 for delay in next(backoff_iterator_generator):
167 try:
168 return call_retryable_function()
169 except Exception as e:
170 if not should_retry_error(e):
171 raise
172 time.sleep(delay)
173
174 # Only or final attempt
175 return call_retryable_function()
176 return run_function
177 return function_wrapper