
    Vhի                     6   d dl mZmZmZ eZdZdZd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mZ d d	l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$ d dl%m&Z&m'Z' d dl(m)Z)m*Z* d dl+m,Z,m-Z- ddZ. G d de      Z/d Z0e1dk(  r e0        yy)    )absolute_importdivisionprint_functiona(  
module: docker_image

short_description: Manage docker images

description:
  - Build, load or pull an image, making the image available for creating containers. Also supports tagging an image, pushing
    an image, and archiving an image to a C(.tar) file.
  - We recommend to use the individual modules M(community.docker.docker_image_build), M(community.docker.docker_image_export),
    M(community.docker.docker_image_load), M(community.docker.docker_image_pull), M(community.docker.docker_image_push),
    M(community.docker.docker_image_remove), and M(community.docker.docker_image_tag) instead of this module.
notes:
  - Building images is done using Docker daemon's API. It is not possible to use BuildKit / buildx this way. Use M(community.docker.docker_image_build)
    to build images with BuildKit.
extends_documentation_fragment:
  - community.docker.docker.api_documentation
  - community.docker.attributes
  - community.docker.attributes.actiongroup_docker

attributes:
  check_mode:
    support: partial
    details:
      - When trying to pull an image, the module assumes this is always changed in check mode.
  diff_mode:
    support: none
  idempotent:
    support: partial
    details:
      - Whether the module is idempotent depends on the exact parameters, in particular of O(force_source) and O(force_tag).
      # TODO: improve idempotent details!

options:
  source:
    description:
      - Determines where the module will try to retrieve the image from.
      - Use V(build) to build the image from a C(Dockerfile). O(build.path) must be specified when this value is used.
      - Use V(load) to load the image from a C(.tar) file. O(load_path) must be specified when this value is used.
      - Use V(pull) to pull the image from a registry.
      - Use V(local) to make sure that the image is already available on the local docker daemon. This means that the module
        does not try to build, pull or load the image.
    type: str
    choices:
      - build
      - load
      - pull
      - local
  build:
    description:
      - Specifies options used for building images.
    type: dict
    suboptions:
      cache_from:
        description:
          - List of image names to consider as cache source.
        type: list
        elements: str
      dockerfile:
        description:
          - Use with O(state=present) and O(source=build) to provide an alternate name for the Dockerfile to use when building
            an image.
          - This can also include a relative path (relative to O(build.path)).
        type: str
      http_timeout:
        description:
          - Timeout for HTTP requests during the image build operation. Provide a positive integer value for the number of
            seconds.
        type: int
      path:
        description:
          - Use with state 'present' to build an image. Will be the path to a directory containing the context and Dockerfile
            for building an image.
        type: path
        required: true
      pull:
        description:
          - When building an image downloads any updates to the FROM image in Dockerfile.
        type: bool
        default: false
      rm:
        description:
          - Remove intermediate containers after build.
        type: bool
        default: true
      network:
        description:
          - The network to use for C(RUN) build instructions.
        type: str
      nocache:
        description:
          - Do not use cache when building an image.
        type: bool
        default: false
      etc_hosts:
        description:
          - Extra hosts to add to C(/etc/hosts) in building containers, as a mapping of hostname to IP address.
          - Instead of an IP address, the special value V(host-gateway) can also be used, which resolves to the host's gateway
            IP and allows building containers to connect to services running on the host.
        type: dict
      args:
        description:
          - Provide a dictionary of C(key:value) build arguments that map to Dockerfile ARG directive.
          - Docker expects the value to be a string. For convenience any non-string values will be converted to strings.
        type: dict
      container_limits:
        description:
          - A dictionary of limits applied to each container created by the build process.
        type: dict
        suboptions:
          memory:
            description:
              - Memory limit for build in format C(<number>[<unit>]). Number is a positive integer. Unit can be V(B) (byte),
                V(K) (kibibyte, 1024B), V(M) (mebibyte), V(G) (gibibyte), V(T) (tebibyte), or V(P) (pebibyte).
              - Omitting the unit defaults to bytes.
              - Before community.docker 3.6.0, no units were allowed.
            type: str
          memswap:
            description:
              - Total memory limit (memory + swap) for build in format C(<number>[<unit>]), or the special values V(unlimited)
                or V(-1) for unlimited swap usage. Number is a positive integer. Unit can be V(B) (byte), V(K) (kibibyte,
                1024B), V(M) (mebibyte), V(G) (gibibyte), V(T) (tebibyte), or V(P) (pebibyte).
              - Omitting the unit defaults to bytes.
              - Before community.docker 3.6.0, no units were allowed, and neither was the special value V(unlimited).
            type: str
          cpushares:
            description:
              - CPU shares (relative weight).
            type: int
          cpusetcpus:
            description:
              - CPUs in which to allow execution.
              - For example, V(0-3) or V(0,1).
            type: str
      use_config_proxy:
        description:
          - If set to V(true) and a proxy configuration is specified in the docker client configuration (by default C($HOME/.docker/config.json)),
            the corresponding environment variables will be set in the container being built.
        type: bool
      target:
        description:
          - When building an image specifies an intermediate build stage by name as a final stage for the resulting image.
        type: str
      platform:
        description:
          - Platform in the format C(os[/arch[/variant]]).
        type: str
        version_added: 1.1.0
      shm_size:
        description:
          - Size of C(/dev/shm) in format C(<number>[<unit>]). Number is positive integer. Unit can be V(B) (byte), V(K) (kibibyte,
            1024B), V(M) (mebibyte), V(G) (gibibyte), V(T) (tebibyte), or V(P) (pebibyte).
          - Omitting the unit defaults to bytes. If you omit the size entirely, Docker daemon uses V(64M).
        type: str
        version_added: 3.6.0
      labels:
        description:
          - Dictionary of key value pairs.
        type: dict
        version_added: 3.6.0
  archive_path:
    description:
      - Use with O(state=present) to archive an image to a C(.tar) file.
    type: path
  load_path:
    description:
      - Use with O(state=present) to load an image from a C(.tar) file.
      - Set O(source=load) if you want to load the image.
    type: path
  force_source:
    description:
      - Use with O(state=present) to build, load or pull an image (depending on the value of the O(source) option) when the
        image already exists.
    type: bool
    default: false
  force_absent:
    description:
      - Use with O(state=absent) to un-tag and remove all images matching the specified name.
    type: bool
    default: false
  force_tag:
    description:
      - Use with O(state=present) to force tagging an image.
    type: bool
    default: false
  name:
    description:
      - 'Image name. Name format will be one of: C(name), C(repository/name), C(registry_server:port/name). When pushing or
        pulling an image the name can optionally include the tag by appending C(:tag_name).'
      - Note that image IDs (hashes) are only supported for O(state=absent), for O(state=present) with O(source=load), and
        for O(state=present) with O(source=local).
    type: str
    required: true
  pull:
    description:
      - Specifies options used for pulling images.
    type: dict
    version_added: 1.3.0
    suboptions:
      platform:
        description:
          - When pulling an image, ask for this specific platform.
          - Note that this value is not used to determine whether the image needs to be pulled. This might change in the future
            in a minor release, though.
        type: str
  push:
    description:
      - Push the image to the registry. Specify the registry as part of the O(name) or O(repository) parameter.
    type: bool
    default: false
  repository:
    description:
      - Use with O(state=present) to tag the image.
      - Expects format C(repository:tag). If no tag is provided, will use the value of the O(tag) parameter or V(latest).
      - If O(push=true), O(repository) must either include a registry, or will be assumed to belong to the default registry
        (Docker Hub).
    type: str
  state:
    description:
      - Make assertions about the state of an image.
      - When V(absent) an image will be removed. Use the force option to un-tag and remove all images matching the provided
        name.
      - When V(present) check if an image exists using the provided name and tag. If the image is not found or the force option
        is used, the image will either be pulled, built or loaded, depending on the O(source) option.
    type: str
    default: present
    choices:
      - absent
      - present
  tag:
    description:
      - Used to select an image when pulling. Will be added to the image when pushing, tagging or building. Defaults to V(latest).
      - If O(name) parameter format is C(name:tag), then tag value from O(name) will take precedence.
    type: str
    default: latest

requirements:
  - "Docker API >= 1.25"

author:
  - Pavel Antonov (@softzilla)
  - Chris Houseknecht (@chouseknecht)
  - Sorin Sbarnea (@ssbarnea)

seealso:
  - module: community.docker.docker_image_build
  - module: community.docker.docker_image_export
  - module: community.docker.docker_image_info
  - module: community.docker.docker_image_load
  - module: community.docker.docker_image_pull
  - module: community.docker.docker_image_push
  - module: community.docker.docker_image_remove
  - module: community.docker.docker_image_tag
aF  
---
- name: Pull an image
  community.docker.docker_image:
    name: pacur/centos-7
    source: pull
  # Select platform for pulling. If not specified, will pull whatever docker prefers.
    pull:
      platform: amd64

- name: Tag and push to docker hub
  community.docker.docker_image:
    name: pacur/centos-7:56
    repository: dcoppenhagan/myimage:7.56
    push: true
    source: local

- name: Tag and push to local registry
  community.docker.docker_image:
  # Image will be centos:7
    name: centos
  # Will be pushed to localhost:5000/centos:7
    repository: localhost:5000/centos
    tag: 7
    push: true
    source: local

- name: Add tag latest to image
  community.docker.docker_image:
    name: myimage:7.1.2
    repository: myimage:latest
  # As 'latest' usually already is present, we need to enable overwriting of existing tags:
    force_tag: true
    source: local

- name: Remove image
  community.docker.docker_image:
    state: absent
    name: registry.ansible.com/chouseknecht/sinatra
    tag: v1

- name: Build an image and push it to a private repo
  community.docker.docker_image:
    build:
      path: ./sinatra
    name: registry.ansible.com/chouseknecht/sinatra
    tag: v1
    push: true
    source: build

- name: Archive image
  community.docker.docker_image:
    name: registry.ansible.com/chouseknecht/sinatra
    tag: v1
    archive_path: my_sinatra.tar
    source: local

- name: Load image from archive and push to a private registry
  community.docker.docker_image:
    name: localhost:5000/myimages/sinatra
    tag: v1
    push: true
    load_path: my_sinatra.tar
    source: load

- name: Build image and with build args
  community.docker.docker_image:
    name: myimage
    build:
      path: /path/to/build/dir
      args:
        log_volume: /var/log/myapp
        listen_port: 8080
    source: build

- name: Build image using cache source
  community.docker.docker_image:
    name: myimage:latest
    build:
      path: /path/to/build/dir
    # Use as cache source for building myimage
      cache_from:
        - nginx:latest
        - alpine:3.8
    source: build
z
image:
  description: Image inspection results for the affected image.
  returned: success
  type: dict
  sample: {}
stdout:
  description: Docker build output when building an image.
  returned: success
  type: str
  sample: ""
  version_added: 1.0.0
N)	to_native)human_to_bytes)AnsibleDockerClientRequestException)archived_image_manifestapi_image_idImageArchiveInvalidException)"clean_dict_booleans_for_docker_apiDockerBaseClassis_image_name_idis_valid_tag)LooseVersion)get_config_headerresolve_repository_name)DEFAULT_DATA_CHUNK_SIZECONTAINER_LIMITS_KEYS)DockerExceptionNotFound)process_dockerfiletar)format_extra_hostsparse_repository_tagc           	          | | S 	 || dt        |      fv r|S t        |       S # t        $ r+}|j                  d|dt	        |             Y d }~y d }~ww xY w)N	unlimitedzFailed to convert z to bytes: )msg)strr   
ValueError	fail_jsonr   )valuemodulenameunlimited_valueexcs        q/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/docker/plugins/modules/docker_image.pyconvert_to_bytesr(     sj    }[&5[#oBV4W+W""e$$ [D)TW.YZZ[s   $ 
$ 	A!AAc                   r     e Zd Z fdZd Zd Zd Zed        Zd Z	ddZ
ddZed	        Zd
 Zd Z xZS )ImageManagerc                    t         t        |           || _        || _        | j                  j
                  j                  }| j                  j                  | _        |d   | _        |d   xs
 t               }|d   xs
 t               }|d   | _
        |j                  d      | _        |j                  d      | _        | j                  rId| j                  v r;t        | j                  d   | j                  j
                  d      | j                  d<   | j                  rKd	| j                  v r=t        | j                  d	   | j                  j
                  d
