
    VhM                         d dl mZmZmZ eZdZdZd dlZd dl	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 d d
lmZ d dlmZ d dlmZmZ  G d de      Zy)    )absolute_importdivisionprint_functiona  
author: Ansible Networking Team (@ansible-network)
name: iosxr
short_description: Use iosxr cliconf to run command on Cisco IOS XR platform
description:
- This iosxr plugin provides low level abstraction apis for sending and receiving
  CLI commands from Cisco IOS XR network devices.
version_added: 1.0.0
notes:
- IOSXR commit confirmed command varies with IOSXR version releases,
  commit_comment and commit_label may or may not
  be valid together as per the device version.
options:
  commit_confirmed:
    type: boolean
    default: false
    description:
    - enable or disable commit confirmed mode
    env:
    - name: ANSIBLE_IOSXR_COMMIT_CONFIRMED
    vars:
    - name: ansible_iosxr_commit_confirmed
  commit_confirmed_timeout:
    type: int
    description:
    - Commits the configuration on a trial basis for the time specified in seconds or minutes.
    env:
    - name: ANSIBLE_IOSXR_COMMIT_CONFIRMED_TIMEOUT
    vars:
    - name: ansible_iosxr_commit_confirmed_timeout
  commit_label:
    type: str
    description:
    - Adds label to commit confirmed.
    env:
    - name: ANSIBLE_IOSXR_COMMIT_LABEL
    vars:
    - name: ansible_iosxr_commit_label
  commit_comment:
    type: str
    description:
    - Adds comment to commit confirmed..
    env:
    - name: ANSIBLE_IOSXR_COMMIT_COMMENT
    vars:
    - name: ansible_iosxr_commit_comment
  config_commands:
    description:
    - Specifies a list of commands that can make configuration changes
      to the target device.
    - When `ansible_network_single_user_mode` is enabled, if a command sent
      to the device is present in this list, the existing cache is invalidated.
    version_added: 2.0.0
    type: list
    elements: str
    default: []
    vars:
    - name: ansible_iosxr_config_commands
  config_mode_exclusive:
    type: boolean
    default: false
    description:
    - enable or disable config mode exclusive
    env:
    - name: ANSIBLE_IOSXR_CONFIG_MODE_EXCLUSIVE
    vars:
    - name: ansible_iosxr_config_mode_exclusive
aW
  
# Use commit confirmed within a task with timeout, label and comment

- name: Commit confirmed with a task
  vars:
    ansible_iosxr_commit_confirmed: True
    ansible_iosxr_commit_confirmed_timeout: 50
    ansible_iosxr_commit_label: TestLabel
    ansible_iosxr_commit_comment: I am a test comment
  cisco.iosxr.iosxr_logging_global:
    state: merged
    config:
      buffered:
        severity: errors #alerts #informational
      correlator:
        buffer_size: 2024

# Commands (cliconf specific)
# ["commit confirmed 50 label TestLabel comment I am a test comment"]

# Use commit within a task with label

- name: Commit label with a task
  vars:
    ansible_iosxr_commit_label: lblTest
  cisco.iosxr.iosxr_hostname:
    state: merged
    config:
      hostname: R1

# Commands (cliconf specific)
# ["commit label lblt1"]

# Use commit confirm with timeout and confirm the commit

# NOTE - IOSXR waits for a `commit` when the command
# executed is `commit confirmed <timeout>` within the timeout
# period for the config to commit successfully, else a rollback
# happens.

- name: Example commit confirmed
  vars:
    ansible_iosxr_commit_confirmed: True
    ansible_iosxr_commit_confirmed_timeout: 60
  tasks:
    - name: "Commit confirmed with timeout"
      cisco.iosxr.iosxr_hostname:
        state: merged
        config:
          hostname: R1

    - name: "Confirm the Commit"
      cisco.iosxr.iosxr_command:
        commands:
          - commit

# Commands (cliconf specific)
# ["commit confirmed 60"]

# Use exclusive mode with a task

- name: Configure exclusive mode with a task
  vars:
    ansible_iosxr_config_mode_exclusive: True
  cisco.iosxr.iosxr_interfaces:
    state: merged
    config:
      - name: GigabitEthernet0/0/0/2
        description: Configured via Ansible
      - name: GigabitEthernet0/0/0/3
        description: Configured via Ansible

# Commands (cliconf specific)
# ["configure exclusive"]

# Use Replace option with commit confirmed

