Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/module_utils/idrac_redfish.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Dell OpenManage Ansible Modules
4 # Version 9.12.3
5 # Copyright (C) 2019-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
6
7 # Redistribution and use in source and binary forms, with or without modification,
8 # are permitted provided that the following conditions are met:
9
10 # * Redistributions of source code must retain the above copyright notice,
11 # this list of conditions and the following disclaimer.
12
13 # * Redistributions in binary form must reproduce the above copyright notice,
14 # this list of conditions and the following disclaimer in the documentation
15 # and/or other materials provided with the distribution.
16
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
25 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #
27
28
29 from __future__ import (absolute_import, division, print_function)
30 __metaclass__ = type
31
32 import json
33 import re
34 import time
35 import os
36 from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError
37 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
38 from ansible.module_utils.six.moves.urllib.parse import urlencode
39 from ansible.module_utils.common.parameters import env_fallback
40 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import config_ipv6
41 from ansible.module_utils.basic import AnsibleModule
42
43 idrac_auth_params = {
44 "idrac_ip": {"required": True, "type": 'str'},
45 "idrac_user": {"required": True, "type": 'str', "fallback": (env_fallback, ['IDRAC_USERNAME'])},
46 "idrac_password": {"required": True, "type": 'str', "aliases": ['idrac_pwd'], "no_log": True, "fallback": (env_fallback, ['IDRAC_PASSWORD'])},
47 "idrac_port": {"required": False, "default": 443, "type": 'int'},
48 "validate_certs": {"type": "bool", "default": True},
49 "ca_path": {"type": "path"},
50 "timeout": {"type": "int", "default": 30},
51
52 }
53
54 SESSION_RESOURCE_COLLECTION = {
55 "SESSION": "/redfish/v1/SessionService/Sessions",
56 "SESSION_ID": "/redfish/v1/SessionService/Sessions/{Id}",
57 }
58 MANAGER_URI = "/redfish/v1/Managers/iDRAC.Embedded.1"
59 EXPORT_URI = "/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/EID_674_Manager.ExportSystemConfiguration"
60 IMPORT_URI = "/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/EID_674_Manager.ImportSystemConfiguration"
61 IMPORT_PREVIEW = "/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/EID_674_Manager.ImportSystemConfigurationPreview"
62 EXPORT_URI_17 = "/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/OemManager.ExportSystemConfiguration"
63 IMPORT_URI_17 = "/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/OemManager.ImportSystemConfiguration"
64 IMPORT_PREVIEW_17 = "/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/OemManager.ImportSystemConfigurationPreview"
65 GET_IDRAC_MANAGER_ATTRIBUTES_9_10 = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellAttributes/iDRAC.Embedded.1"
66
67
68 class OpenURLResponse(object):
69 """Handles HTTPResponse"""
70
71 def __init__(self, resp):
72 self.body = None
73 self.resp = resp
74 if self.resp:
75 self.body = self.resp.read()
76
77 @property
78 def json_data(self):
79 try:
80 return json.loads(self.body)
81 except ValueError:
82 raise ValueError("Unable to parse json")
83
84 @property
85 def status_code(self):
86 return self.resp.getcode()
87
88 @property
89 def success(self):
90 status = self.status_code
91 return status >= 200 & status <= 299
92
93 @property
94 def headers(self):
95 return self.resp.headers
96
97 @property
98 def reason(self):
99 return self.resp.reason
100
101
102 def _get_scp_export_uri(generation: int) -> str:
103 if generation >= 17:
104 return EXPORT_URI_17
105 else:
106 return EXPORT_URI
107
108
109 def _get_scp_import_uri(generation: int) -> str:
110 if generation >= 17:
111 return IMPORT_URI_17
112 else:
113 return IMPORT_URI
114
115
116 def _get_scp_import_preview_uri(generation: int) -> str:
117 if generation >= 17:
118 return IMPORT_PREVIEW_17
119 else:
120 return IMPORT_PREVIEW
121
122
123 def process_scp_target(target) -> list[str]:
124 """
125 Process the SCP target.
126 In the older SCP APIs, the target was a comma-separated string.
127 In the newer SCP APIs, which were made mandatory since 17G,
128 the target is a list of strings.
129 This function takes the target in any format and converts them to the
130 required format.
131 target can be a string or a list of strings
132 """
133 if isinstance(target, str):
134 target = target.split(",")
135 return target
136
137
138 class iDRACRedfishAPI(object):
139 """REST api for iDRAC modules."""
140
141 def __init__(self, module_params, req_session=False):
142 self.ipaddress = module_params['idrac_ip']
143 self.username = module_params['idrac_user']
144 self.password = module_params['idrac_password']
145 self.x_auth_token = module_params.get('x_auth_token')
146 self.port = module_params['idrac_port']
147 self.validate_certs = module_params.get("validate_certs", False)
148 self.ca_path = module_params.get("ca_path")
149 self.timeout = module_params.get("timeout", 30)
150 self.use_proxy = module_params.get("use_proxy", True)
151 self.req_session = req_session
152 self.session_id = None
153 self.protocol = 'https'
154 self._headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
155 self.ipaddress = config_ipv6(self.ipaddress)
156
157 def _get_url(self, uri):
158 return "{0}://{1}:{2}{3}".format(self.protocol, self.ipaddress, self.port, uri)
159
160 def _build_url(self, path, query_param=None):
161 """builds complete url"""
162 url = path
163 base_uri = self._get_url(url)
164 if path:
165 url = base_uri
166 if query_param:
167 url += "?{0}".format(urlencode(query_param))
168 return url
169
170 def _url_common_args_spec(self, method, api_timeout, headers=None):
171 """Creates an argument common spec"""
172 req_header = self._headers
173 if headers:
174 req_header.update(headers)
175 if api_timeout is None:
176 api_timeout = self.timeout
177 if self.ca_path is None:
178 self.ca_path = self._get_omam_ca_env()
179 url_kwargs = {
180 "method": method,
181 "validate_certs": self.validate_certs,
182 "ca_path": self.ca_path,
183 "use_proxy": self.use_proxy,
184 "headers": req_header,
185 "timeout": api_timeout,
186 "follow_redirects": 'all',
187 }
188 return url_kwargs
189
190 def _args_without_session(self, path, method, api_timeout, headers=None):
191 """Creates an argument spec in case of basic authentication"""
192 req_header = self._headers
193 if headers:
194 req_header.update(headers)
195 url_kwargs = self._url_common_args_spec(method, api_timeout, headers=headers)
196 if not (path == SESSION_RESOURCE_COLLECTION["SESSION"] and method == 'POST'):
197 url_kwargs["url_username"] = self.username
198 url_kwargs["url_password"] = self.password
199 url_kwargs["force_basic_auth"] = True
200 return url_kwargs
201
202 def _args_with_session(self, method, api_timeout, headers=None):
203 """Creates an argument spec, in case of authentication with session"""
204 url_kwargs = self._url_common_args_spec(method, api_timeout, headers=headers)
205 url_kwargs["force_basic_auth"] = False
206 return url_kwargs
207
208 def invoke_request(self, uri, method, data=None, query_param=None, headers=None, api_timeout=None, dump=True):
209 try:
210 if 'X-Auth-Token' in self._headers:
211 url_kwargs = self._args_with_session(method, api_timeout, headers=headers)
212 else:
213 url_kwargs = self._args_without_session(uri, method, api_timeout, headers=headers)
214 if data and dump:
215 data = json.dumps(data)
216 url = self._build_url(uri, query_param=query_param)
217 resp = open_url(url, data=data, **url_kwargs)
218 resp_data = OpenURLResponse(resp)
219 except (HTTPError, URLError, SSLValidationError, ConnectionError) as err:
220 raise err
221 return resp_data
222
223 def __enter__(self):
224 """Creates sessions by passing it to header"""
225 if self.req_session and not self.x_auth_token:
226 payload = {'UserName': self.username,
227 'Password': self.password}
228 path = SESSION_RESOURCE_COLLECTION["SESSION"]
229 resp = self.invoke_request(path, 'POST', data=payload)
230 if resp and resp.success:
231 self.session_id = resp.json_data.get("Id")
232 self._headers["X-Auth-Token"] = resp.headers.get('X-Auth-Token')
233 else:
234 msg = "Could not create the session"
235 raise ConnectionError(msg)
236 elif self.x_auth_token is not None:
237 self._headers["X-Auth-Token"] = self.x_auth_token
238 return self
239
240 def __exit__(self, exc_type, exc_value, traceback):
241 """Deletes a session id, which is in use for request"""
242 if self.session_id:
243 path = SESSION_RESOURCE_COLLECTION["SESSION_ID"].format(Id=self.session_id)
244 self.invoke_request(path, 'DELETE')
245 return False
246
247 @property
248 def get_server_generation(self):
249 """
250 This method fetches the connected server generation.
251 :return: 14, 4.11.11.11
252 """
253 firmware_version = None
254 response = self.invoke_request(MANAGER_URI, 'GET')
255 generation = 0
256 if response.status_code == 200:
257 generation = int(re.search(r"\d+(?=G)", response.json_data["Model"]).group())
258 firmware_version = response.json_data["FirmwareVersion"]
259 hw_model = ""
260 try:
261 hw_model_out = self.invoke_request(GET_IDRAC_MANAGER_ATTRIBUTES_9_10, 'GET')
262 if hw_model_out.status_code == 200:
263 hw_model = hw_model_out.json_data.get('Attributes', {}).get('Info.1.HWModel', "iDRAC 9")
264 except HTTPError:
265 hw_model = "iDRAC 8"
266
267 return generation, firmware_version, hw_model
268
269 def wait_for_job_complete(self, task_uri, job_wait=False):
270 """
271 This function wait till the job completion.
272 :param task_uri: uri to track job.
273 :param job_wait: True or False decide whether to wait till the job completion.
274 :return: object
275 """
276 response = None
277 while job_wait:
278 try:
279 response = self.invoke_request(task_uri, "GET")
280 if response.json_data.get("TaskState") == "Running" or \
281 response.json_data.get("TaskState") == "New":
282 time.sleep(10)
283 else:
284 break
285 except ValueError:
286 response = response.body
287 break
288 return response
289
290 def wait_for_job_completion(self, job_uri, job_wait=False, reboot=False, apply_update=False):
291 """
292 This function wait till the job completion.
293 :param job_uri: uri to track job.
294 :param job_wait: True or False decide whether to wait till the job completion.
295 :return: object
296 """
297 time.sleep(5)
298 response = self.invoke_request(job_uri, "GET")
299 while job_wait:
300 response = self.invoke_request(job_uri, "GET")
301 if response.json_data.get("PercentComplete") == 100 and \
302 response.json_data.get("JobState") == "Completed":
303 break
304 if response.json_data.get("JobState") == "Starting" and not reboot and apply_update:
305 break
306 time.sleep(30)
307 return response
308
309 def form_scp_share_param(self, target, share=None):
310 """
311 A function to form the share param body for SCP import and export
312 from the target and Ansible share input dict.
313 share is Optional.
314 """
315 if share is None:
316 share = {}
317 share_param = {
318 "Target": process_scp_target(target)
319 }
320 # Mapping of API body keys to Ansible argument keys
321 scp_share_param_mappings = {
322 "IPAddress": "share_ip",
323 "ShareName": "share_name",
324 "ShareType": "share_type",
325 "FileName": "file_name",
326 "Username": "username",
327 "Password": "password",
328 "IgnoreCertificateWarning": "ignore_certificate_warning",
329 "ProxySupport": "proxy_support",
330 "ProxyType": "proxy_type",
331 "ProxyPort": "proxy_port",
332 "ProxyServer": "proxy_server",
333 "ProxyUserName": "proxy_username",
334 "ProxyPassword": "proxy_password",
335 }
336 for key, param in scp_share_param_mappings.items():
337 if share.get(param) is not None:
338 share_param[key] = share[param]
339 return share_param
340
341 def export_scp(self, export_format=None, export_use=None, target=None,
342 job_wait=False, share=None, include_in_export="Default"):
343 """
344 This method exports system configuration details from the system.
345 :param export_format: XML or JSON.
346 :param export_use: Default or Clone or Replace.
347 :param target: IDRAC or NIC or ALL or BIOS or RAID.
348 :param job_wait: True or False decide whether to wait till the job completion.
349 :return: exported data in requested format.
350 """
351 gen_details = self.get_server_generation
352 generation = gen_details[0]
353 payload = {"ExportFormat": export_format, "ExportUse": export_use,
354 "ShareParameters": self.form_scp_share_param(target, share)}
355 payload["IncludeInExport"] = [include_in_export]
356 export_uri = _get_scp_export_uri(generation)
357 response = self.invoke_request(export_uri, "POST", data=payload)
358 if response.status_code == 202 and job_wait:
359 task_uri = response.headers["Location"]
360 response = self.wait_for_job_complete(task_uri, job_wait=job_wait)
361 return response
362
363 def import_scp_share(self, shutdown_type=None, host_powerstate=None, job_wait=True,
364 target=None, import_buffer=None, share=None, time_to_wait=300):
365 """
366 This method imports system configuration using share.
367 :param shutdown_type: graceful
368 :param host_powerstate: on
369 :param file_name: import.xml
370 :param job_wait: True
371 :param target: iDRAC
372 :param share: dictionary which has all the share details.
373 :return: json response
374 """
375 gen_details = self.get_server_generation
376 generation = gen_details[0]
377 payload = {"ShutdownType": shutdown_type, "EndHostPowerState": host_powerstate,
378 "ShareParameters": self.form_scp_share_param(target, share),
379 "TimeToWait": time_to_wait}
380 if import_buffer is not None:
381 payload["ImportBuffer"] = import_buffer
382 import_uri = _get_scp_import_uri(generation)
383 return self.invoke_request(import_uri, "POST", data=payload)
384
385 def import_preview(self, import_buffer=None, target=None, share=None, job_wait=False):
386 gen_details = self.get_server_generation
387 generation = gen_details[0]
388 payload = {"ShareParameters": self.form_scp_share_param(target, share)}
389 if import_buffer is not None:
390 payload["ImportBuffer"] = import_buffer
391 import_preview_uri = _get_scp_import_preview_uri(generation)
392 response = self.invoke_request(import_preview_uri, "POST", data=payload)
393 if response.status_code == 202 and job_wait:
394 task_uri = response.headers["Location"]
395 response = self.wait_for_job_complete(task_uri, job_wait=job_wait)
396 return response
397
398 def import_scp(self, import_buffer=None, target=None, job_wait=False, time_to_wait=300):
399 """
400 This method imports system configuration details to the system.
401 :param import_buffer: import buffer payload content xml or json format
402 :param target: IDRAC or NIC or ALL or BIOS or RAID.
403 :param job_wait: True or False decide whether to wait till the job completion.
404 :return: json response
405 """
406 gen_details = self.get_server_generation
407 generation = gen_details[0]
408 payload = {
409 "ImportBuffer": import_buffer,
410 "ShareParameters": self.form_scp_share_param(target),
411 "TimeToWait": time_to_wait,
412 }
413 import_uri = _get_scp_import_uri(generation)
414 response = self.invoke_request(import_uri, "POST", data=payload)
415 if response.status_code == 202 and job_wait:
416 task_uri = response.headers["Location"]
417 response = self.wait_for_job_complete(task_uri, job_wait=job_wait)
418 return response
419
420 def import_preview_scp(self, import_buffer=None, target=None, job_wait=False):
421 """
422 This method imports preview system configuration details to the system.
423 :param import_buffer: import buffer payload content xml or json format
424 :param target: IDRAC or NIC or ALL or BIOS or RAID.
425 :param job_wait: True or False decide whether to wait till the job completion.
426 :return: json response
427 """
428 payload = {"ImportBuffer": import_buffer,
429 "ShareParameters": self.form_scp_share_param(target)}
430 response = self.invoke_request(IMPORT_PREVIEW, "POST", data=payload)
431 if response.status_code == 202 and job_wait:
432 task_uri = response.headers["Location"]
433 response = self.wait_for_job_complete(task_uri, job_wait=job_wait)
434 return response
435
436 def get_idrac_local_account_attr(self, idrac_attribues, fqdd=None):
437 """
438 This method filtered from all the user attributes from the given idrac attributes.
439 :param idrac_attribues: all the idrac attribues in json data format.
440 :return: user attributes in dictionary format
441 """
442 user_attr = None
443 if "SystemConfiguration" in idrac_attribues:
444 sys_config = idrac_attribues.get("SystemConfiguration")
445 for comp in sys_config.get("Components"):
446 if comp.get("FQDD") == fqdd:
447 attributes = comp.get("Attributes")
448 break
449 user_attr = dict([(attr["Name"], attr["Value"]) for attr in attributes if attr["Name"].startswith("Users.")])
450 return user_attr
451
452 def _get_omam_ca_env(self):
453 """Check if the value is set in REQUESTS_CA_BUNDLE or CURL_CA_BUNDLE or OMAM_CA_BUNDLE or returns None"""
454 return os.environ.get("REQUESTS_CA_BUNDLE") or os.environ.get("CURL_CA_BUNDLE") or os.environ.get("OMAM_CA_BUNDLE")
455
456 def validate_idrac10_and_above(self):
457 gen_details = self.get_server_generation
458 hw_model = gen_details[2]
459 return hw_model == 'iDRAC 10'
460
461 def get_job_uri(self):
462 idrac10_or_above = self.validate_idrac10_and_above()
463 if idrac10_or_above:
464 return "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs/{job_id}"
465 return "/redfish/v1/Managers/iDRAC.Embedded.1/Jobs/{job_id}"
466
467 def find_ip_address(self, sharename):
468 pattern_ipv4 = r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'
469 ipv4_addresses = re.findall(pattern_ipv4, sharename)
470 pattern_ipv6 = r'\b(?:[A-Fa-f0-9]{1,4}:){7}[A-Fa-f0-9]{1,4}\b'
471 ipv6_addresses = re.findall(pattern_ipv6, sharename)
472 address = None
473 if ipv4_addresses:
474 address = ipv4_addresses[0]
475 elif ipv6_addresses:
476 address = ipv6_addresses[0]
477 return address
478
479
480 class IdracAnsibleModule(AnsibleModule):
481 def __init__(self, argument_spec, bypass_checks=False, no_log=False,
482 mutually_exclusive=None, required_together=None,
483 required_one_of=None, add_file_common_args=False,
484 supports_check_mode=False, required_if=None, required_by=None):
485 idrac_argument_spec = {
486 "idrac_ip": {"required": True, "type": 'str'},
487 "idrac_user": {"required": False, "type": 'str', "fallback": (env_fallback, ['IDRAC_USERNAME'])},
488 "idrac_password": {"required": False, "type": 'str', "aliases": ['idrac_pwd'], "no_log": True, "fallback": (env_fallback, ['IDRAC_PASSWORD'])},
489 "x_auth_token": {"required": False, "type": 'str', "no_log": True, "fallback": (env_fallback, ['IDRAC_X_AUTH_TOKEN'])},
490 "idrac_port": {"required": False, "default": 443, "type": 'int'},
491 "validate_certs": {"type": "bool", "default": True},
492 "ca_path": {"type": "path"},
493 "timeout": {"type": "int", "default": 30},
494 }
495 argument_spec.update(idrac_argument_spec)
496
497 auth_mutually_exclusive = [("idrac_user", "x_auth_token"), ("idrac_password", "x_auth_token")]
498 auth_required_one_of = [("idrac_user", "x_auth_token")]
499 auth_required_together = [("idrac_user", "idrac_password")]
500
501 if mutually_exclusive is None:
502 mutually_exclusive = []
503 mutually_exclusive.extend(auth_mutually_exclusive)
504 if required_together is None:
505 required_together = []
506 required_together.extend(auth_required_together)
507 if required_one_of is None:
508 required_one_of = []
509 required_one_of.extend(auth_required_one_of)
510 if required_by is None:
511 required_by = {}
512
513 super().__init__(argument_spec, bypass_checks, no_log,
514 mutually_exclusive, required_together,
515 required_one_of, add_file_common_args,
516 supports_check_mode, required_if, required_by)