d      | j                  d	<   |j                  d      | _        |d   | _        |d   | _        |d   | _        |d   | _        |d   | _        |j                  d      | _        t-        |j                  d            | _        |j                  dd      | _        |j                  d      | _        |j                  d      | _        |j                  d      | _        |d   | _        |j                  dd      | _        |d   | _        |d   | _        |j                  d      | _         |j                  d      | _!        |d    | _"        |j                  d!      | _#        |j                  d      | _$        |j                  d"      | _%        t        |j                  d#      | j                  j
                  d$      | _&        t-        |j                  d%            | _'        tQ        | j(                        s(tS        | j(                        \  }}|r|| _        || _        | j8                  r3tQ        | j8                        r| jU                  d&| j8                  z         | j8                  s?| jD                  r3tQ        | j(                        r| jU                  d'| j(                  z         | j<                  d(k(  r| jW                          y*| j<                  d)k(  r| jY                          y*y*)+a  
        Configure a docker_image task.

        :param client: Ansible Docker Client wrapper over Docker client
        :type client: AnsibleDockerClient
        :param results: This task adds its output values to this dictionary
        :type results: dict
        sourcebuildpullarchive_path
cache_fromcontainer_limitsmemoryzbuild.container_limits.memorymemswapzbuild.container_limits.memswap)r%   
dockerfileforce_sourceforce_absent	force_tag	load_pathr$   network	etc_hostsnocacheFpathtarget
repositoryrmTstatetaghttp_timeoutplatformpushargsuse_config_proxyshm_sizezbuild.shm_sizelabelsz-`repository` must not be an image ID; got: %sz]Cannot push an image by ID; specify `repository` to tag and push the image with ID %s insteadpresentabsentN)-superr*   __init__clientresultsr#   params
check_moder,   dictr/   getr0   r1   r(   r5   r6   r7   r8   r9   r$   r:   r   extra_hostsr<   
build_pathr.   r>   r?   r@   rA   rB   rC   pull_platformrE   	buildargsbuild_platformrG   rH   rI   r   r   failrJ   rK   )	selfrN   rO   
parametersr-   r.   reporepo_tag	__class__s	           r'   rM   zImageManager.__init__  s    	lD*,[[''..
++00 *7#-tv&!+TV&~6))L1 %		*< =  X1F1F%F.>%%h/1C1CEd/fD!!(+  Y$2G2G%G/?%%i0$++2D2DFfxz0|D!!),))L1&~6&~6#K0#K0v&	yy+=eii>TUyyE2))F+IIf%	ii)$\2))D$'(
e$!IIn5!XXj1v&	6*#ii
3 %		*< =(:)>@R@RTde889LM  		*1$))<ND( 	# ??/@IIEWX4991A$))1LIIux|  yB  yB  B  C::"LLNZZ8#KKM $    c                 :    | j                   j                  |       y N)rN   rY   )rZ   r   s     r'   rY   zImageManager.fail  s    r_   c                 >
   t        | j                        r(| j                  j                  | j                  d      }n1| j                  j	                  | j                  | j
                        }|r| j                  r| j                  dk(  r6t        | j                        r| j                  d| j                  z         t        j                  j                  | j                        s| j                  d| j                  z         | j                  }| j
                  r| j                  d| j
                  }| j                  d|z         | j                  d	   j                  d
