
    Vhh                     v   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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(dZ)dZ*dZ+dZ,d d!d"d#d$d%d&d'd(d)d*d+d,Z-d- Z.d?d.Z/d/ Z0d0 Z1d1 Z2d2 Z3d3 Z4d4 Z5d5 Z6d6 Z7d7 Z8d8 Z9d9 Z:d@d:Z;d; Z<d< Z=d= Z>e?d>k(  r e>        yy)A    )absolute_importdivisionprint_functiona4  
---
module: ome_discovery
short_description: Create, modify, or delete a discovery job on OpenManage Enterprise
version_added: "3.3.0"
description: This module allows to create, modify, or delete a discovery job.
extends_documentation_fragment:
  - dellemc.openmanage.oment_auth_options
options:
  state:
    description:
      - C(present) creates a discovery job or modifies an existing discovery job.
      - I(discovery_job_name) is mandatory for the creation of a new discovery job.
      - If multiple discoveries of the same I(discovery_job_name) exist, then the new discovery job will not be created.
      - C(absent) deletes an existing discovery job(s) with the specified I(discovery_job_name).
    choices: [present, absent]
    default: present
    type: str
  discovery_job_name:
    description:
      - Name of the discovery configuration job.
      - It is mutually exclusive with I(discovery_id).
    type: str
  discovery_id:
    description:
      - ID of the discovery configuration group.
      - This value is DiscoveryConfigGroupId in the return values under discovery_status.
      - It is mutually exclusive with I(discovery_job_name).
    type: int
  new_name:
    description: New name of the discovery configuration job.
    type: str
  schedule:
    description:
      - Provides the option to schedule the discovery job.
      - If C(RunLater) is selected, then I(cron) must be specified.
    choices: [RunNow, RunLater]
    default: RunNow
    type: str
  cron:
    description:
      - Provide a cron expression based on Quartz cron format.
    type: str
  trap_destination:
    description:
      - Enable OpenManage Enterprise to receive the incoming SNMP traps from the discovered devices.
      - This is effective only for servers discovered by using their iDRAC interface.
    type: bool
    default: false
  community_string:
    description: "Enable the use of SNMP community strings to receive SNMP traps using Application Settings in
    OpenManage Enterprise. This option is available only for the discovered iDRAC servers and MX7000 chassis."
    type: bool
    default: false
  email_recipient:
    description: "Enter the email address to which notifications are to be sent about the discovery job status.
    Configure the SMTP settings to allow sending notifications to an email address."
    type: str
  job_wait:
    description:
      - Provides the option to wait for job completion.
      - This option is applicable when I(state) is C(present).
    type: bool
    default: true
  job_wait_timeout:
    description:
      - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
      - This option is applicable when I(job_wait) is C(true).
    type: int
    default: 10800
  ignore_partial_failure:
    description:
      - "Provides the option to ignore partial failures. Partial failures occur when there is a combination of both
      discovered and undiscovered IPs."
      - If C(false), then the partial failure is not ignored, and the module will error out.
      - If C(true), then the partial failure is ignored.
      - This option is only applicable if I(job_wait) is C(true).
    type: bool
    default: false
  discovery_config_targets:
    description:
      - Provide the list of discovery targets.
      - "Each discovery target is a set of I(network_address_detail), I(device_types), and one or more protocol
      credentials."
      - This is mandatory when I(state) is C(present).
      - "C(WARNING) Modification of this field is not supported, this field is overwritten every time. Ensure to provide
      all the required details for this field."
    type: list
    elements: dict
    suboptions:
      network_address_detail:
        description:
          - "Provide the list of IP addresses, host names, or the range of IP addresses of the devices to be discovered
          or included."
          - "Sample Valid IP Range Formats"
          - "   192.35.0.0"
          - "   192.36.0.0-10.36.0.255"
          - "   192.37.0.0/24"
          - "   2345:f2b1:f083:135::5500/118"
          - "   2345:f2b1:f083:135::a500-2607:f2b1:f083:135::a600"
          - "   hostname.domain.tld"
          - "   hostname"
          - "   2345:f2b1:f083:139::22a"
          - "Sample Invalid IP Range Formats"
          - "   192.35.0.*"
          - "   192.36.0.0-255"
          - "   192.35.0.0/255.255.255.0"
          - C(NOTE) The range size for the number of IP addresses is limited to 16,385 (0x4001).
          - C(NOTE) Both IPv6 and IPv6 CIDR formats are supported.
        type: list
        elements: str
        required: true
      device_types:
        description:
          - Provide the type of devices to be discovered.
          - The accepted types are SERVER, CHASSIS, NETWORK SWITCH, and STORAGE.
          - A combination or all of the above can be provided.
          - "Supported protocols for each device type are:"
          - SERVER - I(wsman), I(redfish), I(snmp), I(ipmi), I(ssh), and I(vmware).
          - CHASSIS - I(wsman), and I(redfish).
          - NETWORK SWITCH - I(snmp).
          - STORAGE - I(storage), and I(snmp).
        type: list
        elements: str
        required: true
      wsman:
        description: Web Services-Management (WS-Man).
        type: dict
        suboptions:
          username:
            description: Provide a username for the protocol.
            type: str
            required: true
          password:
            description: Provide a password for the protocol.
            type: str
            required: true
          domain:
            description: Provide a domain for the protocol.
            type: str
          port:
            description: Enter the port number that the job must use to discover the devices.
            type: int
            default: 443
          retries:
            description: Enter the number of repeated attempts required to discover a device.
            type: int
            default: 3
          timeout:
            description: Enter the time in seconds after which a job must stop running.
            type: int
            default: 60
          cn_check:
            description: Enable the Common Name (CN) check.
            type: bool
            default: false
          ca_check:
            description: Enable the Certificate Authority (CA) check.
            type: bool
            default: false
          certificate_data:
            description: Provide certificate data for the CA check.
            type: str
      redfish:
        description: REDFISH protocol.
        type: dict
        suboptions:
          username:
            description: Provide a username for the protocol.
            type: str
            required: true
          password:
            description: Provide a password for the protocol.
            type: str
            required: true
          domain:
            description: Provide a domain for the protocol.
            type: str
          port:
            description: Enter the port number that the job must use to discover the devices.
            type: int
            default: 443
          retries:
            description: Enter the number of repeated attempts required to discover a device.
            type: int
            default: 3
          timeout:
            description: Enter the time in seconds after which a job must stop running.
            type: int
            default: 60
          cn_check:
            description: Enable the Common Name (CN) check.
            type: bool
            default: false
          ca_check:
            description: Enable the Certificate Authority (CA) check.
            type: bool
            default: false
          certificate_data:
            description: Provide certificate data for the CA check.
            type: str
      snmp:
        description: Simple Network Management Protocol (SNMP).
        type: dict
        suboptions:
          community:
            description: Community string for the SNMP protocol.
            type: str
            required: true
          port:
            description: Enter the port number that the job must use to discover the devices.
            type: int
            default: 161
          retries:
            description: Enter the number of repeated attempts required to discover a device.
            type: int
            default: 3
          timeout:
            description: Enter the time in seconds after which a job must stop running.
            type: int
            default: 3
      storage:
        description: HTTPS Storage protocol.
        type: dict
        suboptions:
          username:
            description: Provide a username for the protocol.
            type: str
            required: true
          password:
            description: Provide a password for the protocol.
            type: str
            required: true
          domain:
            description: Provide a domain for the protocol.
            type: str
          port:
            description: Enter the port number that the job must use to discover the devices.
            type: int
            default: 443
          retries:
            description: Enter the number of repeated attempts required to discover a device.
            type: int
            default: 3
          timeout:
            description: Enter the time in seconds after which a job must stop running.
            type: int
            default: 60
          cn_check:
            description: Enable the Common Name (CN) check.
            type: bool
            default: false
          ca_check:
            description: Enable the Certificate Authority (CA) check.
            type: bool
            default: false
          certificate_data:
            description: Provide certificate data for the CA check.
            type: str
      vmware:
        description: VMWARE protocol.
        type: dict
        suboptions:
          username:
            description: Provide a username for the protocol.
            type: str
            required: true
          password:
            description: Provide a password for the protocol.
            type: str
            required: true
          domain:
            description: Provide a domain for the protocol.
            type: str
          port:
            description: Enter the port number that the job must use to discover the devices.
            type: int
            default: 443
          retries:
            description: Enter the number of repeated attempts required to discover a device.
            type: int
            default: 3
          timeout:
            description: Enter the time in seconds after which a job must stop running.
            type: int
            default: 60
          cn_check:
            description: Enable the Common Name (CN) check.
            type: bool
            default: false
          ca_check:
            description: Enable the Certificate Authority (CA) check.
            type: bool
            default: false
          certificate_data:
            description: Provide certificate data for the CA check.
            type: str
      ssh:
        description: Secure Shell (SSH).
        type: dict
        suboptions:
          username:
            description: Provide a username for the protocol.
            type: str
            required: true
          password:
            description: Provide a password for the protocol.
            type: str
            required: true
          port:
            description: Enter the port number that the job must use to discover the devices.
            type: int
            default: 22
          retries:
            description: Enter the number of repeated attempts required to discover a device.
            type: int
            default: 3
          timeout:
            description: Enter the time in seconds after which a job must stop running.
            type: int
            default: 60
          check_known_hosts:
            description: Verify the known host key.
            type: bool
            default: false
          is_sudo_user:
            description: Use the SUDO option.
            type: bool
            default: false
      ipmi:
        description: Intelligent Platform Management Interface (IPMI)
        type: dict
        suboptions:
          username:
            description: Provide a username for the protocol.
            type: str
            required: true
          password:
            description: Provide a password for the protocol.
            type: str
            required: true
          retries:
            description: Enter the number of repeated attempts required to discover a device.
            type: int
            default: 3
          timeout:
            description: Enter the time in seconds after which a job must stop running.
            type: int
            default: 60
          kgkey:
            description: KgKey for the IPMI protocol.
            type: str
