Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/redfish_firmware.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.3.0
7 # Copyright (C) 2019-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
8
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10 #
11
12
13 from __future__ import (absolute_import, division, print_function)
14 __metaclass__ = type
15
16 DOCUMENTATION = r"""
17 ---
18 module: redfish_firmware
19 short_description: To perform a component firmware update using the image file available on the local or remote system
20 version_added: "2.1.0"
21 description:
22 - This module allows the firmware update of only one component at a time.
23 If the module is run for more than one component, an error message is returned.
24 - Depending on the component, the firmware update is applied after an automatic or manual reboot.
25 extends_documentation_fragment:
26 - dellemc.openmanage.redfish_auth_options
27 options:
28 image_uri:
29 description:
30 - Firmware Image location URI or local path.
31 - For example- U(http://<web_address>/components.exe) or /home/firmware_repo/component.exe.
32 type: str
33 required: true
34 transfer_protocol:
35 description: Protocol used to transfer the firmware image file. Applicable for URI based update.
36 type: str
37 default: HTTP
38 choices: ["CIFS", "FTP", "HTTP", "HTTPS", "NSF", "OEM", "SCP", "SFTP", "TFTP"]
39 job_wait:
40 description: Provides the option to wait for job completion.
41 type: bool
42 default: true
43 job_wait_timeout:
44 type: int
45 description:
46 - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
47 - This option is applicable when I(job_wait) is C(true).
48 - "Note: If a firmware update needs a reboot, the job will get scheduled and waits for
49 no of seconds specfied in I(job_wait_time). to reduce the wait time either give
50 I(job_wait_time) minimum or make I(job_wait)as false and retrigger."
51 default: 3600
52 requirements:
53 - "python >= 3.9.6"
54 - "urllib3"
55 author:
56 - "Felix Stephen (@felixs88)"
57 - "Husniya Hameed (@husniya_hameed)"
58 - "Shivam Sharma (@Shivam-Sharma)"
59 - "Kritika Bhateja (@Kritika_Bhateja)"
60 - "Abhishek Sinha (@ABHISHEK-SINHA10)"
61 - "Sakshi Makkar (@Sakshi-dell)"
62 notes:
63 - Run this module from a system that has direct access to Redfish APIs.
64 - This module supports both IPv4 and IPv6 addresses.
65 - This module supports only iDRAC9 and above.
66 - This module does not support C(check_mode).
67 """
68
69 EXAMPLES = """
70 ---
71 - name: Update the firmware from a single executable file available in a HTTP protocol
72 dellemc.openmanage.redfish_firmware:
73 baseuri: "192.168.0.1"
74 username: "user_name"
75 password: "user_password"
76 ca_path: "/path/to/ca_cert.pem"
77 image_uri: "http://192.168.0.2/firmware_repo/component.exe"
78 transfer_protocol: "HTTP"
79
80 - name: Update the firmware from a single executable file available in a HTTP protocol with job_Wait
81 dellemc.openmanage.redfish_firmware:
82 baseuri: "192.168.0.1"
83 username: "user_name"
84 password: "user_password"
85 ca_path: "/path/to/ca_cert.pem"
86 image_uri: "http://192.168.0.2/firmware_repo/component.exe"
87 transfer_protocol: "HTTP"
88 job_wait: true
89 job_wait_timeout: 600
90
91 - name: Update the firmware from a single executable file available in a local path
92 dellemc.openmanage.redfish_firmware:
93 baseuri: "192.168.0.1"
94 username: "user_name"
95 password: "user_password"
96 ca_path: "/path/to/ca_cert.pem"
97 image_uri: "/home/firmware_repo/component.exe"
98 """
99
100 RETURN = """
101 ---
102 msg:
103 description: Overall status of the firmware update task.
104 returned: always
105 type: str
106 sample: "Successfully updated the firmware."
107 task:
108 description: Returns ID and URI of the created task.
109 returned: success
110 type: dict
111 sample: {
112 "id": "JID_XXXXXXXXXXXX",
113 "uri": "/redfish/v1/TaskService/Tasks/JID_XXXXXXXXXXXX"
114 }
115 error_info:
116 type: dict
117 description: Details of http error.
118 returned: on http error
119 sample: {
120 "error": {
121 "@Message.ExtendedInfo": [
122 {
123 "Message": "Unable to complete the operation because the JSON data format entered is invalid.",
124 "Resolution": "Do the following and the retry the operation:
125 1) Enter the correct JSON data format and retry the operation.
126 2) Make sure that no syntax error is present in JSON data format.
127 3) Make sure that a duplicate key is not present in JSON data format.",
128 "Severity": "Critical"
129 },
130 {
131 "Message": "The request body submitted was malformed JSON and
132 could not be parsed by the receiving service.",
133 "Resolution": "Ensure that the request body is valid JSON and resubmit the request.",
134 "Severity": "Critical"
135 }
136 ],
137 "code": "Base.1.2.GeneralError",
138 "message": "A general error has occurred. See ExtendedInfo for more information."
139 }
140 }
141 """
142
143
144 import json
145 import os
146 import time
147 from ssl import SSLError
148 from ansible_collections.dellemc.openmanage.plugins.module_utils.redfish import Redfish, RedfishAnsibleModule
149 from ansible.module_utils.basic import missing_required_lib
150 from ansible.module_utils.urls import ConnectionError, SSLValidationError
151 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
152
153 try:
154 from urllib3.fields import RequestField
155 from urllib3.filepost import encode_multipart_formdata
156 HAS_LIB = True
157 except ImportError:
158 HAS_LIB = False
159
160 UPDATE_SERVICE = "UpdateService"
161 JOB_URI = "JobService/Jobs/{job_id}"
162 JOB_WAIT_MSG = 'Job wait timed out after {0} seconds.'
163 FAIL_JOB_MSG = "Firmware update failed."
164 SUCCESS_JOB_MSG = "Successfully updated the firmware."
165 SCHEDULE_JOB_MSG = "Successfully scheduled the firmware job."
166 JOBSTATUS_SUCCESS = "success"
167 JOBSTATUS_FAILED = "failed"
168 JOBSTATUS_TIMED_OUT = "timed_out"
169 JOBSTATUS_SCHEDULED = "scheduled"
170 JOBSTATUS_ERRORED = "errored"
171 FILE_PAYLOAD_HEADER = "UpdateFile"
172
173
174 def _encode_form_data(payload_file, payload_file_header):
175 """Encode multipart/form-data for file upload."""
176 fields = []
177 f_name, f_data, f_type = payload_file.get(payload_file_header)
178 f_binary = f_data.read()
179 req_field = RequestField(name=payload_file_header, data=f_binary, filename=f_name)
180 req_field.make_multipart(content_type=f_type)
181 fields.append(req_field)
182 data, content_type = encode_multipart_formdata(fields)
183 return data, content_type
184
185
186 def _get_update_service_target(obj, module, generation):
187 """Returns all the URI which is required for firmware update dynamically."""
188 action_resp = obj.invoke_request("GET", "{0}{1}".format(obj.root_uri, UPDATE_SERVICE))
189 action_attr = action_resp.json_data["Actions"]
190 protocol = module.params["transfer_protocol"]
191 update_uri = None
192 if generation <= 16:
193 push_uri = action_resp.json_data.get('HttpPushUri')
194 else:
195 push_uri = action_resp.json_data.get('MultipartHttpPushUri')
196 inventory_uri = action_resp.json_data.get('FirmwareInventory').get('@odata.id')
197 if "#UpdateService.SimpleUpdate" in action_attr:
198 update_service = action_attr.get("#UpdateService.SimpleUpdate")
199 proto = update_service.get("[email protected]")
200 if isinstance(proto, list) and protocol in proto and 'target' in update_service:
201 update_uri = update_service.get('target')
202 else:
203 module.fail_json(msg="Target firmware version does not support {0} protocol.".format(protocol))
204 if update_uri is None or push_uri is None or inventory_uri is None:
205 module.fail_json(msg="Target firmware version does not support redfish firmware update.")
206 return str(inventory_uri), str(push_uri), str(update_uri)
207
208
209 def firmware_update(obj, module):
210 """Firmware update using single binary file from Local path or HTTP location."""
211 gen_details = obj.get_server_generation
212 generation = gen_details[0]
213 image_path = module.params.get("image_uri")
214 trans_proto = module.params["transfer_protocol"]
215 inventory_uri, push_uri, update_uri = _get_update_service_target(obj, module, generation)
216 if image_path.startswith("http"):
217 payload = {"ImageURI": image_path, "TransferProtocol": trans_proto}
218 update_status = obj.invoke_request("POST", update_uri, data=payload)
219 else:
220 payload_file_header = FILE_PAYLOAD_HEADER
221 headers = {}
222 if generation <= 16:
223 resp_inv = obj.invoke_request("GET", inventory_uri)
224 headers = {"If-Match": resp_inv.headers.get("etag")}
225 payload_file_header = "file"
226
227 with open(os.path.join(image_path), "rb") as img_file:
228 binary_payload = {payload_file_header: (image_path.split(os.sep)[-1], img_file, "multipart/form-data")}
229 data, ctype = _encode_form_data(binary_payload, payload_file_header)
230 headers.update({"Content-Type": ctype})
231 upload_status = obj.invoke_request("POST", push_uri, data=data, headers=headers, dump=False, api_timeout=module.params["timeout"])
232 if generation <= 16 and upload_status.status_code == 201:
233 payload = {"ImageURI": upload_status.headers.get("location")}
234 update_status = obj.invoke_request("POST", update_uri, data=payload)
235 else:
236 update_status = upload_status
237 return update_status
238
239
240 def wait_for_job_completion(module, job_uri, job_wait_timeout=900, interval=30):
241 try:
242 with Redfish(module.params, req_session=False) as obj:
243 track_counter = 0
244 final_jobstatus = ""
245 job_msg = ""
246 while track_counter <= job_wait_timeout:
247 try:
248 response = obj.invoke_request("GET", "{0}{1}".format(obj.root_uri, job_uri))
249 if response.json_data.get("PercentComplete") == 100:
250 if response.json_data.get("JobStatus") == "OK":
251 final_jobstatus = JOBSTATUS_SUCCESS
252 job_msg = SUCCESS_JOB_MSG
253 else:
254 final_jobstatus = JOBSTATUS_FAILED
255 job_msg = FAIL_JOB_MSG
256 break
257 track_counter += interval
258 time.sleep(interval)
259 except (HTTPError, URLError):
260 track_counter += interval
261 time.sleep(interval)
262 # TIMED OUT
263 # when job is scheduled
264 if not final_jobstatus:
265 if response.json_data.get("PercentComplete") == 0 and response.json_data.get("JobState") == "Starting":
266 final_jobstatus = JOBSTATUS_SCHEDULED
267 job_msg = SCHEDULE_JOB_MSG
268 # when job timed out
269 else:
270 job_msg = JOB_WAIT_MSG.format(job_wait_timeout)
271 final_jobstatus = JOBSTATUS_TIMED_OUT
272 except Exception as error_message:
273 job_msg = str(error_message)
274 module.exit_json(msg=str(job_msg))
275 final_jobstatus = JOBSTATUS_ERRORED
276 return final_jobstatus, job_msg
277
278
279 def main():
280 specs = {
281 "image_uri": {"required": True, "type": "str"},
282 "transfer_protocol": {"type": "str", "default": "HTTP", "choices": ["CIFS", "FTP", "HTTP", "HTTPS", "NSF", "OEM", "SCP", "SFTP", "TFTP"]},
283 "job_wait": {"required": False, "type": 'bool', "default": True},
284 "job_wait_timeout": {"required": False, "type": "int", "default": 3600}
285 }
286
287 module = RedfishAnsibleModule(
288 argument_spec=specs,
289 supports_check_mode=False)
290 if not HAS_LIB:
291 module.fail_json(msg=missing_required_lib("urllib3"))
292 try:
293 message = "Failed to submit the firmware update task."
294 with Redfish(module.params, req_session=True) as obj:
295 status = firmware_update(obj, module)
296 if status.success:
297 message = "Successfully submitted the firmware update task."
298 task_uri = status.headers.get("Location")
299 job_id = task_uri.split("/")[-1]
300 else:
301 module.fail_json(msg=message, error_info=json.loads(status))
302 job_wait = module.params['job_wait']
303 job_wait_timeout = module.params['job_wait_timeout']
304 if job_wait and job_wait_timeout > 0:
305 job_uri = JOB_URI.format(job_id=job_id)
306 job_resp, job_msg = wait_for_job_completion(module, job_uri, job_wait_timeout=module.params['job_wait_timeout'])
307 if job_resp == JOBSTATUS_FAILED:
308 module.exit_json(msg=job_msg, task={"id": job_id, "uri": JOB_URI.format(job_id=job_id)}, failed=True)
309 else:
310 module.exit_json(msg=job_msg, task={"id": job_id, "uri": JOB_URI.format(job_id=job_id)}, changed=True)
311 else:
312 module.exit_json(msg=message, task={"id": job_id, "uri": JOB_URI.format(job_id=job_id)}, changed=True)
313 except HTTPError as err:
314 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
315 except (RuntimeError, URLError, SSLValidationError, ConnectionError, KeyError,
316 ImportError, ValueError, TypeError, IOError, AssertionError, OSError, SSLError) as e:
317 module.fail_json(msg=str(e))
318
319
320 if __name__ == '__main__':
321 main()