
    uYf|;                        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 d dlmZ d dlZd dl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 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 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 d dlmZ d dlmZ d dlm Z   e jB                  e"      Z# G d de$      Z%ejL                   G d dejN                               Z(y)    N)List)Optional)Type)Union)agentatexit)forksafe)service)uwsgi)writer)ddup)ModuleWatchdog)	collector)exporter)recorder)	scheduler)asyncio)memalloc)stack)stack_event)	threading)configc                   2    e Zd ZdZd ZddZd	dZd Zd Zy)
ProfilerzRun profiling while code is executed.

    Note that the whole Python process is profiled, not only the code executed. Data from all running threads are
    caught.

    c                 $    t        |i || _        y N)_ProfilerInstance	_profiler)selfargskwargss      Z/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/ddtrace/profiling/profiler.py__init__zProfiler.__init__,   s    *D;F;    c                 T   |r0	 t        j                  | j                  |r| j                  nd       | j
                  j                          |rt        j                  | j                         |r t        j                  | j                         yy# t         j                  $ r Y yw xY w)zStart the profiler.

        :param stop_on_exit: Whether to stop the profiler and flush the profile on exit.
        :param profile_children: Whether to start a profiler in child processes.
        Nr   )
r   check_uwsgi_restart_on_forkstopuWSGIMasterProcessr   startr	   registerr
   )r    stop_on_exitprofile_childrens      r#   r+   zProfiler.start/   s     !!$"7"7\		_cd
 	OODII&d334  ++ s   /B B'&B'c                     t        j                  | j                         	 | j                  j                  |       y# t        j
                  $ r Y yw xY w)zFStop the profiler.

        :param flush: Flush last profile.
        N)r	   
unregisterr)   r   r   ServiceStatusError)r    flushs     r#   r)   zProfiler.stopE   sE    
 	$))$	NN&)) 		s   = AAc                     	 | j                   j                  dd       | j                   j	                         | _         | j                   j                          y # t        j                  $ r Y Ow xY w)NF)r2   join)r   r)   r   r1   copyr+   r    s    r#   r(   zProfiler._restart_on_forkQ   s^    	NNe%8 ,,.	 )) 		s   A A/.A/c                 .    t        | j                  |      S r   )getattrr   )r    keys     r#   __getattr__zProfiler.__getattr__\   s    
 t~~s++r%   NTT)T)	__name__
__module____qualname____doc__r$   r+   r)   r(   r:    r%   r#   r   r   $   s     <5,
	,r%   r   c                      e Zd ZdZ ej
                  d      Z ej
                  d       Z ej
                  ee	j                  eef         Z ej
                  d       Z ej
                  d       Z ej
                  ej                         Z ej
                  d	 ee         Z ej
                  eej*                  
      Z ej
                  eej,                  j.                  
      Z ej
                  eej2                  j.                  
      Z ej
                  eej6                  j.                  
      Z ej
                  eej:                  
      Z ej
                  eej>                  
      Z  ej
                  dd      Z! ej
                  dd      Z" ej
                  ddd      Z# ej
                  dde$e%jL                  e%jN                  f         Z( ej
                  dd ee         Z) ej
                  eejT                  jV                  
      Z,dZ-d Z.d Z/d Z0dhZ1d Z2d Z3ddZ4d Z5y)r   zQA instance of the profiler.

    Each process must manage its own instance.

    N)defaultc                  @    t         j                  j                  d      S )N
DD_SERVICEosenvirongetr@   r%   r#   <lambda>z_ProfilerInstance.<lambda>n       bjjnn\&B r%   )factory)rK   typec                  @    t         j                  j                  d      S )NDD_ENVrE   r@   r%   r#   rI   z_ProfilerInstance.<lambda>p   s    "**..": r%   c                  @    t         j                  j                  d      S )N
DD_VERSIONrE   r@   r%   r#   rI   z_ProfilerInstance.<lambda>q   rJ   r%   c                  @    t         j                  j                  d      S )N
DD_API_KEYrE   r@   r%   r#   rI   z_ProfilerInstance.<lambda>s   rJ   r%   )rL   rB   F)initrB   )rS   rB   eq)rS   rB   rL   c                  @    t         j                  j                  d      S )NAWS_LAMBDA_FUNCTION_NAMErE   r@   r%   r#   rI   z_ProfilerInstance.<lambda>   s    BJJNN3M$N r%   )rS   rK   rL   zhttps://intake.profile.{}c                    t         j                  }|rddlm} |j	                  |      gS | j
                  | j
                  }n| j                  rOt        j                  d       | j                  j                  t        j                  j                  dd            }nct        | j                  j                   t"        j$                        r!| j                  j                   j&                  }nt)        j*                         }| j                  rd}nd}| j,                  '| j.                  j1                  d	| j,                  i       | j2                  r-t4        j6                  st        j9                  d
       d| _        n!| j2                  rt        j;                  d       g }| j<                  rGt         j>                  j@                  jB                  r|jE                  d       n|jE                  d       | jF                  r|jE                  d       | jH                  r|jE                  d       t         jJ                  jL                  dkD  r|jE                  d       | j2                  r|jE                  d       n|jE                  d       |jE                  dtO        t         jP                        z          |jE                  dtO        t         jR                        z          | j.                  j1                  ddjU                  |      i       | j                  jV                  }| jX                  r|j[                          | j2                  rSt5        j\                  | j^                  | j`                  | jb                  | j.                  t         jR                  |       g S ddlm2} |jg                  | j`                  | j^                  | j.                  | jb                  | jh                  ||| jj                  |	      gS )Nr   )file)prefixzAgentless uploading is currently for internal usage only and not officially supported. You should not enable it unless somebody at Datadog instructed you to do so.DD_SITEzdatadoghq.comz/api/v2/profilezprofiling/v1/inputfunctionnamezHFailed to load the libdd collector, falling back to the legacy collectorFzUsing the libdd collectorstack_v2r   lockmemheapexp_ddexp_pyCAPMAXFprofiler_config_)envr   versiontagsmax_nframesurl)http)	r   rf   rh   rg   api_keyendpointendpoint_pathenable_code_provenance$endpoint_call_counter_span_processor)6r   output_pprofddtrace.profiling.exporterrX   PprofFileExporterrj   	agentlessLOGwarningENDPOINT_TEMPLATEformatrF   rG   rH   
