
    VhI                    n   d dl mZ d dlmZ d dlZd dlZd dl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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  d dl!m"Z"  e       Z#ddgZ$dZ% e
jL                  d      Z' e
jP                  d      Z)	 	 	 	 ddZ* G d de      Z+ G d de+      Z,y)    )annotationsN)abstractmethodwraps)	constants)to_bytesto_text)PlayContext)AnsiblePlugin)
BecomeBase)	ShellBase)Display)connection_loaderget_shell_plugin)unfrackpathConnectionBaseensure_connecti   PTc                0     t               d fd       }|S )Nc                T    | j                   s| j                           | g|i |S N)
_connected_connect)selfargskwargsfuncs      S/home/dcms/DCMS/lib/python3.12/site-packages/ansible/plugins/connection/__init__.pywrappedzensure_connect.<locals>.wrapped)   s(    MMOD*4*6**    )r   r   r   zP.argsr   zP.kwargsreturnr   r   )r   r    s   ` r   r   r   &   s"     4[+ + Nr!   c                  |    e Zd ZU dZdZdZdZdZdZdZ	dZ
dZdZded<   	 	 d	 	 	 	 	 	 	 	 	 	 	 d fdZedd	       Zdd
Zedd       Zedd       Zedd       Zeed d              Zed!d       Zeed"d#d              Zeed$d              Zeed$d              Zed%d       Zd%dZd%dZd%dZ d&dZ!d Z" xZ#S )'r   z>
    A base class for connections to contain common code.
    FT) N
str | Nonedefault_userc                   t         t        |           t        | d      s|| _        t        | d      s|| _        t        | d      st        | _        d | _        d | _	        d| _
        d | _        || _        | j                  sK|j                  r|j                  nt        | dd       }t        || j                  j                         | _        d | _        y )N_play_context__new_stdin_displayF_shell_type)
shell_type
executable)superr   __init__hasattrr(   _ConnectionBase__new_stdindisplayr*   success_keypromptr   _socket_path_shellshellgetattrr   r-   become)r   play_context	new_stdinr7   r   r   r,   	__class__s          r   r/   zConnectionBase.__init__G   s     	nd,. t_-!-Dt]+(DtZ(#DM(,  {{/;/A/A++wtUbdhGiJ*jTM_M_MjMjkDK)-r!   c                H    t         j                  dd       | j                  S )NzTThe connection's stdin object is deprecated. Call display.prompt_until(msg) instead.z2.19)version)r2   
deprecatedr1   r   s    r   
_new_stdinzConnectionBase._new_stdinl   s+    6 	 	

 r!   c                    || _         y r   )r9   )r   plugins     r   set_become_pluginz ConnectionBase.set_become_pluginu   s	    r!   c                    | j                   S )zYRead-only property holding whether the connection to the remote host is active or closed.)r   r@   s    r   	connectedzConnectionBase.connectedx   s     r!   c                    | j                   S )zJRead-only property holding the connection socket path for this remote host)r5   r@   s    r   socket_pathzConnectionBase.socket_path}   s        r!   c                    t        j                  |       D cg c],  }|j                         st        |j                               . c}S c c}w )z
        Takes a string like '-o Foo=1 -o Bar="foo bar"' and returns a
        list ['-o', 'Foo=1', '-o', 'Bar=foo bar'] that can be added to
        the argument list. The list will not contain any empty elements.
        )shlexsplitstripr	   )	argstringxs     r   _split_ssh_argszConnectionBase._split_ssh_args   s4     -2KK	,BPqaggi	"PPPs
   AAc                     y)z@String used to identify this Connection class from other classesN r@   s    r   	transportzConnectionBase.transport        	r!   c                     y)z/Connect to the host we've been initialized withNrQ   r@   s    r   r   zConnectionBase._connect   s    r!   c                     y)at  Run a command on the remote host.

        :arg cmd: byte string containing the command
        :kwarg in_data: If set, this data is passed to the command's stdin.
            This is used to implement pipelining.  Currently not all
            connection plugins implement pipelining.
        :kwarg sudoable: Tell the connection plugin if we're executing
            a command via a privilege escalation mechanism.  This may affect
            how the connection plugin returns data.  Note that not all
            connections can handle privilege escalation.
        :returns: a tuple of (return code, stdout, stderr)  The return code is
            an int while stdout and stderr are both byte strings.

        When a command is executed, it goes through multiple commands to get
        there.  It looks approximately like this::

            [LocalShell] ConnectionCommand [UsersLoginShell (*)] ANSIBLE_SHELL_EXECUTABLE [(BecomeCommand ANSIBLE_SHELL_EXECUTABLE)] Command
        :LocalShell: Is optional.  It is run locally to invoke the
            ``Connection Command``.  In most instances, the
            ``ConnectionCommand`` can be invoked directly instead.  The ssh
            connection plugin which can have values that need expanding
            locally specified via ssh_args is the sole known exception to
            this.  Shell metacharacters in the command itself should be
            processed on the remote machine, not on the local machine so no
            shell is needed on the local machine.  (Example, ``/bin/sh``)
        :ConnectionCommand: This is the command that connects us to the remote
            machine to run the rest of the command.  ``ansible_user``,
            ``ansible_ssh_host`` and so forth are fed to this piece of the
            command to connect to the correct host (Examples ``ssh``,
            ``chroot``)
        :UsersLoginShell: This shell may or may not be created depending on
            the ConnectionCommand used by the connection plugin.  This is the
            shell that the ``ansible_user`` has configured as their login
            shell.  In traditional UNIX parlance, this is the last field of
            a user's ``/etc/passwd`` entry   We do not specifically try to run
            the ``UsersLoginShell`` when we connect.  Instead it is implicit
            in the actions that the ``ConnectionCommand`` takes when it
            connects to a remote machine.  ``ansible_shell_type`` may be set
            to inform ansible of differences in how the ``UsersLoginShell``
            handles things like quoting if a shell has different semantics
            than the Bourne shell.
        :ANSIBLE_SHELL_EXECUTABLE: This is the shell set via the inventory var
            ``ansible_shell_executable`` or via
            ``constants.DEFAULT_EXECUTABLE`` if the inventory var is not set.
            We explicitly invoke this shell so that we have predictable
            quoting rules at this point.  ``ANSIBLE_SHELL_EXECUTABLE`` is only
            settable by the user because some sudo setups may only allow
            invoking a specific shell.  (For instance, ``/bin/bash`` may be
            allowed but ``/bin/sh``, our default, may not).  We invoke this
            twice, once after the ``ConnectionCommand`` and once after the
            ``BecomeCommand``.  After the ConnectionCommand, this is run by
            the ``UsersLoginShell``.  After the ``BecomeCommand`` we specify
            that the ``ANSIBLE_SHELL_EXECUTABLE`` is being invoked directly.
        :BecomeComand ANSIBLE_SHELL_EXECUTABLE: Is the command that performs
            privilege escalation.  Setting this up is performed by the action
            plugin prior to running ``exec_command``. So we just get passed
            :param:`cmd` which has the BecomeCommand already added.
            (Examples: sudo, su)  If we have a BecomeCommand then we will
            invoke a ANSIBLE_SHELL_EXECUTABLE shell inside of it so that we
            have a consistent view of quoting.
        :Command: Is the command we're actually trying to run remotely.
            (Examples: mkdir -p $HOME/.ansible, python $HOME/.ansible/tmp-script-file)
        NrQ   r   cmdin_datasudoables       r   exec_commandzConnectionBase.exec_command   s    D 	r!   c                     y)$Transfer a file from local to remoteNrQ   r   in_pathout_paths      r   put_filezConnectionBase.put_file   rS   r!   c                     y)zlFetch a file from remote to local; callers are expected to have pre-created the directory chain for out_pathNrQ   r]   s      r   
fetch_filezConnectionBase.fetch_file   rS   r!   c                     y)zTerminate the connectionNrQ   r@   s    r   closezConnectionBase.close   s     	r!   c                   | j                   j                  }t        j                  dt	        j
                         |fz  | j                   j                         t        j                  |t        j                         t        j                  dt	        j
                         |fz  | j                   j                         y )Nz)CONNECTION: pid %d waiting for lock on %dhostz&CONNECTION: pid %d acquired lock on %d)
r(   connection_lockfdr2   vvvvosgetpidremote_addrfcntllockfLOCK_EXr   fs     r   connection_lockzConnectionBase.connection_lock   s    00@BIIKQRCSSZ^ZlZlZxZxyAu}}%=a@PPW[WiWiWuWuvr!   c                    | j                   j                  }t        j                  |t        j                         t
        j                  dt        j                         |fz  | j                   j                         y )Nz&CONNECTION: pid %d released lock on %drf   )
r(   rh   rm   rn   LOCK_UNr2   ri   rj   rk   rl   rp   s     r   connection_unlockz ConnectionBase.connection_unlock   sS    00Au}}%=a@PPW[WiWiWuWuvr!   c                .    t         j                  d       y )Nz,Reset is not implemented for this connection)r2   warningr@   s    r   resetzConnectionBase.reset   s    FGr!   c                P   t         j                  D ]  }d}||v rd|v sd|v r|dk(  r| j                  }n|dk(  r#| j                  r| j                  j                  }nt         j                  j                  d| j                  |      }|r| j                  |d         }nGd|vrCt         j                  j                         D ]"  \  }}||v s	 t        | j                  |      } n |t        j                  d	j                  ||             |||<    y# t        $ r Y aw xY w)
z
        Adds 'magic' variables relating to connections to the variable dictionary provided.
        In case users need to access from the play, this is a legacy from runner.
        Npasswordpasswdansible_connectionansible_shell_type
connectionr   r9   zSet connection var {0} to {1})CCOMMON_CONNECTION_VARS
_load_namer6   configget_plugin_options_from_var
get_optionMAGIC_VARIABLE_MAPPINGitemsr8   r(   AttributeErrorr2   debugformat)r   	variablesvarnamevalueoptionspropvar_lists          r   update_varszConnectionBase.update_vars   s,   
 //  	+GE)#w&(g*=0000T[[.. ((>>|T__^ef OOGAJ7EW,*+*B*B*H*H*J )h"h.)(/0B0BD(I %	)  =DDWeTU%*	'"A 	+4 $2 ) ()s   D	D%$D%c                J   di i}t         j                  j                  d| j                        D ]  }||v s|j	                  ||         ||<     t        | dd      rF|D ]A  }|j                  d| j                   d      s#||vs(|j	                  ||         |d   |<   C |S )z
        Return a dict of variable -> templated value, for any variables that
        that match options registered by this plugin.
        _extrasr~   allow_extrasFansible__)r   r   get_plugin_varsr   templater8   
startswithextras_prefix)r   r   templarvar_optionsvar_names        r   _resolve_option_variablesz(ConnectionBase._resolve_option_variables   s     r
 00tO 	NH9$(/(8(889L(MH%	N
 4/% ]&&$2D2D1EQ'GHX]hMh7>7G7G	RZH[7\K	*84] r!   )NN)r:   r
   r;   io.TextIOWrapper | Noner7   zShellBase | Noner   t.Anyr   r   r"   None)r"   r   )rC   r   r"   r   )r"   bool)r"   r%   )rM   strr"   z	list[str])r"   r   )r   r   r"   r   NTrW   r   rX   zbytes | NonerY   r   r"   ztuple[int, bytes, bytes]r^   r   r_   r   r"   r   r"   r   )r   zdict[str, t.Any]r"   r   )$__name__
__module____qualname____doc__has_pipelininghas_native_asyncalways_pipeline_moduleshas_tty!module_implementation_preferencesallow_executablesupports_persistenceforce_persistencer&   __annotations__r/   propertyrA   rD   rF   rH   staticmethodrO   r   rR   r   r   rZ   r`   rb   rd   rr   ru   rx   r   r   __classcell__r<   s   @r   r   r   1   s    N#G ).% !#L*#
 .2"&	#.!#. +#.  	#.
 #. #. 
