
    Vh7%                         d dl mZmZmZ eZdZdZdZd dl	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mZ d
dddddZdddddZg dZd Zd Zd Zd Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functiona  
---
module: ome_powerstate
short_description: Performs the power management operations on OpenManage Enterprise
version_added: "2.1.0"
description: This module performs the supported power management operations on OpenManage Enterprise.
extends_documentation_fragment:
  - dellemc.openmanage.ome_auth_options
options:
  power_state:
    description: Desired end power state.
    type: str
    required: true
    choices: ['on', 'off', 'coldboot', 'warmboot', 'shutdown']
  device_service_tag:
    description:
      - Targeted device service tag.
      - I(device_service_tag) is mutually exclusive with I(device_id).
    type: str
  device_id:
    description:
      - Targeted device id.
      - I(device_id) is mutually exclusive with I(device_service_tag).
    type: int
requirements:
    - "python >= 3.9.6"
author: "Felix Stephen (@felixs88)"
notes:
    - Run this module from a system that has direct access to Dell OpenManage Enterprise.
    - This module supports C(check_mode).
a)  
---
- name: Power state operation based on device id
  dellemc.openmanage.ome_powerstate:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    device_id: 11111
    power_state: "off"

- name: Power state operation based on device service tag
  dellemc.openmanage.ome_powerstate:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    device_service_tag: "KLBR111"
    power_state: "on"

- name: Power state operation based on list of device ids
  dellemc.openmanage.ome_powerstate:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    device_id: "{{ item.device_id }}"
    power_state: "{{ item.state }}"
  with_items:
    - { "device_id": 11111, "state": "on" }
    - { "device_id": 22222, "state": "off" }

- name: Power state operation based on list of device service tags
  dellemc.openmanage.ome_powerstate:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    device_service_tag: "{{ item.service_tag }}"
    power_state: "{{ item.state }}"
  with_items:
    - { "service_tag": "KLBR111", "state": "on" }
    - { "service_tag": "KLBR222", "state": "off" }
a%  
---
msg:
  type: str
  description: "Overall power state operation job status."
  returned: always
  sample: "Power State operation job submitted successfully."
job_status:
  type: dict
  description: "Power state operation job and progress details from the OME."
  returned: success
  sample: {
    "Builtin": false,
    "CreatedBy": "user",
    "Editable": true,
    "EndTime": null,
    "Id": 11111,
    "JobDescription": "DeviceAction_Task",
    "JobName": "DeviceAction_Task_PowerState",
    "JobStatus": {
      "Id": 1111,
      "Name": "New"
      },
    "JobType": {
      "Id": 1,
      "Internal": false,
      "Name": "DeviceAction_Task"
      },
    "LastRun": "2019-04-01 06:39:02.69",
    "LastRunStatus": {
      "Id": 1112,
      "Name": "Running"
      },
    "NextRun": null,
    "Params": [
      {
        "JobId": 11111,
        "Key": "powerState",
        "Value": "2"
      },
      {
        "JobId": 11111,
        "Key": "operationName",
        "Value": "POWER_CONTROL"
      }
    ],
    "Schedule": "",
    "StartTime": null,
    "State": "Enabled",
    "Targets": [
      {
        "Data": "",
        "Id": 11112,
        "JobId": 11111,
        "TargetType": {
          "Id": 1000,
          "Name": "DEVICE"
        }
      }
    ],
    "UpdatedBy": null,
    "Visible": true
  }
N)SSLError)RestOMEOmeAnsibleModule)URLError	HTTPError)ConnectionErrorSSLValidationError         
      onoffcoldbootwarmbootshutdown            )r   r   
