
    Vh@                     d   d dl mZmZmZ eZd dlZd dlZd dlZd dl	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mZmZ d dlmZ d dlmZmZ  G d de      Z G d d	e      Z G d
 de      Zd ZddZddZddZddZ ddZ!ddZ"ddZ# G d dejH                        Z%d Z&ddZ'ddZ(ddZ)ddZ*y)     )absolute_importdivisionprint_functionN)to_bytes	to_nativeto_text)
raise_from)APIErrorNotFoundc                       e Zd Zy)DockerFileCopyErrorN__name__
__module____qualname__     n/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/docker/plugins/module_utils/copy.pyr   r          r   r   c                       e Zd Zy)DockerUnexpectedErrorNr   r   r   r   r   r      r   r   r   c                       e Zd Zy)DockerFileNotFoundNr   r   r   r   r   r       r   r   r   c                     | j                  d|      }| j                  |d|i|      }| j                  |       |j                  dk(  S )N/containers/{0}/archivepath)paramsdata   )_url_put_raise_for_statusstatus_code)client	containerr   r   urlress         r   _put_archiver(   $   sJ     ++/
;C
++c64.t+
<C
S!??c!!r   c                 .   t        j                  |j                        st        d      t	        j
                         }t        j                  |ddd      5 }|j                  | t        |            }	||	_
        d|	_        |r||	_        ||	_        d|	_        |	xj                  dz  c_        |||	_        |	j                         st        d      |j!                  |	       d d d        |j#                         S # 1 sw Y   |j#                         S xY w)	Nz%stat information is not for a symlinkzw|Fzutf-8)fileobjmodedereferenceencoding)arcname   )statS_ISLNKst_moder   ioBytesIOtarfileopen
gettarinfor   uidunamegidgnamer+   issymaddfilegetvalue)
	b_in_path	file_statout_fileuser_idgroup_idr+   	user_namebiotartarinfos
             r   _symlink_tar_creatorrI   -   s    <<	))*#$KLL
**,C	c%'	R VY ..GH4E.F%GMGL}}'(OPPG!" <<>#" <<>s   BC<<Dc           	   #   2   K   t        | ||||||       y wN)rI   )r@   rA   rB   rC   rD   r+   rE   s          r   _symlink_tar_generatorrL   E   s     
y)XwRVXa
bbs   c              #     K   t        j                  |j                        st        d      t	        j
                         }t        j                  j                  t        |            d   j                  t        j                  d      j                  d      |_        ||j                  dz  n||_        ||_        ||_        |j"                  |_        |j&                  |_        t        j*                  |_        d|_        |r||_        |j3                         }t5        |      }	| |j$                  }
|	|
z  }	t7        | d      5 }|
dkD  r8t9        |
d      }|j;                  |      }|sn|
t5        |      z  }
| |
dkD  r8d d d        |
rt        j<                  |
z   |j$                  t        j>                  z  }|r<t        j<                  t        j>                  |z
  z   |	t        j>                  |z
  z  }	t        j<                  d	t        j>                  z  z   |	d	t        j>                  z  z  }	|	t        j@                  z  }|dkD  r't        j<                  t        j@                  |z
  z   y y # 1 sw Y   xY ww)
Nz*stat information is not for a regular file   /r0   r/   rbr   i      )!r1   S_ISREGr3   r   r6   TarInfoosr   
splitdriver   replaceseplstripnamer+   r9   r;   st_sizesizest_mtimemtimeREGTYPEtypelinknamer:   tobuflenr7   minreadNUL	BLOCKSIZE
RECORDSIZE)r@   rA   rB   rC   rD   r+   rE   rH   tarinfo_buf
total_sizer[   fto_readbuf	remainders                  r   _regular_file_tar_generatorrn   I   s    <<	))*#$PQQooG77%%gh&78;CCBFFCPWWX[\GL26,I%%-DGLGKGK$$GL&&GM??GLG!--/K[!J
<<D$J	i	 !Qh$&G&&/CCHDI Qh  kkD  w000IkkW..:;;g'')33
 ++W...
