o
    i                     @   s  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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# 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"l-m1Z1 d d#l-m2Z2 d d$l-m3Z3 d d%l-m4Z4 d d&l-m5Z5 d d'l-m6Z6 d d(l7m8Z8 d d)l9m: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/lDmEZE d d0lFmGZG d d0lHmGZI d d1lJmKZK d d2lLmMZM d d3lNmOZO d d4lPmQZQ d d5lRmSZS d d6lRmTZT d d7lUmVZV d d8lWmXZX e:eYZZed9ed:Z[d;eAd<e\e fd=d>Z]G d?d@ d@e^Z_dS )A    )contextmanagerN)iscoroutinefunction)chain)getpid)Lock)Callable)Optional)TypeVar)Union)cast)Context)SpanAggregator)SpanProcessor)TopLevelSpanProcessor)TraceProcessor)ResourceRenamingProcessor)BaseContextProvider)DefaultContextProvider)Span)APPSEC)_HOSTNAME_KEY)ENV_KEY)PID)VERSION_KEY)atexit)core)debug)forksafe)hostname)LOG_ATTR_ENV)LOG_ATTR_SERVICE)LOG_ATTR_SPAN_ID)LOG_ATTR_TRACE_ID)LOG_ATTR_VALUE_EMPTY)LOG_ATTR_VALUE_ZERO)LOG_ATTR_VERSION)SAMPLING_DECISION_TRACE_TAG_KEY)SPAN_API_DATADOG)get_hostname)
get_logger)PyTracerMetadata)store_metadata)PeerServiceProcessor)EndpointCallCounterProcessor)get_runtime_id)BaseServiceProcessor)config)
_ps_config)_get_metas_to_propagate)DDTraceDeprecationWarning)format_trace_id)AgentWriterInterface)
HTTPWriter)	deprecate)__version__AnyCallable)boundprofiling_span_processorreturnc                 C   sT   g }|t  g7 }tjr|t  tjr#tjs#ddlm} ||  ||  |S )z5Construct the default list of span processors to use.r   )SpanStatsProcessorV06)	r   r0    _trace_resource_renaming_enabledappendr   _trace_compute_stats_trace_writer_native ddtrace.internal.processor.statsr=   )r;   span_processorsr=    rD   I/home/ubuntu/.local/lib/python3.10/site-packages/ddtrace/_trace/tracer.py _default_span_processors_factoryF   s   
rF   c                   @   s  e Zd ZdZdZdZd]ddZedee	 fddZ
e
jd	e	fd
dZ
d]ddZdd Zd]ddZedefddZedd Zejdd Zedd Zejdd Zedd Zdee fddZd^deeeef  dee	e	f fdd Z				!			d_d"ee d#ee d$ee d%ee	 d&ee d'ee d(eee  ddfd)d*Zd+d, Zd-d. Z 					/d`d(eee  d#ee d0ee d$ee d1eddfd2d3Z!ddddd4e"fd5e	d6eeeef  d7ee	 d8ee	 d9ee	 d:ed;e	defd<d=Z#e#Z$ddddd4e"fd5e	d6eeeef  d7ee	 d8ee	 d9ee	 d:ed;e	defd>d?Z%d@eddfdAdBZ&dCdD Z'ddde"fd5e	d7ee	 d8ee	 d9ee	 d;e	defdEdFZ(dee fdGdHZ)dee fdIdJZ*edee	 fdKdLZ+dMdN Z,			dadOe-dPe	d7ee	 d8ee	 d9ee	 de-fdQdRZ.			dadOe-dPe	d7ee	 d8ee	 d9ee	 de-fdSdTZ/				dbd5ee	 d7ee	 d8ee	 d9ee	 de0e-ge-f f
dUdVZ1dWee	e	f ddfdXdYZ2d^dZee3 ddfd[d\Z4dS )cTracera_  
    Tracer is used to create, sample and submit spans that measure the
    execution time of sections of code.

    If you're running an application that will serve a single trace per thread,
    you can use the global tracer instance::

        from ddtrace.trace import tracer
        trace = tracer.trace('app.request', 'web-server').finish()
       Nr<   c              
   C   sN  t | tu rtjdu r| t_ntd tj | _d| _	t
 | _tj| _t | _tjr2d| _dt_t | _t| j| _ttjtjttt gd| _t| j  t!"| j# t!$| j# t"| j% t& | _'d| _(t)t* t+t, tj-ptdtj.pxdtj/p|dddd}zt0|| _1W dS  t2y } ztj3dt4|dd W Y d}~dS d}~ww )	z
        Create a new ``Tracer`` instance. A global tracer is already initialized
        for common usage, so there is no need to initialize your own ``Tracer``.
        Nz^Initializing multiple Tracer instances is not supported. Use ``ddtrace.trace.tracer`` instead.F)partial_flush_enabledpartial_flush_min_spansdd_processors)
