U
    Ø–]»I  ã                   @   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 k	r‚t  | d¡r@d|kr.|ddƒ d|kr@|ddƒ t  | d¡rd| d	¡d
krd|ddƒ t  | d¡r‚d|kr‚|ddƒ |d k	r¾t  | d¡r |ddƒ t  | d¡r¾d|kr¾|ddƒ |d k	rút  | d¡rúd|krútdd„ |d D ƒƒrú|ddƒ |d k	rFd|k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 k	rÖ|d#dƒ | d$¡d k	rð|d%dƒ | d&¡d k	r
|d'dƒ | d(¡d k	r$|d)dƒ | d*¡d k	r>|d+dƒ t  | d¡r€| d,¡d k	rf|d)dƒ | d-¡d k	r€|d.dƒ t  | d¡rÂ| d/¡d k	r¨|d0dƒ | d1¡d k	rÂ|d2dƒ t  | d3¡rê| d4¡d k	rê|d5d3ƒ t  | d6¡r| d7¡d k	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   ú4/usr/lib/python3/dist-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>*   s     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 k	rv| ¡ D ]\\}}|dkrdd|kr8i |d< |d  ¡ D ]\}}|d k	rD||d |< qDq|d k	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krFt d¡‚|r\t|tƒs\t|ƒ}t	 
|¡\}}t	 | |¡}|r‚||d< t | jd¡r |pž| dd¡}||||t |¡|d	œ}|dk	rÈ||d
< |	dk	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   sJ    $   þ
ÿú	 ÿzServiceApiMixin.create_serviceÚservicec                 C   sN   |   d|¡}i }|dk	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)r/   r   r   r.   r   r   r6   Ú_get)r8   rD   Úinsert_defaultsr>   rG   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)r/   r6   rH   )r8   rK   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.
        rE   T)r/   Z_deleteZ_raise_for_status)r8   rD   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	/servicesrF   T©r   Zconvert_filtersr/   r6   rH   ©r8   rO   rG   r>   r   r   r	   Úservices  s
     ÿ
zServiceApiMixin.servicesr   Fé    Úallc
                 C   sd   |||||||dœ}
|   d|¡}| j||
dd}|	dk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)rG   ÚstreamNÚSpecr'   r   r   F)r/   rH   rJ   r   Z_get_result_tty)r8   rD   rU   rV   rW   rX   rY   rZ   r[   Zis_ttyrG   r>   Úresr   r   r	   Úservice_logs  s0    !ù
ÿþþþ þ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.
        rO   Nz/tasksrF   TrP   rQ   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krj| d¡n||d< |dkr„| d¡n||d< |dk	r°t|tƒs¦t	|ƒ}||d	< n| d	¡|d	< t
| d
i ¡|ƒ|d
< |d
  di ¡}| dd¡}|dk	r"t |¡\}}t | |¡}|r"||d< |dk	r6||d< n| d¡|d< |dk	rX||d< n| d¡|d< |dk	r¢t |¡}t | jd¡r”||d< n||d
 d< ntt | jd¡rÂ| d¡|d< nT|d
  d¡dkr| d
i ¡}| d¡}|dkr | d¡}|dk	r||d
 d< |
dk	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)rI   r]   z/services/{0}/updater%   r&   r(   r'   r   r"   r#   r*   r+   r   r$   r)   r   )r,   rG   r-   )Zjson)r   r.   r   r   rJ   r/   r   r0   r1   r   r    r   r2   r3   r5   r7   r6   )r8   rD   r   r   r9   r:   r;   r   r<   r=   r   Zfetch_current_specr   Zinspect_defaultsr   r>   r,   r-   r   r?   r@   rA   rB   Zconverted_networksZcurrent_task_templateZcurrent_networksrM   r   r   r	   Úupdate_servicei  sŠ    *   þ ÿþ


 ÿ













   ÿzServiceApiMixin.update_service)NNNNNNNN)N)N)FFFFrS   FrT   N)N)
NNNNNNNNFN)Ú__name__Ú
__module__Ú__qualname__r   Zminimum_versionrC   Zcheck_resourcerJ   rL   rN   rR   r_   r`   ra   r   r   r   r	   r!   t   sX                ýK         þ0             ür!   N)
Ú r   r   r   Útypesr   r   r    Úobjectr!   r   r   r   r	   Ú<module>   s   `