
    VhJ=                         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mZ d dlmZ d dlmZ d d	lmZmZ d d
lmZ d dlmZ dZdZdZdZdZdZdZdZ G d de      Z d Z!d Z"e#dk(  r e!        yy)    )absolute_importdivisionprint_functiona	  
---
module: ome_session
short_description: Manage OpenManage Enterprise and OpenManage Enterprise modular sessions
version_added: "9.3.0"
description:
  - This module allows you  to create and delete sessions on OpenManage Enterprise and OpenManage Enterprise Modular.
options:
  hostname:
    description:
      - IP address or hostname of the OpenManage Enterprise.
    type: str
  username:
    description:
      - Username of the OpenManage Enterprise. If the username is not provided, then
        the environment variable E(OME_USERNAME) is used.
      - I(username) is required when I(state) is C(present).
    type: str
  password:
    description:
      - Password of the OpenManage Enterprise. If the password is not provided, then
        the environment variable E(OME_PASSWORD) is used.
      - I(password) is required when I(state) is C(present).
    type: str
  port:
    description:
      - Port of the OpenManage Enterprise.
    type: int
    default: 443
  validate_certs:
    description:
     - If C(false), the SSL certificates will not be validated.
     - Configure C(false) only on personally controlled sites where self-signed certificates are used.
    type: bool
    default: true
  ca_path:
    description:
     - The Privacy Enhanced Mail (PEM) file that contains a CA certificate to be used for the validation.
    type: path
  timeout:
    description:
     - The HTTPS socket level timeout in seconds.
    type: int
    default: 30
  state:
    description:
     - The state of the session in OpenManage Enterprise.
     - C(present) creates a session.
     - C(absent) deletes a session.
     - Module will always report changes found to be applied when I(state) is C(present).
    choices: [present, absent]
    type: str
    default: present
  x_auth_token:
    description:
     - Authentication token.
     - I(x_auth_token) is required when I(state) is C(absent).
    type: str
    aliases: ['auth_token']
  session_id:
    description:
     - Session ID of the OpenManage Enterprise.
     - I(session_id) is required when I(state) is C(absent).
    type: str
requirements:
  - "python >= 3.9.6"
author:
  - "Kritika Bhateja (@Kritika-Bhateja-03)"
notes:
    - Run this module from a system that has direct access to Dell OpenManage Enterprise.
    - This module supports IPv4 and IPv6 addresses.
    - This module supports C(check_mode).
    - This module will always report changes found to be applied when I(state) is C(present).
a  
---
- name: Create a session
  dellemc.openmanage.ome_session:
    hostname: 198.162.0.1
    username: username
    password: password
    ca_path: "/path/to/ca_cert.pem"
    state: present

- name: Delete a session
  dellemc.openmanage.ome_session:
    hostname: 198.162.0.1
    ca_path: "/path/to/ca_cert.pem"
    state: absent
    x_auth_token: aed4aa802b748d2f3b31deec00a6b28a
    session_id: 4b48e9ab-809e-4087-b7c4-201a16e0143d

- name: Create a session and execute other modules
  block:
    - name: Create a session
      dellemc.openmanage.ome_session:
        hostname: 198.162.0.1
        username: username
        password: password
        ca_path: "/path/to/ca_cert.pem"
        state: present
        register: authData

    - name: Call ome_user_info module
      dellemc.openmanage.ome_user_info:
        hostname: 198.162.0.1
        ca_path: "/path/to/ca_cert.pem"
        x_auth_token: "{{ authData.x_auth_token }}"

    - name: Call ome_network_vlan_info module
      dellemc.openmanage.ome_network_vlan_info:
        hostname: 198.162.0.1
        ca_path: "/path/to/ca_cert.pem"
        x_auth_token: "{{ authData.x_auth_token }}"
  always:
    - name: Destroy a session
      dellemc.openmanage.ome_session:
        hostname: 198.162.0.1
        ca_path: "/path/to/ca_cert.pem"
        state: absent
        x_auth_token: "{{ authData.x_auth_token }}"
        session_id: "{{ authData.session_data.Id }}"
a  
---
msg:
    description: Status of the session operation.
    returned: always
    type: str
    sample: "The session has been created successfully."
session_data:
    description: The session details.
    returned: For session creation operation
    type: dict
    sample: {
        "Id": "d5c28d8e-1084-4055-9c01-e1051cfee2dd",
        "Description": "admin",
        "Name": "API",
        "UserName": "admin",
        "UserId": 10078,
        "Password": null,
        "Roles": [
            "BACKUP_ADMINISTRATOR"
        ],
        "IpAddress": "100.198.162.0",
        "StartTimeStamp": "2023-07-03 07:22:43.683",
        "LastAccessedTimeStamp": "2023-07-03 07:22:43.683",
        "DirectoryGroup": []
            }
x_auth_token:
    description: Authentication token.
    returned: For session creation operation
    type: str
    sample: "d15f17f01cd627c30173b1582642497d"
