U
    ]3                     @   s   d dl Z d dlmZmZ d dlmZmZmZmZ ddl	m
Z
mZ G dd de
ZG dd	 d	eZd
dddddddddddddddddddddd gZd!d"d#gZd$dd%d&d'gZd(d)d*gZd+d, ZdS )-    N)create_unexpected_kwargs_errorInvalidArgument)TaskTemplateContainerSpec	PlacementServiceMode   )Model
Collectionc                   @   s^   e Zd ZdZdZedd Zedd Zdd Zdd
dZ	dd Z
dd Zdd Zdd Zd	S )Servicez
A service.ZIDc                 C   s   | j d d S )zThe service's name.SpecName)attrsself r   8/usr/lib/python3/dist-packages/docker/models/services.pyname   s    zService.namec                 C   s   | j ddS )z
        The version number of the service. If this is not the same as the
        server, the :py:meth:`update` function will not work and you will
        need to call :py:meth:`reload` before calling it again.
        ZVersionZIndex)r   getr   r   r   r   version   s    zService.versionc                 C   s   | j j| jS )z
        Stop and remove the service.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        )clientapiZremove_serviceidr   r   r   r   remove   s    zService.removeNc                 C   s&   |dkri }| j |d< | jjj|dS )a  
        List the tasks in this service.

        Args:
            filters (dict): A map of filters to process on the tasks list.
                Valid filters: ``id``, ``name``, ``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.
        Nservice)filters)r   r   r   tasks)r   r   r   r   r   r   #   s    
zService.tasksc                 K   s   d|kr&| j d d d }|d |d< |ddkr^| j d d }t|dd	}|d
 |d< td|}| jjj| j| jf|S )a)  
        Update a service's configuration. Similar to the ``docker service
        update`` command.

        Takes the same parameters as :py:meth:`~ServiceCollection.create`.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        imager   r   r   ZImageforce_updateTZForceUpdater   r   update)	r   r   int_get_create_service_kwargsr   r   update_servicer   r   )r   kwargsspectask_templateZcurrent_valuecreate_kwargsr   r   r   r   8   s    
zService.updatec                 K   s6   | j d d d dd}| jjj| jfd|i|S )a  
        Get log stream for the service.
        Note: This method works only for services with the ``json-file``
        or ``journald`` logging drivers.

        Args:
            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``

        Returns:
            generator: Logs for the service.
        r   r   r   ZTTYFis_tty)r   r   r   r   Zservice_logsr   )r   r#   r'   r   r   r   logsU   s
     zService.logsc                 C   sB   d| j d d  krtdtd|}| jjj| j| j|ddS )z
        Scale service container.

        Args:
            replicas (int): The number of containers that should be running.

        Returns:
            bool: ``True`` if successful.
        ZGlobalr   ZModezCannot scale a global containerZ
replicatedT)modefetch_current_spec)	r   keysr   r   r   r   r"   r   r   )r   ZreplicasZservice_moder   r   r   scaler   s    
zService.scalec                 C   s   | j dddS )z
        Force update the service even if no changes require it.

        Returns:
            bool: ``True`` if successful.
        T)r   r*   )r   r   r   r   r   r      s    zService.force_update)N)__name__
