Debian Codegraph @

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

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # Copyright (2016-2017) Hewlett Packard Enterprise Development LP
8 #
9 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
10 # SPDX-License-Identifier: BSD-2-Clause
11
12 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
13 # Do not use this from other collections or standalone plugins/modules!
14
15 from __future__ import annotations
16
17 import abc
18 import collections
19 import json
20 import traceback
21 from collections.abc import Mapping
22
23 HPE_ONEVIEW_IMP_ERR = None
24 try:
25 from hpOneView.oneview_client import OneViewClient
26
27 HAS_HPE_ONEVIEW = True
28 except ImportError:
29 HPE_ONEVIEW_IMP_ERR = traceback.format_exc()
30 HAS_HPE_ONEVIEW = False
31
32 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
33 from ansible.module_utils.common.text.converters import to_native
34
35
36 def transform_list_to_dict(list_):
37 """
38 Transforms a list into a dictionary, putting values as keys.
39
40 :arg list list_: List of values
41 :return: dict: dictionary built
42 """
43
44 ret = {}
45
46 if not list_:
47 return ret
48
49 for value in list_:
50 if isinstance(value, Mapping):
51 ret.update(value)
52 else:
53 ret[to_native(value, errors="surrogate_or_strict")] = True
54
55 return ret
56
57
58 def merge_list_by_key(original_list, updated_list, key, ignore_when_null=None):
59 """
60 Merge two lists by the key. It basically:
61
62 1. Adds the items that are present on updated_list and are absent on original_list.
63
64 2. Removes items that are absent on updated_list and are present on original_list.
65
66 3. For all items that are in both lists, overwrites the values from the original item by the updated item.
67
68 :arg list original_list: original list.
69 :arg list updated_list: list with changes.
70 :arg str key: unique identifier.
71 :arg list ignore_when_null: list with the keys from the updated items that should be ignored in the merge,
72 if its values are null.
73 :return: list: Lists merged.
74 """
75 ignore_when_null = [] if ignore_when_null is None else ignore_when_null
76
77 if not original_list:
78 return updated_list
79
80 items_map = collections.OrderedDict([(i[key], i.copy()) for i in original_list])
81
82 merged_items = collections.OrderedDict()
83
84 for item in updated_list:
85 item_key = item[key]
86 if item_key in items_map:
87 for ignored_key in ignore_when_null:
88 if ignored_key in item and item[ignored_key] is None:
89 item.pop(ignored_key)
90 merged_items[item_key] = items_map[item_key]
91 merged_items[item_key].update(item)
92 else:
93 merged_items[item_key] = item
94
95 return list(merged_items.values())
96
97
98 def _str_sorted(obj):
99 if isinstance(obj, Mapping):
100 return json.dumps(obj, sort_keys=True)
101 else:
102 return str(obj)
103
104
105 def _standardize_value(value):
106 """
107 Convert value to string to enhance the comparison.
108
109 :arg value: Any object type.
110
111 :return: str: Converted value.
112 """
113 if isinstance(value, float) and value.is_integer():
114 # Workaround to avoid erroneous comparison between int and float
115 # Removes zero from integer floats
116 value = int(value)
117
118 return str(value)
119
120
121 class OneViewModuleException(Exception):
122 """
123 OneView base Exception.
124
125 Attributes:
126 msg (str): Exception message.
127 oneview_response (dict): OneView rest response.
128 """
129
130 def __init__(self, data):
131 self.msg = None
132 self.oneview_response = None
133
134 if isinstance(data, str):
135 self.msg = data
136 else:
137 self.oneview_response = data
138
139 if data and isinstance(data, dict):
140 self.msg = data.get("message")
141
142 if self.oneview_response:
143 Exception.__init__(self, self.msg, self.oneview_response)
144 else:
145 Exception.__init__(self, self.msg)
146
147
148 class OneViewModuleTaskError(OneViewModuleException):
149 """
150 OneView Task Error Exception.
151
152 Attributes:
153 msg (str): Exception message.
154 error_code (str): A code which uniquely identifies the specific error.
155 """
156
157 def __init__(self, msg, error_code=None):
158 super().__init__(msg)
159 self.error_code = error_code
160
161
162 class OneViewModuleValueError(OneViewModuleException):
163 """
164 OneView Value Error.
165 The exception is raised when the data contains an inappropriate value.
166
167 Attributes:
168 msg (str): Exception message.
169 """
170
171 pass
172
173
174 class OneViewModuleResourceNotFound(OneViewModuleException):
175 """
176 OneView Resource Not Found Exception.
177 The exception is raised when an associated resource was not found.
178
179 Attributes:
180 msg (str): Exception message.
181 """
182
183 pass
184
185
186 class OneViewModuleBase(metaclass=abc.ABCMeta):
187 MSG_CREATED = "Resource created successfully."
188 MSG_UPDATED = "Resource updated successfully."
189 MSG_DELETED = "Resource deleted successfully."
190 MSG_ALREADY_PRESENT = "Resource is already present."
191 MSG_ALREADY_ABSENT = "Resource is already absent."
192
193 ONEVIEW_COMMON_ARGS = dict(
194 config=dict(type="path"),
195 hostname=dict(type="str"),
196 username=dict(type="str"),
197 password=dict(type="str", no_log=True),
198 api_version=dict(type="int"),
199 image_streamer_hostname=dict(type="str"),
200 )
201
202 ONEVIEW_VALIDATE_ETAG_ARGS = dict(validate_etag=dict(type="bool", default=True))
203
204 resource_client = None
205
206 def __init__(self, additional_arg_spec=None, validate_etag_support=False, supports_check_mode=False):
207 """
208 OneViewModuleBase constructor.
209
210 :arg dict additional_arg_spec: Additional argument spec definition.
211 :arg bool validate_etag_support: Enables support to eTag validation.
212 """
213 argument_spec = self._build_argument_spec(additional_arg_spec, validate_etag_support)
214
215 self.module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=supports_check_mode)
216
217 self._check_hpe_oneview_sdk()
218 self._create_oneview_client()
219
220 self.state = self.module.params.get("state")
221 self.data = self.module.params.get("data")
222
223 # Preload params for get_all - used by facts
224 self.facts_params = self.module.params.get("params") or {}
225
226 # Preload options as dict - used by facts
227 self.options = transform_list_to_dict(self.module.params.get("options"))
228
229 self.validate_etag_support = validate_etag_support
230
231 def _build_argument_spec(self, additional_arg_spec, validate_etag_support):
232 merged_arg_spec = dict()
233 merged_arg_spec.update(self.ONEVIEW_COMMON_ARGS)
234
235 if validate_etag_support:
236 merged_arg_spec.update(self.ONEVIEW_VALIDATE_ETAG_ARGS)
237
238 if additional_arg_spec:
239 merged_arg_spec.update(additional_arg_spec)
240
241 return merged_arg_spec
242
243 def _check_hpe_oneview_sdk(self):
244 if not HAS_HPE_ONEVIEW:
245 self.module.fail_json(msg=missing_required_lib("hpOneView"), exception=HPE_ONEVIEW_IMP_ERR)
246
247 def _create_oneview_client(self):
248 if self.module.params.get("hostname"):
249 config = dict(
250 ip=self.module.params["hostname"],
251 credentials=dict(userName=self.module.params["username"], password=self.module.params["password"]),
252 api_version=self.module.params["api_version"],
253 image_streamer_ip=self.module.params["image_streamer_hostname"],
254 )
255 self.oneview_client = OneViewClient(config)
256 elif not self.module.params["config"]:
257 self.oneview_client = OneViewClient.from_environment_variables()
258 else:
259 self.oneview_client = OneViewClient.from_json_file(self.module.params["config"])
260
261 @abc.abstractmethod
262 def execute_module(self):
263 """
264 Abstract method, must be implemented by the inheritor.
265
266 This method is called from the run method. It should contains the module logic
267
268 :return: dict: It must return a dictionary with the attributes for the module result,
269 such as ansible_facts, msg and changed.
270 """
271 pass
272
273 def run(self):
274 """
275 Common implementation of the OneView run modules.
276
277 It calls the inheritor 'execute_module' function and sends the return to the Ansible.
278
279 It handles any OneViewModuleException in order to signal a failure to Ansible, with a descriptive error message.
280
281 """
282 try:
283 if self.validate_etag_support:
284 if not self.module.params.get("validate_etag"):
285 self.oneview_client.connection.disable_etag_validation()
286
287 result = self.execute_module()
288
289 if "changed" not in result:
290 result["changed"] = False
291
292 self.module.exit_json(**result)
293
294 except OneViewModuleException as exception:
295 error_msg = "; ".join(str(e) for e in exception.args)
296 self.module.fail_json(msg=error_msg, exception=traceback.format_exc())
297
298 def resource_absent(self, resource, method="delete"):
299 """
300 Generic implementation of the absent state for the OneView resources.
301
302 It checks if the resource needs to be removed.
303
304 :arg dict resource: Resource to delete.
305 :arg str method: Function of the OneView client that will be called for resource deletion.
306 Usually delete or remove.
307 :return: A dictionary with the expected arguments for the AnsibleModule.exit_json
308 """
309 if resource:
310 getattr(self.resource_client, method)(resource)
311
312 return {"changed": True, "msg": self.MSG_DELETED}
313 else:
314 return {"changed": False, "msg": self.MSG_ALREADY_ABSENT}
315
316 def get_by_name(self, name):
317 """
318 Generic get by name implementation.
319
320 :arg str name: Resource name to search for.
321
322 :return: The resource found or None.
323 """
324 result = self.resource_client.get_by("name", name)
325 return result[0] if result else None
326
327 def resource_present(self, resource, fact_name, create_method="create"):
328 """
329 Generic implementation of the present state for the OneView resources.
330
331 It checks if the resource needs to be created or updated.
332
333 :arg dict resource: Resource to create or update.
334 :arg str fact_name: Name of the fact returned to the Ansible.
335 :arg str create_method: Function of the OneView client that will be called for resource creation.
336 Usually create or add.
337 :return: A dictionary with the expected arguments for the AnsibleModule.exit_json
338 """
339
340 changed = False
341 if "newName" in self.data:
342 self.data["name"] = self.data.pop("newName")
343
344 if not resource:
345 resource = getattr(self.resource_client, create_method)(self.data)
346 msg = self.MSG_CREATED
347 changed = True
348
349 else:
350 merged_data = resource.copy()
351 merged_data.update(self.data)
352
353 if self.compare(resource, merged_data):
354 msg = self.MSG_ALREADY_PRESENT
355 else:
356 resource = self.resource_client.update(merged_data)
357 changed = True
358 msg = self.MSG_UPDATED
359
360 return dict(msg=msg, changed=changed, ansible_facts={fact_name: resource})
361
362 def resource_scopes_set(self, state, fact_name, scope_uris):
363 """
364 Generic implementation of the scopes update PATCH for the OneView resources.
365 It checks if the resource needs to be updated with the current scopes.
366 This method is meant to be run after ensuring the present state.
367 :arg dict state: Dict containing the data from the last state results in the resource.
368 It needs to have the 'msg', 'changed', and 'ansible_facts' entries.
369 :arg str fact_name: Name of the fact returned to the Ansible.
370 :arg list scope_uris: List with all the scope URIs to be added to the resource.
371 :return: A dictionary with the expected arguments for the AnsibleModule.exit_json
372 """
373 if scope_uris is None:
374 scope_uris = []
375 resource = state["ansible_facts"][fact_name]
376 operation_data = dict(operation="replace", path="/scopeUris", value=scope_uris)
377
378 if resource["scopeUris"] is None or set(resource["scopeUris"]) != set(scope_uris):
379 state["ansible_facts"][fact_name] = self.resource_client.patch(resource["uri"], **operation_data)
380 state["changed"] = True
381 state["msg"] = self.MSG_UPDATED
382
383 return state
384
385 def compare(self, first_resource, second_resource):
386 """
387 Recursively compares dictionary contents equivalence, ignoring types and elements order.
388 Particularities of the comparison:
389 - Inexistent key = None
390 - These values are considered equal: None, empty, False
391 - Lists are compared value by value after a sort, if they have same size.
392 - Each element is converted to str before the comparison.
393 :arg dict first_resource: first dictionary
394 :arg dict second_resource: second dictionary
395 :return: bool: True when equal, False when different.
396 """
397 resource1 = first_resource
398 resource2 = second_resource
399
400 debug_resources = f"resource1 = {resource1}, resource2 = {resource2}"
401
402 # The first resource is True / Not Null and the second resource is False / Null
403 if resource1 and not resource2:
404 self.module.log(f"resource1 and not resource2. {debug_resources}")
405 return False
406
407 # Checks all keys in first dict against the second dict
408 for key in resource1:
409 if key not in resource2:
410 if resource1[key] is not None:
411 # Inexistent key is equivalent to exist with value None
412 self.module.log(f"Difference found at key '{key}'. {debug_resources}")
413 return False
414 # If both values are null, empty or False it will be considered equal.
415 elif not resource1[key] and not resource2[key]:
416 continue
417 elif isinstance(resource1[key], Mapping):
418 # recursive call
419 if not self.compare(resource1[key], resource2[key]):
420 self.module.log(f"Difference found at key '{key}'. {debug_resources}")
421 return False
422 elif isinstance(resource1[key], list):
423 # change comparison function to compare_list
424 if not self.compare_list(resource1[key], resource2[key]):
425 self.module.log(f"Difference found at key '{key}'. {debug_resources}")
426 return False
427 elif _standardize_value(resource1[key]) != _standardize_value(resource2[key]):
428 self.module.log(f"Difference found at key '{key}'. {debug_resources}")
429 return False
430
431 # Checks all keys in the second dict, looking for missing elements
432 for key in resource2.keys():
433 if key not in resource1:
434 if resource2[key] is not None:
435 # Inexistent key is equivalent to exist with value None
436 self.module.log(f"Difference found at key '{key}'. {debug_resources}")
437 return False
438
439 return True
440
441 def compare_list(self, first_resource, second_resource):
442 """
443 Recursively compares lists contents equivalence, ignoring types and element orders.
444 Lists with same size are compared value by value after a sort,
445 each element is converted to str before the comparison.
446 :arg list first_resource: first list
447 :arg list second_resource: second list
448 :return: True when equal; False when different.
449 """
450
451 resource1 = first_resource
452 resource2 = second_resource
453
454 debug_resources = f"resource1 = {resource1}, resource2 = {resource2}"
455
456 # The second list is null / empty / False
457 if not resource2:
458 self.module.log(f"resource 2 is null. {debug_resources}")
459 return False
460
461 if len(resource1) != len(resource2):
462 self.module.log(f"resources have different length. {debug_resources}")
463 return False
464
465 resource1 = sorted(resource1, key=_str_sorted)
466 resource2 = sorted(resource2, key=_str_sorted)
467
468 for i, val in enumerate(resource1):
469 if isinstance(val, Mapping):
470 # change comparison function to compare dictionaries
471 if not self.compare(val, resource2[i]):
472 self.module.log(f"resources are different. {debug_resources}")
473 return False
474 elif isinstance(val, list):
475 # recursive call
476 if not self.compare_list(val, resource2[i]):
477 self.module.log(f"lists are different. {debug_resources}")
478 return False
479 elif _standardize_value(val) != _standardize_value(resource2[i]):
480 self.module.log(f"values are different. {debug_resources}")
481 return False
482
483 # no differences found
484 return True