Debian Codegraph @

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

raw
1 #
2 # Copyright 2018 www.privaz.io Valletech AB
3 #
4 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
5 # SPDX-License-Identifier: BSD-2-Clause
6
7 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
8 # Do not use this from other collections or standalone plugins/modules!
9
10 from __future__ import annotations
11
12 import ssl
13 import time
14 from os import environ
15
16 from ansible.module_utils.basic import AnsibleModule
17
18 IMAGE_STATES = [
19 "INIT",
20 "READY",
21 "USED",
22 "DISABLED",
23 "LOCKED",
24 "ERROR",
25 "CLONE",
26 "DELETE",
27 "USED_PERS",
28 "LOCKED_USED",
29 "LOCKED_USED_PERS",
30 ]
31 HAS_PYONE = True
32
33 try:
34 from pyone import OneException
35 from pyone.server import OneServer
36 except ImportError:
37 OneException = Exception
38 HAS_PYONE = False
39
40
41 # A helper function to mitigate https://github.com/OpenNebula/one/issues/6064.
42 # It allows for easily handling lists like "NIC" or "DISK" in the JSON-like template representation.
43 # There are either lists of dictionaries (length > 1) or just dictionaries.
44 def flatten(to_flatten, extract=False):
45 """Flattens nested lists (with optional value extraction)."""
46
47 def recurse(to_flatten):
48 return sum(map(recurse, to_flatten), []) if isinstance(to_flatten, list) else [to_flatten]
49
50 value = recurse(to_flatten)
51 if extract and len(value) == 1:
52 return value[0]
53 return value
54
55
56 # A helper function to mitigate https://github.com/OpenNebula/one/issues/6064.
57 # It renders JSON-like template representation into OpenNebula's template syntax (string).
58 def render(to_render):
59 """Converts dictionary to OpenNebula template."""
60
61 def recurse(to_render):
62 for key, value in sorted(to_render.items()):
63 if value is None:
64 continue
65 if isinstance(value, dict):
66 yield f"{key}=[{','.join(recurse(value))}]"
67 continue
68 if isinstance(value, list):
69 for item in value:
70 yield f"{key}=[{','.join(recurse(item))}]"
71 continue
72 if isinstance(value, str):
73 _value = value.replace("\\", "\\\\").replace('"', '\\"')
74 yield f'{key}="{_value}"'
75 continue
76 yield f'{key}="{value}"'
77
78 return "\n".join(recurse(to_render))
79
80
81 class OpenNebulaModule:
82 """
83 Base class for all OpenNebula Ansible Modules.
84 This is basically a wrapper of the common arguments, the pyone client and
85 some utility methods.
86 """
87
88 common_args = dict(
89 api_url=dict(type="str", aliases=["api_endpoint"], default=environ.get("ONE_URL")),
90 api_username=dict(type="str", default=environ.get("ONE_USERNAME")),
91 api_password=dict(type="str", no_log=True, aliases=["api_token"], default=environ.get("ONE_PASSWORD")),
92 validate_certs=dict(default=True, type="bool"),
93 wait_timeout=dict(type="int", default=300),
94 )
95
96 def __init__(
97 self, argument_spec, supports_check_mode=False, mutually_exclusive=None, required_one_of=None, required_if=None
98 ):
99 module_args = OpenNebulaModule.common_args.copy()
100 module_args.update(argument_spec)
101
102 self.module = AnsibleModule(
103 argument_spec=module_args,
104 supports_check_mode=supports_check_mode,
105 mutually_exclusive=mutually_exclusive,
106 required_one_of=required_one_of,
107 required_if=required_if,
108 )
109 self.result = dict(changed=False, original_message="", message="")
110 self.one = self.create_one_client()
111
112 self.resolved_parameters = self.resolve_parameters()
113
114 def create_one_client(self):
115 """
116 Creates an XMLPRC client to OpenNebula.
117
118 Returns: the new xmlrpc client.
119
120 """
121
122 # context required for not validating SSL, old python versions won't validate anyway.
123 if hasattr(ssl, "_create_unverified_context"):
124 no_ssl_validation_context = ssl._create_unverified_context()
125 else:
126 no_ssl_validation_context = None
127
128 # Check if the module can run
129 if not HAS_PYONE:
130 self.fail("pyone is required for this module")
131
132 if self.module.params.get("api_url"):
133 url = self.module.params.get("api_url")
134 else:
135 self.fail("Either api_url or the environment variable ONE_URL must be provided")
136
137 if self.module.params.get("api_username"):
138 username = self.module.params.get("api_username")
139 else:
140 self.fail("Either api_username or the environment variable ONE_USERNAME must be provided")
141
142 if self.module.params.get("api_password"):
143 password = self.module.params.get("api_password")
144 else:
145 self.fail("Either api_password or the environment variable ONE_PASSWORD must be provided")
146
147 session = f"{username}:{password}"
148
149 if not self.module.params.get("validate_certs") and "PYTHONHTTPSVERIFY" not in environ:
150 return OneServer(url, session=session, context=no_ssl_validation_context)
151 else:
152 return OneServer(url, session)
153
154 def close_one_client(self):
155 """
156 Close the pyone session.
157 """
158 self.one.server_close()
159
160 def fail(self, msg):
161 """
162 Utility failure method, will ensure pyone is properly closed before failing.
163 Args:
164 msg: human readable failure reason.
165 """
166 if hasattr(self, "one"):
167 self.close_one_client()
168 self.module.fail_json(msg=msg)
169
170 def exit(self):
171 """
172 Utility exit method, will ensure pyone is properly closed before exiting.
173
174 """
175 if hasattr(self, "one"):
176 self.close_one_client()
177 self.module.exit_json(**self.result)
178
179 def resolve_parameters(self):
180 """
181 This method resolves parameters provided by a secondary ID to the primary ID.
182 For example if cluster_name is present, cluster_id will be introduced by performing
183 the required resolution
184
185 Returns: a copy of the parameters that includes the resolved parameters.
186
187 """
188
189 resolved_params = dict(self.module.params)
190
191 if "cluster_name" in self.module.params:
192 clusters = self.one.clusterpool.info()
193 for cluster in clusters.CLUSTER:
194 if self.module.params.get("cluster_name") == cluster.NAME:
195 resolved_params["cluster_id"] = cluster.ID
196
197 return resolved_params
198
199 def is_parameter(self, name):
200 """
201 Utility method to check if a parameter was provided or is resolved
202 Args:
203 name: the parameter to check
204 """
205 if name in self.resolved_parameters:
206 return self.get_parameter(name) is not None
207 else:
208 return False
209
210 def get_parameter(self, name):
211 """
212 Utility method for accessing parameters that includes resolved ID
213 parameters from provided Name parameters.
214 """
215 return self.resolved_parameters.get(name)
216
217 def get_host_by_name(self, name):
218 """
219 Returns a host given its name.
220 Args:
221 name: the name of the host
222
223 Returns: the host object or None if the host is absent.
224
225 """
226 hosts = self.one.hostpool.info()
227 for h in hosts.HOST:
228 if name == h.NAME:
229 return h
230 return None
231
232 def get_cluster_by_name(self, name):
233 """
234 Returns a cluster given its name.
235 Args:
236 name: the name of the cluster
237
238 Returns: the cluster object or None if the host is absent.
239 """
240
241 clusters = self.one.clusterpool.info()
242 for c in clusters.CLUSTER:
243 if name == c.NAME:
244 return c
245 return None
246
247 def get_template_by_name(self, name):
248 """
249 Returns a template given its name.
250 Args:
251 name: the name of the template
252
253 Returns: the template object or None if the host is absent.
254
255 """
256 templates = self.one.templatepool.info()
257 for t in templates.TEMPLATE:
258 if name == t.NAME:
259 return t
260 return None
261
262 def cast_template(self, template):
263 """
264 OpenNebula handles all template elements as strings
265 At some point there is a cast being performed on types provided by the user
266 This function mimics that transformation so that required template updates are detected properly
267 additionally an array will be converted to a comma separated list,
268 which works for labels and hopefully for something more.
269
270 Args:
271 template: the template to transform
272
273 Returns: the transformed template with data casts applied.
274 """
275
276 # TODO: check formally available data types in templates
277 # TODO: some arrays might be converted to space separated
278
279 for key in template:
280 value = template[key]
281 if isinstance(value, dict):
282 self.cast_template(template[key])
283 elif isinstance(value, list):
284 template[key] = ", ".join(value)
285 elif not isinstance(value, str):
286 template[key] = str(value)
287
288 def requires_template_update(self, current, desired):
289 """
290 This function will help decide if a template update is required or not
291 If a desired key is missing from the current dictionary an update is required
292 If the intersection of both dictionaries is not deep equal, an update is required
293 Args:
294 current: current template as a dictionary
295 desired: desired template as a dictionary
296
297 Returns: True if a template update is required
298 """
299
300 if not desired:
301 return False
302
303 self.cast_template(desired)
304 intersection = dict()
305 for dkey in desired.keys():
306 if dkey in current.keys():
307 intersection[dkey] = current[dkey]
308 else:
309 return True
310 return desired != intersection
311
312 def wait_for_state(
313 self,
314 element_name,
315 state,
316 state_name,
317 target_states,
318 invalid_states=None,
319 transition_states=None,
320 wait_timeout=None,
321 ):
322 """
323 Args:
324 element_name: the name of the object we are waiting for: HOST, VM, etc.
325 state: lambda that returns the current state, will be queried until target state is reached
326 state_name: lambda that returns the readable form of a given state
327 target_states: states expected to be reached
328 invalid_states: if any of this states is reached, fail
329 transition_states: when used, these are the valid states during the transition.
330 wait_timeout: timeout period in seconds. Defaults to the provided parameter.
331 """
332
333 if not wait_timeout:
334 wait_timeout = self.module.params.get("wait_timeout")
335
336 start_time = time.time()
337
338 while (time.time() - start_time) < wait_timeout:
339 current_state = state()
340
341 if current_state in invalid_states:
342 self.fail(f"invalid {element_name} state {state_name(current_state)}")
343
344 if transition_states:
345 if current_state not in transition_states:
346 self.fail(f"invalid {element_name} transition state {state_name(current_state)}")
347
348 if current_state in target_states:
349 return True
350
351 time.sleep(self.one.server_retry_interval())
352
353 self.fail(msg="Wait timeout has expired!")
354
355 def run_module(self):
356 """
357 trigger the start of the execution of the module.
358 Returns:
359
360 """
361 try:
362 self.run(self.one, self.module, self.result)
363 except OneException as e:
364 self.fail(msg=f"OpenNebula Exception: {e}")
365
366 def run(self, one, module, result):
367 """
368 to be implemented by subclass with the actual module actions.
369 Args:
370 one: the OpenNebula XMLRPC client
371 module: the Ansible Module object
372 result: the Ansible result
373 """
374 raise NotImplementedError("Method requires implementation")
375
376 def get_image_list_id(self, image, element):
377 """
378 This is a helper function for get_image_info to iterate over a simple list of objects
379 """
380 list_of_id = []
381
382 if element == "VMS":
383 image_list = image.VMS
384 if element == "CLONES":
385 image_list = image.CLONES
386 if element == "APP_CLONES":
387 image_list = image.APP_CLONES
388
389 for iter in image_list.ID:
390 list_of_id.append(
391 # These are optional so firstly check for presence
392 getattr(iter, "ID", "Null"),
393 )
394 return list_of_id
395
396 def get_image_snapshots_list(self, image):
397 """
398 This is a helper function for get_image_info to iterate over a dictionary
399 """
400 list_of_snapshots = []
401
402 for iter in image.SNAPSHOTS.SNAPSHOT:
403 list_of_snapshots.append(
404 {
405 "date": iter["DATE"],
406 "parent": iter["PARENT"],
407 "size": iter["SIZE"],
408 # These are optional so firstly check for presence
409 "allow_orhans": getattr(image.SNAPSHOTS, "ALLOW_ORPHANS", "Null"),
410 "children": getattr(iter, "CHILDREN", "Null"),
411 "active": getattr(iter, "ACTIVE", "Null"),
412 "name": getattr(iter, "NAME", "Null"),
413 }
414 )
415 return list_of_snapshots
416
417 def get_image_info(self, image):
418 """
419 This method is used by one_image and one_image_info modules to retrieve
420 information from XSD scheme of an image
421 Returns: a copy of the parameters that includes the resolved parameters.
422 """
423 info = {
424 "id": image.ID,
425 "name": image.NAME,
426 "state": IMAGE_STATES[image.STATE],
427 "running_vms": image.RUNNING_VMS,
428 "used": bool(image.RUNNING_VMS),
429 "user_name": image.UNAME,
430 "user_id": image.UID,
431 "group_name": image.GNAME,
432 "group_id": image.GID,
433 "permissions": {
434 "owner_u": image.PERMISSIONS.OWNER_U,
435 "owner_m": image.PERMISSIONS.OWNER_M,
436 "owner_a": image.PERMISSIONS.OWNER_A,
437 "group_u": image.PERMISSIONS.GROUP_U,
438 "group_m": image.PERMISSIONS.GROUP_M,
439 "group_a": image.PERMISSIONS.GROUP_A,
440 "other_u": image.PERMISSIONS.OTHER_U,
441 "other_m": image.PERMISSIONS.OTHER_M,
442 "other_a": image.PERMISSIONS.OTHER_A,
443 },
444 "type": image.TYPE,
445 "disk_type": image.DISK_TYPE,
446 "persistent": image.PERSISTENT,
447 "regtime": image.REGTIME,
448 "source": image.SOURCE,
449 "path": image.PATH,
450 "fstype": getattr(image, "FSTYPE", "Null"),
451 "size": image.SIZE,
452 "cloning_ops": image.CLONING_OPS,
453 "cloning_id": image.CLONING_ID,
454 "target_snapshot": image.TARGET_SNAPSHOT,
455 "datastore_id": image.DATASTORE_ID,
456 "datastore": image.DATASTORE,
457 "vms": self.get_image_list_id(image, "VMS"),
458 "clones": self.get_image_list_id(image, "CLONES"),
459 "app_clones": self.get_image_list_id(image, "APP_CLONES"),
460 "snapshots": self.get_image_snapshots_list(image),
461 "template": image.TEMPLATE,
462 }
463 return info