runtime_idtracer_versionr   service_nameservice_envservice_versionprocess_tagscontainer_idz)Failed to store the configuration on disk)error)extra)5typerG   	_instancelogrS   r0   tagscopy_tags_wrap_executorr   _pid_tracing_enabledenabledr   context_provider
asm_config_apm_opt_outr@   r-   %_endpoint_call_counter_span_processorrF   _span_processorsr   _partial_flush_enabled_partial_flush_min_spansr,   r1   r/   _span_aggregatorr   register_before_fork_sample_before_forkr   register_atexitregister_on_exit_signal_child_after_forkr   _shutdown_lock_new_processr*   r.   r8   r(   serviceenvversionr+   _config_on_disk	Exceptionr   dict)selfmetadataerD   rD   rE   __init__n   sV   

"zTracer.__init__c                 C   s    t | jjttfr| jjjS d S N
isinstancerf   writerr6   r5   
intake_urlru   rD   rD   rE   
_agent_url   s   
zTracer._agent_urlvaluec                 C   s$   t | jjttfr|| jj_d S d S ry   rz   ru   r   rD   rD   rE   r      s   c                 C   s4   t jdkrdnd}td| j| | j| jd d S )Nntz
ctrl-breakzctrl-cz8Waiting %d seconds for tracer to finish. Hit %s to quit.)timeout)osnamerW   r   SHUTDOWN_TIMEOUTshutdown)ru   keyrD   rD   rE   rj      s   zTracer._atexitc                 C   s   | j | d S ry   )_samplersampleru   spanrD   rD   rE   r      s   zTracer.samplec                 C   s2   |   }|d ur|jjd u r| | d S d S d S ry   )current_root_spancontextsampling_priorityr   r   rD   rD   rE   rh      s   zTracer._sample_before_forkr   c              	   c   sR    | j  }d|_| j | zd V  W d|_| j | d S d|_| j | w )NTF)r_   active_reactivateactivate)ru   r   prev_activerD   rD   rE   _activate_context   s   
zTracer._activate_contextc                 C   s"   ddl m} tdddtd | S )Nr   )data_streams_processorz+Tracer.data_streams_processor is deprecatedz:Use ddtrace.data_streams.data_streams_processor() instead.5.0.0)prefixmessageremoval_versioncategory)ddtrace.internal.datastreamsr   r7   r3   )ru   r   rD   rD   rE   r      s   zTracer.data_streams_processorc                 C   s   t ddtd d S )Nz4Setting Tracer.data_streams_processor is unsupportedr   )r   r   r   )r7   r3   r   rD   rD   rE   r      s
   
c                 C   s
   | j jjS ry   rf   sampling_processorsamplerr~   rD   rD   rE   r      s   
zTracer._samplerc                 C   s   || j j_d S ry   r   r   rD   rD   rE   r      s   c                 C   s   t tjS ry   )rW   isEnabledForloggingDEBUGr~   rD   rD   rE   debug_logging   s   zTracer.debug_loggingc                 O   s,   | j  }t|tr|S t|tr|jS dS )znReturn the context for the current trace.

        If there is no active trace then None is returned.
        N)r_   r   r{   r   r   r   )ru   argskwargsr   rD   rD   rE   current_trace_context   s   


