
    2.a`D                         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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 G d de      Z G d de      Zd Zy)    N   )	APIClient)DEFAULT_DATA_CHUNK_SIZE)
BuildErrorImageLoadErrorInvalidArgument)parse_repository_tag)json_stream   )
CollectionModelc                   `    e Zd ZdZd Zed        Zed        Zed        Zd Z	e
dfdZdd
Zy	)Imagez!
    An image on the server.
    c                     dj                  | j                  j                  dj                  | j                              S )Nz
<{}: '{}'>z', ')format	__class____name__jointagsselfs    6/usr/lib/python3/dist-packages/docker/models/images.py__repr__zImage.__repr__   s,    ""4>>#:#:FKK		<RSS    c                 J    | j                   d   j                  d      }|xs i S )z7
        The labels of an image as dictionary.
        ConfigLabelsattrsget)r   results     r   labelszImage.labels   s'    
 H%))(3|r   c                 t    | j                   j                  d      r| j                   dd S | j                   dd S )f
        The ID of the image truncated to 10 characters, plus the ``sha256:``
        prefix.
        sha256:N   
   )id
startswithr   s    r   short_idzImage.short_id   s6     77i(773B<wws|r   c                 v    | j                   j                  d      }|g }|D cg c]
  }|dk7  s	| c}S c c}w )z#
        The image's tags.
        RepoTagsz<none>:<none>r   )r   r   tags      r   r   z
Image.tags&   s;    
 zz~~j)<D#>so'=>>>s   