__module____qualname____doc__Zid_attributepropertyr   r   r   r   r   r(   r,   r   r   r   r   r   r      s   



r   c                   @   s0   e Zd ZdZeZd	ddZd
ddZdd ZdS )ServiceCollectionzServices on the Docker server.Nc                 K   s4   ||d< ||d< t d|}| jjjf |}| |S )a  
        Create a service. Similar to the ``docker service create`` command.

        Args:
            image (str): The image name to use for the containers.
            command (list of str or str): Command to run.
            args (list of str): Arguments to the command.
            constraints (list of str): :py:class:`~docker.types.Placement`
                constraints.
            preferences (list of tuple): :py:class:`~docker.types.Placement`
                preferences.
            platforms (list of tuple): A list of platform constraints
                expressed as ``(arch, os)`` tuples.
            container_labels (dict): Labels to apply to the container.
            endpoint_spec (EndpointSpec): Properties that can be configured to
                access and load balance a service. Default: ``None``.
            env (list of str): Environment variables, in the form
                ``KEY=val``.
            hostname (string): Hostname to set on the container.
            init (boolean): Run an init inside the container that forwards
                signals and reaps processes
            isolation (string): Isolation technology used by the service's
                containers. Only used for Windows containers.
            labels (dict): Labels to apply to the service.
            log_driver (str): Log driver to use for containers.
            log_driver_options (dict): Log driver options.
            mode (ServiceMode): Scheduling mode for the service.
                Default:``None``
            mounts (list of str): Mounts for the containers, in the form
                ``source:target:options``, where options is either
                ``ro`` or ``rw``.
            name (str): Name to give to the service.
            networks (:py:class:`list`): List of network names or IDs or
                :py:class:`~docker.types.NetworkAttachmentConfig` to attach the
                service to. Default: ``None``.
            resources (Resources): Resource limits and reservations.
            restart_policy (RestartPolicy): Restart policy for containers.
            secrets (list of :py:class:`~docker.types.SecretReference`): List
                of secrets accessible to containers for this service.
            stop_grace_period (int): Amount of time to wait for
                containers to terminate before forcefully killing them.
            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``
            user (str): User to run commands as.
            workdir (str): Working directory for commands to run.
            tty (boolean): Whether a pseudo-TTY should be allocated.
            groups (:py:class:`list`): A list of additional groups that the
                container process will run as.
            open_stdin (boolean): Open ``stdin``
            read_only (boolean): Mount the container's root filesystem as read
                only.
            stop_signal (string): Set signal to stop the service's containers
            healthcheck (Healthcheck): Healthcheck
                configuration for this service.
            hosts (:py:class:`dict`): A set of host to IP mappings to add to
                the container's `hosts` file.
            dns_config (DNSConfig): Specification for DNS
                related configurations in resolver configuration file.
            configs (:py:class:`list`): List of
                :py:class:`~docker.types.ConfigReference` that will be exposed
                to the service.
            privileges (Privileges): Security options for the service's
                containers.

        Returns:
            :py:class:`Service`: The created service.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        r   commandcreate)r!   r   r   Zcreate_servicer   )r   r   r3   r#   r&   
service_idr   r   r   r4      s
    J
zServiceCollection.createc                 C   s   |  | jj||S )a}  
        Get a service.

        Args:
            service_id (str): The ID of the service.
            insert_defaults (boolean): If true, default values will be merged
                into the output.

        Returns:
            :py:class:`Service`: The service.

        Raises:
            :py:class:`docker.errors.NotFound`
                If the service does not exist.
            :py:class:`docker.errors.APIError`
                If the server returns an error.
            :py:class:`docker.errors.InvalidVersion`
                If one of the arguments is not supported with the current
                API version.
        )prepare_modelr   r   Zinspect_service)r   r5   Zinsert_defaultsr   r   r   r      s    zServiceCollection.getc                    s    fdd j jjf |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:
            list of :py:class:`Service`: The services.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        c                    s   g | ]}  |qS r   )r6   ).0sr   r   r   
<listcomp>  s   z*ServiceCollection.list.<locals>.<listcomp>)r   r   services)r   r#   r   r   r   list   s    
zServiceCollection.list)N)N)	r-   r.   r/   r0   r   Zmodelr4   r   r;   r   r   r   r   r2      s
   
P
r2   argsr3   ZconfigsZ
dns_configenvgroupsZhealthcheckZhostnameZhostsr   ZinitZ	isolationlabelsZmountsZ
open_stdinZ
privilegesZ	read_onlyZsecretsZstop_grace_periodZstop_signalZttyuserZworkdirZnetworksZ	resourcesZrestart_policyr   r)   Zupdate_configZendpoint_specZconstraintsZpreferencesZ	platformsc           	      C   s^  i }t  |D ]}|tkr||||< qi }t  |D ]}|tkr8||||< q8i }t  |D ]}|tkrb||||< qbd|kr|d|d< i }t  |D ]}|tkr||||< qtf |}||d< d|kr|d|di d|d< | dkr*d|kr|d|d< |d	d
}||d	< |r:t| |tf |}||d< t	f ||d< |S )NZcontainer_labelsr?   	placementZ
log_driverZlog_driver_options)r   ZOptionsr   r   r*   Tcontainer_specr%   )
copyCREATE_SERVICE_KWARGSpopCONTAINER_SPEC_KWARGSTASK_TEMPLATE_KWARGSPLACEMENT_KWARGSr   r   r   r   )	Z	func_namer#   r&   keyZcontainer_spec_kwargsZtask_template_kwargsrA   r*   rB   r   r   r   r!   E  sF    






r!   )rC   Zdocker.errorsr   r   Zdocker.typesr   r   r   r   resourcer	   r
   r   r2   rF   rG   rD   rH   r!   r   r   r   r   <module>   s\    
 	