U
    /e;                     @  s   d dl mZ d dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
 d dlZd dlZd dlmZmZ eeZG dd de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hZd(ddd d d!d!d"d#d$d%	d&d'ZdS ))    )annotationsN)dumps)Any)ProcessInterfaceSpecClusterc                      s8   e Zd ZdZ fddZ fddZ fddZ  ZS )ProcesszaA superclass for SSH Workers and Nannies

    See Also
    --------
    Worker
    Scheduler
    c                   s   d | _ d | _t jf | d S N)
connectionprocsuper__init__)selfkwargs	__class__ :/tmp/pip-unpacked-wheel-g426oqom/distributed/deploy/ssh.pyr      s    zProcess.__init__c                   s.   | j s
tt| | jj t  I d H  d S r   )r	   AssertionErrorweakreffinalizer
   killr   startr   r   r   r   r   !   s    
 zProcess.startc                   s4   | j r| j   | jr | j  t  I d H  d S r   )r
   r   r	   closer   r   r   r   r   r   (   s
    

zProcess.close)__name__
__module____qualname____doc__r   r   r   __classcell__r   r   r   r   r      s   r   c                      sT   e Zd ZdZdddddd fdd	Zed
d Zejdd Z fddZ  Z	S )Workera*  A Remote Dask Worker controlled by SSH

    Parameters
    ----------
    scheduler: str
        The address of the scheduler
    address: str
        The hostname where we should run this worker
    worker_class: str
        The python class to use to create the worker.
    connect_options: dict
        kwargs to be passed to asyncssh connections
    remote_python: str
        Path to Python on remote node to run this worker.
    kwargs: dict
        These will be passed through the dask worker CLI to the
        dask.distributed.Worker class
    
deprecateddistributed.NannyNstrdict)	scheduleraddressconnect_optionsr   c
           
        s   t    |dkrtd|| _|| _|| _|| _t|| _|	| _	|| _
|dd k	rp|dd k	rptdn<|dd k	rtdt | jdd| _n| jdd| _d S )Nr    sworker_module has been deprecated in favor of worker_class. Please specify a Python class rather than a CLI module.nprocs	n_workersz=Both nprocs and n_workers were specified. Use n_workers only.zZThe nprocs argument will be removed in a future release. It has been renamed to n_workers.   )r   r   
ValueErrorr%   r$   worker_classr&   copyr   nameremote_pythongetwarningswarnFutureWarningpopr)   )
r   r$   r%   r&   r   worker_moduler,   r/   Zloopr.   r   r   r   r   D   s.    
zWorker.__init__c                 C  s   t dt | jS Nz[The nprocs attribute will be removed in a future release. It has been renamed to n_workers.r1   r2   r3   r)   r   r   r   r   r(   m   s
    zWorker.nprocsc                 C  s   t dt || _d S r6   r7   )r   valuer   r   r   r(   v   s
    c                   s  zdd l }W n tk
r(   tdY nX |j jf jI d H  _ jdI d H }|jdkrxdt	j
t	j
j}n< jdI d H }|jdkrdt	j
t	j
j}ntd jstj _d| jd	d
 jddt fddt jD  g} j|I d H  _d}| jk rf jj I d H }| sBtdt|  d|kr|d7 }qtd| t  I d H  d S )Nr   hDask's SSHCluster requires the `asyncssh` package to be installed. Please install it using pip or conda.uname%env DASK_INTERNAL_INHERIT_CONFIG="{}"
cmd /c ver&set DASK_INTERNAL_INHERIT_CONFIG={} &&z;Worker failed to set DASK_INTERNAL_INHERIT_CONFIG variable  -mdistributed.cli.dask_spec--spec'%s'c                   s   i | ]}| j  jd qS )clsopts)r,   r   ).0ir   r   r   
<dictcomp>   s   z Worker.start.<locals>.<dictcomp>Worker failed to startz	worker atr*   %s) asyncsshImportErrorconnectr%   r&   r	   runexit_statusformatdaskconfig	serializeglobal_config	Exceptionr/   sys
executablejoinr$   r   ranger)   create_processr
   stderrreadlinestriploggerinfodebugr   r   )r   rK   resultset_envcmdZstarted_workersliner   r   r   r      sb    





zWorker.start)r    r!   NNN)
r   r   r   r   r   propertyr(   setterr   r   r   r   r   r   r   0   s        )

r   c                      s:   e Zd ZdZdddddd fddZ fd	d
Z  ZS )	Schedulera  A Remote Dask Scheduler controlled by SSH

    Parameters
    ----------
    address: str
        The hostname where we should run this worker
    connect_options: dict
        kwargs to be passed to asyncssh connections
    remote_python: str
        Path to Python on remote node to run this scheduler.
    kwargs: dict
        These will be passed through the dask scheduler CLI to the
        dask.distributed.Scheduler class
    Nr"   r#   z
str | Noner%   r&   r   r/   c                   s,   t    || _|| _|| _|p$tj| _d S r   )r   r   r%   r   r&   rV   rW   r/   )r   r%   r&   r   r/   r   r   r   r      s
    