poweringonpoweringoff)r   r   r   c                 l    di }}| j                  d||      }|j                  dk(  r|j                  }|S )z1Spawns an update job and tracks it to completion.zJobService/JobsPOST)data   )invoke_requeststatus_code	json_data)rest_objpayloadjob_urijob_detailsjob_resps        u/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/dellemc/openmanage/plugins/modules/ome_powerstate.pyspawn_update_jobr+      sA    ,b[G&&vwW&EHs"((    c                 f    dddddddddd	d
dt        |      d
gt        |       d|dddgd}|S )z'Build the payload for requested device.r   DeviceAction_Task_PowerStateDeviceAction_TaskstartnowEnabled   )IdNameoperationNamePOWER_CONTROL)KeyValue
powerState DEVICE)r3   Data
TargetType)r3   JobNameJobDescriptionScheduleStateJobTypeParamsTargets)strint)	device_iddevice_typevalid_optionr&   s       r*   build_power_state_payloadrJ      sb     1-%89*_E'#l2CDFy>2*5x#HJ KG Nr,   c                     d\  }}}|d   D ].  }|d   t        |      k(  s|j                  dd      }|d   }d} n |r!| j                  dj                  |      	       |d
vr| j                  d	       ||fS )z4Get the current state and device type from response.)NNTreport_listr3   
PowerStateNTypeFzWUnable to complete the operation because the entered target device id '{0}' is invalid.msg)i  i  zXUnable to complete the operation because power state supports device type 1000 and 2000.)rF   get	fail_jsonformat)moduleresprG   current_staterH   invalid_devicedevices          r*   get_device_staterY      s    1A.M;}% $<3y>)"JJ|T:M .K"N  <<BF9<M 	 	O,& J 	K+%%r,   c                    | j                   d   }| j                   d   }| j                   d   }|j                  d      }|d   rr|pt        |d   D cg c]-  }|j                  d      t	        |j                  d            f/ c}      }||v r||   }n!| j                  dj                  |      	       t        | ||      \  }}	t        |   d
}}
|t        v r|t        d   k7  rd}n8|
|k(  s1|dk(  r|t        d   t        d   fv s|dv r|t        d   t        d   fv rd}| j                  r|r| j                  d	       n!| j                  r|s| j                  dd       t        ||	|
      }|S c c}w )z9Getting the device id filtered from the device inventory.power_staterG   device_service_tagzDeviceService/DevicesrL   DeviceServiceTagr3   z`Unable to complete the operation because the entered target device service tag '{0}' is invalid.rO   Fr   Tr   )r   r   r   r   zNo changes found to commit.zChanges found to commit.)rP   changed)paramsget_all_report_detailsdictrQ   rE   rR   rS   rY   VALID_OPERATIONNOT_APPLICABLE_OPTIONSPOWER_STATE_MAP
check_mode	exit_jsonrJ   )rT   r%   r[   rG   service_tag	resp_datarX   device_resprV   rH   rI   valid_operationr&   s                r*   get_device_resourcerk      s   --.Kk*I-- 45K//0GHIK$;bklybz{X^VZZ(:;SDAQ=RS{|+%#K0I "IIOP[I\  ^!1&)Y!OM; %4K$@%/L,,/RVBW1W
-
'D ]t7Lo^jNk6l%l//u5}7UVV_:;			?7F'	;MGN/ |s   2E1c            	         ddg ddddddddd} t        | d	d
ggd	d
ggd      }	 |j                  d
   !|j                  d	   |j                  d       i }t        |j                  d      5 }t	        ||      }t        ||      }d d d        |j#                  dd       y # 1 sw Y   xY w# t        $ r9}|j                  t        |      t        j                  |             Y d }~^d }~wt        t        t        t        t        t        t         f$ r%}|j                  t        |             Y d }~d }~ww xY w)NTrE   r   )requiredtypechoicesF)rm   rn   rF   )r[   r\   rG   r\   rG   )argument_specrequired_one_ofmutually_exclusivesupports_check_modez?device_id and device_service_tag attributes should not be None.rO   )req_session)rP   
job_statusz1Power State operation job submitted successfully.)rP   ru   r^   )r   r_   rR   r   rk   r+   r
   rE   jsonloadr	   r   r   	TypeError
ValueErrorr   OSErrorrf   )specsrT   ru   r%   r&   errs         r*   mainr}      sJ   $(%#TV+0%@"'7	E .<=1;?@ 	F
'==%-&--@T2U2]!bc
V]]5 	=)&(;G)(G<J	= L *D  :	= 	=  BSX$))C.AA(/9jRZ\cd 'SX&&'s<   A	B4 2B(B4 (B1-B4 4	E=/C11+ED<<E__main__)
__future__r   r   r   rn   __metaclass__DOCUMENTATIONEXAMPLESRETURNrv   sslr   ?ansible_collections.dellemc.openmanage.plugins.module_utils.omer   r   +ansible.module_utils.six.moves.urllib.errorr	   r
   ansible.module_utils.urlsr   r   rb   rd   rc   r+   rJ   rY   rk   r}   __name__ r,   r*   <module>r      s    C B@+Z?
B   e K I21"RSTBbL= "&$B:: zF r,   