#.J       ! ! Q Q    > > @  @D        ww
H%+Nr!   c                       e Zd ZdZdZdZ	 d	 	 	 	 	 	 	 	 	 d fdZd ZdddZddZ	ddZ
ddZdd	Zdd
ZddZ	 	 	 d	 	 	 	 	 	 	 d fdZddZddZ xZS )NetworkConnectionBasez5
    A base class for network-style connections.
    Tc                \   t        t        | 
  ||g|i | g | _        d| _        | j
                  j                  | _        t        j                  d|d      | _
        | j                  j                          i | _        d| _        |j                  d      | _        | j                          y )NFlocalz	/dev/nullNNNansible_playbook_pid)r.   r   r/   	_messages_conn_closedr(   
network_os_network_osr   get_localset_options_sub_plugin_cached_variables_ansible_playbook_pid_update_connection_state)r   r:   r;   r   r   r<   s        r   r/   zNetworkConnectionBase.__init__?  s     	#T3L)]d]V\]02!--88'++G\;O!-/!3 &,ZZ0F%G"%%'r!   c                
   	 | j                   |   S # t        $ rh |j                  d      s0| j                  j	                  d      }|rt        ||d       }||cY S t        d| j                  j                  d|d      w xY w)Nr   obj'z' object has no attribute ')	__dict__KeyErrorr   r   r   r8   r   r<   r   )r   namerC   methods       r   __getattr__z!NetworkConnectionBase.__getattr__V  s    		h==&& 	h??3'))--e4$VT48F)% H_H_ae!fgg	hs    AB'Bc                <    | j                   j                  |||      S r   )r   rZ   rV   s       r   rZ   z"NetworkConnectionBase.exec_commandb  s    {{''Wh??r!   c                >    | j                   j                  ||f       y)a  
        Adds a message to the queue of messages waiting to be pushed back to the controller process.

        :arg level: A string which can either be the name of a method in display, or 'log'. When
            the messages are returned to task_executor, a value of log will correspond to
            ``display.display(message, log_only=True)``, while another value will call ``display.[level](message)``
        N)r   append)r   levelmessages      r   queue_messagez#NetworkConnectionBase.queue_messagee  s     	ug./r!   c                .    | j                   g c}| _         |S r   )r   )r   messagess     r   pop_messagesz"NetworkConnectionBase.pop_messageso  s    #'>>2 $.r!   c                :    | j                   j                  ||      S )r\   )r   r`   r]   s      r   r`   zNetworkConnectionBase.put_files  s    {{##GX66r!   c                :    | j                   j                  ||      S )z!Fetch a file from remote to local)r   rb   r]   s      r   rb   z NetworkConnectionBase.fetch_filew  s    {{%%gx88r!   c                    | j                   r/| j                  dd| j                   z         | j                          | j                  dd       y)z&
        Reset the connection
        ri   z2resetting persistent connection for socket_path %sz!reset call on connection instanceN)r5   r   rd   r@   s    r   rx   zNetworkConnectionBase.reset{  sD     v'[^b^o^o'opJJL6#FGr!   c                :    d| _         | j                  rd| _        y y )NTF)r   r   r@   s    r   rd   zNetworkConnectionBase.close  s     ??#DO r!   c                   t         t        |   |||       | j                  d      rHd| j                  j
                  z  }t        t        d      }||d|z  z  }| j                  dd|z         | j                  j                  d      rB| j                  j                  d	      d