|d| j                         d| j                  d<   | j                   s| j                  j#                  | j%                                nZ| j                  dk(  rt        j                  j'                  | j(                        s,| j                  d| j                  d| j(                  d       | j                  }| j
                  r&t        |      s| j                  d| j
                  }| j                  d	   j                  d|d| j(                         d| j                  d<   | j                   sn| j+                         | j                  d<   nO| j                  dk(  rt        | j                        r| j                  d| j                  z         | j                  d	   j                  d| j                  d| j
                         d| j                  d<   | j                   s| j                  j-                  | j                  | j
                  | j.                        \  | j                  d<   }nm| j                  dk(  r^|\| j                  }| j
                  r&t        |      s| j                  d| j
                  }| j                  j                  d|z         | j                   s9|r7|d   | j                  d   d   k(  rd| j                  d<   n|| j                  d<   | j0                  r&| j3                  | j                  | j
                         | j4                  r3| j6                  s'| j9                  | j                  | j
                         y| j6                  r>| j;                  | j                  | j
                  | j6                  | j4                         yy)z
        Handles state = 'present', which includes building, loading or pulling an image,
        depending on user provided parameters.

        :returns None
        Taccept_missing_imager$   rB   r-   z<Image name must not be an image ID for source=build; got: %szERequested build path %s could not be found or you do not have access.:zBuilding image %sactionszBuilt image z from changedloadError loading image z. Specified path z does not exist.zLoaded image imager.   z;Image name must not be an image ID for source=pull; got: %szPulled image )rB   rD   localNz!Cannot find the image %s locally.IdF)rE   )r   r$   rN   find_image_by_id
