Debian Codegraph @

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

raw
1 # Copyright (c) 2017-2018 Dell EMC Inc.
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt 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 http.client as http_client
11 import json
12 import os
13 import random
14 import string
15 import time
16 import typing as t
17 from http import HTTPStatus
18 from urllib.error import HTTPError, URLError
19 from urllib.parse import urlparse
20
21 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
22 from ansible.module_utils.urls import open_url
23
24 if t.TYPE_CHECKING:
25 from ansible.module_utils.basic import AnsibleModule
26
27
28 GET_HEADERS = {"accept": "application/json", "OData-Version": "4.0"}
29 POST_HEADERS = {"content-type": "application/json", "accept": "application/json", "OData-Version": "4.0"}
30 PATCH_HEADERS = {"content-type": "application/json", "accept": "application/json", "OData-Version": "4.0"}
31 PUT_HEADERS = {"content-type": "application/json", "accept": "application/json", "OData-Version": "4.0"}
32 DELETE_HEADERS = {"accept": "application/json", "OData-Version": "4.0"}
33
34 FAIL_MSG = (
35 "Issuing a data modification command without specifying the "
36 "ID of the target %(resource)s resource when there is more "
37 "than one %(resource)s is no longer allowed. Use the `resource_id` "
38 "option to specify the target %(resource)s ID."
39 )
40
41 # Use together with the community.general.redfish docs fragment
42 REDFISH_COMMON_ARGUMENT_SPEC = {
43 "validate_certs": {
44 "type": "bool",
45 "default": False,
46 },
47 "ca_path": {
48 "type": "path",
49 },
50 "ciphers": {
51 "type": "list",
52 "elements": "str",
53 },
54 }
55
56
57 class RedfishUtils:
58 def __init__(
59 self,
60 creds: dict[str, str],
61 root_uri: str,
62 timeout,
63 module: AnsibleModule,
64 resource_id=None,
65 data_modification: bool = False,
66 strip_etag_quotes: bool = False,
67 ciphers: str | None = None,
68 ) -> None:
69 self.root_uri = root_uri
70 self.creds = creds
71 self.timeout = timeout
72 self.module = module
73 self.service_root = "/redfish/v1/"
74 self.session_service_uri = "/redfish/v1/SessionService"
75 self.sessions_uri = "/redfish/v1/SessionService/Sessions"
76 self.resource_id = resource_id
77 self.data_modification = data_modification
78 self.strip_etag_quotes = strip_etag_quotes
79 self.ciphers = ciphers if ciphers is not None else module.params.get("ciphers")
80 self._vendor = None
81 self.validate_certs = module.params.get("validate_certs", False)
82 self.ca_path = module.params.get("ca_path")
83
84 def _auth_params(self, headers: dict[str, str]) -> tuple[str | None, str | None, bool]:
85 """
86 Return tuple of required authentication params based on the presence
87 of a token in the self.creds dict. If using a token, set the
88 X-Auth-Token header in the `headers` param.
89
90 :param headers: dict containing headers to send in request
91 :return: tuple of username, password and force_basic_auth
92 """
93 if self.creds.get("token"):
94 username = None
95 password = None
96 force_basic_auth = False
97 headers["X-Auth-Token"] = self.creds["token"]
98 else:
99 username = self.creds["user"]
100 password = self.creds["pswd"]
101 force_basic_auth = True
102 return username, password, force_basic_auth
103
104 def _check_request_payload(self, req_pyld, cur_pyld, uri):
105 """
106 Checks the request payload with the values currently held by the
107 service. Will check if changes are needed and if properties are
108 supported by the service.
109
110 :param req_pyld: dict containing the properties to apply
111 :param cur_pyld: dict containing the properties currently set
112 :param uri: string containing the URI being modified
113 :return: dict containing response information
114 """
115
116 change_required = False
117 for prop in req_pyld:
118 # Check if the property is supported by the service
119 if prop not in cur_pyld:
120 return {
121 "ret": False,
122 "changed": False,
123 "msg": f"{uri} does not support the property {prop}",
124 "changes_required": False,
125 }
126
127 # Perform additional checks based on the type of property
128 if isinstance(req_pyld[prop], dict) and isinstance(cur_pyld[prop], dict):
129 # If the property is a dictionary, check the nested properties
130 sub_resp = self._check_request_payload(req_pyld[prop], cur_pyld[prop], uri)
131 if not sub_resp["ret"]:
132 # Unsupported property or other error condition; no change
133 return sub_resp
134 if sub_resp["changes_required"]:
135 # Subordinate dictionary requires changes
136 change_required = True
137
138 else:
139 # For other properties, just compare the values
140
141 # Note: This is also a fallthrough for cases where the request
142 # payload and current settings do not match in their data type.
143 # There are cases where this can be expected, such as when a
144 # property is always 'null' in responses, so we want to attempt
145 # the PATCH request.
146
147 # Note: This is also a fallthrough for properties that are
148 # arrays of objects. Some services erroneously omit properties
149 # within arrays of objects when not configured, and it is
150 # expecting the client to provide them anyway.
151
152 if req_pyld[prop] != cur_pyld[prop]:
153 change_required = True
154
155 resp = {"ret": True, "changes_required": change_required}
156 if not change_required:
157 # No changes required; all properties set
158 resp["changed"] = False
159 resp["msg"] = f"Properties in {uri} are already set"
160 return resp
161
162 def _request(self, uri: str, **kwargs):
163 kwargs.setdefault("validate_certs", self.validate_certs)
164 kwargs.setdefault("follow_redirects", "all")
165 kwargs.setdefault("use_proxy", True)
166 kwargs.setdefault("timeout", self.timeout)
167 kwargs.setdefault("ciphers", self.ciphers)
168 kwargs.setdefault("ca_path", self.ca_path)
169 resp = open_url(uri, **kwargs)
170 headers = {k.lower(): v for (k, v) in resp.info().items()}
171 return resp, headers
172
173 # The following functions are to send GET/POST/PATCH/DELETE requests
174 def get_request(
175 self, uri: str, override_headers: dict[str, str] | None = None, allow_no_resp: bool = False, timeout=None
176 ):
177 req_headers = dict(GET_HEADERS)
178 if override_headers:
179 req_headers.update(override_headers)
180 username, password, basic_auth = self._auth_params(req_headers)
181 if timeout is None:
182 timeout = self.timeout
183 try:
184 # Service root is an unauthenticated resource; remove credentials
185 # in case the caller will be using sessions later.
186 if uri == (self.root_uri + self.service_root):
187 basic_auth = False
188 resp, headers = self._request(
189 uri,
190 method="GET",
191 headers=req_headers,
192 url_username=username,
193 url_password=password,
194 force_basic_auth=basic_auth,
195 timeout=timeout,
196 )
197 try:
198 data = json.loads(resp.read())
199 except Exception:
200 # No response data; this is okay in certain cases
201 data = None
202 if not allow_no_resp:
203 raise
204 except HTTPError as e:
205 msg, data = self._get_extended_message(e)
206 return {
207 "ret": False,
208 "msg": f"HTTP Error {e.code} on GET request to '{uri}', extended message: '{msg}'",
209 "status": e.code,
210 "data": data,
211 }
212 except URLError as e:
213 return {"ret": False, "msg": f"URL Error on GET request to '{uri}': '{e.reason}'"}
214 # Almost all errors should be caught above, but just in case
215 except Exception as e:
216 return {"ret": False, "msg": f"Failed GET request to '{uri}': '{e}'"}
217 return {"ret": True, "data": data, "headers": headers, "resp": resp}
218
219 def post_request(self, uri: str, pyld, multipart: bool = False):
220 req_headers = dict(POST_HEADERS)
221 username, password, basic_auth = self._auth_params(req_headers)
222 try:
223 # When performing a POST to the session collection, credentials are
224 # provided in the request body. Do not provide the basic auth
225 # header since this can cause conflicts with some services
226 if self.sessions_uri is not None and uri == (self.root_uri + self.sessions_uri):
227 basic_auth = False
228 if multipart:
229 # Multipart requests require special handling to encode the request body
230 multipart_encoder = self._prepare_multipart(pyld)
231 data = multipart_encoder[0]
232 req_headers["content-type"] = multipart_encoder[1]
233 else:
234 data = json.dumps(pyld)
235 resp, headers = self._request(
236 uri,
237 data=data,
238 headers=req_headers,
239 method="POST",
240 url_username=username,
241 url_password=password,
242 force_basic_auth=basic_auth,
243 )
244 try:
245 data = json.loads(resp.read())
246 except Exception:
247 # No response data; this is okay in many cases
248 data = None
249 except HTTPError as e:
250 msg, data = self._get_extended_message(e)
251 return {
252 "ret": False,
253 "msg": f"HTTP Error {e.code} on POST request to '{uri}', extended message: '{msg}'",
254 "status": e.code,
255 "data": data,
256 }
257 except URLError as e:
258 return {"ret": False, "msg": f"URL Error on POST request to '{uri}': '{e.reason}'"}
259 # Almost all errors should be caught above, but just in case
260 except Exception as e:
261 return {"ret": False, "msg": f"Failed POST request to '{uri}': '{e}'"}
262 return {"ret": True, "data": data, "headers": headers, "resp": resp}
263
264 def patch_request(self, uri: str, pyld, check_pyld: bool = False):
265 req_headers = dict(PATCH_HEADERS)
266 r = self.get_request(uri)
267 if r["ret"]:
268 # Get etag from etag header or @odata.etag property
269 etag = r["headers"].get("etag")
270 if not etag:
271 etag = r["data"].get("@odata.etag")
272 if etag:
273 if self.strip_etag_quotes:
274 etag = etag.strip('"')
275 req_headers["If-Match"] = etag
276
277 if check_pyld:
278 # Check the payload with the current settings to see if changes
279 # are needed or if there are unsupported properties
280 if r["ret"]:
281 check_resp = self._check_request_payload(pyld, r["data"], uri)
282 if not check_resp.pop("changes_required"):
283 check_resp["changed"] = False
284 return check_resp
285 else:
286 r["changed"] = False
287 return r
288
289 username, password, basic_auth = self._auth_params(req_headers)
290 try:
291 resp, dummy = self._request(
292 uri,
293 data=json.dumps(pyld),
294 headers=req_headers,
295 method="PATCH",
296 url_username=username,
297 url_password=password,
298 force_basic_auth=basic_auth,
299 )
300 except HTTPError as e:
301 msg, data = self._get_extended_message(e)
302 return {
303 "ret": False,
304 "changed": False,
305 "msg": f"HTTP Error {e.code} on PATCH request to '{uri}', extended message: '{msg}'",
306 "status": e.code,
307 "data": data,
308 }
309 except URLError as e:
310 return {"ret": False, "changed": False, "msg": f"URL Error on PATCH request to '{uri}': '{e.reason}'"}
311 # Almost all errors should be caught above, but just in case
312 except Exception as e:
313 return {"ret": False, "changed": False, "msg": f"Failed PATCH request to '{uri}': '{e}'"}
314 return {"ret": True, "changed": True, "resp": resp, "msg": f"Modified {uri}"}
315
316 def put_request(self, uri: str, pyld):
317 req_headers = dict(PUT_HEADERS)
318 r = self.get_request(uri)
319 if r["ret"]:
320 # Get etag from etag header or @odata.etag property
321 etag = r["headers"].get("etag")
322 if not etag:
323 etag = r["data"].get("@odata.etag")
324 if etag:
325 if self.strip_etag_quotes:
326 etag = etag.strip('"')
327 req_headers["If-Match"] = etag
328 username, password, basic_auth = self._auth_params(req_headers)
329 try:
330 resp, dummy = self._request(
331 uri,
332 data=json.dumps(pyld),
333 headers=req_headers,
334 method="PUT",
335 url_username=username,
336 url_password=password,
337 force_basic_auth=basic_auth,
338 )
339 except HTTPError as e:
340 msg, data = self._get_extended_message(e)
341 return {
342 "ret": False,
343 "msg": f"HTTP Error {e.code} on PUT request to '{uri}', extended message: '{msg}'",
344 "status": e.code,
345 "data": data,
346 }
347 except URLError as e:
348 return {"ret": False, "msg": f"URL Error on PUT request to '{uri}': '{e.reason}'"}
349 # Almost all errors should be caught above, but just in case
350 except Exception as e:
351 return {"ret": False, "msg": f"Failed PUT request to '{uri}': '{e}'"}
352 return {"ret": True, "resp": resp}
353
354 def delete_request(self, uri: str, pyld=None):
355 req_headers = dict(DELETE_HEADERS)
356 username, password, basic_auth = self._auth_params(req_headers)
357 try:
358 data = json.dumps(pyld) if pyld else None
359 resp, dummy = self._request(
360 uri,
361 data=data,
362 headers=req_headers,
363 method="DELETE",
364 url_username=username,
365 url_password=password,
366 force_basic_auth=basic_auth,
367 )
368 except HTTPError as e:
369 msg, data = self._get_extended_message(e)
370 return {
371 "ret": False,
372 "msg": f"HTTP Error {e.code} on DELETE request to '{uri}', extended message: '{msg}'",
373 "status": e.code,
374 "data": data,
375 }
376 except URLError as e:
377 return {"ret": False, "msg": f"URL Error on DELETE request to '{uri}': '{e.reason}'"}
378 # Almost all errors should be caught above, but just in case
379 except Exception as e:
380 return {"ret": False, "msg": f"Failed DELETE request to '{uri}': '{e}'"}
381 return {"ret": True, "resp": resp}
382
383 @staticmethod
384 def _prepare_multipart(fields):
385 """Prepares a multipart body based on a set of fields provided.
386
387 Ideally it would have been good to use the existing 'prepare_multipart'
388 found in ansible.module_utils.urls, but it takes files and encodes them
389 as Base64 strings, which is not expected by Redfish services. It also
390 adds escaping of certain bytes in the payload, such as inserting '\r'
391 any time it finds a standalone '\n', which corrupts the image payload
392 send to the service. This implementation is simplified to Redfish's
393 usage and doesn't necessarily represent an exhaustive method of
394 building multipart requests.
395 """
396
397 def write_buffer(body, line):
398 # Adds to the multipart body based on the provided data type
399 # At this time there is only support for strings, dictionaries, and bytes (default)
400 if isinstance(line, str):
401 body.append(to_bytes(line, encoding="utf-8"))
402 elif isinstance(line, dict):
403 body.append(to_bytes(json.dumps(line), encoding="utf-8"))
404 else:
405 body.append(line)
406 return
407
408 # Generate a random boundary marker; may need to consider probing the
409 # payload for potential conflicts in the future
410 boundary = "".join(random.choice(string.digits + string.ascii_letters) for i in range(30))
411 body = []
412 for form in fields:
413 # Fill in the form details
414 write_buffer(body, f"--{boundary}")
415
416 # Insert the headers (Content-Disposition and Content-Type)
417 if "filename" in fields[form]:
418 name = os.path.basename(fields[form]["filename"]).replace('"', '\\"')
419 write_buffer(
420 body, f'Content-Disposition: form-data; name="{to_text(form)}"; filename="{to_native(name)}"'
421 )
422 else:
423 write_buffer(body, f'Content-Disposition: form-data; name="{form}"')
424 write_buffer(body, f"Content-Type: {fields[form]['mime_type']}")
425 write_buffer(body, "")
426
427 # Insert the payload; read from the file if not given by the caller
428 if "content" not in fields[form]:
429 with open(to_bytes(fields[form]["filename"], errors="surrogate_or_strict"), "rb") as f:
430 fields[form]["content"] = f.read()
431 write_buffer(body, fields[form]["content"])
432
433 # Finalize the entire request
434 write_buffer(body, f"--{boundary}--")
435 write_buffer(body, "")
436 return (b"\r\n".join(body), f"multipart/form-data; boundary={boundary}")
437
438 @staticmethod
439 def _get_extended_message(error):
440 """
441 Get Redfish ExtendedInfo message from response payload if present
442 :param error: an HTTPError exception
443 :type error: HTTPError
444 :return: the ExtendedInfo message if present, else standard HTTP error
445 :return: the JSON data of the response if present
446 """
447 msg = http_client.responses.get(error.code, "")
448 data = None
449 if error.code >= HTTPStatus.BAD_REQUEST: # 4xx and 5xx errors
450 try:
451 body = error.read().decode("utf-8")
452 data = json.loads(body)
453 ext_info = data["error"]["@Message.ExtendedInfo"]
454 # if the ExtendedInfo contains a user friendly message send it
455 # otherwise try to send the entire contents of ExtendedInfo
456 try:
457 msg = ext_info[0]["Message"]
458 except Exception:
459 msg = str(data["error"]["@Message.ExtendedInfo"])
460 except Exception:
461 pass
462 return msg, data
463
464 def _get_vendor(self):
465 # If we got the vendor info once, don't get it again
466 if self._vendor is not None:
467 return {"ret": "True", "Vendor": self._vendor}
468
469 # Find the vendor info from the service root
470 response = self.get_request(self.root_uri + self.service_root)
471 if response["ret"] is False:
472 return {"ret": False, "Vendor": ""}
473 data = response["data"]
474
475 if "Vendor" in data:
476 # Extract the vendor string from the Vendor property
477 self._vendor = data["Vendor"]
478 return {"ret": True, "Vendor": data["Vendor"]}
479 elif "Oem" in data and len(data["Oem"]) > 0:
480 # Determine the vendor from the OEM object if needed
481 vendor = list(data["Oem"].keys())[0]
482 if vendor == "Hpe" or vendor == "Hp":
483 # HPE uses Pascal-casing for their OEM object
484 # Older systems reported 'Hp' (pre-split)
485 vendor = "HPE"
486 self._vendor = vendor
487 return {"ret": True, "Vendor": vendor}
488 else:
489 # Could not determine; use an empty string
490 self._vendor = ""
491 return {"ret": True, "Vendor": ""}
492
493 def _find_accountservice_resource(self):
494 response = self.get_request(self.root_uri + self.service_root)
495 if response["ret"] is False:
496 return response
497 data = response["data"]
498 if "AccountService" not in data:
499 return {"ret": False, "msg": "AccountService resource not found"}
500 else:
501 account_service = data["AccountService"]["@odata.id"]
502 response = self.get_request(self.root_uri + account_service)
503 if response["ret"] is False:
504 return response
505 data = response["data"]
506 accounts = data["Accounts"]["@odata.id"]
507 if accounts[-1:] == "/":
508 accounts = accounts[:-1]
509 self.accounts_uri = accounts
510 return {"ret": True}
511
512 def _find_sessionservice_resource(self):
513 # Get the service root
514 response = self.get_request(self.root_uri + self.service_root)
515 if response["ret"] is False:
516 return response
517 data = response["data"]
518
519 # Check for the session service and session collection. Well-known
520 # defaults are provided in the constructor, but services that predate
521 # Redfish 1.6.0 might contain different values.
522 self.session_service_uri = data.get("SessionService", {}).get("@odata.id")
523 self.sessions_uri = data.get("Links", {}).get("Sessions", {}).get("@odata.id")
524
525 # If one isn't found, return an error
526 if self.session_service_uri is None:
527 return {"ret": False, "msg": "SessionService resource not found"}
528 if self.sessions_uri is None:
529 return {"ret": False, "msg": "SessionCollection resource not found"}
530 return {"ret": True}
531
532 def _get_resource_uri_by_id(self, uris, id_prop):
533 for uri in uris:
534 response = self.get_request(self.root_uri + uri)
535 if response["ret"] is False:
536 continue
537 data = response["data"]
538 if id_prop == data.get("Id"):
539 return uri
540 return None
541
542 def _find_systems_resource(self):
543 response = self.get_request(self.root_uri + self.service_root)
544 if response["ret"] is False:
545 return response
546 data = response["data"]
547 if "Systems" not in data:
548 return {"ret": False, "msg": "Systems resource not found"}
549 response = self.get_request(self.root_uri + data["Systems"]["@odata.id"])
550 if response["ret"] is False:
551 return response
552 self.systems_uris = [i["@odata.id"] for i in response["data"].get("Members", [])]
553 if not self.systems_uris:
554 return {"ret": False, "msg": "ComputerSystem's Members array is either empty or missing"}
555 self.systems_uri = self.systems_uris[0]
556 if self.data_modification:
557 if self.resource_id:
558 self.systems_uri = self._get_resource_uri_by_id(self.systems_uris, self.resource_id)
559 if not self.systems_uri:
560 return {"ret": False, "msg": f"System resource {self.resource_id} not found"}
561 elif len(self.systems_uris) > 1:
562 self.module.fail_json(msg=FAIL_MSG % {"resource": "System"})
563 return {"ret": True}
564
565 def _find_updateservice_resource(self):
566 response = self.get_request(self.root_uri + self.service_root)
567 if response["ret"] is False:
568 return response
569 data = response["data"]
570 if "UpdateService" not in data:
571 return {"ret": False, "msg": "UpdateService resource not found"}
572 else:
573 update = data["UpdateService"]["@odata.id"]
574 self.update_uri = update
575 response = self.get_request(self.root_uri + update)
576 if response["ret"] is False:
577 return response
578 data = response["data"]
579 self.firmware_uri = self.software_uri = None
580 if "FirmwareInventory" in data:
581 self.firmware_uri = data["FirmwareInventory"]["@odata.id"]
582 if "SoftwareInventory" in data:
583 self.software_uri = data["SoftwareInventory"]["@odata.id"]
584 return {"ret": True}
585
586 def _find_chassis_resource(self):
587 response = self.get_request(self.root_uri + self.service_root)
588 if response["ret"] is False:
589 return response
590 data = response["data"]
591 if "Chassis" not in data:
592 return {"ret": False, "msg": "Chassis resource not found"}
593 chassis = data["Chassis"]["@odata.id"]
594 response = self.get_request(self.root_uri + chassis)
595 if response["ret"] is False:
596 return response
597 self.chassis_uris = [i["@odata.id"] for i in response["data"].get("Members", [])]
598 if not self.chassis_uris:
599 return {"ret": False, "msg": "Chassis Members array is either empty or missing"}
600 self.chassis_uri = self.chassis_uris[0]
601 if self.data_modification:
602 if self.resource_id:
603 self.chassis_uri = self._get_resource_uri_by_id(self.chassis_uris, self.resource_id)
604 if not self.chassis_uri:
605 return {"ret": False, "msg": f"Chassis resource {self.resource_id} not found"}
606 elif len(self.chassis_uris) > 1:
607 self.module.fail_json(msg=FAIL_MSG % {"resource": "Chassis"})
608 return {"ret": True}
609
610 def _find_managers_resource(self):
611 response = self.get_request(self.root_uri + self.service_root)
612 if response["ret"] is False:
613 return response
614 data = response["data"]
615 if "Managers" not in data:
616 return {"ret": False, "msg": "Manager resource not found"}
617 manager = data["Managers"]["@odata.id"]
618 response = self.get_request(self.root_uri + manager)
619 if response["ret"] is False:
620 return response
621 self.manager_uris = [i["@odata.id"] for i in response["data"].get("Members", [])]
622 if not self.manager_uris:
623 return {"ret": False, "msg": "Managers Members array is either empty or missing"}
624 self.manager_uri = self.manager_uris[0]
625 if self.data_modification:
626 if self.resource_id:
627 self.manager_uri = self._get_resource_uri_by_id(self.manager_uris, self.resource_id)
628 if not self.manager_uri:
629 return {"ret": False, "msg": f"Manager resource {self.resource_id} not found"}
630 elif len(self.manager_uris) > 1:
631 self.module.fail_json(msg=FAIL_MSG % {"resource": "Manager"})
632 return {"ret": True}
633
634 def _get_all_action_info_values(self, action):
635 """Retrieve all parameter values for an Action from ActionInfo.
636 Fall back to AllowableValue annotations if no ActionInfo found.
637 Return the result in an ActionInfo-like dictionary, keyed
638 by the name of the parameter."""
639 ai = {}
640 if "@Redfish.ActionInfo" in action:
641 ai_uri = action["@Redfish.ActionInfo"]
642 response = self.get_request(self.root_uri + ai_uri)
643 if response["ret"] is True:
644 data = response["data"]
645 if "Parameters" in data:
646 params = data["Parameters"]
647 ai = {p["Name"]: p for p in params if "Name" in p}
648 if not ai:
649 ai = {k[:-24]: {"AllowableValues": v} for k, v in action.items() if k.endswith("@Redfish.AllowableValues")}
650 return ai
651
652 def _get_allowable_values(self, action, name, default_values=None):
653 if default_values is None:
654 default_values = []
655 ai = self._get_all_action_info_values(action)
656 allowable_values = ai.get(name, {}).get("AllowableValues")
657 # fallback to default values
658 if allowable_values is None:
659 allowable_values = default_values
660 return allowable_values
661
662 def check_service_availability(self):
663 """
664 Checks if the service is accessible.
665
666 :return: dict containing the status of the service
667 """
668 result = {}
669 service_root_data = {}
670 # Get these entries, but does not fail if not found
671 properties = [
672 "Id",
673 "Name",
674 "RedfishVersion",
675 "Vendor",
676 "ServiceIdentification",
677 "ProtocolFeaturesSupported",
678 "UUID",
679 ]
680
681 # Get the service root
682 # Override the timeout since the service root is expected to be readily available.
683 service_root = self.get_request(self.root_uri + self.service_root, timeout=10)
684 if service_root["ret"] is False:
685 # Failed, either due to a timeout or HTTP error; not available
686 return {"ret": True, "available": False}
687
688 # Successfully accessed the service root; available
689 result["ret"] = True
690 result["available"] = True
691 data = service_root["data"]
692
693 for property in properties:
694 if property in data:
695 service_root_data[property] = data[property]
696
697 result["entries"] = service_root_data
698 return result
699
700 def get_logs(self):
701 log_svcs_uri_list = []
702 list_of_logs = []
703 properties = ["Severity", "Created", "EntryType", "OemRecordFormat", "Message", "MessageId", "MessageArgs"]
704
705 # Find LogService
706 response = self.get_request(self.root_uri + self.manager_uri)
707 if response["ret"] is False:
708 return response
709 data = response["data"]
710 if "LogServices" not in data:
711 return {"ret": False, "msg": "LogServices resource not found"}
712
713 # Find all entries in LogServices
714 logs_uri = data["LogServices"]["@odata.id"]
715 response = self.get_request(self.root_uri + logs_uri)
716 if response["ret"] is False:
717 return response
718 data = response["data"]
719 for log_svcs_entry in data.get("Members", []):
720 response = self.get_request(self.root_uri + log_svcs_entry["@odata.id"])
721 if response["ret"] is False:
722 return response
723 _data = response["data"]
724 if "Entries" in _data:
725 log_svcs_uri_list.append(_data["Entries"]["@odata.id"])
726
727 # For each entry in LogServices, get log name and all log entries
728 for log_svcs_uri in log_svcs_uri_list:
729 logs = {}
730 list_of_log_entries = []
731 response = self.get_request(self.root_uri + log_svcs_uri)
732 if response["ret"] is False:
733 return response
734 data = response["data"]
735 logs["Description"] = data.get("Description", "Collection of log entries")
736 # Get all log entries for each type of log found
737 for logEntry in data.get("Members", []):
738 entry = {}
739 for prop in properties:
740 if prop in logEntry:
741 entry[prop] = logEntry.get(prop)
742 if entry:
743 list_of_log_entries.append(entry)
744 log_name = log_svcs_uri.rstrip("/").split("/")[-1]
745 logs[log_name] = list_of_log_entries
746 list_of_logs.append(logs)
747
748 # list_of_logs[logs{list_of_log_entries[entry{}]}]
749 return {"ret": True, "entries": list_of_logs}
750
751 def clear_logs(self):
752 # Find LogService
753 response = self.get_request(self.root_uri + self.manager_uri)
754 if response["ret"] is False:
755 return response
756 data = response["data"]
757 if "LogServices" not in data:
758 return {"ret": False, "msg": "LogServices resource not found"}
759
760 # Find all entries in LogServices
761 logs_uri = data["LogServices"]["@odata.id"]
762 response = self.get_request(self.root_uri + logs_uri)
763 if response["ret"] is False:
764 return response
765 data = response["data"]
766
767 for log_svcs_entry in data["Members"]:
768 response = self.get_request(self.root_uri + log_svcs_entry["@odata.id"])
769 if response["ret"] is False:
770 return response
771 _data = response["data"]
772 # Check to make sure option is available, otherwise error is ugly
773 if "Actions" in _data:
774 if "#LogService.ClearLog" in _data["Actions"]:
775 self.post_request(self.root_uri + _data["Actions"]["#LogService.ClearLog"]["target"], {})
776 if response["ret"] is False:
777 return response
778 return {"ret": True}
779
780 def aggregate(self, func, uri_list, uri_name):
781 ret = True
782 entries = []
783 for uri in uri_list:
784 inventory = func(uri)
785 ret = inventory.pop("ret") and ret
786 if "entries" in inventory:
787 entries.append(({uri_name: uri}, inventory["entries"]))
788 return dict(ret=ret, entries=entries)
789
790 def aggregate_chassis(self, func):
791 return self.aggregate(func, self.chassis_uris, "chassis_uri")
792
793 def aggregate_managers(self, func):
794 return self.aggregate(func, self.manager_uris, "manager_uri")
795
796 def aggregate_systems(self, func):
797 return self.aggregate(func, self.systems_uris, "system_uri")
798
799 def get_storage_controller_inventory(self, systems_uri):
800 result = {}
801 controller_list = []
802 controller_results = []
803 # Get these entries, but does not fail if not found
804 properties = [
805 "CacheSummary",
806 "FirmwareVersion",
807 "Identifiers",
808 "Location",
809 "Manufacturer",
810 "Model",
811 "Name",
812 "Id",
813 "PartNumber",
814 "SerialNumber",
815 "SpeedGbps",
816 "Status",
817 ]
818 key = "Controllers"
819 deprecated_key = "StorageControllers"
820
821 # Find Storage service
822 response = self.get_request(self.root_uri + systems_uri)
823 if response["ret"] is False:
824 return response
825 data = response["data"]
826
827 if "Storage" not in data:
828 return {"ret": False, "msg": "Storage resource not found"}
829
830 # Get a list of all storage controllers and build respective URIs
831 storage_uri = data["Storage"]["@odata.id"]
832 response = self.get_request(self.root_uri + storage_uri)
833 if response["ret"] is False:
834 return response
835 result["ret"] = True
836 data = response["data"]
837
838 # Loop through Members and their StorageControllers
839 # and gather properties from each StorageController
840 if data["Members"]:
841 for storage_member in data["Members"]:
842 storage_member_uri = storage_member["@odata.id"]
843 response = self.get_request(self.root_uri + storage_member_uri)
844 data = response["data"]
845
846 if key in data:
847 controllers_uri = data[key]["@odata.id"]
848
849 response = self.get_request(self.root_uri + controllers_uri)
850 if response["ret"] is False:
851 return response
852 result["ret"] = True
853 data = response["data"]
854
855 if data["Members"]:
856 for controller_member in data["Members"]:
857 controller_member_uri = controller_member["@odata.id"]
858 response = self.get_request(self.root_uri + controller_member_uri)
859 if response["ret"] is False:
860 return response
861 result["ret"] = True
862 data = response["data"]
863
864 controller_result = {}
865 for property in properties:
866 if property in data:
867 controller_result[property] = data[property]
868 controller_results.append(controller_result)
869 elif deprecated_key in data:
870 controller_list = data[deprecated_key]
871 for controller in controller_list:
872 controller_result = {}
873 for property in properties:
874 if property in controller:
875 controller_result[property] = controller[property]
876 controller_results.append(controller_result)
877 result["entries"] = controller_results
878 return result
879 else:
880 return {"ret": False, "msg": "Storage resource not found"}
881
882 def get_multi_storage_controller_inventory(self):
883 return self.aggregate_systems(self.get_storage_controller_inventory)
884
885 def get_disk_inventory(self, systems_uri):
886 result = {"entries": []}
887 controller_list = []
888 # Get these entries, but does not fail if not found
889 properties = [
890 "BlockSizeBytes",
891 "CapableSpeedGbs",
892 "CapacityBytes",
893 "EncryptionAbility",
894 "EncryptionStatus",
895 "FailurePredicted",
896 "HotspareType",
897 "Id",
898 "Identifiers",
899 "Links",
900 "Manufacturer",
901 "MediaType",
902 "Model",
903 "Name",
904 "PartNumber",
905 "PhysicalLocation",
906 "Protocol",
907 "Revision",
908 "RotationSpeedRPM",
909 "SerialNumber",
910 "Status",
911 ]
912
913 # Find Storage service
914 response = self.get_request(self.root_uri + systems_uri)
915 if response["ret"] is False:
916 return response
917 data = response["data"]
918
919 if "SimpleStorage" not in data and "Storage" not in data:
920 return {
921 "ret": False,
922 "msg": "SimpleStorage and Storage resource \
923 not found",
924 }
925
926 if "Storage" in data:
927 # Get a list of all storage controllers and build respective URIs
928 storage_uri = data["Storage"]["@odata.id"]
929 response = self.get_request(self.root_uri + storage_uri)
930 if response["ret"] is False:
931 return response
932 result["ret"] = True
933 data = response["data"]
934
935 if data["Members"]:
936 for controller in data["Members"]:
937 controller_list.append(controller["@odata.id"])
938 for c in controller_list:
939 uri = self.root_uri + c
940 response = self.get_request(uri)
941 if response["ret"] is False:
942 return response
943 data = response["data"]
944 controller_name = "Controller 1"
945 storage_id = data["Id"]
946 if "Controllers" in data:
947 controllers_uri = data["Controllers"]["@odata.id"]
948
949 response = self.get_request(self.root_uri + controllers_uri)
950 if response["ret"] is False:
951 return response
952 result["ret"] = True
953 cdata = response["data"]
954
955 if cdata["Members"]:
956 controller_member_uri = cdata["Members"][0]["@odata.id"]
957
958 response = self.get_request(self.root_uri + controller_member_uri)
959 if response["ret"] is False:
960 return response
961 result["ret"] = True
962 cdata = response["data"]
963 controller_name = cdata["Name"]
964 elif "StorageControllers" in data:
965 sc = data["StorageControllers"]
966 if sc:
967 if "Name" in sc[0]:
968 controller_name = sc[0]["Name"]
969 else:
970 sc_id = sc[0].get("Id", "1")
971 controller_name = f"Controller {sc_id}"
972 drive_results = []
973 if "Drives" in data:
974 for device in data["Drives"]:
975 disk_uri = self.root_uri + device["@odata.id"]
976 response = self.get_request(disk_uri)
977 data = response["data"]
978
979 drive_result = {}
980 drive_result["RedfishURI"] = data["@odata.id"]
981 for property in properties:
982 if property in data:
983 if data[property] is not None:
984 if property == "Links":
985 if "Volumes" in data["Links"].keys():
986 volumes = [v["@odata.id"] for v in data["Links"]["Volumes"]]
987 drive_result["Volumes"] = volumes
988 else:
989 drive_result[property] = data[property]
990 drive_results.append(drive_result)
991 drives = {"Controller": controller_name, "StorageId": storage_id, "Drives": drive_results}
992 result["entries"].append(drives)
993
994 if "SimpleStorage" in data:
995 # Get a list of all storage controllers and build respective URIs
996 storage_uri = data["SimpleStorage"]["@odata.id"]
997 response = self.get_request(self.root_uri + storage_uri)
998 if response["ret"] is False:
999 return response
1000 result["ret"] = True
1001 data = response["data"]
1002
1003 for controller in data["Members"]:
1004 controller_list.append(controller["@odata.id"])
1005
1006 for c in controller_list:
1007 uri = self.root_uri + c
1008 response = self.get_request(uri)
1009 if response["ret"] is False:
1010 return response
1011 data = response["data"]
1012 if "Name" in data:
1013 controller_name = data["Name"]
1014 else:
1015 sc_id = data.get("Id", "1")
1016 controller_name = f"Controller {sc_id}"
1017 drive_results = []
1018 for device in data["Devices"]:
1019 drive_result = {}
1020 for property in properties:
1021 if property in device:
1022 drive_result[property] = device[property]
1023 drive_results.append(drive_result)
1024 drives = {"Controller": controller_name, "Drives": drive_results}
1025 result["entries"].append(drives)
1026
1027 return result
1028
1029 def get_multi_disk_inventory(self):
1030 return self.aggregate_systems(self.get_disk_inventory)
1031
1032 def get_volume_inventory(self, systems_uri):
1033 result = {"entries": []}
1034 controller_list = []
1035 volume_list = []
1036 # Get these entries, but does not fail if not found
1037 properties = [
1038 "Id",
1039 "Name",
1040 "RAIDType",
1041 "VolumeType",
1042 "BlockSizeBytes",
1043 "Capacity",
1044 "CapacityBytes",
1045 "CapacitySources",
1046 "Encrypted",
1047 "EncryptionTypes",
1048 "Identifiers",
1049 "Operations",
1050 "OptimumIOSizeBytes",
1051 "AccessCapabilities",
1052 "AllocatedPools",
1053 "Status",
1054 ]
1055
1056 # Find Storage service
1057 response = self.get_request(self.root_uri + systems_uri)
1058 if response["ret"] is False:
1059 return response
1060 data = response["data"]
1061
1062 if "SimpleStorage" not in data and "Storage" not in data:
1063 return {
1064 "ret": False,
1065 "msg": "SimpleStorage and Storage resource \
1066 not found",
1067 }
1068
1069 if "Storage" in data:
1070 # Get a list of all storage controllers and build respective URIs
1071 storage_uri = data["Storage"]["@odata.id"]
1072 response = self.get_request(self.root_uri + storage_uri)
1073 if response["ret"] is False:
1074 return response
1075 result["ret"] = True
1076 data = response["data"]
1077
1078 if data.get("Members"):
1079 for controller in data["Members"]:
1080 controller_list.append(controller["@odata.id"])
1081 for idx, c in enumerate(controller_list):
1082 uri = self.root_uri + c
1083 response = self.get_request(uri)
1084 if response["ret"] is False:
1085 return response
1086 data = response["data"]
1087 controller_name = f"Controller {idx}"
1088 if "Controllers" in data:
1089 response = self.get_request(self.root_uri + data["Controllers"]["@odata.id"])
1090 if response["ret"] is False:
1091 return response
1092 c_data = response["data"]
1093
1094 if c_data.get("Members") and c_data["Members"]:
1095 response = self.get_request(self.root_uri + c_data["Members"][0]["@odata.id"])
1096 if response["ret"] is False:
1097 return response
1098 member_data = response["data"]
1099
1100 if member_data:
1101 if "Name" in member_data:
1102 controller_name = member_data["Name"]
1103 else:
1104 controller_id = member_data.get("Id", "1")
1105 controller_name = f"Controller {controller_id}"
1106 elif "StorageControllers" in data:
1107 sc = data["StorageControllers"]
1108 if sc:
1109 if "Name" in sc[0]:
1110 controller_name = sc[0]["Name"]
1111 else:
1112 sc_id = sc[0].get("Id", "1")
1113 controller_name = f"Controller {sc_id}"
1114 volume_results = []
1115 volume_list = []
1116 if "Volumes" in data:
1117 # Get a list of all volumes and build respective URIs
1118 volumes_uri = data["Volumes"]["@odata.id"]
1119 response = self.get_request(self.root_uri + volumes_uri)
1120 data = response["data"]
1121
1122 if data.get("Members"):
1123 for volume in data["Members"]:
1124 volume_list.append(volume["@odata.id"])
1125 for v in volume_list:
1126 uri = self.root_uri + v
1127 response = self.get_request(uri)
1128 if response["ret"] is False:
1129 return response
1130 data = response["data"]
1131
1132 volume_result = {}
1133 for property in properties:
1134 if property in data:
1135 if data[property] is not None:
1136 volume_result[property] = data[property]
1137
1138 # Get related Drives Id
1139 drive_id_list = []
1140 if "Links" in data:
1141 if "Drives" in data["Links"]:
1142 for link in data["Links"]["Drives"]:
1143 drive_id_link = link["@odata.id"]
1144 drive_id = drive_id_link.rstrip("/").split("/")[-1]
1145 drive_id_list.append({"Id": drive_id})
1146 volume_result["Linked_drives"] = drive_id_list
1147 volume_results.append(volume_result)
1148 volumes = {"Controller": controller_name, "Volumes": volume_results}
1149 result["entries"].append(volumes)
1150 else:
1151 return {"ret": False, "msg": "Storage resource not found"}
1152
1153 return result
1154
1155 def get_multi_volume_inventory(self):
1156 return self.aggregate_systems(self.get_volume_inventory)
1157
1158 def manage_system_indicator_led(self, command):
1159 return self.manage_indicator_led(command, self.systems_uri)
1160
1161 def manage_chassis_indicator_led(self, command):
1162 return self.manage_indicator_led(command, self.chassis_uri)
1163
1164 def manage_indicator_led(self, command, resource_uri=None):
1165 # If no resource is specified; default to the Chassis resource
1166 if resource_uri is None:
1167 resource_uri = self.chassis_uri
1168
1169 # Perform a PATCH on the IndicatorLED property based on the requested command
1170 payloads = {"IndicatorLedOn": "Lit", "IndicatorLedOff": "Off", "IndicatorLedBlink": "Blinking"}
1171 if command not in payloads.keys():
1172 return {"ret": False, "msg": f"Invalid command ({command})"}
1173 payload = {"IndicatorLED": payloads[command]}
1174 resp = self.patch_request(self.root_uri + resource_uri, payload, check_pyld=True)
1175 if resp["ret"] and resp["changed"]:
1176 resp["msg"] = f"Set IndicatorLED to {payloads[command]}"
1177 return resp
1178
1179 def _map_reset_type(self, reset_type, allowable_values):
1180 equiv_types = {
1181 "On": "ForceOn",
1182 "ForceOn": "On",
1183 "ForceOff": "GracefulShutdown",
1184 "GracefulShutdown": "ForceOff",
1185 "GracefulRestart": "ForceRestart",
1186 "ForceRestart": "GracefulRestart",
1187 }
1188
1189 if reset_type in allowable_values:
1190 return reset_type
1191 if reset_type not in equiv_types:
1192 return reset_type
1193 mapped_type = equiv_types[reset_type]
1194 if mapped_type in allowable_values:
1195 return mapped_type
1196 return reset_type
1197
1198 def manage_system_power(self, command):
1199 return self.manage_power(command, self.systems_uri, "#ComputerSystem.Reset")
1200
1201 def manage_manager_power(self, command, wait=False, wait_timeout=120):
1202 return self.manage_power(command, self.manager_uri, "#Manager.Reset", wait, wait_timeout)
1203
1204 def manage_power(self, command, resource_uri, action_name, wait=False, wait_timeout=120):
1205 key = "Actions"
1206 reset_type_values = [
1207 "On",
1208 "ForceOff",
1209 "GracefulShutdown",
1210 "GracefulRestart",
1211 "ForceRestart",
1212 "Nmi",
1213 "ForceOn",
1214 "PushPowerButton",
1215 "PowerCycle",
1216 "FullPowerCycle",
1217 ]
1218
1219 # command should be PowerOn, PowerForceOff, etc.
1220 if not command.startswith("Power"):
1221 return {"ret": False, "msg": f"Invalid Command ({command})"}
1222
1223 # Commands (except PowerCycle) will be stripped of the 'Power' prefix
1224 if command == "PowerCycle":
1225 reset_type = command
1226 else:
1227 reset_type = command[5:]
1228
1229 # map Reboot to a ResetType that does a reboot
1230 if reset_type == "Reboot":
1231 reset_type = "GracefulRestart"
1232
1233 if reset_type not in reset_type_values:
1234 return {"ret": False, "msg": f"Invalid Command ({command})"}
1235
1236 # read the resource and get the current power state
1237 response = self.get_request(self.root_uri + resource_uri)
1238 if response["ret"] is False:
1239 return response
1240 data = response["data"]
1241 power_state = data.get("PowerState")
1242
1243 # if power is already in target state, nothing to do
1244 if power_state == "On" and reset_type in ["On", "ForceOn"]:
1245 return {"ret": True, "changed": False}
1246 if power_state == "Off" and reset_type in ["GracefulShutdown", "ForceOff"]:
1247 return {"ret": True, "changed": False}
1248
1249 # get the reset Action and target URI
1250 if key not in data or action_name not in data[key]:
1251 return {"ret": False, "msg": f"Action {action_name} not found"}
1252 reset_action = data[key][action_name]
1253 if "target" not in reset_action:
1254 return {"ret": False, "msg": f"target URI missing from Action {action_name}"}
1255 action_uri = reset_action["target"]
1256
1257 # get AllowableValues
1258 ai = self._get_all_action_info_values(reset_action)
1259 allowable_values = ai.get("ResetType", {}).get("AllowableValues", [])
1260
1261 # map ResetType to an allowable value if needed
1262 if reset_type not in allowable_values:
1263 reset_type = self._map_reset_type(reset_type, allowable_values)
1264
1265 # define payload
1266 payload = {"ResetType": reset_type}
1267
1268 # POST to Action URI
1269 response = self.post_request(self.root_uri + action_uri, payload)
1270 if response["ret"] is False:
1271 return response
1272
1273 # If requested to wait for the service to be available again, block
1274 # until it is ready
1275 if wait:
1276 elapsed_time = 0
1277 start_time = time.time()
1278 # Start with a large enough sleep. Some services will process new
1279 # requests while in the middle of shutting down, thus breaking out
1280 # early.
1281 time.sleep(30)
1282
1283 # Periodically check for the service's availability.
1284 while elapsed_time <= wait_timeout:
1285 status = self.check_service_availability()
1286 if status["available"]:
1287 # It is available; we are done
1288 break
1289 time.sleep(5)
1290 elapsed_time = time.time() - start_time
1291
1292 if elapsed_time > wait_timeout:
1293 # Exhausted the wait timer; error
1294 return {
1295 "ret": False,
1296 "changed": True,
1297 "msg": f"The service did not become available after {int(wait_timeout)} seconds",
1298 }
1299 return {"ret": True, "changed": True}
1300
1301 def manager_reset_to_defaults(self, command):
1302 return self.reset_to_defaults(command, self.manager_uri, "#Manager.ResetToDefaults")
1303
1304 def reset_to_defaults(self, command, resource_uri, action_name):
1305 key = "Actions"
1306 reset_type_values = ["ResetAll", "PreserveNetworkAndUsers", "PreserveNetwork"]
1307
1308 if command not in reset_type_values:
1309 return {"ret": False, "msg": f"Invalid Command ({command})"}
1310
1311 # read the resource and get the current power state
1312 response = self.get_request(self.root_uri + resource_uri)
1313 if response["ret"] is False:
1314 return response
1315 data = response["data"]
1316
1317 # get the reset Action and target URI
1318 if key not in data or action_name not in data[key]:
1319 return {"ret": False, "msg": f"Action {action_name} not found"}
1320 reset_action = data[key][action_name]
1321 if "target" not in reset_action:
1322 return {"ret": False, "msg": f"target URI missing from Action {action_name}"}
1323 action_uri = reset_action["target"]
1324
1325 # get AllowableValues
1326 ai = self._get_all_action_info_values(reset_action)
1327 allowable_values = ai.get("ResetType", {}).get("AllowableValues", [])
1328
1329 # map ResetType to an allowable value if needed
1330 if allowable_values and command not in allowable_values:
1331 return {
1332 "ret": False,
1333 "msg": f"Specified reset type ({command}) not supported by service. Supported types: {allowable_values}",
1334 }
1335
1336 # define payload
1337 payload = {"ResetType": command}
1338
1339 # POST to Action URI
1340 response = self.post_request(self.root_uri + action_uri, payload)
1341 if response["ret"] is False:
1342 return response
1343 return {"ret": True, "changed": True}
1344
1345 def _find_account_uri(self, username=None, acct_id=None, password_change_uri=None):
1346 if not any((username, acct_id)):
1347 return {"ret": False, "msg": "Must provide either account_id or account_username"}
1348
1349 if password_change_uri:
1350 # Password change required; go directly to the specified URI
1351 response = self.get_request(self.root_uri + password_change_uri)
1352 if response["ret"] is False:
1353 return response
1354 data = response["data"]
1355 headers = response["headers"]
1356 if username:
1357 if username == data.get("UserName"):
1358 return {"ret": True, "data": data, "headers": headers, "uri": password_change_uri}
1359 if acct_id:
1360 if acct_id == data.get("Id"):
1361 return {"ret": True, "data": data, "headers": headers, "uri": password_change_uri}
1362 else:
1363 # Walk the accounts collection to find the desired user
1364 response = self.get_request(self.root_uri + self.accounts_uri)
1365 if response["ret"] is False:
1366 return response
1367 data = response["data"]
1368
1369 uris = [a.get("@odata.id") for a in data.get("Members", []) if a.get("@odata.id")]
1370 for uri in uris:
1371 response = self.get_request(self.root_uri + uri)
1372 if response["ret"] is False:
1373 continue
1374 data = response["data"]
1375 headers = response["headers"]
1376 if username:
1377 if username == data.get("UserName"):
1378 return {"ret": True, "data": data, "headers": headers, "uri": uri}
1379 if acct_id:
1380 if acct_id == data.get("Id"):
1381 return {"ret": True, "data": data, "headers": headers, "uri": uri}
1382
1383 return {"ret": False, "no_match": True, "msg": "No account with the given account_id or account_username found"}
1384
1385 def _find_empty_account_slot(self):
1386 response = self.get_request(self.root_uri + self.accounts_uri)
1387 if response["ret"] is False:
1388 return response
1389 data = response["data"]
1390
1391 uris = [a.get("@odata.id") for a in data.get("Members", []) if a.get("@odata.id")]
1392 if uris:
1393 # first slot may be reserved, so move to end of list
1394 uris += [uris.pop(0)]
1395 for uri in uris:
1396 response = self.get_request(self.root_uri + uri)
1397 if response["ret"] is False:
1398 continue
1399 data = response["data"]
1400 headers = response["headers"]
1401 if data.get("UserName") == "" and not data.get("Enabled", True):
1402 return {"ret": True, "data": data, "headers": headers, "uri": uri}
1403
1404 return {"ret": False, "no_match": True, "msg": "No empty account slot found"}
1405
1406 def list_users(self):
1407 result = {}
1408 # listing all users has always been slower than other operations, why?
1409 user_list = []
1410 users_results = []
1411 # Get these entries, but does not fail if not found
1412 properties = ["Id", "Name", "UserName", "RoleId", "Locked", "Enabled", "AccountTypes", "OEMAccountTypes"]
1413
1414 response = self.get_request(self.root_uri + self.accounts_uri)
1415 if response["ret"] is False:
1416 return response
1417 result["ret"] = True
1418 data = response["data"]
1419
1420 for users in data.get("Members", []):
1421 user_list.append(users["@odata.id"]) # user_list[] are URIs
1422
1423 # for each user, get details
1424 for uri in user_list:
1425 user = {}
1426 response = self.get_request(self.root_uri + uri)
1427 if response["ret"] is False:
1428 return response
1429 data = response["data"]
1430
1431 for property in properties:
1432 if property in data:
1433 user[property] = data[property]
1434
1435 # Filter out empty account slots
1436 # An empty account slot can be detected if the username is an empty
1437 # string and if the account is disabled
1438 if user.get("UserName", "") == "" and not user.get("Enabled", False):
1439 continue
1440
1441 users_results.append(user)
1442 result["entries"] = users_results
1443 return result
1444
1445 def add_user_via_patch(self, user):
1446 if user.get("account_id"):
1447 # If Id slot specified, use it
1448 response = self._find_account_uri(acct_id=user.get("account_id"))
1449 else:
1450 # Otherwise find first empty slot
1451 response = self._find_empty_account_slot()
1452
1453 if not response["ret"]:
1454 return response
1455 uri = response["uri"]
1456 payload = {}
1457 if user.get("account_username"):
1458 payload["UserName"] = user.get("account_username")
1459 if user.get("account_password"):
1460 payload["Password"] = user.get("account_password")
1461 if user.get("account_roleid"):
1462 payload["RoleId"] = user.get("account_roleid")
1463 if user.get("account_accounttypes"):
1464 payload["AccountTypes"] = user.get("account_accounttypes")
1465 if user.get("account_oemaccounttypes"):
1466 payload["OEMAccountTypes"] = user.get("account_oemaccounttypes")
1467 return self.patch_request(self.root_uri + uri, payload, check_pyld=True)
1468
1469 def add_user(self, user):
1470 if not user.get("account_username"):
1471 return {"ret": False, "msg": "Must provide account_username for AddUser command"}
1472
1473 response = self._find_account_uri(username=user.get("account_username"))
1474 if response["ret"]:
1475 # account_username already exists, nothing to do
1476 return {"ret": True, "changed": False}
1477
1478 response = self.get_request(self.root_uri + self.accounts_uri)
1479 if not response["ret"]:
1480 return response
1481 headers = response["headers"]
1482
1483 if "allow" in headers:
1484 methods = [m.strip() for m in headers.get("allow").split(",")]
1485 if "POST" not in methods:
1486 # if Allow header present and POST not listed, add via PATCH
1487 return self.add_user_via_patch(user)
1488
1489 payload = {}
1490 if user.get("account_username"):
1491 payload["UserName"] = user.get("account_username")
1492 if user.get("account_password"):
1493 payload["Password"] = user.get("account_password")
1494 if user.get("account_roleid"):
1495 payload["RoleId"] = user.get("account_roleid")
1496 if user.get("account_accounttypes"):
1497 payload["AccountTypes"] = user.get("account_accounttypes")
1498 if user.get("account_oemaccounttypes"):
1499 payload["OEMAccountTypes"] = user.get("account_oemaccounttypes")
1500 if user.get("account_id"):
1501 payload["Id"] = user.get("account_id")
1502
1503 response = self.post_request(self.root_uri + self.accounts_uri, payload)
1504 if not response["ret"]:
1505 if response.get("status") == HTTPStatus.METHOD_NOT_ALLOWED:
1506 # if POST is not allowed, try to add via PATCH
1507 return self.add_user_via_patch(user)
1508 else:
1509 return response
1510 return {"ret": True}
1511
1512 def enable_user(self, user):
1513 response = self._find_account_uri(username=user.get("account_username"), acct_id=user.get("account_id"))
1514 if not response["ret"]:
1515 return response
1516 uri = response["uri"]
1517
1518 payload = {"Enabled": True}
1519 return self.patch_request(self.root_uri + uri, payload, check_pyld=True)
1520
1521 def delete_user_via_patch(self, user, uri=None, data=None):
1522 if not uri:
1523 response = self._find_account_uri(username=user.get("account_username"), acct_id=user.get("account_id"))
1524 if not response["ret"]:
1525 return response
1526 uri = response["uri"]
1527 data = response["data"]
1528
1529 payload = {"UserName": ""}
1530 if data.get("Enabled", False):
1531 payload["Enabled"] = False
1532 return self.patch_request(self.root_uri + uri, payload, check_pyld=True)
1533
1534 def delete_user(self, user):
1535 response = self._find_account_uri(username=user.get("account_username"), acct_id=user.get("account_id"))
1536 if not response["ret"]:
1537 if response.get("no_match"):
1538 # account does not exist, nothing to do
1539 return {"ret": True, "changed": False}
1540 else:
1541 # some error encountered
1542 return response
1543
1544 uri = response["uri"]
1545 headers = response["headers"]
1546 data = response["data"]
1547
1548 if "allow" in headers:
1549 methods = [m.strip() for m in headers.get("allow").split(",")]
1550 if "DELETE" not in methods:
1551 # if Allow header present and DELETE not listed, del via PATCH
1552 return self.delete_user_via_patch(user, uri=uri, data=data)
1553
1554 response = self.delete_request(self.root_uri + uri)
1555 if not response["ret"]:
1556 if response.get("status") == HTTPStatus.METHOD_NOT_ALLOWED:
1557 # if DELETE is not allowed, try to delete via PATCH
1558 return self.delete_user_via_patch(user, uri=uri, data=data)
1559 else:
1560 return response
1561 return {"ret": True}
1562
1563 def disable_user(self, user):
1564 response = self._find_account_uri(username=user.get("account_username"), acct_id=user.get("account_id"))
1565 if not response["ret"]:
1566 return response
1567
1568 uri = response["uri"]
1569 payload = {"Enabled": False}
1570 return self.patch_request(self.root_uri + uri, payload, check_pyld=True)
1571
1572 def update_user_role(self, user):
1573 if not user.get("account_roleid"):
1574 return {"ret": False, "msg": "Must provide account_roleid for UpdateUserRole command"}
1575
1576 response = self._find_account_uri(username=user.get("account_username"), acct_id=user.get("account_id"))
1577 if not response["ret"]:
1578 return response
1579
1580 uri = response["uri"]
1581 payload = {"RoleId": user["account_roleid"]}
1582 return self.patch_request(self.root_uri + uri, payload, check_pyld=True)
1583
1584 def update_user_password(self, user):
1585 if not user.get("account_password"):
1586 return {"ret": False, "msg": "Must provide account_password for UpdateUserPassword command"}
1587
1588 response = self._find_account_uri(
1589 username=user.get("account_username"),
1590 acct_id=user.get("account_id"),
1591 password_change_uri=user.get("account_passwordchangerequired"),
1592 )
1593 if not response["ret"]:
1594 return response
1595
1596 uri = response["uri"]
1597 payload = {"Password": user["account_password"]}
1598 return self.patch_request(self.root_uri + uri, payload, check_pyld=True)
1599
1600 def update_user_name(self, user):
1601 if not user.get("account_updatename"):
1602 return {"ret": False, "msg": "Must provide account_updatename for UpdateUserName command"}
1603
1604 response = self._find_account_uri(username=user.get("account_username"), acct_id=user.get("account_id"))
1605 if not response["ret"]:
1606 return response
1607
1608 uri = response["uri"]
1609 payload = {"UserName": user["account_updatename"]}
1610 return self.patch_request(self.root_uri + uri, payload, check_pyld=True)
1611
1612 def update_accountservice_properties(self, user):
1613 account_properties = user.get("account_properties")
1614 if account_properties is None:
1615 return {"ret": False, "msg": "Must provide account_properties for UpdateAccountServiceProperties command"}
1616
1617 # Find the AccountService resource
1618 response = self.get_request(self.root_uri + self.service_root)
1619 if response["ret"] is False:
1620 return response
1621 data = response["data"]
1622 accountservice_uri = data.get("AccountService", {}).get("@odata.id")
1623 if accountservice_uri is None:
1624 return {"ret": False, "msg": "AccountService resource not found"}
1625
1626 # Perform a PATCH on the AccountService resource with the requested properties
1627 resp = self.patch_request(self.root_uri + accountservice_uri, account_properties, check_pyld=True)
1628 if resp["ret"] and resp["changed"]:
1629 resp["msg"] = "Modified account service"
1630 return resp
1631
1632 def update_user_accounttypes(self, user):
1633 account_types = user.get("account_accounttypes")
1634 oemaccount_types = user.get("account_oemaccounttypes")
1635 if account_types is None and oemaccount_types is None:
1636 return {
1637 "ret": False,
1638 "msg": "Must provide account_accounttypes or account_oemaccounttypes for UpdateUserAccountTypes command",
1639 }
1640
1641 response = self._find_account_uri(username=user.get("account_username"), acct_id=user.get("account_id"))
1642 if not response["ret"]:
1643 return response
1644
1645 uri = response["uri"]
1646 payload = {}
1647 if user.get("account_accounttypes"):
1648 payload["AccountTypes"] = user.get("account_accounttypes")
1649 if user.get("account_oemaccounttypes"):
1650 payload["OEMAccountTypes"] = user.get("account_oemaccounttypes")
1651
1652 return self.patch_request(self.root_uri + uri, payload, check_pyld=True)
1653
1654 def check_password_change_required(self, return_data):
1655 """
1656 Checks a response if a user needs to change their password
1657
1658 :param return_data: The return data for a failed request
1659 :return: None or the URI of the account to update
1660 """
1661 uri = None
1662 if "data" in return_data:
1663 # Find the extended messages in the response payload
1664 extended_messages = return_data["data"].get("error", {}).get("@Message.ExtendedInfo", [])
1665 if len(extended_messages) == 0:
1666 extended_messages = return_data["data"].get("@Message.ExtendedInfo", [])
1667 # Go through each message and look for Base.1.X.PasswordChangeRequired
1668 for message in extended_messages:
1669 message_id = message.get("MessageId")
1670 if message_id is None:
1671 # While this is invalid, treat the lack of a MessageId as "no message"
1672 continue
1673 if message_id.startswith("Base.1.") and message_id.endswith(".PasswordChangeRequired"):
1674 # Password change required; get the URI of the user account
1675 uri = message["MessageArgs"][0]
1676 break
1677 return uri
1678
1679 def get_sessions(self):
1680 result = {}
1681 # listing all users has always been slower than other operations, why?
1682 session_list = []
1683 sessions_results = []
1684 # Get these entries, but does not fail if not found
1685 properties = ["Description", "Id", "Name", "UserName"]
1686
1687 response = self.get_request(self.root_uri + self.sessions_uri)
1688 if response["ret"] is False:
1689 return response
1690 result["ret"] = True
1691 data = response["data"]
1692
1693 for sessions in data["Members"]:
1694 session_list.append(sessions["@odata.id"]) # session_list[] are URIs
1695
1696 # for each session, get details
1697 for uri in session_list:
1698 session = {}
1699 response = self.get_request(self.root_uri + uri)
1700 if response["ret"] is False:
1701 return response
1702 data = response["data"]
1703
1704 for property in properties:
1705 if property in data:
1706 session[property] = data[property]
1707
1708 sessions_results.append(session)
1709 result["entries"] = sessions_results
1710 return result
1711
1712 def clear_sessions(self):
1713 response = self.get_request(self.root_uri + self.sessions_uri)
1714 if response["ret"] is False:
1715 return response
1716 data = response["data"]
1717
1718 # if no active sessions, return as success
1719 if data["[email protected]"] == 0:
1720 return {"ret": True, "changed": False, "msg": "There are no active sessions"}
1721
1722 # loop to delete every active session
1723 for session in data["Members"]:
1724 response = self.delete_request(self.root_uri + session["@odata.id"])
1725 if response["ret"] is False:
1726 return response
1727
1728 return {"ret": True, "changed": True, "msg": "Cleared all sessions successfully"}
1729
1730 def create_session(self):
1731 if not self.creds.get("user") or not self.creds.get("pswd"):
1732 return {
1733 "ret": False,
1734 "msg": "Must provide the username and password parameters for the CreateSession command",
1735 }
1736
1737 payload = {"UserName": self.creds["user"], "Password": self.creds["pswd"]}
1738 response = self.post_request(self.root_uri + self.sessions_uri, payload)
1739 if response["ret"] is False:
1740 return response
1741
1742 headers = response["headers"]
1743 if "x-auth-token" not in headers:
1744 return {
1745 "ret": False,
1746 "msg": "The service did not return the X-Auth-Token header in "
1747 "the response from the Sessions collection POST",
1748 }
1749
1750 if "location" not in headers:
1751 self.module.warn(
1752 "The service did not return the Location header for the "
1753 "session URL in the response from the Sessions collection "
1754 "POST"
1755 )
1756 session_uri = None
1757 else:
1758 session_uri = urlparse(headers.get("location")).path
1759
1760 session = dict()
1761 session["token"] = headers.get("x-auth-token")
1762 session["uri"] = session_uri
1763 return {"ret": True, "changed": True, "session": session, "msg": "Session created successfully"}
1764
1765 def delete_session(self, session_uri):
1766 if not session_uri:
1767 return {"ret": False, "msg": "Must provide the session_uri parameter for the DeleteSession command"}
1768
1769 response = self.delete_request(self.root_uri + session_uri)
1770 if response["ret"] is False:
1771 return response
1772
1773 return {"ret": True, "changed": True, "msg": "Session deleted successfully"}
1774
1775 def get_firmware_update_capabilities(self):
1776 result = {}
1777 response = self.get_request(self.root_uri + self.update_uri)
1778 if response["ret"] is False:
1779 return response
1780
1781 result["ret"] = True
1782
1783 result["entries"] = {}
1784
1785 data = response["data"]
1786
1787 result["multipart_supported"] = "MultipartHttpPushUri" in data
1788
1789 if "Actions" in data:
1790 actions = data["Actions"]
1791 if len(actions) > 0:
1792 for key in actions.keys():
1793 action = actions.get(key)
1794 if "title" in action:
1795 title = action["title"]
1796 else:
1797 title = key
1798 result["entries"][title] = action.get(
1799 "[email protected]",
1800 ["Key [email protected] not found"],
1801 )
1802 else:
1803 return {"ret": "False", "msg": "Actions list is empty."}
1804 else:
1805 return {"ret": "False", "msg": "Key Actions not found."}
1806 return result
1807
1808 def _software_inventory(self, uri):
1809 result = {}
1810 result["entries"] = []
1811
1812 while uri:
1813 response = self.get_request(self.root_uri + uri)
1814 if response["ret"] is False:
1815 return response
1816 result["ret"] = True
1817
1818 data = response["data"]
1819 if data.get("[email protected]"):
1820 uri = data.get("[email protected]")
1821 else:
1822 uri = None
1823
1824 for member in data["Members"]:
1825 fw_uri = self.root_uri + member["@odata.id"]
1826 # Get details for each software or firmware member
1827 response = self.get_request(fw_uri)
1828 if response["ret"] is False:
1829 return response
1830 result["ret"] = True
1831 data = response["data"]
1832 software = {}
1833 # Get these standard properties if present
1834 for key in [
1835 "Name",
1836 "Id",
1837 "Status",
1838 "Version",
1839 "Updateable",
1840 "SoftwareId",
1841 "LowestSupportedVersion",
1842 "Manufacturer",
1843 "ReleaseDate",
1844 ]:
1845 if key in data:
1846 software[key] = data.get(key)
1847 result["entries"].append(software)
1848
1849 return result
1850
1851 def get_firmware_inventory(self):
1852 if self.firmware_uri is None:
1853 return {"ret": False, "msg": "No FirmwareInventory resource found"}
1854 else:
1855 return self._software_inventory(self.firmware_uri)
1856
1857 def get_software_inventory(self):
1858 if self.software_uri is None:
1859 return {"ret": False, "msg": "No SoftwareInventory resource found"}
1860 else:
1861 return self._software_inventory(self.software_uri)
1862
1863 def _operation_results(self, response, data, handle=None):
1864 """
1865 Builds the results for an operation from task, job, or action response.
1866
1867 :param response: HTTP response object
1868 :param data: HTTP response data
1869 :param handle: The task or job handle that was last used
1870 :return: dict containing operation results
1871 """
1872
1873 operation_results = {"status": None, "messages": [], "handle": None, "ret": True, "resets_requested": []}
1874
1875 if response.status == HTTPStatus.NO_CONTENT:
1876 # No content; successful, but nothing to return
1877 # Use the Redfish "Completed" enum from TaskState for the operation status
1878 operation_results["status"] = "Completed"
1879 else:
1880 # Parse the response body for details
1881
1882 # Determine the next handle, if any
1883 operation_results["handle"] = handle
1884 if response.status == HTTPStatus.ACCEPTED:
1885 # Task generated; get the task monitor URI
1886 operation_results["handle"] = response.getheader("Location", handle)
1887
1888 # Pull out the status and messages based on the body format
1889 if data is not None:
1890 response_type = data.get("@odata.type", "")
1891 if response_type.startswith("#Task.") or response_type.startswith("#Job."):
1892 # Task and Job have similar enough structures to treat the same
1893 operation_results["status"] = data.get("TaskState", data.get("JobState"))
1894 operation_results["messages"] = data.get("Messages", [])
1895 else:
1896 # Error response body, which is a bit of a misnomer since it is used in successful action responses
1897 operation_results["status"] = "Completed"
1898 if response.status >= HTTPStatus.BAD_REQUEST: # 4xx and 5xx errors
1899 operation_results["status"] = "Exception"
1900 operation_results["messages"] = data.get("error", {}).get("@Message.ExtendedInfo", [])
1901 else:
1902 # No response body (or malformed); build based on status code
1903 operation_results["status"] = "Completed"
1904 if response.status == HTTPStatus.ACCEPTED:
1905 operation_results["status"] = "New"
1906 elif response.status >= HTTPStatus.BAD_REQUEST: # 4xx and 5xx errors
1907 operation_results["status"] = "Exception"
1908
1909 # Clear out the handle if the operation is complete
1910 if operation_results["status"] in ["Completed", "Cancelled", "Exception", "Killed"]:
1911 operation_results["handle"] = None
1912
1913 # Scan the messages to see if next steps are needed
1914 for message in operation_results["messages"]:
1915 message_id = message.get("MessageId")
1916 if message_id is None:
1917 # While this is invalid, treat the lack of a MessageId as "no message"
1918 continue
1919
1920 if message_id.startswith("Update.1.") and message_id.endswith(".OperationTransitionedToJob"):
1921 # Operation rerouted to a job; update the status and handle
1922 operation_results["status"] = "New"
1923 operation_results["handle"] = message["MessageArgs"][0]
1924 operation_results["resets_requested"] = []
1925 # No need to process other messages in this case
1926 break
1927
1928 if message_id.startswith("Base.1.") and message_id.endswith(".ResetRequired"):
1929 # A reset to some device is needed to continue the update
1930 reset = {"uri": message["MessageArgs"][0], "type": message["MessageArgs"][1]}
1931 operation_results["resets_requested"].append(reset)
1932
1933 return operation_results
1934
1935 def simple_update(self, update_opts):
1936 image_uri = update_opts.get("update_image_uri")
1937 protocol = update_opts.get("update_protocol")
1938 targets = update_opts.get("update_targets")
1939 creds = update_opts.get("update_creds")
1940 apply_time = update_opts.get("update_apply_time")
1941
1942 if not image_uri:
1943 return {"ret": False, "msg": "Must specify update_image_uri for the SimpleUpdate command"}
1944
1945 response = self.get_request(self.root_uri + self.update_uri)
1946 if response["ret"] is False:
1947 return response
1948 data = response["data"]
1949 if "Actions" not in data:
1950 return {"ret": False, "msg": "Service does not support SimpleUpdate"}
1951 if "#UpdateService.SimpleUpdate" not in data["Actions"]:
1952 return {"ret": False, "msg": "Service does not support SimpleUpdate"}
1953 action = data["Actions"]["#UpdateService.SimpleUpdate"]
1954 if "target" not in action:
1955 return {"ret": False, "msg": "Service does not support SimpleUpdate"}
1956 update_uri = action["target"]
1957 if protocol:
1958 default_values = ["CIFS", "FTP", "SFTP", "HTTP", "HTTPS", "NSF", "SCP", "TFTP", "OEM", "NFS"]
1959 allowable_values = self._get_allowable_values(action, "TransferProtocol", default_values)
1960 if protocol not in allowable_values:
1961 return {
1962 "ret": False,
1963 "msg": f"Specified update_protocol ({protocol}) not supported by service. Supported protocols: {allowable_values}",
1964 }
1965 if targets:
1966 allowable_values = self._get_allowable_values(action, "Targets")
1967 if allowable_values:
1968 for target in targets:
1969 if target not in allowable_values:
1970 return {
1971 "ret": False,
1972 "msg": f"Specified target ({target}) not supported by service. Supported targets: {allowable_values}",
1973 }
1974
1975 payload = {"ImageURI": image_uri}
1976 if protocol:
1977 payload["TransferProtocol"] = protocol
1978 if targets:
1979 payload["Targets"] = targets
1980 if creds:
1981 if creds.get("username"):
1982 payload["Username"] = creds.get("username")
1983 if creds.get("password"):
1984 payload["Password"] = creds.get("password")
1985 if apply_time:
1986 payload["@Redfish.OperationApplyTime"] = apply_time
1987 response = self.post_request(self.root_uri + update_uri, payload)
1988 if response["ret"] is False:
1989 return response
1990 return {
1991 "ret": True,
1992 "changed": True,
1993 "msg": "SimpleUpdate requested",
1994 "update_status": self._operation_results(response["resp"], response["data"]),
1995 }
1996
1997 def multipath_http_push_update(self, update_opts):
1998 """
1999 Provides a software update via the URI specified by the
2000 MultipartHttpPushUri property. Callers should adjust the 'timeout'
2001 variable in the base object to accommodate the size of the image and
2002 speed of the transfer. For example, a 200MB image will likely take
2003 more than the default 10 second timeout.
2004
2005 :param update_opts: The parameters for the update operation
2006 :return: dict containing the response of the update request
2007 """
2008 image_file = update_opts.get("update_image_file")
2009 targets = update_opts.get("update_targets")
2010 apply_time = update_opts.get("update_apply_time")
2011 oem_params = update_opts.get("update_oem_params")
2012 custom_oem_header = update_opts.get("update_custom_oem_header")
2013 custom_oem_mime_type = update_opts.get("update_custom_oem_mime_type")
2014 custom_oem_params = update_opts.get("update_custom_oem_params")
2015
2016 # Ensure the image file is provided
2017 if not image_file:
2018 return {"ret": False, "msg": "Must specify update_image_file for the MultipartHTTPPushUpdate command"}
2019 if not os.path.isfile(image_file):
2020 return {"ret": False, "msg": "Must specify a valid file for the MultipartHTTPPushUpdate command"}
2021 try:
2022 with open(image_file, "rb") as f:
2023 image_payload = f.read()
2024 except Exception:
2025 return {"ret": False, "msg": f"Could not read file {image_file}"}
2026
2027 # Check that multipart HTTP push updates are supported
2028 response = self.get_request(self.root_uri + self.update_uri)
2029 if response["ret"] is False:
2030 return response
2031 data = response["data"]
2032 if "MultipartHttpPushUri" not in data:
2033 return {"ret": False, "msg": "Service does not support MultipartHttpPushUri"}
2034 update_uri = data["MultipartHttpPushUri"]
2035
2036 # Assemble the JSON payload portion of the request
2037 payload = {}
2038 if targets:
2039 payload["Targets"] = targets
2040 if apply_time:
2041 payload["@Redfish.OperationApplyTime"] = apply_time
2042 if oem_params:
2043 payload["Oem"] = oem_params
2044 multipart_payload = {
2045 "UpdateParameters": {"content": json.dumps(payload), "mime_type": "application/json"},
2046 "UpdateFile": {"filename": image_file, "content": image_payload, "mime_type": "application/octet-stream"},
2047 }
2048 if custom_oem_params:
2049 multipart_payload[custom_oem_header] = {"content": custom_oem_params}
2050 if custom_oem_mime_type:
2051 multipart_payload[custom_oem_header]["mime_type"] = custom_oem_mime_type
2052
2053 response = self.post_request(self.root_uri + update_uri, multipart_payload, multipart=True)
2054 if response["ret"] is False:
2055 return response
2056 return {
2057 "ret": True,
2058 "changed": True,
2059 "msg": "MultipartHTTPPushUpdate requested",
2060 "update_status": self._operation_results(response["resp"], response["data"]),
2061 }
2062
2063 def get_update_status(self, update_handle):
2064 """
2065 Gets the status of an update operation.
2066
2067 :param handle: The task or job handle tracking the update
2068 :return: dict containing the response of the update status
2069 """
2070
2071 if not update_handle:
2072 return {"ret": False, "msg": "Must provide a handle tracking the update."}
2073
2074 # Get the task or job tracking the update
2075 response = self.get_request(self.root_uri + update_handle, allow_no_resp=True)
2076 if response["ret"] is False:
2077 return response
2078
2079 # Inspect the response to build the update status
2080 return self._operation_results(response["resp"], response["data"], update_handle)
2081
2082 def perform_requested_update_operations(self, update_handle):
2083 """
2084 Performs requested operations to allow the update to continue.
2085
2086 :param handle: The task or job handle tracking the update
2087 :return: dict containing the result of the operations
2088 """
2089
2090 # Get the current update status
2091 update_status = self.get_update_status(update_handle)
2092 if update_status["ret"] is False:
2093 return update_status
2094
2095 changed = False
2096
2097 # Perform any requested updates
2098 for reset in update_status["resets_requested"]:
2099 resp = self.post_request(self.root_uri + reset["uri"], {"ResetType": reset["type"]})
2100 if resp["ret"] is False:
2101 # Override the 'changed' indicator since other resets may have
2102 # been successful
2103 resp["changed"] = changed
2104 return resp
2105 changed = True
2106
2107 msg = "No operations required for the update"
2108 if changed:
2109 # Will need to consider finetuning this message if the scope of the
2110 # requested operations grow over time
2111 msg = "One or more components reset to continue the update"
2112 return {"ret": True, "changed": changed, "msg": msg}
2113
2114 def get_bios_attributes(self, systems_uri):
2115 result = {}
2116 bios_attributes = {}
2117 key = "Bios"
2118
2119 # Search for 'key' entry and extract URI from it
2120 response = self.get_request(self.root_uri + systems_uri)
2121 if response["ret"] is False:
2122 return response
2123 result["ret"] = True
2124 data = response["data"]
2125
2126 if key not in data:
2127 return {"ret": False, "msg": f"Key {key} not found"}
2128
2129 bios_uri = data[key]["@odata.id"]
2130
2131 response = self.get_request(self.root_uri + bios_uri)
2132 if response["ret"] is False:
2133 return response
2134 result["ret"] = True
2135 data = response["data"]
2136 for attribute in data["Attributes"].items():
2137 bios_attributes[attribute[0]] = attribute[1]
2138 result["entries"] = bios_attributes
2139 return result
2140
2141 def get_multi_bios_attributes(self):
2142 return self.aggregate_systems(self.get_bios_attributes)
2143
2144 def _get_boot_options_dict(self, boot):
2145 # Get these entries from BootOption, if present
2146 properties = ["DisplayName", "BootOptionReference"]
2147
2148 # Retrieve BootOptions if present
2149 if "BootOptions" in boot and "@odata.id" in boot["BootOptions"]:
2150 boot_options_uri = boot["BootOptions"]["@odata.id"]
2151 # Get BootOptions resource
2152 response = self.get_request(self.root_uri + boot_options_uri)
2153 if response["ret"] is False:
2154 return {}
2155 data = response["data"]
2156
2157 # Retrieve Members array
2158 if "Members" not in data:
2159 return {}
2160 members = data["Members"]
2161 else:
2162 members = []
2163
2164 # Build dict of BootOptions keyed by BootOptionReference
2165 boot_options_dict = {}
2166 for member in members:
2167 if "@odata.id" not in member:
2168 return {}
2169 boot_option_uri = member["@odata.id"]
2170 response = self.get_request(self.root_uri + boot_option_uri)
2171 if response["ret"] is False:
2172 return {}
2173 data = response["data"]
2174 if "BootOptionReference" not in data:
2175 return {}
2176 boot_option_ref = data["BootOptionReference"]
2177
2178 # fetch the props to display for this boot device
2179 boot_props = {}
2180 for prop in properties:
2181 if prop in data:
2182 boot_props[prop] = data[prop]
2183
2184 boot_options_dict[boot_option_ref] = boot_props
2185
2186 return boot_options_dict
2187
2188 def get_boot_order(self, systems_uri):
2189 result = {}
2190
2191 # Retrieve System resource
2192 response = self.get_request(self.root_uri + systems_uri)
2193 if response["ret"] is False:
2194 return response
2195 result["ret"] = True
2196 data = response["data"]
2197
2198 # Confirm needed Boot properties are present
2199 if "Boot" not in data or "BootOrder" not in data["Boot"]:
2200 return {"ret": False, "msg": "Key BootOrder not found"}
2201
2202 boot = data["Boot"]
2203 boot_order = boot["BootOrder"]
2204 boot_options_dict = self._get_boot_options_dict(boot)
2205
2206 # Build boot device list
2207 boot_device_list = []
2208 for ref in boot_order:
2209 boot_device_list.append(boot_options_dict.get(ref, {"BootOptionReference": ref}))
2210
2211 result["entries"] = boot_device_list
2212 return result
2213
2214 def get_multi_boot_order(self):
2215 return self.aggregate_systems(self.get_boot_order)
2216
2217 def get_boot_override(self, systems_uri):
2218 result = {}
2219
2220 properties = [
2221 "BootSourceOverrideEnabled",
2222 "BootSourceOverrideTarget",
2223 "BootSourceOverrideMode",
2224 "UefiTargetBootSourceOverride",
2225 "[email protected]",
2226 ]
2227
2228 response = self.get_request(self.root_uri + systems_uri)
2229 if response["ret"] is False:
2230 return response
2231 result["ret"] = True
2232 data = response["data"]
2233
2234 if "Boot" not in data:
2235 return {"ret": False, "msg": "Key Boot not found"}
2236
2237 boot = data["Boot"]
2238
2239 boot_overrides = {}
2240 if "BootSourceOverrideEnabled" in boot:
2241 if boot["BootSourceOverrideEnabled"] is not False:
2242 for property in properties:
2243 if property in boot:
2244 if boot[property] is not None:
2245 boot_overrides[property] = boot[property]
2246 else:
2247 return {"ret": False, "msg": "No boot override is enabled."}
2248
2249 result["entries"] = boot_overrides
2250 return result
2251
2252 def get_multi_boot_override(self):
2253 return self.aggregate_systems(self.get_boot_override)
2254
2255 def set_bios_default_settings(self):
2256 # Find the Bios resource from the requested ComputerSystem resource
2257 response = self.get_request(self.root_uri + self.systems_uri)
2258 if response["ret"] is False:
2259 return response
2260 data = response["data"]
2261 bios_uri = data.get("Bios", {}).get("@odata.id")
2262 if bios_uri is None:
2263 return {"ret": False, "msg": "Bios resource not found"}
2264
2265 # Find the URI of the ResetBios action
2266 response = self.get_request(self.root_uri + bios_uri)
2267 if response["ret"] is False:
2268 return response
2269 data = response["data"]
2270 reset_bios_uri = data.get("Actions", {}).get("#Bios.ResetBios", {}).get("target")
2271 if reset_bios_uri is None:
2272 return {"ret": False, "msg": "ResetBios action not found"}
2273
2274 # Perform the ResetBios action
2275 response = self.post_request(self.root_uri + reset_bios_uri, {})
2276 if response["ret"] is False:
2277 return response
2278 return {"ret": True, "changed": True, "msg": "BIOS set to default settings"}
2279
2280 def set_boot_override_with_settings_uri(self, boot_opts):
2281 # Extract the requested boot override options
2282 bootdevice = boot_opts.get("bootdevice")
2283 uefi_target = boot_opts.get("uefi_target")
2284 boot_next = boot_opts.get("boot_next")
2285 override_enabled = boot_opts.get("override_enabled")
2286 boot_override_mode = boot_opts.get("boot_override_mode")
2287 if not bootdevice and override_enabled != "Disabled":
2288 return {"ret": False, "msg": "bootdevice option required for temporary boot override"}
2289
2290 # Get the current boot override options from the Boot property
2291 response = self.get_request(self.root_uri + self.systems_uri)
2292 if response["ret"] is False:
2293 return response
2294 data = response["data"]
2295 current_boot = data.get("Boot")
2296 if current_boot is None:
2297 return {"ret": False, "msg": "Boot property not found"}
2298 cur_override_mode = current_boot.get("BootSourceOverrideMode")
2299 rfsettings = data.get("@Redfish.Settings")
2300
2301 settings_uri = rfsettings["SettingsObject"]["@odata.id"]
2302 response = self.get_request(self.root_uri + settings_uri)
2303 if response["ret"] is False:
2304 return response
2305 data = response["data"]
2306 future_boot = data.get("Boot")
2307
2308 # Check if the requested target is supported by the system
2309 if override_enabled != "Disabled":
2310 annotation = "[email protected]"
2311 if annotation in future_boot:
2312 allowable_values = future_boot[annotation]
2313 if isinstance(allowable_values, list) and bootdevice not in allowable_values:
2314 return {
2315 "ret": False,
2316 "msg": f"Boot device {bootdevice} not in list of allowable values ({allowable_values})",
2317 }
2318
2319 # Build the request payload based on the desired boot override options
2320 if override_enabled == "Disabled":
2321 payload = {"Boot": {"BootSourceOverrideEnabled": override_enabled, "BootSourceOverrideTarget": "None"}}
2322 elif bootdevice == "UefiTarget":
2323 if not uefi_target:
2324 return {"ret": False, "msg": "uefi_target option required to SetOneTimeBoot for UefiTarget"}
2325 payload = {
2326 "Boot": {
2327 "BootSourceOverrideEnabled": override_enabled,
2328 "BootSourceOverrideTarget": bootdevice,
2329 "UefiTargetBootSourceOverride": uefi_target,
2330 }
2331 }
2332 # If needed, also specify UEFI mode
2333 if cur_override_mode == "Legacy":
2334 payload["Boot"]["BootSourceOverrideMode"] = "UEFI"
2335 elif bootdevice == "UefiBootNext":
2336 if not boot_next:
2337 return {"ret": False, "msg": "boot_next option required to SetOneTimeBoot for UefiBootNext"}
2338 payload = {
2339 "Boot": {
2340 "BootSourceOverrideEnabled": override_enabled,
2341 "BootSourceOverrideTarget": bootdevice,
2342 "BootNext": boot_next,
2343 }
2344 }
2345 # If needed, also specify UEFI mode
2346 if cur_override_mode == "Legacy":
2347 payload["Boot"]["BootSourceOverrideMode"] = "UEFI"
2348 else:
2349 payload = {"Boot": {"BootSourceOverrideEnabled": override_enabled, "BootSourceOverrideTarget": bootdevice}}
2350 if boot_override_mode:
2351 payload["Boot"]["BootSourceOverrideMode"] = boot_override_mode
2352
2353 # Apply the requested boot override request
2354 resp = self.patch_request(self.root_uri + settings_uri, payload, check_pyld=True)
2355 if resp["ret"] is False:
2356 # WORKAROUND
2357 # Older Dell systems do not allow BootSourceOverrideEnabled to be
2358 # specified with UefiTarget as the target device
2359 vendor = self._get_vendor()["Vendor"]
2360 if vendor == "Dell":
2361 if bootdevice == "UefiTarget" and override_enabled != "Disabled":
2362 payload["Boot"].pop("BootSourceOverrideEnabled", None)
2363 resp = self.patch_request(self.root_uri + settings_uri, payload, check_pyld=True)
2364 if resp["ret"] and resp["changed"]:
2365 resp["msg"] = "Updated the boot override settings"
2366 return resp
2367
2368 def set_boot_override(self, boot_opts):
2369 # Extract the requested boot override options
2370 bootdevice = boot_opts.get("bootdevice")
2371 uefi_target = boot_opts.get("uefi_target")
2372 boot_next = boot_opts.get("boot_next")
2373 override_enabled = boot_opts.get("override_enabled")
2374 boot_override_mode = boot_opts.get("boot_override_mode")
2375 if not bootdevice and override_enabled != "Disabled":
2376 return {"ret": False, "msg": "bootdevice option required for temporary boot override"}
2377
2378 # Get the current boot override options from the Boot property
2379 response = self.get_request(self.root_uri + self.systems_uri)
2380 if response["ret"] is False:
2381 return response
2382 data = response["data"]
2383 rfsettings = data.get("@Redfish.Settings")
2384 boot = data.get("Boot")
2385 if boot is None:
2386 return {"ret": False, "msg": "Boot property not found"}
2387 cur_override_mode = boot.get("BootSourceOverrideMode")
2388
2389 # Check if the requested target is supported by the system
2390 if override_enabled != "Disabled":
2391 annotation = "[email protected]"
2392 if annotation in boot:
2393 allowable_values = boot[annotation]
2394 if isinstance(allowable_values, list) and bootdevice not in allowable_values:
2395 return {
2396 "ret": False,
2397 "msg": f"Boot device {bootdevice} not in list of allowable values ({allowable_values})",
2398 }
2399
2400 # Build the request payload based on the desired boot override options
2401 if override_enabled == "Disabled":
2402 payload = {"Boot": {"BootSourceOverrideEnabled": override_enabled, "BootSourceOverrideTarget": "None"}}
2403 elif bootdevice == "UefiTarget":
2404 if not uefi_target:
2405 return {"ret": False, "msg": "uefi_target option required to SetOneTimeBoot for UefiTarget"}
2406 payload = {
2407 "Boot": {
2408 "BootSourceOverrideEnabled": override_enabled,
2409 "BootSourceOverrideTarget": bootdevice,
2410 "UefiTargetBootSourceOverride": uefi_target,
2411 }
2412 }
2413 # If needed, also specify UEFI mode
2414 if cur_override_mode == "Legacy":
2415 payload["Boot"]["BootSourceOverrideMode"] = "UEFI"
2416 elif bootdevice == "UefiBootNext":
2417 if not boot_next:
2418 return {"ret": False, "msg": "boot_next option required to SetOneTimeBoot for UefiBootNext"}
2419 payload = {
2420 "Boot": {
2421 "BootSourceOverrideEnabled": override_enabled,
2422 "BootSourceOverrideTarget": bootdevice,
2423 "BootNext": boot_next,
2424 }
2425 }
2426 # If needed, also specify UEFI mode
2427 if cur_override_mode == "Legacy":
2428 payload["Boot"]["BootSourceOverrideMode"] = "UEFI"
2429 else:
2430 payload = {"Boot": {"BootSourceOverrideEnabled": override_enabled, "BootSourceOverrideTarget": bootdevice}}
2431 if boot_override_mode:
2432 payload["Boot"]["BootSourceOverrideMode"] = boot_override_mode
2433
2434 # Apply the requested boot override request
2435 resp = self.patch_request(self.root_uri + self.systems_uri, payload, check_pyld=True)
2436 if resp["ret"] is False:
2437 vendor = self._get_vendor()["Vendor"]
2438 if vendor == "Dell":
2439 # WORKAROUND
2440 # Newer Dell systems (iDRAC10) do not allow to PATCH ComputerSystem resource
2441 # directly. Need to PATCH Settings URI
2442 if rfsettings:
2443 return self.set_boot_override_with_settings_uri(boot_opts)
2444
2445 # WORKAROUND
2446 # Older Dell systems do not allow BootSourceOverrideEnabled to be
2447 # specified with UefiTarget as the target device
2448 if bootdevice == "UefiTarget" and override_enabled != "Disabled":
2449 payload["Boot"].pop("BootSourceOverrideEnabled", None)
2450 resp = self.patch_request(self.root_uri + self.systems_uri, payload, check_pyld=True)
2451
2452 if resp["ret"] and resp["changed"]:
2453 resp["msg"] = "Updated the boot override settings"
2454 return resp
2455
2456 def set_bios_attributes(self, attributes):
2457 # Find the Bios resource from the requested ComputerSystem resource
2458 response = self.get_request(self.root_uri + self.systems_uri)
2459 if response["ret"] is False:
2460 return response
2461 data = response["data"]
2462 bios_uri = data.get("Bios", {}).get("@odata.id")
2463 if bios_uri is None:
2464 return {"ret": False, "msg": "Bios resource not found"}
2465
2466 # Get the current BIOS settings
2467 response = self.get_request(self.root_uri + bios_uri)
2468 if response["ret"] is False:
2469 return response
2470 data = response["data"]
2471
2472 # Make a copy of the attributes dict
2473 attrs_to_patch = dict(attributes)
2474 # List to hold attributes not found
2475 attrs_bad = {}
2476
2477 # Check the attributes
2478 for attr_name, attr_value in attributes.items():
2479 # Check if attribute exists
2480 if attr_name not in data["Attributes"]:
2481 # Remove and proceed to next attribute if this isn't valid
2482 attrs_bad.update({attr_name: attr_value})
2483 del attrs_to_patch[attr_name]
2484 continue
2485
2486 # If already set to requested value, remove it from PATCH payload
2487 if data["Attributes"][attr_name] == attr_value:
2488 del attrs_to_patch[attr_name]
2489
2490 warning = ""
2491 if attrs_bad:
2492 warning = f"Unsupported attributes {attrs_bad}"
2493
2494 # Return success w/ changed=False if no attrs need to be changed
2495 if not attrs_to_patch:
2496 return {"ret": True, "changed": False, "msg": "BIOS attributes already set", "warning": warning}
2497
2498 # Get the SettingsObject URI to apply the attributes
2499 set_bios_attr_uri = data.get("@Redfish.Settings", {}).get("SettingsObject", {}).get("@odata.id")
2500 if set_bios_attr_uri is None:
2501 return {"ret": False, "msg": "Settings resource for BIOS attributes not found."}
2502
2503 # Construct payload and issue PATCH command
2504 payload = {"Attributes": attrs_to_patch}
2505
2506 # WORKAROUND
2507 # Dell systems require manually setting the apply time to "OnReset"
2508 # to spawn a proprietary job to apply the BIOS settings
2509 vendor = self._get_vendor()["Vendor"]
2510 if vendor == "Dell":
2511 payload.update({"@Redfish.SettingsApplyTime": {"ApplyTime": "OnReset"}})
2512
2513 response = self.patch_request(self.root_uri + set_bios_attr_uri, payload)
2514 if response["ret"] is False:
2515 return response
2516 return {
2517 "ret": True,
2518 "changed": True,
2519 "msg": f"Modified BIOS attributes {attrs_to_patch}. A reboot is required",
2520 "warning": warning,
2521 }
2522
2523 def set_boot_order(self, boot_list):
2524 if not boot_list:
2525 return {"ret": False, "msg": "boot_order list required for SetBootOrder command"}
2526
2527 systems_uri = self.systems_uri
2528 response = self.get_request(self.root_uri + systems_uri)
2529 if response["ret"] is False:
2530 return response
2531 data = response["data"]
2532
2533 # Confirm needed Boot properties are present
2534 if "Boot" not in data or "BootOrder" not in data["Boot"]:
2535 return {"ret": False, "msg": "Key BootOrder not found"}
2536
2537 boot = data["Boot"]
2538 # boot_order = boot["BootOrder"] - TODO is this needed?
2539 boot_options_dict = self._get_boot_options_dict(boot)
2540
2541 # Verify the requested boot options are valid
2542 if boot_options_dict:
2543 boot_option_references = boot_options_dict.keys()
2544 for ref in boot_list:
2545 if ref not in boot_option_references:
2546 return {"ret": False, "msg": f"BootOptionReference {ref} not found in BootOptions"}
2547
2548 # Apply the boot order
2549 payload = {"Boot": {"BootOrder": boot_list}}
2550 resp = self.patch_request(self.root_uri + systems_uri, payload, check_pyld=True)
2551 if resp["ret"] and resp["changed"]:
2552 resp["msg"] = "Modified the boot order"
2553 return resp
2554
2555 def set_default_boot_order(self):
2556 systems_uri = self.systems_uri
2557 response = self.get_request(self.root_uri + systems_uri)
2558 if response["ret"] is False:
2559 return response
2560 data = response["data"]
2561
2562 # get the #ComputerSystem.SetDefaultBootOrder Action and target URI
2563 action = "#ComputerSystem.SetDefaultBootOrder"
2564 if "Actions" not in data or action not in data["Actions"]:
2565 return {"ret": False, "msg": f"Action {action} not found"}
2566 if "target" not in data["Actions"][action]:
2567 return {"ret": False, "msg": f"target URI missing from Action {action}"}
2568 action_uri = data["Actions"][action]["target"]
2569
2570 # POST to Action URI
2571 payload = {}
2572 response = self.post_request(self.root_uri + action_uri, payload)
2573 if response["ret"] is False:
2574 return response
2575 return {"ret": True, "changed": True, "msg": "BootOrder set to default"}
2576
2577 def get_chassis_inventory(self):
2578 result = {}
2579 chassis_results = []
2580
2581 # Get these entries, but does not fail if not found
2582 properties = [
2583 "Name",
2584 "Id",
2585 "ChassisType",
2586 "PartNumber",
2587 "AssetTag",
2588 "Manufacturer",
2589 "IndicatorLED",
2590 "SerialNumber",
2591 "Model",
2592 ]
2593
2594 # Go through list
2595 for chassis_uri in self.chassis_uris:
2596 response = self.get_request(self.root_uri + chassis_uri)
2597 if response["ret"] is False:
2598 return response
2599 result["ret"] = True
2600 data = response["data"]
2601 chassis_result = {}
2602 for property in properties:
2603 if property in data:
2604 chassis_result[property] = data[property]
2605 chassis_results.append(chassis_result)
2606
2607 result["entries"] = chassis_results
2608 return result
2609
2610 def get_fan_inventory(self):
2611 result = {}
2612 fan_results = []
2613 key = "Thermal"
2614 # Get these entries, but does not fail if not found
2615 properties = ["Name", "FanName", "Reading", "ReadingUnits", "Status"]
2616
2617 # Go through list
2618 for chassis_uri in self.chassis_uris:
2619 response = self.get_request(self.root_uri + chassis_uri)
2620 if response["ret"] is False:
2621 return response
2622 result["ret"] = True
2623 data = response["data"]
2624 if key in data:
2625 # match: found an entry for "Thermal" information = fans
2626 thermal_uri = data[key]["@odata.id"]
2627 response = self.get_request(self.root_uri + thermal_uri)
2628 if response["ret"] is False:
2629 return response
2630 result["ret"] = True
2631 data = response["data"]
2632
2633 # Checking if fans are present
2634 if "Fans" in data:
2635 for device in data["Fans"]:
2636 fan = {}
2637 for property in properties:
2638 if property in device:
2639 fan[property] = device[property]
2640 fan_results.append(fan)
2641 else:
2642 return {"ret": False, "msg": "No Fans present"}
2643 result["entries"] = fan_results
2644 return result
2645
2646 def get_chassis_power(self):
2647 result = {}
2648 key = "Power"
2649
2650 # Get these entries, but does not fail if not found
2651 properties = [
2652 "Name",
2653 "PowerAllocatedWatts",
2654 "PowerAvailableWatts",
2655 "PowerCapacityWatts",
2656 "PowerConsumedWatts",
2657 "PowerMetrics",
2658 "PowerRequestedWatts",
2659 "RelatedItem",
2660 "Status",
2661 ]
2662
2663 chassis_power_results = []
2664 # Go through list
2665 for chassis_uri in self.chassis_uris:
2666 chassis_power_result = {}
2667 response = self.get_request(self.root_uri + chassis_uri)
2668 if response["ret"] is False:
2669 return response
2670 result["ret"] = True
2671 data = response["data"]
2672 if key in data:
2673 response = self.get_request(self.root_uri + data[key]["@odata.id"])
2674 data = response["data"]
2675 if "PowerControl" in data:
2676 if len(data["PowerControl"]) > 0:
2677 data = data["PowerControl"][0]
2678 for property in properties:
2679 if property in data:
2680 chassis_power_result[property] = data[property]
2681 chassis_power_results.append(chassis_power_result)
2682
2683 if len(chassis_power_results) > 0:
2684 result["entries"] = chassis_power_results
2685 return result
2686 else:
2687 return {"ret": False, "msg": "Power information not found."}
2688
2689 def get_chassis_thermals(self):
2690 result = {}
2691 sensors = []
2692 key = "Thermal"
2693
2694 # Get these entries, but does not fail if not found
2695 properties = [
2696 "Name",
2697 "PhysicalContext",
2698 "UpperThresholdCritical",
2699 "UpperThresholdFatal",
2700 "UpperThresholdNonCritical",
2701 "LowerThresholdCritical",
2702 "LowerThresholdFatal",
2703 "LowerThresholdNonCritical",
2704 "MaxReadingRangeTemp",
2705 "MinReadingRangeTemp",
2706 "ReadingCelsius",
2707 "RelatedItem",
2708 "SensorNumber",
2709 "Status",
2710 ]
2711
2712 # Go through list
2713 for chassis_uri in self.chassis_uris:
2714 response = self.get_request(self.root_uri + chassis_uri)
2715 if response["ret"] is False:
2716 return response
2717 result["ret"] = True
2718 data = response["data"]
2719 if key in data:
2720 thermal_uri = data[key]["@odata.id"]
2721 response = self.get_request(self.root_uri + thermal_uri)
2722 if response["ret"] is False:
2723 return response
2724 result["ret"] = True
2725 data = response["data"]
2726 if "Temperatures" in data:
2727 for sensor in data["Temperatures"]:
2728 sensor_result = {}
2729 for property in properties:
2730 if property in sensor:
2731 if sensor[property] is not None:
2732 sensor_result[property] = sensor[property]
2733 sensors.append(sensor_result)
2734
2735 if sensors is None:
2736 return {"ret": False, "msg": "Key Temperatures was not found."}
2737
2738 result["entries"] = sensors
2739 return result
2740
2741 def get_cpu_inventory(self, systems_uri):
2742 result = {}
2743 cpu_list = []
2744 cpu_results = []
2745 key = "Processors"
2746 # Get these entries, but does not fail if not found
2747 properties = [
2748 "Id",
2749 "Name",
2750 "Manufacturer",
2751 "Model",
2752 "MaxSpeedMHz",
2753 "ProcessorArchitecture",
2754 "TotalCores",
2755 "TotalThreads",
2756 "Status",
2757 ]
2758
2759 # Search for 'key' entry and extract URI from it
2760 response = self.get_request(self.root_uri + systems_uri)
2761 if response["ret"] is False:
2762 return response
2763 result["ret"] = True
2764 data = response["data"]
2765
2766 if key not in data:
2767 return {"ret": False, "msg": f"Key {key} not found"}
2768
2769 processors_uri = data[key]["@odata.id"]
2770
2771 # Get a list of all CPUs and build respective URIs
2772 response = self.get_request(self.root_uri + processors_uri)
2773 if response["ret"] is False:
2774 return response
2775 result["ret"] = True
2776 data = response["data"]
2777
2778 for cpu in data["Members"]:
2779 cpu_list.append(cpu["@odata.id"])
2780
2781 for c in cpu_list:
2782 cpu = {}
2783 uri = self.root_uri + c
2784 response = self.get_request(uri)
2785 if response["ret"] is False:
2786 return response
2787 data = response["data"]
2788
2789 for property in properties:
2790 if property in data:
2791 cpu[property] = data[property]
2792
2793 cpu_results.append(cpu)
2794 result["entries"] = cpu_results
2795 return result
2796
2797 def get_multi_cpu_inventory(self):
2798 return self.aggregate_systems(self.get_cpu_inventory)
2799
2800 def get_memory_inventory(self, systems_uri):
2801 result = {}
2802 memory_list = []
2803 memory_results = []
2804 key = "Memory"
2805 # Get these entries, but does not fail if not found
2806 properties = [
2807 "Id",
2808 "SerialNumber",
2809 "MemoryDeviceType",
2810 "PartNumber",
2811 "MemoryLocation",
2812 "RankCount",
2813 "CapacityMiB",
2814 "OperatingMemoryModes",
2815 "Status",
2816 "Manufacturer",
2817 "Name",
2818 ]
2819
2820 # Search for 'key' entry and extract URI from it
2821 response = self.get_request(self.root_uri + systems_uri)
2822 if response["ret"] is False:
2823 return response
2824 result["ret"] = True
2825 data = response["data"]
2826
2827 if key not in data:
2828 return {"ret": False, "msg": f"Key {key} not found"}
2829
2830 memory_uri = data[key]["@odata.id"]
2831
2832 # Get a list of all DIMMs and build respective URIs
2833 response = self.get_request(self.root_uri + memory_uri)
2834 if response["ret"] is False:
2835 return response
2836 result["ret"] = True
2837 data = response["data"]
2838
2839 for dimm in data["Members"]:
2840 memory_list.append(dimm["@odata.id"])
2841
2842 for m in memory_list:
2843 dimm = {}
2844 uri = self.root_uri + m
2845 response = self.get_request(uri)
2846 if response["ret"] is False:
2847 return response
2848 data = response["data"]
2849
2850 if "Status" in data:
2851 if "State" in data["Status"]:
2852 if data["Status"]["State"] == "Absent":
2853 continue
2854 else:
2855 continue
2856
2857 for property in properties:
2858 if property in data:
2859 dimm[property] = data[property]
2860
2861 memory_results.append(dimm)
2862 result["entries"] = memory_results
2863 return result
2864
2865 def get_multi_memory_inventory(self):
2866 return self.aggregate_systems(self.get_memory_inventory)
2867
2868 def get_nic(self, resource_uri):
2869 result = {}
2870 properties = [
2871 "Name",
2872 "Id",
2873 "Description",
2874 "FQDN",
2875 "IPv4Addresses",
2876 "IPv6Addresses",
2877 "NameServers",
2878 "MACAddress",
2879 "PermanentMACAddress",
2880 "SpeedMbps",
2881 "MTUSize",
2882 "AutoNeg",
2883 "Status",
2884 "LinkStatus",
2885 ]
2886 response = self.get_request(self.root_uri + resource_uri)
2887 if response["ret"] is False:
2888 return response
2889 result["ret"] = True
2890 data = response["data"]
2891 nic = {}
2892 for property in properties:
2893 if property in data:
2894 nic[property] = data[property]
2895 result["entries"] = nic
2896 return result
2897
2898 def get_nic_inventory(self, resource_uri):
2899 result = {}
2900 nic_list = []
2901 nic_results = []
2902 key = "EthernetInterfaces"
2903
2904 response = self.get_request(self.root_uri + resource_uri)
2905 if response["ret"] is False:
2906 return response
2907 result["ret"] = True
2908 data = response["data"]
2909
2910 if key not in data:
2911 return {"ret": False, "msg": f"Key {key} not found"}
2912
2913 ethernetinterfaces_uri = data[key]["@odata.id"]
2914
2915 # Get a list of all network controllers and build respective URIs
2916 response = self.get_request(self.root_uri + ethernetinterfaces_uri)
2917 if response["ret"] is False:
2918 return response
2919 result["ret"] = True
2920 data = response["data"]
2921
2922 for nic in data["Members"]:
2923 nic_list.append(nic["@odata.id"])
2924
2925 for n in nic_list:
2926 nic = self.get_nic(n)
2927 if nic["ret"]:
2928 nic_results.append(nic["entries"])
2929 result["entries"] = nic_results
2930 return result
2931
2932 def get_multi_nic_inventory(self, resource_type):
2933 ret = True
2934 entries = []
2935
2936 # Given resource_type, use the proper URI
2937 if resource_type == "Systems":
2938 resource_uris = self.systems_uris
2939 elif resource_type == "Manager":
2940 resource_uris = self.manager_uris
2941
2942 for resource_uri in resource_uris:
2943 inventory = self.get_nic_inventory(resource_uri)
2944 ret = inventory.pop("ret") and ret
2945 if "entries" in inventory:
2946 entries.append(({"resource_uri": resource_uri}, inventory["entries"]))
2947 return dict(ret=ret, entries=entries)
2948
2949 def get_virtualmedia(self, resource_uri):
2950 result = {}
2951 virtualmedia_list = []
2952 virtualmedia_results = []
2953 key = "VirtualMedia"
2954 # Get these entries, but does not fail if not found
2955 properties = [
2956 "Description",
2957 "ConnectedVia",
2958 "Id",
2959 "MediaTypes",
2960 "Image",
2961 "ImageName",
2962 "Name",
2963 "WriteProtected",
2964 "TransferMethod",
2965 "TransferProtocolType",
2966 ]
2967
2968 response = self.get_request(self.root_uri + resource_uri)
2969 if response["ret"] is False:
2970 return response
2971 result["ret"] = True
2972 data = response["data"]
2973
2974 if key not in data:
2975 return {"ret": False, "msg": f"Key {key} not found"}
2976
2977 virtualmedia_uri = data[key]["@odata.id"]
2978
2979 # Get a list of all virtual media and build respective URIs
2980 response = self.get_request(self.root_uri + virtualmedia_uri)
2981 if response["ret"] is False:
2982 return response
2983 result["ret"] = True
2984 data = response["data"]
2985
2986 for virtualmedia in data["Members"]:
2987 virtualmedia_list.append(virtualmedia["@odata.id"])
2988
2989 for n in virtualmedia_list:
2990 virtualmedia = {}
2991 uri = self.root_uri + n
2992 response = self.get_request(uri)
2993 if response["ret"] is False:
2994 return response
2995 data = response["data"]
2996
2997 for property in properties:
2998 if property in data:
2999 virtualmedia[property] = data[property]
3000
3001 virtualmedia_results.append(virtualmedia)
3002 result["entries"] = virtualmedia_results
3003 return result
3004
3005 def get_multi_virtualmedia(self, resource_type="Manager"):
3006 ret = True
3007 entries = []
3008
3009 # Given resource_type, use the proper URI
3010 if resource_type == "Systems":
3011 resource_uris = self.systems_uris
3012 elif resource_type == "Manager":
3013 resource_uris = self.manager_uris
3014
3015 for resource_uri in resource_uris:
3016 virtualmedia = self.get_virtualmedia(resource_uri)
3017 ret = virtualmedia.pop("ret") and ret
3018 if "entries" in virtualmedia:
3019 entries.append(({"resource_uri": resource_uri}, virtualmedia["entries"]))
3020 return dict(ret=ret, entries=entries)
3021
3022 @staticmethod
3023 def _find_empty_virt_media_slot(resources, media_types, media_match_strict=True, vendor=""):
3024 for uri, data in resources.items():
3025 # check MediaTypes
3026 if "MediaTypes" in data and media_types:
3027 if not set(media_types).intersection(set(data["MediaTypes"])):
3028 continue
3029 else:
3030 if media_match_strict:
3031 continue
3032 # Base on current Lenovo server capability, filter out slot RDOC1/2 and Remote1/2/3/4 which are not supported to Insert/Eject.
3033 if vendor == "Lenovo" and ("RDOC" in uri or "Remote" in uri):
3034 continue
3035 # if ejected, 'Inserted' should be False and 'ImageName' cleared
3036 if not data.get("Inserted", False) and not data.get("ImageName"):
3037 return uri, data
3038 return None, None
3039
3040 @staticmethod
3041 def _virt_media_image_inserted(resources, image_url):
3042 for data in resources.values():
3043 if data.get("Image"):
3044 if urlparse(image_url) == urlparse(data.get("Image")):
3045 if data.get("Inserted", False) and data.get("ImageName"):
3046 return True
3047 return False
3048
3049 @staticmethod
3050 def _find_virt_media_to_eject(resources, image_url):
3051 matched_uri, matched_data = None, None
3052 for uri, data in resources.items():
3053 if data.get("Image"):
3054 if urlparse(image_url) == urlparse(data.get("Image")):
3055 matched_uri, matched_data = uri, data
3056 if data.get("Inserted", True) and data.get("ImageName", "x"):
3057 return uri, data, True
3058 return matched_uri, matched_data, False
3059
3060 def _read_virt_media_resources(self, uri_list):
3061 resources = {}
3062 headers = {}
3063 for uri in uri_list:
3064 response = self.get_request(self.root_uri + uri)
3065 if response["ret"] is False:
3066 continue
3067 resources[uri] = response["data"]
3068 headers[uri] = response["headers"]
3069 return resources, headers
3070
3071 @staticmethod
3072 def _insert_virt_media_payload(options, param_map, data, ai):
3073 payload = {"Image": options.get("image_url")}
3074 for param, option in param_map.items():
3075 if options.get(option) is not None and param in data:
3076 allowable = ai.get(param, {}).get("AllowableValues", [])
3077 if allowable and options.get(option) not in allowable:
3078 return {
3079 "ret": False,
3080 "msg": f"Value '{options.get(option)}' specified for option '{option}' not in list of AllowableValues {allowable}",
3081 }
3082 payload[param] = options.get(option)
3083 return payload
3084
3085 def virtual_media_insert_via_patch(self, options, param_map, uri, data, image_only=False):
3086 # get AllowableValues
3087 ai = {k[:-24]: {"AllowableValues": v} for k, v in data.items() if k.endswith("@Redfish.AllowableValues")}
3088 # construct payload
3089 payload = self._insert_virt_media_payload(options, param_map, data, ai)
3090 if "Inserted" not in payload and not image_only:
3091 # Add Inserted to the payload if needed
3092 payload["Inserted"] = True
3093
3094 # PATCH the resource
3095 resp = self.patch_request(self.root_uri + uri, payload, check_pyld=True)
3096 if resp["ret"] is False:
3097 # WORKAROUND
3098 # Older HPE systems with iLO 4 and Supermicro do not support
3099 # specifying Inserted or WriteProtected
3100 vendor = self._get_vendor()["Vendor"]
3101 if vendor == "HPE" or vendor == "Supermicro":
3102 payload.pop("Inserted", None)
3103 payload.pop("WriteProtected", None)
3104 resp = self.patch_request(self.root_uri + uri, payload, check_pyld=True)
3105 if resp["ret"] and resp["changed"]:
3106 resp["msg"] = "VirtualMedia inserted"
3107 return resp
3108
3109 def virtual_media_insert(self, options, resource_type="Manager"):
3110 param_map = {
3111 "Inserted": "inserted",
3112 "WriteProtected": "write_protected",
3113 "UserName": "username",
3114 "Password": "password",
3115 "TransferProtocolType": "transfer_protocol_type",
3116 "TransferMethod": "transfer_method",
3117 }
3118 image_url = options.get("image_url")
3119 if not image_url:
3120 return {"ret": False, "msg": "image_url option required for VirtualMediaInsert"}
3121 media_types = options.get("media_types")
3122
3123 # locate and read the VirtualMedia resources
3124 # Given resource_type, use the proper URI
3125 if resource_type == "Systems":
3126 resource_uri = self.systems_uri
3127 elif resource_type == "Manager":
3128 resource_uri = self.manager_uri
3129 response = self.get_request(self.root_uri + resource_uri)
3130 if response["ret"] is False:
3131 return response
3132 data = response["data"]
3133 if "VirtualMedia" not in data:
3134 return {"ret": False, "msg": "VirtualMedia resource not found"}
3135
3136 virt_media_uri = data["VirtualMedia"]["@odata.id"]
3137 response = self.get_request(self.root_uri + virt_media_uri)
3138 if response["ret"] is False:
3139 return response
3140 data = response["data"]
3141 virt_media_list = []
3142 for member in data["Members"]:
3143 virt_media_list.append(member["@odata.id"])
3144 resources, headers = self._read_virt_media_resources(virt_media_list)
3145
3146 # see if image already inserted; if so, nothing to do
3147 if self._virt_media_image_inserted(resources, image_url):
3148 return {"ret": True, "changed": False, "msg": f"VirtualMedia '{image_url}' already inserted"}
3149
3150 # find an empty slot to insert the media
3151 # try first with strict media_type matching
3152 vendor = self._get_vendor()["Vendor"]
3153 uri, data = self._find_empty_virt_media_slot(resources, media_types, media_match_strict=True, vendor=vendor)
3154 if not uri:
3155 # if not found, try without strict media_type matching
3156 uri, data = self._find_empty_virt_media_slot(
3157 resources, media_types, media_match_strict=False, vendor=vendor
3158 )
3159 if not uri:
3160 return {
3161 "ret": False,
3162 "msg": f"Unable to find an available VirtualMedia resource {f'supporting {media_types}' if media_types else ''}",
3163 }
3164
3165 # confirm InsertMedia action found
3166 if "Actions" not in data or "#VirtualMedia.InsertMedia" not in data["Actions"]:
3167 # try to insert via PATCH if no InsertMedia action found
3168 h = headers[uri]
3169 if "allow" in h:
3170 methods = [m.strip() for m in h.get("allow").split(",")]
3171 if "PATCH" not in methods:
3172 # if Allow header present and PATCH missing, return error
3173 return {"ret": False, "msg": "#VirtualMedia.InsertMedia action not found and PATCH not allowed"}
3174 return self.virtual_media_insert_via_patch(options, param_map, uri, data)
3175
3176 # get the action property
3177 action = data["Actions"]["#VirtualMedia.InsertMedia"]
3178 if "target" not in action:
3179 return {"ret": False, "msg": "target URI missing from Action #VirtualMedia.InsertMedia"}
3180 action_uri = action["target"]
3181 # get ActionInfo or AllowableValues
3182 ai = self._get_all_action_info_values(action)
3183 # construct payload
3184 payload = self._insert_virt_media_payload(options, param_map, data, ai)
3185 # POST to action
3186 response = self.post_request(self.root_uri + action_uri, payload)
3187 if response["ret"] is False and ("Inserted" in payload or "WriteProtected" in payload):
3188 # WORKAROUND
3189 # Older HPE systems with iLO 4 and Supermicro do not support
3190 # specifying Inserted or WriteProtected
3191 vendor = self._get_vendor()["Vendor"]
3192 if vendor == "HPE" or vendor == "Supermicro":
3193 payload.pop("Inserted", None)
3194 payload.pop("WriteProtected", None)
3195 response = self.post_request(self.root_uri + action_uri, payload)
3196 if response["ret"] is False:
3197 return response
3198 return {"ret": True, "changed": True, "msg": "VirtualMedia inserted"}
3199
3200 def virtual_media_eject_via_patch(self, uri, image_only=False):
3201 # construct payload
3202 payload = {"Inserted": False, "Image": None}
3203
3204 # Inserted is not writable
3205 if image_only:
3206 del payload["Inserted"]
3207
3208 # PATCH resource
3209 resp = self.patch_request(self.root_uri + uri, payload, check_pyld=True)
3210 if resp["ret"] is False and "Inserted" in payload:
3211 # WORKAROUND
3212 # Older HPE systems with iLO 4 and Supermicro do not support
3213 # specifying Inserted
3214 vendor = self._get_vendor()["Vendor"]
3215 if vendor == "HPE" or vendor == "Supermicro":
3216 payload.pop("Inserted", None)
3217 resp = self.patch_request(self.root_uri + uri, payload, check_pyld=True)
3218 if resp["ret"] and resp["changed"]:
3219 resp["msg"] = "VirtualMedia ejected"
3220 return resp
3221
3222 def virtual_media_eject(self, options, resource_type="Manager"):
3223 image_url = options.get("image_url")
3224 if not image_url:
3225 return {"ret": False, "msg": "image_url option required for VirtualMediaEject"}
3226
3227 # locate and read the VirtualMedia resources
3228 # Given resource_type, use the proper URI
3229 if resource_type == "Systems":
3230 resource_uri = self.systems_uri
3231 elif resource_type == "Manager":
3232 resource_uri = self.manager_uri
3233 response = self.get_request(self.root_uri + resource_uri)
3234 if response["ret"] is False:
3235 return response
3236 data = response["data"]
3237 if "VirtualMedia" not in data:
3238 return {"ret": False, "msg": "VirtualMedia resource not found"}
3239
3240 virt_media_uri = data["VirtualMedia"]["@odata.id"]
3241 response = self.get_request(self.root_uri + virt_media_uri)
3242 if response["ret"] is False:
3243 return response
3244 data = response["data"]
3245 virt_media_list = []
3246 for member in data["Members"]:
3247 virt_media_list.append(member["@odata.id"])
3248 resources, headers = self._read_virt_media_resources(virt_media_list)
3249
3250 # find the VirtualMedia resource to eject
3251 uri, data, eject = self._find_virt_media_to_eject(resources, image_url)
3252 if uri and eject:
3253 if "Actions" not in data or "#VirtualMedia.EjectMedia" not in data["Actions"]:
3254 # try to eject via PATCH if no EjectMedia action found
3255 h = headers[uri]
3256 if "allow" in h:
3257 methods = [m.strip() for m in h.get("allow").split(",")]
3258 if "PATCH" not in methods:
3259 # if Allow header present and PATCH missing, return error
3260 return {"ret": False, "msg": "#VirtualMedia.EjectMedia action not found and PATCH not allowed"}
3261 return self.virtual_media_eject_via_patch(uri)
3262 else:
3263 # POST to the EjectMedia Action
3264 action = data["Actions"]["#VirtualMedia.EjectMedia"]
3265 if "target" not in action:
3266 return {"ret": False, "msg": "target URI property missing from Action #VirtualMedia.EjectMedia"}
3267 action_uri = action["target"]
3268 # empty payload for Eject action
3269 payload = {}
3270 # POST to action
3271 response = self.post_request(self.root_uri + action_uri, payload)
3272 if response["ret"] is False:
3273 return response
3274 return {"ret": True, "changed": True, "msg": "VirtualMedia ejected"}
3275 elif uri and not eject:
3276 # already ejected: return success but changed=False
3277 return {"ret": True, "changed": False, "msg": f"VirtualMedia image '{image_url}' already ejected"}
3278 else:
3279 # return failure (no resources matching image_url found)
3280 return {
3281 "ret": False,
3282 "changed": False,
3283 "msg": f"No VirtualMedia resource found with image '{image_url}' inserted",
3284 }
3285
3286 def get_psu_inventory(self):
3287 result = {}
3288 psu_list = []
3289 psu_results = []
3290 key = "PowerSupplies"
3291 # Get these entries, but does not fail if not found
3292 properties = [
3293 "Name",
3294 "Model",
3295 "SerialNumber",
3296 "PartNumber",
3297 "Manufacturer",
3298 "FirmwareVersion",
3299 "PowerCapacityWatts",
3300 "PowerSupplyType",
3301 "Status",
3302 ]
3303
3304 # Get a list of all Chassis and build URIs, then get all PowerSupplies
3305 # from each Power entry in the Chassis
3306 for chassis_uri in self.chassis_uris:
3307 response = self.get_request(self.root_uri + chassis_uri)
3308 if response["ret"] is False:
3309 return response
3310
3311 result["ret"] = True
3312 data = response["data"]
3313
3314 if "Power" in data:
3315 power_uri = data["Power"]["@odata.id"]
3316 else:
3317 continue
3318
3319 response = self.get_request(self.root_uri + power_uri)
3320 data = response["data"]
3321
3322 if key not in data:
3323 return {"ret": False, "msg": f"Key {key} not found"}
3324
3325 psu_list = data[key]
3326 for psu in psu_list:
3327 psu_not_present = False
3328 psu_data = {}
3329 for property in properties:
3330 if property in psu:
3331 if psu[property] is not None:
3332 if property == "Status":
3333 if "State" in psu[property]:
3334 if psu[property]["State"] == "Absent":
3335 psu_not_present = True
3336 psu_data[property] = psu[property]
3337 if psu_not_present:
3338 continue
3339 psu_results.append(psu_data)
3340
3341 result["entries"] = psu_results
3342 if not result["entries"]:
3343 return {"ret": False, "msg": "No PowerSupply objects found"}
3344 return result
3345
3346 def get_multi_psu_inventory(self):
3347 return self.aggregate_systems(self.get_psu_inventory)
3348
3349 def get_system_inventory(self, systems_uri):
3350 result = {}
3351 inventory = {}
3352 # Get these entries, but does not fail if not found
3353 properties = [
3354 "Status",
3355 "HostName",
3356 "PowerState",
3357 "BootProgress",
3358 "Model",
3359 "Manufacturer",
3360 "PartNumber",
3361 "SystemType",
3362 "AssetTag",
3363 "ServiceTag",
3364 "SerialNumber",
3365 "SKU",
3366 "BiosVersion",
3367 "MemorySummary",
3368 "ProcessorSummary",
3369 "TrustedModules",
3370 "Name",
3371 "Id",
3372 ]
3373
3374 response = self.get_request(self.root_uri + systems_uri)
3375 if response["ret"] is False:
3376 return response
3377 result["ret"] = True
3378 data = response["data"]
3379
3380 for property in properties:
3381 if property in data:
3382 inventory[property] = data[property]
3383
3384 result["entries"] = inventory
3385 return result
3386
3387 def get_multi_system_inventory(self):
3388 return self.aggregate_systems(self.get_system_inventory)
3389
3390 def get_network_protocols(self):
3391 result = {}
3392 service_result = {}
3393 # Find NetworkProtocol
3394 response = self.get_request(self.root_uri + self.manager_uri)
3395 if response["ret"] is False:
3396 return response
3397 data = response["data"]
3398 if "NetworkProtocol" not in data:
3399 return {"ret": False, "msg": "NetworkProtocol resource not found"}
3400 networkprotocol_uri = data["NetworkProtocol"]["@odata.id"]
3401
3402 response = self.get_request(self.root_uri + networkprotocol_uri)
3403 if response["ret"] is False:
3404 return response
3405 data = response["data"]
3406 protocol_services = [
3407 "SNMP",
3408 "VirtualMedia",
3409 "Telnet",
3410 "SSDP",
3411 "IPMI",
3412 "SSH",
3413 "KVMIP",
3414 "NTP",
3415 "HTTP",
3416 "HTTPS",
3417 "DHCP",
3418 "DHCPv6",
3419 "RDP",
3420 "RFB",
3421 ]
3422 for protocol_service in protocol_services:
3423 if protocol_service in data.keys():
3424 service_result[protocol_service] = data[protocol_service]
3425
3426 result["ret"] = True
3427 result["entries"] = service_result
3428 return result
3429
3430 def set_network_protocols(self, manager_services):
3431 # Check input data validity
3432 protocol_services = [
3433 "SNMP",
3434 "VirtualMedia",
3435 "Telnet",
3436 "SSDP",
3437 "IPMI",
3438 "SSH",
3439 "KVMIP",
3440 "NTP",
3441 "HTTP",
3442 "HTTPS",
3443 "DHCP",
3444 "DHCPv6",
3445 "RDP",
3446 "RFB",
3447 ]
3448 protocol_state_onlist = ["true", "True", True, "on", 1]
3449 protocol_state_offlist = ["false", "False", False, "off", 0]
3450 payload = {}
3451 for service_name in manager_services.keys():
3452 if service_name not in protocol_services:
3453 return {"ret": False, "msg": f"Service name {service_name} is invalid"}
3454 payload[service_name] = {}
3455 for service_property in manager_services[service_name].keys():
3456 value = manager_services[service_name][service_property]
3457 if service_property in ["ProtocolEnabled", "protocolenabled"]:
3458 if value in protocol_state_onlist:
3459 payload[service_name]["ProtocolEnabled"] = True
3460 elif value in protocol_state_offlist:
3461 payload[service_name]["ProtocolEnabled"] = False
3462 else:
3463 return {"ret": False, "msg": f"Value of property {service_property} is invalid"}
3464 elif service_property in ["port", "Port"]:
3465 if isinstance(value, int):
3466 payload[service_name]["Port"] = value
3467 elif isinstance(value, str) and value.isdigit():
3468 payload[service_name]["Port"] = int(value)
3469 else:
3470 return {"ret": False, "msg": f"Value of property {service_property} is invalid"}
3471 else:
3472 payload[service_name][service_property] = value
3473
3474 # Find the ManagerNetworkProtocol resource
3475 response = self.get_request(self.root_uri + self.manager_uri)
3476 if response["ret"] is False:
3477 return response
3478 data = response["data"]
3479 networkprotocol_uri = data.get("NetworkProtocol", {}).get("@odata.id")
3480 if networkprotocol_uri is None:
3481 return {"ret": False, "msg": "NetworkProtocol resource not found"}
3482
3483 # Modify the ManagerNetworkProtocol resource
3484 resp = self.patch_request(self.root_uri + networkprotocol_uri, payload, check_pyld=True)
3485 if resp["ret"] and resp["changed"]:
3486 resp["msg"] = "Modified manager network protocol settings"
3487 return resp
3488
3489 @staticmethod
3490 def to_singular(resource_name):
3491 if resource_name.endswith("ies"):
3492 resource_name = f"{resource_name[:-3]}y"
3493 elif resource_name.endswith("s"):
3494 resource_name = resource_name[:-1]
3495 return resource_name
3496
3497 def get_health_resource(self, subsystem, uri, health, expanded):
3498 status = "Status"
3499
3500 if expanded:
3501 d = expanded
3502 else:
3503 r = self.get_request(self.root_uri + uri)
3504 if r.get("ret"):
3505 d = r.get("data")
3506 else:
3507 return
3508
3509 if "Members" in d: # collections case
3510 for m in d.get("Members"):
3511 u = m.get("@odata.id")
3512 r = self.get_request(self.root_uri + u)
3513 if r.get("ret"):
3514 p = r.get("data")
3515 if p:
3516 e = {
3517 f"{self.to_singular(subsystem.lower())}_uri": u,
3518 status: p.get(status, "Status not available"),
3519 }
3520 health[subsystem].append(e)
3521 else: # non-collections case
3522 e = {f"{self.to_singular(subsystem.lower())}_uri": uri, status: d.get(status, "Status not available")}
3523 health[subsystem].append(e)
3524
3525 def get_health_subsystem(self, subsystem, data, health):
3526 if subsystem in data:
3527 sub = data.get(subsystem)
3528 if isinstance(sub, list):
3529 for r in sub:
3530 if "@odata.id" in r:
3531 uri = r.get("@odata.id")
3532 expanded = None
3533 if "#" in uri and len(r) > 1:
3534 expanded = r
3535 self.get_health_resource(subsystem, uri, health, expanded)
3536 elif isinstance(sub, dict):
3537 if "@odata.id" in sub:
3538 uri = sub.get("@odata.id")
3539 self.get_health_resource(subsystem, uri, health, None)
3540 elif "Members" in data:
3541 for m in data.get("Members"):
3542 u = m.get("@odata.id")
3543 r = self.get_request(self.root_uri + u)
3544 if r.get("ret"):
3545 d = r.get("data")
3546 self.get_health_subsystem(subsystem, d, health)
3547
3548 def get_health_report(self, category, uri, subsystems):
3549 result = {}
3550 health = {}
3551 status = "Status"
3552
3553 # Get health status of top level resource
3554 response = self.get_request(self.root_uri + uri)
3555 if response["ret"] is False:
3556 return response
3557 result["ret"] = True
3558 data = response["data"]
3559 health[category] = {status: data.get(status, "Status not available")}
3560
3561 # Get health status of subsystems
3562 for sub in subsystems:
3563 d = None
3564 if sub.startswith("Links."): # ex: Links.PCIeDevices
3565 sub = sub[len("Links.") :]
3566 d = data.get("Links", {})
3567 elif "." in sub: # ex: Thermal.Fans
3568 p, sub = sub.split(".")
3569 u = data.get(p, {}).get("@odata.id")
3570 if u:
3571 r = self.get_request(self.root_uri + u)
3572 if r["ret"]:
3573 d = r["data"]
3574 if not d:
3575 continue
3576 else: # ex: Memory
3577 d = data
3578 health[sub] = []
3579 self.get_health_subsystem(sub, d, health)
3580 if not health[sub]:
3581 del health[sub]
3582
3583 result["entries"] = health
3584 return result
3585
3586 def get_system_health_report(self, systems_uri):
3587 subsystems = [
3588 "Processors",
3589 "Memory",
3590 "SimpleStorage",
3591 "Storage",
3592 "EthernetInterfaces",
3593 "NetworkInterfaces.NetworkPorts",
3594 "NetworkInterfaces.NetworkDeviceFunctions",
3595 ]
3596 return self.get_health_report("System", systems_uri, subsystems)
3597
3598 def get_multi_system_health_report(self):
3599 return self.aggregate_systems(self.get_system_health_report)
3600
3601 def get_chassis_health_report(self, chassis_uri):
3602 subsystems = ["Power.PowerSupplies", "Thermal.Fans", "Links.PCIeDevices"]
3603 return self.get_health_report("Chassis", chassis_uri, subsystems)
3604
3605 def get_multi_chassis_health_report(self):
3606 return self.aggregate_chassis(self.get_chassis_health_report)
3607
3608 def get_manager_health_report(self, manager_uri):
3609 subsystems = []
3610 return self.get_health_report("Manager", manager_uri, subsystems)
3611
3612 def get_multi_manager_health_report(self):
3613 return self.aggregate_managers(self.get_manager_health_report)
3614
3615 def set_manager_nic(self, nic_addr, nic_config):
3616 # Get the manager ethernet interface uri
3617 nic_info = self.get_manager_ethernet_uri(nic_addr)
3618
3619 if nic_info.get("nic_addr") is None:
3620 return nic_info
3621 else:
3622 target_ethernet_uri = nic_info["nic_addr"]
3623 target_ethernet_current_setting = nic_info["ethernet_setting"]
3624
3625 # Convert input to payload and check validity
3626 # Note: Some properties in the EthernetInterface resource are arrays of
3627 # objects. The call into this module expects a flattened view, meaning
3628 # the user specifies exactly one object for an array property. For
3629 # example, if a user provides IPv4StaticAddresses in the request to this
3630 # module, it will turn that into an array of one member. This pattern
3631 # should be avoided for future commands in this module, but needs to be
3632 # preserved here for backwards compatibility.
3633 payload = {}
3634 for property in nic_config.keys():
3635 value = nic_config[property]
3636 if (
3637 property in target_ethernet_current_setting
3638 and isinstance(value, dict)
3639 and isinstance(target_ethernet_current_setting[property], list)
3640 ):
3641 payload[property] = list()
3642 payload[property].append(value)
3643 else:
3644 payload[property] = value
3645
3646 # Modify the EthernetInterface resource
3647 resp = self.patch_request(self.root_uri + target_ethernet_uri, payload, check_pyld=True)
3648 if resp["ret"] and resp["changed"]:
3649 resp["msg"] = "Modified manager NIC"
3650 return resp
3651
3652 # A helper function to get the EthernetInterface URI
3653 def get_manager_ethernet_uri(self, nic_addr="null"):
3654 # Get EthernetInterface collection
3655 response = self.get_request(self.root_uri + self.manager_uri)
3656 if not response["ret"]:
3657 return response
3658 data = response["data"]
3659 if "EthernetInterfaces" not in data:
3660 return {"ret": False, "msg": "EthernetInterfaces resource not found"}
3661 ethernetinterfaces_uri = data["EthernetInterfaces"]["@odata.id"]
3662 response = self.get_request(self.root_uri + ethernetinterfaces_uri)
3663 if not response["ret"]:
3664 return response
3665 data = response["data"]
3666 uris = [a.get("@odata.id") for a in data.get("Members", []) if a.get("@odata.id")]
3667
3668 # Find target EthernetInterface
3669 target_ethernet_uri = None
3670 target_ethernet_current_setting = None
3671 if nic_addr == "null":
3672 # Find root_uri matched EthernetInterface when nic_addr is not specified
3673 nic_addr = (self.root_uri).split("/")[-1]
3674 nic_addr = nic_addr.split(":")[0] # split port if existing
3675 for uri in uris:
3676 response = self.get_request(self.root_uri + uri)
3677 if not response["ret"]:
3678 return response
3679 data = response["data"]
3680 data_string = json.dumps(data)
3681 if nic_addr.lower() in data_string.lower():
3682 target_ethernet_uri = uri
3683 target_ethernet_current_setting = data
3684 break
3685
3686 nic_info = {}
3687 nic_info["nic_addr"] = target_ethernet_uri
3688 nic_info["ethernet_setting"] = target_ethernet_current_setting
3689
3690 if target_ethernet_uri is None:
3691 return {}
3692 else:
3693 return nic_info
3694
3695 def set_hostinterface_attributes(self, hostinterface_config, hostinterface_id=None):
3696 if hostinterface_config is None:
3697 return {"ret": False, "msg": "Must provide hostinterface_config for SetHostInterface command"}
3698
3699 # Find the HostInterfaceCollection resource
3700 response = self.get_request(self.root_uri + self.manager_uri)
3701 if response["ret"] is False:
3702 return response
3703 data = response["data"]
3704 hostinterfaces_uri = data.get("HostInterfaces", {}).get("@odata.id")
3705 if hostinterfaces_uri is None:
3706 return {"ret": False, "msg": "HostInterface resource not found"}
3707 response = self.get_request(self.root_uri + hostinterfaces_uri)
3708 if response["ret"] is False:
3709 return response
3710 data = response["data"]
3711 uris = [a.get("@odata.id") for a in data.get("Members", []) if a.get("@odata.id")]
3712
3713 # Capture list of URIs that match a specified HostInterface resource Id
3714 if hostinterface_id:
3715 matching_hostinterface_uris = [uri for uri in uris if hostinterface_id in uri.rstrip("/").split("/")[-1]]
3716 if hostinterface_id and matching_hostinterface_uris:
3717 hostinterface_uri = list.pop(matching_hostinterface_uris)
3718 elif hostinterface_id and not matching_hostinterface_uris:
3719 return {"ret": False, "msg": f"HostInterface ID {hostinterface_id} not present."}
3720 elif len(uris) == 1:
3721 hostinterface_uri = list.pop(uris)
3722 else:
3723 return {"ret": False, "msg": "HostInterface ID not defined and multiple interfaces detected."}
3724
3725 # Modify the HostInterface resource
3726 resp = self.patch_request(self.root_uri + hostinterface_uri, hostinterface_config, check_pyld=True)
3727 if resp["ret"] and resp["changed"]:
3728 resp["msg"] = "Modified host interface"
3729 return resp
3730
3731 def get_hostinterfaces(self):
3732 result = {}
3733 hostinterface_results = []
3734 properties = [
3735 "Id",
3736 "Name",
3737 "Description",
3738 "HostInterfaceType",
3739 "Status",
3740 "InterfaceEnabled",
3741 "ExternallyAccessible",
3742 "AuthenticationModes",
3743 "AuthNoneRoleId",
3744 "CredentialBootstrapping",
3745 ]
3746 manager_uri_list = self.manager_uris
3747 for manager_uri in manager_uri_list:
3748 response = self.get_request(self.root_uri + manager_uri)
3749 if response["ret"] is False:
3750 return response
3751
3752 result["ret"] = True
3753 data = response["data"]
3754 hostinterfaces_uri = data.get("HostInterfaces", {}).get("@odata.id")
3755 if hostinterfaces_uri is None:
3756 continue
3757
3758 response = self.get_request(self.root_uri + hostinterfaces_uri)
3759 data = response["data"]
3760
3761 if "Members" in data:
3762 for hostinterface in data["Members"]:
3763 hostinterface_uri = hostinterface["@odata.id"]
3764 hostinterface_response = self.get_request(self.root_uri + hostinterface_uri)
3765 # dictionary for capturing individual HostInterface properties
3766 hostinterface_data_temp = {}
3767 if hostinterface_response["ret"] is False:
3768 return hostinterface_response
3769 hostinterface_data = hostinterface_response["data"]
3770 for property in properties:
3771 if property in hostinterface_data:
3772 if hostinterface_data[property] is not None:
3773 hostinterface_data_temp[property] = hostinterface_data[property]
3774 # Check for the presence of a ManagerEthernetInterface
3775 # object, a link to a _single_ EthernetInterface that the
3776 # BMC uses to communicate with the host.
3777 if "ManagerEthernetInterface" in hostinterface_data:
3778 interface_uri = hostinterface_data["ManagerEthernetInterface"]["@odata.id"]
3779 interface_response = self.get_nic(interface_uri)
3780 if interface_response["ret"] is False:
3781 return interface_response
3782 hostinterface_data_temp["ManagerEthernetInterface"] = interface_response["entries"]
3783
3784 # Check for the presence of a HostEthernetInterfaces
3785 # object, a link to a _collection_ of EthernetInterfaces
3786 # that the host uses to communicate with the BMC.
3787 if "HostEthernetInterfaces" in hostinterface_data:
3788 interfaces_uri = hostinterface_data["HostEthernetInterfaces"]["@odata.id"]
3789 interfaces_response = self.get_request(self.root_uri + interfaces_uri)
3790 if interfaces_response["ret"] is False:
3791 return interfaces_response
3792 interfaces_data = interfaces_response["data"]
3793 if "Members" in interfaces_data:
3794 for interface in interfaces_data["Members"]:
3795 interface_uri = interface["@odata.id"]
3796 interface_response = self.get_nic(interface_uri)
3797 if interface_response["ret"] is False:
3798 return interface_response
3799 # Check if this is the first
3800 # HostEthernetInterfaces item and create empty
3801 # list if so.
3802 if "HostEthernetInterfaces" not in hostinterface_data_temp:
3803 hostinterface_data_temp["HostEthernetInterfaces"] = []
3804
3805 hostinterface_data_temp["HostEthernetInterfaces"].append(interface_response["entries"])
3806
3807 hostinterface_results.append(hostinterface_data_temp)
3808 else:
3809 continue
3810 result["entries"] = hostinterface_results
3811 if not result["entries"]:
3812 return {"ret": False, "msg": "No HostInterface objects found"}
3813 return result
3814
3815 def get_manager_inventory(self, manager_uri):
3816 result = {}
3817 inventory = {}
3818 # Get these entries, but does not fail if not found
3819 properties = [
3820 "Id",
3821 "FirmwareVersion",
3822 "ManagerType",
3823 "Manufacturer",
3824 "Model",
3825 "PartNumber",
3826 "PowerState",
3827 "SerialNumber",
3828 "ServiceIdentification",
3829 "Status",
3830 "UUID",
3831 ]
3832
3833 response = self.get_request(self.root_uri + manager_uri)
3834 if response["ret"] is False:
3835 return response
3836 result["ret"] = True
3837 data = response["data"]
3838
3839 for property in properties:
3840 if property in data:
3841 inventory[property] = data[property]
3842
3843 result["entries"] = inventory
3844 return result
3845
3846 def get_multi_manager_inventory(self):
3847 return self.aggregate_managers(self.get_manager_inventory)
3848
3849 def get_service_identification(self, manager):
3850 result = {}
3851 if manager is None:
3852 if len(self.manager_uris) == 1:
3853 manager = self.manager_uris[0].rstrip("/").split("/")[-1]
3854 elif len(self.manager_uris) > 1:
3855 entries = self.get_multi_manager_inventory()["entries"]
3856 managers = [m[0]["manager_uri"] for m in entries if m[1].get("ServiceIdentification")]
3857 if len(managers) == 1:
3858 manager = managers[0].rstrip("/").split("/")[-1]
3859 else:
3860 self.module.fail_json(
3861 msg=[
3862 f"Multiple managers with ServiceIdentification were found: {managers}",
3863 "Please specify by using the 'manager' parameter in your playbook",
3864 ]
3865 )
3866 elif len(self.manager_uris) == 0:
3867 self.module.fail_json(msg="No manager identities were found")
3868 response = self.get_request(f"{self.root_uri}/redfish/v1/Managers/{manager}", override_headers=None)
3869 try:
3870 result["service_identification"] = response["data"]["ServiceIdentification"]
3871 except Exception:
3872 self.module.fail_json(msg=f"Service ID not found for manager {manager}")
3873 result["ret"] = True
3874 return result
3875
3876 def set_service_identification(self, service_id):
3877 data = {"ServiceIdentification": service_id}
3878 resp = self.patch_request(f"{self.root_uri}/redfish/v1/Managers/{self.resource_id}", data, check_pyld=True)
3879 return resp
3880
3881 def set_session_service(self, sessions_config):
3882 if sessions_config is None:
3883 return {"ret": False, "msg": "Must provide sessions_config for SetSessionService command"}
3884
3885 resp = self.patch_request(self.root_uri + self.session_service_uri, sessions_config, check_pyld=True)
3886 if resp["ret"] and resp["changed"]:
3887 resp["msg"] = "Modified session service"
3888 return resp
3889
3890 def verify_bios_attributes(self, bios_attributes):
3891 # This method verifies BIOS attributes against the provided input
3892 server_bios = self.get_bios_attributes(self.systems_uri)
3893 if server_bios["ret"] is False:
3894 return server_bios
3895
3896 bios_dict = {}
3897 wrong_param = {}
3898
3899 # Verify bios_attributes with BIOS settings available in the server
3900 for key, value in bios_attributes.items():
3901 if key in server_bios["entries"]:
3902 if server_bios["entries"][key] != value:
3903 bios_dict.update({key: value})
3904 else:
3905 wrong_param.update({key: value})
3906
3907 if wrong_param:
3908 return {"ret": False, "msg": f"Wrong parameters are provided: {wrong_param}"}
3909
3910 if bios_dict:
3911 return {"ret": False, "msg": f"BIOS parameters are not matching: {bios_dict}"}
3912
3913 return {"ret": True, "changed": False, "msg": "BIOS verification completed"}
3914
3915 def enable_secure_boot(self):
3916 # This function enable Secure Boot on an OOB controller
3917
3918 response = self.get_request(self.root_uri + self.systems_uri)
3919 if response["ret"] is False:
3920 return response
3921
3922 server_details = response["data"]
3923 secure_boot_url = server_details["SecureBoot"]["@odata.id"]
3924
3925 response = self.get_request(self.root_uri + secure_boot_url)
3926 if response["ret"] is False:
3927 return response
3928
3929 body = {}
3930 body["SecureBootEnable"] = True
3931
3932 return self.patch_request(self.root_uri + secure_boot_url, body, check_pyld=True)
3933
3934 def set_secure_boot(self, secure_boot_enable):
3935 # This function enable Secure Boot on an OOB controller
3936
3937 response = self.get_request(self.root_uri + self.systems_uri)
3938 if response["ret"] is False:
3939 return response
3940
3941 server_details = response["data"]
3942 secure_boot_url = server_details["SecureBoot"]["@odata.id"]
3943
3944 response = self.get_request(self.root_uri + secure_boot_url)
3945 if response["ret"] is False:
3946 return response
3947
3948 body = {}
3949 body["SecureBootEnable"] = secure_boot_enable
3950
3951 return self.patch_request(self.root_uri + secure_boot_url, body, check_pyld=True)
3952
3953 def get_hpe_thermal_config(self):
3954 result = {}
3955 # Go through list
3956 for chassis_uri in self.chassis_uris:
3957 response = self.get_request(self.root_uri + chassis_uri)
3958 if response["ret"] is False:
3959 return response
3960 result["ret"] = True
3961 data = response["data"]
3962 val = data.get("Oem", {}).get("Hpe", {}).get("ThermalConfiguration")
3963 if val is not None:
3964 return {"ret": True, "current_thermal_config": val}
3965 return {"ret": False}
3966
3967 def get_hpe_fan_percent_min(self):
3968 # Go through list
3969 for chassis_uri in self.chassis_uris:
3970 response = self.get_request(self.root_uri + chassis_uri)
3971 if response["ret"] is False:
3972 return response
3973 data = response["data"]
3974 val = data.get("Oem", {}).get("Hpe", {}).get("FanPercentMinimum")
3975 if val is not None:
3976 return {"ret": True, "fan_percent_min": val}
3977 return {"ret": False}
3978
3979 def delete_volumes(self, storage_subsystem_id, volume_ids):
3980 # Find the Storage resource from the requested ComputerSystem resource
3981 response = self.get_request(self.root_uri + self.systems_uri)
3982 if response["ret"] is False:
3983 return response
3984 data = response["data"]
3985 storage_uri = data.get("Storage", {}).get("@odata.id")
3986 if storage_uri is None:
3987 return {"ret": False, "msg": "Storage resource not found"}
3988
3989 # Get Storage Collection
3990 response = self.get_request(self.root_uri + storage_uri)
3991 if response["ret"] is False:
3992 return response
3993 data = response["data"]
3994
3995 # Collect Storage Subsystems
3996 self.storage_subsystems_uris = [i["@odata.id"] for i in response["data"].get("Members", [])]
3997 if not self.storage_subsystems_uris:
3998 return {"ret": False, "msg": "StorageCollection's Members array is either empty or missing"}
3999
4000 # Matching Storage Subsystem ID with user input
4001 self.storage_subsystem_uri = ""
4002 for storage_subsystem_uri in self.storage_subsystems_uris:
4003 if storage_subsystem_uri.rstrip("/").split("/")[-1] == storage_subsystem_id:
4004 self.storage_subsystem_uri = storage_subsystem_uri
4005
4006 if not self.storage_subsystem_uri:
4007 return {
4008 "ret": False,
4009 "msg": f"Provided Storage Subsystem ID {storage_subsystem_id} does not exist on the server",
4010 }
4011
4012 # Get Volume Collection
4013 response = self.get_request(self.root_uri + self.storage_subsystem_uri)
4014 if response["ret"] is False:
4015 return response
4016 data = response["data"]
4017
4018 response = self.get_request(self.root_uri + data["Volumes"]["@odata.id"])
4019 if response["ret"] is False:
4020 return response
4021 data = response["data"]
4022
4023 # Collect Volumes
4024 self.volume_uris = [i["@odata.id"] for i in response["data"].get("Members", [])]
4025 if not self.volume_uris:
4026 return {"ret": True, "changed": False, "msg": "VolumeCollection's Members array is either empty or missing"}
4027
4028 # Delete each volume
4029 for volume in self.volume_uris:
4030 if volume.rstrip("/").split("/")[-1] in volume_ids:
4031 response = self.delete_request(self.root_uri + volume)
4032 if response["ret"] is False:
4033 return response
4034
4035 return {"ret": True, "changed": True, "msg": f"The following volumes were deleted: {volume_ids}"}
4036
4037 def create_volume(self, volume_details, storage_subsystem_id, storage_none_volume_deletion=False):
4038 # Find the Storage resource from the requested ComputerSystem resource
4039 response = self.get_request(self.root_uri + self.systems_uri)
4040 if response["ret"] is False:
4041 return response
4042 data = response["data"]
4043 storage_uri = data.get("Storage", {}).get("@odata.id")
4044 if storage_uri is None:
4045 return {"ret": False, "msg": "Storage resource not found"}
4046
4047 # Get Storage Collection
4048 response = self.get_request(self.root_uri + storage_uri)
4049 if response["ret"] is False:
4050 return response
4051 data = response["data"]
4052
4053 # Collect Storage Subsystems
4054 self.storage_subsystems_uris = [i["@odata.id"] for i in response["data"].get("Members", [])]
4055 if not self.storage_subsystems_uris:
4056 return {"ret": False, "msg": "StorageCollection's Members array is either empty or missing"}
4057
4058 # Matching Storage Subsystem ID with user input
4059 self.storage_subsystem_uri = ""
4060 for storage_subsystem_uri in self.storage_subsystems_uris:
4061 if storage_subsystem_uri.rstrip("/").split("/")[-1] == storage_subsystem_id:
4062 self.storage_subsystem_uri = storage_subsystem_uri
4063
4064 if not self.storage_subsystem_uri:
4065 return {
4066 "ret": False,
4067 "msg": f"Provided Storage Subsystem ID {storage_subsystem_id} does not exist on the server",
4068 }
4069
4070 # Validate input parameters
4071 required_parameters = ["RAIDType", "Drives"]
4072
4073 for parameter in required_parameters:
4074 if not volume_details.get(parameter):
4075 return {"ret": False, "msg": f"{required_parameters} are required parameter to create a volume"}
4076
4077 # Navigate to the volume uri of the correct storage subsystem
4078 response = self.get_request(self.root_uri + self.storage_subsystem_uri)
4079 if response["ret"] is False:
4080 return response
4081 data = response["data"]
4082
4083 # Deleting any volumes of RAIDType None present on the Storage Subsystem
4084 if storage_none_volume_deletion:
4085 response = self.get_request(self.root_uri + data["Volumes"]["@odata.id"])
4086 if response["ret"] is False:
4087 return response
4088 volume_data = response["data"]
4089
4090 if "Members" in volume_data:
4091 for member in volume_data["Members"]:
4092 response = self.get_request(self.root_uri + member["@odata.id"])
4093 if response["ret"] is False:
4094 return response
4095 member_data = response["data"]
4096
4097 if member_data["RAIDType"] == "None":
4098 response = self.delete_request(self.root_uri + member["@odata.id"])
4099 if response["ret"] is False:
4100 return response
4101
4102 # Construct payload and issue POST command to create volume
4103 volume_details["Links"] = {}
4104 volume_details["Links"]["Drives"] = []
4105 for drive in volume_details["Drives"]:
4106 volume_details["Links"]["Drives"].append({"@odata.id": drive})
4107 del volume_details["Drives"]
4108 payload = volume_details
4109 response = self.post_request(self.root_uri + data["Volumes"]["@odata.id"], payload)
4110 if response["ret"] is False:
4111 return response
4112
4113 return {"ret": True, "changed": True, "msg": "Volume Created"}
4114
4115 def get_bios_registries(self):
4116 # Get /redfish/v1
4117 response = self.get_request(self.root_uri + self.systems_uri)
4118 if not response["ret"]:
4119 return response
4120
4121 server_details = response["data"]
4122
4123 # Get Registries URI
4124 if "Bios" not in server_details:
4125 return {
4126 "ret": False,
4127 "msg": f"Getting BIOS URI failed, Key 'Bios' not found in /redfish/v1/Systems/1/ response: {server_details}",
4128 }
4129
4130 bios_uri = server_details["Bios"]["@odata.id"]
4131 bios_resp = self.get_request(self.root_uri + bios_uri)
4132 if not bios_resp["ret"]:
4133 return bios_resp
4134
4135 bios_data = bios_resp["data"]
4136 attribute_registry = bios_data["AttributeRegistry"]
4137
4138 reg_uri = f"{self.root_uri}{self.service_root}Registries/{attribute_registry}"
4139 reg_resp = self.get_request(reg_uri)
4140 if not reg_resp["ret"]:
4141 return reg_resp
4142
4143 reg_data = reg_resp["data"]
4144
4145 # Get BIOS attribute registry URI
4146
4147 # Get the location URI
4148 response = self.check_location_uri(reg_data, reg_uri)
4149 if not response["ret"]:
4150 return response
4151
4152 rsp_data, rsp_uri = response["rsp_data"], response["rsp_uri"]
4153
4154 if "RegistryEntries" not in rsp_data:
4155 return {"msg": f"'RegistryEntries' not present in {rsp_uri} response, {rsp_data}", "ret": False}
4156
4157 return {"bios_registry": rsp_data, "bios_registry_uri": rsp_uri, "ret": True}
4158
4159 def check_location_uri(self, resp_data, resp_uri):
4160 # Get the location URI response
4161 # return {"msg": self.creds, "ret": False}
4162 vendor = self._get_vendor()["Vendor"]
4163 rsp_uri = ""
4164 for loc in resp_data["Location"]:
4165 if loc["Language"].startswith("en"):
4166 rsp_uri = loc["Uri"]
4167 if vendor == "HPE":
4168 # WORKAROUND
4169 # HPE systems with iLO 4 will have BIOS Attribute Registries location URI as a dictionary with key 'extref'
4170 # Hence adding condition to fetch the Uri
4171 if isinstance(loc["Uri"], dict) and "extref" in loc["Uri"].keys():
4172 rsp_uri = loc["Uri"]["extref"]
4173 if not rsp_uri:
4174 return {
4175 "ret": False,
4176 "msg": f"Language 'en' not found in BIOS Attribute Registries location, URI: {resp_uri}, response: {resp_data}",
4177 }
4178
4179 res = self.get_request(self.root_uri + rsp_uri)
4180 if res["ret"] is False:
4181 # WORKAROUND
4182 # HPE systems with iLO 4 or iLO5 compresses (gzip) for some URIs
4183 # Hence adding encoding to the header
4184 if vendor == "HPE":
4185 override_headers = {"Accept-Encoding": "gzip"}
4186 res = self.get_request(self.root_uri + rsp_uri, override_headers=override_headers)
4187 if res["ret"]:
4188 return {"ret": True, "rsp_data": res["data"], "rsp_uri": rsp_uri}
4189 return res
4190
4191 def get_accountservice_properties(self):
4192 # Find the AccountService resource
4193 response = self.get_request(self.root_uri + self.service_root)
4194 if response["ret"] is False:
4195 return response
4196 data = response["data"]
4197 accountservice_uri = data.get("AccountService", {}).get("@odata.id")
4198 if accountservice_uri is None:
4199 return {"ret": False, "msg": "AccountService resource not found"}
4200
4201 response = self.get_request(self.root_uri + accountservice_uri)
4202 if response["ret"] is False:
4203 return response
4204 return {"ret": True, "entries": response["data"]}
4205
4206 def get_power_restore_policy(self, systems_uri):
4207 # Retrieve System resource
4208 response = self.get_request(self.root_uri + systems_uri)
4209 if response["ret"] is False:
4210 return response
4211 return {"ret": True, "entries": response["data"]["PowerRestorePolicy"]}
4212
4213 def get_multi_power_restore_policy(self):
4214 return self.aggregate_systems(self.get_power_restore_policy)
4215
4216 def set_power_restore_policy(self, policy):
4217 body = {"PowerRestorePolicy": policy}
4218 return self.patch_request(self.root_uri + self.systems_uri, body, check_pyld=True)