Skip to content

Commit

Permalink
[idrac_server_config_profile] BugFix to handle error on scp operations
Browse files Browse the repository at this point in the history
  • Loading branch information
Jennifer-John committed Oct 8, 2023
1 parent 75012d6 commit 22603b1
Show file tree
Hide file tree
Showing 2 changed files with 253 additions and 431 deletions.
263 changes: 152 additions & 111 deletions plugins/modules/idrac_server_config_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

#
# Dell OpenManage Ansible Modules
# Version 8.0.0
# Version 8.4.0
# Copyright (C) 2019-2023 Dell Inc. or its subsidiaries. All Rights Reserved.

# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
Expand Down Expand Up @@ -631,31 +631,18 @@ def run_export_import_scp_http(idrac, module):
share["ignore_certificate_warning"] = IGNORE_WARNING[module.params["ignore_certificate_warning"]]
if command == "import":
job_wait = copy.copy(module.params["job_wait"])
if module.check_mode:
module.params["job_wait"] = True
scp_resp = preview_scp_redfish(module, idrac, True, import_job_wait=True)
if "SYS081" in scp_resp["MessageId"] or "SYS082" in scp_resp["MessageId"]:
module.exit_json(msg=CHANGES_FOUND, changed=True)
elif "SYS069" in scp_resp["MessageId"]:
module.exit_json(msg=NO_CHANGES_FOUND)
else:
module.fail_json(msg=scp_resp)
module.params["job_wait"] = job_wait
perform_check_mode(module, idrac, job_wait)

if module.params.get("import_buffer") and module.params.get("share_name") is not None:
module.fail_json(msg=MUTUALLY_EXCLUSIVE.format("share_name"))
if share["share_type"] in ["HTTP", "HTTPS"]:
proxy_share = get_proxy_share(module)
share.update(proxy_share)
scp_response = idrac.import_scp_share(shutdown_type=module.params["shutdown_type"],
host_powerstate=module.params["end_host_power_state"],
job_wait=module.params["job_wait"],
target=scp_target, share=share, )
job_id = scp_response.headers["Location"].split("/")[-1]
if module.params["job_wait"]:
job_failed, msg, job_dict, wait_time = idrac_redfish_job_tracking(
idrac, iDRAC_JOB_URI.format(job_id=job_id))
scp_response = job_dict
idrac_import_scp_params = {
"target": scp_target, "share": share, "job_wait": module.params["job_wait"],
"host_powerstate": module.params["end_host_power_state"], "shutdown_type": module.params["shutdown_type"]
}
scp_response = idrac_import_scp_share(module, idrac, idrac_import_scp_params)
elif command == "export":
scp_file_name_format = get_scp_file_format(module)
share["file_name"] = scp_file_name_format
Expand All @@ -674,6 +661,19 @@ def run_export_import_scp_http(idrac, module):
return scp_response


def perform_check_mode(module, idrac, job_wait, http_share=True):
if module.check_mode:
module.params["job_wait"] = True
scp_resp = preview_scp_redfish(module, idrac, http_share, import_job_wait=True)
if "SYS081" in scp_resp["MessageId"] or "SYS082" in scp_resp["MessageId"]:
module.exit_json(msg=CHANGES_FOUND, changed=True)
elif "SYS069" in scp_resp["MessageId"]:
module.exit_json(msg=NO_CHANGES_FOUND)
else:
module.fail_json(msg=scp_resp)
module.params["job_wait"] = job_wait


def get_scp_share_details(module):
share_name = module.params.get("share_name")
command = module.params["command"]
Expand Down Expand Up @@ -757,13 +757,7 @@ def preview_scp_redfish(module, idrac, http_share, import_job_wait=False):
else:
share, scp_file_name_format = get_scp_share_details(module)
share["file_name"] = module.params.get("scp_file")
buffer_text = None
if share["share_type"] == "LOCAL":
file_path = "{0}{1}{2}".format(share["share_name"], os.sep, share["file_name"])
if not exists(file_path):
module.fail_json(msg=INVALID_FILE)
with open(file_path, "r") as file_obj:
buffer_text = file_obj.read()
buffer_text = get_buffer_text(module, share)
scp_response = idrac.import_preview(import_buffer=buffer_text, target=scp_targets,
share=share, job_wait=job_wait_option)
else:
Expand All @@ -774,22 +768,25 @@ def preview_scp_redfish(module, idrac, http_share, import_job_wait=False):
return scp_response


def get_buffer_text(module, share):
buffer_text = None
if share["share_type"] == "LOCAL":
file_path = "{0}{1}{2}".format(share["share_name"], os.sep, share["file_name"])
if not exists(file_path):
module.fail_json(msg=INVALID_FILE)
with open(file_path, "r") as file_obj:
buffer_text = file_obj.read()
return buffer_text


