o
    i$k                     @   s  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Zd dlm	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 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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-m0Z0 d dl1m2Z2 d dl3m4Z4 d d l5m6Z6 d d!l5m7Z7 d d"l8m9Z9 d d#l8m:Z: d d$l;m<Z< d d%l=m>Z> d d&l=m?Z? d d'l@mAZA d d(lBmCZC d d)lBmDZD d d*lEmFZF d d+lEmGZG d d,lEmHZH d d-lImJZK d d.lLmMZM d d/lNmOZO d d0lPmQZQ d d1lRmSZS d d2lTmUZU eAeVZWeDeCd3d4d5ZXeXY  ed6ZZG d7d8 d8e[Z\G d9d: d:eSZ]G d;d< d<eOZ^dS )=    )defaultdict)deque)chainN)Path)FunctionType)
ModuleType)TracebackType)Any)Iterable)Optional)TypeVar)cast)config)	di_config)FunctionDiscovery) FullyNamedContextWrappedFunction)FunctionStore)DebuggerModuleWatchdog)metrics)FunctionLocationMixin)FunctionProbe)LineLocationMixin)	LineProbe)Probe)ProbeRegistry)DebuggerRCCallback)ProbePollerEventbuild_probe)ProbeStatusLogger)SignalCollector)Signal)SignalState)SignalUploader)UploaderProduct)core)NO_EXCEPTION)ExcInfoType)
get_logger)DogStatsdClient)Metrics)origin)register_post_run_module_hook)unregister_post_run_module_hook)BudgetRateLimiterWithJitter)remoteconfig_poller)Service)telemetry_writer)WrappingContext)Tracerzdynamic.instrumentation.metric)	namespace)clientTc                   @   s   e Zd ZdZdS )DebuggerErrorzGeneric debugger error.N)__name__
__module____qualname____doc__ r<   r<   O/home/ubuntu/.local/lib/python3.10/site-packages/ddtrace/debugging/_debugger.pyr7   D   s    r7   c                       s   e Zd ZdZdededededej	ddf fd	d
Z
deddfddZdeddfddZdefddZd"ddZdefdedeeeef ddfddZd# fddZdedef fddZdeee  dee dee ddf fd d!Z  ZS )$DebuggerWrappingContextc   f	collectorregistrytracerprobe_meterreturnNc                    s.   t  | || _|| _|| _|| _i | _d S N)super__init__
_collector_probe_registry_tracer_probe_meterprobes)selfr@   rA   rB   rC   rD   	__class__r<   r=   rH   M   s   
z DebuggerWrappingContext.__init__probec                 C   s   || j |j< d S rF   rM   probe_idrN   rQ   r<   r<   r=   	add_probe^   s   z!DebuggerWrappingContext.add_probec                 C   s   | j |j= d S rF   rR   rT   r<   r<   r=   remove_probea   s   z$DebuggerWrappingContext.remove_probec                 C   s
   t | jS rF   )boolrM   rN   r<   r<   r=   
has_probesd   s   
z"DebuggerWrappingContext.has_probesc           
      C   s  g }g }| j  D ]}|jr|n|| q	t }zf| j}t }t||D ]H}zt	j