isinstancetracer_writerr   AgentWriter	agent_urlr   get_trace_url_lambda_function_namerh   update_export_libdd_enabledr   is_availableerrordebug_stack_collector_enabledr   v2enabledappend_lock_collector_enabled_memory_collector_enabledr_   sample_sizestrcapture_pct
max_framesr4   %_endpoint_call_counter_span_processorendpoint_collection_enabledenablerS   rf   r   rg   rk   PprofHTTPExporterrl   ro   )r    _OUTPUT_PPROFrX   rm   rn   configured_featuresrp   rk   s           r#   _build_default_exportersz*_ProfilerInstance._build_default_exporters   s   ++ 8 &&m&<  88xxH^^KK_ --44RZZ^^I5_`H$++--v/A/AB;;..88 ..0>>-M
 1M%%1IInd.H.HIJ %%d.?.?II`a).D&''II12 !((||&&#**:6#**73''&&v.))&&u-;;""Q&&&v.%%&&x0&&x0""53v/A/A+B#BC""6C0A0A,B#BC		+SXX6I-JKL/3{{/`/`,++0779%%IIHHYY"--4 	 8 && LL LL LL%"/+/+F+F9] ' 
 r%   c                     d}t        j                  t        j                  |t        j                  t        |dz        t        j                  t        t        j                  j                  t        j                  j                  z  dz        t        j                  d it        j                        x _        g  _         j                   rpt"        j%                  d       	  j                  j'                  t)        j*                   j,                   j.                               t"        j%                  d        j4                  rLdt6        dd f fddfdfdfdfg _         j8                  D ]  \  }}t;        j<                  ||         j>                  r. j                  j'                  t        j                                jA                         }|s jB                  rG jD                  rtF        jH                  ntF        jJ                  } || jL                         _'        y y # t0        $ r t"        j3                  dd	
       Y w xY w)Ni0u     <   )
max_eventsdefault_max_eventsz#Profiling collector (stack) enabled)rz   r   z'Profiling collector (stack) initializedz+Failed to start stack collector, disabling.Texc_infocollector_classreturnc                    j                   5   | j                        }j                  t        j                  j
                  k(  r'	 |j                          t        j                  d|       j                  j                  |       d d d        y # t        j                  $ r! t        j                  d|       Y d d d        y t        $ r# t        j                  d|d       Y d d d        y w xY w# 1 sw Y   y xY w)N)rz   zStarted collector %r&Collector %r is unavailable, disabling(Failed to start collector %r, disabling.Tr   )_service_lockrz   statusr   ServiceStatusRUNNINGr+   ru   r   r   CollectorUnavailable	Exceptionr   _collectorsr   )r   colrr    s     r#   start_collectorz>_ProfilerInstance.__attrs_post_init__.<locals>.start_collector  s    '' 1)!DKK@C{{g&;&;&C&CC#IIKII&<cB $$++C01 1  )== #II&NPST"1 1  ) #II&PRU`dIe"1 1#1 1s;   <C6&B1C6)C3>C6 C3(C62C33C66C?r   c                 0     t         j                        S r   )r   ThreadingLockCollectorre   r   s    r#   rI   z7_ProfilerInstance.__attrs_post_init__.<locals>.<lambda>"  s    	8X8X(Y r%   r   c                 0     t         j                        S r   )r   AsyncioLockCollectorr   s    r#   rI   z7_ProfilerInstance.__attrs_post_init__.<locals>.<lambda>#  s    og6R6R&S r%   )r   	exportersbefore_flush)(r   Recorderr   StackSampleEventStackExceptionSampleEventintr   MemoryAllocSampleEventMemoryCollector_DEFAULT_MAX_EVENTS_DEFAULT_INTERVALMemoryHeapSampleEventr   r   	_recorderr   r   ru   r   r   r   StackCollectorrz   r   r   r   r   r   _collectors_on_importr   register_module_hookr   r   r   r   r   ServerlessScheduler	Scheduler_collectors_snapshot
