Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.5.0
7 # Copyright (C) 2020-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_powerstate
19 short_description: Manage device power state
20 version_added: "2.1.0"
21 description:
22 - This module allows to manage the different power states of the specified device.
23 extends_documentation_fragment:
24 - dellemc.openmanage.redfish_auth_options
25 options:
26 resource_id:
27 description:
28 - This option is the unique identifier of the device being managed. For example, U(https://<I(baseuri)>/redfish/v1/Systems/<I(resource_id)>).
29 - This option is mandatory for I(base_uri) with multiple devices.
30 - To get the device details, use the API U(https://<I(baseuri)>/redfish/v1/Systems) for reset_type operation and
31 U(https://<I(baseuri)>/redfish/v1/Chassis) for oem_reset_type operation.
32 required: false
33 type: str
34 reset_type:
35 description:
36 - This option resets the device.
37 - C(ForceOff) turns off the device immediately.
38 - C(ForceOn) turns on the device immediately.
39 - C(ForceRestart) turns off the device immediately, and then restarts the server.
40 - C(GracefulRestart) performs graceful shutdown of the device, and then restarts the device.
41 - C(GracefulShutdown) performs a graceful shutdown of the device, and then turns off the device.
42 - C(Nmi) sends a diagnostic interrupt to the device. This option is usually a nonmaskable interrupt (NMI) on x86 systems.
43 - C(On) turns on the device.
44 - C(PowerCycle) performs a power cycle on the device.
45 - C(PushPowerButton) simulates the pressing of a physical power button on the device.
46 - I(reset_type) is mutually exclusive with I(oem_reset_type).
47 - When a power control operation is performed, which is not supported on the device, an error message is displayed
48 with the list of operations that can be performed.
49 required: false
50 type: str
51 choices: ["ForceOff", "ForceOn", "ForceRestart", "GracefulRestart", "GracefulShutdown",
52 "Nmi", "On", "PowerCycle", "PushPowerButton"]
53 oem_reset_type:
54 description:
55 - This parameter initiates a complete Alternate Current (AC) power cycle of the server which is equivalent to disconnecting power cables using OEM API.
56 - I(oem_reset_type) is mutually exclusive with I(reset_type).
57 - If the value of 'final_power_state' is not provided, the default value is 'Off'.
58 required: false
59 type: dict
60 version_added: 9.5.0
61 requirements:
62 - "python >= 3.9.6"
63 author:
64 - "Sajna Shetty(@Sajna-Shetty)"
65 - "Lovepreet Singh (@singh-lovepreet1)"
66 notes:
67 - Run this module from a system that has direct access to Redfish APIs.
68 - This module supports C(check_mode).
69 '''
70
71 EXAMPLES = r'''
72 ---
73 - name: Manage power state of the first device
74 dellemc.openmanage.redfish_powerstate:
75 baseuri: "192.168.0.1"
76 username: "username"
77 password: "password"
78 ca_path: "/path/to/ca_cert.pem"
79 reset_type: "On"
80
81 - name: Manage power state of a specified device
82 dellemc.openmanage.redfish_powerstate:
83 baseuri: "192.168.0.1"
84 username: "username"
85 password: "password"
86 ca_path: "/path/to/ca_cert.pem"
87 reset_type: "ForceOff"
88 resource_id: "System.Embedded.1"
89
90 - name: Perform AC Power Cycle with final power state On
91 dellemc.openmanage.redfish_powerstate:
92 baseuri: "192.168.0.1"
93 username: "username"
94 password: "password"
95 ca_path: "/path/to/ca_cert.pem"
96 oem_reset_type:
97 dell:
98 final_power_state: "On"
99 reset_type: "PowerCycle"
100
101 - name: Perform AC Power Cycle with final power state Off
102 dellemc.openmanage.redfish_powerstate:
103 baseuri: "192.168.0.1"
104 username: "username"
105 password: "password"
106 ca_path: "/path/to/ca_cert.pem"
107 oem_reset_type:
108 dell:
109 final_power_state: "Off"
110 reset_type: "PowerCycle"
111 '''
112
113 RETURN = r'''
114 ---
115 msg:
116 description: Overall status of the reset operation.
117 returned: always
118 type: str
119 sample: "Successfully performed the reset type operation 'On'."
120 error_info:
121 type: dict
122 description: Details of the HTTP error.
123 returned: on http error
124 sample: {
125 "error": {
126 "@Message.ExtendedInfo": [
127 {
128 "Message": "Unable to complete the operation because the resource
129 /redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset entered in not found.",
130 "MessageArgs": [
131 "/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset"
132 ],
133 "[email protected]": 1,
134 "MessageId": "IDRAC.2.1.SYS403",
135 "RelatedProperties": [],
136 "[email protected]": 0,
137 "Resolution": "Enter the correct resource and retry the operation.
138 For information about valid resource,
139 see the Redfish Users Guide available on the support site.",
140 "Severity": "Critical"
141 },
142 ],
143 "code": "Base.1.5.GeneralError",
144 "message": "A general error has occurred. See ExtendedInfo for more information"
145 }
146 }
147 '''
148
149 import json
150 import re
151 from ssl import SSLError
152 from ansible.module_utils.compat.version import LooseVersion
153 from ansible_collections.dellemc.openmanage.plugins.module_utils.redfish import Redfish, RedfishAnsibleModule
154 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
155 from ansible.module_utils.urls import ConnectionError
156
157
158 CHANGES_FOUND = "Changes found to be applied."
159 NO_CHANGES_FOUND = "No Changes found to be applied."
160 FIRM_VER_URI = "/redfish/v1/Managers/iDRAC.Embedded.1?$select=FirmwareVersion"
161 INVALID_RESET_TYPE_OEM = "'{option}' is not supported. The supported values" \
162 " are {supported_oem_reset_type_values}. Enter the valid values and retry" \
163 " the operation."
164 TARGET_DEVICE_NOT_SUPPORTED = "The target device does not support the system reset feature using Redfish API."
165 INVALID_DEVICE_ID = "Invalid device Id '{0}' is provided"
166 MINIMUM_SUPPORTED_FIRMWARE_VERSION = "7.00.60"
167 UNSUPPORTED_FIRMWARE_MSG = "Unable to perform the Virtual AC power-cycle" \
168 " operation because the firmware version is not supported. The minimum" \
169 " supported firmware version is '{minimum_supported_firmware_version}'."
170 INITIAL_DESIRED_STATE_ERROR = "No changes found to be applied because system is in power ON state."
171 VENDOR_NOT_SUPPORTED = "The vendor is not supported. The supported vendors" \
172 " are '{supported_vendors}'. Enter the valid vendor and retry the operation."
173 SUCCESS_AC_MSG = "Successfully performed the full virtual server AC power-cycle operation."
174 SUCCESS_AC_MSG_ON = "Successfully performed the full virtual server AC power-cycle operation." \
175 " Please wait a few minutes, the server will automatically power on."
176 INVALID_RESET_TYPE = "The target device does not support a {0} operation.The acceptable values for device reset types are {1}."
177 OEM_RESET_KEY = '#{0}OemChassis.ExtendedReset'
178 INVALID_PWR_ERROR = "The target device does not support '{0}' operation. The valid values of final power states for device are '{1}'."
179 VENDOR_NOT_SPECIFIED = "The vendor is not specified. Enter the valid vendor and retry the operation."
180 OPERATION_ERROR = "No reset type is specified for the target device. Enter the valid value and retry the operation."
181 powerstate_map = {}
182
183
184 def fetch_powerstate_details(system_res_data, action_data):
185 current_state = system_res_data["PowerState"]
186 power_uri = action_data['#ComputerSystem.Reset']['target']
187 allowable_enums = action_data['#ComputerSystem.Reset']['[email protected]']
188 powerstate_map.update(
189 {'power_uri': power_uri, 'allowable_enums': allowable_enums, 'current_state': current_state})
190
191
192 def fetch_ac_powerstate_details(module, system_id_res_data, action_id_res):
193 current_state = system_id_res_data.get("PowerState")
194 oem_reset_type = module.params["oem_reset_type"]
195 current_vendor = next(iter(oem_reset_type), None)
196 oem_key_resp = action_id_res.get('Oem')
197 if oem_key_resp is None:
198 module.exit_json(msg=TARGET_DEVICE_NOT_SUPPORTED, skipped=True)
199 sub_key = OEM_RESET_KEY.format(current_vendor.capitalize())
200 sub_oem_key = None
201 if oem_key_resp is not None:
202 sub_oem_key = oem_key_resp.get(sub_key)
203 if sub_oem_key is None:
204 module.exit_json(msg=TARGET_DEVICE_NOT_SUPPORTED, skipped=True)
205 power_uri = None
206 allowable_enums = None
207 allowable_final_power_state = None
208 if sub_oem_key is not None:
209 power_uri = sub_oem_key.get('target')
210 allowable_enums = sub_oem_key.get('[email protected]')
211 allowable_final_power_state = sub_oem_key.get('[email protected]')
212 powerstate_map.update(
213 {'power_uri': power_uri, 'allowable_enums': allowable_enums,
214 'current_state': current_state, 'allowable_power_state': allowable_final_power_state})
215
216
217 def perform_uri_fetch(session_obj, module, system_id_res, resource_id_list, resource_id):
218 reset_type = module.params.get("reset_type")
219 if system_id_res in resource_id_list:
220 system_id_res_resp = session_obj.invoke_request("GET", system_id_res)
221 system_id_res_data = system_id_res_resp.json_data
222 action_id_res = system_id_res_data.get("Actions")
223 if action_id_res:
224 if reset_type:
225 fetch_powerstate_details(system_id_res_data, action_id_res)
226 else:
227 fetch_ac_powerstate_details(module, system_id_res_data, action_id_res)
228 else:
229 module.exit_json(msg=TARGET_DEVICE_NOT_SUPPORTED, skipped=True)
230 else:
231 module.exit_json(msg=INVALID_DEVICE_ID.format(resource_id), skipped=True)
232
233
234 def fetch_power_uri_resource(module, session_obj, reset_type_map=None):
235 try:
236 resource_id = module.params.get("resource_id")
237 static_resource_id_resource = None
238 if resource_id:
239 static_resource_id_resource = "{0}{1}{2}".format(session_obj.root_uri, reset_type_map + "/", resource_id)
240 system_uri = "{0}{1}".format(session_obj.root_uri, reset_type_map)
241 system_resp = session_obj.invoke_request("GET", system_uri)
242 system_members = system_resp.json_data.get("Members")
243 if system_members and len(system_members) > 0:
244 resource_id_list = [system_id["@odata.id"] for system_id in system_members if "@odata.id" in system_id]
245 system_id_res = static_resource_id_resource or resource_id_list[0]
246 perform_uri_fetch(session_obj, module, system_id_res, resource_id_list, resource_id)
247 else:
248 module.exit_json(msg=TARGET_DEVICE_NOT_SUPPORTED, skipped=True)
249 except HTTPError as err:
250 if err.code in [404, 405]:
251 module.exit_json(msg=TARGET_DEVICE_NOT_SUPPORTED,
252 error_info=json.load(err), failed=True)
253 raise err
254
255
256 def is_change_applicable_for_power_state(current_power_state, apply_power_state):
257 """ checks if changes are applicable or not for current system state
258 :param current_power_state: Current power state
259 :type current_power_state: str
260 :param apply_power_state: Required power state
261 :type apply_power_state: str
262 :return: boolean True if changes is applicable
263 """
264 on_states = ["On", "PoweringOn"]
265 off_states = ["Off", "PoweringOff"]
266
267 reset_map_apply = {
268 ("On", "ForceOn",): off_states,
269 ("PushPowerButton",): on_states + off_states,
270 ("ForceOff", "ForceRestart", "GracefulRestart", "GracefulShutdown", "Nmi", "PowerCycle",): on_states
271 }
272 is_reset_applicable = False
273 for apply_states, applicable_states in reset_map_apply.items():
274 if apply_power_state in apply_states:
275 if current_power_state in applicable_states:
276 is_reset_applicable = True
277 break
278 break
279 return is_reset_applicable
280
281
282 def is_valid_reset_type(reset_type, allowable_enum, module):
283 reset_type_param = module.params.get('reset_type')
284 if reset_type not in allowable_enum:
285 res_list = re.findall('[A-Z][^A-Z]*', reset_type)
286 lw_reset_type = " ".join([word.lower() for word in res_list])
287 if reset_type_param:
288 error_msg = INVALID_RESET_TYPE.format(lw_reset_type, ", ".join(allowable_enum))
289 else:
290 error_msg = INVALID_RESET_TYPE_OEM.format(option=reset_type,
291 supported_oem_reset_type_values=", ".join(allowable_enum))
292 module.exit_json(msg=error_msg, failed=True)
293
294
295 def is_valid_final_pwr_state(final_pwr_state, allowed_final_pwr_state, module):
296 if final_pwr_state.capitalize() not in allowed_final_pwr_state:
297 error_msg = INVALID_PWR_ERROR.format(final_pwr_state, ", ".join(allowed_final_pwr_state))
298 module.exit_json(msg=error_msg, failed=True)
299
300
301 def is_valid_vendor(redfish_session_obj, module, vendor):
302 system_resp = redfish_session_obj.invoke_request("GET", "/redfish/v1/")
303 system_vendor = system_resp.json_data.get("Vendor")
304 if system_vendor.lower() != vendor.lower():
305 module.exit_json(msg=VENDOR_NOT_SUPPORTED.format(supported_vendors=system_vendor), skipped=True)
306
307
308 def check_firmware_version(module, redfish_session_obj):
309 resp = redfish_session_obj.invoke_request("GET", FIRM_VER_URI)
310 redfish_firmware_version = resp.json_data.get('FirmwareVersion', '')
311 if LooseVersion(redfish_firmware_version) <= MINIMUM_SUPPORTED_FIRMWARE_VERSION:
312 module.exit_json(msg=UNSUPPORTED_FIRMWARE_MSG.format(
313 minimum_supported_firmware_version=MINIMUM_SUPPORTED_FIRMWARE_VERSION), skipped=True)
314
315
316 def prepare_payload(current_vendor_dict):
317 payload = {}
318 final_pwr_state = current_vendor_dict.get("final_power_state")
319 reset_type = current_vendor_dict.get("reset_type")
320 if final_pwr_state:
321 final_pwr_state = final_pwr_state.capitalize()
322 payload["FinalPowerState"] = final_pwr_state
323 if reset_type:
324 payload["ResetType"] = reset_type
325 return payload
326
327
328 def run_change_power_state(redfish_session_obj, module):
329 """
330 Apply reset type to system
331 Keyword arguments:
332 redfish_session_obj -- session handle
333 module -- Ansible module obj
334 """
335 apply_reset_type = module.params["reset_type"]
336 fetch_power_uri_resource(module, redfish_session_obj, "Systems")
337 is_valid_reset_type(apply_reset_type, powerstate_map["allowable_enums"], module)
338 current_power_state = powerstate_map["current_state"]
339 reset_flag = is_change_applicable_for_power_state(current_power_state, apply_reset_type)
340 if module.check_mode is True:
341 if reset_flag is True:
342 module.exit_json(msg=CHANGES_FOUND, changed=True)
343 else:
344 module.exit_json(msg=NO_CHANGES_FOUND, changed=False)
345
346 if reset_flag is True:
347 payload = {"ResetType": apply_reset_type}
348 power_uri = powerstate_map["power_uri"]
349 reset_resp = redfish_session_obj.invoke_request("POST", power_uri, data=payload)
350 if reset_resp.success:
351 module.exit_json(msg="Successfully performed the reset type operation"
352 " '{0}'.".format(apply_reset_type), changed=True)
353 else:
354 module.exit_json(msg="Unable to perform the reset type operation '{0}'.".format(apply_reset_type),
355 changed=False)
356 else:
357 module.exit_json(msg="The device is already powered {0}.".format(current_power_state.lower()), changed=False)
358
359
360 def power_cycle_check_mode(module):
361 current_power_state = powerstate_map["current_state"]
362 if module.check_mode:
363 if current_power_state.lower() != 'off':
364 module.exit_json(msg=INITIAL_DESIRED_STATE_ERROR)
365 module.exit_json(msg=CHANGES_FOUND, changed=True)
366
367
368 def run_change_ac_power_cycle(redfish_session_obj, module):
369 check_firmware_version(module, redfish_session_obj)
370 oem_reset_type = module.params["oem_reset_type"]
371 current_vendor = next(iter(oem_reset_type), None)
372 is_valid_vendor(redfish_session_obj, module, current_vendor)
373 current_vendor_dict = oem_reset_type[current_vendor]
374 apply_reset_type = None
375 if "reset_type" in current_vendor_dict:
376 apply_reset_type = current_vendor_dict['reset_type']
377 final_pwr_state = None
378 if "final_power_state" in current_vendor_dict:
379 final_pwr_state = current_vendor_dict["final_power_state"]
380 if apply_reset_type is None or apply_reset_type == "":
381 module.exit_json(msg=OPERATION_ERROR, skipped=True)
382 fetch_power_uri_resource(module, redfish_session_obj, "Chassis")
383 is_valid_reset_type(apply_reset_type, powerstate_map["allowable_enums"], module)
384 if final_pwr_state:
385 is_valid_final_pwr_state(final_pwr_state, powerstate_map["allowable_power_state"], module)
386 power_cycle_check_mode(module)
387 payload = prepare_payload(current_vendor_dict)
388 power_uri = powerstate_map["power_uri"]
389 try:
390 reset_resp = redfish_session_obj.invoke_request("POST", power_uri, data=payload)
391 if reset_resp.status_code == 204:
392 if final_pwr_state and final_pwr_state.lower() == "on":
393 module.exit_json(msg=SUCCESS_AC_MSG_ON, changed=True)
394 module.exit_json(msg=SUCCESS_AC_MSG, changed=True)
395 except HTTPError as err:
396 err_message = json.load(err)
397 if err.code == 409 and err_message["error"]["@Message.ExtendedInfo"][0]["MessageId"] == "IDRAC.2.9.PSU507":
398 error_msg = err_message["error"]["@Message.ExtendedInfo"][0]["Message"]
399 module.exit_json(msg=error_msg, skipped=True)
400
401
402 def main():
403 specs = {
404 "resource_id": {"required": False, "type": "str"},
405 "reset_type": {"required": False, "type": "str",
406 "choices": ['ForceOff', 'ForceOn', 'ForceRestart', 'GracefulRestart',
407 'GracefulShutdown', 'Nmi', 'On', 'PowerCycle', 'PushPowerButton']},
408 "oem_reset_type": {"required": False, "type": "dict"},
409 }
410 module = RedfishAnsibleModule(
411 argument_spec=specs,
412 supports_check_mode=True,
413 mutually_exclusive=[("oem_reset_type", "reset_type")])
414 try:
415 reset_type = module.params["reset_type"]
416 oem_reset_type = module.params["oem_reset_type"]
417 with Redfish(module.params) as redfish_obj:
418 if reset_type:
419 run_change_power_state(redfish_obj, module)
420 elif oem_reset_type:
421 run_change_ac_power_cycle(redfish_obj, module)
422 else:
423 module.exit_json(msg=OPERATION_ERROR, skipped=True)
424 except HTTPError as err:
425 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
426 except URLError as err:
427 module.exit_json(msg=str(err), unreachable=True)
428 except (IOError, ValueError, SSLError, TypeError, ConnectionError, OSError) as err:
429 module.exit_json(msg=str(err), failed=True)
430 except Exception as err:
431 module.exit_json(msg=str(err), failed=True)
432
433
434 if __name__ == '__main__':
435 main()