find_imagerB   r6   r,   rY   osr=   isdirrU   logrO   appendrQ   updatebuild_imageisfiler9   
load_image
pull_imagerV   r/   archive_imagerE   r?   
push_image	tag_image)rZ   rk   
image_namedummyr$   s        r'   rJ   zImageManager.present  s    DII&KK00QU0VEKK**		txx*HE)){{g%#DII.II\_c_h_hhi ww}}T__5IIehlhwhwwx!YY
88,0IItxx!@J,z9:Y'..:W[WfWf/gh*.Y'LL''(8(8(:;&ww~~dnn5II]a]f]f]a]k]km n!YY
88$4Z$@,0IItxx!@JY'..JX\XfXf/gh*.Y',0OO,=DLL)&#DII.II[^b^g^ggh Y'..tyyRVRZRZ/[\*.Y'37;;3I3I$))Y]YaYalpl~l~3I30DLL)5'=99Dxx(8(>*.))TXX>KK$$%H4%OP??utW@UVZ@[1[*/Y'$)DLL!tyy$((399T__OODIItxx0__NN499dhhdiiNP r_   c           	         | j                   }t        |      r| j                  j                  |d      }nM| j                  j	                  || j
                        }| j
                  r| j                   d| j
                  }|rz| j                  s+	 | j                  j                  d|d| j                  i       d| j                  d
<   | j                  d   j                  d|z         d| j                  d   d<   y	y	# t        $ r Y Ot        $ r*}| j                  d|dt        |             Y d	}~|d	}~ww xY w)zY
        Handles state = 'absent', which removes an image.

        :return None
        Trc   rf   z/images/{0}forcerP   zError removing image  - Nrh   rg   zRemoved image %sDeletedrk   rA   )r$   r   rN   rn   ro   rB   rQ   delete_jsonr7   r   	ExceptionrY   r   rO   rs   )rZ   r$   rk   r&   s       r'   rK   zImageManager.absent9  s    yyD!KK00D0QEKK**4:Exx"&))TXX6??WKK++M4RVRcRcHd+e '+DLL#LL#**+=+FG-6DLL!'*      WIIiPSnUVVWs   *D   	D=D= D88D=c                 Z   fd}	 t              }| |d      S |t        |j                        k(  rg|j
                  k(  rydj                  |j
                        } |d|j                  d|      S # t        $ r&} | dt        |      z          |d      cY d}~S d}~ww xY w)	aU  
        If the archive is missing or requires replacement, return an action message.

        :param failure_logger: a logging function that accepts one parameter of type str
        :type failure_logger: Callable
        :param archive_path: Filename to write archive to
        :type archive_path: str
        :param current_image_name: repo:tag
        :type current_image_name: str
        :param current_image_id: Hash, including hash type prefix such as "sha256:"
        :type current_image_id: str

        :returns: Either None, or an Ansible action message.
        :rtype: str
        c                     ddd| S )NzArchived image  to ,  )reasonr/   current_image_names    r'   	build_msgz5ImageManager.archived_image_action.<locals>.build_msgf  s    4FV\]]r_   z3Unable to extract manifest summary from archive: %sz&overwriting an unreadable archive fileNzsince none presentr   zoverwriting archive with image z named )r
   r   r   r   image_id	repo_tagsjoin)failure_loggerr/   r   current_image_idr   archivedr&   r$   s    ``     r'   archived_image_actionz"ImageManager.archived_image_actionT  s    $	^	G.|<H
 122h.?.?!@@FXEY]e]o]oEo99X//0DXM^M^`deff , 	GPS\]`SaabEFF	Gs   A; ;	B*B%B*%B*c           	      \   |sd}t        |      r | j                  j                  |d      }|}n$| j                  j                  ||      }|d|}|s| j	                  d|z         y|d   }| j                  | j                  j                  j                  | j                  ||      }|r| j                  d	   j                  |       |du| j                  d
