Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/redfish_firmware_rollback.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) 2023-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
17 DOCUMENTATION = r"""
18 ---
19 module: redfish_firmware_rollback
20 short_description: To perform a component firmware rollback using component name
21 version_added: "8.2.0"
22 description:
23 - This module allows to rollback the firmware of different server components.
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 name:
29 type: str
30 required: true
31 description:
32 - The name or regular expression of the component to match and is case-sensitive.
33 - "The Name should be a supported rollback component. To view the list of rollback components for iDRAC9 and above,
34 see, U(https://I(idrac_ip)/redfish/v1/UpdateService/FirmwareInventory?$expand=*($levels=1)'"
35 reboot:
36 description:
37 - Reboot the server to apply the previous version of the firmware.
38 - C(true) reboots the server to rollback the firmware to the available version.
39 - C(false) schedules the rollback of firmware until the next restart.
40 - When I(reboot) is C(false), some components update immediately, and the server may reboot.
41 So, the module must wait till the server is accessible.
42 type: bool
43 default: true
44 reboot_timeout:
45 type: int
46 description: Wait time in seconds. The module waits for this duration till the server reboots.
47 default: 900
48 requirements:
49 - "python >= 3.9.6"
50 author:
51 - "Felix Stephen (@felixs88)"
52 - "Sakshi Makkar (@Sakshi-dell)"
53 notes:
54 - Run this module from a system that has direct access to Redfish APIs.
55 - For components that do not require a reboot, firmware rollback proceeds irrespective of
56 I(reboot) is C(true) or C(false).
57 - This module supports IPv4 and IPv6 addresses.
58 - This module supports C(check_mode).
59 """
60
61 EXAMPLES = """
62 ---
63 - name: Rollback a BIOS component firmware
64 dellemc.openmanage.redfish_firmware_rollback:
65 baseuri: "192.168.0.1"
66 username: "user_name"
67 password: "user_password"
68 ca_path: "/path/to/ca_cert.pem"
69 name: "BIOS"
70
71 - name: Rollback all NIC cards with a name starting from 'Broadcom Gigabit'.
72 dellemc.openmanage.redfish_firmware_rollback:
73 baseuri: "192.168.0.1:443"
74 username: "user_name"
75 password: "user_password"
76 ca_path: "/path/to/ca_cert.pem"
77 name: "Broadcom Gigabit Ethernet.*"
78
79 - name: Rollback all the component firmware except BIOS component.
80 dellemc.openmanage.redfish_firmware_rollback:
81 baseuri: "192.168.0.1:443"
82 username: "user_name"
83 password: "user_password"
84 ca_path: "/path/to/ca_cert.pem"
85 name: "(?!BIOS).*"
86
87 - name: Rollback all the available firmware component.
88 dellemc.openmanage.redfish_firmware_rollback:
89 baseuri: "192.168.0.1:443"
90 username: "user_name"
91 password: "user_password"
92 ca_path: "/path/to/ca_cert.pem"
93 name: ".*"
94 """
95
96 RETURN = """
97 ---
98 msg:
99 type: str
100 description: Overall firmware rollback status.
101 returned: always
102 sample: "Successfully completed the job for firmware rollback."
103 status:
104 type: list
105 description: Firmware rollback job and progress details from the iDRAC.
106 returned: success
107 sample: [{
108 "ActualRunningStartTime": "2023-08-04T12:26:55",
109 "ActualRunningStopTime": "2023-08-04T12:32:35",
110 "CompletionTime": "2023-08-04T12:32:35",
111 "Description": "Job Instance",
112 "EndTime": "TIME_NA",
113 "Id": "JID_911698303631",
114 "JobState": "Completed",
115 "JobType": "FirmwareUpdate",
116 "Message": "Job completed successfully.",
117 "MessageArgs": [],
118 "MessageId": "PR19",
119 "Name": "Firmware Rollback: Firmware",
120 "PercentComplete": 100,
121 "StartTime": "2023-08-04T12:23:50",
122 "TargetSettingsURI": null
123 }]
124 error_info:
125 type: dict
126 description: Details of the HTTP error.
127 returned: on http error
128 sample: {
129 "error": {
130 "@Message.ExtendedInfo": [{
131 "Message": "InstanceID value provided for the update operation is invalid",
132 "MessageArgs": [],
133 "[email protected]": 0,
134 "MessageId": "IDRAC.2.8.SUP024",
135 "RelatedProperties": [],
136 "[email protected]": 0,
137 "Resolution": "Enumerate inventory, copy the InstanceID value and provide that value for the update operation.",
138 "Severity": "Warning"
139 }],
140 "code": "Base.1.12.GeneralError",
141 "message": "A general error has occurred. See ExtendedInfo for more information"
142 }
143 }
144 """
145
146
147 import json
148 import re
149 import time
150 from ssl import SSLError
151 from ansible_collections.dellemc.openmanage.plugins.module_utils.redfish import Redfish, RedfishAnsibleModule
152 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import wait_for_redfish_reboot_job, \
153 wait_for_redfish_job_complete, strip_substr_dict, MANAGER_JOB_ID_URI_10, MANAGERS_URI
154 from ansible.module_utils.urls import ConnectionError, SSLValidationError
155 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
156
157
158 UPDATE_SERVICE = "UpdateService"
159 SYSTEM_RESOURCE_ID = "System.Embedded.1"
160 NO_COMPONENTS = "There were no firmware components to rollback."
161 CHANGES_FOUND = "Changes found to be applied."
162 NO_CHANGES_FOUND = "No changes found to be applied."
163 NOT_SUPPORTED = "The target firmware version does not support the firmware rollback."
164 COMPLETED_ERROR = "The job for firmware rollback has been completed with error(s)."
165 SCHEDULED_ERROR = "The job for firmware rollback has been scheduled with error(s)."
166 ROLLBACK_SUCCESS = "Successfully completed the job for firmware rollback."
167 ROLLBACK_SCHEDULED = "Successfully scheduled the job for firmware rollback."
168 ROLLBACK_FAILED = "Failed to complete the job for firmware rollback."
169 REBOOT_FAIL = "Failed to reboot the server."
170 NEGATIVE_TIMEOUT_MESSAGE = "The parameter reboot_timeout value cannot be negative or zero."
171 JOB_WAIT_MSG = "Task excited after waiting for {0} seconds. Check console for firmware rollback status."
172 REBOOT_COMP = ["Integrated Dell Remote Access Controller", "BMC Firmware Inventory"]
173 BIOS_COMP = ["BIOS", "BIOS Firmware Inventory"]
174 BACKPLANE_COMP = ["RAID.Backplane.Firmware Firmware Inventory"]
175 INITIAL_DELAY_17G = 240
176 SESSION_RESOURCE_COLLECTION = {
177 "SESSION": "/redfish/v1/SessionService/Sessions",
178 "SESSION_ID": "/redfish/v1/SessionService/Sessions/{Id}",
179 }
180
181
182 def categorize_components(previous_components, component_compile):
183 prev_uri, reboot_uri, bios_uri, backplane_uri = {}, [], [], []
184 for comp in previous_components:
185 available_name = comp["Name"]
186 if not re.match(component_compile, available_name):
187 continue
188
189 uri = comp["@odata.id"]
190
191 if available_name in REBOOT_COMP:
192 reboot_uri.append(uri)
193 elif available_name in BIOS_COMP:
194 bios_uri.append(uri)
195 elif available_name in BACKPLANE_COMP:
196 backplane_uri.append(uri)
197 else:
198 prev_uri[comp["Version"]] = uri
199
200 return prev_uri, reboot_uri, bios_uri, backplane_uri
201
202
203 def get_rollback_preview_target(redfish_obj, module):
204 action_resp = redfish_obj.invoke_request("GET", "{0}{1}".format(redfish_obj.root_uri, UPDATE_SERVICE))
205 action_attr = action_resp.json_data["Actions"]
206 update_service = action_attr.get("#UpdateService.SimpleUpdate")
207
208 if not update_service or 'target' not in update_service:
209 module.fail_json(msg=NOT_SUPPORTED)
210
211 update_uri = update_service.get('target')
212 inventory_uri = action_resp.json_data.get('FirmwareInventory').get('@odata.id')
213 inventory_uri_resp = redfish_obj.invoke_request("GET", "{0}{1}".format(inventory_uri, "?$expand=*($levels=1)"),
214 api_timeout=120)
215 previous_component = list(filter(lambda d: d["Id"].startswith("Previous"), inventory_uri_resp.json_data["Members"]))
216 if not previous_component:
217 module.fail_json(msg=NO_COMPONENTS)
218
219 component_name = module.params["name"]
220 try:
221 component_compile = re.compile(r"^{0}$".format(component_name))
222 except Exception:
223 module.exit_json(msg=NO_CHANGES_FOUND)
224
225 prev_uri, reboot_uri, bios_uri, backplane_uri = categorize_components(previous_component, component_compile)
226
227 if prev_uri or reboot_uri or bios_uri:
228 if module.check_mode:
229 module.exit_json(msg=CHANGES_FOUND, changed=True)
230 else:
231 module.exit_json(msg=NO_CHANGES_FOUND)
232
233 return list(prev_uri.values()), reboot_uri, update_uri, bios_uri, backplane_uri
234
235
236 def get_job_status(redfish_obj, module, job_ids, job_wait=True, check_completion=False):
237 each_status, failed_count, js_job_msg = [], 0, ""
238 wait_timeout = module.params["reboot_timeout"]
239 for each in job_ids:
240 each_job_uri = MANAGER_JOB_ID_URI_10.format(each)
241 job_resp, js_job_msg = wait_for_redfish_job_complete(redfish_obj, each_job_uri, job_wait=job_wait,
242 wait_timeout=wait_timeout, check_completion=check_completion)
243 if job_resp and js_job_msg:
244 module.exit_json(msg=JOB_WAIT_MSG.format(wait_timeout), job_status=[strip_substr_dict(job_resp.json_data)],
245 changed=True)
246 job_status = job_resp.json_data
247 if job_status["JobState"] == "Failed":
248 failed_count += 1
249 strip_odata = strip_substr_dict(job_status)
250 each_status.append(strip_odata)
251 return each_status, failed_count
252
253
254 def require_session(idrac, module):
255 session_id, token = "", None
256 payload = {'UserName': module.params["username"], 'Password': module.params["password"]}
257 path = SESSION_RESOURCE_COLLECTION["SESSION"]
258 resp = idrac.invoke_request('POST', path, data=payload, api_timeout=120)
259 if resp and resp.success:
260 session_id = resp.json_data.get("Id")
261 token = resp.headers.get('X-Auth-Token')
262 return session_id, token
263
264
265 def wait_for_redfish_idrac_reset(module, redfish_obj, wait_time_sec, generation, interval=30):
266 _sleep_initial_delay(generation, interval)
267
268 wait = wait_time_sec
269 track_failed = True
270 resetting = False
271 while wait > 0 and track_failed:
272 try:
273 redfish_obj.invoke_request("GET", MANAGERS_URI, api_timeout=120)
274 track_failed = False
275 break
276 except HTTPError as err:
277 if err.getcode() == 401:
278 redfish_obj, wait, resetting = _handle_unauthorized_error(module, redfish_obj, generation, wait)
279 track_failed = False
280 else:
281 wait, resetting = _handle_connection_error(wait, interval, resetting)
282 except (URLError, Exception):
283 wait, resetting = _handle_connection_error(wait, interval, resetting)
284
285 return track_failed, resetting
286
287
288 def _sleep_initial_delay(generation, interval):
289 """Sleep before starting the polling for reset."""
290 if generation >= 17:
291 time.sleep(INITIAL_DELAY_17G)
292 else:
293 time.sleep(interval // 2)
294
295
296 def _handle_unauthorized_error(module, redfish_obj, generation, wait):
297 """Handle 401 Unauthorized errors during reset polling."""
298 if generation >= 17:
299 time.sleep(INITIAL_DELAY_17G)
300 wait -= INITIAL_DELAY_17G
301 new_redfish_obj = Redfish(module.params, req_session=True)
302 sid, token = require_session(new_redfish_obj, module)
303 redfish_obj.session_id = sid
304 redfish_obj._headers.update({"X-Auth-Token": token})
305 return redfish_obj, wait, True
306
307
308 def _handle_connection_error(wait, interval, resetting):
309 """Handle connection-related issues such as URLError or unknown exceptions."""
310 time.sleep(interval)
311 wait -= interval
312 if not resetting:
313 resetting = True
314 return wait, resetting
315
316
317 def simple_update(redfish_obj, preview_uri, update_uri):
318 job_ids = []
319 for uri in preview_uri:
320 resp = redfish_obj.invoke_request("POST", update_uri, data={"ImageURI": uri})
321 time.sleep(30)
322 task_uri = resp.headers.get("Location")
323 task_id = task_uri.split("/")[-1]
324 job_ids.append(task_id)
325 return job_ids
326
327
328 def handle_reboot_job(redfish_obj, module):
329 payload = {"ResetType": "ForceRestart"}
330 job_resp_status, reset_status, reset_fail = wait_for_redfish_reboot_job(
331 redfish_obj, SYSTEM_RESOURCE_ID, payload=payload
332 )
333
334 if not reset_status and reset_fail:
335 module.fail_json(msg=reset_fail)
336
337 if reset_status and job_resp_status:
338 job_uri = MANAGER_JOB_ID_URI_10.format(job_resp_status["Id"])
339 job_resp, job_msg = wait_for_redfish_job_complete(redfish_obj, job_uri)
340 job_state = job_resp.json_data.get("JobState")
341
342 if job_state != "RebootCompleted":
343 module.fail_json(
344 msg=JOB_WAIT_MSG.format(module.params["reboot_timeout"]) if job_msg else REBOOT_FAIL
345 )
346
347
348 def rollback_firmware(redfish_obj, module, preview_uri, reboot_uri, update_uri, bios_uri, backplane_uri):
349 current_job_status, failed_cnt, resetting = [], 0, False
350 direct_updates = []
351 job_ids = simple_update(redfish_obj, preview_uri, update_uri)
352
353 for job_id in job_ids:
354 job_uri = MANAGER_JOB_ID_URI_10.format(job_id)
355 job_resp, _job_msg = wait_for_redfish_job_complete(redfish_obj, job_uri, job_wait=False)
356 job_state = job_resp.json_data.get("JobState")
357 if job_state in {"Running", "Scheduling"}:
358 direct_updates.append(job_id)
359
360 if direct_updates:
361 _status, _failed = get_job_status(redfish_obj, module, direct_updates, job_wait=True)
362
363 # handle backplane uri separately since they interfere with other updates in iDRAC 10 (generation >= 17G)
364 if backplane_uri:
365 backplane_job_id = simple_update(redfish_obj, backplane_uri, update_uri)
366 status, failed = get_job_status(redfish_obj, module, backplane_job_id, job_wait=True, check_completion=True)
367 current_job_status.extend(status)
368 failed_cnt += failed
369
370 if bios_uri:
371 bios_job_ids = simple_update(redfish_obj, bios_uri, update_uri)
372 job_ids.extend(bios_job_ids)
373
374 if job_ids:
375 if module.params["reboot"]:
376 handle_reboot_job(redfish_obj, module)
377 status, failed = get_job_status(redfish_obj, module, job_ids, job_wait=True, check_completion=True)
378 else:
379 status, failed = get_job_status(redfish_obj, module, job_ids, job_wait=False)
380 current_job_status.extend(status)
381 failed_cnt += failed
382
383 if reboot_uri:
384 generation = redfish_obj.get_server_generation[0]
385 reboot_job_ids = simple_update(redfish_obj, reboot_uri, update_uri)
386 track, resetting = wait_for_redfish_idrac_reset(module, redfish_obj, 900, generation)
387 if not track and resetting:
388 status, failed = get_job_status(redfish_obj, module, reboot_job_ids, job_wait=True)
389 current_job_status.extend(status)
390 failed_cnt += failed
391
392 return current_job_status, failed_cnt, resetting
393
394
395 def main():
396 specs = {
397 "name": {"required": True, "type": "str"},
398 "reboot": {"type": "bool", "default": True},
399 "reboot_timeout": {"type": "int", "default": 900},
400 }
401
402 module = RedfishAnsibleModule(argument_spec=specs, supports_check_mode=True)
403 if module.params["reboot_timeout"] <= 0:
404 module.fail_json(msg=NEGATIVE_TIMEOUT_MESSAGE)
405 try:
406 with Redfish(module.params, req_session=True) as redfish_obj:
407 preview_uri, reboot_uri, update_uri, bios_uri, backplane_uri = get_rollback_preview_target(redfish_obj, module)
408 job_status, failed_count, resetting = rollback_firmware(redfish_obj, module, preview_uri, reboot_uri, update_uri, bios_uri, backplane_uri)
409 if not job_status or (failed_count == len(job_status)):
410 module.exit_json(msg=ROLLBACK_FAILED, status=job_status, failed=True)
411 if module.params["reboot"]:
412 msg, module_fail, changed = ROLLBACK_SUCCESS, False, True
413 if failed_count > 0 and failed_count != len(job_status):
414 msg, module_fail, changed = COMPLETED_ERROR, True, False
415 else:
416 msg, module_fail, changed = ROLLBACK_SCHEDULED, False, True
417 if failed_count > 0 and failed_count != len(job_status):
418 msg, module_fail, changed = SCHEDULED_ERROR, True, False
419 elif resetting and len(job_status) == 1 and failed_count != len(job_status):
420 msg, module_fail, changed = ROLLBACK_SUCCESS, False, True
421 module.exit_json(msg=msg, job_status=job_status, failed=module_fail, changed=changed)
422 except HTTPError as err:
423 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
424 except URLError as err:
425 module.exit_json(msg=str(err), unreachable=True)
426 except (RuntimeError, SSLValidationError, ConnectionError, KeyError,
427 ImportError, ValueError, TypeError, IOError, AssertionError, OSError, SSLError) as e:
428 module.fail_json(msg=str(e))
429
430
431 if __name__ == '__main__':
432 main()