
    a_aI                        d dl Z d dlZd dlZd dlmZ d dlZd dlZd dlZddlm	Z	 ddl
mZmZmZmZmZmZmZmZ ddlmZmZmZmZ ddlmZ ddlmZ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dlm+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? 	 ddlm@Z@ 	 ddlmBZB  G d dej                  e*e+e-e/e1e3e5e7e9e;e=e?      ZDy# eA$ r Y 0w xY w# eA$ r Y 4w xY w)    N)partial   )auth)DEFAULT_NUM_POOLSDEFAULT_NUM_POOLS_SSHDEFAULT_MAX_POOL_SIZEDEFAULT_TIMEOUT_SECONDSDEFAULT_USER_AGENTIS_WINDOWS_PLATFORMMINIMUM_DOCKER_API_VERSIONSTREAM_HEADER_SIZE_BYTES)DockerExceptionInvalidVersionTLSParameterError$create_api_error_from_http_exception)	TLSConfig)SSLHTTPAdapterUnixHTTPAdapter)check_resourceconfigupdate_headersutils)json_stream)ProxyConfig)consume_socket_outputdemux_adaptorframes_iter   )BuildApiMixin)ConfigApiMixin)ContainerApiMixin)DaemonApiMixin)ExecApiMixin)ImageApiMixin)NetworkApiMixin)PluginApiMixin)SecretApiMixin)ServiceApiMixin)SwarmApiMixin)VolumeApiMixin)NpipeHTTPAdapter)SSHHTTPAdapterc            	       ~    e Zd ZdZej
                  j                  g dz   Zddededdde	f	 fd	Z
d Zd Zed        Zed	        Zed
        Zed        Zd Zd Zd"dZd Zd#dZ ed      d#d       Zd Zd Zd$dZd Zd Zd%dZd&dZd Z  ed      d        Z!d Z"d Z#d Z$ fdZ%e&d         Z'd#d!Z( xZ)S )'	APIClientaW  
    A low-level client for the Docker Engine API.

    Example:

        >>> import docker
        >>> client = docker.APIClient(base_url='unix://var/run/docker.sock')
        >>> client.version()
        {u'ApiVersion': u'1.33',
         u'Arch': u'amd64',
         u'BuildTime': u'2017-11-19T18:46:37.000000000+00:00',
         u'GitCommit': u'f4ffd2511c',
         u'GoVersion': u'go1.9.2',
         u'KernelVersion': u'4.14.3-1-ARCH',
         u'MinAPIVersion': u'1.12',
         u'Os': u'linux',
         u'Version': u'17.10.0-ce'}

    Args:
        base_url (str): URL to the Docker server. For example,
            ``unix:///var/run/docker.sock`` or ``tcp://127.0.0.1:1234``.
        version (str): The version of the API to use. Set to ``auto`` to
            automatically detect the server's version. Default: ``1.35``
        timeout (int): Default timeout for API calls, in seconds.
        tls (bool or :py:class:`~docker.tls.TLSConfig`): Enable TLS. Pass
            ``True`` to enable it with default options, or pass a
            :py:class:`~docker.tls.TLSConfig` object to use custom
            configuration.
        user_agent (str): Set a custom user agent for requests to the server.
        credstore_env (dict): Override environment variables when calling the
            credential store process.
        use_ssh_client (bool): If set to `True`, an ssh connection is made
            via shelling out to the ssh client. Ensure the ssh client is
            installed and configured on the host.
        max_pool_size (int): The maximum number of connections
            to save in the pool.
    )_auth_configs_general_configs_versionbase_urltimeoutNFc
                    t         |           |r|st        d      || _        || _        || j
                  d<   t        j                         | _        | j                  j                  di       }
	 |