def import_scp_redfish(module, idrac, http_share):
import_buffer = module.params.get("import_buffer")
if import_buffer and module.params.get("share_name") is not None:
module.fail_json(msg=MUTUALLY_EXCLUSIVE.format("share_name"))
command = module.params["command"]
scp_targets = ",".join(module.params["scp_components"])
job_wait = copy.copy(module.params["job_wait"])
if module.check_mode:
module.params["job_wait"] = True
scp_resp = preview_scp_redfish(module, idrac, http_share, import_job_wait=True)
if "SYS081" in scp_resp["MessageId"] or "SYS082" in scp_resp["MessageId"]:
module.exit_json(msg=CHANGES_FOUND, changed=True)
elif "SYS069" in scp_resp["MessageId"]:
module.exit_json(msg=NO_CHANGES_FOUND)
else:
module.fail_json(msg=scp_resp)
perform_check_mode(module, idrac, job_wait, http_share)
share = {}
if not import_buffer:
if http_share:
Expand All @@ -800,28 +797,18 @@ def import_scp_redfish(module, idrac, http_share):
if http_share == "HTTPS":
share["ignore_certificate_warning"] = IGNORE_WARNING[module.params["ignore_certificate_warning"]]
else:
share, scp_file_name_format = get_scp_share_details(module)
share, _scp_file_name_format = get_scp_share_details(module)
share["file_name"] = module.params.get("scp_file")
buffer_text = None
buffer_text = get_buffer_text(module, share)
share_dict = share
if share["share_type"] == "LOCAL":
file_path = "{0}{1}{2}".format(share["share_name"], os.sep, share["file_name"])
if not exists(file_path):
module.fail_json(msg=INVALID_FILE)
with open(file_path, "r") as file_obj:
buffer_text = file_obj.read()
share_dict = {}
module.params["job_wait"] = job_wait
scp_response = idrac.import_scp_share(shutdown_type=module.params["shutdown_type"],
host_powerstate=module.params["end_host_power_state"],
job_wait=module.params["job_wait"],
target=scp_targets,
import_buffer=buffer_text, share=share_dict, )
job_id = scp_response.headers["Location"].split("/")[-1]
if module.params["job_wait"]:
job_failed, msg, job_dict, wait_time = idrac_redfish_job_tracking(
idrac, iDRAC_JOB_URI.format(job_id=job_id))
scp_response = job_dict
idrac_import_scp_params = {
"import_buffer": buffer_text, "target": scp_targets, "share": share_dict, "job_wait": module.params["job_wait"],
"host_powerstate": module.params["end_host_power_state"], "shutdown_type": module.params["shutdown_type"]
}
scp_response = idrac_import_scp_share(module, idrac, idrac_import_scp_params)
else:
scp_response = idrac.import_scp(import_buffer=import_buffer, target=scp_targets, job_wait=module.params["job_wait"])
scp_response = response_format_change(scp_response, module.params, share.get("file_name"))
Expand All @@ -830,8 +817,119 @@ def import_scp_redfish(module, idrac, http_share):
return scp_response


def idrac_import_scp_share(module, idrac, job_params):
scp_response = idrac.import_scp_share(**job_params)
job_id = scp_response.headers["Location"].split("/")[-1]
if module.params["job_wait"]:
job_failed, _msg, job_dict, _wait_time = idrac_redfish_job_tracking(
idrac, iDRAC_JOB_URI.format(job_id=job_id))
if job_failed:
module.exit_json(failed=True, status_msg=job_dict, job_id=job_id)
scp_response = job_dict
return scp_response


def validate_input(module, scp_components):
if len(scp_components) != 1 and "ALL" in scp_components:
module.fail_json(msg=SCP_ALL_ERR_MSG)
if module.params["command"] in ["import", "preview"] and (module.params.get("scp_file") is not None and
module.params.get("import_buffer") is not None):
module.fail_json(msg=MUTUALLY_EXCLUSIVE.format("scp_file"))


class ImportCommand():
def __init__(self, idrac, http_share, module):
self.idrac = idrac
self.http_share = http_share
self.module = module

def execute(self):
changed = False
if self.http_share:
scp_status = run_export_import_scp_http(self.idrac, self.module)
if "SYS069" in scp_status.get("MessageId", ""):
changed = False
elif "SYS053" in scp_status.get("MessageId", ""):
changed = True
else:
scp_status = import_scp_redfish(self.module, self.idrac, self.http_share)
if "No changes were applied" not in scp_status.get('Message', ""):
changed = True
elif "SYS043" in scp_status.get("MessageId", ""):
changed = True
elif "SYS069" in scp_status.get("MessageId", ""):
changed = False
return scp_status, changed