requirements:
    - "python >= 3.9.6"
author:
    - "Jagadeesh N V (@jagadeeshnv)"
    - "Sajna Shetty (@Sajna-Shetty)"
    - "Abhishek Sinha (@Abhishek-Dell)"
notes:
    - Run this module from a system that has direct access to Dell OpenManage Enterprise.
    - This module does not support C(check_mode).
    - If I(state) is C(present), then Idempotency is not supported.
a  
---
- name: Discover servers in a range
  dellemc.openmanage.ome_discovery:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    discovery_job_name: "Discovery_server_1"
    discovery_config_targets:
      - network_address_detail:
          - 192.96.24.1-192.96.24.255
        device_types:
          - SERVER
        wsman:
          username: user
          password: password

- name: Discover chassis in a range
  dellemc.openmanage.ome_discovery:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    discovery_job_name: "Discovery_chassis_1"
    discovery_config_targets:
      - network_address_detail:
          - 192.96.24.1-192.96.24.255
        device_types:
          - CHASSIS
        wsman:
          username: user
          password: password

- name: Discover switches in a range
  dellemc.openmanage.ome_discovery:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    discovery_job_name: "Discover_switch_1"
    discovery_config_targets:
      - network_address_detail:
          - 192.96.24.1-192.96.24.255
        device_types:
          - NETWORK SWITCH
        snmp:
          community: snmp_creds