|   }t        j                  |      | _        t        j                  | j                  |      | _        || _        t%        j&                  |t(        t+        |            }|j-                  d      r
|xs t.        nt0        }|j-                  d      rKt3        ||||		      | _        | j7                  d
| j4                         | j9                  dd       d| _        n|j-                  d      rJt(        st;        d      	 t=        ||||		      | _        | j7                  d
| j4                         d| _        n|j-                  d      rL	 tA        ||||	|      | _        | j7                  d| j4                         | j9                  dd       d| _        nXtC        |tD              r|jG                  |        n/|r-tI        |      | _        | j7                  d| j4                         || _        |#tC        |tJ              r)|jM                         dk(  r| jO                         | _(        n|| _(        tC        | jP                  tJ              s-t;        djS                  tU        |      jV                              t%        jX                  | jP                  tZ              rt]        djS                  tZ                    y # t        $ r |
j                  di       }Y w xY w# t>        $ r t;        d      w xY w# t>        $ r t;        d      w xY w)Nz5If using TLS, the base_url argument must be provided.z
User-Agentproxiesdefault)config_dictcredstore_env)tlszssh://zhttp+unix://)pool_connectionsmax_pool_sizezhttp+docker://http://https://zhttp+docker://localhostznpipe://z2The npipe:// protocol is only supported on Windowsz4Install pypiwin32 package to enable npipe:// supporthttp+docker://localnpipe)r:   r;   	shell_outz1Install paramiko package to enable ssh:// supporthttp+docker://ssh)r:   autoz4Version parameter must be a string or None. Found {}z>API versions below {} are no longer supported by this library.)/super__init__r   r2   r3   headersr   load_general_configr0   getKeyErrorr   	from_dict_proxy_configsr   load_configr/   r8   r   
parse_hostr   bool
startswithr   r   r   _custom_adaptermount_unmountr   r+   	NameErrorr,   
isinstancer   configure_clientr   strlower_retrieve_server_versionr1   formattype__name__
version_ltr   r   )selfr2   versionr3   r9   
user_agent	num_poolsr8   use_ssh_clientr;   proxy_configr5   	__class__s               3/usr/lib/python3/dist-packages/docker/api/client.pyrC   zAPIClient.__init__i   sW   
 	x#G  !%/\" & : : <,,00B?	6"8,G *33G<!----]
 +##)tCy

 ) 6!6/@ 	 ~.#2'I+$D  JJ')=)=>MM)Z0 6DM  ,&%H '7g	"/($ JJ')=)=>6DM  *'5g	"/>($ JJ*D,@,@AMM)Z0/DM #y)$$T*'5%.(0$

:t';';<$DM ?z ' # " '.mmo&? 99;DM#DM$---!FMMM** 
 DMM+EF !6"<=  Ga  	6"&&y"5G	6J  %J   %G s*   2L< M M6 <MMM36Nc                     	 | j                  d      d   S # t        $ r t        d      t        $ r}t        d|       d }~ww xY w)NF)api_version
ApiVersionzAInvalid response from docker daemon: key "ApiVersion" is missing.z)Error while fetching server API version: )r\   rG   r   	Exception)r[   es     rb   rV   z"APIClient._retrieve_server_version   s`    
	<<E<2<@@ 	!   	!;A3? 	s    AAAc                 >    |j                  d| j                         |S )zjPrepare the kwargs for an HTTP request by inserting the timeout
        parameter, if not already present.r3   )
