
    VhB                       d dl mZ d dlmZ d dlmZ d dlmZ d dlm	Z	 d dl
mZ d dlmZ 	 d dlmZ d d	lmZmZmZ d
ZdZ	 d dlmZmZmZmZ d Z G d de	      Z y# e$ rZdZeZY dZ[*dZ[ww xY w# e$ r d dlmZmZmZmZ Y 8w xY w)    )annotations)abstractmethodwraps)AnsibleError)AnsiblePlugin)	to_native)missing_required_lib)RPCError)to_xmlto_ele	NCElementTNF)Element
SubElementtostring
fromstringc                .     t                fd       }|S )Nc                t    t         s&t        t        d      dt        t                     | g|i |S )Nncclientz: )HAS_NCCLIENTr   r
   r	   NCCLIENT_IMP_ERR)selfargskwargsfuncs      P/home/dcms/DCMS/lib/python3.12/site-packages/ansible/plugins/netconf/__init__.pywrappedz ensure_ncclient.<locals>.wrapped0   s7    +?
+KYWgMhijjD*4*6**    r   )r   r   s   ` r   ensure_ncclientr   /   s     
4[+ + Nr   c                       e Zd ZdZg dZ fdZed        Zd ZddZ	ddZ
ddZdd	Zd
 ZddZddZddZd ZddZddZd Zd Zed        Zed        Zd Zd Zd Zd Z xZS )NetconfBasea	  
    A base class for implementing Netconf connections

    .. note:: Unlike most of Ansible, nearly all strings in
        :class:`TerminalBase` plugins are byte strings.  This is because of
        how close to the underlying platform these plugins operate.  Remember
        to mark literal strings as byte string (``b"string"``) and to use
        :func:`~ansible.module_utils.common.text.converters.to_bytes` and
        :func:`~ansible.module_utils.common.text.converters.to_text` to avoid unexpected
        problems.

        List of supported rpc's:
            :get: Retrieves running configuration and device state information
            :get_config: Retrieves the specified configuration from the device
            :edit_config: Loads the specified commands into the remote device
            :commit: Load configuration from candidate to running
            :discard_changes: Discard changes to candidate datastore
            :validate: Validate the contents of the specified configuration.
            :lock: Allows the client to lock the configuration system of a device.
            :unlock: Release a configuration lock, previously obtained with the lock operation.
            :copy_config: create or replace an entire configuration datastore with the contents of another complete
                          configuration datastore.
            :get-schema: Retrieves the required schema from the device
            :get_capabilities: Retrieves device information and supported rpc methods

            For JUNOS:
            :execute_rpc: RPC to be execute on remote device
            :load_configuration: Loads given configuration on device

        Note: rpc support depends on the capabilities of remote device.

        :returns: Returns output received from remote device as byte string
        Note: the 'result' or 'error' from response should to be converted to object
              of ElementTree using 'fromstring' to parse output as xml doc

              'get_capabilities()' returns 'result' as a json string.

            Usage:
            from ansible.module_utils.connection import Connection

            conn = Connection()
            data = conn.execute_rpc(rpc)
            reply = fromstring(reply)

            data = conn.get_capabilities()
            json.loads(data)

            conn.load_configuration(config=[''set system ntp server 1.1.1.1''], action='set', format='text')
    )rpc
get_configgetedit_configvalidatecopy_configdispatchlockunlockdiscard_changescommit
get_schemadelete_configget_device_operationsc                8    t         t        |           || _        y N)superr!   __init___connection)r   
connection	__class__s     r   r3   zNetconfBase.__init__n   s    k4)+%r   c                .    | j                   j                  S r1   )r4   managerr   s    r   mzNetconfBase.mr   s    '''r   c                    	 t        |      }| j                  j                  |      }t        |d      r|j                  S |j
                  S # t        $ r%}|j
                  }t        t        |            d}~ww xY w)z
        RPC to be execute on remote device
        :param name: Name of rpc in string format
        :return: Received rpc response from remote host
        data_xmlN)	r   r:   r"   hasattrr<   xmlr   	Exceptionr   )r   nameobjrespexcmsgs         r   r"   zNetconfBase.rpcv   se    	),C66::c?D$+D*$=4==K488K 	)''CF3K((	)s   =A  A 	A: A55A:c                    t        |t              rt        |      }|sd}| j                  j	                  ||      }t        |d      r|j                  S |j                  S )a  
        Retrieve all or part of a specified configuration
        (by default entire configuration is retrieved).
        :param source: Name of the configuration datastore being queried, defaults to running datastore
        :param filter: This argument specifies the portion of the configuration data to retrieve
        :return: Returns xml string containing the RPC response received from remote host
        runningsourcefilterr<   )
isinstancelisttupler:   r#   r=   r<   r>   )r   rH   rI   rB   s       r   r#   zNetconfBase.get_config   sT     fd#6]FFvv  v > 'j 9t}}GtxxGr   c                    t        |t              rt        |      }| j                  j	                  ||      }t        |d      r|j                  }|S |j                  }|S )a  
        Retrieve device configuration and state information.
        :param filter: This argument specifies the portion of the state data to retrieve
                       (by default entire state data is retrieved)
        :param with_defaults: defines an explicit method of retrieving default values
                              from the configuration
        :return: Returns xml string containing the RPC response received from remote host
        )rI   with_defaultsr<   )rJ   rK   rL   r:   r$   r=   r<   r>   )r   rI   rN   rB   responses        r   r$   zNetconfBase.get   sV     fd#6]Fvvzz}zE$+D*$=4== DH88r   c                    |t        d      | j                  j                  ||||||      }t        |d      r|j                  S |j
                  S )a  
        Loads all or part of the specified *config* to the *target* configuration datastore.
        :param config: Is the configuration, which must be rooted in the `config` element.
                       It can be specified either as a string or an :class:`~xml.etree.ElementTree.Element`.
        :param format: The format of configuration eg. xml, text
        :param target: Is the name of the configuration datastore being edited
        :param default_operation: If specified must be one of { `"merge"`, `"replace"`, or `"none"` }
        :param test_option: If specified must be one of { `"test_then_set"`, `"set"` }
        :param error_option: If specified must be one of { `"stop-on-error"`, `"continue-on-error"`, `"rollback-on-error"` }
                             The `"rollback-on-error"` *error_option* depends on the `:rollback-on-error` capability.
        :return: Returns xml string containing the RPC response received from remote host
        zconfig value must be provided)formattargetdefault_operationtest_optionerror_optionr<   )
ValueErrorr:   r%   r=   r<   r>   )r   configrQ   rR   rS   rT   rU   rB   s           r   r%   zNetconfBase.edit_config   s]     ><==vv!!&Zk  zE/; " = 'j 9t}}GtxxGr   c                    | j                   j                  |      }t        |d      r|j                  S |j                  S )aS  
        Validate the contents of the specified configuration.
        :param source: Is the name of the configuration datastore being validated or `config` element
                       containing the configuration subtree to be validated
        :return: Returns xml string containing the RPC response received from remote host
        )rH   r<   )r:   r&   r=   r<   r>   )r   rH   rB   s      r   r&   zNetconfBase.validate   s4     vvf- 'j 9t}}GtxxGr   c                    | j                   j                  ||      }t        |d      r|j                  S |j                  S )a  
        Create or replace an entire configuration datastore with the contents of another complete configuration datastore.
        :param source: Is the name of the configuration datastore to use as the source of the copy operation or `config`
                       element containing the configuration subtree to copy
        :param target: Is the name of the configuration datastore to use as the destination of the copy operation
        :return: Returns xml string containing the RPC response received from remote host
        r<   )r:   r'   r=   r<   r>   )r   rH   rR   rB   s       r   r'   zNetconfBase.copy_config   s6     vv!!&&1 'j 9t}}GtxxGr   c                   |t        d      | j                  j                  t        |      ||      }t	        |t
              r|j                  }|S t        |d      r|j                  r|j                  }|S |j                  }|S )a  
        Execute rpc on the remote device eg. dispatch('clear-arp-table')
        :param rpc_command: specifies rpc command to be dispatched either in plain text or in xml element format (depending on command)
        :param source: name of the configuration datastore being queried
        :param filter: specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
        :return: Returns xml string containing the RPC response received from remote host
        z"rpc_command value must be providedrG   data_ele)
rV   r:   r(   r   rJ   r   r<   r=   r[   r>   )r   rpc_commandrH   rI   rB   results         r   r(   zNetconfBase.dispatch   s     ABBvvz+6vfUdI& ]]F  T:&4== ]]F
  XXFr   c                    | j                   j                  |      }t        |d      r|j                  S |j                  S )a.  
        Allows the client to lock the configuration system of a device.
        :param target: is the name of the configuration datastore to lock,
                        defaults to candidate datastore
        :return: Returns xml string containing the RPC response received from remote host
        rR   r<   )r:   r)   r=   r<   r>   r   rR   rB   s      r   r)   zNetconfBase.lock   s4     vv{{&{) 'j 9t}}GtxxGr   c                    | j                   j                  |      }t        |d      r|j                  S |j                  S )a:  
        Release a configuration lock, previously obtained with the lock operation.
        :param target: is the name of the configuration datastore to unlock,
                       defaults to candidate datastore
        :return: Returns xml string containing the RPC response received from remote host
        r_   r<   )r:   r*   r=   r<   r>   r`   s      r   r*   zNetconfBase.unlock   s4     vv}}F}+ 'j 9t}}GtxxGr   c                ~    | j                   j                         }t        |d      r|j                  S |j                  S )z
        Revert the candidate configuration to the currently running configuration.
        Any uncommitted changes are discarded.
        :return: Returns xml string containing the RPC response received from remote host
        r<   )r:   r+   r=   r<   r>   )r   rB   s     r   r+   zNetconfBase.discard_changes   s2     vv%%' 'j 9t}}GtxxGr   c                    | j                   j                  |||      }t        |d      r|j                  S |j                  S )az  
        Commit the candidate configuration as the device's new current configuration.
        Depends on the `:candidate` capability.
        A confirmed commit (i.e. if *confirmed* is `True`) is reverted if there is no
        followup commit within the *timeout* interval. If no timeout is specified the
        confirm timeout defaults to 600 seconds (10 minutes).
        A confirming commit may have the *confirmed* parameter but this is not required.
        Depends on the `:confirmed-commit` capability.
        :param confirmed: whether this is a confirmed commit
        :param timeout: specifies the confirm timeout in seconds
        :param persist: make the confirmed commit survive a session termination,
                        and set a token on the ongoing confirmed commit
        :return: Returns xml string containing the RPC response received from remote host
        )	confirmedtimeoutpersistr<   )r:   r,   r=   r<   r>   )r   rd   re   rf   rB   s        r   r,   zNetconfBase.commit  s8     vv}}y'7}S 'j 9t}}GtxxGr   c                    | j                   j                  |||      }t        |d      r|j                  S |j                  S )ae  
        Retrieve a named schema, with optional revision and type.
        :param identifier: name of the schema to be retrieved
        :param version: version of schema to get
        :param format: format of the schema to be retrieved, yang is the default
        :return: Returns xml string containing the RPC response received from remote host
        )versionrQ   r<   )r:   r-   r=   r<   r>   )r   