- name: Discover storage in a range
  dellemc.openmanage.ome_discovery:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    discovery_job_name: "Discover_storage_1"
    discovery_config_targets:
      - network_address_detail:
          - 192.96.24.1-192.96.24.255
        device_types:
          - STORAGE
        storage:
          username: user
          password: password
        snmp:
          community: snmp_creds

- name: Delete a discovery job
  dellemc.openmanage.ome_discovery:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    state: "absent"
    discovery_job_name: "Discovery-123"

- name: Schedule the discovery of multiple devices ignoring partial failure and enable trap to receive alerts
  dellemc.openmanage.ome_discovery:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    state: "present"
    discovery_job_name: "Discovery-123"
    discovery_config_targets:
      - network_address_detail:
          - 192.96.24.1-192.96.24.255
          - 192.96.0.0/24
          - 192.96.26.108
        device_types:
          - SERVER
          - CHASSIS
          - STORAGE
          - NETWORK SWITCH
        wsman:
          username: wsman_user
          password: wsman_pwd
        redfish:
          username: redfish_user
          password: redfish_pwd
        snmp:
          community: snmp_community
      - network_address_detail:
          - 192.96.25.1-192.96.25.255
          - ipmihost
          - esxiserver
          - sshserver
        device_types:
          - SERVER
        ssh:
          username: ssh_user
          password: ssh_pwd
        vmware:
          username: vm_user
          password: vmware_pwd
        ipmi:
          username: ipmi_user
          password: ipmi_pwd
    schedule: RunLater
    cron: "0 0 9 ? * MON,WED,FRI *"
    ignore_partial_failure: true
    trap_destination: true
    community_string: true
    email_recipient: test_email@company.com

- name: Discover servers with ca check enabled
  dellemc.openmanage.ome_discovery:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    discovery_job_name: "Discovery_server_ca1"
    discovery_config_targets:
      - network_address_detail:
          - 192.96.24.108
        device_types:
          - SERVER
        wsman:
          username: user
          password: password
          ca_check: true
          certificate_data: "{{ lookup('ansible.builtin.file', '/path/to/certificate_data_file') }}"