_scheduler)r    max_stack_eventsmodulehookr   scheduler_classr   r   s   `     @@r#   __attrs_post_init__z%_ProfilerInstance.__attrs_post_init__   s    (%..,,.>55s;Ka;O7P//--AAHD\D\DnDnnrtt2 ..	  &00
 	
DN ((II;<
X  ''((#{{484T4T 		CD ''1 1$ 1& YZST*D&
 !% : : B33FDAB ))##H$<$<Q$?@113	22151K1K	--QZQdQd  .#!66DO 3K  X		GRV	WXs   &AH8 8 IIc                     | j                   D ]7  }	 |j                         }|r"|D ]  }| j                  j                  |        9 y # t        $ r t
        j                  d|d       Y ^w xY w)Nz$Error while snapshoting collector %rTr   )r   snapshotr   push_eventsr   ru   r   )r    cr   eventss       r#   r   z&_ProfilerInstance._collectors_snapshot9  su    !! 	TAT::<"* ;226:;		T  T		@!d	STs   4A!A,+A,r   c                     | j                   di t        j                  | j                         D ci c]M  }|j                  d   dk7  r9|j                  | j                  vr!|j                  t        | |j                        O c}S c c}w )Nr   re   r@   )	__class__attrfieldsname_COPY_IGNORE_ATTRIBUTESr8   )r    as     r#   r5   z_ProfilerInstance.copyE  sy    t~~ 
 T^^466!9#d6R6R(R aff--
 	
s   ABc                 l   g }| j                   D ]$  }	 |j                          |j                  |       & || _         | j                  | j                  j                          yy# t        j                  $ r t
        j                  d|       Y t        $ r t
        j                  d|d       Y w xY w)zStart the profiler.r   r   Tr   N)
r   r+   r   r   r   ru   r   r   r   r   )r    
collectorsr   s      r#   _start_servicez _ProfilerInstance._start_serviceN  s     
## 	'C'		 !!#&	' &??&OO!!# ' 11 I		BCH Z		DcTX	YZs   A%%)B3 B32B3c                 .   | j                   r+| j                  D ]  \  }}	 t        j                  ||        | j
                  R| j
                  j                          |r| j
                  j                          |r| j
                  j                          t        | j                        D ]  }	 |j                           |r+t        | j                        D ]  }|j                           yy# t        $ r Y w xY w# t        j                  $ r Y hw xY w)zHStop the profiler.

        :param flush: Flush a last profile.
        N)r   r   r   unregister_module_hook
ValueErrorr   r)   r4   r2   reversedr   r   r1   )r    r2   r4   r   r   r   s         r#   _stop_servicez_ProfilerInstance._stop_service`  s    '' $ : : "99&$G ??&OO  " $$&%%'D,,- 	C
	  0 01 
 ) "   -- s#   C//C>/	C;:C;>DDc                     | j                    S r   )r   r6   s    r#   visible_eventsz _ProfilerInstance.visible_events  s    ----r%   r;   )6r<   r=   r>   r?   r   ibrj   r   dicttypingDictr   rh   rf   rg   ddtracerz   r   rl   boolr   rt   memoryr   r   r   r   r]   r   code_provenancero   endpoint_collectionr   r   r   r   r   r   r   r   r   r   exportlibdd_enabledr   rw   r   r   r   r   r5   r   r   r   r@   r%   r#   r   r   d   s    $''$
CdggBCG4774fkk#s(&;<D
$'':
;CdggBCGTWWW^^,FdggBRUWGT6+;+;<I 'T6==;P;P Q&twwD&,,:N:NO%dgg49L9LM$TWW$8N8NO")$''tV=W=W"XUD1I$''ud3K#DGGGeTi>Q>QS\SpSp>p8qrJ#DGGNU]^aUb $DGGv}}7R7RS3bHM^T  (j
$$!F.r%   r   ))loggingrF   r   r   r   r   r   r   r   ddtrace.internalr   r	   r
   r   r   r   "ddtrace.internal.datadog.profilingr   ddtrace.internal.moduler   ddtrace.profilingr   r   r   r   ddtrace.profiling.collectorr   r   r   r   r   ddtrace.settings.profilingr   	getLoggerr<   ru   objectr   sServicer   r@   r%   r#   <module>r      s     	        " # % $ " # 3 2 ' & & ' / 0 - 3 1 - g!=,v =,@ _. _. _.r%   