Debian Codegraph @

ansible_collections/amazon/aws/plugins/module_utils/waiter.py

raw
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 # import typing
13 from copy import deepcopy
14
15 try:
16 import botocore.waiter as botocore_waiter
17
18 import_error = None
19 except ImportError as e:
20 botocore_waiter = None
21 import_error = e
22
23
24 class BaseWaiterFactory:
25 """
26 A helper class used for creating additional waiters.
27 Unlike the waiters available directly from botocore these waiters will
28 automatically retry on common (temporary) AWS failures.
29
30 This class should be treated as an abstract class and subclassed before use.
31 A subclass should:
32 - override _BaseWaiterFactory._waiter_model_data to return the data defining
33 the waiter
34
35 Usage:
36 waiter_factory = BaseWaiterFactory()
37 waiter = waiter_factory.get_waiter(client, 'my_waiter_name')
38 waiter.wait(**params)
39 """
40
41 def __init__(self):
42 if not botocore_waiter:
43 return
44
45 # While it would be nice to supliment this with the upstream data,
46 # unfortunately client doesn't have a public method for getting the
47 # waiter configs.
48 data = self._inject_ratelimit_retries(self._waiter_model_data)
49 self._model = botocore_waiter.WaiterModel(
50 waiter_config=dict(version=2, waiters=data),
51 )
52
53 @property
54 def _waiter_model_data(self):
55 r"""
56 Subclasses should override this method to return a dictionary mapping
57 waiter names to the waiter definition.
58
59 This data is similar to the data found in botocore's waiters-2.json
60 files (for example: botocore/botocore/data/ec2/2016-11-15/waiters-2.json)
61 with two differences:
62 1) Waiter names do not have transformations applied during lookup
63 2) Only the 'waiters' data is required, the data is assumed to be
64 version 2
65
66 for example:
67
68 @property
69 def _waiter_model_data(self):
70 return dict(
71 tgw_attachment_deleted=dict(
72 operation='DescribeTransitGatewayAttachments',
73 delay=5, maxAttempts=120,
74 acceptors=[
75 dict(state='retry', matcher='pathAll', expected='deleting', argument='TransitGatewayAttachments[].State'),
76 dict(state='success', matcher='pathAll', expected='deleted', argument='TransitGatewayAttachments[].State'),
77 dict(state='success', matcher='path', expected=True, argument='length(TransitGatewayAttachments[]) == `0`'),
78 dict(state='success', matcher='error', expected='InvalidRouteTableID.NotFound'),
79 ]
80 ),
81 )
82
83 or
84
85 @property
86 def _waiter_model_data(self):
87 return {
88 "instance_exists": {
89 "delay": 5,
90 "maxAttempts": 40,
91 "operation": "DescribeInstances",
92 "acceptors": [
93 {
94 "matcher": "path",
95 "expected": true,
96 "argument": "length(Reservations[]) > `0`",
97 "state": "success"
98 },
99 {
100 "matcher": "error",
101 "expected": "InvalidInstanceID.NotFound",
102 "state": "retry"
103 }
104 ]
105 },
106 }
107 """
108
109 return dict()
110
111 def _inject_ratelimit_retries(self, model_data):
112 extra_retries = [
113 "RequestLimitExceeded",
114 "Unavailable",
115 "ServiceUnavailable",
116 "InternalFailure",
117 "InternalError",
118 "TooManyRequestsException",
119 "Throttling",
120 ]
121
122 acceptors = []
123 for error in extra_retries:
124 acceptors.append(dict(state="retry", matcher="error", expected=error))
125
126 _model_data = deepcopy(model_data)
127 for waiter_name in _model_data:
128 _model_data[waiter_name]["acceptors"].extend(acceptors)
129
130 return _model_data
131
132 def get_waiter(self, client, waiter_name: str):
133 if import_error:
134 # We shouldn't get here, but if someone's trying to use this without botocore installed
135 # let's re-raise the actual import error
136 raise import_error
137
138 waiters = self._model.waiter_names
139 if waiter_name not in waiters:
140 raise NotImplementedError(f"Unable to find waiter {waiter_name}. Available_waiters: {waiters}")
141 return botocore_waiter.create_waiter_with_client(
142 waiter_name,
143 self._model,
144 client,
145 )
146
147
148 def custom_waiter_config(timeout: int, default_pause: int = 2):
149 """
150 Generates the waiter_config dict that allows configuring a custom wait_timeout
151
152 Where the pause and the timeouts aren't perfectly divisible, this will default to waiting
153 slightly longer than the configured timeout so that we give at least the timeout time for a
154 change to happen.
155 """
156
157 pause = default_pause
158
159 # Do something sensible when the user's passed a short timeout, but our default pause wouldn't
160 # have allowed any retries
161 if timeout < (default_pause * 3):
162 pause = max(1, timeout // 3)
163
164 attempts = 1 + (timeout // pause)
165
166 if (attempts - 1) * pause < timeout:
167 attempts += 1
168
169 return dict(Delay=pause, MaxAttempts=attempts)