
    VhKR                        d dl mZmZmZ eZdZdZdZdZ	d dl
mZ d dlmZmZ d dlZd dlZ G d	 d
e      Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functionz4Abinash Mishra, Phan Nguyen, Madhan Sankaranarayanana,F  
---
module: discovery_intent
short_description: A resource module for handling device discovery tasks.
description:
  - Manages device discovery using IP address, address range, CDP, and LLDP, including
    deletion of discovered devices.
  - API to discover a device or multiple devices
  - API to delete a discovery of a device or multiple devices
version_added: '6.6.0'
extends_documentation_fragment:
  - cisco.dnac.intent_params
author: Abinash Mishra (@abimishr) Phan Nguyen (@phannguy) Madhan Sankaranarayanan
  (@madhansansel)
options:
  config_verify:
    description: Set to True to verify the Cisco Catalyst Center config after applying
      the playbook config.
    type: bool
    default: false
  state:
    description: The state of Cisco Catalyst Center after module completion.
    type: str
    choices: [merged, deleted]
    default: merged
  config:
    description:
      - List of details of device being managed.
    type: list
    elements: dict
    required: true
    suboptions:
      discovery_name:
        description: Name of the discovery task
        type: str
        required: true
      discovery_type:
        description: Determines the method of device discovery. Here are the available
          options. - SINGLE discovers a single device using a single IP address. -
          RANGE discovers multiple devices within a single IP address range. - MULTI
          RANGE discovers devices across multiple IP address ranges. - CDP  uses Cisco
          Discovery Protocol to discover devices in subsequent layers of the given
          IP address. - LLDP uses Link Layer Discovery Protocol to discover devices
          in subsequent layers of the specified IP address. - CIDR discovers devices
          based on subnet filtering using Classless Inter-Domain Routing.
        type: str
        required: true
        choices: ['SINGLE', 'RANGE', 'MULTI RANGE', 'CDP', 'LLDP', 'CIDR']
      ip_address_list:
        description: List of IP addresses to be discovered. For CDP/LLDP/SINGLE based
          discovery, we should pass a list with single element like - 10.197.156.22.
          For CIDR based discovery, we should pass a list with single element like
          - 10.197.156.22/22. For RANGE based discovery, we should pass a list with
          single element and range like - 10.197.156.1-10.197.156.100. For MULTI RANGE
          based discovery, we should pass a list with multiple elements like - 10.197.156.1-10.197.156.100
          and in next line - 10.197.157.1-10.197.157.100. Maximum of 8 IP address
          ranges are allowed.
        type: list
        elements: str
        required: true
      ip_filter_list:
        description: List of IP adddrsess that needs to get filtered out from the
          IP addresses passed.
        type: list
        elements: str
      cdp_level:
        description: Total number of levels that are there in cdp's method of discovery
        type: int
        default: 16
      lldp_level:
        description: Total number of levels that are there in lldp's method of discovery
        type: int
        default: 16
      preferred_mgmt_ip_method:
        description: Preferred method for the management of the IP (None/UseLoopBack)
        type: str
        default: None
      use_global_credentials:
        description:
          - Determines if device discovery should utilize pre-configured global credentials.
          - Setting to True employs the predefined global credentials for discovery
            tasks. This is the default setting.
          - Setting to False requires manually provided, device-specific credentials
            for discovery, as global credentials will be bypassed.
        type: bool
        default: true
      discovery_specific_credentials:
        description: Credentials specifically created by the user for performing device
          discovery.
        type: dict
        suboptions:
          cli_credentials_list:
            description: List of CLI credentials to be used during device discovery.
            type: list
            elements: dict
            suboptions:
              username:
                description: Username for CLI authentication, mandatory when using
                  CLI credentials.
                type: str
              password:
                description: Password for CLI authentication, mandatory when using
                  CLI credential.
                type: str
              enable_password:
                description: Enable password for CLI authentication, mandatory when
                  using CLI credential.
                type: str
          http_read_credential:
            description: HTTP read credential is used for authentication purposes
              and specifically utilized to grant read-only access to certain resources
              from the device.
            type: dict
            suboptions:
              username:
                description: Username for HTTP(S) Read authentication, mandatory when
                  using HTTP credentials.
                type: str
              password:
                description: Password for HTTP(S) Read authentication, mandatory when
                  using HTTP credentials.
                type: str
              port:
                description: Port for HTTP(S) Read authentication, mandatory for using
                  HTTP credentials.
                type: int
              secure:
                description: Flag for HTTP(S) Read authentication, not mandatory when
                  using HTTP credentials.
                type: bool
          http_write_credential:
            description: HTTP write credential is used for authentication purposes
              and grants Cisco Catalyst Center the ability to alter configurations,
              update software, or perform other modifications on a network device.
            type: dict
            suboptions:
              username:
                description: Username for HTTP(S) Write authentication, mandatory
                  when using HTTP credentials.
                type: str
              password:
                description: Password for HTTP(S) Write authentication, mandatory
                  when using HTTP credentials.
                type: str
              port:
                description: Port for HTTP(S) Write authentication, mandatory when
                  using HTTP credentials.
                type: int
              secure:
                description: Flag for HTTP(S) Write authentication, not mandatory
                  when using HTTP credentials.
                type: bool
          snmp_v2_read_credential:
            description:
              - The SNMP v2 credentials to be created and used for contacting a device
                via SNMP protocol in read mode.
              - SNMP v2 also delivers data encryptions, but it uses data types.
            type: dict
            suboptions:
              description:
                description: Name/Description of the SNMP read credential to be used
                  for creation of snmp_v2_read_credential.
                type: str
              community:
                description: SNMP V2 Read community string enables Cisco Catalyst
                  Center to extract read-only data from device.
                type: str
          snmp_v2_write_credential:
            description:
              - The SNMP v2 credentials to be created and used for contacting a device
                via SNMP protocol in read and write mode.
              - SNMP v2 also delivers data encryptions, but it uses data types.
            type: dict
            suboptions:
              description:
                description: Name/Description of the SNMP write credential to be used
                  for creation of snmp_v2_write_credential.
                type: str
              community:
                description: SNMP V2 Write community string is used to extract data
                  and alter device configurations.
                type: str
          snmp_v3_credential:
            description:
              - The SNMP v3 credentials to be created and used for contacting a device
                via SNMP protocol in read and write mode.
              - SNMPv3 is the most secure version of SNMP, allowing users to fully
                encrypt transmissions, keeping us safe from external attackers.
            type: dict
            suboptions:
              username:
                description: Username of the SNMP v3 protocol to be used.
                type: str
              snmp_mode:
                description:
                  - Mode of SNMP which determines the encryption level of our community
                    string.
                  - AUTHPRIV mode uses both Authentication and Encryption.
                  - AUTHNOPRIV mode uses Authentication but no Encryption.
                  - NOAUTHNOPRIV mode does not use either Authentication or Encryption.
                type: str
                choices: ['AUTHPRIV', 'AUTHNOPRIV', 'NOAUTHNOPRIV']
              auth_password:
                description:
                  - Authentication Password of the SNMP v3 protocol to be used.
                  - Must be of length greater than 7 characters.
                  - Not required for NOAUTHNOPRIV snmp_mode.
                type: str
              auth_type:
                description:
                  - Authentication type of the SNMP v3 protocol to be used.
                  - SHA uses Secure Hash Algorithm (SHA) as your authentication protocol.
                  - MD5 uses Message Digest 5 (MD5) as your authentication protocol
                    and is not recommended.
                  - Not required for NOAUTHNOPRIV snmp_mode.
                type: str
                choices: ['SHA', 'MD5']
              privacy_type:
                description:
                  - Privacy type/protocol of the SNMP v3 protocol to be used in AUTHPRIV
                    SNMP mode
                  - Not required for AUTHNOPRIV and NOAUTHNOPRIV snmp_mode.
                type: str
                choices: ['AES128', 'AES192', 'AES256']
              privacy_password:
                description:
                  - Privacy password of the SNMP v3 protocol to be used in AUTHPRIV
                    SNMP mode
                  - Not required for AUTHNOPRIV and NOAUTHNOPRIV snmp_mode.
                type: str
          net_conf_port:
            description:
              - To be used when network contains IOS XE-based wireless controllers.
              - This is used for discovery and the enabling of wireless services on
                the controllers.
              - Requires valid SSH credentials to work.
              - Avoid standard ports like 22, 80, and 8080.
            type: str
      global_credentials:
        description:
          - Set of various credential types, including CLI, SNMP, HTTP, and NETCONF,
            that a user has pre-configured in the Device Credentials section of the
            Cisco Catalyst Center.
          - If user doesn't pass any global credentials in the playbook, then by default,
            we will use all the global credentials present in the Cisco Catalyst Center
            of each type for performing discovery. (Max 5 allowed)
        type: dict
        version_added: 6.12.0
        suboptions:
          cli_credentials_list:
            description:
              - Accepts a list of global CLI credentials for use in device discovery.
              - It's recommended to create device credentials with both a unique username
                and a clear description.
            type: list
            elements: dict
            suboptions:
              username:
                description: Username required for CLI authentication and is mandatory
                  when using global CLI credentials.
                type: str
              description:
                description: Name of the CLI credential, mandatory when using global
                  CLI credentials.
                type: str
          http_read_credential_list:
            description:
              - List of global HTTP Read credentials that will be used in the process
                of discovering devices.
              - It's recommended to create device credentials with both a unique username
                and a clear description for easy identification.
            type: list
            elements: dict
            suboptions:
              username:
                description: Username for HTTP Read authentication, mandatory when
                  using global HTTP credentials.
                type: str
              description:
                description: Name of the HTTP Read credential, mandatory when using  global
                  HTTP credentials.
                type: str
          http_write_credential_list:
            description:
              - List of global HTTP Write credentials that will be used in the process
                of discovering devices.
              - It's recommended to create device credentials with both a unique username
                and a clear description for easy identification.
            type: list
            elements: dict
            suboptions:
              username:
                description: Username for HTTP Write authentication, mandatory when
                  using global HTTP credentials.
                type: str
              description:
                description: Name of the HTTP Write credential, mandatory when using  global
                  HTTP credentials.
                type: str
          snmp_v2_read_credential_list:
            description:
              - List of Global SNMP V2 Read credentials to be used during device discovery.
              - It's recommended to create device credentials with a clear description
                for easy identification.
            type: list
            elements: dict
            suboptions:
              description:
                description: Name of the SNMP Read credential, mandatory when using  global
                  SNMP credentials.
                type: str
          snmp_v2_write_credential_list:
            description:
              - List of Global SNMP V2 Write credentials to be used during device
                discovery.
              - It's recommended to create device credentials with a clear description
                for easy identification.
            type: list
            elements: dict
            suboptions:
              description:
                description: Name of the SNMP Write credential, mandatory when using
                  global SNMP credentials.
                type: str
          snmp_v3_credential_list:
            description:
              - List of Global SNMP V3 credentials to be used during device discovery,
                giving read and write mode.
              - It's recommended to create device credentials with both a unique username
                and a clear description for easy identification.
            type: list
            elements: dict
            suboptions:
              username:
                description: Username for SNMP V3 authentication, mandatory when using
                  global SNMP credentials.
                type: str
              description:
                description: Name of the SNMP V3 credential, mandatory when using
                  global SNMP credentials.
                type: str
          net_conf_port_list:
            description:
              - List of Global Net conf ports to be used during device discovery.
              - It's recommended to create device credentials with unique description.
            type: list
            elements: dict
            suboptions:
              description:
                description: Name of the Net Conf Port credential, mandatory when
                  using global Net conf port.
                type: str
      start_index:
        description: Start index for the header in fetching SNMP v2 credentials
        type: int
        default: 1
      records_to_return:
        description: Number of records to return for the header in fetching global
          v2 credentials
        type: int
        default: 100
      protocol_order:
        description: Determines the order in which device connections will be attempted.
          Here are the options - "telnet" Only telnet connections will be tried. -
          "ssh, telnet" SSH (Secure Shell) will be attempted first, followed by telnet
          if SSH fails.
        type: str
        default: ssh
      retry:
        description: Number of times to try establishing connection to device
        type: int
      timeout:
        description: Time to wait for device response in seconds
        type: int
      delete_all:
        description: Parameter to delete all the discoveries at one go
        type: bool
        default: false
