a
   T¥H„£-ìZã                   @   sD   d dl mZmZmZ d dlmZ dd„ Zdd„ ZG dd„ deƒZ	d	S )
é   )ÚauthÚerrorsÚutils)ÚServiceModec                 C   sJ  dd„ }|d ur‚t  | d¡r@d|v r.|ddƒ d|v r@|ddƒ t  | d¡rd| d	¡d
krd|ddƒ t  | d¡r‚d|v r‚|ddƒ |d ur¾t  | d¡r |ddƒ t  | d¡r¾d|v r¾|ddƒ |d urút  | d¡rúd|v rútdd„ |d D ƒƒrú|ddƒ |d urFd|v r&t  | d¡r&|ddƒ | d¡r‚t  | d¡rZ|d  d¡rZ|ddƒ t  | d¡r‚|d  d¡r‚|ddƒ | d¡r| d¡}t  | d¡r>| d ¡r¼|d!dƒ | d"¡d urÖ|d#dƒ | d$¡d urð|d%dƒ | d&¡d ur
|d'dƒ | d(¡d ur$|d)dƒ | d*¡d ur>|d+dƒ t  | d¡r€| d,¡d urf|d)dƒ | d-¡d ur€|d.dƒ t  | d¡rÂ| d/¡d ur¨|d0dƒ | d1¡d urÂ|d2dƒ t  | d3¡rê| d4¡d urê|d5d3ƒ t  | d6¡r| d7¡d ur|d8d6ƒ | d9¡rFt  | d¡rF|d9  d:¡rF|d;dƒ d S )<Nc                 S   s   t  d | |¡¡‚d S )Nz'{} is not supported in API version < {})r   ÚInvalidVersionÚformat)ZparamZmin_version© r   ú6/usr/lib/python3.9/site-packages/docker/api/service.pyÚraise_version_error   s
    ÿÿz0_check_api_features.<locals>.raise_version_errorú1.25ZMaxFailureRatiozUpdateConfig.max_failure_ratioZMonitorzUpdateConfig.monitorz1.28ZFailureActionZrollbackz$UpdateConfig.failure_action rollbackú1.29ZOrderzUpdateConfig.orderÚrollback_configzRollbackConfig.orderz1.32ZPortsc                 s   s   | ]}|  d ¡V  qdS )ZPublishModeN)Úget)Ú.0Úpr   r   r	   Ú	<genexpr>*   ó    z&_check_api_features.<locals>.<genexpr>zEndpointSpec.Ports[].modeZForceUpdateZforce_updateZ	Placementz1.30Z	PlatformszPlacement.platformsz1.27ZPreferenceszPlacement.preferencesÚContainerSpecÚTTYzContainerSpec.ttyZHostnamezContainerSpec.hostnameZHostszContainerSpec.hostsZGroupszContainerSpec.groupsZ	DNSConfigzContainerSpec.dns_configZHealthcheckzContainerSpec.healthcheckZReadOnlyZ
StopSignalzContainerSpec.stop_signalZConfigszContainerSpec.configsZ
PrivilegeszContainerSpec.privilegesz1.35Z	IsolationzContainerSpec.isolationz1.38ZInitzContainerSpec.initZ	ResourcesZGenericResourceszResources.generic_resources)r   Ú
version_ltr   Úany)ÚversionÚtask_templateÚupdate_configÚendpoint_specr   r
   Úcontainer_specr   r   r	   Ú_check_api_features   s    

ÿ




ÿ















r   c                 C   sz   |   ¡ }|d urv| ¡ D ]\\}}|dkrdd|vr8i |d< |d  ¡ D ]\}}|d urD||d |< qDq|d ur|||< q|S )Nr   )ÚcopyÚitems)ÚcurrentÚoverrideZmergedZts_keyZts_valueZcs_keyZcs_valuer   r   r	   Ú_merge_task_templatee   s    
r!   c                   @   sÚ   e Zd Ze d¡ddd„ƒZe d¡e d¡ddd„ƒƒZe d¡e d¡d	d
„ ƒƒZe d¡e d¡dd„ ƒƒZ	e d¡ddd„ƒZ
e d¡e d¡ddd„ƒƒZe d¡ddd„ƒZe d¡e d¡ddd„ƒƒZdS )ÚServiceApiMixinz1.24Nc
                 C   sð   t | j||||	ƒ |  d¡}