|||| j | jd}W n tyI   tdt| Y q&w z|  W n tyh }	 ztd|	 W Y d }	~	q&d }	~	ww || q&W | dt  | d| d S | dt  | d| w )Nframethreadtrace_contextmeterzUnsupported probe type: %szFailed to enter signal
start_timesignals)rM   values__context_creator__appendr   	__frame__	threadingcurrent_threadr   r!   
from_proberK   current_trace_contextrL   	TypeErrorlogerrortypedo_enter	Exceptionr1   add_error_logsettimemonotonic_ns)
rN   context_creatorscontext_consumerspr`   r[   r\   rQ   signaler<   r<   r=   _open_signalsg   sD   
	z%DebuggerWrappingContext._open_signalsretvalexc_infoc              
   C   s   t  }zttt | d}W n ty) } ztd| W Y d }~d S d }~ww |rn|	 }z|
|||| d  W n tyV } ztd| W Y d }~q*d }~ww | j| |jtju rj| j|j |s,d S d S )Nr`   z2Signal contexts were not opened for function prober_   zFailed to exit signal)rq   rr   r   r   r!   getKeyErrorr1   ro   popdo_exitrn   rI   pushstater"   DONErJ   set_emittingrQ   )rN   ry   rz   end_timer`   rw   rv   r<   r<   r=   _close_signals   s*   z&DebuggerWrappingContext._close_signalsc                    s8   t    z|   W | S  ty   td Y | S w )Nz!Failed to open debugging contexts)rG   	__enter__rx   rn   rj   	exceptionrX   rO   r<   r=   r      s   

z!DebuggerWrappingContext.__enter__valuec                    s:   z| j |d W n ty   td Y nw t |S )N)ry   z.Failed to close debugging contexts from return)r   rn   rj   r   rG   
__return__)rN   r   rO   r<   r=   r      s   z"DebuggerWrappingContext.__return__exc_typeexc_valexc_tbc                    sN   z| j tt|||fd W n ty   td Y nw t ||| d S )Nrz   z7Failed to close debugging contexts from exception block)r   r   r'   rn   rj   r   rG   __exit__)rN   r   r   r   rO   r<   r=   r      s   z DebuggerWrappingContext.__exit__rE   N)rE   r>   )r8   r9   r:   __priority__r   r    r   r3   r*   MeterrH   r   rU   rV   rW   rY   rx   r&   r	   tupler   r   r6   r   r   rl   BaseExceptionr   r   __classcell__r<   r<   rO   r=   r>   J   s>    
&)

r>   c                       sd  e Zd ZU dZed  ed< edZe	Z
eZeZeZed*ddZed+deddfd	d
Zd,dee ddf fddZd*ddZdeddfddZdeddfddZdee ddfddZdee ddfddZdeddfddZ dee! ddfddZ"dee! ddfdd Z#d!e$de%e ddfd"d#Z&d+deddfd$d%Z'd*d&d'Z(ededdfd(d)Z)  Z*S )-DebuggerN	_instancerQ   rE   c                 C   sx   | j durtd| j dS td| j dt_tjrt  |   | _ }|  t	| j
 td| j td dS )zEnable dynamic instrumentation

        This class method is idempotent. Dynamic instrumentation will be
        disabled automatically at exit.
        Nz%s already enabledzEnabling %sTz
%s enabledzdynamic-instrumentation.enabled)r   rj   debugr8   r   enabledr   enablestartr,   _on_run_moduler%   dispatch)clsdebuggerr<   r<   r=   r      s   

zDebugger.enableTjoinc                 C   s   | j du rtd| j dS td| j td}td td |dur/tt	|
  t| j | j j|d d| _ tjrEt  dt_td| j dS )zDisable dynamic instrumentation.

        This class method is idempotent. Called automatically at exit, if
        dynamic instrumentation was enabled.
        Nz%s not enabledzDisabling %sLIVE_DEBUGGING)r   Fz%s disabled)r   rj   r   r8   r/   get_registeredunregister_callbackdisable_productr   r   delete_all_probesr-   r   stopr   r   disabler   )r   r   callbackr<   r<   r=   r      s    




zDebugger.disablerC   c                    s   t    |p	tj| _tj}| | | _}t	|d| _
tdgd| _tddd ttj fddd	dd
| _tj| _tjretjdu rKd	t_td | | j|| j
tj}td| td |   td| jj| d S )N)status_logger__dd_wrappers__)extra_attrsg      ?F)
limit_rateraise_on_exceedc                      s     tjdS )NzGlobal rate limit exceeded)limitrj   warningr<   log_limiterr<   r=   <lambda>  s    z#Debugger.__init__.<locals>.<lambda>T)r   	on_exceed	call_oncer   zADisabled Remote Configuration enabled by Dynamic Instrumentation.r   z!%s initialized (service name: %s)) rG   rH   ddtracerC   rK   r   service_name
__logger___status_loggerr   rJ   r   _function_storeRateLimiterglobal_rate_limit_global_rate_limiter
probe_filer   ddconfig_remote_config_enabledrj   info__rc_adapter___on_configurationdiagnostics_intervalr/   register_callbackenable_product_load_local_configr   rP   r8   )rN   rC   r   r   di_callbackrO   r   r=   rH     s8   