setdefaultr3   )r[   kwargss     rb   _set_request_timeoutzAPIClient._set_request_timeout   s     	)T\\2    c                 F     | j                   |fi | j                  |      S N)postrk   r[   urlrj   s      rb   _postzAPIClient._post   s#    tyyB 9 9& ABBrl   c                 F     | j                   |fi | j                  |      S rn   )rF   rk   rp   s      rb   _getzAPIClient._get   #    txxAt88@AArl   c                 F     | j                   |fi | j                  |      S rn   )putrk   rp   s      rb   _putzAPIClient._put   ru   rl   c                 F     | j                   |fi | j                  |      S rn   )deleterk   rp   s      rb   _deletezAPIClient._delete   s#    t{{3D$";";F"CDDrl   c           	         |D ]6  }t        |t              rt        dj                  |t	        |                   t        t        j                  j                  d      }t        ||      }|j                  dd      r4dj                  | j                  | j                   |j                  |       S | j                    |j                  |  S )Nz+Expected a string but found {} ({}) insteadz/:)safeversioned_apiTz{}/v{}{})rR   rT   
ValueErrorrW   rX   r   urllibparsequotemaprF   r2   r1   )r[   pathfmtargsrj   argquote_fs         rb   _urlzAPIClient._url   s     	Cc3' $fS$s)4 	 &,,,,487D!::ot,$$t}}ngnnd.C  mm_^W^^T%:$;<<rl   c                     	 |j                          y# t        j                  j                  $ r}t	        |      d}~ww xY w)z1Raises stored :class:`APIError`, if one occurred.N)raise_for_statusrequests
exceptions	HTTPErrorr   )r[   responserg   s      rb   _raise_for_statuszAPIClient._raise_for_status	  s:    	:%%'"",, 	:6q99	:s    A ;A c                     |r|rJ | j                  |       |r|j                         S |r|j                  S |j                  S rn   )r   jsoncontenttext)r[   r   r   binarys       rb   _resultzAPIClient._result  sC    V$$x(==?"###}}rl   c                     i }|:t        |t              r*t        |j                               D ]  \  }}|	|||<    n||}d|vri |d<   d|d   d<    | j                  |fdt        j                  |      i|S )NrD   zapplication/jsonzContent-Typedata)rR   dictiteritemsrr   r   dumps)r[   rq   r   rj   data2kvs          rb   
_post_jsonzAPIClient._post_json  s     
4 6TZZ\* !1= E!H! EF" "F9,>y.)tzz#@DJJu$5@@@rl   c                     |xs ddddS )Nr   )stdoutstderrstream )r[   overrides     rb   _attach_paramszAPIClient._attach_params*  s     

 	
rl   	containerc                    | j                  d|      }t        j                  d|| j                  |            }|j	                         j
                  }|j                  ddd      }|j                  ddd      }| j                  |      S )	Nz/containers/{0}/attach/wsPOST)paramsr<   zws://r   r=   zwss://)r   r   Requestr   preparerq   replace_create_websocket_connection)r[   r   r   rq   reqfull_urls         rb   _attach_websocketzAPIClient._attach_websocket1  s|    ii3Y?vs43F3Fv3NO;;=$$##Iw:##J!<00::rl   c                 ,    t        j                  |      S rn   )	websocketcreate_connection)r[   rq   s     rb   r   z&APIClient._create_websocket_connection:  s    **3//rl   c                    | j                  |       | j                  dk(  r5|j                  j                  j                  j                  j
                  }n| j                  j                  d      r+|j                  j                  j                  j                  }nQ|j                  j                  j                  j                  }| j                  j                  d      r|j                  }	 ||_	        |S # t        $ r Y |S w xY w)Nr>   r@   r=   )r   r2   raw_fpfpsockrM   channel_sock	_responseAttributeError)r[   r   r   s      rb   _get_raw_response_socketz"APIClient._get_raw_response_socket=  s    x(==66<<##&&**//D]]%%&9:<<##&&..D<<##&&**D}}''
3zz	 &DN   	 	s   .C7 7	DDc              #     K   |j                   j                  j                  r|r$t        | j	                  |d            E d{    y|j                   }|j
                  sd|j                  d      }|sy|j                  j                  r(||j                  |j                  j                        z  }| |j
                  scyy| j                  ||       y7 w)z?Generator for data coming from a chunked-encoded HTTP response.FNr   )r   )	r   r   chunkedr   _stream_helperclosedread
chunk_leftr   )r[   r   decodereaderr   s        rb   r   zAPIClient._stream_helperS  s      <<##&t':':8U'KLLL! --!;;q>Dzz,,FJJ,A,A BBJ !-- ,,xf,55 Ms   ACCA?CCc              #      K   | j                  |d      }t        |      }d}	 ||z
  t        k  ry|||t        z    }t        j                  d|      \  }}|t        z   }||z   }	|	}|||	  Jw)zMA generator of multiplexed data blocks read from a buffered
        response.Tr   r   >BxxxLN)r   lenr   structunpack_from)