i }| di ¡ dd¡}|du rFt d¡‚|r\t|tƒs\t|ƒ}t	 
|¡\}}t	 | |¡}|r‚||d< t | jd¡r |pž| dd¡}||||t |¡|d	œ}|durÈ||d
< |	durØ|	|d< |  | j|
||dd¡S )a  
        Create a service.

        Args:
            task_template (TaskTemplate): Specification of the task to start as
                part of the new service.
            name (string): User-defined name for the service. Optional.
            labels (dict): A map of labels to associate with the service.
                Optional.
            mode (ServiceMode): Scheduling mode for the service (replicated
                or global). Defaults to replicated.
            update_config (UpdateConfig): Specification for the update strategy
                of the service. Default: ``None``
            rollback_config (RollbackConfig): Specification for the rollback
                strategy of the service. Default: ``None``
            networks (:py:class:`list`): List of network names or IDs or
                :py:class:`~docker.types.NetworkAttachmentConfig` to attach the
                service to. Default: ``None``.
            endpoint_spec (EndpointSpec): Properties that can be configured to
                access and load balance a service. Default: ``None``.

        Returns:
            A dictionary containing an ``ID`` key for the newly created
            service.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        z/services/creater   ÚImageNz,Missing mandatory Image key in ContainerSpecúX-Registry-Authr   ÚNetworks)ÚNameÚLabelsÚTaskTemplateÚModer%   ÚEndpointSpecÚUpdateConfigÚRollbackConfig)ÚdataÚheadersT)r   Ú_versionÚ_urlr   r   ZDockerExceptionÚ
isinstanceÚdictr   r   Úresolve_repository_nameÚget_config_headerr   r   ÚpopÚconvert_service_networksÚ_resultÚ
_post_json)Úselfr   ÚnameÚlabelsÚmoder   ÚnetworksÚendpoint_configr   r   Úurlr.   ÚimageÚregistryÚ	repo_nameÚauth_headerr-   r   r   r	   Úcreate_serviceu   sB    $
þ
ÿú	ÿzServiceApiMixin.create_serviceÚservicec                 C   sN   |   d|¡}i }|dur8t | jd¡r0t d¡‚||d< |  | j||dd¡S )aú  
        Return information about a service.

        Args:
            service (str): Service name or ID.
            insert_defaults (boolean): If true, default values will be merged
                into the service inspect output.

        Returns:
            (dict): A dictionary of the server-side representation of the
                service, including all relevant properties.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        ú/services/{0}Nr   z6insert_defaults is not supported in API version < 1.29ZinsertDefaults©ÚparamsT)r0   r   r   r/   r   r   r7   Ú_get)r9   rE   Úinsert_defaultsr?   rH   r   r   r	   Úinspect_serviceÁ   s    ÿzServiceApiMixin.inspect_serviceÚtaskc                 C   s   |   d|¡}|  |  |¡d¡S )a  
        Retrieve information about a task.

        Args:
            task (str): Task ID

        Returns:
            (dict): Information about the task.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        z
/tasks/{0}T)r0   r7   rI   )r9   rL   r?   r   r   r	   Úinspect_taskß   s    zServiceApiMixin.inspect_taskc                 C   s$   |   d|¡}|  |¡}|  |¡ dS )a  
        Stop and remove a service.

        Args:
            service (str): Service name or ID

        Returns:
            ``True`` if successful.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        rF   T)r0   Ú_deleteZ_raise_for_status)r9   rE   r?   Úrespr   r   r	   Úremove_serviceò   s    

zServiceApiMixin.remove_servicec                 C   s6   d|rt  |¡ndi}|  d¡}|  | j||dd¡S )a§  
        List services.

        Args:
            filters (dict): Filters to process on the nodes list. Valid
                filters: ``id``, ``name`` , ``label`` and ``mode``.
                Default: ``None``.

        Returns:
            A list of dictionaries containing data about each service.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        ÚfiltersNz	/servicesrG   T©r   Zconvert_filtersr0   r7   rI   ©r9   rQ   rH   r?   r   r   r	   Úservices  s    ÿ
zServiceApiMixin.servicesr   Fé    Úallc
                 C   sd   |||||||dœ}
|   d|¡}| j||
dd}|	du rV|  |¡d d d  d	d
¡}	|  d||	¡S )ar  
            Get log stream for a service.
            Note: This endpoint works only for services with the ``json-file``
            or ``journald`` logging drivers.

            Args:
                service (str): ID or name of the service
                details (bool): Show extra details provided to logs.
                    Default: ``False``
                follow (bool): Keep connection open to read logs as they are
                    sent by the Engine. Default: ``False``
                stdout (bool): Return logs from ``stdout``. Default: ``False``
                stderr (bool): Return logs from ``stderr``. Default: ``False``
                since (int): UNIX timestamp for the logs staring point.
                    Default: 0
                timestamps (bool): Add timestamps to every log line.
                tail (string or int): Number of log lines to be returned,
                    counting from the current end of the logs. Specify an
                    integer or ``'all'`` to output all log lines.
                    Default: ``all``
                is_tty (bool): Whether the service's :py:class:`ContainerSpec`
                    enables the TTY option. If omitted, the method will query
                    the Engine for the information, causing an additional
                    roundtrip.

            Returns (generator): Logs for the service.
        )ÚdetailsÚfollowÚstdoutÚstderrÚsinceÚ
