
    VhL                     4   d dl mZmZmZ eZdZdZdZd dl	Z	d dl
Z
d dlmZ d dlmZ d dlmZmZ d d	lmZmZ d d
lmZ dZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'i Z(d Z)d Z*d Z+d+dZ,d  Z-d! Z.d" Z/d# Z0d$ Z1d% Z2d& Z3d' Z4d( Z5d) Z6e7d*k(  r e6        yy),    )absolute_importdivisionprint_functionaX
  
---
module: redfish_powerstate
short_description: Manage device power state
version_added: "2.1.0"
description:
  - This module allows to manage the different power states of the specified device.
extends_documentation_fragment:
  - dellemc.openmanage.redfish_auth_options
options:
  resource_id:
    description:
      - This option is the unique identifier of the device being managed. For example, U(https://<I(baseuri)>/redfish/v1/Systems/<I(resource_id)>).
      - This option is mandatory for I(base_uri) with multiple devices.
      - To get the device details, use the API U(https://<I(baseuri)>/redfish/v1/Systems) for reset_type operation and
        U(https://<I(baseuri)>/redfish/v1/Chassis) for oem_reset_type operation.
    required:  false
    type: str
  reset_type:
    description:
      - This option resets the device.
      - C(ForceOff) turns off the device immediately.
      - C(ForceOn) turns on the device immediately.
      - C(ForceRestart) turns off the device immediately, and then restarts the server.
      - C(GracefulRestart) performs graceful shutdown of the device, and then restarts the device.
      - C(GracefulShutdown) performs a graceful shutdown of the device, and then turns off the device.
      - C(Nmi) sends a diagnostic interrupt to the device. This option is usually a nonmaskable interrupt (NMI) on x86 systems.
      - C(On) turns on the device.
      - C(PowerCycle) performs a power cycle on the device.
      - C(PushPowerButton) simulates the pressing of a physical power button on the device.
      - I(reset_type) is mutually exclusive with I(oem_reset_type).
      - When a power control operation is performed, which is not supported on the device, an error message is displayed
       with the list of operations that can be performed.
    required:  false
    type: str
    choices: ["ForceOff", "ForceOn", "ForceRestart", "GracefulRestart", "GracefulShutdown",
               "Nmi", "On", "PowerCycle", "PushPowerButton"]
  oem_reset_type:
    description:
      - This parameter initiates a complete Alternate Current (AC) power cycle of the server which is equivalent to disconnecting power cables using OEM API.
      - I(oem_reset_type) is mutually exclusive with I(reset_type).
      - If the value of 'final_power_state' is not provided, the default value is 'Off'.
    required:  false
    type: dict
    version_added: 9.5.0
requirements:
    - "python >= 3.9.6"
author:
    - "Sajna Shetty(@Sajna-Shetty)"
    - "Lovepreet Singh (@singh-lovepreet1)"
notes:
    - Run this module from a system that has direct access to Redfish APIs.
    - This module supports C(check_mode).
a\  
---
- name: Manage power state of the first device
  dellemc.openmanage.redfish_powerstate:
    baseuri: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    reset_type: "On"

- name: Manage power state of a specified device
  dellemc.openmanage.redfish_powerstate:
    baseuri: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    reset_type: "ForceOff"
    resource_id: "System.Embedded.1"

- name: Perform AC Power Cycle with final power state On
  dellemc.openmanage.redfish_powerstate:
    baseuri: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    oem_reset_type:
      dell:
        final_power_state: "On"
        reset_type: "PowerCycle"

- name: Perform AC Power Cycle  with final power state Off
  dellemc.openmanage.redfish_powerstate:
    baseuri: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    oem_reset_type:
      dell:
        final_power_state: "Off"
        reset_type: "PowerCycle"
a  
---
msg:
  description: Overall status of the reset operation.
  returned: always
  type: str
  sample: "Successfully performed the reset type operation 'On'."
error_info:
  type: dict
  description: Details of the HTTP error.
  returned: on http error
  sample:  {
    "error": {
        "@Message.ExtendedInfo": [
            {
                "Message": "Unable to complete the operation because the resource
                 /redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset entered in not found.",
                "MessageArgs": [
                    "/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset"
                ],
                "MessageArgs@odata.count": 1,
                "MessageId": "IDRAC.2.1.SYS403",
                "RelatedProperties": [],
                "RelatedProperties@odata.count": 0,
                "Resolution": "Enter the correct resource and retry the operation.
                 For information about valid resource,
                 see the Redfish Users Guide available on the support site.",
                "Severity": "Critical"
            },
        ],
        "code": "Base.1.5.GeneralError",
        "message": "A general error has occurred. See ExtendedInfo for more information"
    }
}
N)SSLError)LooseVersion)RedfishRedfishAnsibleModule)URLError	HTTPError)ConnectionErrorzChanges found to be applied.zNo Changes found to be applied.z=/redfish/v1/Managers/iDRAC.Embedded.1?$select=FirmwareVersionz'{option}' is not supported. The supported values are {supported_oem_reset_type_values}. Enter the valid values and retry the operation.zNThe target device does not support the system reset feature using Redfish API.z#Invalid device Id '{0}' is providedz7.00.60zUnable to perform the Virtual AC power-cycle operation because the firmware version is not supported. The minimum supported firmware version is '{minimum_supported_firmware_version}'.zCNo changes found to be applied because system is in power ON state.z}The vendor is not supported. The supported vendors are '{supported_vendors}'. Enter the valid vendor and retry the operation.zHSuccessfully performed the full virtual server AC power-cycle operation.zSuccessfully performed the full virtual server AC power-cycle operation. Please wait a few minutes, the server will automatically power on.zhThe target device does not support a {0} operation.The acceptable values for device reset types are {1}.z#{0}OemChassis.ExtendedResetzpThe target device does not support '{0}' operation. The valid values of final power states for device are '{1}'.zLThe vendor is not specified. Enter the valid vendor and retry the operation.z`No reset type is specified for the target device. Enter the valid value and retry the operation.c                 `    | d   }|d   d   }|d   d   }t         j                  |||d       y )N
PowerStatez#ComputerSystem.Resettarget!ResetType@Redfish.AllowableValues)	power_uriallowable_enumscurrent_state)powerstate_mapupdate)system_res_dataaction_datar   r   r   s        y/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/dellemc/openmanage/plugins/modules/redfish_powerstate.pyfetch_powerstate_detailsr      sG    #L1M34X>I!"9:;^_OOVcdf    c                    |j                  d      }| j                  d   }t        t        |      d       }|j                  d      }|| j	                  t
        d       t        j                  |j                               }d }||j                  |      }|| j	                  t
        d       d }	d }