zDebugger.__init__c              
   C   s   | j d u rd S z&t| j  }dd |D }| tj| td| j dd |D  W d S  t	yH } zt
d| j | W Y d }~d S d }~ww )Nc                 S   s   g | ]}t |qS r<   r   .0ru   r<   r<   r=   
<listcomp>C  s    z/Debugger._load_local_config.<locals>.<listcomp>z+Successfully loaded probes from file %s: %sc                 S   s   g | ]}|j qS r<   rS   r   r<   r<   r=   r   F  s    z&Failed to load probes from file %s: %s)r   jsonloads	read_textr   r   
NEW_PROBESrj   r   rn   rk   )rN   
raw_probesrM   rw   r<   r<   r=   r   :  s   
 zDebugger._load_local_configc                 C   s   zizt j|tdt | j | jd}W n t	y+   t
jdt|dd Y W dS w || r5| jnd |jtju rD| j| t
dt t | | j  }du rbt
d| W dS || W dS  tyz   t
jd	dd Y dS w )
a(  Debugger probe hook.

        This gets called with a reference to the probe. We only check whether
        the probe is active. If so, we push the collected data to the collector
        for bulk processing. This way we avoid adding delay while the
        instrumented code is running.
           rZ   zUnsupported probe type: %rTr   Nz&[%s][P: %s] Debugger. Report signal %sz(No collector available to push signal %szFailed to execute probe hook)r!   rg   sys	_getframere   rf   rK   rh   rL   ri   rj   rk   rl   do_lineis_global_rate_limitedr   r   r"   r   rJ   r   r   osgetpidgetppid__uploader__get_collectorr   rn   )rN   rQ   rv   rA   r<   r<   r=   _dd_debugger_hookK  s0   
zDebugger._dd_debugger_hookmodulec           
   	      s  t t}jtt|D ]h}t|tsq|j}|d usJ t	
||}|sbtt|}t||rCd|j d| d| d}nd|j d| d| d}tj|ddid	 j|d
| qdd |D D ]}|| tt| qiq| D ]M\}}	j|fdd|	D  |	D ]}|j v rj|dd qj| q rtdt t   tdt t  fdd|	D | q{d S )NCannot install probe z: function at line z within source file z3 is likely decorated with an unsupported decorator.z: no functions at line z foundsend_to_telemetryFextraNoFunctionsAtLinec                 s       | ]}t t|V  qd S rF   r   r   r   _r<   r<   r=   	<genexpr>      z1Debugger._probe_injection_hook.<locals>.<genexpr>c                    s    g | ]} j tt|j|fqS r<   )r   r   r   liner   rQ   rX   r<   r=   r     s     z2Debugger._probe_injection_hook.<locals>.<listcomp>InjectionFailurezFailed to injectz&[%s][P: %s] Failed to inject probes %rz$[%s][P: %s] Injected probes %r in %rc                    s   g | ]
}|j  vr|j qS r<   r   r   )failedr<   r=   r         )r   listrJ   get_pendingstrr+   
isinstancer   r   r   from_moduleat_line	linecachegetlinerS   rj   rk   	set_errorrc   r   r   itemsr   inject_hooksset_installedr   r   r   r   )
rN   r   probes_for_functionrQ   r   	functionsmodule_originmessagefunctionrM   r<   )r   rN   r=   _probe_injection_hookn  s\   



