Debian Codegraph @

ansible_collections/community/hrobot/plugins/module_utils/api.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2025 Felix Fontein <[email protected]>
4 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
5 # SPDX-License-Identifier: BSD-2-Clause
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 import sys
11
12 from ansible.module_utils.common.text.converters import to_native
13 from ansible.module_utils.urls import fetch_url
14
15 import time
16
17 from ansible_collections.community.hrobot.plugins.module_utils.common import ( # pylint: disable=unused-import
18 CheckDoneTimeoutException,
19 )
20
21 try:
22 from urllib.parse import urlencode
23 except ImportError:
24 # Python 2.x fallback:
25 from urllib import urlencode
26
27
28 API_DEFAULT_ARGUMENT_SPEC = dict(
29 hetzner_token=dict(type='str', required=True, no_log=True),
30 rate_limit_retry_timeout=dict(type='int', default=-1),
31 )
32
33 _API_DEFAULT_ARGUMENT_SPEC_COMPAT = dict(
34 hetzner_token=dict(type='str', required=False, no_log=True),
35 )
36
37 # The API endpoint is fixed.
38 API_BASE_URL = "https://api.hetzner.com"
39
40
41 _RATE_LIMITING_ERROR = 'rate_limit_exceeded'
42 _RATE_LIMITING_START_DELAY = 5
43
44
45 def format_api_error_msg(error, rate_limit_timeout=None, url=None, method=None):
46 # Reference: https://docs.hetzner.cloud/reference/hetzner#errors
47 prefix = 'Request failed'
48 if url is not None and method is not None:
49 prefix = 'Request {0} {1} failed'.format(method, url)
50 msg = '{0}: [{1}] {2}'.format(
51 prefix,
52 error['code'],
53 error['message'],
54 )
55 if error.get('details'):
56 msg += ". Details: {0}".format(error['details'])
57 return msg
58
59
60 def raw_api_fetch_url_json(
61 module,
62 url,
63 method='GET',
64 timeout=10,
65 data=None,
66 headers=None,
67 accept_errors=None,
68 # allow_empty_result=False,
69 # allowed_empty_result_status_codes=(),
70 rate_limit_timeout=None,
71 ):
72 '''
73 Make general request to Hetzner's API.
74 Does not handle rate limiting especially.
75 '''
76 actual_headers = {
77 "Authorization": "Bearer {0}".format(module.params['hetzner_token']),
78 }
79 if headers:
80 actual_headers.update(headers)
81 accept_errors = accept_errors or ()
82
83 resp, info = fetch_url(module, url, method=method, timeout=timeout, data=data, headers=actual_headers)
84 try:
85 # In Python 2, reading from a closed response yields a TypeError.
86 # In Python 3, read() simply returns ''
87 if sys.version_info[0] > 2 and resp.closed:
88 raise TypeError
89 content = resp.read()
90 except (AttributeError, TypeError):
91 content = info.pop('body', None)
92
93 if not content:
94 # if allow_empty_result and info.get('status') in allowed_empty_result_status_codes:
95 # return None, info, None
96 module.fail_json(
97 msg='Cannot retrieve content from {0} {1}, HTTP status code {2} ({3})'.format(
98 method, url, info.get('status'), info.get('msg')
99 )
100 )
101
102 try:
103 result = module.from_json(content.decode('utf8'))
104 if 'error' in result:
105 if result['error']['code'] in accept_errors:
106 return result, info, result['error']['code']
107 module.fail_json(
108 msg=format_api_error_msg(result['error'], rate_limit_timeout=rate_limit_timeout, url=url, method=method),
109 error=result['error'],
110 )
111 return result, info, None
112 except ValueError:
113 module.fail_json(msg='Cannot decode content retrieved from {0} {1}'.format(method, url))
114
115
116 def _handle_rate_limit(accept_errors, check_done_timeout, call):
117 original_accept_errors, accept_errors = accept_errors, accept_errors or ()
118 check_done_delay = _RATE_LIMITING_START_DELAY
119 if _RATE_LIMITING_ERROR in accept_errors or check_done_timeout == 0:
120 return call(original_accept_errors, None)
121 accept_errors = [_RATE_LIMITING_ERROR] + list(accept_errors)
122
123 start_time = time.time()
124 first = True
125 timeout = False
126 while True:
127 if first:
128 elapsed = 0
129 first = False
130 else:
131 elapsed = (time.time() - start_time)
132 if check_done_timeout > 0:
133 left_time = check_done_timeout - elapsed
134 wait = max(min(check_done_delay, left_time), 0)
135 timeout = left_time <= check_done_delay
136 else:
137 wait = check_done_delay
138 time.sleep(wait)
139 result, info, error = call(
140 original_accept_errors if timeout else accept_errors,
141 elapsed,
142 )
143 if error != _RATE_LIMITING_ERROR:
144 return result, info, error
145 # TODO: is there a hint how much time we should wait?
146 # If yes, adjust check_done_delay accordingly!
147
148
149 def api_fetch_url_json(
150 module,
151 url,
152 method='GET',
153 timeout=10,
154 data=None,
155 headers=None,
156 accept_errors=None,
157 # allow_empty_result=False,
158 # allowed_empty_result_status_codes=(),
159 ):
160 '''
161 Make general request to Hetzner's API.
162 '''
163 def call(accept_errors_, rate_limit_timeout):
164 return raw_api_fetch_url_json(
165 module,
166 url,
167 method=method,
168 timeout=timeout,
169 data=data,
170 headers=headers,
171 accept_errors=accept_errors_,
172 # allow_empty_result=allow_empty_result,
173 # allowed_empty_result_status_codes=allowed_empty_result_status_codes,
174 rate_limit_timeout=rate_limit_timeout,
175 )
176
177 return _handle_rate_limit(
178 accept_errors,
179 module.params['rate_limit_retry_timeout'],
180 call,
181 )
182
183
184 def deterministic_urlencode(data, **kwargs):
185 """
186 Same as urlencode(), but the keys are sorted lexicographically.
187 """
188 result = []
189 for key, value in sorted(data.items()):
190 result.append(urlencode({key: value}, **kwargs))
191 return '&'.join(result)
192
193
194 def api_fetch_url_json_list(
195 module,
196 url,
197 data_key,
198 method='GET',
199 timeout=10,
200 headers=None,
201 accept_errors=None,
202 page_size=100,
203 ):
204 '''
205 Completely request a paginated list from Hetzner's API.
206 '''
207 page = 1
208 last_page = None
209 result_list = []
210 while page is not None and (last_page is None or last_page >= page):
211 page_url = '{0}{1}{2}'.format(url, '&' if '?' in url else '?', deterministic_urlencode({"page": str(page), "per_page": page_size}))
212 result, dummy, error = api_fetch_url_json(
213 module,
214 page_url,
215 method=method,
216 timeout=timeout,
217 headers=headers,
218 accept_errors=accept_errors,
219 )
220 # TODO: add coverage!
221 if error: # pragma: no cover
222 return result_list, error # pragma: no cover
223 if isinstance(result.get(data_key), list):
224 result_list += result[data_key]
225 if isinstance(result.get("meta"), dict) and isinstance(result["meta"].get("pagination"), dict):
226 pagination = result["meta"]["pagination"]
227 if isinstance(pagination.get("last_page"), int):
228 last_page = pagination["last_page"]
229 if isinstance(pagination.get("next_page"), int):
230 page = pagination["next_page"]
231 else:
232 page += 1
233 elif not result.get(data_key):
234 break
235 else:
236 page += 1
237 return result_list, None
238
239
240 def api_fetch_url_json_with_retries(module, url, check_done_callback, check_done_delay=10, check_done_timeout=180, skip_first=False, **kwargs):
241 '''
242 Make general request to Hetzner's API, with retries until a condition is satisfied.
243
244 The condition is tested by calling ``check_done_callback(result, error)``. If it is not satisfied,
245 it will be retried with delays ``check_done_delay`` (in seconds) until a total timeout of
246 ``check_done_timeout`` (in seconds) since the time the first request is started is reached.
247
248 If ``skip_first`` is specified, will assume that a first call has already been made and will
249 directly start with waiting.
250 '''
251 start_time = time.time()
252 if not skip_first: # pragma: no cover
253 raise AssertionError("Code path not yet available") # pragma: no cover
254 # result, error = api_fetch_url_json(module, url, **kwargs)
255 # if check_done_callback(result, error):
256 # return result, error
257 while True:
258 elapsed = (time.time() - start_time)
259 left_time = check_done_timeout - elapsed
260 time.sleep(max(min(check_done_delay, left_time), 0))
261 result, info, error = api_fetch_url_json(module, url, **kwargs)
262 if check_done_callback(result, info, error):
263 return result, info, error
264 if left_time < check_done_delay:
265 raise CheckDoneTimeoutException(result, error)
266
267
268 class ApplyActionError(Exception):
269 def __init__(self, msg, extracted_ids=None):
270 super(ApplyActionError, self).__init__(msg)
271 self.extracted_ids = extracted_ids or {}
272
273
274 def api_apply_action(
275 module,
276 action_url,
277 action_data,
278 action_check_url_provider,
279 method='POST',
280 check_done_delay=10,
281 check_done_timeout=180,
282 accept_errors=None,
283 ):
284 headers = {"Content-type": "application/json"} if action_data is not None else {}
285 result, dummy, error = api_fetch_url_json(
286 module,
287 action_url,
288 data=module.jsonify(action_data) if action_data is not None else None,
289 headers=headers,
290 method=method,
291 accept_errors=accept_errors,
292 )
293 if error:
294 return None, error
295 action_id = result["action"]["id"]
296 extracted_ids = {
297 res["type"]: res["id"] for res in result["action"]["resources"] or [] if res.get("id") is not None and res.get("type")
298 }
299 if result["action"]["status"] == "running":
300 this_action_url = action_check_url_provider(action_id)
301
302 def action_done_callback(result_, info_, error_):
303 if error_ is not None: # pragma: no cover
304 return True # pragma: no cover
305 return result_["action"]["status"] != "running"
306
307 try:
308 result, dummy, dummy2 = api_fetch_url_json_with_retries(
309 module, this_action_url, action_done_callback, check_done_delay=1, check_done_timeout=60, skip_first=True,
310 )
311 except CheckDoneTimeoutException as dummy:
312 raise ApplyActionError("Timeout", extracted_ids=extracted_ids)
313 error = result["action"].get("error")
314 if isinstance(error, dict):
315 raise ApplyActionError('[{0}] {1}'.format(to_native(error.get("code")), to_native(error.get("message"))), extracted_ids=extracted_ids)
316 elif result["action"]["status"] == "error":
317 raise ApplyActionError('Unknown error', extracted_ids=extracted_ids)
318 return extracted_ids, None