
    0Fie                    J   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Zd dlm	Z	m
Z
 d dlmZmZ d dlmZ d dlmZ d dlmZ d dlmZ 	 d dlZn# e$ r  ed	          w xY w ej        e          Zd$dZd%dZej        	 	 	 	 d&d'd"            Zej        	 	 d(d)d#            ZdS )*    )annotationsN)IteratorSequence)AnyLiteral)quote)	partition)
get_client)Workerz.You have to install memray to use this module.dask_workerr   filenamestrkwargsr   returnboolc                   t          | d          r| j                                         t          j        | j                  |t          | j                  z   z  }|                                r|	                                 t          j                    | _        | j                            t          j        |fi |           dS )z$Start the memray Tracker on a Server_memrayT)hasattrr   closepathlibPathlocal_directoryr   idexistsrmdir
contextlib	ExitStackenter_contextmemrayTracker)r   r   r   paths       >lib/python3.11/site-packages/distributed/diagnostics/memray.py_start_memrayr#      s    {I&& $!!###<3443{~CVCV8VWD{{}} 

$.00K%%t&&v&&   4    report_argsSequence[str] | Literal[False]bytesc                   t          | d          sdS t          j        | j                  |t	          | j                  z   z  }| j                                         | `|s<t          |d          5 }|	                                cddd           S # 1 swxY w Y   |
                    d          }|d         dk    sdgt          |          z   }d|vs
J d	            d
|vs
J d            t          |          dt	          |          d
t	          |          gz   }t          j        |           t          |d          5 }|	                                cddd           S # 1 swxY w Y   dS )z$Generate and fetch the memray reportr   r$   rbN.htmlr   r   z-fz-Cannot provide filename for report generationz-oz4Cannot provide output filename for report generation)r   r   r   r   r   r   r   r   openreadwith_suffixlist
subprocessrun)r   r   r%   r!   fdreport_filenames         r"   _fetch_memray_profiler3   +   s    ;	** s<3443{~CVCV8VWD $ 	7799	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 &&w//Oq>X%%j4#4#44{"""$S"""K= 	 {##tSYYc/>R>R&SSKN;	ot	$	$ wwyy                 s$   1BBBE""E&)E&memray-profiles
flamegraphz
--temporalz--leaksT	directorystr | pathlib.Pathworkersint | None | list[str]fetch_reports_parallel
bool | intmemray_kwargsIterator[None]c           	   +    K   t          j        |           } t                      }|                                }|d         }d |d                                         D             }|rt          |t                    r=t          |          }	t          |t                    r|}	t          |          d|	         }t          |          }t          j
                    j        }
t           |j        t          fd|
i|                                          sJ t!          j        d           dV  |                     d           t                      }|du rt          |          }n	|du rd	}n|}t'          ||          D ]}	 |                    t(          |
||
          }|                                D ]\  }}| t+          t-          ||                   d          z  }|rd}nd}t/          t-          |          |z   d          5 }|                    |           ddd           n# 1 swxY w Y   # t2          $ r t4                              d|           Y w xY wdS )a(  Generate a Memray profile on the workers and download the generated report.

    Example::

        with memray_workers():
            client.submit(my_function).result()

        # Or even while the computation is already running

        fut = client.submit(my_function)

        with memray_workers():
            time.sleep(10)

        fut.result()

    Parameters
    ----------
    directory : str
        The directory to save the reports to.
    workers : int | None | list[str]
        The workers to profile. If int, the first n workers will be used.
        If None, all workers will be used.
        If list[str], the workers with the given addresses will be used.
    report_args : tuple[str]
        Particularly for native_traces=True, the reports have to be
        generated on the same host using the same Python interpreter as the
        profile was generated. Otherwise, native traces will yield unusable
        results. Therefore, we're generating the reports on the workers and
        download them afterwards. You can modify the report generation by
        providing additional arguments and we will generate the reports as::

            memray *report_args -f <filename> -o <filename>.html

        If the raw data should be fetched instead of the report, set this to
        False.

    fetch_reports_parallel : bool | int
        Fetching results is sometimes slow and it's sometimes not desired to
        wait for all workers to finish before receiving the first reports.
        This controls how many workers are fetched concurrently.

            int: Number of workers to fetch concurrently
            True: All workers concurrently
            False: One worker at a time

    **memray_kwargs
        Keyword arguments to be passed to memray.Tracker, e.g.
        {"native_traces": True}
    r9   c                &    i | ]\  }}||d          S )name ).0addrwinfos      r"   
<dictcomp>z"memray_workers.<locals>.<dictcomp>   s/        +eeFm  r$   Nr   皙?Texist_okF   )r   r%   r9    )safer*   .memraywbz2Exception during report downloading from worker %s)r   r   r
   scheduler_infoitems
isinstanceintlenr.   uuiduuid4hexallr0   r#   valuestimesleepmkdirr	   r3   r   r   r+   write	Exceptionlogger	exception)r7   r9   r%   r;   r=   clientrO   worker_addrworker_namesnworkersr   fetch_parallelwprofilesprofiler!   suffixr1   s                     r"   memray_workersri   F   s     v Y''I\\F**,,N +K /=i/H/N/N/P/P  L  /j#.. /{##gs## 	H{##IXI.7mmGz||Hzvz-LL(LmLLSSUUVVVVV 	JsOOO	EEEOOTO"""\\F%%W	5	(	(/~w// V V	Vzz%!'	 "  H )1(8(8 & &$W 5\+-F)G)Gb#Q#Q#QQ '$FF&F#d))f,d33 &rHHW%%%& & & & & & & & & & & & & & &&  	V 	V 	VQSTUUUUU	V#V Vs7   BH6H)H6)H--H60H-1H66%IIc              +    K   t          j        |           } t                      }t          j                    j        } |j        t          fd|i|sJ t          j	        d           dV  | 
                    d           t                      }|                    t          ||          }| dz  }|rd}nd	}t          t          |          |z   d
          5 }|                    |           ddd           dS # 1 swxY w Y   dS )a  Generate a Memray profile on the Scheduler and download the generated report.

    Example::

        with memray_scheduler():
            client.submit(my_function).result()

        # Or even while the computation is already running

        fut = client.submit(my_function)

        with memray_scheduler():
            time.sleep(10)

        fut.result()

    Parameters
    ----------
    directory : str
        The directory to save the reports to.
    report_args : tuple[str]
        Particularly for native_traces=True, the reports have to be
        generated on the same host using the same Python interpreter as the
        profile was generated. Otherwise, native traces will yield unusable
        results. Therefore, we're generating the reports on the Scheduler and
        download them afterwards. You can modify the report generation by
        providing additional arguments and we will generate the reports as::

            memray *report_args -f <filename> -o <filename>.html

        If the raw data should be fetched instead of the report, set this to
        False.
    **memray_kwargs
        Keyword arguments to be passed to memray.Tracker, e.g.
        {"native_traces": True}
    r   rG   NTrH   )r   r%   	schedulerr*   rM   rN   )r   r   r
   rT   rU   rV   run_on_schedulerr#   rY   rZ   r[   r3   r+   r   r\   )	r7   r%   r=   r`   r   rg   r!   rh   r1   s	            r"   memray_schedulerrm      s[     V Y''I\\Fz||H"6"=UU8U}UUUUU 	JsOOO	EEEOOTO"""\\F%% &  G
 {"D 	c$ii& $	'	' 2
                 s   C<<D D )r   r   r   r   r   r   r   r   )r   r   r   r   r%   r&   r   r'   )r4   Nr5   T)r7   r8   r9   r:   r%   r&   r;   r<   r=   r   r   r>   )r4   r5   )r7   r8   r%   r&   r=   r   r   r>   ) 
__future__r   r   loggingr   r/   rY   rT   collections.abcr   r   typingr   r   urllib.parser   toolz.itertoolzr	   distributedr
   distributed.workerr   r   ImportError	getLogger__name__r^   r#   r3   contextmanagerri   rm   rB   r$   r"   <module>rz      s   " " " " " "             . . . . . . . .               % % % % % % " " " " " " % % % % % %HMMMM H H H
+F
G
GGH 
	8	$	$   "   6 $5&*>)-iV iV iV iV iVX $5>A A A A A A As   A A