- name: Discover chassis with ca check enabled data
  dellemc.openmanage.ome_discovery:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    discovery_job_name: "Discovery_chassis_ca1"
    discovery_config_targets:
      - network_address_detail:
          - 192.96.24.108
        device_types:
          - CHASSIS
        redfish:
          username: user
          password: password
          ca_check: true
          certificate_data: "-----BEGIN CERTIFICATE-----\r\n
          ABCDEFGHIJKLMNOPQRSTUVWXYZaqwertyuiopasdfghjklzxcvbnmasdasagasvv\r\n
          ABCDEFGHIJKLMNOPQRSTUVWXYZaqwertyuiopasdfghjklzxcvbnmasdasagasvv\r\n
          ABCDEFGHIJKLMNOPQRSTUVWXYZaqwertyuiopasdfghjklzxcvbnmasdasagasvv\r\n
          aqwertyuiopasdfghjklzxcvbnmasdasagasvv=\r\n
          -----END CERTIFICATE-----"
a
  
---
msg:
  description: Overall status of the discovery operation.
  returned: always
  type: str
  sample: "Successfully deleted 1 discovery job(s)."
discovery_status:
  description:
    - Details of the discovery job created or modified.
    - If I(job_wait) is true, Completed and Failed IPs are also listed.
  returned: when I(state) is C(present)
  type: dict
  sample: {
    "Completed": [
      "192.168.24.17",
      "192.168.24.20",
      "192.168.24.22"
    ],
    "Failed": [
      "192.168.24.15",
      "192.168.24.16",
      "192.168.24.18",
      "192.168.24.19",
      "192.168.24.21",
      "host123"
    ],
    "DiscoveredDevicesByType": [
      {
        "Count": 3,
        "DeviceType": "SERVER"
      }
    ],
    "DiscoveryConfigDiscoveredDeviceCount": 3,
    "DiscoveryConfigEmailRecipient": "myemail@dell.com",
    "DiscoveryConfigExpectedDeviceCount": 9,
    "DiscoveryConfigGroupId": 125,
    "JobDescription": "D1",
    "JobEnabled": true,
    "JobEndTime": "2021-01-01 06:27:29.99",
    "JobId": 12666,
    "JobName": "D1",
    "JobNextRun": null,
    "JobProgress": "100",
    "JobSchedule": "startnow",
    "JobStartTime": "2021-01-01 06:24:10.071",
    "JobStatusId": 2090,
    "LastUpdateTime": "2021-01-01 06:27:30.001",
    "UpdatedBy": "admin"
  }
discovery_ids:
  description: IDs of the discoveries with duplicate names.
  returned: when discoveries with duplicate name exist for I(state) is C(present)
  type: list
  sample: [1234, 5678]
job_detailed_status:
  description: Detailed last execution history of a job.
  returned: All time.
  type: list
  sample: [
        {
            "ElapsedTime": "00:00:00",
            "EndTime": null,
            "ExecutionHistoryId": 564873,
            "Id": 656893,
            "IdBaseEntity": 0,
            "JobStatus": {
                "Id": 2050,
                "Name": "Running"
            },
            "Key": "192.96.24.1",
            "Progress": "0",
            "StartTime": "2023-07-04 06:23:54.008",
            "Value": "Running\nDiscovery of target 192.96.24.1 started.\nDiscovery target resolved to IP  192.96.24.1 ."
        }
    ]
error_info:
  description: Details of the HTTP Error.
  returned: on HTTP error
  type: dict
  sample: {
    "error": {
      "code": "Base.1.0.GeneralError",
      "message": "A general error has occurred. See ExtendedInfo for more information.",
      "@Message.ExtendedInfo": [
        {
          "MessageId": "GEN1234",
          "RelatedProperties": [],
          "Message": "Unable to process the request because an error occurred.",
          "MessageArgs": [],
          "Severity": "Critical",
          "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
        }
      ]
    }
  }