//!g''''JW///I1}kkW//);<< 1 s   EJ=I;C6J;J Jc           	   #     K   t        j                         }t        j                  j	                  t        |            d   j                  t        j                  d      j                  d      |_	        ||_
        ||_        ||_        t        |       |_        	 t        t         j                   j#                         j%                               |_        t         j.                  |_        d|_        |r||_        |j7                         }t        |      }| |t        |       z  }|  |j                  t         j8                  z  }	|	r<t         j:                  t         j8                  |	z
  z   |t         j8                  |	z
  z  }t         j:                  dt         j8                  z  z   |dt         j8                  z  z  }|t         j<                  z  }	|	dkD  r't         j:                  t         j<                  |	z
  z   y y # t(        $ rV t        t         j                   j+                         t!        j                   ddd      z
  j-                               |_        Y w xY ww)NrN   rO   i  r/   rQ   r   )r6   rS   rT   r   rU   r   rV   rW   rX   rY   r+   r9   r;   rb   r[   intdatetimenow	timestampr]   AttributeErrorutcnowtotal_secondsr^   r_   r`   r:   ra   rf   re   rg   )
contentrB   rC   rD   r+   rE   rH   rh   ri   rm   s
             r   _regular_content_tar_generatorrx   z   s    ooG77%%gh&78;CCBFFCPWWX[\GLGLGKGKw<GLjH--113==?@
 ??GLG!--/K[!J
#g,J
Mw000IkkW..:;;g'')33
 ++W...
//!g''''JW///I1}kkW//);<< 7  j X..557(:K:KDRSUV:WWffhijs,   BI#:H D-I#AI I#I  I#c	           	         t         j                  j                  t        |d            st	        dt        |      z        t        |d      }	t         j                  j                  |      \  }
}|rt        j                  |	      }nt        j                  |	      }t        j                  |j                        rt        |	||||||      }net        j                  |j                        rt        |	||||||      }n3t        dj                  |rdnd|t!        |j                                    t#        | ||
|      }|st%        dj                  ||            y	)
/Transfer a file from local to Docker container.surrogate_or_stricterrorsz!file or module does not exist: %s)r+   rE   zDFile{0} {1} is neither a regular file nor a symlink (stat mode {2}).z referenced byr/   ;Unknown error while creating file "{0}" in container "{1}".N)rT   r   existsr   r   r   splitr1   lstatrR   r3   rn   r2   rL   r   formatoctr(   r   )r$   r%   in_pathout_pathrC   rD   r+   rE   follow_linksr@   out_dirrB   rA   streamoks                  r   put_filer      s;   77>>(73HIJ /)G2DDF 	F )>?Ih/GXGGI&	HHY'	||I%%&,Y	8WV^eiu~	i''	('	9hQY`dpyz!RYY$0 b'3yGXGXCY[\ 	\ 
fi&	9B#$a$h$hiqs|$}~~ r   c                     t         j                  j                  |      \  }}	t        ||	||||      }
t	        | |||
      }|st        dj                  ||            y)rz   )rE   r~   N)rT   r   r   rx   r(   r   r   )r$   r%   rw   r   rC   rD   r+   rE   r   rB   r   r   s               r   put_file_contentr      sb    h/GX+GXwRVbklF	fi&	9B#$a$h$hiqs|$}~~ r   c           	         t               }	 ||v rt        dj                  |            |j                  |       |r |d|z         | j	                  | j                  d|      d|i      }|j                  dk(  r|ddfS | j                  |       |j                  j                  d      }	 t        j                  t        j                  |            }|d   dz  dk7  rN|d   }
|s|||
fS t         j"                  j%                  t         j"                  j'                  |      d   |
      }$||dfS # t        $ r#}	t        d	j                  ||||	
            d}	~	ww xY w)aJ  Fetch information on a file from a Docker container to local.

    Return a tuple ``(path, stat_data, link_target)`` where:

    :path: is the resolved path in case ``follow_links=True``;
    :stat_data: is ``None`` if the file does not exist, or a dictionary with fields
        ``name`` (string), ``size`` (integer), ``mode`` (integer, see https://pkg.go.dev/io/fs#FileMode),
        ``mtime`` (string), and ``linkTarget`` (string);
    :link_target: is ``None`` if the file is not a symlink or when ``follow_links=False``,
        and a string with the symlink target otherwise.
    z>Found infinite symbolic link loop when trying to stating "{0}"zFETCH: Stating "%s"r   r   )r   i  Nzx-docker-container-path-statz{When retrieving information for {in_path} from {container}, obtained header {header!r} that cannot be loaded as JSON: {exc})r   r%   headerexcr+   i   r   