requirements:
  - dnacentersdk == 2.6.10
  - python >= 3.9
notes:
  - SDK Method used are discovery.Discovery.get_all_global_credentials_v2, discovery.Discovery.start_discovery,
    task.Task.get_task_by_id, discovery.Discovery.get_discoveries_by_range, discovery.Discovery.get_discovered_network_devices_by_discovery_id',
    discovery.Discovery.delete_discovery_by_id discovery.Discovery.delete_all_discovery
    discovery.Discovery.get_count_of_all_discovery_jobs
  - Paths used are get /dna/intent/api/v2/global-credential post /dna/intent/api/v1/discovery
    get /dna/intent/api/v1/task/{taskId} get /dna/intent/api/v1/discovery/{startIndex}/{recordsToReturn}
    get /dna/intent/api/v1/discovery/{id}/network-device delete /dna/intent/api/v1/discovery/{id}
    delete /dna/intent/api/v1/delete get /dna/intent/api/v1/discovery/count
  - Removed 'global_cli_len' option in v6.12.0.
a=  
- name: Execute discovery of devices with both global credentials and discovery
    specific credentials
  cisco.dnac.discovery_intent:
    dnac_host: "{{dnac_host}}"
    dnac_username: "{{dnac_username}}"
    dnac_password: "{{dnac_password}}"
    dnac_verify: "{{dnac_verify}}"
    dnac_port: "{{dnac_port}}"
    dnac_version: "{{dnac_version}}"
    dnac_debug: "{{dnac_debug}}"
    dnac_log: true
    dnac_log_level: "{{dnac_log_level}}"
    state: merged
    config_verify: true
    config:
      - discovery_name: Discovery with both global and job specific credentials
        discovery_type: RANGE
        ip_address_list:
          - 201.1.1.1-201.1.1.100
        ip_filter_list:
          - 201.1.1.2
          - 201.1.1.10
        discovery_specific_credentials:
          cli_credentials_list:
            - username: cisco
              password: Cisco123
              enable_password: Cisco123
          http_read_credential:
            username: cisco
            password: Cisco123
            port: 443
            secure: true
          http_write_credential:
            username: cisco
            password: Cisco123
            port: 443
            secure: true
          snmp_v2_read_credential:
            description: snmp_v2-new
            community: Cisco123
          snmp_v2_write_credential:
            description: snmp_v2-new
            community: Cisco123
          snmp_v3_credential:
            username: v3Public2
            snmp_mode: AUTHPRIV
            auth_type: SHA
            auth_password: Lablab123
            privacy_type: AES256
            privacy_password: Lablab123
          net_conf_port: 750
        global_credentials:
          cli_credentials_list:
            - description: ISE
              username: cisco
            - description: CLI1234
              username: cli
          http_read_credential_list:
            - description: HTTP Read
              username: HTTP_Read
          http_write_credential_list:
            - description: HTTP Write
              username: HTTP_Write
          snmp_v3_credential_list:
            - description: snmpV3
              username: snmpV3
          snmp_v2_read_credential_list:
            - description: snmpV2_read
          snmp_v2_write_credential_list:
            - description: snmpV2_write
          net_conf_port_list:
            - description: Old_one
        start_index: 1
        records_to_return: 100
        protocol_order: ssh
        retry: 5
        timeout: 3
- name: Execute discovery of devices with discovery specific credentials only
  cisco.dnac.discovery_intent:
    dnac_host: "{{dnac_host}}"
    dnac_username: "{{dnac_username}}"
    dnac_password: "{{dnac_password}}"
    dnac_verify: "{{dnac_verify}}"
    dnac_port: "{{dnac_port}}"
    dnac_version: "{{dnac_version}}"
    dnac_debug: "{{dnac_debug}}"
    dnac_log: true
    dnac_log_level: "{{dnac_log_level}}"
    state: merged
    config_verify: true
    config:
      - discovery_name: Single with discovery specific credentials only
        discovery_type: SINGLE
        ip_address_list:
          - 204.1.1.10
        discovery_specific_credentials:
          cli_credentials_list:
            - username: cisco
              password: Cisco123
              enable_password: Cisco123
          http_read_credential:
            username: cisco
            password: Cisco123
            port: 443
            secure: true
          http_write_credential:
            username: cisco
            password: Cisco123
            port: 443
            secure: true
          snmp_v2_read_credential:
            description: snmp_v2-new
            community: Cisco123
          snmp_v2_write_credential:
            description: snmp_v2-new
            community: Cisco123
          snmp_v3_credential:
            username: v3Public2
            snmp_mode: AUTHPRIV
            auth_type: SHA
            auth_password: Lablab123
            privacy_type: AES256
            privacy_password: Lablab123
          net_conf_port: 750
        use_global_credentials: false
        start_index: 1
        records_to_return: 100
        protocol_order: ssh
        retry: 5
        timeout: 3
