
    &`i"1                         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 d dlmZ d dl	m
Z
  ej        e          ZdZdZdZde
eef         fd	Zd
efdZd
efdZ G d d          Z G d d          ZdS )    N)datetime)Path)Unionz#sudo chown root: `which {profiler}`z'sudo chown root:root `which {profiler}`aB  
Note that this command requires `{profiler}` to be installed with root permissions. You
can install `{profiler}` and give it root permissions as follows:
  $ pip install {profiler}
  $ {set_chown_command}
  $ sudo chmod u+s `which {profiler}`

Alternatively, you can start Ray with passwordless sudo / root permissions.

stringc                 Z    t          | t                    r|                     d          S | S )Nzutf-8)
isinstancebytesdecode)r   s    /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/dashboard/modules/reporter/profile_manager.pyr
   r
      s+    &%   &}}W%%%M    returnc           
      f   t          |          }d}d|                                v rbt          j        dk    rt                              |          nt                              |          }t                              ||          }d|  d| dt          |           d	t          |           d
	S )N 
permissiondarwin)profiler)r   set_chown_commandzFailed to execute `z`.
z
=== stderr ===
z

=== stdout ===

)r
   lowersysplatformDARWIN_SET_CHOWN_CMDformatLINUX_SET_CHOWN_CMD"PROFILER_PERMISSIONS_ERROR_MESSAGE)cmdr   stdoutstderr
stderr_strextra_messager   s          r   _format_failed_profiler_commandr!   "   s    JM z'')))) |x'' !''':::$++X+>> 	
 ;AA1B B 
 
3         r   c                     K   	 t          j        dddt          j        t          j                   d {V } |                                  d {V \  }}| j        dk    S # t          $ r Y dS w xY w)Nsudo-ntruer   r   r   F)asynciocreate_subprocess_exec
subprocessPIPEcommunicate
returncodeFileNotFoundError)process_s     r   _can_passwordless_sudor0   >   s      '6??
 
 
 
 
 
 
 
 
 ((********1!Q&&	    uus   3A 
A-,A-c            
       T    e Zd ZdefdZddededeeffdZ	 dded
ededeeffdZ	dS )CpuProfilingManagerprofile_dir_pathc                 r    t          |          | _        | j                            d           d| _        d S )NTexist_okzpy-spyr   r3   mkdirprofiler_nameselfr3   s     r   __init__zCpuProfilingManager.__init__O   s;     $%5 6 6##T#222%r   Fpidnativer   c                   K   t          j        | j                  }|dS |ddt          |          g}t          j        dk    r|r|                    d           t                       d{V rddg|z   }t          j	        |t          j        t          j        d	 d{V }|                                 d{V \  }}|j        d
k    rdt          || j        ||          fS dt          |          fS )a  
        Capture and dump a trace for a specified process.

        Args:
            pid: The process ID (PID) of the target process for trace capture.
            native (bool, optional): If True, includes native (C/C++) stack frames.
                Default is False.

        Returns:
            Tuple[bool, str]: A tuple containing a boolean indicating the success
                of the trace capture operation and a string with the
                trace data or an error message.
        NFz*Failed to execute: py-spy is not installeddump-plinux--nativer#   r$   r&   r   FT)shutilwhichr9   strr   r   appendr0   r'   r(   r)   r*   r+   r,   r!   r
   )r;   r=   r>   pyspyr   r.   r   r   s           r   
trace_dumpzCpuProfilingManager.trace_dumpT   s=      T/00=FFfdCHH-<7""v"JJz"""')))))))) 	'4.3&C6??
 
 
 
 
 
 
 
 

  '2244444444""9T'    ''r   
flamegraph   durationc           
        K   t          j        | j                  }|dS |dvrdd| ddz   fS |dk    rd	}nd
}| j        | d| d| z  }|dd|dt	          |          dt	          |          d|g
}t
          j        dk    r|r|                    d           t                       d{V rddg|z   }t          j
        |t          j        t          j        d d{V }	|	                                 d{V \  }
}|	j        dk    rdt          || j        |
|          fS dt!          |d                                          fS )a  
        Perform CPU profiling on a specified process.

        Args:
            pid: The process ID (PID) of the target process to be profiled.
                format (str, optional): The format of the CPU profile output.
                Default is "flamegraph".
            duration (float, optional): The duration of the profiling
                session in seconds. Default is 5 seconds.
            native (bool, optional): If True, includes native (C/C++) stack frames.
                Default is False.

        Returns:
            Tuple[bool, str]: A tuple containing a boolean indicating the success
                of the profiling operation and a string with the
                profile data or an error message.
        Nr@   )rK   raw
speedscopeFz"Failed to execute: Invalid format z, z%must be [flamegraph, raw, speedscope]rK   svgtxtr/   z_cpu_profiling.record-orB   z-d-frC   rD   r#   r$   r&   r   Trb)rE   rF   r9   r3   rG   r   r   rH   r0   r'   r(   r)   r*   r+   r,   r!   openread)r;   r=   r   rM   r>   rI   	extensionprofile_file_pathr   r.   r   r   s               r   cpu_profilezCpuProfilingManager.cpu_profiley   s     ( T/00=FF<<<?V???9:  \!!III!v$O$O$O$OI$O$OO 	 HHMM
 <7""v"JJz"""')))))))) 	'4.3&C6??
 
 
 
 
 
 
 
 

  '2244444444""9T'    /66;;====r   NF)rK   rL   F)
__name__
__module____qualname__rG   r<   intboolrJ   floatr[    r   r   r2   r2   N   s        & & & & &
#( #(C #( #(4+ #( #( #( #(L RWA> A>A>7<A>JNA>
A> A> A> A> A> A>r   r2   c                       e Zd ZdefdZ	 	 ddedededed	eeff
d
Z	 	 	 ddedededed	eeff
dZ	 ddeded	eeffdZ	dS )MemoryProfilingManagerr3   c                 x    t          |          dz  | _        | j                            d           d| _        d S )NmemrayTr5   r7   r:   s     r   r<   zMemoryProfilingManager.__init__   s@     $%5 6 6 A##T#222%r   rK   Fr=   profiler_filenamer   leaksr   c                   K   t          j        | j                  }|dS | j        |z  }t	          |                                          sdd| dfS t          j                            |          \  }}| j        | dz  }	|dk    r|dd|	d	g}
n|d
k    r|d
d|	d	g}
ndd| dfS |r|
	                    d           |
	                    |           t          j        |
t          j        t          j        d d{V }|                                 d{V \  }}|j        dk    rdt!          |
| j        ||          fS dt#          |	d                                          fS )a  
        Convert the Memray profile result to specified format.

        Args:
            pid: The process ID (PID) associated with the profiling operation.
                profiler_filename: The filename of the profiler output to
                be processed.
            format (str, optional): The format of the profile result.
                Default is "flamegraph".
            leaks (bool, optional): If True, include memory leak information in
                the profile result.

        Returns:
            Tuple[bool, str]: A tuple containing a boolean indicating the success
                of the operation and a string with the processed profile result
                or an error message.
        NF*Failed to execute: memray is not installedFzFailed to execute: process z has not been profiledz.htmlrK   rT   rU   tablez'Failed to execute: Report with format: z is not supportedz--leaksr&   r   TrV   )rE   rF   r9   r3   r   is_fileospathsplitextrH   r'   r(   r)   r*   r+   r,   r!   rW   rX   )r;   r=   rh   r   ri   rg   rZ   r9   r/   profile_visualize_pathvisualize_cmdr.   r   r   s                 r   get_profile_resultz)MemoryProfilingManager.get_profile_result   s     0 d011>FF 14EE%&&..00 	TSSSSSS7++,=>>q!%!6M9P9P9P!P\!!&MM w&MM S&SSS 
  	,  +++.///6??
 
 
 
 
 
 
 
 

  '2244444444""9t166    T0$77<<>>>>r   r>   trace_python_allocatorsverbosec                   K   t          j        | j                  }|dS t          j                                        d          }| d| d}| j        |z  }|dt          |          d|g}	|r|	                    d           |r|	                    d	           |r|	                    d
           t                       d{V rddg|	z   }	t          j        |	t          j        t          j        d d{V }
|
                                 d{V \  }}|
j        dk    rddt!          |	| j        ||          fS d|d| fS )a  
        Attach a Memray profiler to a specified process.

        Args:
            pid: The process ID (PID) of the target process which
                the profiler attached to.
            native (bool, optional): If True, includes native (C/C++) stack frames.
                Default is False.
            trace_python_allocators (bool, optional): If True, includes Python
                stack frames. Default is False.
            verbose (bool, optional): If True, enables verbose output.
                Default is False.

        Returns:
            Tuple[bool, str]: A tuple containing a boolean indicating the success
                of the operation and a string of a success message or an error message.
        N)FNrl   z%Y%m%d%H%M%S_memory_profiling_z.binattachrT   rD   z--trace-python-allocators	--verboser#   r$   r&   r   FTz$Success attaching memray to process )rE   rF   r9   r   nowstrftimer3   rG   rH   r0   r'   r(   r)   r*   r+   r,   r!   )r;   r=   r>   ru   rv   rg   	timestamprh   rZ   r   r.   r   r   s                r   attach_profilerz&MemoryProfilingManager.attach_profiler  s     0 d011>LLLNN++N;;	"EEiEEE 14EExS41BC 	#JJz"""" 	4JJ2333 	$JJ{###')))))))) 	'4.3&C6??
 
 
 
 
 
 
 
 
  '2244444444""/+VV   !<s<< r   c                   K   t          j        | j                  }|dS |dg}|r|                    d           |                    t	          |                     t                       d{V rddg|z   }t          j        |t          j	        t          j	        d d{V }|
                                 d{V \  }}|j        dk    rd	t          || j        ||          fS d
d| fS )a  
        Detach a profiler from a specified process.

        Args:
            pid: The process ID (PID) of the target process the
                profiler detached from.
            verbose (bool, optional): If True, enables verbose output.
                Default is False.

        Returns:
            Tuple[bool, str]: A tuple containing a boolean indicating the success
                of the operation and a string of a success message or an error message.
        Nrk   detachrz   r#   r$   r&   r   FTz&Success detaching memray from process )rE   rF   r9   rH   rG   r0   r'   r(   r)   r*   r+   r,   r!   )r;   r=   rv   rg   r   r.   r   r   s           r   detach_profilerz&MemoryProfilingManager.detach_profilerL  sD     $ d011>FFx  	$JJ{###

3s88')))))))) 	'4.3&C6??
 
 
 
 
 
 
 
 

  '2244444444""9T'    G#GGGGr   N)rK   F)FFFr\   )
r]   r^   r_   rG   r<   r`   ra   rt   r~   r   rc   r   r   re   re      s0       & & & & & #G? G?G? G? 	G?
 G? G? G? G? G?X (-> >> > "&	>
 > > > > >F )H )H)H )H 	)H )H )H )H )H )Hr   re   )r'   loggingro   rE   r)   r   r   pathlibr   typingr   	getLoggerr]   loggerr   r   r   rG   r	   r
   r!   ra   r0   r2   re   rc   r   r   <module>r      sk     				      



                  		8	$	$< ? 	& "5e$    c    8'd ' ' ' ' l> l> l> l> l> l> l> l>^xH xH xH xH xH xH xH xH xH xHr   