d }|3|j                  d      }	|j                  d      }
|j                  d      }t        j                  |	|
||d	       y )
Nr   oem_reset_typeOemTmsgskippedr   r   z'FinalPowerState@Redfish.AllowableValues)r   r   r   allowable_power_state)getparamsnextiter	exit_jsonTARGET_DEVICE_NOT_SUPPORTEDOEM_RESET_KEYformat
capitalizer   r   )modulesystem_id_res_dataaction_id_resr   r   current_vendoroem_key_respsub_keysub_oem_keyr   r   allowable_final_power_states               r   fetch_ac_powerstate_detailsr3      s   &**<8M]]#34N$~.5N $$U+L8$G"">#<#<#>?GK"&&w/8$GIO"&OOH-	%//*MN&1oo6_&`#O*E`	bcr   c                 Z   |j                   j                  d      }||v rf| j                  d|      }|j                  }|j                  d      }|r|rt	        ||       y t        |||       y |j                  t        d       y |j                  t        j                  |      d       y )N
reset_typeGETActionsTr   )
r#   r"   invoke_request	json_datar   r3   r&   r'   INVALID_DEVICE_IDr)   )	session_objr+   system_id_resresource_id_listresource_idr5   system_id_res_respr,   r-   s	            r   perform_uri_fetchr@      s    ""<0J(((77}M/99*..y9();]K+F4FV!<dK.55kBDQr   c                 f   	 | j                   j                  d      }d }|r dj                  |j                  |dz   |      }dj                  |j                  |      }|j	                  d|      }|j
                  j                  d      }|r>t        |      dkD  r0|D cg c]  }d|v s|d    }	}|xs |	d   }
t        || |
|	|       y | j                  t        d	
       y c c}w # t        $ r@}|j                  dv r+| j                  t        t        j                  |      d	       |d }~ww xY w)Nr>   z	{0}{1}{2}/z{0}{1}r6   Membersr   z	@odata.idTr   )i  i  r   
