o
    NrfK                     @   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)parammin_version r	   [/var/www/html/software/conda/envs/catlas/lib/python3.10/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FailureAction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overridemergedZts_keyZts_valueZcs_keyZcs_valuer	   r	   r
   _merge_task_templatec   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   urlr0   imageregistry	repo_nameauth_headerr/   r	   r	   r
   create_services   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)r2   r   r   r1   r   r   r9   _get)r;   rG   insert_defaultsrA   rJ   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)r2   r9   rK   )r;   rN   rA   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.
        rH   T)r2   _deleteZ_raise_for_status)r;   rG   rA   respr	   r	   r
   remove_service   s   

zServiceApiMixin.remove_servicec                 C   s^   d|rt |ndi}|durt | jdrtd||d< | 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``.
            status (bool): Include the service task count of running and
                desired tasks. 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1.41z-status is not supported in API version < 1.41statusz	/servicesrI   T)	r   convert_filtersr   r1   r   r   r2   r9   rK   )r;   rS   rT   rJ   rA   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)rJ   streamNSpecr*   r   r   F)r2   rK   rM   r   Z_get_result_tty)r;   rG   rY   rZ   r[   r\   r]   r^   r_   Zis_ttyrJ   rA   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.
        rS   Nz/tasksrI   T)r   rU   r2   r9   rK   )r;   rS   rJ   rA   r	   r	   r
   tasksW  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)rL   ra   z/services/{0}/updater(   r)   r+   r*   r   r%   r&   r-   r.   r   r'   r,   r   )r/   rJ   r0   )json)r   r1   r   r   rM   r2   r   r3   r4   r   r#   r   r5   r6   r8   r:   r9   )r;   rG   r   r   r<   r=   r>   r   r?   r@   r   Zfetch_current_specr   Zinspect_defaultsr    rA   r/   r0   r   rB   rC   rD   rE   Zconverted_networksZcurrent_task_templateZcurrent_networksrQ   r	   r	   r
   update_serviceo  sz   *











zServiceApiMixin.update_service)NNNNNNNN)N)NN)FFFFrW   FrX   N)
NNNNNNNNFN)__name__
__module____qualname__r   minimum_versionrF   Zcheck_resourcerM   rO   rR   rV   rc   rd   rf   r	   r	   r	   r
   r$   r   sB    K0r$   N)	 r   r   r   typesr   r   r#   r$   r	   r	   r	   r
   <module>   s
    ^