U
    /e*                     @  s   U d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
mZmZmZmZmZ ddlZddlmZ dd	lmZ dd
lmZ dZded< dZded< dd ZefddddddddZddddddZG d d! d!eZdS )"z4Utilities for generating and analyzing cluster dumps    )annotations)defaultdict)Mapping)Path)IOAny	AwaitableCallable
CollectionLiteralN)scheduler_story)worker_story)	to_threadmsgpackzLiteral['msgpack' | 'yaml']DEFAULT_CLUSTER_DUMP_FORMAT)Zrun_specCollection[str]DEFAULT_CLUSTER_DUMP_EXCLUDEc                 C  s@   t | ttfrdd | D S t | tr8dd |  D S | S d S )Nc                 S  s   g | ]}t |qS  _tuple_to_list).0elr   r   </tmp/pip-unpacked-wheel-g426oqom/distributed/cluster_dump.py
<listcomp>   s     z"_tuple_to_list.<locals>.<listcomp>c                 S  s   i | ]\}}|t |qS r   r   )r   kvr   r   r   
<dictcomp>   s      z"_tuple_to_list.<locals>.<dictcomp>)
isinstancelisttupledictitems)noder   r   r   r      s
    
r   zCallable[[], Awaitable[Any]]strzLiteral[('msgpack', 'yaml')]zdict[str, Any]None)	get_stateurlformatstorage_optionsreturnc           
   	     s   |dkr*d}d}| |s"||7 }tj}nR|dkrlddl d}d}| |sT||7 }d	d
dd fdd}ntd|dddl}|j||fddi|$}|  I dH }	t||	|I dH  W 5 Q R X dS )z;Await a cluster dump, then serialize and write it to a pathr   wb.msgpack.gzyamlr   Nw.yamlr    r   r$   )statefr)   c                   s     t| | d S N)dumpr   )r/   r0   r,   r   r   writer2   s    zwrite_state.<locals>.writerzUnsupported format z*. Possible values are 'msgpack' or 'yaml'.compressioninfer)endswithr   packr,   
ValueErrorfsspecopenr   )
r%   r&   r'   r(   modesuffixr4   r:   r0   r/   r   r3   r   write_state   s(    


r>   r   r    r&   kwargsr)   c              
   K  s   |  drd}tj}n.|  dr4ddl}d}|j}ntd|  d|d	d
 ddl}|j| |f|}||W  5 Q R  S Q R X dS )a  Loads a cluster dump from a disk artefact

    Parameters
    ----------
    url : str
        Name of the disk artefact. This should have either a
        ``.msgpack.gz`` or ``yaml`` suffix, depending on the dump format.
    **kwargs :
        Extra arguments passed to :func:`fsspec.open`.

    Returns
    -------
    state : dict
        The cluster state at the time of the dump.
    r+   rbr.   r   Nrzurl (z)) must have a .msgpack.gz or .yaml suffixr5   r6   )	r7   r   unpackr,   Z	safe_loadr9   
setdefaultr:   r;   )r&   r@   r<   readerr,   r:   r0   r   r   r   load_cluster_dumpI   s    

rF   c                   @  s   e Zd ZdZddddZeddd dd	d
Zdd Zdd Zdd Z	ddddddZ
d2dddddZd3dddddZddddd Zdddd!d"Zdd#d$d%Zdd&dd'd(d)Zd4d,d-d-d.d/d0d1ZdS )5DumpArtefacta  
    Utility class for inspecting the state of a cluster dump

    .. code-block:: python

        dump = DumpArtefact.from_url("dump.msgpack.gz")
        memory_tasks = dump.scheduler_tasks("memory")
        executing_tasks = dump.worker_tasks("executing")
    r    r/   c                 C  s
   || _ d S r1   r2   selfr/   r   r   r   __init__x   s    zDumpArtefact.__init__r#   r   r?   c                 K  s   t t|f|S )a  Loads a cluster dump from a disk artefact

        Parameters
        ----------
        url : str
            Name of the disk artefact. This should have either a
            ``.msgpack.gz`` or ``yaml`` suffix, depending on the dump format.
        **kwargs :
            Extra arguments passed to :func:`fsspec.open`.

        Returns
        -------
        state : dict
            The cluster state at the time of the dump.
        )rG   rF   )clsr&   r@   r   r   r   from_url{   s    zDumpArtefact.from_urlc                 C  s
   | j | S r1   rI   )rK   keyr   r   r   __getitem__   s    zDumpArtefact.__getitem__c                 C  s
   t | jS r1   )iterr2   rK   r   r   r   __iter__   s    zDumpArtefact.__iter__c                 C  s
   t | jS r1   )lenr2   rR   r   r   r   __len__   s    zDumpArtefact.__len__z