66c                 `    | j                   j                  j                  | j                        S )z
        Show the history of an image.

        Returns:
            (str): The history of the image.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        )clientapihistoryr(   r   s    r   r1   zImage.history0   s!     {{&&tww//r   Fc                     | j                   }|rK| j                  r| j                  d   n|}t        |t              r|| j                  vrt	        | d      |}| j
                  j                  j                  ||      S )a  
        Get a tarball of an image. Similar to the ``docker save`` command.

        Args:
            chunk_size (int): The generator will return up to that much data
                per iteration, but may return less. If ``None``, data will be
                streamed as it is received. Default: 2 MB
            named (str or bool): If ``False`` (default), the tarball will not
                retain repository and tag information for this image. If set
                to ``True``, the first tag in the :py:attr:`~tags` list will
                be used to identify the image. Alternatively, any element of
                the :py:attr:`~tags` list can be used as an argument to use
                that specific tag as the saved identifier.

        Returns:
            (generator): A stream of raw archive data.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.

        Example:

            >>> image = cli.images.get("busybox:latest")
            >>> f = open('/tmp/busybox-latest.tar', 'wb')
            >>> for chunk in image.save():
            >>>   f.write(chunk)
            >>> f.close()
        r   z" is not a valid tag for this image)r(   r   
isinstancestrr   r/   r0   	get_image)r   
chunk_sizenamedimgs       r   savez
Image.save=   su    < gg"&))$))A,C%%		)) '!CD  {{((j99r   Nc                 j     | j                   j                  j                  | j                  |fd|i|S )a  
        Tag this image into a repository. Similar to the ``docker tag``
        command.

        Args:
            repository (str): The repository to set for the tag
            tag (str): The tag name
            force (bool): Force

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.

        Returns:
            (bool): ``True`` if successful
        r-   )r/   r0   r-   r(   r   
repositoryr-   kwargss       r   r-   z	Image.tagg   s/    " #t{{""477JJCJ6JJr   N)r   
__module____qualname____doc__r   propertyr"   r*   r   r1   r   r9   r-    r   r   r   r      sa    T     ? ?0 6U (:TKr   r   c                        e Zd ZdZ fdZed        Zed        ZddZd Z	d Z
ej                  j                  e
_         xZS )	RegistryDatazO
    Image metadata stored on the registry, including available platforms.
    c                 2    t        |   |i | || _        y r>   )super__init__
image_name)r   rI   argsr=   r   s       r   rH   zRegistryData.__init__   s    $)&)$r   c                 &    | j                   d   d   S )z'
        The ID of the object.
        
Descriptordigest)r   r   s    r   r(   zRegistryData.id   s    
 zz,'11r   c                      | j                   dd S )r$   Nr&   )r(   r   s    r   r*   zRegistryData.short_id   s     wws|r   c                     t        | j                        \  }}| j                  j                  || j                  |      S )z
        Pull the image digest.

        Args:
            platform (str): The platform to pull the image for.
            Default: ``None``

        Returns:
            (:py:class:`Image`): A reference to the pulled image.
        )r-   platform)r	   rI   
collectionpullr(   )r   rP   r<   _s       r   rR   zRegistryData.pull   s6     -T__=
A##JDGGh#OOr   c                 j   |rt        |t              so|j                  d      }t        |      dkD  st        |      dk  rt	        d| d      d|d   i}t        |      dkD  r|d   |d	<   t        |      dkD  r|d   |d
<   t        || j                  j                               | j                  d   v S )a  
        Check whether the given platform identifier is available for this
        digest.

        Args:
            platform (str or dict): A string using the ``os[/arch[/variant]]``
                format, or a platform dictionary.

        Returns:
            (bool): ``True`` if the platform is recognized as available,
            ``False`` otherwise.

        Raises:
            :py:class:`docker.errors.InvalidArgument`
                If the platform argument is not a valid descriptor.
        /   r   "z$" is not a valid platform descriptorosr   r   variantarchitecture	Platforms)	r3   dictsplitlenr   normalize_platformr/   versionr   )r   rP   partss      r   has_platformzRegistryData.has_platform   s    " Jx6NN3'E5zA~Ua%z!EF  eAh'H5zA~&+Ah#5zA~+08(!dkk))+
ZZ$% 	%r   c                 l    | j                   j                  j                  | j                        | _        y r>   )r/   r0   inspect_distributionrI   r   r   s    r   reloadzRegistryData.reload   s     [[__99$//J
r   r>   )r   r?   r@   rA   rH   rB   r(   r*   rR   rb   re   r   __classcell__)r   s   @r   rE   rE   {   s\    % 2 2  P%@K \\))FNNr   rE   c                   j   e Zd ZeZd Zd ZddZddZd Z	ddZ
ddZej                  j                  e_        d	 Zej                  j                  e_        d
 Zej                   j                  e_        ddZej$                  j                  e_        d Zej&                  j                  e_        y)ImageCollectionc                     | j                   j                  j                  di |}t        |t              r| j                  |      S d}d}t        j                  t        |            \  }}|D ]G  }d|v rt        |d   |      d|v r,t        j                  d|d         }|r|j                  d      }|}I |r| j                  |      |fS t        |xs d|      )a  
        Build an image and return it. Similar to the ``docker build``
        command. Either ``path`` or ``fileobj`` must be set.

        If you have a tar file for the Docker build context (including a
        Dockerfile) already, pass a readable file-like object to ``fileobj``
        and also pass ``custom_context=True``. If the stream is compressed
        also, set ``encoding`` to the correct value (e.g ``gzip``).

        If you want to get the raw output of the build, use the
        :py:meth:`~docker.api.build.BuildApiMixin.build` method in the
        low-level API.

        Args:
            path (str): Path to the directory containing the Dockerfile
            fileobj: A file object to use as the Dockerfile. (Or a file-like
                object)
            tag (str): A tag to add to the final image
            quiet (bool): Whether to return the status
            nocache (bool): Don't use the cache when set to ``True``
            rm (bool): Remove intermediate containers. The ``docker build``
                command now defaults to ``--rm=true``, but we have kept the old
                default of `False` to preserve backward compatibility
            timeout (int): HTTP timeout
            custom_context (bool): Optional if using ``fileobj``
            encoding (str): The encoding for a stream. Set to ``gzip`` for
                compressing
            pull (bool): Downloads any updates to the FROM image in Dockerfiles
            forcerm (bool): Always remove intermediate containers, even after
                unsuccessful builds
            dockerfile (str): path within the build context to the Dockerfile
            buildargs (dict): A dictionary of build arguments
            container_limits (dict): A dictionary of limits applied to each
                container created by the build process. Valid keys:

                - memory (int): set memory limit for build
                - memswap (int): Total memory (memory + swap), -1 to disable
                    swap
                - cpushares (int): CPU shares (relative weight)
                - cpusetcpus (str): CPUs in which to allow execution, e.g.,
                    ``"0-3"``, ``"0,1"``
            shmsize (int): Size of `/dev/shm` in bytes. The size must be
                greater than 0. If omitted the system uses 64MB
            labels (dict): A dictionary of labels to set on the image
            cache_from (list): A list of images used for build cache
                resolution
            target (str): Name of the build-stage to build in a multi-stage
                Dockerfile
            network_mode (str): networking mode for the run commands during
                build
            squash (bool): Squash the resulting images layers into a
                single layer.
            extra_hosts (dict): Extra hosts to add to /etc/hosts in building
                containers, as a mapping of hostname to IP address.
            platform (str): Platform in the format ``os[/arch[/variant]]``.
            isolation (str): Isolation technology used during build.
                Default: `None`.
            use_config_proxy (bool): If ``True``, and if the docker client
                configuration file (``~/.docker/config.json`` by default)
                contains a proxy configuration, the corresponding environment
                variables will be set in the container being built.

        Returns:
            (tuple): The first item is the :py:class:`Image` object for the
                image that was build. The second item is a generator of the
                build logs as JSON-decoded objects.

        Raises:
            :py:class:`docker.errors.BuildError`
                If there is an error during the build.
            :py:class:`docker.errors.APIError`
                If the server returns any other error.
            ``TypeError``
                If neither ``path`` nor ``fileobj`` is specified.
        Nerrorstreamz*(^Successfully built |sha256:)([0-9a-f]+)$r   UnknownrC   )r/   r0   buildr3   r4   r    	itertoolsteer
   r   researchgroup)	r   r=   resp
last_eventimage_idresult_streaminternal_streamchunkmatchs	            r   rm   zImageCollection.build   s    X %t{{$$.v.dC 88D>!
)2{47H)I&$ 
	E% w??5 		A(O ${{1~HJ
	 HHX&660y-@@r   c                 j    | j                  | j                  j                  j                  |            S )am  
        Gets an image.

        Args:
            name (str): The name of the image.

        Returns:
            (:py:class:`Image`): The image.

        Raises:
            :py:class:`docker.errors.ImageNotFound`
                If the image does not exist.
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        )prepare_modelr/   r0   inspect_image)r   names     r   r    zImageCollection.get*  s(      !!$++//"?"?"EFFr   Nc                 |    t        || j                  j                  j                  ||      | j                  |       S )a  
        Gets the registry data for an image.

        Args:
            name (str): The name of the image.
            auth_config (dict): Override the credentials that are found in the
                config for this request.  ``auth_config`` should contain the
                ``username`` and ``password`` keys to be valid.

        Returns:
            (:py:class:`RegistryData`): The data object.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        )rI   r   r/   rQ   )rE   r/   r0   rd   )r   r}   auth_configs      r   get_registry_dataz!ImageCollection.get_registry_data<  s6    " ++//66t[I;;	
 	
r   c                     | j                   j                  j                  |||      }|D cg c]  }| j                  |d          c}S c c}w )a  
        List images on the server.

        Args:
            name (str): Only show images belonging to the repository ``name``
            all (bool): Show intermediate image layers. By default, these are
                filtered out.
            filters (dict): Filters to be processed on the image list.
                Available filters:
                - ``dangling`` (bool)
                - `label` (str|list): format either ``"key"``, ``"key=value"``
                    or a list of such.

        Returns:
            (list of :py:class:`Image`): The images.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        )r}   allfiltersId)r/   r0   imagesr    )r   r}   r   r   rs   rs         r   listzImageCollection.listT  sD    * {{%%4S'%J+/0a4!000s   Ac                 L   | j                   j                  j                  |      }g }|D ]U  }d|v r=t        j                  d|d         }|r"|j                  d      }|j                  |       d|v sIt        |d          |D cg c]  }| j                  |       c}S c c}w )a  
        Load an image that was previously saved using
        :py:meth:`~docker.models.images.Image.save` (or ``docker save``).
        Similar to ``docker load``.

        Args:
            data (binary): Image data to be loaded.

        Returns:
            (list of :py:class:`Image`): The images.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        rk   z)(^Loaded image ID: |^Loaded image: )(.+)$r   rj   )	r/   r0   
load_imagerp   rq   rr   appendr   r    )r   datars   r   rx   ry   ru   is           r   loadzImageCollection.loadl  s      {{))$/ 
	5E5 		@(O ${{1~HMM(+%$U7^44
	5 &,,,,,s   B!c           	      n   t        |      \  }}|xs |xs d}d|v rt        j                  d       |d=  | j                  j                  j
                  |f|d|d|}|D ]  } |s=| j                  dj                  |||j                  d      r
d            S d	            S | j                  |      S )
a  
        Pull an image of the given name and return it. Similar to the
        ``docker pull`` command.
        If ``tag`` is ``None`` or empty, it is set to ``latest``.
        If ``all_tags`` is set, the ``tag`` parameter is ignored and all image
        tags will be pulled.

        If you want to get the raw pull output, use the
        :py:meth:`~docker.api.image.ImageApiMixin.pull` method in the
        low-level API.

        Args:
            repository (str): The repository to pull
            tag (str): The tag to pull
            auth_config (dict): Override the credentials that are found in the
                config for this request.  ``auth_config`` should contain the
                ``username`` and ``password`` keys to be valid.
            platform (str): Platform in the format ``os[/arch[/variant]]``
            all_tags (bool): Pull all image tags

        Returns:
            (:py:class:`Image` or list): The image that has been pulled.
                If ``all_tags`` is True, the method will return a list
                of :py:class:`Image` objects belonging to this repository.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.

        Example:

            >>> # Pull the image tagged `latest` in the busybox repo
            >>> image = client.images.pull('busybox')

            >>> # Pull all tags in the busybox repo
            >>> images = client.images.pull('busybox', all_tags=True)
        latestrk   zH`stream` is not a valid parameter for this method and will be overriddenT)r-   rk   all_tagsz	{0}{2}{1}r%   @:)
r	   warningswarnr/   r0   rR   r    r   r)   r   )r   r<   r-   r   r=   	image_tagpull_logrS   s           r   rR   zImageCollection.pull  s    L !5Z @
I*Y*(vMM* x '4;;??''
x
CI
  	A 		
 88K..Cy(A  GJ   yy$$r   c                 T     | j                   j                  j                  |fd|i|S )Nr-   )r/   r0   pushr;   s       r   r   zImageCollection.push  s'    #t{{##JBCB6BBr   c                 P     | j                   j                  j                  |i | y r>   )r/   r0   remove_imager   rJ   r=   s      r   removezImageCollection.remove  s    $$$d5f5r   c                 N     | j                   j                  j                  |i |S r>   )r/   r0   rq   r   s      r   rq   zImageCollection.search  s"    %t{{%%t6v66r   c                 N    | j                   j                  j                  |      S )N)r   )r/   r0   prune_images)r   r   s     r   prunezImageCollection.prune  s    {{++G+<<r   c                 N     | j                   j                  j                  |i |S r>   )r/   r0   prune_buildsr   s      r   r   zImageCollection.prune_builds  s"    +t{{++T<V<<r   r>   )NFN)NF)r   r?   r@   r   modelrm   r    r   r   r   rR   r   r   rA   r   r   rq   r   r   r   rC   r   r   rh   rh      s    E_ABG$
010-@<%|C>>))DL6++33FN7%%--FN=**22EM=$1199Lr   rh   c                 >    | i } d| vr|d   | d<   d| vr|d   | d<   | S )NrX   OsrZ   ArchrC   )rP   engine_infos     r   r_   r_     s?    8$T*X%#.v#6 Or   )rn   rp   r   r0   r   	constantsr   errorsr   r   r   utilsr	   utils.json_streamr
   resourcer   r   r   rE   rh   r_   rC   r   r   <module>r      sW     	   / @ @ ( + 'kKE kK\H*5 H*VV:j V:rr   