# NOTE - IOSXR waits for a `commit` when the command
# executed is `commit replace confirmed <timeout>` within the timeout
# period for the config to commit successfully, else a rollback
# happens.
# This option is supported by only iosxr_config module

- name: Example replace config with commit confirmed
  vars:
    ansible_iosxr_commit_confirmed: True
    ansible_iosxr_commit_confirmed_timeout: 60
  tasks:
    - name: "Replace config with Commit confirmed"
      cisco.iosxr.iosxr_config:
        src: 'replace_running_cfg_iosxr.txt'
        replace: config

    - name: "Confirm the Commit"
      cisco.iosxr.iosxr_command:
        commands:
          - commit
N)AnsibleConnectionFailure)to_text)Mapping)ConnectionError)NetworkConfigdumps)to_list)CliconfBase)mask_config_blocks_from_diffsanitize_configc                        e Zd Z fdZd Zd ZddZddZd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 Z fdZd Z xZS )Cliconfc                 :    i | _         t        t        |   |i | y )N)_device_infosuperr   __init__)selfargskwargs	__class__s      e/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/cisco/iosxr/plugins/cliconf/iosxr.pyr   zCliconf.__init__   s    gt%t6v6    c                 ^    | j                  |      }t        |d      j                         }|S )Nsurrogate_or_stricterrors)getr   strip)r   commandreplydatas       r   get_command_outputzCliconf.get_command_output   s+    !u%:;AACr   c                 *   | j                   st               }d|d<   | j                  d      }t        j                  d|t        j
                        }|r|j                  d      |d<   n;t        j                  d|t        j
                        }|r|j                  d      |d<   t        j                  d|      }|r|j                  d      |d	<   g d
}|D ]?  }t        j                  ||t        j
                        }|s+|j                  d      |d<    n 	 | j                  d      }d|vr;t        j                  d|t        j
                        }|r|j                  d      |d<   t        j                  d|t        j
                        }|r|j                  d      |d<   | j                  d      }t        j                  d|t        j
                        }|r|j                  d      |d<   || _         | j                   S # t        $ r d}Y w xY w)Niosxr
network_osz!show version | utility head -n 20zVersion (\S+)$   network_os_versionzVersion (\S+ \S+)$zimage file is "(.+)"network_os_image)z^[Cc]isco (.+) \(\) processorz!^[Cc]isco ([A-Z0-9\-]+) processorz^[Cc]isco (.+) \(revisionz&^[Cc]isco (\S+ \S+).+bytes of .*memorynetwork_os_modelzshow inventory zDESCR: \"[Cc]isco (\S+ \S+)zSN: (\S+)\n\nNAME:network_os_serialnumzshow running-config hostnamezhostname\s(\S+)$network_os_hostname)r   dictr%   researchMgroupr   )r   device_infor$   matchmodel_search_strsitemhostnames          r   get_device_infozCliconf.get_device_info   s     &K(/K%**+NODII/rtt<E49KKN01		"7rttD8=AK 45II5t<E27++a../! * 		$bdd36;kk!nK 23	../?@ "4		"@$M6;kk!nK 23II3T244@E6;kk!n23../MNHII18RTTBE5:[[^12 +D   ' , s   H HHc                 (   t        | j                  j                         d      j                         }|j	                  d      sN|rd|vr| j                  d       |s| j                  d      r| j                  d       y | j                  d       y y )	Nr   r   )#admin-adminconfig_mode_exclusivezconfigure exclusivezconfigure terminal)r   _connection
get_promptr!   endswithsend_command
get_option)r   r>   	exclusiveprompts       r   	configurezCliconf.configure  s    ))446?TU[[]t$/!!'*DOO,CD!!"7823 %r   c                     t        | j                  j                         d      j                         }|j	                  d      r+| j                  d       |rd|v r| j                  d       y y y y )Nr   r   r<   abortr=   exit)r   r@   rA   r!   rB   rC   )r   r>   rF   s      r   rI   zCliconf.abort  se    ))446?TU[[]??4 g&V+!!&) ,u !r   c                     |dvrt        d|z        ddi}dj                  ||         }|dj                  t        |            z  }|j	                         }| j                  |      S )N)runningz/fetching configuration from %s is not supportedrL   zrunning-configz	show {0}  )
ValueErrorformatjoinr   r!   rC   )r   sourceflagsrO   lookupcmds         r   
get_configzCliconf.get_config#  sn    $NQWWXX-.  0sxx''iik  %%r   c	                 (   | j                         }	| j                  |	||||       i }
g }g }| j                  ||       |rdj                  |      }t	        |      D ]M  }t        |t              sd|i}|d   }|j                   | j                  di |       |j                  |       O | j                  d      |
d<   |r	 | j                  |||       n| j#                          | j%                  d      s| j'                  |       ||
d<   ||
d<   |
S # t        $ rp}t        |d      j                         }d	|v r<d
|v r8d|z  }| j                  j                  d|       d }| j                  |||       nt!        |      Y d }~d }~ww xY w)N)r>   rE   zload {0}r"   zshow commit changes diffshow_commit_config_diff)commentlabelreplacer   r   zInvalid input detectedrX   zGvalue of comment option '%s' is ignored as it in not supported by IOSXRwarningcommit_confirmed)r>   requestresponse )get_device_operationscheck_edit_config_capabilityrG   rO   r   
isinstancer   appendrC   r    commitr   r   r!   r@   queue_messager	   discard_changesrD   rI   )r   	candidaterd   rZ   diffrX   r>   rE   rY   
operationsrespresultsrequestslinerT   exc	error_msgmsgs                     r   edit_configzCliconf.edit_config/  s    //1
))*iRYZUi8"))'2II& 	!DdG,!4(y/CNN,4,,4t45OOC 	! +/((3M*N&'5G5'J   "12JJUJ#"Y"Z+ , 5#C0EFLLN	+y8Y)=Sa!"  $$229cB"GKKugKN))44 O5s   D 	F!A&FFc                     |st        d      | j                          d| | }| j                  |      }| j                          |S )Nz)'file_name' value is required for restorezload )rN   rG   rC   rd   )r   filenamepathrT   rj   s        r   restorezCliconf.restorel  sI    HIIdVH:&  %r   c           	      2   i }| j                         }| j                         }	||d   rt        d      ||	d   vr#t        d|ddj                  |	d               ||	d   vr#t        d|ddj                  |	d               t	        |      }
t        d	d
g      }|j                  |
       |rC|dk7  r>t        ||d      }t	        |      }t        d	||d
