Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_consul.py

raw
1 # Copyright (c) 2022, Håkon Lerring
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import copy
11 import json
12 import re
13 import typing as t
14 from http import HTTPStatus
15 from urllib import error as urllib_error
16 from urllib.parse import urlencode
17
18 from ansible.module_utils.urls import open_url
19
20 if t.TYPE_CHECKING:
21 from ansible.module_utils.basic import AnsibleModule
22
23
24 def get_consul_url(configuration):
25 return f"{configuration.scheme}://{configuration.host}:{configuration.port}/v1"
26
27
28 def get_auth_headers(configuration):
29 if configuration.token is None:
30 return {}
31 else:
32 return {"X-Consul-Token": configuration.token}
33
34
35 class RequestError(Exception):
36 def __init__(self, status, response_data=None):
37 self.status = status
38 self.response_data = response_data
39
40 def __str__(self):
41 if self.response_data is None:
42 # self.status is already the message (backwards compat)
43 return self.status
44 return f"HTTP {self.status}: {self.response_data}"
45
46
47 def handle_consul_response_error(response):
48 if response.status_code >= HTTPStatus.BAD_REQUEST: # 4xx and 5xx errors
49 raise RequestError(f"{response.status_code} {response.content}")
50
51
52 AUTH_ARGUMENTS_SPEC = dict(
53 host=dict(default="localhost"),
54 port=dict(type="int", default=8500),
55 scheme=dict(default="http"),
56 validate_certs=dict(type="bool", default=True),
57 token=dict(no_log=True),
58 ca_path=dict(),
59 )
60
61
62 def camel_case_key(key):
63 parts = []
64 for part in key.split("_"):
65 if part in {"id", "ttl", "jwks", "jwt", "oidc", "iam", "sts"}:
66 parts.append(part.upper())
67 else:
68 parts.append(part.capitalize())
69 return "".join(parts)
70
71
72 def validate_check(check):
73 validate_duration_keys = ["Interval", "Ttl", "Timeout"]
74 validate_tcp_regex = r"(?P<host>.*):(?P<port>(?:[0-9]+))$"
75 if check.get("Tcp") is not None:
76 match = re.match(validate_tcp_regex, check["Tcp"])
77 if not match:
78 raise Exception("tcp check must be in host:port format")
79 for duration in validate_duration_keys:
80 if duration in check and check[duration] is not None:
81 check[duration] = validate_duration(check[duration])
82
83
84 def validate_duration(duration):
85 if duration:
86 if not re.search(r"\d+(?:ns|us|ms|s|m|h)", duration):
87 duration = f"{duration}s"
88 return duration
89
90
91 STATE_PARAMETER = "state"
92 STATE_PRESENT = "present"
93 STATE_ABSENT = "absent"
94
95 OPERATION_READ = "read"
96 OPERATION_CREATE = "create"
97 OPERATION_UPDATE = "update"
98 OPERATION_DELETE = "remove"
99
100
101 def _normalize_params(params, arg_spec):
102 final_params = {}
103 for k, v in params.items():
104 if k not in arg_spec or v is None: # Alias
105 continue
106 spec = arg_spec[k]
107 if spec.get("type") == "list" and spec.get("elements") == "dict" and spec.get("options") and v:
108 v = [_normalize_params(d, spec["options"]) for d in v]
109 elif spec.get("type") == "dict" and spec.get("options") and v:
110 v = _normalize_params(v, spec["options"])
111 final_params[k] = v
112 return final_params
113
114
115 class _ConsulModule:
116 """Base class for Consul modules.
117
118 This class is considered private, till the API is fully fleshed out.
119 As such backwards incompatible changes can occur even in bugfix releases.
120 """
121
122 api_endpoint: str | None = None
123 unique_identifiers: list | None = None
124 result_key: str | None = None
125 create_only_fields: set[str] = set()
126 operational_attributes: set[str] = set()
127 params: dict[str, t.Any] = {}
128
129 def __init__(self, module: AnsibleModule) -> None:
130 self._module = module
131 self.params = _normalize_params(module.params, module.argument_spec)
132 self.api_params = {
133 k: camel_case_key(k) for k in self.params if k not in STATE_PARAMETER and k not in AUTH_ARGUMENTS_SPEC
134 }
135
136 self.operational_attributes.update({"CreateIndex", "CreateTime", "Hash", "ModifyIndex"})
137
138 def execute(self):
139 obj = self.read_object()
140
141 changed = False
142 diff = {}
143 if self.params[STATE_PARAMETER] == STATE_PRESENT:
144 obj_from_module = self.module_to_obj(obj is not None)
145 if obj is None:
146 operation = OPERATION_CREATE
147 new_obj = self.create_object(obj_from_module)
148 diff = {"before": {}, "after": new_obj}
149 changed = True
150 else:
151 operation = OPERATION_UPDATE
152 if self._needs_update(obj, obj_from_module):
153 new_obj = self.update_object(obj, obj_from_module)
154 diff = {"before": obj, "after": new_obj}
155 changed = True
156 else:
157 new_obj = obj
158 elif self.params[STATE_PARAMETER] == STATE_ABSENT:
159 operation = OPERATION_DELETE
160 if obj is not None:
161 self.delete_object(obj)
162 changed = True
163 diff = {"before": obj, "after": {}}
164 else:
165 diff = {"before": {}, "after": {}}
166 new_obj = None
167 else:
168 raise RuntimeError("Unknown state supplied.")
169
170 result = {"changed": changed}
171 if changed:
172 result["operation"] = operation
173 if self._module._diff:
174 result["diff"] = diff
175 if self.result_key:
176 result[self.result_key] = new_obj
177 self._module.exit_json(**result)
178
179 def module_to_obj(self, is_update):
180 obj = {}
181 for k, v in self.params.items():
182 result = self.map_param(k, v, is_update)
183 if result:
184 obj[result[0]] = result[1]
185 return obj
186
187 def map_param(self, k, v, is_update):
188 def helper(item):
189 return {camel_case_key(k): v for k, v in item.items()}
190
191 def needs_camel_case(k):
192 spec = self._module.argument_spec[k]
193 return (spec.get("type") == "list" and spec.get("elements") == "dict" and spec.get("options")) or (
194 spec.get("type") == "dict" and spec.get("options")
195 )
196
197 if k in self.api_params and v is not None:
198 if isinstance(v, dict) and needs_camel_case(k):
199 v = helper(v)
200 elif isinstance(v, (list, tuple)) and needs_camel_case(k):
201 v = [helper(i) for i in v]
202 if is_update and k in self.create_only_fields:
203 return
204 return camel_case_key(k), v
205
206 def _needs_update(self, api_obj, module_obj):
207 api_obj = copy.deepcopy(api_obj)
208 module_obj = copy.deepcopy(module_obj)
209 return self.needs_update(api_obj, module_obj)
210
211 def needs_update(self, api_obj, module_obj):
212 for k, v in module_obj.items():
213 if k not in api_obj:
214 return True
215 if api_obj[k] != v:
216 return True
217 return False
218
219 def prepare_object(self, existing, obj):
220 existing = {k: v for k, v in existing.items() if k not in self.operational_attributes}
221 for k, v in obj.items():
222 existing[k] = v
223 return existing
224
225 def id_from_obj(self, obj, camel_case=False):
226 def key_func(key):
227 return camel_case_key(key) if camel_case else key
228
229 if self.unique_identifiers:
230 for identifier in self.unique_identifiers:
231 identifier = key_func(identifier)
232 if identifier in obj:
233 return obj[identifier]
234 return None
235
236 def endpoint_url(self, operation, identifier=None):
237 if operation == OPERATION_CREATE:
238 return self.api_endpoint
239 elif identifier:
240 return f"{self.api_endpoint}/{identifier}"
241 raise RuntimeError("invalid arguments passed")
242
243 def read_object(self):
244 identifier = self.id_from_obj(self.params)
245 url = self.endpoint_url(OPERATION_READ, identifier)
246 try:
247 return self.get(url)
248 except RequestError as e:
249 if e.status == HTTPStatus.NOT_FOUND:
250 return
251 elif e.status == HTTPStatus.FORBIDDEN and b"ACL not found" in e.response_data:
252 return
253 raise
254
255 def create_object(self, obj):
256 if self._module.check_mode:
257 return obj
258 else:
259 url = self.endpoint_url(OPERATION_CREATE)
260 created_obj = self.put(url, data=self.prepare_object({}, obj))
261 if created_obj is None:
262 created_obj = self.read_object()
263 return created_obj
264
265 def update_object(self, existing, obj):
266 merged_object = self.prepare_object(existing, obj)
267 if self._module.check_mode:
268 return merged_object
269 else:
270 url = self.endpoint_url(OPERATION_UPDATE, self.id_from_obj(existing, camel_case=True))
271 updated_obj = self.put(url, data=merged_object)
272 if updated_obj is None:
273 updated_obj = self.read_object()
274 return updated_obj
275
276 def delete_object(self, obj):
277 if self._module.check_mode:
278 return {}
279 else:
280 url = self.endpoint_url(OPERATION_DELETE, self.id_from_obj(obj, camel_case=True))
281 return self.delete(url)
282
283 def _request(self, method, url_parts, data=None, params=None):
284 module_params = self.params
285
286 if not isinstance(url_parts, (tuple, list)):
287 url_parts = [url_parts]
288 if params:
289 # Remove values that are None
290 params = {k: v for k, v in params.items() if v is not None}
291
292 ca_path = module_params.get("ca_path")
293 base_url = f"{module_params['scheme']}://{module_params['host']}:{module_params['port']}/v1"
294 url = "/".join([base_url] + list(url_parts))
295
296 headers = {}
297 token = self.params.get("token")
298 if token:
299 headers["X-Consul-Token"] = token
300
301 try:
302 if data is not None:
303 data = json.dumps(data)
304 headers["Content-Type"] = "application/json"
305 if params:
306 url = f"{url}?{urlencode(params)}"
307 response = open_url(
308 url,
309 method=method,
310 data=data,
311 headers=headers,
312 validate_certs=module_params["validate_certs"],
313 ca_path=ca_path,
314 )
315 response_data = response.read()
316 status = response.status if hasattr(response, "status") else response.getcode()
317
318 except urllib_error.URLError as e:
319 if isinstance(e, urllib_error.HTTPError):
320 status = e.code
321 response_data = e.fp.read()
322 else:
323 self._module.fail_json(
324 msg=f"Could not connect to consul agent at {module_params['host']}:{module_params['port']}, error was {e}"
325 )
326 raise
327
328 if status >= HTTPStatus.BAD_REQUEST: # 4xx and 5xx errors
329 raise RequestError(status, response_data)
330
331 if response_data:
332 return json.loads(response_data)
333 return None
334
335 def get(self, url_parts, **kwargs):
336 return self._request("GET", url_parts, **kwargs)
337
338 def put(self, url_parts, **kwargs):
339 return self._request("PUT", url_parts, **kwargs)
340
341 def delete(self, url_parts, **kwargs):
342 return self._request("DELETE", url_parts, **kwargs)