zDebugger._probe_injection_hookrM   c                 C   s   |D ]2}|| j vrtdt t | | j | |j}|d u r4td|j	|j
 | j |dd qqdd |D D ]@}z
| j|| j W q< ty| } z(|D ]}|j|krZqRt|}| j ||jt| qRtjd|dd	 W Y d }~q<d }~ww d S )
Nz[%s][P: %s] Received new %s.z9Cannot inject probe %s: source file %s cannot be resolvedNoSourceFilez'Source file location cannot be resolvedc                 S   s   h | ]
}|j d ur|j qS rF   )resolved_source_filer   r<   r<   r=   	<setcomp>  r   z*Debugger._inject_probes.<locals>.<setcomp>z3Cannot register probe injection hook on source '%s'Tr   )rJ   rj   r   r   r   r   registerr   rk   rS   source_filer   __watchdog__register_origin_hookr   rn   rl   r8   r   )rN   rM   rQ   resolved_sourcesourceexcr   r<   r<   r=   _inject_probes  s2   


zDebugger._inject_probesprobes_to_ejectc              	      s  g }|D ]}| j vrtd| q j |\}|tt| qtt}|D ]}|j	d u r0q(||j	 | q(|
 D ]\}} j|}|d urtt}	|D ],}t|tsYqQ|j}
|
d usdJ |t||
}dd |D D ]	}|	| | qsqQ|	
 D ].\}} jtt| fdd|D }|D ]}|j|v rtd|| qtd|| qq j t|sz j| j td| W q= ty   tjd	|d
d Y q=w q=d S )N(Attempted to eject unregistered probe %rc                 s   r   rF   r   r   r<   r<   r=   r     r   z)Debugger._eject_probes.<locals>.<genexpr>c                    s$   g | ]}|j d ur j|j |fqS rF   )r   r   r   rX   r<   r=   r     s   $ z*Debugger._eject_probes.<locals>.<listcomp>zFailed to eject %r from %rzEjected %r from %rz*Unregistered injection hook on source '%s'z&Cannot unregister injection hook on %rTr   )rJ   rj   rk   
unregisterrc   r   r   r   r   r   r   r  get_by_originr   r   r   r   r   r   r   eject_hooksr   rS   r   rY   r   unregister_origin_hookr   
ValueError)rN   r  unregistered_probesrQ   registered_probeprobes_for_sourcer  rM   r   r   r   r   r   psr   r<   rX   r=   _eject_probes  sX   



zDebugger._eject_probesc                 C   st  | j |j}| j }|D ]}t|tsqz|jd ur!|jd us#J t	t
t||j}W n) tyY   d|j d|j d|j d}| j |d| tj|ddid Y qw t|rvt	tt|}td	t t |j| n6|d u rtd
 | j |dd
 qt||| j | j| jd}| jt	t
|| tdt t |j| || | j | qd S )Nr   z: no function 'z' in module zYfound (note: if the function exists, it might be decorated with an unsupported decorator)NoFunctionInModuler   Fr   z9[%s][P: %s] Function probe %r added to already wrapped %rzNo signal collector availableNoCollector)rA   rB   rC   rD   z/[%s][P: %s] Function probe %r wrapped around %r) rJ   r   r8   r   r   r   r   r   
func_qnamer   r   r   r   by_namer  rS   r   rj   rk   r>   
is_wrappedextractr   r   r   r   rK   rL   r   wraprU   r   )rN   r   rM   rA   rQ   r   r   contextr<   r<   r=   _probe_wrapping_hook  s\   


	

zDebugger._probe_wrapping_hookc                 C   s   |D ]D}| j | z|jd usJ | j|j| j W q tyF } zt|}| j ||j	t
| tjd|jdd W Y d }~qd }~ww d S )Nz2Cannot register probe wrapping hook on module '%s'Tr   )rJ   r   r   r  register_module_hookr  rn   rl   r   r8   r   rj   rk   )rN   rM   rQ   r  r   r<   r<   r=   _wrap_functions$  s   zDebugger._wrap_functionsc           
   	   C   sB  t  }|D ]l}| j|}|std| q|\}|jd us J tj|jd }|d urq|	|j |j
