Debian Codegraph @

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

raw
1 # Copyright (c), Google Inc, 2017
2 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
3 # SPDX-License-Identifier: BSD-2-Clause
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 re
11 import time
12 import traceback
13 import typing as t
14 from http import HTTPStatus
15
16 THIRD_LIBRARIES_IMP_ERR = None
17 try:
18 from keystoneauth1 import session
19 from keystoneauth1.adapter import Adapter
20 from keystoneauth1.identity import v3
21
22 HAS_THIRD_LIBRARIES = True
23 except ImportError:
24 THIRD_LIBRARIES_IMP_ERR = traceback.format_exc()
25 HAS_THIRD_LIBRARIES = False
26
27 from ansible.module_utils.basic import AnsibleModule, env_fallback, missing_required_lib
28 from ansible.module_utils.common.text.converters import to_text
29
30
31 class HwcModuleException(Exception):
32 def __init__(self, message: str) -> None:
33 super().__init__()
34
35 self._message = message
36
37 def __str__(self) -> str:
38 return f"[HwcClientException] message={self._message}"
39
40
41 class HwcClientException(Exception):
42 def __init__(self, code: int, message: str) -> None:
43 super().__init__()
44
45 self._code = code
46 self._message = message
47
48 def __str__(self) -> str:
49 msg = f" code={self._code}," if self._code != 0 else ""
50 return f"[HwcClientException]{msg} message={self._message}"
51
52
53 class HwcClientException404(HwcClientException):
54 def __init__(self, message: str) -> None:
55 super().__init__(404, message)
56
57 def __str__(self) -> str:
58 return f"[HwcClientException404] message={self._message}"
59
60
61 def session_method_wrapper(f):
62 def _wrap(self, url: str, *args, **kwargs):
63 try:
64 url = self.endpoint + url
65 r = f(self, url, *args, **kwargs)
66 except Exception as ex:
67 raise HwcClientException(0, f"Sending request failed, error={ex}") from ex
68
69 result = None
70 if r.content:
71 try:
72 result = r.json()
73 except Exception as ex:
74 raise HwcClientException(0, f"Parsing response to json failed, error: {ex}") from ex
75
76 code = r.status_code
77 if not (HTTPStatus.OK <= code < HTTPStatus.MULTIPLE_CHOICES): # not 2xx codes
78 msg = ""
79 for i in ["message", "error.message"]:
80 try:
81 msg = navigate_value(result, i)
82 break
83 except Exception:
84 pass
85 else:
86 msg = str(result)
87
88 if code == HTTPStatus.NOT_FOUND:
89 raise HwcClientException404(msg)
90
91 raise HwcClientException(code, msg)
92
93 return result
94
95 return _wrap
96
97
98 class _ServiceClient:
99 def __init__(self, client, endpoint: str, product):
100 self._client = client
101 self._endpoint = endpoint
102 self._default_header = {
103 "User-Agent": f"Huawei-Ansible-MM-{product}",
104 "Accept": "application/json",
105 }
106
107 @property
108 def endpoint(self) -> str:
109 return self._endpoint
110
111 @endpoint.setter
112 def endpoint(self, e: str) -> None:
113 self._endpoint = e
114
115 @session_method_wrapper
116 def get(self, url: str, body=None, header: dict[str, t.Any] | None = None, timeout=None):
117 return self._client.get(url, json=body, timeout=timeout, headers=self._header(header))
118
119 @session_method_wrapper
120 def post(self, url: str, body=None, header: dict[str, t.Any] | None = None, timeout=None):
121 return self._client.post(url, json=body, timeout=timeout, headers=self._header(header))
122
123 @session_method_wrapper
124 def delete(self, url: str, body=None, header: dict[str, t.Any] | None = None, timeout=None):
125 return self._client.delete(url, json=body, timeout=timeout, headers=self._header(header))
126
127 @session_method_wrapper
128 def put(self, url: str, body=None, header: dict[str, t.Any] | None = None, timeout=None):
129 return self._client.put(url, json=body, timeout=timeout, headers=self._header(header))
130
131 def _header(self, header: dict[str, t.Any] | None) -> dict[str, t.Any]:
132 if header and isinstance(header, dict):
133 for k, v in self._default_header.items():
134 if k not in header:
135 header[k] = v
136 else:
137 header = self._default_header
138
139 return header
140
141
142 class Config:
143 def __init__(self, module: AnsibleModule, product) -> None:
144 self._project_client = None
145 self._domain_client = None
146 self._module = module
147 self._product = product
148 self._endpoints: dict[str, t.Any] = {}
149
150 self._validate()
151 self._gen_provider_client()
152
153 @property
154 def module(self) -> AnsibleModule:
155 return self._module
156
157 def client(self, region, service_type, service_level):
158 c = self._project_client
159 if service_level == "domain":
160 c = self._domain_client
161
162 e = self._get_service_endpoint(c, service_type, region)
163
164 return _ServiceClient(c, e, self._product)
165
166 def _gen_provider_client(self):
167 m = self._module
168 p = {
169 "auth_url": m.params["identity_endpoint"],
170 "password": m.params["password"],
171 "username": m.params["user"],
172 "project_name": m.params["project"],
173 "user_domain_name": m.params["domain"],
174 "reauthenticate": True,
175 }
176
177 self._project_client = Adapter(session.Session(auth=v3.Password(**p)), raise_exc=False)
178
179 p.pop("project_name")
180 self._domain_client = Adapter(session.Session(auth=v3.Password(**p)), raise_exc=False)
181
182 def _get_service_endpoint(self, client, service_type, region):
183 k = f"{service_type}.{region if region else ''}"
184
185 if k in self._endpoints:
186 return self._endpoints.get(k)
187
188 url = None
189 try:
190 url = client.get_endpoint(service_type=service_type, region_name=region, interface="public")
191 except Exception as ex:
192 raise HwcClientException(0, f"Getting endpoint failed, error={ex}") from ex
193
194 if url == "":
195 raise HwcClientException(0, f"Cannot find the endpoint for {service_type}")
196
197 if url[-1] != "/":
198 url += "/"
199
200 self._endpoints[k] = url
201 return url
202
203 def _validate(self):
204 if not HAS_THIRD_LIBRARIES:
205 self.module.fail_json(msg=missing_required_lib("keystoneauth1"), exception=THIRD_LIBRARIES_IMP_ERR)
206
207
208 class HwcModule(AnsibleModule):
209 def __init__(self, *args, **kwargs):
210 arg_spec = kwargs.setdefault("argument_spec", {})
211
212 arg_spec.update(
213 dict(
214 identity_endpoint=dict(
215 required=True,
216 type="str",
217 fallback=(env_fallback, ["ANSIBLE_HWC_IDENTITY_ENDPOINT"]),
218 ),
219 user=dict(
220 required=True,
221 type="str",
222 fallback=(env_fallback, ["ANSIBLE_HWC_USER"]),
223 ),
224 password=dict(
225 required=True,
226 type="str",
227 no_log=True,
228 fallback=(env_fallback, ["ANSIBLE_HWC_PASSWORD"]),
229 ),
230 domain=dict(
231 required=True,
232 type="str",
233 fallback=(env_fallback, ["ANSIBLE_HWC_DOMAIN"]),
234 ),
235 project=dict(
236 required=True,
237 type="str",
238 fallback=(env_fallback, ["ANSIBLE_HWC_PROJECT"]),
239 ),
240 region=dict(
241 type="str",
242 fallback=(env_fallback, ["ANSIBLE_HWC_REGION"]),
243 ),
244 id=dict(type="str"),
245 )
246 )
247
248 super().__init__(*args, **kwargs)
249
250
251 class _DictComparison:
252 """This class takes in two dictionaries `a` and `b`.
253 These are dictionaries of arbitrary depth, but made up of standard
254 Python types only.
255 This differ will compare all values in `a` to those in `b`.
256 If value in `a` is None, always returns True, indicating
257 this value is no need to compare.
258 Note: On all lists, order does matter.
259 """
260
261 def __init__(self, request):
262 self.request = request
263
264 def __eq__(self, other):
265 return self._compare_dicts(self.request, other.request)
266
267 def __ne__(self, other):
268 return not self.__eq__(other)
269
270 def _compare_dicts(self, dict1, dict2):
271 if dict1 is None:
272 return True
273
274 if set(dict1.keys()) != set(dict2.keys()):
275 return False
276
277 return all(self._compare_value(dict1[k], dict2[k]) for k in dict1)
278
279 def _compare_lists(self, list1, list2):
280 """Takes in two lists and compares them."""
281 if list1 is None:
282 return True
283
284 if len(list1) != len(list2):
285 return False
286
287 return all(self._compare_value(l1, l2) for l1, l2 in zip(list1, list2))
288
289 def _compare_value(self, value1, value2):
290 """
291 return: True: value1 is same as value2, otherwise False.
292 """
293 if value1 is None:
294 return True
295
296 if not (value1 and value2):
297 return (not value1) and (not value2)
298
299 # Can assume non-None types at this point.
300 if isinstance(value1, list) and isinstance(value2, list):
301 return self._compare_lists(value1, value2)
302
303 elif isinstance(value1, dict) and isinstance(value2, dict):
304 return self._compare_dicts(value1, value2)
305
306 # Always use to_text values to avoid unicode issues.
307 return to_text(value1, errors="surrogate_or_strict") == to_text(value2, errors="surrogate_or_strict")
308
309
310 def wait_to_finish(target, pending, refresh, timeout, min_interval=1, delay=3):
311 is_last_time = False
312 not_found_times = 0
313 wait = 0
314
315 time.sleep(delay)
316
317 end = time.time() + timeout
318 while not is_last_time:
319 if time.time() > end:
320 is_last_time = True
321
322 obj, status = refresh()
323
324 if obj is None:
325 not_found_times += 1
326
327 if not_found_times > 10:
328 raise HwcModuleException(f"not found the object for {not_found_times} times")
329 else:
330 not_found_times = 0
331
332 if status in target:
333 return obj
334
335 if pending and status not in pending:
336 raise HwcModuleException(f"unexpected status({status}) occurred")
337
338 if not is_last_time:
339 wait *= 2
340 if wait < min_interval:
341 wait = min_interval
342 elif wait > 10:
343 wait = 10
344
345 time.sleep(wait)
346
347 raise HwcModuleException(f"async wait timeout after {timeout} seconds")
348
349
350 def navigate_value(data, index, array_index=None):
351 if array_index and (not isinstance(array_index, dict)):
352 raise HwcModuleException("array_index must be dict")
353
354 d = data
355 for n in range(len(index)):
356 if d is None:
357 return None
358
359 if not isinstance(d, dict):
360 raise HwcModuleException("can't navigate value from a non-dict object")
361
362 i = index[n]
363 if i not in d:
364 raise HwcModuleException(f"navigate value failed: key({i}) is not exist in dict")
365 d = d[i]
366
367 if not array_index:
368 continue
369
370 k = ".".join(index[: (n + 1)])
371 if k not in array_index:
372 continue
373
374 if d is None:
375 return None
376
377 if not isinstance(d, list):
378 raise HwcModuleException("can't navigate value from a non-list object")
379
380 j = array_index.get(k)
381 if j >= len(d):
382 raise HwcModuleException("navigate value failed: the index is out of list")
383 d = d[j]
384
385 return d
386
387
388 def build_path(module: AnsibleModule, path, kv=None):
389 if kv is None:
390 kv = dict()
391
392 v = {}
393 for p in re.findall(r"{[^/]*}", path):
394 n = p[1:][:-1]
395
396 if n in kv:
397 v[n] = str(kv[n])
398
399 else:
400 if n in module.params:
401 v[n] = str(module.params.get(n))
402 else:
403 v[n] = ""
404
405 return path.format(**v)
406
407
408 def get_region(module: AnsibleModule):
409 if module.params["region"]:
410 return module.params["region"]
411
412 return module.params["project"].split("_")[0]
413
414
415 def is_empty_value(v):
416 return not v
417
418
419 def are_different_dicts(dict1, dict2):
420 return _DictComparison(dict1) != _DictComparison(dict2)