| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright (c), Felix Fontein <[email protected]>, 2019 |
| 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, open_url |
| 14 |
|
| 15 |
try: |
| 16 |
from urllib.error import HTTPError |
| 17 |
except ImportError: |
| 18 |
# Python 2.x fallback: |
| 19 |
from urllib2 import HTTPError |
| 20 |
|
| 21 |
import json |
| 22 |
import time |
| 23 |
|
| 24 |
from ansible_collections.community.hrobot.plugins.module_utils.common import ( |
| 25 |
PluginException, |
| 26 |
CheckDoneTimeoutException, |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
ROBOT_DEFAULT_ARGUMENT_SPEC = dict( |
| 31 |
hetzner_user=dict(type='str', required=True), |
| 32 |
hetzner_password=dict(type='str', required=True, no_log=True), |
| 33 |
rate_limit_retry_timeout=dict(type='int', default=-1), |
| 34 |
) |
| 35 |
|
| 36 |
_ROBOT_DEFAULT_ARGUMENT_SPEC_COMPAT = dict( |
| 37 |
hetzner_user=dict(type='str', required=False), |
| 38 |
hetzner_password=dict(type='str', required=False, no_log=True), |
| 39 |
) |
| 40 |
|
| 41 |
_ROBOT_DEFAULT_ARGUMENT_SPEC_COMPAT_DEPRECATED = dict( |
| 42 |
hetzner_user=dict(type='str', required=False, removed_in_version="3.0.0", removed_from_collection="community.hrobot"), |
| 43 |
hetzner_password=dict(type='str', required=False, no_log=True, removed_in_version="3.0.0", removed_from_collection="community.hrobot"), |
| 44 |
) |
| 45 |
|
| 46 |
|
| 47 |
# The API endpoint is fixed. |
| 48 |
BASE_URL = "https://robot-ws.your-server.de" |
| 49 |
|
| 50 |
|
| 51 |
def get_x_www_form_urlenconded_dict_from_list(key, values): |
| 52 |
'''Return a dictionary with keys values''' |
| 53 |
if len(values) == 1: |
| 54 |
return {'{key}[]'.format(key=key): values[0]} |
| 55 |
else: |
| 56 |
return dict(('{key}[{index}]'.format(key=key, index=i), x) for i, x in enumerate(values)) |
| 57 |
|
| 58 |
|
| 59 |
def _format_list(obj): |
| 60 |
if not isinstance(obj, (list, tuple)): |
| 61 |
return to_native(obj) |
| 62 |
return [_format_list(e) for e in obj] |
| 63 |
|
| 64 |
|
| 65 |
_RATE_LIMITING_ERROR = 'RATE_LIMIT_EXCEEDED' |
| 66 |
_RATE_LIMITING_START_DELAY = 5 |
| 67 |
|
| 68 |
|
| 69 |
def format_error_msg(error, rate_limit_timeout=None): |
| 70 |
# Reference: https://robot.hetzner.com/doc/webservice/en.html#errors |
| 71 |
msg = 'Request failed: {0} {1} ({2})'.format( |
| 72 |
error['status'], |
| 73 |
error['code'], |
| 74 |
error['message'], |
| 75 |
) |
| 76 |
if error.get('missing'): |
| 77 |
msg += '. Missing input parameters: {0}'.format(_format_list(error['missing'])) |
| 78 |
if error.get('invalid'): |
| 79 |
msg += '. Invalid input parameters: {0}'.format(_format_list(error['invalid'])) |
| 80 |
if error.get('max_request') is not None: |
| 81 |
msg += '. Maximum allowed requests: {0}'.format(error['max_request']) |
| 82 |
if error.get('interval') is not None: |
| 83 |
msg += '. Time interval in seconds: {0}'.format(error['interval']) |
| 84 |
if rate_limit_timeout is not None and rate_limit_timeout > 0 and error['code'] == _RATE_LIMITING_ERROR: |
| 85 |
msg += '. Waited a total of {0:.1f} seconds for rate limit errors to go away'.format(rate_limit_timeout) |
| 86 |
return msg |
| 87 |
|
| 88 |
|
| 89 |
def raw_plugin_open_url_json(plugin, url, method='GET', timeout=10, data=None, headers=None, |
| 90 |
accept_errors=None, allow_empty_result=False, |
| 91 |
allowed_empty_result_status_codes=(200, 204), templar=None, |
| 92 |
rate_limit_timeout=None): |
| 93 |
''' |
| 94 |
Make general request to Hetzner's JSON robot API. |
| 95 |
Does not handle rate limiting especially. |
| 96 |
''' |
| 97 |
accept_errors = accept_errors or () |
| 98 |
user = plugin.get_option('hetzner_user') |
| 99 |
password = plugin.get_option('hetzner_password') |
| 100 |
if templar is not None: |
| 101 |
if templar.is_template(user): |
| 102 |
user = templar.template(variable=user) |
| 103 |
if templar.is_template(password): |
| 104 |
password = templar.template(variable=password) |
| 105 |
try: |
| 106 |
response = open_url( |
| 107 |
url, |
| 108 |
url_username=user, |
| 109 |
url_password=password, |
| 110 |
force_basic_auth=True, |
| 111 |
data=data, |
| 112 |
headers=headers, |
| 113 |
method=method, |
| 114 |
timeout=timeout, |
| 115 |
) |
| 116 |
status = response.code |
| 117 |
content = response.read() |
| 118 |
reason = response.reason |
| 119 |
except HTTPError as e: |
| 120 |
status = e.code |
| 121 |
reason = e.reason |
| 122 |
try: |
| 123 |
content = e.read() |
| 124 |
except AttributeError: |
| 125 |
content = b'' |
| 126 |
except Exception as e: |
| 127 |
raise PluginException('Failed request to Hetzner Robot server endpoint {0}: {1}'.format(url, e)) |
| 128 |
|
| 129 |
if not content: |
| 130 |
if allow_empty_result and status in allowed_empty_result_status_codes: |
| 131 |
return None, None |
| 132 |
raise PluginException( |
| 133 |
"Cannot retrieve content from {0} {1}, HTTP status code {2} ({3})".format( |
| 134 |
method, url, status, reason |
| 135 |
) |
| 136 |
) |
| 137 |
|
| 138 |
try: |
| 139 |
result = json.loads(content.decode('utf-8')) |
| 140 |
if 'error' in result: |
| 141 |
if result['error']['code'] in accept_errors: |
| 142 |
return result, result['error']['code'] |
| 143 |
raise PluginException(format_error_msg(result['error'], rate_limit_timeout=rate_limit_timeout)) |
| 144 |
return result, None |
| 145 |
except ValueError: |
| 146 |
raise PluginException('Cannot decode content retrieved from {0}'.format(url)) |
| 147 |
|
| 148 |
|
| 149 |
def raw_fetch_url_json(module, url, method='GET', timeout=10, data=None, headers=None, |
| 150 |
accept_errors=None, allow_empty_result=False, |
| 151 |
allowed_empty_result_status_codes=(200, 204), |
| 152 |
rate_limit_timeout=None): |
| 153 |
''' |
| 154 |
Make general request to Hetzner's JSON robot API. |
| 155 |
Does not handle rate limiting especially. |
| 156 |
''' |
| 157 |
accept_errors = accept_errors or () |
| 158 |
module.params['url_username'] = module.params['hetzner_user'] |
| 159 |
module.params['url_password'] = module.params['hetzner_password'] |
| 160 |
module.params['force_basic_auth'] = True |
| 161 |
resp, info = fetch_url(module, url, method=method, timeout=timeout, data=data, headers=headers) |
| 162 |
try: |
| 163 |
# In Python 2, reading from a closed response yields a TypeError. |
| 164 |
# In Python 3, read() simply returns '' |
| 165 |
if sys.version_info[0] > 2 and resp.closed: |
| 166 |
raise TypeError |
| 167 |
content = resp.read() |
| 168 |
except (AttributeError, TypeError): |
| 169 |
content = info.pop('body', None) |
| 170 |
|
| 171 |
if not content: |
| 172 |
if allow_empty_result and info.get('status') in allowed_empty_result_status_codes: |
| 173 |
return None, None |
| 174 |
module.fail_json( |
| 175 |
msg='Cannot retrieve content from {0} {1}, HTTP status code {2} ({3})'.format( |
| 176 |
method, url, info.get('status'), info.get('msg') |
| 177 |
) |
| 178 |
) |
| 179 |
|
| 180 |
try: |
| 181 |
result = module.from_json(content.decode('utf8')) |
| 182 |
if 'error' in result: |
| 183 |
if result['error']['code'] in accept_errors: |
| 184 |
return result, result['error']['code'] |
| 185 |
module.fail_json( |
| 186 |
msg=format_error_msg(result['error'], rate_limit_timeout=rate_limit_timeout), |
| 187 |
error=result['error'], |
| 188 |
) |
| 189 |
return result, None |
| 190 |
except ValueError: |
| 191 |
module.fail_json(msg='Cannot decode content retrieved from {0}'.format(url)) |
| 192 |
|
| 193 |
|
| 194 |
def _handle_rate_limit(accept_errors, check_done_timeout, call): |
| 195 |
original_accept_errors, accept_errors = accept_errors, accept_errors or () |
| 196 |
check_done_delay = _RATE_LIMITING_START_DELAY |
| 197 |
if _RATE_LIMITING_ERROR in accept_errors or check_done_timeout == 0: |
| 198 |
return call(original_accept_errors, None) |
| 199 |
accept_errors = [_RATE_LIMITING_ERROR] + list(accept_errors) |
| 200 |
|
| 201 |
start_time = time.time() |
| 202 |
first = True |
| 203 |
timeout = False |
| 204 |
while True: |
| 205 |
if first: |
| 206 |
elapsed = 0 |
| 207 |
first = False |
| 208 |
else: |
| 209 |
elapsed = (time.time() - start_time) |
| 210 |
if check_done_timeout > 0: |
| 211 |
left_time = check_done_timeout - elapsed |
| 212 |
wait = max(min(check_done_delay, left_time), 0) |
| 213 |
timeout = left_time <= check_done_delay |
| 214 |
else: |
| 215 |
wait = check_done_delay |
| 216 |
time.sleep(wait) |
| 217 |
result, error = call( |
| 218 |
original_accept_errors if timeout else accept_errors, |
| 219 |
elapsed, |
| 220 |
) |
| 221 |
if error != _RATE_LIMITING_ERROR: |
| 222 |
return result, error |
| 223 |
if result['error'].get('interval') and check_done_delay > result['error']['interval'] > 0: |
| 224 |
check_done_delay = result['error']['interval'] |
| 225 |
|
| 226 |
|
| 227 |
def plugin_open_url_json(plugin, url, method='GET', timeout=10, data=None, headers=None, |
| 228 |
accept_errors=None, allow_empty_result=False, |
| 229 |
allowed_empty_result_status_codes=(200, 204), templar=None): |
| 230 |
''' |
| 231 |
Make general request to Hetzner's JSON robot API. |
| 232 |
''' |
| 233 |
def call(accept_errors_, rate_limit_timeout): |
| 234 |
return raw_plugin_open_url_json( |
| 235 |
plugin, |
| 236 |
url, |
| 237 |
method=method, |
| 238 |
timeout=timeout, |
| 239 |
data=data, |
| 240 |
headers=headers, |
| 241 |
accept_errors=accept_errors_, |
| 242 |
allow_empty_result=allow_empty_result, |
| 243 |
allowed_empty_result_status_codes=allowed_empty_result_status_codes, |
| 244 |
templar=templar, |
| 245 |
rate_limit_timeout=rate_limit_timeout, |
| 246 |
) |
| 247 |
|
| 248 |
return _handle_rate_limit( |
| 249 |
accept_errors, |
| 250 |
plugin.get_option('rate_limit_retry_timeout'), |
| 251 |
call, |
| 252 |
) |
| 253 |
|
| 254 |
|
| 255 |
def fetch_url_json(module, url, method='GET', timeout=10, data=None, headers=None, |
| 256 |
accept_errors=None, allow_empty_result=False, |
| 257 |
allowed_empty_result_status_codes=(200, 204)): |
| 258 |
''' |
| 259 |
Make general request to Hetzner's JSON robot API. |
| 260 |
''' |
| 261 |
def call(accept_errors_, rate_limit_timeout): |
| 262 |
return raw_fetch_url_json( |
| 263 |
module, |
| 264 |
url, |
| 265 |
method=method, |
| 266 |
timeout=timeout, |
| 267 |
data=data, |
| 268 |
headers=headers, |
| 269 |
accept_errors=accept_errors_, |
| 270 |
allow_empty_result=allow_empty_result, |
| 271 |
allowed_empty_result_status_codes=allowed_empty_result_status_codes, |
| 272 |
rate_limit_timeout=rate_limit_timeout, |
| 273 |
) |
| 274 |
|
| 275 |
return _handle_rate_limit( |
| 276 |
accept_errors, |
| 277 |
module.params['rate_limit_retry_timeout'], |
| 278 |
call, |
| 279 |
) |
| 280 |
|
| 281 |
|
| 282 |
def fetch_url_json_with_retries(module, url, check_done_callback, check_done_delay=10, check_done_timeout=180, skip_first=False, **kwargs): |
| 283 |
''' |
| 284 |
Make general request to Hetzner's JSON robot API, with retries until a condition is satisfied. |
| 285 |
|
| 286 |
The condition is tested by calling ``check_done_callback(result, error)``. If it is not satisfied, |
| 287 |
it will be retried with delays ``check_done_delay`` (in seconds) until a total timeout of |
| 288 |
``check_done_timeout`` (in seconds) since the time the first request is started is reached. |
| 289 |
|
| 290 |
If ``skip_first`` is specified, will assume that a first call has already been made and will |
| 291 |
directly start with waiting. |
| 292 |
''' |
| 293 |
start_time = time.time() |
| 294 |
if not skip_first: |
| 295 |
result, error = fetch_url_json(module, url, **kwargs) |
| 296 |
if check_done_callback(result, error): |
| 297 |
return result, error |
| 298 |
while True: |
| 299 |
elapsed = (time.time() - start_time) |
| 300 |
left_time = check_done_timeout - elapsed |
| 301 |
time.sleep(max(min(check_done_delay, left_time), 0)) |
| 302 |
result, error = fetch_url_json(module, url, **kwargs) |
| 303 |
if check_done_callback(result, error): |
| 304 |
return result, error |
| 305 |
if left_time < check_done_delay: |
| 306 |
raise CheckDoneTimeoutException(result, error) |