error_infofailed)r#   r"   r)   root_urir8   r9   lenr@   r&   r'   r   codejsonload)r+   r;   reset_type_mapr>   static_resource_id_resource
system_urisystem_respsystem_members	system_idr=   r<   errs               r   fetch_power_uri_resourcerS      s9   mm''6&*#*5*<*<[=Q=QSadgSgit*u'__[%9%9>J
!00
C$..229=c.1A5HVs9ZeirZr	+ 6ss7N;KA;NMk6=BRT_`!<dK	  t
  88z!!<(,		#t  E		s6   BC' 	C"(C"/C' 
C' "C' '	D00;D++D0c                 |    ddg}ddg}|||z   |d}d}|j                         D ]  \  }}||v s| |v rd} |S  |S  |S )a8   checks if changes are applicable or not for current system state
        :param current_power_state: Current power state
        :type current_power_state: str
        :param apply_power_state: Required power state
        :type apply_power_state: str
        :return: boolean True if changes is applicable
    On
PoweringOnOffPoweringOff))rU   ForceOn)PushPowerButton)ForceOffForceRestartGracefulRestartGracefulShutdownNmi
PowerCycleFT)items)current_power_stateapply_power_state	on_states
off_statesreset_map_applyis_reset_applicableapply_statesapplicable_statess           r   $is_change_applicable_for_power_staterj      s     |$I'J ''*4clO
  +:+@+@+B '',"&77&*#  r   c                    |j                   j                  d      }| |vrt        j                  d|       }dj	                  |D cg c]  }|j                          c}      }|r&t        j                  |dj	                  |            }n&t        j                  | dj	                  |            }|j                  |d       y y c c}w )Nr5   z[A-Z][^A-Z]* , )optionsupported_oem_reset_type_valuesTr   rF   )
r#   r"   refindalljoinlowerINVALID_RESET_TYPEr)   INVALID_RESET_TYPE_OEMr&   )r5   allowable_enumr+   reset_type_paramres_listwordlw_reset_type	error_msgs           r   is_valid_reset_typer}     s    }}((6'::nj98!D4$**,!DE*11->AZ[I.55ZVZV_V_`nVo 6 qIYt4 (!Ds   Cc                     | j                         |vr9t        j                  | dj                  |            }|j	                  |d       y y )Nrm   Trp   )r*   INVALID_PWR_ERRORr)   rs   r&   )final_pwr_stateallowed_final_pwr_stater+   r|   s       r   is_valid_final_pwr_stater   '  sI    !!#+BB%,,_diiH_>`a	Yt4 Cr   c                     | j                  dd      }|j                  j                  d      }|j                         |j                         k7  r(|j	                  t
        j                  |      d       y y )Nr6   z/redfish/v1/Vendor)supported_vendorsTr   )r8   r9   r"   rt   r&   VENDOR_NOT_SUPPORTEDr)   )redfish_session_objr+   vendorrO   system_vendors        r   is_valid_vendorr   -  si    %44UNKK))--h7M.188=8Ycgh /r   c                     |j                  dt              }|j                  j                  dd      }t	        |      t
        k  r,| j                  t        j                  t
              d       y y )Nr6   FirmwareVersion )"minimum_supported_firmware_versionTr   )	r8   FIRM_VER_URIr9   r"   r   "MINIMUM_SUPPORTED_FIRMWARE_VERSIONr&   UNSUPPORTED_FIRMWARE_MSGr)   )r+   r   respredfish_firmware_versions       r   check_firmware_versionr   4  so    --e\BD#~~112CRH,-1SS5<</Q = S\` 	 	b Tr   c                     i }| j                  d      }| j                  d      }|r|j                         }||d<   |r||d<   |S )Nfinal_power_stater5   FinalPowerState	ResetType)r"   r*   )current_vendor_dictpayloadr   r5   s       r   prepare_payloadr   <  sV    G)--.ABO$((6J)446%4!")Nr   c                 ^   |j                   d   }t        || d       t        |t        d   |       t        d   }t	        ||      }|j
                  du r3|du r|j                  t        d       n|j                  t        d       |du rsd|i}t        d	   }| j                  d
||      }|j                  r#|j                  dj                  |      d       y|j                  dj                  |      d       y|j                  dj                  |j                               d       y)z
    Apply reset type to system
    Keyword arguments:
    redfish_session_obj  -- session handle
    module -- Ansible module obj
    r5   Systemsr   r   Tr   changedFr   r   POSTdataz6Successfully performed the reset type operation '{0}'.z1Unable to perform the reset type operation '{0}'.z"The device is already powered {0}.N)r#   rS   r}   r   rj   