d us9J ttt||j
}t|rkttt|}|| | sd| jtt| td| qtd| q|D ]*}	| j|	sz| j|	| j td|	 W qt ty   tjd|	dd Y qtw qtd S )Nr	  zUnwrapped %rz,Attempted to unwrap %r, but no wrapper foundz.Unregistered wrapping import hook on module %sz4Cannot unregister wrapping import hook for module %rTr   )rp   rJ   r
  rj   rk   r   r   modulesr{   addr  r   r   r   r   r  r>   r  r  rV   rY   r   unwrapr   r   r  unregister_module_hookr  r  )
rN   rM   touched_modulesrQ   registered_probesr  r   r   r  module_namer<   r<   r=   _unwrap_functions/  s>   

zDebugger._unwrap_functionseventc                 C   s*  t dt t || |tjkr| j  d S |tj	krB|D ]}|| jv r?| j
|j}|d u r9t d| q | j| q d S g }g }|D ]$}t|trX|tt| qHt|trf|tt| qHt d| qH|tjkr~| | | | d S |tjkr| | | | d S td| )Nz3[%s][P: %s] Received poller event %r with probes %rz,Modified probe %r was not found in registry.z#Skipping probe '%r': not supported.zUnknown probe poller event %r)rj   r   r   r   r   r   STATUS_UPDATErJ   log_probes_statusMODIFIED_PROBESr{   rS   rk   updater   r   rc   r   r   r   r   r   r   r  r  DELETED_PROBESr  r&  r  )rN   r'  rM   rQ   r  line_probesfunction_probesr<   r<   r=   r   U  s:   









zDebugger._on_configurationc                 C   s   | j   | jtj d S rF   )r   restore_allr   r
  r$   DEBUGGER)rN   r   r<   r<   r=   _stop_service{  s   
zDebugger._stop_servicec                 C   s   | j tj d S rF   )r   r   r$   r0  rX   r<   r<   r=   _start_service  s   zDebugger._start_servicec                 C   s"   | j }|d ur|j| d S d S rF   )r   r  on_run_module)r   r   r   r<   r<   r=   r     s   zDebugger._on_run_moduler   )TrF   )+r8   r9   r:   r   r   __annotations___probe_metrics	get_meterrL   r   r   r#   r   r   r  r   r   classmethodr   rW   r   r3   rH   r   r   r   r   r   r   r   r  r  r  r   r  r&  r   r
   r   r1  r2  r   r   r<   r<   rO   r=   r      s2   
 
$
-#724&&
r   )_collectionsr   r   	itertoolsr   r   r   r   pathlibr   r   re   rq   typesr   r   r   typingr	   r
   r   r   r   r   r   r   ddtrace.debugging._configr   %ddtrace.debugging._function.discoveryr   !ddtrace.debugging._function.storer   r   ddtrace.debugging._importr   ddtrace.debugging._metricsr   ddtrace.debugging._probe.modelr   r   r   r   r   !ddtrace.debugging._probe.registryr   %ddtrace.debugging._probe.remoteconfigr   r   r   ddtrace.debugging._probe.statusr   #ddtrace.debugging._signal.collectorr    ddtrace.debugging._signal.modelr!   r"   ddtrace.debugging._uploaderr#   r$   ddtrace.internalr%   ddtrace.internal.compatr&   r'   ddtrace.internal.loggerr(   ddtrace.internal.metricsr)   r*   ddtrace.internal.moduler+   r,   r-   ddtrace.internal.rate_limiterr.   r   $ddtrace.internal.remoteconfig.workerr/   ddtrace.internal.servicer0   ddtrace.internal.telemetryr1   !ddtrace.internal.wrapping.contextr2   ddtrace.tracer3   r8   rj   r5  r   r6   rn   r7   r>   r   r<   r<   r<   r=   <module>   s~    y