r[   r   buf
buf_lengthwalkerheader_lengthstartends
             rb   _multiplexed_buffer_helperz$APIClient._multiplexed_buffer_helperh  s      ll8Dl1X
F"%==)A ABF**8V<IAv55E&.CFeC.  s   A,A.c              #     K   | j                  |      }| j                  |       	 |j                  j                  t              }|syt        j                  d|      \  }}|s?|j                  j                  |      }|sy| aw)zMA generator of multiplexed data blocks coming from a response
        stream.r   N)r   _disable_socket_timeoutr   r   r   r   unpack)r[   r   socketr   r   r   r   s          rb   #_multiplexed_response_stream_helperz-APIClient._multiplexed_response_stream_helperx  s      ..x8$$V,\\&&'?@Fh7IAv<<$$V,DJ s   BBc              #      K   | j                  |       | j                  |      }| j                  |       |j                  ||      E d{    y7 w)z< Stream result for TTY-enabled container and raw binary dataN)r   r   r   iter_content)r[   r   
chunk_sizer   r   s        rb   _stream_raw_resultzAPIClient._stream_raw_result  sJ     x( ..x8$$V,((V<<<s   A	AAAc                     | j                  |      }t        ||      }|r
d |D        }n	d |D        }|r|S t        ||      S )Nc              3   ,   K   | ]  }t        |   y wrn   )r   ).0frames     rb   	<genexpr>z.APIClient._read_from_socket.<locals>.<genexpr>  s     :U=%(:s   c              3   &   K   | ]	  \  }}|  y wrn   r   )r   r   r   s      rb   r   z.APIClient._read_from_socket.<locals>.<genexpr>  s     -IQ4-s   )demux)r   r   r   )r[   r   r   ttyr   r   gens          rb   _read_from_socketzAPIClient._read_from_socket  sN    ..x8&#&:c:C .-CJ )E::rl   c                     |t        |dd      g}|D ]F  }t        |d      sd}t        |d      r|j                         }||dk(  r6|j                  d       H y)a   Depending on the combination of python version and whether we're
        connecting over http or https, we might need to access _sock, which
        may or may not exist; or we may need to just settimeout on socket
        itself, which also may or may not have settimeout on it. To avoid
        missing the correct one, we try both.

        We also do not want to set the timeout if it is already disabled, as
        you run the risk of changing a socket that was non-blocking to
        blocking, for example when using gevent.
        r   N
settimeout
gettimeoutg        )getattrhasattrr   r   )r[   r   socketssr3   s        rb   r   z!APIClient._disable_socket_timeout  si     767D9: 	A1l+Gq,',,. 'S.LL	rl   c                 4    | j                  |      }|d   d   S )NConfigTty)inspect_container)r[   r   conts      rb   _check_is_ttyzAPIClient._check_is_tty  s!    %%i0H~e$$rl   c                 F    | j                  ||| j                  |            S rn   )_get_result_ttyr   )r[   r   r   ress       rb   _get_resultzAPIClient._get_result  s"    ##FC1C1CI1NOOrl   c                    |r&|r| j                  |      S | j                  |d      S | j                  |       d}|r| j                  |      S |j	                  | j                  |      D cg c]  }| c}      S c c}w )NTr   rl   )r   r   r   r   joinr   )r[   r   r   is_ttysepxs         rb   r   zAPIClient._get_result_tty  s     394**3/ /S./ 	s#;;C@@88 ;;C@AqA As   -	A=c                 H    |D ]  }| j                   j                  |        y rn   )adapterspop)r[   r   protos      rb   rP   zAPIClient._unmount  s#     	%EMMe$	%rl   c                     	 t         |   |      S # t        j                  j                  $ r$}| j
                  r| j
                  cY d }~S |d }~ww xY wrn   )rB   get_adapterr   r   InvalidSchemarN   )r[   rq   rg   ra   s      rb   r  zAPIClient.get_adapter  sN    	7&s++""00 	##+++		s     AAAAAc                     | j                   S rn   )r1   )r[   s    rb   rd   zAPIClient.api_version  s    }}rl   c                 P    t        j                  || j                        | _        y)a.  
        Force a reload of the auth configuration

        Args:
            dockercfg_path (str): Use a custom path for the Docker config file
                (default ``$HOME/.docker/config.json`` if present,
                otherwise ``$HOME/.dockercfg``)

        Returns:
            None
        )r8   N)r   rJ   r8   r/   )r[   dockercfg_paths     rb   reload_configzAPIClient.reload_config  s"     "--$*<*<
rl   )FFrn   )F)r   T)TF)*rY   
__module____qualname____doc__r   Session	__attrs__r	   r
   r   rC   rV   rk   r   rr   rt   rx   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rP   r  propertyrd   r
  __classcell__)ra   s   @rb   r.   r.   /   sJ   $L   ** .9 9I !%d0e.$#E4	iV C C B B B B E E=$:A 
 K ; !;0,6*! *	=;$8 K % !%P %  
rl   r.   )Er   r   r   	functoolsr   r   requests.exceptionsr    r   	constantsr   r   r   r	   r
   r   r   r   errorsr   r   r   r   r9   r   	transportr   r   r   r   r   r   utils.json_streamr   utils.proxyr   utils.socketr   r   r   buildr   r    r   r!   daemonr"   exec_apir#   imager$   networkr%   pluginr&   secretr'   servicer(   swarmr)   volumer*   r+   ImportErrorr,   r  r.   r   rl   rb   <module>r&     s           O O O< <  7 A A + % L L   " ( " "   $ " " $   "	,	*
N
N
  		
  		s$   >C- C8 -C54C58D ?D 