check_moder&   CHANGES_FOUNDNO_CHANGES_FOUNDr8   successr)   rt   )r   r+   apply_reset_typerb   
reset_flagr   r   
reset_resps           r   run_change_power_stater   H  s@    }}\2V%8)D(.9J*KVT(956IK[\JD =!15AT 01";/	(77	PW7X
 "++162B+CT  S !T![![\l!m%*  , 	AHHI\IbIbIdeotur   c                     t         d   }| j                  rA|j                         dk7  r| j                  t               | j                  t
        d       y y )Nr   off)r   Tr   )r   r   rt   r&   INITIAL_DESIRED_STATE_ERRORr   )r+   rb   s     r   power_cycle_check_moder   h  sQ    (9$$&%/!<=]D9 r   c                 X   t        ||        |j                  d   }t        t        |      d       }t	        | ||       ||   }d }d|v r|d   }d }d|v r|d   }||dk(  r|j                  t        d       t        || d       t        |t        d   |       |rt        |t        d	   |       t        |       t        |      }t        d
   }	 | j                  d||      }	|	j                  dk(  rD|r*|j                         dk(  r|j                  t         d       |j                  t"        d       y y # t$        $ rj}
t'        j(                  |
      }|
j*                  dk(  r<|d   d   d   d   dk(  r&|d   d   d   d   }|j                  |d       Y d }
~
y Y d }
~
y Y d }
~
y d }
~
ww xY w)Nr   r5   r   r   Tr   Chassisr   r!   r   r   r      onr   i  errorz@Message.ExtendedInfor   	MessageIdzIDRAC.2.9.PSU507Message)r   r#   r$   r%   r   r&   OPERATION_ERRORrS   r}   r   r   r   r   r8   status_codert   SUCCESS_AC_MSG_ONSUCCESS_AC_MSGr   rJ   rK   rI   )r   r+   r   r.   r   r   r   r   r   r   rR   err_messager|   s                r   run_change_ac_power_cycler   p  s   6#67]]#34N$~.5N'@(8**.|<O11-.AB#3r#9_d;V%8)D(.9J*KVT .AX2Y[ab6"12G{+I
:(77	PW7X
!!S(?#8#8#:d#B  %6 E> )  :iin88s?{734KLQOP[\`rr#G,-DEaHSID99  s?:s   A&D6 6	F)?AF$$F)c                     dddddg dddddd} t        | dd	g
      }	 |j                  d   }|j                  d   }t        |j                        5 }|rt        ||       n&|rt	        ||       n|j                  t        d       d d d        y # 1 sw Y   y xY w# t        $ r:}|j                  t        |      t        j                  |      d       Y d }~y d }~wt        $ r&}|j                  t        |      d       Y d }~y d }~wt        t        t        t        t         t"        f$ r&}|j                  t        |      d       Y d }~y d }~wt$        $ r&}|j                  t        |      d       Y d }~y d }~ww xY w)NFstr)requiredtype)	r[   rY   r\   r]   r^   r_   rU   r`   rZ   )r   r   choicesdict)r>   r5   r   T)r   r5   )argument_specsupports_check_modemutually_exclusiver5   r   r   rD   )r   unreachablerp   )r	   r#   r   r   r   r&   r   r   r   rJ   rK   r
   IOError
ValueErrorr   	TypeErrorr   OSError	Exception)specsr+   r5   r   redfish_objrR   s         r   mainr     sf   $)59#(%#ef (-f=E " <=?F4]]<0
'78V]]# 	D{&{F;)+v>  _d C	D 	D 	D  OSX$))C.NN 9SX488Z9owO 4SXd33 4SXd334sY   3B! 6BB! BB! B! !	F*0CF+D&F2EFF  F__main__)N)8
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESRETURNrJ   rq   sslr   #ansible.module_utils.compat.versionr   Cansible_collections.dellemc.openmanage.plugins.module_utils.redfishr   r	   +ansible.module_utils.six.moves.urllib.errorr
   r   ansible.module_utils.urlsr   r   r   r   rv   r'   r:   r   r   r   r   r   r   ru   r(   r   VENDOR_NOT_SPECIFIEDr   r   r   r3   r@   rS   rj   r}   r   r   r   r   r   r   r   r   __name__ r   r   <module>r      s!   C B5n(T"
H  	  < m K 5 /4 N  o 9 %. "M  d R [J  . G e tfc2R",4
55ib	v@::D4@ zF r   