zScheduler.__init__c                   sn  zdd l }W n tk
r(   tdY nX td |j| jf| jI d H | _| jdI d H }|j	dkrd
tjtjj}n<| jdI d H }|j	dkrd
tjtjj}ntdd	|| jd
dddtd| jd g}| j|I d H | _| jj I d H }| stdt|  d|kr|dd  | _qNqtd| t  I d H  d S )Nr   r9   zCreated Scheduler Connectionr:   r;   r<   r=   z>Scheduler failed to set DASK_INTERNAL_INHERIT_CONFIG variable r>   r?   r@   rA   rB   zdistributed.SchedulerrC   rI   zScheduler atzScheduler at:r*   rJ   )rK   rL   r^   r`   rM   r%   r&   r	   rN   rO   rP   rQ   rR   rS   rT   rU   rX   r/   r   r   rZ   r
   r[   r\   r]   r_   splitr   r   )r   rK   ra   rb   rc   rd   r   r   r   r      sP    





zScheduler.start)N)r   r   r   r   r   r   r   r   r   r   r   rg      s    rg   Zscheduler_addrZscheduler_portworker_addrsZnthreadsr(   r)   Zssh_usernameZssh_portZssh_private_keyZnohostZlogdirr/   Zmemory_limitZworker_portZ
nanny_portZremote_dask_workerr    r!   zlist[str] | Nonezdict | list[dict] | Nonezdict | Noner"   zstr | list[str] | Noner   r   )	hostsr&   worker_optionsscheduler_optionsr5   r,   r/   r   returnc                   s2   pi  pi |pi }|dkr(t dt|t@ r`ddlm} td |d|  |f |S | sxt dt| dt	 t
rt t| krtd	t	t
rtt| krtd
t| d t	 tr҈ n d |t	t
rd ndd}	 fddt| dd D }
t|
|	fddi|S )a  Deploy a Dask cluster using SSH

    The SSHCluster function deploys a Dask Scheduler and Workers for you on a
    set of machine addresses that you provide.  The first address will be used
    for the scheduler while the rest will be used for the workers (feel free to
    repeat the first hostname if you want to have the scheduler and worker
    co-habitate one machine.)

    You may configure the scheduler and workers by passing
    ``scheduler_options`` and ``worker_options`` dictionary keywords.  See the
    ``dask.distributed.Scheduler`` and ``dask.distributed.Worker`` classes for
    details on the available options, but the defaults should work in most
    situations.

    You may configure your use of SSH itself using the ``connect_options``
    keyword, which passes values to the ``asyncssh.connect`` function.  For
    more information on these see the documentation for the ``asyncssh``
    library https://asyncssh.readthedocs.io .

    Parameters
    ----------
    hosts
        List of hostnames or addresses on which to launch our cluster.
        The first will be used for the scheduler and the rest for workers.
    connect_options
        Keywords to pass through to :func:`asyncssh.connect`.
        This could include things such as ``port``, ``username``, ``password``
        or ``known_hosts``. See docs for :func:`asyncssh.connect` and
        :class:`asyncssh.SSHClientConnectionOptions` for full information.
        If a list it must have the same length as ``hosts``.
    worker_options
        Keywords to pass on to workers.
    scheduler_options
        Keywords to pass on to scheduler.
    worker_class
        The python class to use to create the worker(s).
    remote_python
        Path to Python on remote nodes.

    Examples
    --------
    Create a cluster with one worker:

    >>> from dask.distributed import Client, SSHCluster
    >>> cluster = SSHCluster(["localhost", "localhost"])
    >>> client = Client(cluster)

    Create a cluster with three workers, each with two threads
    and host the dashdoard on port 8797:

    >>> from dask.distributed import Client, SSHCluster
    >>> cluster = SSHCluster(
    ...     ["localhost", "localhost", "localhost", "localhost"],
    ...     connect_options={"known_hosts": None},
    ...     worker_options={"nthreads": 2},
    ...     scheduler_options={"port": 0, "dashboard_address": ":8797"}
    ... )
    >>> client = Client(cluster)

    Create a cluster with two workers on each host:

    >>> from dask.distributed import Client, SSHCluster
    >>> cluster = SSHCluster(
    ...     ["localhost", "localhost", "localhost", "localhost"],
    ...     connect_options={"known_hosts": None},
    ...     worker_options={"nthreads": 2, "n_workers": 2},
    ...     scheduler_options={"port": 0, "dashboard_address": ":8797"}
    ... )
    >>> client = Client(cluster)

    An example using a different worker class, in particular the
    ``CUDAWorker`` from the ``dask-cuda`` project:

    >>> from dask.distributed import Client, SSHCluster
    >>> cluster = SSHCluster(
    ...     ["localhost", "hostwithgpus", "anothergpuhost"],
    ...     connect_options={"known_hosts": None},
    ...     scheduler_options={"port": 0, "dashboard_address": ":8797"},
    ...     worker_class="dask_cuda.CUDAWorker")
    >>> client = Client(cluster)

    See Also
    --------
    dask.distributed.Scheduler
    dask.distributed.Worker
    asyncssh.connect
    r    r'   r   )
SSHClusterzNote that the SSHCluster API has been replaced.  We're routing you to the older implementation.  This will be removed in the futurerj   z(`hosts` must be a non empty list, value z found.zYWhen specifying a list of connect_options you must provide a dictionary for each address.zQWhen specifying a list of remote_python you must provide a path for each address.rh   rD   optionsc                   sT   i | ]L\}}|t |t tr  n
 |d   ttrD|d   nddqS )r*   )r%   r&   r   r,   r/   rp   )r   
isinstancer#   list)rF   rG   hostr&   r/   r,   rl   r   r   rH     s   
zSSHCluster.<locals>.<dictcomp>r*   Nr.   ro   )r+   setold_cluster_kwargsZdistributed.deploy.old_sshro   r1   r2   
setdefaultreprrr   rs   lenRuntimeErrorrg   r#   	enumerater   )rk   r&   rl   rm   r5   r,   r/   r   ZOldSSHClusterr$   workersr   ru   r   ro   +  sR    a

ro   )NNNNr    r!   N)
__future__r   r-   loggingrV   r1   r   jsonr   typingr   rQ   Zdask.configZdistributed.deploy.specr   r   	getLoggerr   r^   r   r   rg   rw   ro   r   r   r   r   <module>   sP   
 U       