| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: Ansible Project |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
# |
| 7 |
# Note: This code should probably live in amazon.aws rather than community.aws. |
| 8 |
# However, for the sake of getting something into a useful shape first, it makes |
| 9 |
# sense for it to start life in community.aws. |
| 10 |
# |
| 11 |
|
| 12 |
from copy import deepcopy |
| 13 |
from functools import wraps |
| 14 |
|
| 15 |
try: |
| 16 |
import botocore |
| 17 |
except ImportError: |
| 18 |
pass # Handled by AnsibleAWSModule |
| 19 |
|
| 20 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 21 |
|
| 22 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict |
| 23 |
|
| 24 |
|
| 25 |
class BaseWaiterFactory: |
| 26 |
""" |
| 27 |
A helper class used for creating additional waiters. |
| 28 |
Unlike the waiters available directly from botocore these waiters will |
| 29 |
automatically retry on common (temporary) AWS failures. |
| 30 |
|
| 31 |
This class should be treated as an abstract class and subclassed before use. |
| 32 |
A subclass should: |
| 33 |
- create the necessary client to pass to BaseWaiterFactory.__init__ |
| 34 |
- override _BaseWaiterFactory._waiter_model_data to return the data defining |
| 35 |
the waiter |
| 36 |
|
| 37 |
Usage: |
| 38 |
waiter_factory = BaseWaiterFactory(module, client) |
| 39 |
waiter = waiters.get_waiter('my_waiter_name') |
| 40 |
waiter.wait(**params) |
| 41 |
""" |
| 42 |
|
| 43 |
module = None |
| 44 |
client = None |
| 45 |
|
| 46 |
def __init__(self, module, client): |
| 47 |
self.module = module |
| 48 |
self.client = client |
| 49 |
# While it would be nice to supliment this with the upstream data, |
| 50 |
# unfortunately client doesn't have a public method for getting the |
| 51 |
# waiter configs. |
| 52 |
data = self._inject_ratelimit_retries(self._waiter_model_data) |
| 53 |
self._model = botocore.waiter.WaiterModel( |
| 54 |
waiter_config=dict(version=2, waiters=data), |
| 55 |
) |
| 56 |
|
| 57 |
@property |
| 58 |
def _waiter_model_data(self): |
| 59 |
r""" |
| 60 |
Subclasses should override this method to return a dictionary mapping |
| 61 |
waiter names to the waiter definition. |
| 62 |
|
| 63 |
This data is similar to the data found in botocore's waiters-2.json |
| 64 |
files (for example: botocore/botocore/data/ec2/2016-11-15/waiters-2.json) |
| 65 |
with two differences: |
| 66 |
1) Waiter names do not have transformations applied during lookup |
| 67 |
2) Only the 'waiters' data is required, the data is assumed to be |
| 68 |
version 2 |
| 69 |
|
| 70 |
for example: |
| 71 |
|
| 72 |
@property |
| 73 |
def _waiter_model_data(self): |
| 74 |
return dict( |
| 75 |
tgw_attachment_deleted=dict( |
| 76 |
operation='DescribeTransitGatewayAttachments', |
| 77 |
delay=5, maxAttempts=120, |
| 78 |
acceptors=[ |
| 79 |
dict(state='retry', matcher='pathAll', expected='deleting', argument='TransitGatewayAttachments[].State'), |
| 80 |
dict(state='success', matcher='pathAll', expected='deleted', argument='TransitGatewayAttachments[].State'), |
| 81 |
dict(state='success', matcher='path', expected=True, argument='length(TransitGatewayAttachments[]) == `0`'), |
| 82 |
dict(state='success', matcher='error', expected='InvalidRouteTableID.NotFound'), |
| 83 |
] |
| 84 |
), |
| 85 |
) |
| 86 |
|
| 87 |
or |
| 88 |
|
| 89 |
@property |
| 90 |
def _waiter_model_data(self): |
| 91 |
return { |
| 92 |
"instance_exists": { |
| 93 |
"delay": 5, |
| 94 |
"maxAttempts": 40, |
| 95 |
"operation": "DescribeInstances", |
| 96 |
"acceptors": [ |
| 97 |
{ |
| 98 |
"matcher": "path", |
| 99 |
"expected": true, |
| 100 |
"argument": "length(Reservations[]) > `0`", |
| 101 |
"state": "success" |
| 102 |
}, |
| 103 |
{ |
| 104 |
"matcher": "error", |
| 105 |
"expected": "InvalidInstanceID.NotFound", |
| 106 |
"state": "retry" |
| 107 |
} |
| 108 |
] |
| 109 |
}, |
| 110 |
} |
| 111 |
""" |
| 112 |
|
| 113 |
return dict() |
| 114 |
|
| 115 |
def _inject_ratelimit_retries(self, model): |
| 116 |
extra_retries = [ |
| 117 |
"RequestLimitExceeded", |
| 118 |
"Unavailable", |
| 119 |
"ServiceUnavailable", |
| 120 |
"InternalFailure", |
| 121 |
"InternalError", |
| 122 |
"TooManyRequestsException", |
| 123 |
"Throttling", |
| 124 |
] |
| 125 |
|
| 126 |
acceptors = [] |
| 127 |
for error in extra_retries: |
| 128 |
acceptors.append(dict(state="retry", matcher="error", expected=error)) |
| 129 |
|
| 130 |
_model = deepcopy(model) |
| 131 |
for waiter in _model: |
| 132 |
_model[waiter]["acceptors"].extend(acceptors) |
| 133 |
|
| 134 |
return _model |
| 135 |
|
| 136 |
def get_waiter(self, waiter_name): |
| 137 |
waiters = self._model.waiter_names |
| 138 |
if waiter_name not in waiters: |
| 139 |
self.module.fail_json(f"Unable to find waiter {waiter_name}. Available_waiters: {waiters}") |
| 140 |
return botocore.waiter.create_waiter_with_client( |
| 141 |
waiter_name, |
| 142 |
self._model, |
| 143 |
self.client, |
| 144 |
) |
| 145 |
|
| 146 |
|
| 147 |
class Boto3Mixin: |
| 148 |
@staticmethod |
| 149 |
def aws_error_handler(description): |
| 150 |
r""" |
| 151 |
A simple wrapper that handles the usual botocore exceptions and exits |
| 152 |
with module.fail_json_aws. Designed to be used with BaseResourceManager. |
| 153 |
Assumptions: |
| 154 |
1) First argument (usually `self` of method being wrapped will have a |
| 155 |
'module' attribute which is an AnsibleAWSModule |
| 156 |
2) First argument of method being wrapped will have an |
| 157 |
_extra_error_output() method which takes no arguments and returns a |
| 158 |
dictionary of extra parameters to be returned in the event of a |
| 159 |
botocore exception. |
| 160 |
Parameters: |
| 161 |
description (string): In the event of a botocore exception the error |
| 162 |
message will be 'Failed to {DESCRIPTION}'. |
| 163 |
|
| 164 |
Example Usage: |
| 165 |
class ExampleClass(Boto3Mixin): |
| 166 |
def __init__(self, module) |
| 167 |
self.module = module |
| 168 |
self._get_client() |
| 169 |
|
| 170 |
@Boto3Mixin.aws_error_handler("connect to AWS") |
| 171 |
def _get_client(self): |
| 172 |
self.client = self.module.client('ec2') |
| 173 |
|
| 174 |
@Boto3Mixin.aws_error_handler("describe EC2 instances") |
| 175 |
def _do_something(**params): |
| 176 |
return self.client.describe_instances(**params) |
| 177 |
""" |
| 178 |
|
| 179 |
def wrapper(func): |
| 180 |
@wraps(func) |
| 181 |
def handler(_self, *args, **kwargs): |
| 182 |
extra_ouput = _self._extra_error_output() |
| 183 |
try: |
| 184 |
return func(_self, *args, **kwargs) |
| 185 |
except botocore.exceptions.WaiterError as e: |
| 186 |
_self.module.fail_json_aws(e, msg=f"Failed waiting for {description}", **extra_ouput) |
| 187 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 188 |
_self.module.fail_json_aws(e, msg=f"Failed to {description}", **extra_ouput) |
| 189 |
|
| 190 |
return handler |
| 191 |
|
| 192 |
return wrapper |
| 193 |
|
| 194 |
def _normalize_boto3_resource(self, resource, add_tags=False): |
| 195 |
r""" |
| 196 |
Performs common boto3 resource to Ansible resource conversion. |
| 197 |
`resource['Tags']` will by default be converted from the boto3 tag list |
| 198 |
format to a simple dictionary. |
| 199 |
Parameters: |
| 200 |
resource (dict): The boto3 style resource to convert to the normal Ansible |
| 201 |
format (snake_case). |
| 202 |
add_tags (bool): When `true`, if a resource does not have 'Tags' property |
| 203 |
the returned resource will have tags set to an empty |
| 204 |
dictionary. |
| 205 |
""" |
| 206 |
if resource is None: |
| 207 |
return None |
| 208 |
|
| 209 |
tags = resource.get("Tags", None) |
| 210 |
if tags: |
| 211 |
tags = boto3_tag_list_to_ansible_dict(tags) |
| 212 |
elif add_tags or tags is not None: |
| 213 |
tags = {} |
| 214 |
|
| 215 |
normalized_resource = camel_dict_to_snake_dict(resource) |
| 216 |
if tags is not None: |
| 217 |
normalized_resource["tags"] = tags |
| 218 |
return normalized_resource |
| 219 |
|
| 220 |
def _extra_error_output(self): |
| 221 |
# In the event of an error it can be helpful to ouput things like the |
| 222 |
# 'name'/'arn' of a resource. |
| 223 |
return dict() |
| 224 |
|
| 225 |
|
| 226 |
class BaseResourceManager(Boto3Mixin): |
| 227 |
def __init__(self, module): |
| 228 |
r""" |
| 229 |
Parameters: |
| 230 |
module (AnsibleAWSModule): An Ansible module. |
| 231 |
""" |
| 232 |
self.module = module |
| 233 |
self.changed = False |
| 234 |
self.original_resource = dict() |
| 235 |
self.updated_resource = dict() |
| 236 |
self._resource_updates = dict() |
| 237 |
self._preupdate_resource = dict() |
| 238 |
self._wait = True |
| 239 |
self._wait_timeout = None |
| 240 |
super(BaseResourceManager, self).__init__() |
| 241 |
|
| 242 |
def _merge_resource_changes(self, filter_immutable=True, creation=False): |
| 243 |
""" |
| 244 |
Merges the contents of the 'pre_update' resource and metadata variables |
| 245 |
with the pending updates |
| 246 |
""" |
| 247 |
resource = deepcopy(self._preupdate_resource) |
| 248 |
resource.update(self._resource_updates) |
| 249 |
|
| 250 |
if filter_immutable: |
| 251 |
resource = self._filter_immutable_resource_attributes(resource) |
| 252 |
|
| 253 |
return resource |
| 254 |
|
| 255 |
def _filter_immutable_resource_attributes(self, resource): |
| 256 |
return deepcopy(resource) |
| 257 |
|
| 258 |
def _do_creation_wait(self, **params): |
| 259 |
pass |
| 260 |
|
| 261 |
def _do_deletion_wait(self, **params): |
| 262 |
pass |
| 263 |
|
| 264 |
def _do_update_wait(self, **params): |
| 265 |
pass |
| 266 |
|
| 267 |
@property |
| 268 |
def _waiter_config(self): |
| 269 |
params = dict() |
| 270 |
if self._wait_timeout: |
| 271 |
delay = min(5, self._wait_timeout) |
| 272 |
max_attempts = self._wait_timeout // delay |
| 273 |
config = dict(Delay=delay, MaxAttempts=max_attempts) |
| 274 |
params["WaiterConfig"] = config |
| 275 |
return params |
| 276 |
|
| 277 |
def _wait_for_deletion(self): |
| 278 |
if not self._wait: |
| 279 |
return |
| 280 |
params = self._waiter_config |
| 281 |
self._do_deletion_wait(**params) |
| 282 |
|
| 283 |
def _wait_for_creation(self): |
| 284 |
if not self._wait: |
| 285 |
return |
| 286 |
params = self._waiter_config |
| 287 |
self._do_creation_wait(**params) |
| 288 |
|
| 289 |
def _wait_for_update(self): |
| 290 |
if not self._wait: |
| 291 |
return |
| 292 |
params = self._waiter_config |
| 293 |
self._do_update_wait(**params) |
| 294 |
|
| 295 |
def _generate_updated_resource(self): |
| 296 |
""" |
| 297 |
Merges all pending changes into self.updated_resource |
| 298 |
Used during check mode where it's not possible to get and |
| 299 |
refresh the resource |
| 300 |
""" |
| 301 |
return self._merge_resource_changes(filter_immutable=False) |
| 302 |
|
| 303 |
# If you override _flush_update you're responsible for handling check_mode |
| 304 |
# If you override _do_update_resource you'll only be called if check_mode == False |
| 305 |
def _flush_create(self): |
| 306 |
changed = True |
| 307 |
|
| 308 |
if not self.module.check_mode: |
| 309 |
changed = self._do_create_resource() |
| 310 |
self._wait_for_creation() |
| 311 |
self._do_creation_wait() |
| 312 |
self.updated_resource = self.get_resource() |
| 313 |
else: # (CHECK MODE) |
| 314 |
self.updated_resource = self._normalize_resource(self._generate_updated_resource()) |
| 315 |
|
| 316 |
self._resource_updates = dict() |
| 317 |
self.changed = changed |
| 318 |
return True |
| 319 |
|
| 320 |
def _check_updates_pending(self): |
| 321 |
if self._resource_updates: |
| 322 |
return True |
| 323 |
return False |
| 324 |
|
| 325 |
# If you override _flush_update you're responsible for handling check_mode |
| 326 |
# If you override _do_update_resource you'll only be called if there are |
| 327 |
# updated pending and check_mode == False |
| 328 |
def _flush_update(self): |
| 329 |
if not self._check_updates_pending(): |
| 330 |
self.updated_resource = self.original_resource |
| 331 |
return False |
| 332 |
|
| 333 |
if not self.module.check_mode: |
| 334 |
self._do_update_resource() |
| 335 |
self._wait_for_update() |
| 336 |
self.updated_resource = self.get_resource() |
| 337 |
else: # (CHECK_MODE) |
| 338 |
self.updated_resource = self._normalize_resource(self._generate_updated_resource()) |
| 339 |
|
| 340 |
self._resource_updates = dict() |
| 341 |
return True |
| 342 |
|
| 343 |
def flush_changes(self): |
| 344 |
if self.original_resource: |
| 345 |
return self._flush_update() |
| 346 |
else: |
| 347 |
return self._flush_create() |
| 348 |
|
| 349 |
def _set_resource_value(self, key, value, description=None, immutable=False): |
| 350 |
if value is None: |
| 351 |
return False |
| 352 |
if value == self._get_resource_value(key): |
| 353 |
return False |
| 354 |
if immutable and self.original_resource: |
| 355 |
if description is None: |
| 356 |
description = key |
| 357 |
self.module.fail_json(msg=f"{description} can not be updated after creation") |
| 358 |
self._resource_updates[key] = value |
| 359 |
self.changed = True |
| 360 |
return True |
| 361 |
|
| 362 |
def _get_resource_value(self, key, default=None): |
| 363 |
default_value = self._preupdate_resource.get(key, default) |
| 364 |
return self._resource_updates.get(key, default_value) |
| 365 |
|
| 366 |
def set_wait(self, wait): |
| 367 |
if wait is None: |
| 368 |
return False |
| 369 |
if wait == self._wait: |
| 370 |
return False |
| 371 |
|
| 372 |
self._wait = wait |
| 373 |
return True |
| 374 |
|
| 375 |
def set_wait_timeout(self, timeout): |
| 376 |
if timeout is None: |
| 377 |
return False |
| 378 |
if timeout == self._wait_timeout: |
| 379 |
return False |
| 380 |
|
| 381 |
self._wait_timeout = timeout |
| 382 |
return True |