timestampsÚtailz/services/{0}/logsT)rH   ÚstreamNÚSpecr(   r   r   F)r0   rI   rK   r   Z_get_result_tty)r9   rE   rW   rX   rY   rZ   r[   r\   r]   Zis_ttyrH   r?   Úresr   r   r	   Úservice_logs  s.    !ù
ÿþþþþzServiceApiMixin.service_logsc                 C   s6   d|rt  |¡ndi}|  d¡}|  | j||dd¡S )a»  
        Retrieve a list of tasks.

        Args:
            filters (dict): A map of filters to process on the tasks list.
                Valid filters: ``id``, ``name``, ``service``, ``node``,
                ``label`` and ``desired-state``.

        Returns:
            (:py:class:`list`): List of task dictionaries.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        rQ   Nz/tasksrG   TrR   rS   r   r   r	   ÚtasksQ  s    ÿ
zServiceApiMixin.tasksc                 C   s\  t | j|||
|ƒ |r@d}t | jd¡r,d}| j||dd }ni }|  d|¡}i }i }|du rj| d¡n||d< |du r„| d¡n||d< |dur°t|tƒs¦t	|ƒ}||d	< n| d	¡|d	< t
| d
i ¡|ƒ|d
< |d
  di ¡}| dd¡}|dur"t |¡\}}t | |¡}|r"||d< |dur6||d< n| d¡|d< |durX||d< n| d¡|d< |dur¢t |¡}t | jd¡r”||d< n||d
 d< ntt | jd¡rÂ| d¡|d< nT|d
  d¡du r| d
i ¡}| d¡}|du r | d¡}|dur||d
 d< |
dur*|
|d< n| d¡|d< | j||d|i|d}| j|ddS )a€  
        Update a service.

        Args:
            service (string): A service identifier (either its name or service
                ID).
            version (int): The version number of the service object being
                updated. This is required to avoid conflicting writes.
            task_template (TaskTemplate): Specification of the updated task to
                start as part of the service.
            name (string): New name for the service. Optional.
            labels (dict): A map of labels to associate with the service.
                Optional.
            mode (ServiceMode): Scheduling mode for the service (replicated
                or global). Defaults to replicated.
            update_config (UpdateConfig): Specification for the update strategy
                of the service. Default: ``None``.
            rollback_config (RollbackConfig): Specification for the rollback
                strategy of the service. Default: ``None``
            networks (:py:class:`list`): List of network names or IDs or
                :py:class:`~docker.types.NetworkAttachmentConfig` to attach the
                service to. Default: ``None``.
            endpoint_spec (EndpointSpec): Properties that can be configured to
                access and load balance a service. Default: ``None``.
            fetch_current_spec (boolean): Use the undefined settings from the
                current specification of the service. Default: ``False``

        Returns:
            A dictionary containing a ``Warnings`` key.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        Tr   N)rJ   r_   z/services/{0}/updater&   r'   r)   r(   r   r#   r$   r+   r,   r   r%   r*   r   )r-   rH   r.   )Zjson)r   r/   r   r   rK   r0   r   r1   r2   r   r!   r   r3   r4   r6   r8   r7   )r9   rE   r   r   r:   r;   r<   r   r=   r>   r   Zfetch_current_specr   Zinspect_defaultsr   r?   r-   r.   r   r@   rA   rB   rC   Zconverted_networksZcurrent_task_templateZcurrent_networksrO   r   r   r	   Úupdate_servicei  sz    *
þÿþ

ÿ













ÿzServiceApiMixin.update_service)NNNNNNNN)N)N)FFFFrU   FrV   N)N)
NNNNNNNNFN)Ú__name__Ú
__module__Ú__qualname__r   Zminimum_versionrD   Zcheck_resourcerK   rM   rP   rT   ra   rb   rc   r   r   r   r	   r"   t   s@      ýK   þ0     ür"   N)
Ú r   r   r   Útypesr   r   r!   Úobjectr"   r   r   r   r	   Ú<module>   s   `