o
    2.aI                     @   sB   d dl mZmZmZ d dlmZ dd Zdd ZG dd dZd	S )
   )autherrorsutils)ServiceModec                 C   sD  dd }|d urAt | dr d|v r|dd d|v r |dd t | dr2|d	d
kr2|dd t | drAd|v rA|dd |d ur_t | drP|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rd|v rt | dr|dd |drt | dr|d dr|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r5|d,d ur(|d)d |d-d ur5|d.d t | drV|d/d urI|d0d |d1d urV|d2d t | d3rj|d4d urj|d5d3 t | d6r~|d7d ur~|d8d6 |d9rt | dr|d9 d:r|d;d d S d S d S d S d S )<Nc                 S   s   t d| |)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   
























2r   c                 C   sz   |   }|d ur;| D ].\}}|dkr2d|vri |d< |d  D ]\}}|d ur0||d |< q"q|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 r#td|r.t|ts.t|}t	
|\}}t	| |}|rA||d< t| jdrP|pO|dd}||||t||d	}|durd||d
< |	durl|	|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rt| jdrt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   6   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   rP   rG   r>   r   r   r	   services  s   
zServiceApiMixin.servicesr   F    allc
                 C   sd   |||||||d}
|  d|}| j||
dd}|	du r+| |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   rV   rW   rX   rY   rZ   r[   r\   Zis_ttyrG   r>   resr   r   r	   service_logs  s.   !
zServiceApiMixin.service_logsc                 C   rO   )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.
        rP   Nz/tasksrF   TrQ   rR   r   r   r	   tasksQ  s   
zServiceApiMixin.tasksc                 C   sL  t | j|||
| |r d}t| jdrd}| j||dd }ni }| d|}i }i }|du r5|dn||d< |du rB|dn||d< |durXt|tsSt	|}||d	< n|d	|d	< t
|d
i ||d
< |d
 di }|dd}|durt|\}}t| |}|r||d< |dur||d< n|d|d< |dur||d< n|d|d< |durt|}t| jdr||d< n?||d
 d< n8t| jdr|d|d< n)|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)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  sz   *











zServiceApiMixin.update_service)NNNNNNNN)N)FFFFrT   FrU   N)
NNNNNNNNFN)__name__
__module____qualname__r   Zminimum_versionrC   Zcheck_resourcerJ   rL   rN   rS   r`   ra   rb   r   r   r   r	   r!   t   sB    K0r!   N)	 r   r   r   typesr   r   r    r!   r   r   r   r	   <module>   s
    `