
    Vhu@                         d dl mZmZmZ eZdZd dlZd dlZd dl	m
Z
mZ d dlmZ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mZmZmZ d dlmZ d dlm Z  d dl!m"Z"m#Z#m$Z$ d dl%m&Z& dZ' e       Z( G d de      Z)y)    )absolute_importdivisionprint_functiona  
author:
  - Felix Fontein (@felixfontein)
name: docker_api
short_description: Run tasks in docker containers
version_added: 1.1.0
description:
  - Run commands or put/fetch files to an existing docker container.
  - Uses the L(requests library,https://pypi.org/project/requests/) to interact directly with the Docker daemon instead of
    using the Docker CLI. Use the P(community.docker.docker#connection) connection plugin if you want to use the Docker CLI.
notes:
  - Does B(not work with TCP TLS sockets)! This is caused by the inability to send C(close_notify) without closing the connection
    with Python's C(SSLSocket)s. See U(https://github.com/ansible-collections/community.docker/issues/605) for more information.
extends_documentation_fragment:
  - community.docker.docker.api_documentation
  - community.docker.docker.var_names
options:
  remote_user:
    type: str
    description:
      - The user to execute as inside the container.
    vars:
      - name: ansible_user
      - name: ansible_docker_user
    ini:
      - section: defaults
        key: remote_user
    env:
      - name: ANSIBLE_REMOTE_USER
    cli:
      - name: user
    keyword:
      - name: remote_user
  remote_addr:
    type: str
    description:
      - The name of the container you want to access.
    default: inventory_hostname
    vars:
      - name: inventory_hostname
      - name: ansible_host
      - name: ansible_docker_host
  container_timeout:
    default: 10
    description:
      - Controls how long we can wait to access reading output from the container once execution started.
    env:
      - name: ANSIBLE_TIMEOUT
      - name: ANSIBLE_DOCKER_TIMEOUT
        version_added: 2.2.0
    ini:
      - key: timeout
        section: defaults
      - key: timeout
        section: docker_connection
        version_added: 2.2.0
    vars:
      - name: ansible_docker_timeout
        version_added: 2.2.0
    cli:
      - name: timeout
    type: integer
  extra_env:
    description:
      - Provide extra environment variables to set when running commands in the Docker container.
      - This option can currently only be provided as Ansible variables due to limitations of ansible-core's configuration
        manager.
    vars:
      - name: ansible_docker_extra_env
    type: dict
    version_added: 3.12.0
  working_dir:
    description:
      - The directory inside the container to run commands in.
      - Requires Docker API version 1.35 or later.
    env:
      - name: ANSIBLE_DOCKER_WORKING_DIR
    ini:
      - key: working_dir
        section: docker_connection
    vars:
      - name: ansible_docker_working_dir
    type: string
    version_added: 3.12.0
  privileged:
    description:
      - Whether commands should be run with extended privileges.
      - B(Note) that this allows command to potentially break out of the container. Use with care!
    env:
      - name: ANSIBLE_DOCKER_PRIVILEGED
    ini:
      - key: privileged
        section: docker_connection
    vars:
      - name: ansible_docker_privileged
    type: boolean
    default: false
    version_added: 3.12.0
N)AnsibleFileNotFoundAnsibleConnectionFailure)to_bytes	to_nativeto_text)string_types)ConnectionBase)Display)RequestException)DockerFileCopyErrorDockerFileNotFound
fetch_fileput_file)DockerSocketHandler)AnsibleDockerClient)APIErrorDockerExceptionNotFound)LooseVersionc                   t     e Zd ZdZdZdZddZ fdZd fd	Zd fd	Z	d Z
 fd	Z fd
Z fdZd Z xZS )
Connectionz  Local docker based connections zcommunity.docker.docker_apiTc           	      @   	  |       S # t         $ r[}|r*t        dj                  || j                  d                  t        dj                  || j                  d                  d }~wt        $ r}|j
                  C|j
                  j                  dk(  r*t        dj                  || j                  d                  | j                  j                  dj                  || j                  d                   Y d }~y d }~wt        $ rD}| j                  j                  dj                  || j                  d                   Y d }~y d }~wt        $ rD}| j                  j                  dj                  || j                  d                   Y d }~y d }~ww xY w)Nz6Could not find container "{1}" or resource in it ({0})remote_addrz$Could not find container "{1}" ({0})i  z)The container "{1}" has been paused ({0})z<An unexpected Docker error occurred for container "{1}": {0}zgAn unexpected requests error occurred for container "{1}" when trying to talk to the Docker daemon: {0})r   r   format