linkTarget)setr   r   add_headr    r#   r"   headersgetjsonloadsbase64	b64decode	Exceptionr   rT   r   joinr   )r$   r%   r   r   logconsidered_in_pathsresponser   	stat_datar   link_targets              r   	stat_filer      su    %
))%&f&m&mnu&vww(%/0<<KK19=G$   
 3&D$&&  *!!%%&DE	

6#3#3F#;<I V.!3#L1K	;66ggll277==#9!#<kJG	4''  	' N9VQTU 	s   .(D4 4	E =EE c                   $    e Zd Zd Zd Zd Zd Zy)_RawGeneratorFileobjc                      || _         d| _        y )Nr   )_stream_buf)selfr   s     r   __init__z_RawGeneratorFileobj.__init__   s    	r   c                      y)NTr   )r   s    r   readablez_RawGeneratorFileobj.readable   s    r   c                     t        ||z
  t        | j                              }|r.| j                  d | ||||z    | j                  |d  | _        ||z  }|S rK   )rc   rb   r   )r   bindexlengthcpys        r   _readinto_from_bufz'_RawGeneratorFileobj._readinto_from_buf  sV    &5.#dii.1#'99Tc?AeECK 		#$DISLEr   c                     d}t        |      }| j                  |||      }||k(  r|S 	 | xj                  t        | j                        z  c_        | j                  |||      S # t
        $ r |cY S w xY w)Nr   )rb   r   r   nextr   StopIteration)r   r   r   r   s       r   readintoz_RawGeneratorFileobj.readinto  sy    Q''5&9F?L	IIdll++I &&q%88  	L	s   (A$ $A21A2N)r   r   r   r   r   r   r   r   r   r   r   r      s    9r   r   c                 B    t        |       }t        j                  |      S )zTGiven a generator that generates chunks of bytes, create a readable buffered stream.)r   r4   BufferedReader)r   raws     r   _stream_generator_to_fileobjr     s    
v
&CS!!r   c	                    t               }		 ||	v rt        dj                  |            |	j                  |       |r |d|z         	 | j	                  d|d|iddi      }
t        j                  t        |
      d	
      5 }d}d}d}|D ]H  }|rt        d      d}|j                         r|}%|j                         r ||||      }@ |||      }J |rv|s |||      cddd       S t        j                  j                  t        j                  j                  |      d   |j                         }|r |d|z         	 ddd       C|r|cddd       S t        d      # t
        $ r  ||      cY S w xY w# 1 sw Y   nxY w)zDFetch a file (as a tar file entry) from a Docker container to local.Tz<Found infinite symbolic link loop when trying to fetch "{0}"zFETCH: Fetching "%s"r   r   zAccept-Encodingidentity)r   r   zr|)r*   r+   NFz-Received tarfile contains more than one file!r   z&FETCH: Following symbolic link to "%s"zReceived tarfile is empty!)r   r   r   r   get_raw_streamr   r6   r7   r   r   r=   isfilerT   r   r   r   r`   )r$   r%   r   process_noneprocess_regularprocess_symlinkprocess_otherr   r   r   r   rG   symlink_memberresultfoundmembers                   r   fetch_file_exr   !  s   %
))%&d&k&kls&tuu(&01	)**)9(*J7 + F \\">v"FTR 	FVY!NFE 
8/0_``<<>%+N==?,Wc6BF&w7
8 #*7NC#	F 	F$ '',,rww}}W'=a'@.BYBYZ@7JK+	F 	F, /	F 	F0 ((DEE7  	)((	)	F 	F! s2   	E& A E=,AE=E=E=&E:9E:=Fc                 p   
 t        |d      
fd}
fd}
fd}d }	t        | |||||	|	      S )Nr{   r|   c                 <    t        dj                  |             )Nz6File {in_path} does not exist in container {container}r   r%   )r   r   r   s    r   r   z fetch_file.<locals>.process_noneS  s!     DVGyV9
 	