N)RestOMEOmeAnsibleModule)strip_substr_dict)ConnectionErrorSSLValidationError)URLError	HTTPError)snake_dict_to_camel_dictz,DiscoveryConfigService/DiscoveryConfigGroupszDiscoveryConfigService/JobszJDiscoveryConfigService/Actions/DiscoveryConfigService.RemoveDiscoveryGroupz+DiscoveryConfigService/ProtocolToDeviceTypez,JobService/Jobs({job_id})/ExecutionHistoriesz8DiscoveryConfigService/DiscoveryConfigGroups({group_id})zNo changes found to be applied.zRDiscovery job '{name}' with ID {id} is running. Please retry after job completion.z*Successfully deleted {n} discovery job(s).zDMultiple discoveries present. Run the job again using a specific ID.z)Successfully scheduled the Discovery job.z)Successfully completed the Discovery job.zDiscovery job has {0}.z+No devices discovered, job is in {0} state.z,Unable to track discovery job status of {0}.z5Discovery job {0} incomplete after polling {1} times.z!Invalid device types found - {0}.zSome IPs are not discovered.z/Protocol not applicable for given device types.zInvalid discovery ID provided.   	ScheduledQueuedStartingRunningzcompleted successfullyFailedzcompleted with errorsNewAbortedPausedStoppedCanceled)  i  i        *  i   4  5  6  7  c                 l   g }| j                   j                  d      }d}| j                   j                  d      }|rd}| j                   j                  d      }|j                  dt        dz         }|j                  j                  d      }|D ]!  }||   |k(  s|j                  |       |s  |S  |S )Ndiscovery_idDiscoveryConfigGroupNamediscovery_job_nameDiscoveryConfigGroupIdGET
?$top=9999value)paramsgetinvoke_requestCONFIG_GROUPS_URI	json_dataappend)	modulerest_objdiscovery_cfgsr#   srch_keysrch_valrespdiscovsds	            t/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/dellemc/openmanage/plugins/modules/ome_discovery.pycheck_existing_discoveryr9     s    N==$$^4L)H}}  !56H+==$$^4""5*;l*JKDnn  )G X;("!!!$
     c                     | j                  dt              }|j                  j                  d      }t	        |D cg c]  }|d   ||   f c}      }|S c c}w )Nr'   r)   r&   )r,   DISCOVERY_JOBS_URIr.   r+   dict)r1   keyr5   	disc_jobsitemjob_state_dicts         r8   get_discovery_statesrB     sZ    ""5*<=D""7+IS\]4D!9:DIF]^N ^s   Ac                    i }i }| j                  dt              }|j                  j                  d      }|D ]M  }|d   }|j                  |g       }|j	                  |d          |||<   |d   ||<   |dk(  sA||d<   |d   |d<   O ||fS )Nr'   r)   DeviceTypeNameProtocolNameDeviceTypeIdzDELL STORAGESTORAGE)r,   PROTOCOL_DEVICEr.   r+   r/   )r1   prot_dev_map
dev_id_mapr5   prot_devr@   dnamedlists           r8   get_protocol_device_maprN     s    LJ""5/:D~~!!'*H 9%&  +T.)*#U 0
5N"&+L#$($8Jy!9 ##r:   c                     ddddd}i }|j                         D ]?  \  }}| j                  j                  |      "| j                  j                  |      ||<   A |S )Nr$   TrapDestinationCommunityStringDiscoveryStatusEmailRecipient)r%   trap_destinationcommunity_stringemail_recipient)itemsr*   r+   )r0   
trans_dict
other_dictr>   vals        r8   get_other_discovery_payloadrZ     sn    (B&7&7%DFJ J$$& 5S==S!-$mm//4JsO5 r:   c                     i }| j                   j                  d      }|r|dk(  rd|d<   d|d<   d|d<   |S d|d<   d|d<   | j                   j                  d      |d<   |S )	NscheduleRunNowTFRunLaterstartnowCroncron)r*   r+   )r0   schedule_payloadr\   s      r8   get_schedulerc     s    }}  ,Hx8+%)"',$#- 
  &+"'+$#)==#4#4V#< r:   c                    	 g g d}g }| j                  dt        j                  |            }|j                  j	                  d      }t        d |D              }t        |j                               }t        j                  |      dj                  ||d            z   }| j                  |      }	|	j	                  d      D ]  }
t        |
      }
|
j	                  di       j                  d	d        |j                  |
       |
