Debian Codegraph @

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

raw
1 # Copyright (c) 2022 Western Digital Corporation
2 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
7 # Do not use this from other collections or standalone plugins/modules!
8
9 from __future__ import annotations
10
11 import json
12 import os
13 import typing as t
14 import uuid
15 from http import HTTPStatus
16 from urllib.error import HTTPError, URLError
17 from urllib.parse import urlparse
18
19 from ansible.module_utils.common.text.converters import to_native
20 from ansible.module_utils.urls import open_url
21
22 if t.TYPE_CHECKING:
23 from ansible.module_utils.basic import AnsibleModule
24
25
26 GET_HEADERS = {"accept": "application/json"}
27 PUT_HEADERS = {"content-type": "application/json", "accept": "application/json"}
28 POST_HEADERS = {"content-type": "application/json", "accept": "application/json"}
29 DELETE_HEADERS = {"accept": "application/json"}
30
31 HEALTH_OK = 5
32
33
34 class OcapiUtils:
35 def __init__(self, creds, base_uri, proxy_slot_number, timeout, module: AnsibleModule) -> None:
36 self.root_uri = base_uri
37 self.proxy_slot_number = proxy_slot_number
38 self.creds = creds
39 self.timeout = timeout
40 self.module = module
41
42 def _auth_params(self):
43 """
44 Return tuple of required authentication params based on the username and password.
45
46 :return: tuple of username, password
47 """
48 username = self.creds["user"]
49 password = self.creds["pswd"]
50 force_basic_auth = True
51 return username, password, force_basic_auth
52
53 def get_request(self, uri):
54 req_headers = dict(GET_HEADERS)
55 username, password, basic_auth = self._auth_params()
56 try:
57 resp = open_url(
58 uri,
59 method="GET",
60 headers=req_headers,
61 url_username=username,
62 url_password=password,
63 force_basic_auth=basic_auth,
64 validate_certs=False,
65 follow_redirects="all",
66 use_proxy=True,
67 timeout=self.timeout,
68 )
69 data = json.loads(resp.read())
70 headers = {k.lower(): v for (k, v) in resp.info().items()}
71 except HTTPError as e:
72 return {"ret": False, "msg": f"HTTP Error {e.code} on GET request to '{uri}'", "status": e.code}
73 except URLError as e:
74 return {"ret": False, "msg": f"URL Error on GET request to '{uri}': '{e.reason}'"}
75 # Almost all errors should be caught above, but just in case
76 except Exception as e:
77 return {"ret": False, "msg": f"Failed GET request to '{uri}': '{e}'"}
78 return {"ret": True, "data": data, "headers": headers}
79
80 def delete_request(self, uri, etag=None):
81 req_headers = dict(DELETE_HEADERS)
82 if etag is not None:
83 req_headers["If-Match"] = etag
84 username, password, basic_auth = self._auth_params()
85 try:
86 resp = open_url(
87 uri,
88 method="DELETE",
89 headers=req_headers,
90 url_username=username,
91 url_password=password,
92 force_basic_auth=basic_auth,
93 validate_certs=False,
94 follow_redirects="all",
95 use_proxy=True,
96 timeout=self.timeout,
97 )
98 if resp.status != HTTPStatus.NO_CONTENT:
99 data = json.loads(resp.read())
100 else:
101 data = ""
102 headers = {k.lower(): v for (k, v) in resp.info().items()}
103 except HTTPError as e:
104 return {"ret": False, "msg": f"HTTP Error {e.code} on DELETE request to '{uri}'", "status": e.code}
105 except URLError as e:
106 return {"ret": False, "msg": f"URL Error on DELETE request to '{uri}': '{e.reason}'"}
107 # Almost all errors should be caught above, but just in case
108 except Exception as e:
109 return {"ret": False, "msg": f"Failed DELETE request to '{uri}': '{e}'"}
110 return {"ret": True, "data": data, "headers": headers}
111
112 def put_request(self, uri, payload, etag=None):
113 req_headers = dict(PUT_HEADERS)
114 if etag is not None:
115 req_headers["If-Match"] = etag
116 username, password, basic_auth = self._auth_params()
117 try:
118 resp = open_url(
119 uri,
120 data=json.dumps(payload),
121 headers=req_headers,
122 method="PUT",
123 url_username=username,
124 url_password=password,
125 force_basic_auth=basic_auth,
126 validate_certs=False,
127 follow_redirects="all",
128 use_proxy=True,
129 timeout=self.timeout,
130 )
131 headers = {k.lower(): v for (k, v) in resp.info().items()}
132 except HTTPError as e:
133 return {"ret": False, "msg": f"HTTP Error {e.code} on PUT request to '{uri}'", "status": e.code}
134 except URLError as e:
135 return {"ret": False, "msg": f"URL Error on PUT request to '{uri}': '{e.reason}'"}
136 # Almost all errors should be caught above, but just in case
137 except Exception as e:
138 return {"ret": False, "msg": f"Failed PUT request to '{uri}': '{e}'"}
139 return {"ret": True, "headers": headers, "resp": resp}
140
141 def post_request(self, uri, payload, content_type="application/json", timeout=None):
142 req_headers = dict(POST_HEADERS)
143 if content_type != "application/json":
144 req_headers["content-type"] = content_type
145 username, password, basic_auth = self._auth_params()
146 if content_type == "application/json":
147 request_data = json.dumps(payload)
148 else:
149 request_data = payload
150 try:
151 resp = open_url(
152 uri,
153 data=request_data,
154 headers=req_headers,
155 method="POST",
156 url_username=username,
157 url_password=password,
158 force_basic_auth=basic_auth,
159 validate_certs=False,
160 follow_redirects="all",
161 use_proxy=True,
162 timeout=self.timeout if timeout is None else timeout,
163 )
164 headers = {k.lower(): v for (k, v) in resp.info().items()}
165 except HTTPError as e:
166 return {"ret": False, "msg": f"HTTP Error {e.code} on POST request to '{uri}'", "status": e.code}
167 except URLError as e:
168 return {"ret": False, "msg": f"URL Error on POST request to '{uri}': '{e.reason}'"}
169 # Almost all errors should be caught above, but just in case
170 except Exception as e:
171 return {"ret": False, "msg": f"Failed POST request to '{uri}': '{e}'"}
172 return {"ret": True, "headers": headers, "resp": resp}
173
174 def get_uri_with_slot_number_query_param(self, uri):
175 """Return the URI with proxy slot number added as a query param, if there is one.
176
177 If a proxy slot number is provided, to access it, we must append it as a query parameter.
178 This method returns the given URI with the slotnumber query param added, if there is one.
179 If there is not a proxy slot number, it just returns the URI as it was passed in.
180 """
181 if self.proxy_slot_number is not None:
182 parsed_url = urlparse(uri)
183 return parsed_url._replace(query=f"slotnumber={self.proxy_slot_number}").geturl()
184 else:
185 return uri
186
187 def manage_system_power(self, command):
188 """Process a command to manage the system power.
189
190 :param str command: The Ansible command being processed.
191 """
192 if command == "PowerGracefulRestart":
193 resource_uri = self.root_uri
194 resource_uri = self.get_uri_with_slot_number_query_param(resource_uri)
195
196 # Get the resource so that we have the Etag
197 response = self.get_request(resource_uri)
198 if "etag" not in response["headers"]:
199 return {"ret": False, "msg": "Etag not found in response."}
200 etag = response["headers"]["etag"]
201 if response["ret"] is False:
202 return response
203
204 # Issue the PUT to do the reboot (unless we are in check mode)
205 if self.module.check_mode:
206 return {"ret": True, "changed": True, "msg": "Update not performed in check mode."}
207 payload = {"Reboot": True}
208 response = self.put_request(resource_uri, payload, etag)
209 if response["ret"] is False:
210 return response
211 elif command.startswith("PowerMode"):
212 return self.manage_power_mode(command)
213 else:
214 return {"ret": False, "msg": f"Invalid command: {command}"}
215
216 return {"ret": True}
217
218 def manage_chassis_indicator_led(self, command):
219 """Process a command to manage the chassis indicator LED.
220
221 :param string command: The Ansible command being processed.
222 """
223 return self.manage_indicator_led(command, self.root_uri)
224
225 def manage_indicator_led(self, command, resource_uri=None):
226 """Process a command to manage an indicator LED.
227
228 :param string command: The Ansible command being processed.
229 :param string resource_uri: URI of the resource whose indicator LED is being managed.
230 """
231 key = "IndicatorLED"
232 if resource_uri is None:
233 resource_uri = self.root_uri
234 resource_uri = self.get_uri_with_slot_number_query_param(resource_uri)
235
236 payloads = {"IndicatorLedOn": {"ID": 2}, "IndicatorLedOff": {"ID": 4}}
237
238 response = self.get_request(resource_uri)
239 if "etag" not in response["headers"]:
240 return {"ret": False, "msg": "Etag not found in response."}
241 etag = response["headers"]["etag"]
242 if response["ret"] is False:
243 return response
244 data = response["data"]
245 if key not in data:
246 return {"ret": False, "msg": f"Key {key} not found"}
247 if "ID" not in data[key]:
248 return {"ret": False, "msg": "IndicatorLED for resource has no ID."}
249
250 if command in payloads.keys():
251 # See if the LED is already set as requested.
252 current_led_status = data[key]["ID"]
253 if current_led_status == payloads[command]["ID"]:
254 return {"ret": True, "changed": False}
255
256 # Set the LED (unless we are in check mode)
257 if self.module.check_mode:
258 return {"ret": True, "changed": True, "msg": "Update not performed in check mode."}
259 payload = {"IndicatorLED": payloads[command]}
260 response = self.put_request(resource_uri, payload, etag)
261 if response["ret"] is False:
262 return response
263 else:
264 return {"ret": False, "msg": "Invalid command"}
265
266 return {"ret": True}
267
268 def manage_power_mode(self, command):
269 key = "PowerState"
270 resource_uri = self.get_uri_with_slot_number_query_param(self.root_uri)
271
272 payloads = {"PowerModeNormal": 2, "PowerModeLow": 4}
273
274 response = self.get_request(resource_uri)
275 if "etag" not in response["headers"]:
276 return {"ret": False, "msg": "Etag not found in response."}
277 etag = response["headers"]["etag"]
278 if response["ret"] is False:
279 return response
280 data = response["data"]
281 if key not in data:
282 return {"ret": False, "msg": f"Key {key} not found"}
283 if "ID" not in data[key]:
284 return {"ret": False, "msg": "PowerState for resource has no ID."}
285
286 if command in payloads.keys():
287 # See if the PowerState is already set as requested.
288 current_power_state = data[key]["ID"]
289 if current_power_state == payloads[command]:
290 return {"ret": True, "changed": False}
291
292 # Set the Power State (unless we are in check mode)
293 if self.module.check_mode:
294 return {"ret": True, "changed": True, "msg": "Update not performed in check mode."}
295 payload = {"PowerState": {"ID": payloads[command]}}
296 response = self.put_request(resource_uri, payload, etag)
297 if response["ret"] is False:
298 return response
299 else:
300 return {"ret": False, "msg": f"Invalid command: {command}"}
301
302 return {"ret": True}
303
304 def prepare_multipart_firmware_upload(self, filename):
305 """Prepare a multipart/form-data body for OCAPI firmware upload.
306
307 :arg filename: The name of the file to upload.
308 :returns: tuple of (content_type, body) where ``content_type`` is
309 the ``multipart/form-data`` ``Content-Type`` header including
310 ``boundary`` and ``body`` is the prepared bytestring body
311
312 Prepares the body to include "FirmwareFile" field with the contents of the file.
313 Because some OCAPI targets do not support Base-64 encoding for multipart/form-data,
314 this method sends the file as binary.
315 """
316 boundary = str(uuid.uuid4()) # Generate a random boundary
317 body = f"--{boundary}\r\n"
318 body += f'Content-Disposition: form-data; name="FirmwareFile"; filename="{to_native(os.path.basename(filename))}"\r\n'
319 body += "Content-Type: application/octet-stream\r\n\r\n"
320 body_bytes = bytearray(body, "utf-8")
321 with open(filename, "rb") as f:
322 body_bytes += f.read()
323 body_bytes += bytearray(f"\r\n--{boundary}--", "utf-8")
324 return (f"multipart/form-data; boundary={boundary}", body_bytes)
325
326 def upload_firmware_image(self, update_image_path):
327 """Perform Firmware Upload to the OCAPI storage device.
328
329 :param str update_image_path: The path/filename of the firmware image, on the local filesystem.
330 """
331 if not (os.path.exists(update_image_path) and os.path.isfile(update_image_path)):
332 return {"ret": False, "msg": "File does not exist."}
333 url = f"{self.root_uri}OperatingSystem"
334 url = self.get_uri_with_slot_number_query_param(url)
335 content_type, b_form_data = self.prepare_multipart_firmware_upload(update_image_path)
336
337 # Post the firmware (unless we are in check mode)
338 if self.module.check_mode:
339 return {"ret": True, "changed": True, "msg": "Update not performed in check mode."}
340 result = self.post_request(url, b_form_data, content_type=content_type, timeout=300)
341 if result["ret"] is False:
342 return result
343 return {"ret": True}
344
345 def update_firmware_image(self):
346 """Perform a Firmware Update on the OCAPI storage device."""
347 resource_uri = self.root_uri
348 resource_uri = self.get_uri_with_slot_number_query_param(resource_uri)
349 # We have to do a GET to obtain the Etag. It's required on the PUT.
350 response = self.get_request(resource_uri)
351 if response["ret"] is False:
352 return response
353 if "etag" not in response["headers"]:
354 return {"ret": False, "msg": "Etag not found in response."}
355 etag = response["headers"]["etag"]
356
357 # Issue the PUT (unless we are in check mode)
358 if self.module.check_mode:
359 return {"ret": True, "changed": True, "msg": "Update not performed in check mode."}
360 payload = {"FirmwareUpdate": True}
361 response = self.put_request(resource_uri, payload, etag)
362 if response["ret"] is False:
363 return response
364
365 return {"ret": True, "jobUri": response["headers"]["location"]}
366
367 def activate_firmware_image(self):
368 """Perform a Firmware Activate on the OCAPI storage device."""
369 resource_uri = self.root_uri
370 resource_uri = self.get_uri_with_slot_number_query_param(resource_uri)
371 # We have to do a GET to obtain the Etag. It's required on the PUT.
372 response = self.get_request(resource_uri)
373 if "etag" not in response["headers"]:
374 return {"ret": False, "msg": "Etag not found in response."}
375 etag = response["headers"]["etag"]
376 if response["ret"] is False:
377 return response
378
379 # Issue the PUT (unless we are in check mode)
380 if self.module.check_mode:
381 return {"ret": True, "changed": True, "msg": "Update not performed in check mode."}
382 payload = {"FirmwareActivate": True}
383 response = self.put_request(resource_uri, payload, etag)
384 if response["ret"] is False:
385 return response
386
387 return {"ret": True, "jobUri": response["headers"]["location"]}
388
389 def get_job_status(self, job_uri):
390 """Get the status of a job.
391
392 :param str job_uri: The URI of the job's status monitor.
393 """
394 job_uri = self.get_uri_with_slot_number_query_param(job_uri)
395 response = self.get_request(job_uri)
396 if response["ret"] is False:
397 if response.get("status") == HTTPStatus.NOT_FOUND:
398 # Job not found -- assume 0%
399 return {
400 "ret": True,
401 "percentComplete": 0,
402 "operationStatus": "Not Available",
403 "operationStatusId": 1,
404 "operationHealth": None,
405 "operationHealthId": None,
406 "details": "Job does not exist.",
407 "jobExists": False,
408 }
409 else:
410 return response
411 details = response["data"]["Status"].get("Details")
412 if isinstance(details, str):
413 details = [details]
414 health_list = response["data"]["Status"]["Health"]
415 return_value = {
416 "ret": True,
417 "percentComplete": response["data"]["PercentComplete"],
418 "operationStatus": response["data"]["Status"]["State"]["Name"],
419 "operationStatusId": response["data"]["Status"]["State"]["ID"],
420 "operationHealth": health_list[0]["Name"] if len(health_list) > 0 else None,
421 "operationHealthId": health_list[0]["ID"] if len(health_list) > 0 else None,
422 "details": details,
423 "jobExists": True,
424 }
425 return return_value
426
427 def delete_job(self, job_uri):
428 """Delete the OCAPI job referenced by the specified job_uri."""
429 job_uri = self.get_uri_with_slot_number_query_param(job_uri)
430 # We have to do a GET to obtain the Etag. It's required on the DELETE.
431 response = self.get_request(job_uri)
432
433 if response["ret"] is True:
434 if "etag" not in response["headers"]:
435 return {"ret": False, "msg": "Etag not found in response."}
436 else:
437 etag = response["headers"]["etag"]
438
439 if response["data"]["PercentComplete"] != 100:
440 return {"ret": False, "changed": False, "msg": "Cannot delete job because it is in progress."}
441
442 if response["ret"] is False:
443 if response["status"] == HTTPStatus.NOT_FOUND:
444 return {"ret": True, "changed": False, "msg": "Job already deleted."}
445 return response
446 if self.module.check_mode:
447 return {"ret": True, "changed": True, "msg": "Update not performed in check mode."}
448
449 # Do the DELETE (unless we are in check mode)
450 response = self.delete_request(job_uri, etag)
451 if response["ret"] is False:
452 if response["status"] == HTTPStatus.NOT_FOUND:
453 return {"ret": True, "changed": False}
454 elif response["status"] == HTTPStatus.CONFLICT:
455 return {"ret": False, "changed": False, "msg": "Cannot delete job because it is in progress."}
456 return response
457 return {"ret": True, "changed": True}