get_optionr   responsestatus_codeclientfailr   r   )selfcallablenot_found_can_be_resourcees       r/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/docker/plugins/connection/docker_api.py_call_clientzConnection._call_client   s   	: 	A(./g/n/noprv  sB  sB  CP  sQ  0R  S  S./U/\/\]^`d`o`op}`~/  A  A 	zz%!***@*@C*G./Z/a/abceietet  vC  fD  0E  F  FKKNUUVWY]YhYhivYwx   	KKNUUVWY]YhYhivYwx    	KKy4??=9: 	s:   	 	FAA((F4B	DF:EF:FFc                     t        t        | 
  ||g|i | d | _        t	               | _        t        | j                  dd      rd| _        d | _	        y )N_IS_WINDOWSF)z.ps1z.exe )
superr   __init__r!   dictidsgetattr_shell!module_implementation_preferencesactual_user)r#   play_context	new_stdinargskwargs	__class__s        r'   r-   zConnection.__init__   sP    j$(yR4R6R6 4;;u55ID2    c                     t         t                    j                  s3 j	                  d       _        t        j                  dj                   j
                  xs d       j	                  d              j                  t         t               _	        d _         j
                  t        j                  d	kD  rt        j                  d
        j                   fd      }|j                  d      rU|d   j                  d       _         j
                  /t        j                  dj                   j
                               yyyyyy)z) Connect to the container. Nothing to do remote_userz)ESTABLISH DOCKER CONNECTION FOR USER: {0}?r   hostN)min_docker_api_versionT   zTrying to determine actual userc                  Z     j                   j                  d j                  d            S )Nz/containers/{0}/jsonr   )r!   get_jsonr   r#   s   r'   <lambda>z%Connection._connect.<locals>.<lambda>   s&    4;;3G3GH^`d`o`op}`~3 r9   ConfigUserzActual user is '{0}')r,   r   _connect
_connectedr   r3   displayvvvr   r!   r   MIN_DOCKER_API	verbosityr(   get)r#   portresultr8   s   `  r'   rG   zConnection._connect   s$   j$(*#}=DKKDKK  (D*040N   {{"1$~^"DO'G,=,=,A >?**+  A::h''-h'7';';F'CD$''3$;$B$B4CSCS$TU 4 ( -B' r9   c           
      	    t         t           |||        j                  j                  dt        |      g} j                  xr  j                  j                         xr |}t        j                  dj                  t        |      |dj                  t        |            nd|rdnd       j                  d      	       ||rd