<   | j                  s| j                  d
   r| j	                  d|z         	 | j                  j                  | j                  j                  | j                  j                  d|      d      t        d      }	 t'        | j                  d      5 }	D ]  }
|	j)                  |
        	 ddd       || j                  d<   y# t         $ r*}| j#                  d|dt%        |             Y d}~wd}~ww xY w# 1 sw Y   OxY w# t         $ r4}| j#                  d| j                  dt%        |             Y d}~d}~ww xY w)a  
        Archive an image to a .tar file. Called when archive_path is passed.

        :param name: Name/repository of the image
        :type name: str
        :param tag: Optional image tag; assumed to be "latest" if None
        :type tag: str | None
        latestTrc   re   rf   z!archive image: image %s not foundNrm   rg   rh   zGetting archive of image %sz/images/{0}/get)streamFzError getting image r   wbzError writing image archive rk   )r   rN   rn   ro   rr   r   r#   debugr/   rO   rs   rQ   _stream_raw_result_get_urlr   r   rY   r   openwrite)rZ   r$   rB   rk   r|   r   actionsaved_imager&   fdchunks              r'   ry   zImageManager.archive_imagex  s    CD!KK00D0QEJKK**#*>E$(#.JHH8:EF ;++DKK,>,>,D,DdFWFWYcemnLL#**62"("4YT\\)%<HH2Z?@X"kk<<KK$$T[[%5%56G%T]a$b+g$++T2 (b!, ((( !&W  X		:yQT~VWWX( (  g		4CTCTV_`cVdeffgsI   AF, $G. :G"G. ,	G5 GG"G+'G. .	H+7*H&&H+c                    t        |      r| j                  d|z         |}|st        |      \  }}t        |      \  }}| j	                  d| j
                  d|d|d|       |r| j                  d   j                  d| j
                  d|d|d|       d| j                  d	<   | j                  sd
}	 d}||}	}|	st        |      \  }}	t        |      \  }
}i }t        | j                  |
      }|r||d<   | j                  j                  | j                  j                  d|      d
|dd|	i      }| j                  j                  |       | j                  j                  |d      D ]P  }| j	                  |d       |j                  d      rt!        |d   d         |j                  d      }|dk(  sOd}R || j                  d	<   | j                  j'                  ||      | j                  d<   | j                  d   st)               | j                  d<   || j                  d   d <   y
y
y
# t         $ r}dt#        |      v r_dt#        |      v r+| j                  d|d|d|dt%        |      d|d       n'| j                  d|d|d|dt#        |      d	       | j                  d|dt%        |             Y d
}~d
}~ww xY w)!z
        If the name of the image contains a repository path, then push the image.

        :param name Name of the image to push.
        :param tag Use a specific tag.
        :return: None
        zCannot push an image ID: %szpush r   /rf   rg   zPushed image Trh   NFzX-Registry-Authz/images/{0}/pushrB   )dataheadersr   rP   decodepretty_printerrorDetailmessagestatusPushingunauthorizedzauthentication requiredzError pushing image r   z. Try logging into z first.z. Does the repository exist?z: re   rk   push_status)r   rY   r   r   rr   r$   rO   rs   rQ   r   rN   