r   c                    s4t         j                  j                        rt        j                         |j	                  |      }t        d      5 }t        j                  ||       d d d        | S # 1 sw Y   | S xY w)Nwb)rT   r   r   unlinkextractfiler7   shutilcopyfileobj)r   rG   r   in_fout_f
b_out_pathr   s        r   r   z#fetch_file.<locals>.process_regularY  se    z :IIj!v&*d# 	,utU+	,	,s   A66B c                     t         j                  j                        rt        j                         t        j                  |j
                         | S rK   )rT   r   r   r   symlinkr`   )r   r   r   s     r   r   z#fetch_file.<locals>.process_symlinkb  s6    77>>*%IIj!


6??J/r   c                     t        d| z        )Nz9Remote file "%s" is not a regular file or a symbolic link)r   )r   r   s     r   r   z!fetch_file.<locals>.process_otheri  s    !"]`g"ghhr   )r   r   )r   r   )r$   r%   r   r   r   r   r   r   r   r   r   s    `  `     @r   
fetch_filer   P  sT    (+@AJ
i G\?Tcer  BN  TW  X  Xr   c           	      4   |r |dj                  ||             |dddddd|d}d| j                  v r| j                  d   |d<   	 | j                  d||	      }d   }ddd}| j                  d|ddd      \  }	}
| j                  d|      }|j                  d      xs d}|	xs d}	|
xs d}
|r |dj                  ||	|
             |r3|dk7  r.t        dj                  dj                  |      |||	|
            ||	|
fS # t        $ r/}t	        t        d
j                  |            |       Y d }~d }~wt        $ rP}|j                  >|j                  j                  dk(  r%t	        t        dj                  |            |        d }~ww xY w)Nz"Executing {command} in {container})commandr%   r/   FT)	ContainerUser
PrivilegedTtyAttachStdinAttachStdoutAttachStderrCmd
detachKeysz/containers/{0}/exec)r   z&Could not find container "{container}")r%   i  z8Cannot execute command in paused container "{container}"Id)r   Detachz/exec/{0}/start)r   demuxttyz/exec/{0}/jsonExitCoder   r   z4Exit code {rc}, stdout {stdout!r}, stderr {stderr!r})rcstdoutstderrzmObtained unexpected exit code {rc} when running "{command}" in {container}.
STDOUT: {stdout}
STDERR: {stderr} )r   r%   r   r   r   )r   _general_configspost_json_to_jsonr   r	   r   r
   r   r#   post_json_to_streamget_jsonr   r   r   )r$   r%   r   r   check_rcr   	exec_dataeexec_idr   r   r   r   s                r   _execute_commandr   o  s   
077S\7]^ 	D v...#44\B\,,-CYUY,Z	 oG D //0A7SX`djo/pNFF__-w7F	J		$1B]sF]sF
BIIRX^gmInoB!G#}VCHHW-rRXagVh
 	

 vvG  
 H O OZc O de	
 	
  ::!ajj&<&<&C#$^$e$epy$e$z{ 	s%   D 	F%D;;FAFFc                 B   t        | |g dd|      \  }}}|j                         }t        |      dk7  r&t        dj	                  |t        |      |            |\  }}	 t        |      t        |      fS # t        $ r t        dj	                  |||            w xY w)	N)z/bin/shz-czid -u && id -gT)r   r   rQ   zlExpected two-line output to obtain user and group ID for container {container}, but got {lc} lines:
{stdout})r%   lcr   zExpected two-line output with numeric IDs to obtain user and group ID for container {container}, but got "{l1}" and "{l2}" instead)r%   l1l2)r   
splitlinesrb   r   r   rp   
ValueError)	r$   r%   r   dummyr   r   stdout_linesrC   rD   s	            r   determine_user_groupr     s    ,VY@cnrx{|E66$$&L
<A#{ViC,=fVM
 	

 %GX
7|S]** 
# QViGVA
 	

s   !A7 7'B)NNrK   )NNF)FN)NF)+
__future__r   r   r   r_   __metaclass__r   rq   r4   r   rT   os.pathr   r1   r6   +ansible.module_utils.common.text.convertersr   r   r   ansible.module_utils.sixr	   Eansible_collections.community.docker.plugins.module_utils._api.errorsr
   r   r   r   r   r   r(   rI   rL   rn   rx   r   r   r   	RawIOBaser   r   r   r   r   r   r   r   r   <module>r     s   
 C B   	  	     T T / d	) 		/ 		, 	"0c.=b%=P:.(b92<< 9@",F^X>7t
r   