identifierrh   rQ   rB   s        r   r-   zNetconfBase.get_schema  s;     vv  WV L 'j 9t}}GtxxGr   c                    | j                   j                  |      }t        |d      r|j                  S |j                  S )z
        delete a configuration datastore
        :param target: specifies the  name or URL of configuration datastore to delete
        :return: Returns xml string containing the RPC response received from remote host
        r<   )r:   r.   r=   r<   r>   r`   s      r   r.   zNetconfBase.delete_config   s4     vv##F+ 'j 9t}}GtxxGr   c                8    | j                   j                  |      S r1   )r:   locked)r   rR   s     r   rl   zNetconfBase.locked)  s    vv}}V$$r   c                     y)z
        Retrieves device information and supported
        rpc methods by device platform and return result
        as a string
        :return: Netconf session capability
        N r9   s    r   get_capabilitieszNetconfBase.get_capabilities,  s     	r   c                     y)z
        Identifies the operating system of network device.
        :param obj: ncclient manager connection instance
        :return: The name of network operating system.
        Nrn   )rA   s    r   guess_network_oszNetconfBase.guess_network_os6       	r   c                    | j                   S )zs
        Returns list of base rpc method supported by remote device
        :return: List of RPC supported
        )__rpc__r9   s    r   get_base_rpczNetconfBase.get_base_rpc?  s    
 ||r   c                     y)z
        Copies file to remote host
        :param source: Source location of file
        :param destination: Destination file path
        :return: Returns xml string containing the RPC response received from remote host
        Nrn   r   rH   destinations      r   put_filezNetconfBase.put_fileF  rr   r   c                     y)z
        Fetch file from remote host
        :param source: Source location of file
        :param destination: Source location of file
        :return: Returns xml string containing the RPC response received from remote host
        Nrn   rw   s      r   
fetch_filezNetconfBase.fetch_fileO  rr   r   c                P   i }dj                  |      }d|v |d<   d|v |d<   d|v |d<   d|v |d	<   d
|v |d<   d|v |d<   d|v |d<   g |d<   |d   r|d   j                  d       |d   r|d   j                  d       |d	   r|d   j                  d       t        |d         |d<   |S )z
        Retrieve remote host capability from Netconf server hello message.
        :param server_capabilities: Server capabilities received during Netconf session initialization
        :return: Remote host capabilities in dictionary format
        
z
:candidatesupports_commitz:with-defaultssupports_defaultsz:confirmed-commitsupports_confirm_commitz:startupsupports_startupz:xpathsupports_xpathz:writable-runningsupports_writable_runningz	:validatesupports_validatelock_datastorerF   	candidatestartupsupports_lock)joinappendbool)r   server_capabilities
operationscapabilitiess       r   r/   z!NetconfBase.get_device_operationsX  s    
yy!45(4(D
$%*:l*J
&'0C|0S
,-)3|)C
%&'/<'?
#$2E2U
./*5*E
&'')
#$12'(//	:'('(//<()'(//	:&*:6F+G&H
?#r   )NN)Nr>   r   NNN)r   )NNN)FNN)__name__
__module____qualname____doc__rt   r3   propertyr:   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   rl   r   ro   staticmethodrq   ru   ry   r{   r/   __classcell__)r6   s   @r   r!   r!   8   s    0ddG& ( ()H H&H	H6HHHH$	HH%    r   r!   )!
__future__r   abcr   	functoolsr   ansible.errorsr   ansible.pluginsr   +ansible.module_utils.common.text.convertersr	   ansible.module_utils.basicr
   ncclient.operationsr   ncclient.xml_r   r   r   r   r   r?   err
lxml.etreer   r   r   r   ImportErrorxml.etree.ElementTreer   r!   rn   r   r   <module>r      s   & #   ' ) A ;
,77LPDD
|- |'  L  POOPs)   A A2 A/!A**A/2BB