zTracer.current_trace_contextr   c              
   C   s|   |du r| j s
tjr| j }t }}|r)|jrt|jn|}|jr't	|jn|}t
|t|ttjp2tttjp7tttjp<tiS )a  Retrieves the data used to correlate a log with the current active trace.
        Generates a dictionary for custom logging instrumentation including the trace id and
        span id of the current active span, as well as the configured service, version, and environment names.
        If there is no active span, a dictionary with an empty string for each value will be returned.
        N)r^   r`   ra   r_   r   r$   span_idstrtrace_idr4   r"   r!   r    r0   ro   r#   r%   rq   r   rp   )ru   r   r   r   rD   rD   rE   get_log_correlation_context  s   



z"Tracer.get_log_correlation_context r_   compute_stats_enabledappsec_enabledappsec_enabled_originiast_enabledapm_tracing_disabledtrace_processorsc                 C   s   |dur|t _|r|t _|dur|t _|dur| t _t jr-d t_| _dt_	t
d n	t jr6d t_| _|dur=|t_	tdd ||||fD rU| j||t j|dd |dur^|| _dS dS )a  Configure a Tracer.

        :param object context_provider: The ``ContextProvider`` that will be used to retrieve
            automatically the current call context. This is an advanced option that usually
            doesn't need to be changed from the default value.
        :param bool appsec_enabled: Enables Application Security Monitoring (ASM) for the tracer.
        :param bool iast_enabled: Enables IAST support for the tracer
        :param bool apm_tracing_disabled: When APM tracing is disabled ensures ASM support is still enabled.
        :param list[TraceProcessor] trace_processors: This parameter sets TraceProcessor (ex: TraceFilters).
           Trace processors are used to modify and filter traces based on certain criteria.
        NFzQASM standalone mode is enabled, traces will be rate limited at 1 trace per minuteTc                 s   s    | ]}|d uV  qd S ry   rD   ).0xrD   rD   rE   	<genexpr>G  s
    
z#Tracer.configure.<locals>.<genexpr>reset_buffer)r`   _asm_enabled_asm_enabled_origin_iast_enabled_apm_tracing_enabledra   r0   r]   r^   r@   rW   r   any	_recreater_   )ru   r_   r   r   r   r   r   r   rD   rD   rE   	configure  s:   	
zTracer.configurec              
   C   s   t jst jrRzt }W n  ty, } zd| }| tjd|  W Y d }~d S d }~ww t	