_post_jsonr   _raise_for_status_stream_helperrS   r   r   r   ro   rR   )rZ   r$   rB   r?   registry	repo_namer   rh   push_repositorypush_tagpush_registryr}   r   headerresponseliner&   s                    r'   rz   zImageManager.push_image  s    D!II3d:;
248OJ5jA)$))Xy#NOLL#**DIIW_ajlo+pq&*DLL#??#[#G0:CXO#4H4Y1+B?+S(M5 G.t{{MJF5; 12#{{55(();_M! '# %x0  6  H KK11(; $ : :8D : Q +D988M2"+D,?	,J"KK!%(!3!Y.&*G+ /6DLL+ )-(>(>JTW(>(XW%||G,,0FDLL)7=W%m4S # @ ! [%S14C@ II'/C3QY'[ \ !II'/CS'K LIIj)TW.YZZ[s    =DH; H; ;	KBKKc                    t        |      \  }}|sd}|r|}| j                  j                  ||      }|rdnd}| j                  d|d|       |r| j                  rM|}	t        |      s|r|j                  d|z         s|d|}	| j                  d|	d	|d|       d
| j                  d<   | j                  d   j                  d|	d	|d|       | j                  s	 ||d
d}
| j                  j                  | j                  j                  d|	      |
      }| j                  j                  |       |j                  dk7  rt        d      	 | j                  j                  ||      | j                  d<   |r'|d   | j                  d   d   k(  rd| j                  d<   |r| j#                  ||       yy# t        $ r'}| j                  dt!        |      z         Y d}~d}~ww xY w)a  
        Tag an image into a repository.

        :param name: name of the image. required.
        :param tag: image tag.
        :param repository: path to the repository. required.
        :param push: bool. push the image once it is tagged.
        :return: None
        r   re   foundz	not foundzimage z was rf   ztagging r   Trh   rg   zTagged image )rB   r\   r   z/images/{0}/tagr      zTag operation failed.zError: failed to tag image - %sNrk   rm   F)r   rN   ro   rr   r8   r   endswithrO   rs   rQ   _postr   r   status_coder   rY   r   rz   )rZ   r$   rB   r?   rE   r\   r]   rk   r   r|   rP   resr&   s                r'   r{   zImageManager.tag_image  s    .j9hH&&Dh&? kdE23J#D)c$--c	:R(,c2
HHj$IJ&*DLL#LL#**UY[c+de??R  ( $!%F
 ++++DKK,<,<=NPZ,[dj+kCKK11#6#-'(?@@ . )-(>(>Dh(>(WW%U4[DLL,A$,GG.3DLL+OOD(+  ! RII?)C.PQQRs   'A2G 	G3G..G3c                     d| v sd| v rH| j                  d      xs | j                  d      xs d}|j                  |j                                yy)zX
        Extract text line from stream output and, if found, adds it to output.
        r   r    N)rS   extend