error_info:
    description: Details of the HTTP Error.
    returned: On HTTP error
    type: dict
    sample: {
        "error": {
            "@Message.ExtendedInfo": [
                {
                    "Message": "Unable to complete the operation because an invalid username and/or password is entered, and therefore authentication failed.",
                    "MessageArgs": [],
                    "MessageArgs@odata.count": 0,
                    "MessageId": "IDRAC.2.7.SYS415",
                    "RelatedProperties": [],
                    "RelatedProperties@odata.count": 0,
                    "Resolution": "Enter valid user name and password and retry the operation.",
                    "Severity": "Warning"
                }
            ],
            "code": "Base.1.12.GeneralError",
            "message": "A general error has occurred. See ExtendedInfo for more information"
        }
    }
N)	HTTPErrorURLError)Session)AnsibleModule)ConnectionErrorSSLValidationErrorenv_fallback)
remove_keyz/api/SessionService/Sessions	@odata.idz(.*?)@odataz*The session has been created successfully.z*The session has been deleted successfully.z"Unable to '{operation}' a session.zChanges found to be applied.zNo changes found to be applied.c                   0     e Zd Z fdZd Zd Zd Z xZS )
OMESessionc                     t         |   |       d| j                  j                  j	                  d      | j                  j                  j	                  d      d| _        y )NTusernamepassword)force_basic_authurl_usernameurl_password)super__init__moduleparamsget
url_kwrags)selfr   	__class__s     r/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/dellemc/openmanage/plugins/modules/ome_session.pyr   zOMESession.__init__   sM     /3+/;;+=+=+A+A*+M+/;;+=+=+A+A*+MO    c                     | j                   j                  t        d      }|j                  }|d   D cg c]  }|d   j	                  d      d    }}|v }|S c c}w )ae  
        Retrieves the status of a session given its URL and ID.

        Args:
            session_url (str): The URL of the session.
            session_id (str): The ID of the session.

        Returns:
            int: The status code of the session status response. If an HTTPError occurs, the status
            code of the error is returned.
        GETvaluer   '   )instanceinvoke_requestSESSION_URL	json_datasplit)r   session_url
session_idsession_status_responsesessions_datasession_idssession_statuss          r    get_session_statuszOMESession.get_session_status   sj     #'--">">{E"R/99O\]dOefz+.44S9!<ff#{2 gs   Ac                    | j                   j                  j                  d      | j                   j                  j                  d      d}| j                   j                  r!| j                   j	                  t
        d       | j                  j                  t        d|| j                        }|j                  }|dk(  r\|j                  }t        |t        	      }|j                  j                  d
      }| j                   j	                  t        d||       y| j                   j	                  t         j#                  d      d       y)a5  
        Executes the session creation process.

        This function creates a session by sending a POST request to the session URL with the
        provided username and password.
        If the request is successful (status code 201), it retrieves the session details, removes
        any OData keys from the response,
        and extracts the X-Auth-Token from the response headers. It then exits the module with a
        success message, indicating that
        the session was created successfully, and provides the session data and X-Auth-Token as
        output variables.

        If the request fails (status code other than 201), it exits the module with a failure
        message, indicating that the session creation failed.

        Parameters:
            None

        Returns:
            None
        r   r   )UserNamePasswordTmsgchangedPOST)data
url_kwargs   regex_patternzX-Auth-Token)r7   r8   session_datax_auth_tokencreate	operationr7   failedN)r   r   r   
check_mode	exit_jsonCHANGES_FOUND_MSGr'   r(   r)   r   status_coder*   r   ODATA_REGEXheadersCREATE_SUCCESS_MSGFAILURE_MSGformat)r   payloadsession_responsestatussession_detailsr?   r@   s          r    create_sessionzOMESession.create_session   s   ,  ${{1155jA#{{1155jAC;;!!KK!!&7!F==77VRYfjfufu7v!--S=.88O%o[QL+3377GLKK!!&8*./;/; " =
 KK!!k&8&88&8&LUY!Zr!   c                    | j                   j                  j                  d      }| j                  t        |      }| j                   j
                  rE|r"| j                   j                  t        d       y| j                   j                  t               y|r`	 t        dz   |z   dz   }| j                  j                  |d      }|j                  }|dk(  r"| j                   j                  t        d       yy| j                   j                  t               y# t        $ r`}t        t        j                   |      t"        	      }| j                   j                  t$        j'                  d
      |d       Y d}~yd}~ww xY w)a  
        Executes the deletion of a session.
        This function retrieves the session ID from the module parameters.It then invokes a
        DELETE request to the session URL with the session ID appended. The response from
        the request is stored in the `session_response` variable.

        If the response status code is 200, indicating a successful deletion, the function exits
        the module with a success message and sets the `changed` parameter to True. Otherwise, it
        exits the module with a failure message and sets the `failed` parameter to True.

        Parameters:
            None

        Returns:
            None
        r-   Tr6   )r7   z('z')DELETE   r=   deleterB   r7   