tjr>d| }| tj| |d}|rTd| }| tj| d S d S d S )Nz#Failed to collect start-up logs: %sz - DATADOG TRACER DIAGNOSTIC - %sz#- DATADOG TRACER CONFIGURATION - %sagent_error)r0   _debug_mode_startup_logs_enabledr   collectrs   _log_compatr   WARNINGrW   r   INFOget)ru   inforw   msgr   rD   rD   rE   _generate_diagnostic_logsW  s"    
z Tracer._generate_diagnostic_logsc                 C   s   t  | _| jdd d| _d S )NTr   )r   r\   r   rn   r~   rD   rD   rE   rl   j  s   
zTracer._child_after_forkTapm_opt_outr   c                 C   s&   | j j|||||d t| j| _dS )z6Re-initialize the tracer's processors and trace writer)user_processorscompute_statsr   r   r   N)rf   resetrF   rb   rc   )ru   r   r   r   r   r   rD   rD   rE   r   o  s   
zTracer._recreateFr   child_ofro   resource	span_typer   span_apic                 C   s^  | j rd| _ t|tr|j}| j |u r| j| |}d}	d}
d}d}|dur<t|tr1|}
n|j}
|}	|
j}|
j	}|du rI|	rF|	j
}ntj
}|durTtj||}|	s[|
r[|
jng }|sf|sf|
r|
jrt||
|||||||| jgd
}|	r|	|_|	j|_|jj
|kr|	j|_t|
D ]\}}|ttjfvr||j|< qnt||
||||| jgd}tjr|tt  |js|dt  | j|j t!< | j"r|#| j" tj$r|t%tj$ tj&r| ' }|du r|tj
ks|r|j
|kr|(t)dur|t)tj& |r| j| | j*st+j,r&t-| j.t/j0| j1gD ]}|r$|2| qt34d|f |S )a  Return a span that represents an operation called ``name``.

        Note that the :meth:`.trace` method will almost always be preferred
        over this method as it provides automatic span parenting. This method
        should only be used if manual parenting is desired.

        :param str name: the name of the operation being traced.
        :param object child_of: a ``Span`` or a ``Context`` instance representing the parent for this span.
        :param str service: the name of the service being traced.
        :param str resource: an optional name of the resource being tracked.
        :param str span_type: an optional operation type.
        :param activate: activate the span once it is created.

        To start a new root span::

            span = tracer.start_span("web.request")

        To create a child for a root span::

            root_span = tracer.start_span("web.request")
            span = tracer.start_span("web.decoder", child_of=root_span)

        Spans from ``start_span`` are not activated by default::

            with tracer.start_span("parent") as parent:
                assert tracer.current_span() is None
                with tracer.start_span("child", child_of=parent):
                    assert tracer.current_span() is None

            new_parent = tracer.start_span("new_parent", activate=True)
            assert tracer.current_span() is new_parent

        Note: be sure to finish all spans to avoid memory leaks and incorrect
        parenting of spans.
        FN)
r   r   r   	parent_idro   r   r   r   links	on_finish)r   r   ro   r   r   r   r   z
runtime-idztrace.span_start)5rn   r{   r   r   r_   r   r   r   r   r   ro   r0   service_mappingr   _span_links_baggage_on_span_finish_parent_local_root_service_entry_spanr2   r&   r   PROPAGATION_HEADER_meta_report_hostname_set_tag_strr   r   r(   r.   r\   _metricsr   rZ   set_tagsrp   r   rq   r   get_tagr   r^   r`   ra   r   rc   r   __processors__rf   on_span_startr   dispatch)ru   r   r   ro   r   r   r   r   new_ctxparentr   r   r   r   r   kv	root_spanprD   rD   rE   
start_span  s   -


	
zTracer.start_spanc           	   	   C   s&   |  |||||||}td| |S )Nz\Spans started after the tracer has been shut down will not be sent to the Datadog Agent: %s.)_start_spanrW   warning)	ru   r   r   ro   r   r   r   r   r   rD   rD   rE   _start_span_after_shutdown/  s
   
z!Tracer._start_span_after_shutdownr   c                 C   s   |   }|jd ur||jurtd||j | jstjr0t| jt	j
| jgD ]	}|r/|| q&td|f td|| j d S )NzJspan %r closing after its parent %r, this is an error when not using asyncztrace.span_finishz finishing span - %r (enabled:%s))current_spanr   rW   r   r^   r`   ra   r   rc   r   r   rf   on_span_finishr   r   )ru   r   r   r   rD   rD   rE   r   ?  s   
zTracer._on_span_finishc                 C   s   t  || dS )a  Logs a message for the given level.

        Instead, something like this will be printed to stderr:
            No handlers could be found for logger "ddtrace.tracer"

        Since the global tracer is configured on import and it is recommended
        to import the tracer as early as possible, it will likely be the case
        that there are no handlers installed yet.
        N)rW   )ru   levelr   rD   rD   rE   r   O  s   