splitlines)r   output	text_lines      r'   _extract_output_linez!ImageManager._extract_output_line  sP    
 tx4/ *Fdhhx.@FBIMM)..01	  0r_   c                 `   dx}}i }i }| j                   r0| j                   j                         D ]  \  }}t        |      ||<    | j                  xs i }|j	                         D ]%  }|t
        vst        dj                  |             | j                  }| j                  j                  d      r| j                  }nt        j                  j                  | j                        st        d      t        j                  j                  | j                  d      }	d}
t        j                  j!                  |	      rbt#        |	      5 }t%        t'        d |j)                         j+                         D cg c]  }|j-                          c}            }
ddd       t/        || j                        }t1        | j                  |
|d	      }| j2                  r| j4                  d
| j2                  n| j4                  |d| j6                  | j8                  | j8                  | j:                  |d}|j=                  |       | j>                  rN| j@                  jB                  jE                         }|j                         D ]  \  }}|jG                  ||        |r&|j=                  dtI        jJ                  |      i       | jL                  r0|j=                  dtI        jJ                  | jL                        i       | jN                  r|j=                  d| jN                  i       | jP                  r|j=                  d| jP                  i       | jR                  &|j=                  dtU        | jR                        i       | jV                  | jV                  |d<   | jX                  | jX                  |d<   | jZ                  r"tI        jJ                  | jZ                        |d<   |d|d<   | j@                  j]                  |       | j@                  j_                  | j@                  ja                  d      |||d| jb                        }||je                          g }| j@                  jg                  |d      D ]  }| ji                  |d       | jk                  ||       |jm                  d      s:|jm                  d      rW|jm                  d      }| jo                  d| j4                  d|jm                  d      d |jm                  d!      d"|       | jo                  d| j4                  d#|jm                  d      d"|        d$j                  |      | j@                  jq                  | j4                  | j2                  %      d&S c c}w # 1 sw Y   
xY w)'z=
        Build an image

        :return: image dict
        Nz"Invalid container_limits key {key})key)zhttp://zhttps://zgit://zgithub.com/zgit@z-You must specify a directory to build in pathz.dockerignorec                      | dk7  xr | d   dk7  S )Nr   r   #r   )xs    r'   <lambda>z*ImageManager.build_image.<locals>.<lambda>G  s    !r'"9adck r_   F)excluder5   gziprf   )tremoteqr<   r@   forcermr.   r5   rW   	cachefromr>   networkmode
extrahostsrD   shmsizerI   zapplication/tarzContent-Typez/buildT)r   rP   r   r   timeoutr   r   errorr   zError building z	 - code: codez, message: r   z, logs: z - message: 
re   )stdoutrk   )9rW   itemsr   r1   keysr   r   formatr5   rU   
startswithrp   r=   rq   	TypeErrorr   existsr   listfilterreadr   stripr   r   rB   r$   r<   r@   r.   rt   rG   rN   _proxy_configsget_environment
setdefaultjsondumpsr0   r>   r:   rT   r   rX   rH   rI   _set_auth_headersr   r   rC   closer   rr   r   rS   rY   ro   )rZ   r   contextr   rW   r   r"   r1   r5   dockerignorer   fr   rP   
proxy_argskvr   build_outputr   s                       r'   ru   zImageManager.build_image*  s     	>>"nn224 2
U!*5!1	#2  006B#((* 	\C//%&J&Q&QVY&Q&Z[[	\ __
??%%&^___Ft/KLL77<<ILGww~~l+,' 1"6923&&(2E2E2GH$H$ G
 ,JHJ$//7zX]^G 59HHDIItxx0$))||''wwII$	
 	&'  33CCEJ"((* +1$$Q*+MM;

9(=>???MM;

4??(CDE;;MM8T[[12<<MM=$,,78'MM<);D<L<L)MNO*!%!4!4F:==$ $F9;;#zz$++6F8&7GN#%%g.;;$$KKX&%% % 
 MMOKK..x.E 	EDHHTH-%%dL9xx 88M*"&((="9KII II'OOF3'OOI6(	*+ II		488G#4lD E	E& ii-[[+++I
 	
c I s   -V#9VV#V##V-c                 	   g }d}	 | j                  d| j                  z         t        | j                  d      5 }| j                  d| j                  z         | j                  j	                  | j                  j                  d      |d      }t        | j                  j                        t        d      k\  rJd}| j                  j                  |d	      D ]'  }| j                  |d
       | j                  ||       ) n@| j                  j                  |       | j                  j                  j                  d       ddd       |rt+               }t+               }|D ]  }|j-                  d      r+|j/                  |t1        d      d j3                                |j-                  d      sQ|j/                  |t1        d      d j3                         j5                                 |s.|s,| j                  j!                  ddj'                  |             t7        | j$                        r| j$                  j5                         }	|	|v}
n| j$                  d| j8                  }	|	|v}
|
rh| j                  j!                  d|	ddj'                  t;        |D cg c]  }d|z  	 c}t=        |      z               ddj'                  |             |j?                  |	       |r]| j                  j                  j                  ddj'                  t;        |D cg c]  }d|z  	 c}t=        |      z                      t7        | j$                        r'| j                  jA                  | j$                  d      S | j                  jC                  | j$                  | j8                        S # 1 sw Y   xxY w# t        $ r}|j                  t        j                  k(  r4| j                  j!                  d| j                  dt#        |             | j                  j!                  d| j$                  dt#        |      dj'                  |             Y d}~ d}~wt(        $ rP}| j                  j!                  d| j$                  dt#        |      dj'                  |             Y d}~wd}~ww xY wc c}w c c}w )zP
        Load an image from a .tar archive

        :return: image dict
        FzOpening image %srbzLoading image from %sz/images/loadT)r   r   z1.23r   r   a:  The API version of your Docker daemon is < 1.23, which does not return the image loading result from the Docker daemon. Therefore, we cannot verify whether the expected image was loaded, whether multiple images where loaded, or whether the load actually succeeded. You should consider upgrading your Docker daemon.NzError opening image r   rj   r   )r   zLoaded image:zLoaded image ID:z7Detected no loaded images. Archive potentially corrupt?rf   z#The archive did not contain image 'z'. Instead, found r   z'%s'.z2The archive contained more images than specified: rc   )"rr   r9   r   rN   r   r   r   api_versionr   r   r   r#   warnEnvironmentErrorerrnoENOENTrY   r   r$   r   r   setr   addlenr   lowerr   rB   sortedr   removern   ro   )rZ   load_output
has_output	image_tarr   r   r&   loaded_imagesloaded_image_idsexpected_imagefound_imagerk   s               r'   rw   zImageManager.load_image  s    
	yHH'$..89dnnd+ y04>>ABkk''(8(8(Hyae'f 7 78L<PP!%J $ : :3t : L ED911$DE KK11#6KK&&++a0 EM"u# Y???3!%%d3+?+@&A&G&G&IJ??#56$((c2D.E.F)G)M)M)O)U)U)WX	Y !)9  !Zcgclclmxcy z		*!%!2,4DD,0IItxx!@,MA  &		&m)TU&5.)TW[\lWm)m"noq  99[1	 ! 3
   0""''		&m)TU&5.)TW[\lWm)m"nost DII&;;//		PT/UU;;))$))TXX>>w     	yyyELL(  $..R[\_R`!abKKdiiSVXaeajajkvawxx 	yKKdiiSVXaeajajkvawxx	y6 *U *UsI   4O DN;O $S&S;O O 	S	BQ--S	9ASS	ra   )F)__name__