j	                  di       j	                  d
d      }|j	                  |g       }|j                  |
j	                  d             |||<    	 ||fS # t        $ r Y fS w xY w)N)	Completedr   r'   job_idr)   c              3   0   K   | ]  }|d    |d   f  yw)	StartTimeIdN .0xs     r8   	<genexpr>z(get_execution_details.<locals>.<genexpr>  s     Ca;41Cs   z({0})/ExecutionHistoryDetails	JobStatusz@odata.typeNameUnknownKey)r,   JOB_EXEC_HISTORYformatr.   r+   r=   sortedkeysget_all_items_with_paginationr   popr/   	Exception)r1   rg   ipsjob_detail_statusr5   ex_histtmp_dictsorted_datesex_urlall_execjb_ip	jobstatusjlists                r8   get_execution_detailsr     sq   "-&&u.>.E.EV.E.TU..$$W-C7CChmmo.!(((7:Y:`:`aijvwyjza{:||99&A\\'* 	#E%e,EIIk2&**=$?$$U+		+r266vyIIGGIr*ELL5)*"C	N	# !!!  !!!s   EE& &	E54E5c                 F   d}||z  }g d}g d}t         dz   j                  |      }d}t        j                  t               ||k  r|dz  }	 | j                  d|      }	|	j                  }
|
d	   }||v rt        j                  t        |         S ||v rt        j                  t        |         S t        j                  |       ||k  rt        j                  ||      S # t        $ r t        j                  |      cY S t        $ r}t        |      cY d }~S d }~ww xY w)
N   )r   r   r   r    r!   )r   r   r   z
({job_id})rf   r      r'   JobStatusId)r<   rv   timesleepSETTLING_TIMEr,   r.   JOB_TRACK_SUCCESSJOB_STATUS_MAPJOB_TRACK_FAILr   JOB_TRACK_UNABLEr{   strJOB_TRACK_INCOMPLETE)r1   rg   job_wait_secsleep_intervalmax_retriesfailed_job_statussuccess_job_statusjob_urlloop_ctrjob_respjob_dict
job_statuserrs                r8   discovery_job_trackingr     s    N.0K6+!L0888GGHJJ}
[
 A	..ug>H))H!-0J//(//z0JKK00%,,^J-GHHJJ~& [
   &&v{;;	  	3#**622 	s8O	s1   AC# C# 2C# #D D 
DD D c                     | d   }t        |      dk(  r|d   j                  d      }|S d}| |   }|j                  dt        dz         }|j                  j                  d      }|D ]  }||   |k(  s|d	   } |S  S )
NDiscoveryConfigTaskParamr   r   TaskIdr&   r'   r(   r)   JobId)lenr+   r,   r<   r.   )	discovery_jsonr1   job_listrg   r3   r4   r5   r6   r7   s	            r8   get_job_datar     s    89H
8}!* M ,!(+&&u.@<.OP..$$W- 	A{h&7M		 Mr:   c           
         d dddd ddddddd ddddd d d dddid dddd}g d	}d
dddd}i }|D ]  }| j                  |      s|j                         ddd}t        | |         |d<   |d   j                  |j                  |i              |||<   |dk(  si|j	                         }d|d<   ||d<    t        |j                               |d<   |S )NFT)certificateDetailisHttp	keepAlive)
enableV1V2enableV3)useKeyr>   knownHostKey
passphrase	privilege   )wsmanredfishsnmpvmwaresshipmistorage)r   r   r   r   r   r   r   r    	DISCOVERY)	profileIdprofileNameprofileDescriptiontypeBasic)r   authTypemodifiedcredentialsr   REDFISHr   r   )r+   upperr   updatecopylistvalues)disc_configproto_add_dict
proto_listconn_profile
creds_dictpxprotorfs           r8   get_connection_profiler   /  s1    "&
 *.TR 		
 )-ERdRVWa !%
+N8 RJ!"2RYdeLJ +??1ggi")"')F %=[^$LF=!M"**>+=+=a+DE"JqMG|[[]&6
(*
9%+ #'z'8'8':";Lr:   c                    g }t        |      \  }| j                  j                  d      }|D ]  }i }t        fd|j                  d      D              |d<   t        t	        |j                  d                  }t        |      t        |d         k7  rYt	        |      t	        j                               z
  }| j                  t        j                  dj                  |                   t        d |d   D              |d	<   t        |      }	t        d
 |	d   D              }
g }|j                  d      D ]%  }|j                  |g       }|j                  |       ' t	        |      t	        |
      z  s| j                  t        |       t        j                  |	      |d<   |j!                  |        |S )Ndiscovery_config_targetsc              3   N   K   | ]  }|j                         v s|     y wN)rx   )rm   devrJ   s     r8   ro   z'get_discovery_config.<locals>.<genexpr>f  s-      &d ##Q[Q`Q`QbJbJsO&ds   %
%device_types
DeviceType,msgc              3   $   K   | ]  }d |i 
 yw)NetworkAddressDetailNrk   )rm   ips     r8   ro   z'get_discovery_config.<locals>.<genexpr>l  s     1SU3I22N1s   network_address_detailDiscoveryConfigTargetsc              3   &   K   | ]	  }|d      yw)r   Nrk   rl   s     r8   ro   z'get_discovery_config.<locals>.<genexpr>n  s     K!AfIK   r   )r   discovery_statusConnectionProfile)rN   r*   r+   r   setr   rx   	fail_jsonINVALID_DEVICESrv   joinr   extendATLEAST_ONE_PROTOCOLjsondumpsr/   )r0   r1   disc_cfg_listproto_dev_mapdiscovery_config_listr   disc_cfgdevicesinvalid_devr   given_protos