zTracer._log_compatc              	   C   s   | j || j |||d|dS )a  Activate and return a new span that inherits from the current active span.

        :param str name: the name of the operation being traced
        :param str service: the name of the service being traced. If not set,
                            it will inherit the service from its parent.
        :param str resource: an optional name of the resource being tracked.
        :param str span_type: an optional operation type.

        The returned span *must* be ``finish``'d or it will remain in memory
        indefinitely::

            >>> span = tracer.trace("web.request")
                try:
                    # do something
                finally:
                    span.finish()

            >>> with tracer.trace("web.request") as span:
                    # do something

        Example of the automatic parenting::

            parent = tracer.trace("parent")     # has no parent span
            assert tracer.current_span() is parent

            child  = tracer.trace("child")
            assert child.parent_id == parent.span_id
            assert tracer.current_span() is child
            child.finish()

            # parent is now the active span again
            assert tracer.current_span() is parent
            parent.finish()

            assert tracer.current_span() is None

            parent2 = tracer.trace("parent2")
            assert parent2.parent_id is None
            parent2.finish()
        T)r   ro   r   r   r   r   )r   r_   r   )ru   r   ro   r   r   r   rD   rD   rE   trace[  s   0zTracer.tracec                 C   s   |   }|du r
dS |jS )a  Returns the local root span of the current execution/process.

        Note: This cannot be used to access the true root span of the trace
        in a distributed tracing setup if the actual root span occurred in
        another execution/process.

        This is useful for attaching information to the local root span
        of the current execution/process, which is often also service
        entry span.

        For example::

            # get the local root span
            local_root_span = tracer.current_root_span()
            # set the host just once on the root span
            if local_root_span:
                local_root_span.set_tag('host', '127.0.0.1')
        N)r   r   r   rD   rD   rE   r     s   zTracer.current_root_spanc                 C   s   | j  }t|tr|S dS )zReturn the active span in the current execution context.

        Note that there may be an active span represented by a context object
        (like from a distributed trace) which will not be returned by this
        method.
        N)r_   r   r{   r   )ru   r   rD   rD   rE   r     s   
zTracer.current_spanc                 C   s   t | jjtr| jjjS dS )zTrace agent urlN)r{   rf   r|   r5   r}   r~   rD   rD   rE   agent_trace_url  s   
zTracer.agent_trace_urlc                 C   s   | j j  dS )z^Flush the buffer of the trace writer. This does nothing if an unbuffered trace writer is used.N)rf   r|   flush_queuer~   rD   rD   rE   flush  s   zTracer.flushf	span_namec                    *   t   fdd}tt|S )'Wrap a generator function with tracing.c               
   ?   st    j d urj  | |dS jd  | i |E d H }|W  d    S 1 s3w   Y  d S Nro   r   r   r[   r   )r   r   return_valuer   r   ru   ro   r   r   rD   rE   func_wrapper  s    
$z,Tracer._wrap_generator.<locals>.func_wrapper	functoolswrapsr   r9   ru   r   r   ro   r   r   r   rD   r   rE   _wrap_generator  s   

zTracer._wrap_generatorc                    r   )r   c                    s^   j d  | i |2 z	3 d H W }|V  q6 W d    d S 1 s(w   Y  d S r   r   )r   r   r   r   rD   rE   r     s   "z2Tracer._wrap_generator_async.<locals>.func_wrapperr   r  rD   r   rE   _wrap_generator_async  s   

zTracer._wrap_generator_asyncc                    s"   dt dt f fdd}|S )a#  
        A decorator used to trace an entire function. If the traced function
        is a coroutine, it traces the coroutine execution when is awaited.

        :param str name: the name of the operation being traced. If not set,
                         defaults to the fully qualified function name.
        :param str service: the name of the service being traced. If not set,
                            it will inherit the service from its parent.
        :param str resource: an optional name of the resource being tracked.
        :param str span_type: an optional operation type.

        >>> @tracer.wrap('my.wrapped.function', service='my.service')
            def run():
                return 'run'

        >>> # name will default to 'execute' if unset
            @tracer.wrap()
            def execute():
                return 'executed'

        >>> # or use it in asyncio coroutines
            @tracer.wrap()
            async def coroutine():
                return 'executed'

        >>> @tracer.wrap()
            @asyncio.coroutine
            def coroutine():
                return 'executed'

        >>> # or use it on generators
            @tracer.wrap()
            def gen():
                yield 'executed'

        >>> @tracer.wrap()
            async def gen():
                yield 'executed'

        You can access the current span using `tracer.current_span()` to set
        tags:

        >>> @tracer.wrap()
            def execute():
                span = tracer.current_span()
                span.set_tag('a', 'b')
        r   r<   c                    s   rnd j  jf t rj d}|S t r.j d}|S t rDt	  fdd}|S t	  fdd}|S )Nz%s.%sr   c                     sL   j d  | i |I d H W  d    S 1 sw   Y  d S r   r  r   r   r   rD   rE   r   C  s   $z9Tracer.wrap.<locals>.wrap_decorator.<locals>.func_wrapperc               
      sh   j d urj  | |dS jd  | i |W  d    S 1 s-w   Y  d S r   r   r  r   rD   rE   r   J  s   