__module____qualname__rM   rY   rJ   rK   staticmethodr   ry   rz   r{   r   ru   rw   __classcell__)r^   s   @r'   r*   r*     sf    FPCQJ76 !g !gF4&l?>B.,` 2 2r
hF?r_   r*   c                     t        t        dg d      t        dt        d=i dt        dd      dt        dt        t        d	      t        d	      t        d
	      t        d	                  dt        d	      dt        d
	      dt        d	      dt        dd      dt        dd      dt        dd      dt        dd      dt        d	      dt        d	      dt        d	      dt        d	      dt        d	      dt        d	      dt        d	            t        d	      t        dd      t        dd      t        dd      t        d	      t        dd      t        dt        t        d	                   t        dd      t        d	      t        dd!d"d!g#      t        dd$      %      } d&d!d'gfd'd(d(gfd'd)d*gfg}d+ }d, }d- }t               }t        d.|/      |d0<   t        d1|/      |d2<   t        d1|/      |d3<   t        | |d|4      }t        |j                  j                  d5   d6      s7|j                  d7j                  |j                  j                  d5                |j                  j                  d'   d(k(  rR|j                  j                  d(   r(|j                  j                  d(   j                  d      s|j                  d8       	 t        dg i 9      }t        ||        |j                  j                  d=i | y # t        $ rG}|j                  d:j                  t        |            t        j                         ;       Y d }~y d }~wt        $ rG}|j                  d<j                  t        |            t        j                         ;       Y d }~y d }~ww xY w)>Nr   )r-   ri   r.   rl   )typechoicesrR   r0   r   )r  elementsr1   )r  int)r2   r3   	cpushares
cpusetcpus)r  optionsr5   rC   r:   r<   boolF)r  defaultr=   T)r  requiredr.   r@   rF   rG   r>   r;   rD   rH   rI   )rD   rJ   rK   )r  r  r  r   )r,   r-   r/   r6   r7   r8   r9   r$   r.   rE   r?   rA   rB   rA   r,   r-   ri   r9   c                     | j                   j                  d   xr1 t        | j                   j                  d   j                  d            S )Nr-   r;   )r#   rP   r  rS   rN   s    r'   detect_etc_hostszmain.<locals>.detect_etc_hosts  s<    }}##G,efmm6J6J76S6W6WXc6d1eer_   c                     | j                   j                  d   xr* | j                   j                  d   j                  d      d uS )Nr-   rD   r#   rP   rS   r  s    r'   detect_build_platformz#main.<locals>.detect_build_platform  s=    }}##G,j1E1Eg1N1R1RS]1^fj1jjr_   c                     | j                   j                  d   xr* | j                   j                  d   j                  d      d uS )Nr.   rD   r  r  s    r'   detect_pull_platformz"main.<locals>.detect_pull_platform  s=    }}##F+h0D0DV0L0P0PQ[0\dh0hhr_   z1.27)docker_api_versiondetect_usagezbuild.etc_hostsz1.32zbuild.platformzpull.platform)argument_specrequired_ifsupports_check_modeoption_minimal_versionsrB   )allow_emptyz "{0}" is not a valid docker tag!zIIf "source" is set to "build", the "build.path" option must be specified.)rh   rg   rk   z(An unexpected Docker error occurred: {0})	exceptionzSAn unexpected requests error occurred when trying to talk to the Docker daemon: {0}r   )rR   r   r   r#   rP   rY   r   rS   r*   	exit_jsonr   r   	traceback
format_excr	   )	r%  r&  r  r   r"  r(  rN   rO   es	            r'   mainr/    s   (JK )
%8)
!vt'%(E*U+	8 )
 ')
 5))
 e$)
 fe4)
 6D1)
 651)
 .)
 6")
  "v.!)
" U##)
$ '%)
& u%')
( u%))
* V$+)
 . v&vu5vu5FE2F#ut,vtu%(
  vu-U#y8Y:OPeX.K&MR 
)hZ(	7WI&	6K=)Kfki #f15^n1o-.04]r0s,-/3v\p/qO, #  7	F ,,U3F6==fmm>R>RSX>YZ[}}H%0}}##G,FMM4H4H4Q4U4UV\4]KKcd.
 	VW%*'* w>EEiPQlS_h_s_s_uvv .ahhirstiuv**, 	 	. 	..s$   =6L4 4	O==M??O=OO__main__ra   )2
__future__r   r   r   r  __metaclass__DOCUMENTATIONEXAMPLESRETURNr   r   rp   r,  +ansible.module_utils.common.text.convertersr   +ansible.module_utils.common.text.formattersr   Dansible_collections.community.docker.plugins.module_utils.common_apir   r	   Gansible_collections.community.docker.plugins.module_utils.image_archiver
   r   r   >ansible_collections.community.docker.plugins.module_utils.utilr   r   r   r   Aansible_collections.community.docker.plugins.module_utils.versionr   Cansible_collections.community.docker.plugins.module_utils._api.authr   r   Hansible_collections.community.docker.plugins.module_utils._api.constantsr   r   Eansible_collections.community.docker.plugins.module_utils._api.errorsr   r   Jansible_collections.community.docker.plugins.module_utils._api.utils.buildr   r   Jansible_collections.community.docker.plugins.module_utils._api.utils.utilsr   r   r(   r*   r/  r  r   r_   r'   <module>rA     s    A @||Un
   	  A F
   [ l[}?? }?@Y.x zF r_   