g      }|j                  ||||      }n|j                  }|rt        |d      nd|d<   |S )Nsupports_generate_diffz4candidate configuration is required to generate diff
diff_matchz'match' value z in invalid, valid values are z, diff_replacez'replace' value r)   !)indentcomment_tokensnoneansible)r{   contentsignore_linesr|   )rt   r6   rZ   commandsr-   config_diff)r`   get_option_valuesrN   rP   r   r
   loadr   
differenceitemsr   )r   rg   rL   rx   diff_ignore_linesrt   ry   rh   device_operationsoption_valuessanitized_candidatecandidate_objrunning_objconfigdiffobjss                 r   get_diffzCliconf.get_diffu  sX     668..0!23K!LSTT]<88tyy|)DEG 
 }^<<=+H!IK  .i8%QuE./zV+27IyQG%g.G' . #u	K +55 $	 6 N +00NCQeNJ?WY]r   c                 P    |rt        d|z        | j                  ||||||      S )Nz*'output' value %s is not supported for get)r"   rF   answersendonlynewline	check_all)rN   rC   )r   r"   rF   r   r   r   outputr   s           r   r    zCliconf.get  sB     IFRSS   ! 
 	
r   c                    i }|rcd|d<   | j                  d      rAd|d<   | j                  d      r+|dxx   dj                  | j                  d            z  cc<   d|d<   d	|d
<   nJ| j                  d      rd|d<   | j                  d      r+|dxx   dj                  | j                  d            z  cc<   | j                  d      r+|dxx   dj                  | j                  d            z  cc<   | j                  d      r|dxx   dj                  | j                  d            z  cc<   n|xs | j                  d      }|xs | j                  d      }|s|rBd|d<   |r|dxx   dj                  |      z  cc<   |r"|dxx   dj                  |      z  cc<   nd|d<   d|d<   d|d
<    | j                  di | y)a_  Implements commit functionality of config module
        and commit confirmed functionality of cliconf module

        Args:
            comment (str, optional): commit comment. Defaults to None.
            label (str, optional): commit label. Defaults to None.
            replace (bool, optional): Flag to replace commit. Defaults to None.
        zcommit replacer"   r\   zcommit replace confirmedcommit_confirmed_timeoutz {0}zCThis commit will replace or remove the entire running configurationrF   yesr   zcommit confirmedcommit_labelz
 label {0}commit_commentz comment {0}rd   zcommit show-errorz(C|c)onfirmyNr_   )rD   rO   rC   )r   rX   rY   rZ   cmd_objs        r   rd   zCliconf.commit  s    !1GI12%?	"??#=>I&&--(BC+ &
 V H !&GH__/0!3GI9:	"fmmOO$>?' " ~.	"l&9&9OON3' " /0	"n&;&;OO$45' "
 <T__^<EB1A!BG%%-	"I&,*=*=e*DD&I&.*?*?*HH& &9	" !.GH #GH$G$r   c           
      ,   |t        d      t               }t        |      D ]  }t        |t              sd|i}|j                  dd       }|rt        d|z        	  | j                  di |}|O	 t        |d      j                         }	 t        j                  |      }|j                  |        |S # t        $ r}|r t        |d|      }Y d }~hd }~ww xY w# t        $ r t        d|d	t        |      
      w xY w# t         $ r Y nw xY w)Nz'commands' value is requiredr"   r   z3'output' value %s is not supported for run_commandserrr   r   zFailed to decode output from z: )messager_   )rN   listr   rb   r   poprC   r   getattrr   r!   UnicodeErrorr	   jsonloadsrc   )r   r   check_rc	responsesrT   r   outes           r   run_commandszCliconf.run_commands  s4   ;<<F	8$ 	&Cc7+ #&WWXt,F IFR +'d''.#. !#.CDJJLC**S/C   %=	&> ' , +a*+ $ )ILgVYl [  " s6   B93CD9	CCC%D	DDc                 &    | j                  d       y )NrI   )rC   r   s    r   rf   zCliconf.discard_changes$  s    '"r   c                 "    ddddddddddddddS )NTF)supports_diff_replacesupports_commitsupports_rollbacksupports_defaultssupports_onbox_diffsupports_commit_commentsupports_multiline_delimitersupports_diff_matchsupports_diff_ignore_linesrw   supports_replacesupports_adminsupports_commit_labelr_   r   s    r   r`   zCliconf.get_device_operations'  s3    %)#!&!&#('+,1#'*.&* $"%)
 	