nd} j                  d       j                  d      xs d j                  d      d|d
d
|dd j                  j                  v r j                  j                  d   d<    j                  d      rg d<    j                  d      j                         D ]  \  }}|df|dffD ]?  \  }	}
t!        |	t"              rt%        dj                  |
j'                         |
|	             d   j)                  dj                  t        |d      t        |d                     j                  d      d j                  d      d<    j                  j*                  t-        d      k  r.t%        dj                   j                  j.                               j1                   fd      }|d   ddd|r j1                   fd      }	 t3        t        | j                  d             5 }|rmd!gfd"}|j5                  |        j                  j7                  d#         s҉ j                  j9                  d#         s|j;                   j                  d$            s-|j=                         \  }}t%        d%t?        d#         z         |jA                         rt%        d&t?        d#         z          j                  j7                  d#         s j                  j9                  d#         s j                  j7                  d#         sF j                  j                  d' j                  (      }|jC                  tE        |d      d)z          ||jC                  |       |j=                         \  }}ddd       |jG                          n j1                   fd*      \  }} j1                   fd+      }|jI                  d,      xs d#xs d!xs d!fS # 1 sw Y   hxY w# |jG                          w xY w)-z" Run a command on the docker host )in_datasudoablez-czEXEC {0}{1}{2}Nz, with stdin ({0} bytes)r+   z, with become promptr   r=   TFr;   
privileged)	ContainerrF   
PrivilegedTtyAttachStdinAttachStdoutAttachStderrCmd
detachKeys	extra_envEnvKeyValuezNon-string {0} found for extra_env option. Ambiguous env options must be wrapped in quotes to avoid them being interpreted. {1}: {2!r}z{0}={1}surrogate_or_strict)errorsworking_dir
WorkingDirz1.35zProviding the working directory requires Docker API version 1.35 or newer. The Docker daemon the connection is using has API version {0}.c                  ^    j                   j                  dj                  d             S )Nz/containers/{0}/execr   data)r!   post_json_to_jsonr   )rf   r#   s   r'   rD   z)Connection.exec_command.<locals>.<lambda>  s;    dkk.K.KLbdhdsds  uB  eC  JN.K  /O r9   Id)rV   Detachc                  @    j                   j                  d       S )N/exec/{0}/startre   )r!   post_json_to_stream_socketrf   exec_idr#   s   r'   rD   z)Connection.exec_command.<locals>.<lambda>  s'    DKK4Z4Z[lnu  }A4Z  5B r9   )	containerr9   c                      dxx   |z  cc<   y )Nr    )	stream_idrf   become_outputs     r'   append_become_outputz5Connection.exec_command.<locals>.append_become_output  s    )!,4,r9   r   container_timeoutz:timeout waiting for privilege escalation password prompt:
z;privilege output closed while waiting for password prompt:
become_pass)playcontext   
c                  F    j                   j                  dddd       S )Nrk   FT)streamdemuxttyrf   )r!   post_json_to_streamrm   s   r'   rD   z)Connection.exec_command.<locals>.<lambda>.  s+    t{{7V7V!75%VZ 8W 8\ r9   c                  <    j                   j                  d       S )Nz/exec/{0}/json)r!   rB   )rn   r#   s   r'   rD   z)Connection.exec_command.<locals>.<lambda>1  s    4;;+?+?@PRY+Z r9   ExitCode)%r,   r   exec_command_play_context
executabler
   becomeexpect_promptrI   rJ   r   lenr   r!   _general_configsitems
isinstancer   r   lowerappenddocker_api_versionr   docker_api_version_strr(   r   set_block_done_callbackcheck_successcheck_password_promptselectconsumer	   is_eofwriter   closerM   )r#   cmdrQ   rR   command	do_become
need_stdinkvvalwhat	exec_dataexec_socketexec_socket_handlerrt   stdoutstderrrv   rO   rs   rf   rn   r8   s   `                  @@@r'   r   zConnection.exec_command   s    	j$,S'H,U%%00$EKKLDKK$=$=$?LH	$$ CJCV*11#g,?\^*3&
 / 	 	
 &1iTU
 7OOM28b//,7%  	
 4;;777!%!=!=l!KD??;'DK4::< J1#$e*q'l!; IC%c<86\#VDJJL$<  U"":#4#4WQG\5]_fgh  rG  `H  $I  JJ ??=)5!%!?D{{--V0DD.VVDKK>>?  %%  'O  P	D/ 
 ++  -B  CK$(+YfIgh Cl ),5 ,CCDXY"&++";";M!<L"MVZVaVaVwVw  yF  GH  yI  WJ#6#=#=dooNa>b#c1D1L1L1N&>?|  @I  JW  XY  JZ  @[  @[  '\  !\299;&>?}  AJ  KX  YZ  K[  A\  @\  ']  !] #'++";";M!<L"MVZVaVaVwVw  yF  GH  yI  WJ  ${{88q9IJ*.++*@*@\`\n\n*@*oK/55h{Sh6ilq6qr*+11':%8%@%@%BNFF1C4 !!#!.. 0\ ]NFF ""#Z[zz*%*FMc6=SHHCC C4 !!#s,   1!S DSB
S)S SS S.c                 Z   t        | j                  dd      rddl}|j                  |      S |j	                  t
        j                  j                        s8t
        j                  j                  t
        j                  j                  |      }t
        j                  j                  |      S )a   Make sure that we put files into a standard path

            If a path is relative, then we need to choose where to put it.
            ssh chooses $HOME but we are not guaranteed that a home dir will
            exist in any given chroot.  So for now we are choosing "/" instead.
            This also happens to be the former default.

            Can revisit using $HOME instead if it is a problem
        r*   Fr   N)	r0   r1   ntpathnormpath