req_protosr   proto_dev_valuerJ   s                 @r8   get_discovery_configr   `  s   M 7 AM:"MM--.HI, '!% &d'2~'F&d "ds;??>:;<w<3x566g,Z__->)??K!7!78M!NO-11Yde}Y~1-)*-k:K|M/JKK
??>2 	/C+//R8Oo.	/ J#l"33!5V(,

<(@$%X&%'& r:   c                    | j                  dt        dj                  |      z         }|j                  }t	        |      }|D ]<  }t        |      j                         j                  d      s,|j                  |       > |S )Nr'   z({0})z@odata)	r,   r<   rv   r.   r   r   lower
startswithrz   )r1   rg   r5   djobnlistks         r8   get_discovery_jobr   z  sn    ""5*<w~~f?U*UVD>>DJE q6<<>$$X.HHQK Kr:   c                 4   t         }t        j                  t               t	        ||      }g }| j
                  j                  d      r:| j
                  j                  d      dk(  rt        ||| j
                  d         }|}t        ||      \  }}t	        ||      }|j                  |       |d   dk(  r3| j
                  j                  d      s| j                  t        ||	       |d   dk(  rM| j
                  j                  d      r2| j                  t        j                  t        |d            ||d
       |j                  d      r1| j                  t         j                  t        |d            ||	       | j                  |||d
       y )Njob_waitr\   r]   job_wait_timeout)r   r   r   ignore_partial_failure)r   r   job_detailed_statusT)r   r   r  changedr   )DISCOVERY_SCHEDULEDr   r   r   r   r*   r+   r   r   r   r   DISCOVERY_PARTIAL	exit_jsonr   rv   r   r   )r0   r1   rg   r   r   detailed_jobjob_message
ip_detailss           r8   exit_discoveryr    so   
CJJ}Xv.DL}}$):)::)F()R,XvFMMZlLmn#86#J 
L 62J$&v}}/@/@AY/Z!2T_kl$&6==+<+<=U+V!2!9!9.mI\:]!^qu1=t  M>>(#!6!6~d=FY7Z![nr1=  ?
t_cdr:   c                     i }t        | |      |d<   t        |       |d<   t        |       }|j                  |       |j	                  dt
        |      }t        |j                  |      }t        | ||       y )NDiscoveryConfigModelsSchedulePOSTdata)	r   rc   rZ   r   r,   r-   r   r.   r  )r0   r1   discovery_payloadother_paramsr5   rg   s         r8   create_discoveryr    sx    1Efh1W-.$0$8j!.v6L\*""6+<CT"UD$..(3F68V,r:   c                 6   g d}|D ]  }|| vs||v s||   | |<    | j                  d      s[|j                  di       }i }|j                  d      dk(  rd|d<   d|d<   d|d<   nd|d<   d|d<   |j                  d      |d<   || d<   |d	   | d	<   |r|| d
<   y y )N)r$   rP   rQ   rR   CreateGroupUseAllProfilesr  r`   r_   Tr]   Fr^   r&   r$   )r+   )discovery_modify_payloadcurrent_payloadnew_nameparent_itemsr>   exist_schedulerb   s          r8   update_modify_payloadr    s    &L  A..3/3I,;C,@$S)A $''
3(,,Z<f%3)-X&+0Z('1V$).X&+/Z('5'9'9&'AV$/? ,9HIa9b56?G !;< r:   c                 v   t        |      dkD  r)t        d |D              }| j                  t        |       t	        |      }|D ]G  }|j                  |d         dk(  s| j                  t        j                  |d   |d                I t        | |      t        |       d	}t        |       }|j                  |       t        ||d
   | j                  j                  d             |j                  dt        j                  |d         |      }t!        |j"                  |      }	t%        | ||	       y )Nr   c              3   &   K   | ]	  }|d      yw)r&   Nrk   )rm   r@   s     r8   ro   z#modify_discovery.<locals>.<genexpr>  s     TT":;Tr   )r   discovery_idsr&   r   r$   nameidr   )r  r  r   r  PUT)group_idr  )r   r   r   MULTI_DISCOVERYrB   r+   DISC_JOB_RUNNINGrv   r   rc   rZ   r   r  r*   r,   CONFIG_GROUPS_ID_URIr   r.   r  )
r0   r1   discov_listdup_discoveryrA   r7   r  r  r5   rg   s
             r8   modify_discoveryr+    s?   