- name: Execute discovery of devices with global credentials only
  cisco.dnac.discovery_intent:
    dnac_host: "{{dnac_host}}"
    dnac_username: "{{dnac_username}}"
    dnac_password: "{{dnac_password}}"
    dnac_verify: "{{dnac_verify}}"
    dnac_port: "{{dnac_port}}"
    dnac_version: "{{dnac_version}}"
    dnac_debug: "{{dnac_debug}}"
    dnac_log: true
    dnac_log_level: "{{dnac_log_level}}"
    state: merged
    config_verify: true
    config:
      - discovery_name: CDP with global credentials only
        discovery_type: CDP
        ip_address_list:
          - 204.1.1.1
        cdp_level: 16
        global_credentials:
          cli_credentials_list:
            - description: ISE
              username: cisco
            - description: CLI1234
              username: cli
          http_read_credential_list:
            - description: HTTP Read
              username: HTTP_Read
          http_write_credential_list:
            - description: HTTP Write
              username: HTTP_Write
          snmp_v3_credential_list:
            - description: snmpV3
              username: snmpV3
          snmp_v2_read_credential_list:
            - description: snmpV2_read
          snmp_v2_write_credential_list:
            - description: snmpV2_write
          net_conf_port_list:
            - description: Old_one
        start_index: 1
        records_to_return: 100
        protocol_order: ssh
        retry: 5
        timeout: 3
- name: Execute discovery of devices with all the global credentials (max 5 allowed)
  cisco.dnac.discovery_intent:
    dnac_host: "{{dnac_host}}"
    dnac_username: "{{dnac_username}}"
    dnac_password: "{{dnac_password}}"
    dnac_verify: "{{dnac_verify}}"
    dnac_port: "{{dnac_port}}"
    dnac_version: "{{dnac_version}}"
    dnac_debug: "{{dnac_debug}}"
    dnac_log: true
    dnac_log_level: "{{dnac_log_level}}"
    state: merged
    config_verify: true
    config:
      - discovery_name: CIDR with all global credentials
        discovery_type: CIDR
        ip_address_list:
          - 204.1.2.0/24
        ip_filter_list:
          - 204.1.2.10
        preferred_mgmt_ip_method: None
        start_index: 1
        records_to_return: 100
        protocol_order: telnet
        retry: 10
        timeout: 3
        use_global_credentials: true
- name: Delete disovery by name
  cisco.dnac.discovery_intent:
    dnac_host: "{{dnac_host}}"
    dnac_username: "{{dnac_username}}"
    dnac_password: "{{dnac_password}}"
    dnac_verify: "{{dnac_verify}}"
    dnac_port: "{{dnac_port}}"
    dnac_version: "{{dnac_version}}"
    dnac_debug: "{{dnac_debug}}"
    dnac_log: true
    dnac_log_level: "{{dnac_log_level}}"
    state: deleted
    config_verify: true
    config:
      - discovery_name: Single discovery
aL  
#Case_1: When the device(s) are discovered successfully.
response_1:
  description: A dictionary with the response returned by the Cisco Catalyst Center Python SDK
  returned: always
  type: dict
  sample: >
    {
      "response":
        {
          "response": String,
          "version": String
        },
      "msg": String
    }
#Case_2: Given device details or SNMP mode are not provided
response_2:
  description: A list with the response returned by the Cisco Catalyst Center Python SDK
  returned: always
  type: list
  sample: >
    {
      "response": [],
      "msg": String
    }
#Case_3: Error while deleting a discovery
response_3:
  description: A string with the response returned by the Cisco Catalyst Center Python SDK
  returned: always
  type: dict
  sample: >
    {
      "response": String,
      "msg": String
    }
)AnsibleModule)DnacBasevalidate_list_of_dictsNc                        e Zd Z fdZddZd Zd ZddZd Zd Z	ddZ
d	 Zdd
ZddZddZddZddZddZd Zd ZddZd Zd Zd Zd Zd Zd Z xZS )	Discoveryc                 2    t         |   |       g | _        y)a  
        Initialize an instance of the class. It also initializes an empty
        list for 'creds_ids_list' attribute.

        Parameters:
          - module: The module associated with the class instance.

        Returns:
          The method does not return a value. Instead, it initializes the
          following instance attributes:
          - self.creds_ids_list: An empty list that will be used to store
                                 credentials IDs.
        N)super__init__creds_ids_list)selfmodule	__class__s     o/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/cisco/dnac/plugins/modules/discovery_intent.pyr   zDiscovery.__init__  s     	      c                    | j                   sd| _        d| _        | S 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k(  rdddd|d<   ddd
|d<   nT|dk(  rO| j                   d   j                  d      du r/ddig| _        d| _        | j                  | j                  d       | S t        | j                   |      \  }}|rSdj                  dj                  |            | _        | j                  t        | j                        d       d| _        | S || _        dj                  t        |            | _        | j                  t        | j                        d        d| _        | S )!a  
        Validate the fields provided in the playbook.  Checks the
        configuration provided in the playbook against a predefined
        specification to ensure it adheres to the expected structure
        and data types.

        Returns:
          The method returns an instance of the class with updated attributes:
          - self.msg: A message describing the validation result.
          - self.status: The status of the validation (either 'success' or 'failed').
          - self.validated_config: If successful, a validated version of the
                                   'config' parameter.
        Example:
          To use this method, create an instance of the class and call
          'validate_input' on it.If the validation succeeds, 'self.status'
          will be 'success'and 'self.validated_config' will contain the
          validated configuration. If it fails, 'self.status' will be
          'failed', and 'self.msg' will describe the validation issues.
        z/config not available in playbook for validationsuccessintF   )typerequireddefault   d   dict)r   r   liststr)r   r   elementsTNonesshbool)	cdp_levelstart_indexrecords_to_returndiscovery_specific_credentialsip_filter_list