startswithospathsepjoin)r#   remote_pathr   s      r'   _prefix_login_pathzConnection._prefix_login_path5  sm     4;;u5??;//))"''++6 ggll277;;D77##K00r9   c           	          t         t                  t        j	                  dd j                  d              j                         j                   j                  vr j                  d      \  }}}	 |j                         \  t              t              f j                   j                  <   t        j                  dj                   j                         j                  d              j                   j                     \  	  j!                   fd	d
       y# t        $ r0}t        dj                  | j                  d      |            d}~ww xY w# t"        $ r}t%        t'        |            d}~wt(        $ r}t        t'        |            d}~ww xY w)z0 Transfer a file from local to docker container zPUT  TO r   r=   s   id -u && id -gz2PUT: Determined uid={0} and gid={1} for user "{2}"zbError while determining user and group ID of current user in container "{1}": {0}
Got value: {2!r}Nc            
      p    t        j                  j                  d       j                  d      S )Nr   T)ro   in_pathout_pathuser_idgroup_id	user_namefollow_links)r   r!   r   r3   )r   r   r   r#   r   s   r'   rD   z%Connection.put_file.<locals>.<lambda>`  s7    KK"oom<#%#%"..!%	 r9   Tr%   )r,   r   r   rI   rJ   r   r   r3   r/   r   
splitlinesintvvvvr   	Exceptionr   r(   r   r   r	   r   )
r#   r   r   dummyr/   r&   excr   r   r8   s
   ```    @@r'   r   zConnection.put_fileG  s   j$((;gx8t}?]^**84488+ $ 1 12C DE3$'NN$4!-0\3x=-H))*HOOPWYacgcscst7   !HHT%5%56	;	 +/    .yVAt}=sC * " 	6%in55" 	;*9S>::	;s=   BD? $E; ?	E8+E33E8;	F=FF=$F88F=c                 j    t         t                  t        j	                  dd j                  d              j                        	  j                   fdd       y# t        $ r}t        t        |            d}~wt        $ r}t        t        |            d}~ww xY w)	z' Fetch a file from container to local. zFETCH r   r   r=   c            	      ^    t        j                  j                  d       dfd      S )Nr   Tc                 P    t         j                  | j                  d            S )Nr   r=   )rI   r   r   )msgr#   s    r'   rD   z9Connection.fetch_file.<locals>.<lambda>.<locals>.<lambda>  s    GLL4??=;YL$Z r9   )ro   r   r   r   log)r   r!   r   )r   r   r#   s   r'   rD   z'Connection.fetch_file.<locals>.<lambda>z  s+    
KK"oom<#%!%Z r9   Tr   N)r,   r   r   rI   rJ   r   r   r(   r   r   r	   r   r   )r#   r   r   r   r8   s   ``` r'   r   zConnection.fetch_fileq  s    j$*7H=:Q^A_`))'2	; +/  
 " 	6%in55" 	;*9S>::	;s$   A0 0	B29BB2B--B2c                 8    t         t        |           d| _        y)z3 Terminate the connection. Nothing to do for DockerFN)r,   r   r   rH   )r#   r8   s    r'   r   zConnection.close  s    j$%'r9   c                 8    | j                   j                          y N)r/   clearrC   s    r'   resetzConnection.reset  s    r9   )Fr   )NF)__name__
__module____qualname____doc__	transporthas_pipeliningr(   r-   rG   r   r   r   r   r   r   __classcell__)r8   s   @r'   r   r      sB    *-IN0
 V.bIH1$(;T;0 
r9   r   )*
__future__r   r   r   type__metaclass__DOCUMENTATIONr   os.pathansible.errorsr   r   +ansible.module_utils.common.text.convertersr   r	   r
   ansible.module_utils.sixr   ansible.plugins.connectionr   ansible.utils.displayr   Dansible_collections.community.docker.plugins.module_utils.common_apir   >ansible_collections.community.docker.plugins.module_utils.copyr   r   r   r   Hansible_collections.community.docker.plugins.plugin_utils.socket_handlerr   Dansible_collections.community.docker.plugins.plugin_utils.common_apir   Eansible_collections.community.docker.plugins.module_utils._api.errorsr   r   r   Aansible_collections.community.docker.plugins.module_utils.versionr   rK   rI   r   rq   r9   r'   <module>r      sw   
 C BbH 
  H T T 1 5 )  v u Z ) r9   