class ExportCommand():
def __init__(self, idrac, http_share, module):
self.idrac = idrac
self.http_share = http_share
self.module = module

def execute(self):
if self.http_share:
scp_status = run_export_import_scp_http(self.idrac, self.module)
else:
scp_status = export_scp_redfish(self.module, self.idrac)
return scp_status, False


class PreviewCommand():
def __init__(self, idrac, http_share, module):
self.idrac = idrac
self.http_share = http_share
self.module = module

def execute(self):
scp_status = preview_scp_redfish(self.module, self.idrac, self.http_share, import_job_wait=False)
return scp_status, False


def main():
specs = {
specs = get_argument_spec()
specs.update(idrac_auth_params)
module = AnsibleModule(
argument_spec=specs,
required_if=[
["command", "export", ["share_name"]],
],
supports_check_mode=True)

validate_input(module, module.params.get("scp_components"))
try:
http_share = False
if module.params.get("share_name") is not None:
http_share = module.params["share_name"].lower().startswith(('http://', 'https://'))
with iDRACRedfishAPI(module.params) as idrac:
command = module.params['command']
if command == 'import':
command_obj = ImportCommand(idrac, http_share, module)
elif command == 'export':
command_obj = ExportCommand(idrac, http_share, module)
else:
command_obj = PreviewCommand(idrac, http_share, module)
scp_status, changed = command_obj.execute()

if module.params.get('job_wait'):
scp_status = strip_substr_dict(scp_status)
msg = "Successfully {0}ed the Server Configuration Profile."
module.exit_json(changed=changed, msg=msg.format(command), scp_status=scp_status)
else:
msg = "Successfully triggered the job to {0} the Server Configuration Profile."
module.exit_json(msg=msg.format(command), scp_status=scp_status)
except HTTPError as err:
module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
except URLError as err:
module.exit_json(msg=str(err), unreachable=True)
except (ImportError, ValueError, RuntimeError, SSLValidationError,
ConnectionError, KeyError, TypeError, IndexError) as e:
module.fail_json(msg=str(e))


def get_argument_spec():
return {
"command": {"required": False, "type": 'str',
"choices": ['export', 'import', 'preview'], "default": 'export'},
"job_wait": {"required": True, "type": 'bool'},
Expand Down Expand Up @@ -864,63 +962,6 @@ def main():
"proxy_username": {"type": "str", "required": False},
"proxy_password": {"type": "str", "required": False, "no_log": True},
}
specs.update(idrac_auth_params)
module = AnsibleModule(
argument_spec=specs,
required_if=[
["command", "export", ["share_name"]],
],
supports_check_mode=True)

scp_components = module.params["scp_components"]
if not len(scp_components) == 1 and "ALL" in scp_components:
module.fail_json(msg=SCP_ALL_ERR_MSG)
if module.params["command"] in ["import", "preview"] and (module.params.get("scp_file") is not None and
module.params.get("import_buffer") is not None):
module.fail_json(msg=MUTUALLY_EXCLUSIVE.format("scp_file"))
try:
changed, http_share = False, ""
if module.params.get("share_name") is not None:
http_share = module.params["share_name"].lower().startswith(('http://', 'https://'))
with iDRACRedfishAPI(module.params) as idrac:
command = module.params['command']
if command == 'import':
if http_share:
scp_status = run_export_import_scp_http(idrac, module)
if "SYS069" in scp_status.get("MessageId", ""):
changed = False
elif "SYS053" in scp_status.get("MessageId", ""):
changed = True
else:
scp_status = import_scp_redfish(module, idrac, http_share)
if "No changes were applied" not in scp_status.get('Message', ""):
changed = True
elif "SYS043" in scp_status.get("MessageId", ""):
changed = True
elif "SYS069" in scp_status.get("MessageId", ""):
changed = False
elif command == "export":
if http_share:
scp_status = run_export_import_scp_http(idrac, module)
else:
scp_status = export_scp_redfish(module, idrac)
else:
scp_status = preview_scp_redfish(module, idrac, http_share, import_job_wait=False)
if module.params.get('job_wait'):
scp_status = strip_substr_dict(scp_status)
msg = "Successfully {0}ed the Server Configuration Profile."
module.exit_json(changed=changed, msg=msg.format(command), scp_status=scp_status)
else:
msg = "Successfully triggered the job to {0} the Server Configuration Profile."
module.exit_json(msg=msg.format(command), scp_status=scp_status)
except HTTPError as err:
module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
except URLError as err:
module.exit_json(msg=str(err), unreachable=True)
except (ImportError, ValueError, RuntimeError, SSLValidationError,
ConnectionError, KeyError, TypeError, IndexError) as e:
module.fail_json(msg=str(e))


if __name__ == '__main__':
main()
Loading

0 comments on commit 22603b1

Please sign in to comment.