lldp_leveldiscovery_namenetconf_portpreferred_mgmt_ip_methodretrytimeoutglobal_credentialsprotocol_orderuse_global_credentialsmergedip_address_listdiscovery_typedeletedr   
delete_allz?Sucessfully collected input for deletion of all the discoveriesWARNINGz#Invalid parameters in playbook: {0}
ERRORfailedzTSuccessfully validated playbook configuration parameters using 'validate_input': {0}INFO)
configmsgstatusgetvalidated_configlogr   formatjoinr   )r   statediscovery_specvalid_discoveryinvalid_paramss        r   validate_inputzDiscovery.validate_input  s   * {{HDH#DKK #(U%')$)u'(**/U-0"27=5.Q'-5+02#(e&(*',$?%*>16E4:)<#7 %59+1u"E',%ER/55UY&Z)
. H9?T=B1DN,-8=4/PN+,i{{1~!!,/47*6)=(>%\9- +AKK+
' <CC		.)+DHHHS]G,"DKK /ippqt  vE  rF  GTXX'r   c           	         | j                   d   j                  d      }|D ];  }d|v r|j                  d      d   }d|v rt        |j                  d            dk(  rd|j                  d      \  }}| j	                  |      du r?dj                  |      }| j                  |d       | j                  j                  |	       | j	                  |      du r?dj                  |      }| j                  |d       | j                  j                  |	       t        t        t        |j                  d
                  }t        t        t        |j                  d
                  }t        d      D ]M  }||   ||   kD  sdj                  |      }| j                  |d       | j                  j                  |	       O n?dj                  |      }| j                  |d       | j                  j                  |	       | j	                  |      du sd|vsdj                  |      }| j                  |d       | j                  j                  |	       > | j                  dd       y)zs
        Validates each ip adress paased in the IP_address_list passed by the user before preprocessing it
        r   r3   /-   FzIP address {0} is not validCRITICALr=   .   zAIncorrect range passed: {0}. Please pass correct IP address rangezaProvided range '{0}' is incorrect. IP address range should have only upper and lower limit valuesz'All the IP addresses passed are correctr;   N)r@   r?   splitlenis_valid_ipv4rB   rA   r   	fail_jsonr   mapr   range)	r   r3   ipip1ip2r=   	ip1_parts	ip2_partsparts	            r   validate_ip4_address_listz#Discovery.validate_ip4_address_list  s+   
 //2667HI! 	/BbyXXc]1%byrxx}%*!xx}HC))#.%7;BB3Gj1--#-6))#.%7;BB3Gj1--#-6 $Sciin%= >I $Sciin%= >I %a ;$T?Yt_<"e"l"lmo"pC HHS*5 KK11c1:	; ~  E  E  FH  ICHHS*-KK))c)2!!"%.3b=3::2>j)%%#%.9	/: 	:FCr   c                     | j                  dj                  t        | j                              d       | j                  S )a$  
        Retrieve the list of credentials IDs associated with class instance.

        Returns:
          The method returns the list of credentials IDs:
          - self.creds_ids_list: The list of credentials IDs associated with
                                 the class instance.
        z!Credential Ids list passed is {0}r;   )rA   rB   r   r   r   s    r   get_creds_ids_listzDiscovery.get_creds_ids_list   s6     	4;;C@S@S<TUW]^"""r   c                 r   | j                   d   j                  d      }i }|j                  d      }|r8t        |t              sd}| j	                  |       |j                  d      d}| j	                  |       t        |      dkD  rg |d<   t        |      }|d	kD  rd	}|D ]  }|j                  d
      r|j                  d      r|j                  d      D ]m  }|j                  d
      |j                  d
      k(  s'|j                  d      |j                  d      k(  sK|d   j                  |j                  d             o |d   d| |d<   d}| j	                  |        |j                  d      }	|	r8t        |	t              sd}| j	                  |       |j                  d      d}| j	                  |       t        |	      dkD  rg |d<   t        |	      }|d	kD  rd	}|	D ]  }
|
j                  d
      r|
j                  d      r|j                  d      D ]m  }|j                  d
      |j                  d
      k(  s'|j                  d      |j                  d      k(  sK|d   j                  |j                  d             o |d   d| |d<   d}| j	                  |        |j                  d      }|r8t        |t              sd}| j	                  |       |j                  d      d}| j	                  |       t        |      dkD  rg |d<   t        |      }|d	kD  rd	}|D ]  }
|
j                  d
      r|
j                  d      r|j                  d      D ]m  }|j                  d
      |j                  d
      k(  s'|j                  d      |j                  d      k(  sK|d   j                  |j                  d             o |d   d| |d<   d}| j	                  |        |j                  d      }|rt        |t              sd}| j	                  |       |j                  d      d}| j	                  |       t        |      dkD  rg |d<   t        |      }|d	kD  rd	}|D ]  }|j                  d
      ri|j                  d      D ]I  }|j                  d
      |j                  d
      k(  s'|d   j                  |j                  d             K |d   d| |d<   }d}| j	                  |        |j                  d      }|rt        |t              sd}| j	                  |       |j                  d      d }| j	                  |       t        |      dkD  rg |d<   t        |      }|d	kD  rd	}|D ]  }|j                  d
      ri|j                  d      D ]I  }|j                  d
      |j                  d
      k(  s'|d   j                  |j                  d             K |d   d| |d<   }d!}| j	                  |        |j                  d"      }|r8t        |t              sd#}| j	                  |       |j                  d$      d%}| j	                  |       t        |      dkD  rg |d$<   t        |      }|d	kD  rd	}|D ]  }|j                  d
      r|j                  d      r|j                  d$      D ]m  }|j                  d
      |j                  d
      k(  s'|j                  d      |j                  d      k(  sK|d$   j                  |j                  d             o |d$   d| |d$<   d&}| j	                  |        |j                  d'      }|rt        |t              sd(}| j	                  |       |j                  d)      d*}| j	                  |       t        |      dkD  rg |d)<   t        |      }|d	kD  rd	}|D ]  }|j                  d
      ri|j                  d)      D ]I  }|j                  d
      |j                  d
      k(  s'|d)   j                  |j                  d             K |d)   d| |d)<   }d+}| j	                  |        | j                  d,j                  |      d-       |S ).a  
        Method to convert values for create_params API when global paramters
        are passed as input.

        Parameters:
            - response: The response collected from the get_all_global_credentials_v2 API

        Returns:
            - global_credentials_all  : The dictionary containing list of IDs of various types of
                                    Global credentials.
        r   r/   cli_credentials_listz/Global CLI credentials must be passed as a listrN   cliCredentialNzCGlobal CLI credentials are not present in the Cisco Catalyst Center   descriptionusernameidzuKindly ensure you include both the description and the username for the Global CLI credential to discover the deviceshttp_read_credential_listz5Global HTTP read credentials must be passed as a list	httpsReadzIGlobal HTTP read credentials are not present in the Cisco Catalyst Centerz{Kindly ensure you include both the description and the username for the Global HTTP Read credential to discover the deviceshttp_write_credential_listz6Global HTTP write credentials must be passed as a list
httpsWritezJGlobal HTTP write credentials are not present in the Cisco Catalyst Centerz|Kindly ensure you include both the description and the username for the Global HTTP Write credential to discover the devicessnmp_v2_read_credential_listz7Global SNMPv2 read credentials must be passed as a listsnmpV2cReadzKGlobal SNMPv2 read credentials are not present in the Cisco Catalyst CenterzKindly ensure you include the description for the Global SNMPv2 Read                                 credential to discover the devicessnmp_v2_write_credential_listz8Global SNMPv2 write credentials must be passed as a listsnmpV2cWritezLGlobal SNMPv2 write credentials are not present in the Cisco Catalyst CenterzhKindly ensure you include the description for the Global SNMPV2 write credential to discover the devicessnmp_v3_credential_listz8Global SNMPv3 write credentials must be passed as a listsnmpV3zFGlobal SNMPv3 credentials are not present in the Cisco Catalyst CenterzKindly ensure you include both the description and the username for the Global SNMPv3                                 to discover the devicesnet_conf_port_listz)Global net Conf Ports be passed as a listnetconfCredentialzAGlobal netconf ports are not present in the Cisco Catalyst CenterzFPlease provide valid description of the Global Netconf port to be usedz&Fetched Global credentials IDs are {0}r;   )	r@   r?   
isinstancer   discovery_specific_cred_failurerR   appendrA   rB   )r   responser/   global_credentials_allrb   r=   cred_lencli_credclirh   	http_credhttprj   rl   	snmp_credsnmprn   rp   rr   portnetconfs                        r   handle_global_credentialsz#Discovery.handle_global_credentials-  s	    "221599:NO!#1556LM2D9G444=||O,4[444='(1,:<&734a< H 4 FH||M2x||J7O#+<<#@ ^C"ww}5m9TTY\Y`Y`akYlpxp|p|  ~H  qI  ZI 6 G N NswwW[} ]^ CYYhBijsksBt.? V<<<EF %7$:$:;V$W!$7>M444=||K(0a444=,-168&{389a< H!: FI }}]3	j8Q$,LL$= [D#xx6$((=:QQVZV^V^_iVjnrnvnv  xB  oC  WC 6{ C J J488TX> Z[ ?UU`>abkck>l.{; \<<<EF &8%;%;<X%Y"%8$?N444=||L)1b444=-.279&|49:a< H!; FI }}]3	j8Q$,LL$> \D#xx6$((=:QQVZV^V^_iVjnrnvnv  xB  oC  WC 6| D K KDHHUYN [\ @VVb?cdmem?n.|< ]<<<EF (:'='=>\']$':DAO444=||M*2c444=/0148:&}5;<a< H!= 	FI }}]3$,LL$? ]D#xx6)--:VV 6} E L LTXXVZ^ \] AWWd@efogo@p.}=D<<<E	F );(>(>?^(_%(;TBP444=||N+3d444=01A59;&~6<=a< H!> FI }}]3$,LL$@ ^D#xx6)--:VV 6~ F M MdhhW[n ]^ BXXfAghqiqAr.~> I<<<EF #5"8"89R"S"5t<P444=||H%-^444=*+a/35&x067a< H!8 	FI }}]3	j8Q$,LL$: XD#xx6)--:VV[_[c[cdn[os|  tA  tA  BL  tM  \M 6x @ G GQU WX <RRZ;[\e]e;f.x89<<<E	F 0334HI0$7A444=||/08Y444=%&*>@&':;12a< H. FDxx.'/||4G'H fG#xx6'++m:TT 67J K R RSZS^S^_cSd ef G]]pFqr{s{F|./BCf<<<EF 	9@@AWXZ`a%%r   c                     | j                   d   dd| j                  d   j                  d      d      }|j                  d      }| j                  d	j	                  t        |            d
       i }| j                  d   j                  d      }|r| j                  |      }t        |j                               }t        |j                               }|j                  |      }|D ]j  }g ||<   ||   g ||<   t        ||         }|dkD  rd}|j                  |      D ]%  }	||   j                  |	j                  d             ' ||   d| ||<   l |i k(  rd}
| j                  |
d       |S )aI  
        Retrieve the global credentials information (version 2).
        It applies the 'get_all_global_credentials_v2' function and extracts
        the IDs of the credentials. If no credentials are found, the
        function fails with a message.

        Returns:
          This method does not return a value. However, updates the attributes:
          - self.creds_ids_list: The list of credentials IDs is extended with
                                 the IDs extracted from the response.
          - self.result: A dictionary that is updated with the credentials IDs.
        exec	discoveryget_all_global_credentials_v2r   headersTfamilyfunctionparamsop_modifiesrw   zOThe Global credentials response from 'get all global credentials v2' API is {0}DEBUGr/   )rw   Nrd   rg   z5Not found any global credentials to perform discoveryr7   )
dnac_applyr@   r?   rA   rB   r   r   setkeys
differencerR   rv   )r   rw   rx   r/   global_cred_setresponse_cred_set	diff_keyskey	total_lenelementr=   s              r   "get_ccc_global_credentials_v2_infoz,Discovery.get_ccc_global_credentials_v2_info  s    +4??6*4((+//	:	
 <<
+biijmnvjwx  {B  	C!#!221599:NO%)%C%CX%C%V"499;<0%00A	 		RC*,"3'}$ "HSM*I1}	#<<, F&s+227;;t3DEF*@*Ejy*Q"3'		R "R'ICHHS)$%%r   c                     | j                   d   j                  d      }| j                  j                  t	        |             | j                  dj                  t        |            d       |S )a  
        Retrieve the list of devices from the validated configuration.
        It then updates the result attribute with this list.

        Returns:
          - ip_address_list: The list of devices extracted from the
                          'validated_config' attribute.
        r   r3   )devices_infoz&Details of the device list passed: {0}r;   )r@   r?   resultupdater   rA   rB   r   )r   r3   s     r   get_devices_list_infozDiscovery.get_devices_list_info  s]     //2667HI4_=>9@@_AUVX^_r   c                    |g }| j                   d   j                  d      }| j                  dj                  |      d       |dv r't	        |      dk(  r|d   }n| j                          n|dk(  rt	        |      dk(  r|d   }t        |j                  d      d         t        d	d
      vr0d}| j                  |d       | j                  j                  |       t	        |j                  d            dk(  r|}nUdj                  |      }| j                  dd       n0| j                          n|dk(  rgt	        |      dk(  rHt	        t        |d         j                  d            dk(  r|d   }ndj                  |d   |d         }n| j                          nt	        |      dkD  r0d}| j                  |d       | j                  j                  |       g }|D ]\  }t	        t        |      j                  d            dk7  r#dj                  |      }|j                  |       L|j                  |       ^ dj                  |      }| j                  dj                  t        |            d       t        |      S )a  
        Preprocess the devices' information. Extract the IP addresses from
        the list of devices and perform additional processing based on the
        'discovery_type' in the validated configuration.

        Parameters:
          - ip_address_list: The list of devices' IP addresses intended for preprocessing.
                             If not provided, an empty list will be used.

        Returns:
          - ip_address_list: It returns IP address list for the API to process. The value passed
                             for single, CDP, LLDP, CIDR, Range and Multi Range varies depending
                             on the need.
        r   r4   z.Discovery type passed for the discovery is {0}r;   )SINGLECDPLLDPr   CIDRrJ         z)Prefix length should be between 20 and 30rM   rN   rL   z{0}/30zCIDR notation is being used for discovery and it requires a prefix length to be specified, such as 1.1.1.1/24.                        As no prefix length was provided, it will default to 30.r7   RANGErK   z{0}-{1}   z#Maximum of 8 IP ranges are allowed.z{0}-{0},z&Collected IP address/addresses are {0})r@   r?   rA   rB   rR   (preprocess_device_discovery_handle_errorr   rQ   rV   r   rT   r   rv   rC   )r   r3   r4   cidr_notationr=   new_ip_collectedrW   ip_collecteds           r   preprocess_device_discoveryz%Discovery.preprocess_device_discovery!  sa     " O..q1556FGAHHXZ`a66?#q("1!"4==?v%?#q( / 2}**3/235R=HECHHS*-KK))c)2}**3/0A5&3O&.oom&DOHH RS\^ ==?w&?#q(s?1-.44S9:a?&5a&8O&/&6&6q7I?[\K]&^O==??#a';j)%%#%.!% 0s2w}}S)*a/#,#3#3B#7L$++L9$++B/0 "hh'78O9@@_AUVX^_?##r   c                 b    | j                  dd       | j                  j                  dg        y)z
        Method for failing discovery based on the length of list of IP Addresses passed
        for performing discovery.
        z)IP Address list's length is longer than 1r9   )r=   rw   NrA   r   rT   r_   s    r   r   z2Discovery.preprocess_device_discovery_handle_errora  s,     	<gF"MXZ[r   c                 `    | j                  |d       | j                  j                  |       y)zx
        Method for failing discovery if there is any discrepancy in the credentials
        passed by the user
        rM   rN   Nr   )r   r=   s     r   ru   z)Discovery.discovery_specific_cred_failurej  s'     	j!#&r   c                    | j                   d   j                  d      }|j                  d      }|j                  d      }|j                  d      }|j                  d      }|j                  d      }|j                  d      }|j                  d	      }	|rt        |t              sd
}
| j	                  |
       t        |      dkD  rg }g }g }|D ]  }|j                  d      r|j                  d      rr|j                  d      ra|j                  |j                  d             |j                  |j                  d             |j                  |j                  d             d}
| j	                  |
        ||d<   ||d<   ||d<   |r|j                  d      rt        |j                  d      t              sd}
| j	                  |
       |j                  d      rt        |j                  d      t              sd}
| j	                  |
       |j                  d      rt        |j                  d      t              sd}
| j	                  |
       t        |j                  d      t              sd}
| j	                  |
       ||d<   |r|j                  d      rt        |j                  d      t              sd}
| j	                  |
       |j                  d      rt        |j                  d      t              sd}
| j	                  |
       |j                  d      rt        |j                  d      t              sd}
| j	                  |
       t        |j                  d      t              sd}
| j	                  |
       ||d<   |r|j                  d      s3t        |j                  d      t              rd }
| j	                  |
       |j                  d!      s3t        |j                  d!      t              rd"}
| j	                  |
       |j                  d      |d#<   |j                  d!      |d$<   d%|d&<   |r|j                  d      s3t        |j                  d      t              rd'}
| j	                  |
       |j                  d!      s3t        |j                  d!      t              rd"}
| j	                  |
       |j                  d      |d(<   |j                  d!      |d)<   d%|d&<   |rT|j                  d      s3t        |j                  d      t              rd*}
| j	                  |
       |j                  d+      st        |j                  d+      t              rad,}
| j	                  |
       |j                  d+      d-k(  s|j                  d+      d.k(  r$|j                  d/      s3t        |j                  d/      t              rd0}
| j	                  |
       |j                  d1      s3t        |j                  d1      t              rd2}
| j	                  |
       |j                  d+      d-k(  r|j                  d3      s3t        |j                  d3      t              rd4}
| j	                  |
       |j                  d5      s3t        |j                  d5      t              rd6}
| j	                  |
       |j                  d      |d7<   |j                  d+      |d8<   |j                  d/      |d9<   |j                  d1      |d:<   |j                  d3      |d;<   |j                  d5      |d<<   d=|d&<   |	rt        |	      |d><   |S )?a  
        Method to convert values for create_params API when discovery specific paramters
        are passed as input.

        Parameters:
            - new_object_params: The dictionary storing various parameters for calling the
                                 start discovery API

        Returns:
            - new_object_params: The dictionary storing various parameters for calling the
                                 start discovery API in an updated fashion
        r   r'   rb   http_read_credentialhttp_write_credentialsnmp_v2_read_credentialsnmp_v2_write_credentialsnmp_v3_credentialnet_conf_portz8Device Specific ClI credentials must be passed as a listrN   rf   passwordenable_passwordzZusername, password and enable_password must be passed toether for creating CLI credentialsuserNameListpasswordListenablePasswordListzAThe password for the HTTP read credential must be of string type.zAThe username for the HTTP read credential must be of string type.r   z>The port for the HTTP read Credential must be of integer type.securez8Secure for HTTP read Credential must be of type boolean.httpReadCredentialzBThe password for the HTTP write credential must be of string type.zBThe username for the HTTP write credential must be of string type.z?The port for the HTTP write Credential must be of integer type.z9Secure for HTTP write Credential must be of type boolean.httpWriteCredentialre   zGName/description for the SNMP v2 read credential must be of string type	communityz+The community string must be of string typesnmpROCommunityDescsnmpROCommunityv2snmpVersionzHName/description for the SNMP v2 write credential must be of string typesnmpRWCommunityDescsnmpRWCommunityz3Username of SNMP v3 protocol must be of string type	snmp_modezKMode of SNMP is madantory to use SNMPv3 protocol and must be of string typeAUTHPRIV
AUTHNOPRIVauth_passwordz-Authorization password must be of string type	auth_typez)Authorization type must be of string typeprivacy_typez#Privacy type must be of string typeprivacy_passwordz'Privacy password must be of string typesnmpUserNamesnmpModesnmpAuthPassphrasesnmpAuthProtocolsnmpPrivProtocolsnmpPrivPassphrasev3netconfPort)
r@   r?   rt   r   ru   rR   rv   r   r   r#   )r   new_object_paramsr'   rb   r   r   r   r   r   r   r=   username_listpassword_listenable_password_listrz   s                  r   %handle_discovery_specific_credentialsz/Discovery.handle_discovery_specific_credentialss  sM    *.)>)>q)A)E)EFf)g&=AABXY=AABXY > B BCZ ["@"D"DE^"_#A#E#EF`#a ;??@TU6::?K2D9P444='(1, " "')$ 4 FH||J/HLL4LQYQ]Q]^oQp%,,X\\*-EF%,,X\\*-EF,33HLLAR4STz<<<EF 5B!.14A!.1:N!"67(,,Z8ZH\H`H`akHlnq=rY444=(,,Z8ZH\H`H`akHlnq=rY444=(,,V4DXD\D\]cDdfi9jV444=266x@$GP444=6J23 )--j9jI^IbIbcmInps>tZ444=)--j9jI^IbIbcmInps>tZ444=)--f5*EZE^E^_eEfhk:lW444=377A4HQ444=7L34"+//>JOfOjOjkxOy{~D_444=+//<*MdMhMhitMuwzB{C444=7N7R7RS`7a343J3N3N{3[/0/3m,#,00?ZPhPlPlmzP{  ~A  FB`444=,00=:NfNjNjkvNwy|C}C444=7O7S7STa7b343K3O3OP[3\/0/3m,&**:6JGYG]G]^hGikn<oK444=&**;7ZHZH^H^_jHkmp=qc444=&**;7JFJ\J`J`alJmq}J}.22?CTfTjTjkzT{  ~A  JBM<<<E.22;?ZPbPfPfgrPsuxEyI<<<E)--k:jH 2 6 6~ FJWiWmWmn|W}  @C  MD"GC @@S@I 2 6 67I JPZ[m[q[q  sE  \F  HK  QL"KC @@S@I0B0F0Fz0Rn-,>,B,B;,Oj)6H6L6L_6]234F4J4J;4W014F4J4J>4Z016H6L6LM_6`23/3m,/2=/Am,  r   c                    g }i }| j                   d   j                  d      |d<   | j                   d   j                  d      |d<   ||d<   | j                   d   j                  d      |d<   | j                   d   j                  d	      |d
<   | j                   d   j                  d      |d<   | j                   d   j                  d      |d<   | j                   d   j                  d      |d<   | j                   d   j                  d      |d<   | j                   d   j                  d      |d<   | j                   d   j                  d      r| j                  |       | j                   d   j                  d      }i }|du r;| j                         }|j	                         D ]  }|j                  |        ||d<   | j                  dj                  t        |            d       |j                  d      si|j                  d      sX|j                  d      sG|j                  d      s6|j                  d      s%|j                  d      sd }| j                  |!       |j                  d"      s%|j                  d#      sd$}| j                  |!       | j                  d%j                  t        |            d&       |S )'aF  
        Create a new parameter object based on the validated configuration,
        credential IDs, and IP address list.

        Parameters:
          - credential_ids: The list of credential IDs to include in the
                            parameters. If not provided, an empty list is used.
          - ip_address_list: The list of IP addresses to include in the
                             parameters. If not provided, None is used.

        Returns:
          - new_object_params: A dictionary containing the newly created
                               parameters.
        r   r$   cdpLevelr4   discoveryTypeipAddressListr(   ipFilterListr)   	lldpLevelr*   namer,   preferredMgmtIPMethodr0   protocolOrderr-   r.   r'   )r   r1   TglobalCredentialIdListz>All the global credentials used for the discovery task are {0}r   r   r   r   rm   ro   rq   zEPlease provide atleast one valid SNMP credential to perform DiscoveryrN   r   rc   zDPlease provide atleast one valid CLI credential to perform DiscoveryzEThe payload/object created for calling the start discovery API is {0}r;   )
r@   r?   r   r   valuesextendrA   rB   r   ru   )r   r3   credential_idsr   global_cred_flagrx   global_cred_listr=   s           r   create_paramszDiscovery.create_params  s     (,(=(=a(@(D(D[(Q*%-1-B-B1-E-I-IJZ-[/*-</*,0,A,A!,D,H,HIY,Z.))-)>)>q)A)E)El)S+&$($9$9!$<$@$@AQ$R&!595J5J15M5Q5QRl5m12-1-B-B1-E-I-IJZ-[/*%)%:%:1%=%A%A'%J'"'+'<'<Q'?'C'CI'N)$  #''(HI66IZ6[003778PQ!#t#%)%L%L%N"$:$A$A$C 8 %%&678:H67QXXY\]sYtuw~!%%n59J9N9NOd9eizi~i~  @U  jV)--m<@V@Z@Z[i@j  oE  oI  oI  JR  oSYC00S09!%%n59O9S9STc9dXC00S09X__`cdu`vwy  	A  r   c                     | j                   d   dd| j                  |      d      }| j                  dj                  t	        |            d       | j
                  j                  t        |	             | j                  d
j                  |j                  j                  d            d       |j                  j                  d      S )a  
        Start a new discovery process in the Cisco Catalyst Center. It creates the
        parameters required for the discovery and then calls the
        'start_discovery' function. The result of the discovery process
        is added to the 'result' attribute.

        Parameters:
          - credential_ids: The list of credential IDs to include in the
                            discovery. If not provided, an empty list is used.
          - ip_address_list: The list of IP addresses to include in the
                             discovery. If not provided, None is used.

        Returns:
          - task_id: The ID of the task created for the discovery process.
        r   r   start_discoveryr3   Tr   z?The response received post discovery creation API called is {0}r   )discovery_resultz&Task Id of the API task created is {0}taskIdr;   )
r   r   rA   rB   r   r   r   r   rw   r?   )r   r3   r   s      r   create_discoveryzDiscovery.create_discovery-  s    " )(&%%o%F	
 	RYYZ]^dZefhop4899@@ATATU]A^_agh""8,,r   c                    d}t        |      }	  | j                  d   dd|d      }|j                  }| j                  dj	                  t        |      t        |      t        |j                  d	                  d
       |j                  d	      s5t        j                  d|j                  d      t        j                        rPdj	                  ||j                  d            }| j                  |d       | j                  j                  |       y| j                  dj	                  t        |      t        |            d
       |j                  d      }	 t        |      }d}| j                  dd
       | j                  j                  t        |             |S # t        $ r8 | j                  dj	                  |             t!        j"                  d       Y nw xY w)a  
        Monitor the status of a task of creation of dicovery in the Cisco Catalyst Center.
        It checks the task status periodically until the task is no longer 'In Progress'
        or other states. If the task encounters an error or fails, it immediately fails the
        module and returns False.

        Parameters:
          - task_id: The ID of the task to monitor.

        Returns:
          - result: True if the task completed successfully, False otherwise.
        Ftask_idTr   taskget_task_by_idr   5Task status for the task id {0} is {1}, is_error: {2}isErrorr;   r:   progressflags:Discovery task with id {0} has not completed - Reason: {1}failureReasonrM   rN   ?Task status for the task id (before checking status) {0} is {1}"The discovery process is completeddiscovery_taskjThe progress status is {0}, continue to check the status after 3 seconds. Putting into sleep for 3 seconds   )r   r   rw   rA   rB   r   r?   research
IGNORECASEr   rT   r   r   r   	Exceptiontimesleep)r   r   r   r   rw   r=   r   progress_values           r   get_merged_task_statusz Discovery.get_merged_task_statusK  s    g&.tv.) 	H  ((HHHLSSTWX_T`befnboqtu}  vB  vB  CL  vM  rN  O  QW  X||I&"))(,,z2"--+ SYYX\\/:<j)%%#%.HHV]]^abi^jlopxlyz  }C  D||J/H!$X=vF""4x#@A   F  M  M  NV  W  X

15 s   AF$ $>G%$G%c                    d}t        |      }	  | j                  d   dd|d      }|j                  }| j                  dj	                  t        |      t        |      t        |j                  d	                  d
       |j                  d	      s5t        j                  d|j                  d      t        j                        rPdj	                  ||j                  d            }| j                  |d       | j                  j                  |       y| j                  dj	                  t        |      t        |            d
       |j                  d      }t        j                  d|j                  d            r;d}| j                  dd
       | j                  j                  t        |             |S | j                  dj	                  |             t        j                  d       )a  
        Monitor the status of a task of deletion of dicovery in the Cisco Catalyst Center.
        It checks the itask status periodically until the task is 'Discovery deleted successfully'.
        If the task encounters an error or fails, it immediately fails the module and returns False.

        Parameters:
          - task_id: The ID of the task to monitor.

        Returns:
          - result: True if the task completed successfully, False otherwise.
        Fr   Tr   r   r   r   r   r   r;   r:   r   r   r   r   rM   rN   r   zDiscovery deleted successfully.r   r   r   r  )r   r   rw   rA   rB   r   r?   r  r  r  r   rT   r   r   r  r  )r   r   r   r   rw   r=   r   s          r   get_deleted_task_statusz!Discovery.get_deleted_task_statusy  s    g&.tv.) 	H  ((HHHLSSTWX_T`befnboqtu}  vB  vB  CL  vM  rN  O  QW  X||I&"))(,,z2"--+ SYYX\\/:<j)%%#%.HHV]]^abi^jlopxlyz  }C  D||J/Hyy:HLL<TU=vF""4x#@AHH  B  I  I  JR  S  TJJqM7 r   c                      j                   d   j                  d      } j                   d   j                  d      }dg i}|dkD  rz|dz  }t        d|dz         D ]b  }t        d|dz  z   d j                   d   j                  d            }  j                  d	   d
d|d      }|d   j                  |d          d n{t         j                   d   j                  d       j                   d   j                  d       j                   d   j                  d            }  j                  d	   d
d|d      } j                  dj                  t        |            d       t        t         fd|j                  d            d      S )aI  
        Retrieve a specific discovery by name from a range of
        discoveries in the Cisco Catalyst Center.

        Returns:
          - discovery: The discovery with the specified name from the range
                       of discoveries. If no matching discovery is found, it
                       returns None.
        r   r%   r&   rw   i  r   r   )r%   r&   r   r   r   get_discoveries_by_rangeTr   z4Response of the get discoveries via range API is {0}r   c                 L    | d   j                   d   j                  d      k(  S )Nr   r   r*   )r@   r?   )xr   s    r   <lambda>z>Discovery.lookup_discovery_by_range_via_name.<locals>.<lambda>  s'    !F)t'<'<Q'?'C'CDT'UU r   N)r@   r?   rV   r   r   r   rA   rB   r   nextfilter)r   r%   r&   rw   num_intervalsnumr   response_parts   `       r   "lookup_discovery_by_range_via_namez,Discovery.lookup_discovery_by_range_via_name  s    ++A.22=A 11!4889LM#s"-4MQ 12 G !C#I&) 11!488C
 !8 7&7! $	! $++M*,EFG  11!488G"&"7"7":">">?R"S--a044Y?F /tv."3 	H 	GNNsS[}]_fgUZ( 	
 	
r   c                    d}d}| j                         }|sndj                  t        | j                  d   j	                  d            t        |            }| j                  |d       | j                  j                  |       	 | j                         }|j	                  d      }|d	k(  rd}n|d
k(  rd}nt        j                  d       G|s|du redj                  t        | j                  d   j	                  d                  }| j                  |d       | j                  j                  |       nndj                  t        | j                  d   j	                  d            t        |            }| j                  |d       | j                  j                  |       | j                  j                  t        |             |S )a  
        Continuously retrieve a specific discovery by name from a range of
        discoveries in the Cisco Catalyst Center until the discovery is complete.

        Returns:
          - discovery: The completed discovery with the specified name from
                       the range of discoveries. If the discovery is not
                       found or not completed, the function fails the module
                       and returns None.
        FzECannot find any discovery task with name {0} -- Discovery result: {1}r   r*   r;   rN   TdiscoveryConditionCompleteAbortedr  z9Discovery with name {0} is aborted by the user on the GUIrM   )discovery_range)r  rB   r   r@   r?   rA   r   rT   r  r  r   r   r   )r   r   abortedr   r=   discovery_conditions         r   &get_discoveries_by_range_until_successz0Discovery.get_discoveries_by_range_until_success  s    ;;=	Y``D))!,001ABCS^UCHHS&!KK!!c!*??AI"+--0D"E"j0$	1JJqM  $QXXY\]a]r]rst]u]y]y  {K  ^L  ZM  Nj)%%#%.]dd--a0445EFGYYj)%%#%.4	:;r   c                 <   t        ||| j                  d   j                  d            }d}d}	  | j                  d   dd|d	      }|j                  }| j                  d
j                  t        |            d       t        d |D              rd}| j                  dd       not        d |D              rd}| j                  dd       nHt        d |D              rd}| j                  dd       n!|dz  }|dk(  rnt        j                  d       |s?dj                  |      }| j                  |d       | j                  j                  |       | j                  dj                  |      d       | j                  j                  t        |             |S )a   
        Retrieve the information of devices discovered by a specific discovery
        process in the Cisco Catalyst Center. It checks the reachability status of the
        devices periodically until all devices are reachable or until a
        maximum of 3 attempts.

        Parameters:
          - discovery_id: ID of the discovery process to retrieve devices from.
          - task_id: ID of the task associated with the discovery process.

        Returns:
          - result: True if all devices are reachable, False otherwise.
        r   r   )rg   r   r   FTr   r   .get_discovered_network_devices_by_discovery_idr   z\Retrieved device details using the API 'get_discovered_network_devices_by_discovery_id': {0}r   c              3   D   K   | ]  }|j                  d       dk(    ywreachabilityStatusSuccessNr?   .0ress     r   	<genexpr>z6Discovery.get_discovery_device_info.<locals>.<genexpr>'  s     Q#377/0I=Q    z&All devices in the range are reachabler;   c              3   D   K   | ]  }|j                  d       dk(    ywr"  r%  r&  s     r   r)  z6Discovery.get_discovery_device_info.<locals>.<genexpr>,       SCSWW12i?Sr*  z'Some devices in the range are reachablec              3   D   K   | ]  }|j                  d       dk7    ywr"  r%  r&  s     r   r)  z6Discovery.get_discovery_device_info.<locals>.<genexpr>1  r,  r*  z9All devices are not reachable, but discovery is completedr7   r   r  z6Discovery network device with id {0} has not completedrM   rN   z2Discovery network device with id {0} got completed)discovery_device_info)r   r@   r?   r   rw   rA   rB   r   allanyr  r  r   rT   r   r   )	r   discovery_idr   r   r   countrw   devicesr=   s	            r   get_discovery_device_infoz#Discovery.get_discovery_device_info  s    ))!,00;

 .tv."I 	H ''GHHszz{~  @G  |H  I  KR  SQQQA6JS7SSBFKS7SSTV_`QJEzJJqM; > JQQR^_CHHS*%KK!!c!*ELL\Z\bc4g>?r   c                     | j                         }|s&| j                  j                  t        |             yt        |      }|| _        | j                  j                  t        |             |S )a  
        Retrieve an existing discovery by its name from a range of discoveries.

        Returns:
          - discovery: The discovery with the specified name from the range of
                       discoveries. If no matching discovery is found, it
                       returns None and updates the 'exist_discovery' entry in
                       the result dictionary to None.
        )exist_discoveryN)r  r   r   r   have)r   r   r7  s      r   get_exist_discoveryzDiscovery.get_exist_discoveryE  s]     ;;=	KKtI>?I.	4	:;r   c                 |    | j                   d   dd|d      }| j                  dj                  t        |            d       | j                  j                  t        |             | j                  d	j                  |j                  j                  d
            d       |j                  j                  d
      S )a]  
        Delete an existing discovery in the Cisco Catalyst Center by its ID.

        Parameters:
          - params: A dictionary containing the parameters for the delete
                    operation, including the ID of the discovery to delete.

        Returns:
          - task_id: The ID of the task created for the delete operation.
        r   r   delete_discovery_by_idTr   z9Response collected from API 'delete_discovery_by_id': {0}r   )delete_discoveryz#Task Id of the deletion task is {0}r   r;   )	r   rA   rB   r   r   r   r   rw   r?   )r   r   rw   s      r   delete_exist_discoveryz Discovery.delete_exist_discoveryY  s     +4??6*-	
 	LSSTWX`Tabdkl4:;6==h>O>O>S>ST\>]^`fg  $$X..r   c                    | j                          | j                         }| j                  |      }| j                         }|r?t	        |j                  d            }| j                  |      }| j                  |      }| j                  |      }| j                  |      }| j                         }| j                  |j                  d            }d| j                  d<   d	| j                  d
<   | j                  | j                  d<   || j                  d<   | j                  j                  t	        d	             | j                  | j                  d
   d       | S )ax  
        Retrieve the information of devices discovered by a specific discovery
        process in the Cisco Catalyst Center, delete existing discoveries if they exist,
        and create a new discovery. The function also updates various
        attributes of the class instance.

        Returns:
          - self: The instance of the class with updated attributes.
        rg   rg   r   r   r   )r1  TchangedzDiscovery Created Successfullyr=   diffrw   rN   r;   )r]   r   r   r8  r   r?   r<  r  r   r	  r  r4  r   r@   r   rA   )	r   devices_list_infor3   r6  r   discovery_task_idcomplete_discoverydiscovery_task_infor   s	            r   get_diff_mergedzDiscovery.get_diff_mergedq  sN    	&&( 668::;LM224_0067F $ ; ;6 ; J!%!=!=FW!=!X 11+ 2 -!88AR8S"IIK//=P=T=TUY=Z/[!%I=E"33F"3J4$DEFU#V,r   c                    | j                   d   j                  d      r | j                  d   dd      }|j                  d      dk(  rAd}|| j                  d	<   | j	                  |d
       | j                   d   | j                  d<   | S  | j                  d   dd      }|j                  d      j                  d      }d| j                  d<   d| j                  d	<   | j                   | j                  d<   n| j                         }|s[dj                  | j                   d   j                  d            | j                  d	<   | j	                  | j                  d	   d       | S t        |j                  d            }| j                  |      }| j                  |      }d| j                  d<   d| j                  d	<   | j                   | j                  d<   || j                  d<   | j	                  | j                  d	   d       | S )au  
        Delete an existing discovery in the Cisco Catalyst Center by its name, and
        updates various attributes of the class instance. If no
        discovery with the specified name is found, the function
        updates the 'msg' attribute with an appropriate message.

        Returns:
          - self: The instance of the class with updated attributes.
        r   r6   r   r   get_count_of_all_discovery_jobsr   r   rw   zHThere are no discoveries present in the Discovery Dashboard for deletionr=   r7   delete_all_discoveryr   Tr@  z+All of the Discoveries Deleted SuccessfullyrA  zDiscovery {0} Not Foundr*   r9   rg   r>  r?  r   zSuccessfully deleted discoveryr;   )
r@   r?   r   r   rA   r8  rB   r   r<  r  )r   count_discoveriesr=   delete_all_responserC  r6  r   rD  s           r   get_diff_deletedzDiscovery.get_diff_deleted  s      #''5 7 7":! !$$Z0A5`%(E"i(*.*?*?*BJ'"9$//&"9"/# !4 7 7
 C G G Q%)DKK	"!NDKK"&"7"7DKK #668O"%>%E%E))!,001AB&DE"U+W5_0067F $ ; ;6 ; J!%!=!=FW!=!X%)DKK	"!ADKK"&"7"7DKK&7DKK
#U#V,r   c                    | j                  dj                  t        | j                              d       | j                  dj                  t        |            d       | j	                         }|j                  d      }t        |      } | j                  d   dd|d	
      }|j                  d      }|r"| j                  dj                  |      d       n!| j                  dj                  |      d       d| _        | S )a  
        Verify the merged status(Creation/Updation) of Discovery in Cisco Catalyst Center.
        Args:
            - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
            - config (dict): The configuration details to be verified.
        Return:
            - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
        Description:
            This method checks the merged status of a configuration in Cisco Catalyst Center by
            retrieving the current state (have) and desired state (want) of the configuration,
            logs the states, and validates whether the specified device(s) exists in the DNA
            Center configuration's Discovery Database.
        Current State (have): {0}r;   Desired State (want): {0}rg   r>  r   r   get_discovery_by_idTr   r*   z.Requested Discovery with name {0} is completedz2Requested Discovery with name {0} is not completedr7   r   )	rA   rB   r   r7  r  r?   r   r   r>   )r   r<   rE  r1  r   rw   r*   s          r   verify_diff_mergedzDiscovery.verify_diff_merged  s     	,33C		NCVL,33CK@&I"IIK*..t4
 +4??6**	
  $45HHELL^\^de HHIPPQ_`bklr   c                 V   | j                  dj                  t        | j                              d       | j                  dj                  t        |            d       |j	                  d      du rJ | j
                  d   dd	      }|d
k(  r| j                  dd       n| j                  dd       d| _        | S | j                         }|j	                  d      }|r"| j                  dj                  |      d       n!| j                  dj                  |      d       d| _        | S )a  
        Verify the deletion status of Discovery in Cisco Catalyst Center.
        Args:
            - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
            - config (dict): The configuration details to be verified.
        Return:
            - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
        Description:
            This method checks the deletion status of a configuration in Cisco Catalyst Center.
            It validates whether the specified discovery(s) exists in the Cisco Catalyst Center configuration's
            Discovery Database.
        rO  r;   rP  r6   Tr   r   rH  rI  r   zAll discoveries are deletedzAll discoveries are not deletedr7   r   r*   z,Requested Discovery with name {0} is presentz<Requested Discovery with name {0} is not present and deleted)rA   rB   r   r7  r?   r   r>   r  )r   r<   rK  rE  r*   s        r   verify_diff_deletedzDiscovery.verify_diff_deleted  s    	,33C		NCVL,33CK@&I::l#t+ 7 7":! !A%6?:IF#DKK"EEG$45HHCJJ>Z\ef HHSZZ[ijlrsr   )N)NN)__name__
__module____qualname__r   rH   r]   r`   r   r   r   r   r   ru   r   r   r   r	  r  r  r  r4  r8  r<  rF  rM  rR  rT  __classcell__)r   s   @r   r
   r
     s    !$L\#DJ#t&l.&`>$@\'!B7!r-<,\*X1
f-^<|(/0B1f%N&r   r
   c                  :   i ddddddddddd	d
g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)} t        | d*      }t        |      }|j                  j                  d      }|j                  j                  d&      }||j                  vr-d+|_        d,j                  |      |_        |j                          |j                  |-      j                          |j                  D ]Z  }|j                           |j                  |          j                          |s8 |j                  |   |      j                          \  |j                  d/i |j                   y.)0z+ main entry point for module execution
    	dnac_hostTr   )r   r   	dnac_port443)r   r   dnac_usernameadminuser)r   r   aliasesdnac_password)r   no_logdnac_verifyr#   Truednac_versionz2.2.3.3
dnac_debugFdnac_logdnac_log_levelr7   dnac_log_file_pathzdnac.logdnac_log_appendvalidate_response_schemaconfig_verifydnac_api_task_timeoutr   i  dnac_task_poll_intervalrL   r<   r   r   )r   r   r    rD   r2   r5   )r   choices)argument_specsupports_check_modeinvalidzState {0} is invalid)rD   N )r   r
   r   r?   supported_statesr>   rB   r=   check_return_statusrH   r@   reset_valuesget_diff_state_applyverify_diff_state_apply	exit_jsonr   )element_specr   ccc_discoveryrl  rD   r<   s         r   mainr|    sC   KdE!B %E!B#eU[T\%] $et%D "Fv#F	
 #Uy$I !6e"D E B %u&K )5Z*P &4'H /D0Q $f%G ,e-M .!/L 4VT  x>ST!L& /46F f%M!((,,_=M  $$W-EM222(299%@))+  u -AAC00 W""$1**513GGI8M11%8@TTV	W F,}++,r   __main__)
__future__r   r   r   r   __metaclass__
__author__DOCUMENTATIONEXAMPLESRETURNansible.module_utils.basicr   8ansible_collections.cisco.dnac.plugins.module_utils.dnacr   r   r  r  r
   r|  rU  rs  r   r   <module>r     sm   
 A @D
GPZv#
L 5  	x xv#*-Z zF r   