error_inforE   N)r   r   r   r2   r)   rF   rG   rH   NO_CHANGES_FOUND_MSGr'   r(   rI   DELETE_SUCCESS_MSGr   r   jsonloadrJ   rM   rN   )r   r-   r1   delete_session_urlrP   rQ   err
filter_errs           r    delete_sessionzOMESession.delete_session  sC   " [[''++L9
00jI;;!!%%*;T%J%%*>%?
7)4t);j)H4)O&'+}}'C'CDVX`'a$-99F}--2Dd-S % %%*>%? ! 7!+DIIcN+!VJKK))k.@.@8.@.T5?15 * 7 77s   AD 	F#AE>>F)__name__
__module____qualname__r   r2   rS   ra   __classcell__)r   s   @r    r   r      s    O$%[N&@r!   r   c                     t               } t        | g dg dgd      }	 t        |      }|j                  j	                  d      }|dk(  r|j                          y	|j                          y	# t        $ r]}i }t        |t              r$t        t        j                  |      t              }|j                  t        |      |d       Y d	}~y	d	}~wt         $ r&}|j                  t        |      d
       Y d	}~y	d	}~wt"        t$        t&        t(        t*        f$ r&}|j                  t        |      d       Y d	}~y	d	}~ww xY w)a  
    Main function that initializes the Ansible module with the argument specs and required if
    conditions.
    It then creates a SessionAPI object with the module parameters and performs a session operation
    based on the state parameter.
    If the state is "present", it creates a CreateSession object and executes it. If the state is
    "absent", it creates a DeleteSession object and executes it.
    The session status is returned.

    Raises:
        HTTPError: If an HTTP error occurs, the error message and filtered error information are
        returned in the module's exit_json.
        URLError: If a URL error occurs, the error message is returned in the module's exit_json.
        SSLValidationError, ConnectionError, TypeError, ValueError, OSError: If any other error
        occurs, the error message is returned in the module's exit_json.

    Returns:
        None
    )statepresent)r   r   )rg   absent)r@   r-   T)argument_specrequired_ifsupports_check_moderg   rh   r=   rX   N)r7   unreachablerD   )get_argument_specr	   r   r   r   rS   ra   r   
isinstancedictr   r\   r]   rJ   rG   strr   r   r
   	TypeError
ValueErrorOSError)specsr   omesession_operationr_   r`   s         r    mainrx   B  s   ( E;@
 !F4 "MM--g6	)   K
c4 #DIIcN+NJSX*TJJ 9SX488JP 4SXd334s6   ;A- A- -	E6ACEC;;!ED==Ec                  |    ddidt         dgfdddt         dgfddd	d
ddd
ddd
ddd
ddddgddddgdddid
S )a  
    Returns a dictionary representing the argument specification for a module.

    The dictionary contains the following keys and their corresponding values:
    - "hostname": A string representing the hostname.
    - "username": A string representing the username. It has a fallback option to retrieve the
    value from the environment variable 'IDRAC_USERNAME'.
    - "password": A string representing the password. It is marked as not to be logged and has a
    fallback option to retrieve the value from the environment variable 'IDRAC_PASSWORD'.
    - "port": An integer representing the port number. The default value is 443.
    - "validate_certs": A boolean representing whether to validate certificates. The default value
    is True.
    - "ca_path": A path representing the certificate authority path. The default value is None.
    - "timeout": An integer representing the timeout value. The default value is 30.
    - "state": A string representing the state. The default value is "present". The choices are
    ["present", "absent"].
    - "x_auth_token": A string representing the authentication token. It is marked as not to be
    logged.
    - "session_id": A string representing the session ID.

    Returns:
        A dictionary representing the argument specification.
    typerq   OME_USERNAME)rz   fallbackTOME_PASSWORD)rz   no_logr|   inti  )rz   defaultboolpathN   rh   ri   )rz   r   choices
auth_token)rz   r~   aliases)
hostnamer   r   portvalidate_certsca_pathtimeoutrg   r@   r-   r    r!   r    rn   rn   q  sz    2 UO"?O0PQ"dP^O_@`a3/#)d;"t4!b1I9hBWX!&$L>Ruo r!   __main__)$
__future__r   r   r   rz   __metaclass__DOCUMENTATIONEXAMPLESRETURNr\   urllib.errorr   r   Iansible_collections.dellemc.openmanage.plugins.module_utils.session_utilsr   ansible.module_utils.basicr	   ansible.module_utils.urlsr
   r   &ansible.module_utils.common.parametersr   Aansible_collections.dellemc.openmanage.plugins.module_utils.utilsr   r)   ODATArJ   rL   r[   rM   rH   rZ   r   rx   rn   rb   r   r!   r    <module>r      s    C BIV0d5
p  , ] 4 I ? X,A A 22 8 f@ f@R,4^#L zF r!   