$)

__module____name__inspectisgeneratorfunctionr  isasyncgenfunctionr  r   r   r  )r   r   r   r   ru   ro   r   )r   r   rE   wrap_decorator*  s4   
,
$z#Tracer.wrap.<locals>.wrap_decorator)r9   )ru   r   ro   r   r   r  rD   r  rE   wrap  s   76zTracer.wraprX   c                 C   s   | j | dS )zSet some tags at the tracer level.
        This will append those tags to each span created by the tracer.

        :param dict tags: dict of tags to set at tracer level
        N)rZ   update)ru   rX   rD   rD   rE   r   b  s   zTracer.set_tagsr   c                 C   s   | j jdds	dS zLt| jtj| jgD ]	}|r|| qd| _d| _	| j
d | j| jkrNt| j t| j t| j | j| _W | j   dS W | j   dS | j   w )ap  Shutdown the tracer and flush finished traces. Avoid calling shutdown multiple times.

        :param timeout: How long in seconds to wait for the background worker to flush traces
            before exiting or :obj:`None` to block until flushing has successfully completed (default: :obj:`None`)
        :type timeout: :obj:`int` | :obj:`float` | :obj:`None`
        F)blockingN)rm   acquirer   rc   r   r   rf   r   r^   r[   r_   r   r   r   r   unregister_before_forkrh   r   
unregisterrj   rl   release)ru   r   	processorrD   rD   rE   r   j  s$   

zTracer.shutdown)r<   Nry   )NNNr   NNN)NNNNT)NNN)NNNN)5r  r  __qualname____doc__r   rV   rx   propertyr   r   r   setterrj   r   rh   r   r   r   r   r   r   r   r
   r   rt   r   r   boollistr   r   r   rl   r   r'   r   r   r   r   r   r   r   r   r   r   r9   r  r  r   r  r   floatr   rD   rD   rD   rE   rG   _   s~   
C
	






(
	
<

	
 )	

:

"

orG   )`
contextlibr   r   r	  r   	itertoolsr   r   r   r   	threadingr   typingr   r   r	   r
   r   ddtrace._trace.contextr   ddtrace._trace.processorr   r   r   r   *ddtrace._trace.processor.resource_renamingr   ddtrace._trace.providerr   r   ddtrace._trace.spanr   ddtrace.appsec._constantsr   ddtrace.constantsr   r   r   r   ddtrace.internalr   r   r   r   r   ddtrace.internal.constantsr   r    r!   r"   r#   r$   r%   r&   r'   ddtrace.internal.hostnamer(   ddtrace.internal.loggerr)   ddtrace.internal.nativer*   r+   'ddtrace.internal.peer_service.processorr,   0ddtrace.internal.processor.endpoint_call_counterr-   ddtrace.internal.runtimer.   !ddtrace.internal.schema.processorr/   !ddtrace.internal.settings._configr0   ddtrace.internal.settings.asmr`   &ddtrace.internal.settings.peer_servicer1   ddtrace.internal.utilsr2   #ddtrace.internal.utils.deprecationsr3   ddtrace.internal.utils.formatsr4   ddtrace.internal.writerr5   r6   ddtrace.vendor.debtcollectorr7   ddtrace.versionr8   r  rW   r9   r  rF   objectrG   rD   rD   rD   rE   <module>   s    