str | Nonezdict[str, dict]z
list[dict])r/   contextr)   c                   s*    r fdd|  D S t|  S d S )Nc                   s   g | ]}|d   kr|qS rH   r   )r   r   rH   r   r   r      s      z/DumpArtefact._extract_tasks.<locals>.<listcomp>)valuesr   )rK   r/   rV   r   rH   r   _extract_tasks   s    zDumpArtefact._extract_tasksNr   )r/   r)   c                 C  s   |  || jd d S )a-  
        Parameters
        ----------
        state : optional, str
            If provided, only tasks in the given state are returned.
            Otherwise, all tasks are returned.

        Returns
        -------
        tasks : list
            The list of scheduler tasks in ``state``.
        	schedulertasks)rX   r2   rJ   r   r   r   scheduler_tasks_in_state   s    z%DumpArtefact.scheduler_tasks_in_statec                 C  sD   g }| j d  D ],}t|trd|kr|| ||d  q|S )a)  
        Parameters
        ----------
        state : optional, str
            If provided, only tasks in the given state are returned.
            Otherwise, all tasks are returned.

        Returns
        -------
        tasks : list
            The list of worker tasks in ``state``
        workersrZ   )r2   rW   r   r    extendrX   )rK   r/   rZ   worker_dumpr   r   r   worker_tasks_in_state   s
    z"DumpArtefact.worker_tasks_in_state)key_or_stimulus_idr)   c                 G  sL   t t}| jd d }t|}t||D ]}||d  t| q(t|S )z
        Returns
        -------
        stories : dict
            A list of stories for the keys/stimulus ID's in ``*key_or_stimulus_id``.
        rY   transition_logr   )r   r   r2   set_scheduler_storyappendr   r    )rK   r`   storieslogkeysstoryr   r   r   r      s    zDumpArtefact.scheduler_storyc                 G  sh   t |}tt}| jd  D ]@}t|trd|krt||d D ]}||d  t	| qBqt|S )z
        Returns
        -------
        stories : dict
            A dict of stories for the keys/stimulus ID's in ``*key_or_stimulus_id`.`
        r\   rf   r   )
rb   r   r   r2   rW   r   r    _worker_storyrd   r   )rK   r`   rg   re   r^   rh   r   r   r   r      s    zDumpArtefact.worker_story)r)   c                   s*   | j d d }| j d   fdd|D S )z
        Returns
        -------
        missing : list
            A list of workers connected to the scheduler, but which
            did not respond to requests for a state dump.
        rY   r\   c                   s&   g | ]}| kst  | ts|qS r   )r   r    )r   r-   Zresponsive_workersr   r   r      s   z0DumpArtefact.missing_workers.<locals>.<listcomp>rI   )rK   Zscheduler_workersr   rj   r   missing_workers   s
    

zDumpArtefact.missing_workerszset[str])r/   expand_keysr)   c                 C  sL   d|kst i }i }| D ]"\}}||kr6|||< q|||< q||d< |S )zXCompacts ``state`` keys into a general key,
        unless the key is in ``expand_keys``general)AssertionErrorr!   )rK   r/   rl   resultrm   r   r   r   r   r   _compact_state   s    

zDumpArtefact._compact_stateconfigrf   ZlogsrZ   events
extensionsrf   Ztask_groupsrZ   ra   r\   zstr | Path | Noner   r$   )root_dirworker_expand_keysscheduler_expand_keysr)   c                 C  sX  ddl }|rt|nt }|j}t|}t|}| jd }| D ]}z|d }W n tk
rl   Y qDY nX | ||}	|| }
|
j	ddd |	
 D ]@\}}t|
| d }t|d}|j|||d	 W 5 Q R X qqDd
}| | j| |}|| }
|
j	ddd |
 D ]B\}}t|
| d }t|d}|j|||d	 W 5 Q R X qdS )a  
        Splits the Dump Artefact into a tree of yaml files with
        ``root_dir`` as it's base.

        The root level of the tree contains a directory for the scheduler
        and directories for each individual worker.
        Each directory contains yaml files describing the state of the scheduler
        or worker when the artefact was created.

        In general, keys associated with the state are compacted into a ``general.yaml``
        file, unless they are in ``scheduler_expand_keys`` and ``worker_expand_keys``.

        Parameters
        ----------
        root_dir : str or Path
            The root directory into which the tree is written.
            Defaults to the current working directory if ``None``.
        worker_expand_keys : iterable of str
            An iterable of artefact worker keys that will be expanded
            into separate yaml files.
            Keys that are not in this iterable are compacted into a
            `general.yaml` file.
        scheduler_expand_keys : iterable of str
            An iterable of artefact scheduler keys that will be expanded
            into separate yaml files.
            Keys that are not in this iterable are compacted into a
            ``general.yaml`` file.
        r   Nr\   idT)parentsexist_okr.   r-   )ZDumperrY   )r,   r   cwdZCSafeDumperrb   r2   rW   KeyErrorrp   mkdirr!   r#   r;   )rK   rv   rw   rx   r,   Zdumperr\   infoZ	worker_idZworker_stateZlog_dirnameZ_logsfilenamefdrV   Zscheduler_stater   r   r   to_yamls  s4    *

zDumpArtefact.to_yamls)N)N)Nrq   rs   )__name__
__module____qualname____doc__rL   classmethodrN   rP   rS   rU   rX   r[   r_   r   r   rk   rp   r   r   r   r   r   rG   m   s$   
   rG   )r   
__future__r   collectionsr   collections.abcr   pathlibr   typingr   r   r   r	   r
   r   r   Zdistributed._storiesr   rc   r   ri   Zdistributed.compatibilityr   r   __annotations__r   r   r>   rF   rG   r   r   r   r   <module>   s     ,$