r   c                     dgg dg dg dS )Ntext)rm   strictexactr}   )rm   blockconfig)rO   rx   ry   r   r_   r   s    r   r   zCliconf.get_option_values8  s    h=7	
 	
r   c                     t         t        |          }|dxx   g dz  cc<   | j                         |d<   |j	                  | j                                t        j                  |      S )Nrpc)rd   rf   r   rG   rJ   r   )r   r   get_capabilitiesr`   updater   r   r   )r   resultr   s     r   r   zCliconf.get_capabilities@  sY    w68uWW&*&@&@&B"#d,,./zz&!!r   c                 |    | j                   j                  r&| j                  d      s| j                  dd       yyy)zT
        Make sure we are in the operational cli mode
        :return: None
        r\   r<   rI   )config_contextexit_commandN)r@   	connectedrD   _update_cli_prompt_contextr   s    r   set_cli_prompt_contextzCliconf.set_cli_prompt_contextG  s;    
 %%doo>P.Q++4g+V /R%r   )FF)F)rL   Nr   )NTNFNFFN)Nr-   )NNrm   NNrm   )NNNFTNF)NNN)NT)__name__
__module____qualname__r   r%   r:   rG   rI   rU   rq   ru   r   r    rd   r   rf   r`   r   r   r   __classcell__)r   s   @r   r   r      s    7
2!h4*
& ;z 7v 
*:%x#J#
"
"Wr   r   )
__future__r   r   r   type__metaclass__DOCUMENTATIONEXAMPLESr   r1   ansible.errorsr   ansible.module_utils._textr   /ansible.module_utils.common._collections_compatr   ansible.module_utils.connectionr	   Pansible_collections.ansible.netcommon.plugins.module_utils.network.common.configr
   r   Oansible_collections.ansible.netcommon.plugins.module_utils.network.common.utilsr   Gansible_collections.ansible.netcommon.plugins.plugin_utils.cliconf_baser   Hansible_collections.cisco.iosxr.plugins.module_utils.network.iosxr.iosxrr   r   r   r_   r   r   <module>r      s^   & A @ CJaF  	 3 . C ; d _yWk yWr   