;!TTT_MJ)(3N qa 89:dB$++3M1NSTUmSn+o  qq 3Gvx2X%1&%9;.v6L\*+[^V]]=N=Nz=Z[""5#7#>#>HYZrHs#>#t(9 # ;D $..(3F68V,r:   c                 v   t        |      }g }|D ][  }|j                  |d         dk(  r.| j                  t        j	                  |d   |d                H|j                  |d          ] d|i}|j                  dt        |       | j                  t        j	                  t        |      	      d
       y )Nr&   r   r$   r!  r   DiscoveryGroupIdsr  r  )nT)r   r  )rB   r+   r   r'  rv   r/   r,   DELETE_JOB_URIr  DISC_DEL_JOBS_SUCCESSr   )r0   r1   r)  rA   
delete_idsr7   delete_payloads          r8   delete_discoveryr3    s    )(3NJ ;a 89:dB!1!8!8a@Z>[<=>V<W "9 "Y Z a 89:; *:6NFNH
.55J5HRVWr:   c                      dddddddddiddddd	ddd
ddddddddddd	} ddddddddddddd}dddddddddddd	ddddddddddd}dddddddddddd	ddddd}ddddddddd| g dgdd| g dgdd| g dgdd| g dgdd|dd|dd|dd	}ddiddidddgdddidd|dgdd d d!gdddiddddd"dddddddddidddd#}t        |g d$g d%gd&gd&gd'      }	 t        |j                  d(      5 }t        ||      }|j                  j	                  d)      dk(  r&|rt        |||       |j                  t        *       nM|rt        |||       n=|j                  j	                  d+      r|j                  t        *       t        ||       d d d        y # 1 sw Y   y xY w# t        $ r9}	|j                  t        |	      t        j                  |	      ,       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        |	      *       Y d }	~	y d }	~	ww xY w).Nr   T)r   required)r   r5  no_logr   int   )r   default<   i  boolF)r   r6  )	usernamepassworddomainretriestimeoutportcn_checkca_checkcertificate_data   )	communityr?  r@  rA     )r<  r=  r?  r@  rA  check_known_hostsis_sudo_user)r<  r=  r?  r@  kgkeyr   )r5  r   elementsr=   )rC  T)rD  )r   optionsrequired_if)r   rL  )	r   r   r   r   r   r   r   r   r   presentabsent)r9  choices)r   r   r   r   r   r   r   )r   rK  rL  required_one_ofr]   r^   i0*  )r%   r#   stater  r   r\   ra   r   r  rS   rT   rU   r  )rR  rN  )r   )r\   r^   )ra   )r%   r#   )argument_specrM  rQ  mutually_exclusivesupports_check_mode)req_sessionrR  r   r#   )r   
error_info)r   unreachable)r   r   r*   r9   r+   r3  r  NO_CHANGES_MSGr+  r   INVALID_DISCOVERY_IDr  r   r   r   loadr   IOError
ValueError	TypeErrorr	   r
   OSError)

http_creds
snmp_creds	ssh_creds
ipmi_credsdiscovery_config_modelspecsr0   r1   r)  r   s
             r8   mainrf    sQ   ',$?',$$O#UO&+:&+;#(S9'-%@'-%@/4&E	J ).4@&+:&+:#(S9J
 ',>&+N%*q9%*r:"'B7/5%&H*0U!CI (-$?',$$O&+:&+;$)T:	J <@]b.cEISYgl8m06:8a7b(d28Z:c9d*f28Z:c9d*f17J9b8c)e/5*&M.4%K/5*&M   &uo&Ix3HIUO<RQ! !)h
5KL#5%*u=%+>%+>"E?+1e"D#E( ?/
 @@BC!	F'V]]5 	7268DK}}  )X5$VX{C  ^ 4$VX{C}}((8((-A(B$VX6	7 	7 	7  BSX$))C.AA 9SX488ZO=OQXY 'SX&&'sO   >G BF<3G <GG G 	I=/HI=H22&I=I88I=__main__)r   r   )@
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESRETURNr   r   ?ansible_collections.dellemc.openmanage.plugins.module_utils.omer   r   Aansible_collections.dellemc.openmanage.plugins.module_utils.utilsr   ansible.module_utils.urlsr	   r
   +ansible.module_utils.six.moves.urllib.errorr   r   0ansible.module_utils.common.dict_transformationsr   r-   r<   r/  rH   ru   r(  rY  r'  r0  r&  r  DISCOVER_JOB_COMPLETEr   r   r   r   r   r  r   rZ  r   r   r9   rB   rN   rZ   rc   r   r   r   r   r   r   r  r  r  r+  r3  rf  __name__rk   r:   r8   <module>rt     sQ   C BjXeN`
D   e _ I K UB 2 ]?A Q 2g D XA C , >A N 52 H 7 
XZyPh
1iW_gp
$$"	"0<4 .b4e,-H6-*X]'@ zF r:   