k7  r#	 | j                  d   j                  |||       y y y # t        $ r Y y w xY w)N)	task_keysr   directpersistent_log_messageszOPersistent connection logging is enabled for %s. This will log ALL interactionsDEFAULT_LOG_PATHz to %srw   zP%s and WILL NOT redact sensitive configuration like passwords. USE WITH CAUTION!r   typeexternal)r.   r   r   r   r(   rl   r8   r   r   r   r   r   )r   r   r   r   rw   logpathr<   s         r   r   z!NetworkConnectionBase.set_options  s     	#T6Xclr6s??45gjnj|j|  kI  kI  IGa!34G"8g--y*|  @G  +G  H&4+;+;+?+?+G:+U  '33iU`io3p ,V& " s   +!C 	CCc                   t        j                  dd      }|j                  | j                  j                  | j                  j
                  | j                  j                  | j                  j                  | j                        }t        t        j                        }t        |t        |      z        }t        j                  j                  |      rd| _        || _        yy)ac  
        Reconstruct the connection socket_path and check if it exists

        If the socket path exists then the connection is active and set
        both the _socket_path value to the path and the _connected value
        to True.  If the socket path doesn't exist, leave the socket path
        value to None and the _connected value to False
        sshT)
class_only)	directoryN)r   r   _create_control_pathr(   rl   portremote_userr~   r   r   r   PERSISTENT_CONTROL_PATH_DIRdictrj   pathexistsr   r5   )r   r   control_pathtmp_pathrH   s        r   r   z.NetworkConnectionBase._update_connection_state  s      ##Ed;//**D,>,>,C,C**D,>,>,I,I&&
 q<<=!,1I"IJ77>>+&"DO +D 'r!   c                L    | j                  d      r| j                  d|       y y )Nr   log)r   r   )r   r   s     r   _log_messagesz#NetworkConnectionBase._log_messages  s$    ??45ug. 6r!   r   )
r:   r
   r;   r   r   r   r   r   r"   r   r   r   )r   r   r   r   r"   r   )r"   zlist[tuple[str, str]]r   r   r   )r   dict[str, t.Any] | Noner   r   r   r   r"   r   )r   r   r"   r   )r   r   r   r   r   _remote_is_localr/   r   rZ   r   r   r`   rb   rx   rd   r   r   r   r   r   s   @r   r   r   6  s     
 .2(!( +( 	(
 ( 
(.
h@079H$ .2/3*.	* - (	
 
(,./r!   r   )r   /c.Callable[t.Concatenate[ConnectionBase, P], T]r"   r   )-
__future__r   collections.abcabccrm   iorj   rJ   typingtr   	functoolsr   ansibler   r   +ansible.module_utils.common.text.convertersr   r	   ansible.playbook.play_contextr
   ansible.pluginsr   ansible.plugins.becomer   ansible.plugins.shellr   ansible.utils.displayr   ansible.plugins.loaderr   r   ansible.utils.pathr   r2   __all__BUFSIZE	ParamSpecr   TypeVarr   r   r   r   rQ   r!   r   <module>r     s   
 #   	 	     " I 5 ) - + ) F *
) -
.
AKKAIIcN
94B] BJ@/N @/r!   