
    gA                     b   d 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	m
Z
 ddlmZ ddlmZmZ ddlmZmZmZ dd	lmZ dd
lmZ  ee      Z G d dej4                        Z G d d      Z G d dej:                        Z G d de      Z eej@                        Z!	  eejD                        Z#	  G d de      Z$ G d de      Z% e%e!      Z&	  e%e#      Z'	  G d de%      Z( G d de      Z) G d de      Z* G d de%      Z+ G d d e%      Z,e#e!e'e&e$e(d!Z-d"efd#Z.d$e	e   d"e	d%   fd&Z/y)'a  
For general information about sampling, see `the specification <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#sampling>`_.

OpenTelemetry provides two types of samplers:

- `StaticSampler`
- `TraceIdRatioBased`

A `StaticSampler` always returns the same sampling result regardless of the conditions. Both possible StaticSamplers are already created:

- Always sample spans: ALWAYS_ON
- Never sample spans: ALWAYS_OFF

A `TraceIdRatioBased` sampler makes a random sampling result based on the sampling probability given.

If the span being sampled has a parent, `ParentBased` will respect the parent delegate sampler. Otherwise, it returns the sampling result from the given root sampler.

Currently, sampling results are always made during the creation of the span. However, this might not always be the case in the future (see `OTEP #115 <https://github.com/open-telemetry/oteps/pull/115>`_).

Custom samplers can be created by subclassing `Sampler` and implementing `Sampler.should_sample` as well as `Sampler.get_description`.

Samplers are able to modify the `opentelemetry.trace.span.TraceState` of the parent of the span being created. For custom samplers, it is suggested to implement `Sampler.should_sample` to utilize the
parent span context's `opentelemetry.trace.span.TraceState` and pass into the `SamplingResult` instead of the explicit trace_state field passed into the parameter of `Sampler.should_sample`.

To use a sampler, pass it into the tracer provider constructor. For example:

.. code:: python

    from opentelemetry import trace
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import (
        ConsoleSpanExporter,
        SimpleSpanProcessor,
    )
    from opentelemetry.sdk.trace.sampling import TraceIdRatioBased

    # sample 1 in every 1000 traces
    sampler = TraceIdRatioBased(1/1000)

    # set the sampler onto the global tracer provider
    trace.set_tracer_provider(TracerProvider(sampler=sampler))

    # set up an exporter for sampled spans
    trace.get_tracer_provider().add_span_processor(
        SimpleSpanProcessor(ConsoleSpanExporter())
    )

    # created spans will now be sampled by the TraceIdRatioBased sampler
    with trace.get_tracer(__name__).start_as_current_span("Test Span"):
        ...

The tracer sampler can also be configured via environment variables ``OTEL_TRACES_SAMPLER`` and ``OTEL_TRACES_SAMPLER_ARG`` (only if applicable).
The list of built-in values for ``OTEL_TRACES_SAMPLER`` are:

    * always_on - Sampler that always samples spans, regardless of the parent span's sampling decision.
    * always_off - Sampler that never samples spans, regardless of the parent span's sampling decision.
    * traceidratio - Sampler that samples probabilistically based on rate.
    * parentbased_always_on - (default) Sampler that respects its parent span's sampling decision, but otherwise always samples.
    * parentbased_always_off - Sampler that respects its parent span's sampling decision, but otherwise never samples.
    * parentbased_traceidratio - Sampler that respects its parent span's sampling decision, but otherwise samples probabilistically based on rate.

Sampling probability can be set with ``OTEL_TRACES_SAMPLER_ARG`` if the sampler is traceidratio or parentbased_traceidratio. Rate must be in the range [0.0,1.0]. When not provided rate will be set to
1.0 (maximum rate possible).

Prev example but with environment variables. Please make sure to set the env ``OTEL_TRACES_SAMPLER=traceidratio`` and ``OTEL_TRACES_SAMPLER_ARG=0.001``.

.. code:: python

    from opentelemetry import trace
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import (
        ConsoleSpanExporter,
        SimpleSpanProcessor,
    )

    trace.set_tracer_provider(TracerProvider())

    # set up an exporter for sampled spans
    trace.get_tracer_provider().add_span_processor(
        SimpleSpanProcessor(ConsoleSpanExporter())
    )

    # created spans will now be sampled by the TraceIdRatioBased sampler with rate 1/1000.
    with trace.get_tracer(__name__).start_as_current_span("Test Span"):
        ...

When utilizing a configurator, you can configure a custom sampler. In order to create a configurable custom sampler, create an entry point for the custom sampler
factory method or function under the entry point group, ``opentelemetry_traces_sampler``. The custom sampler factory method must be of type ``Callable[[str], Sampler]``, taking a single string argument and
returning a Sampler object. The single input will come from the string value of the ``OTEL_TRACES_SAMPLER_ARG`` environment variable. If ``OTEL_TRACES_SAMPLER_ARG`` is not configured, the input will
be an empty string. For example:

.. code:: python

    setup(
        ...
        entry_points={
            ...
            "opentelemetry_traces_sampler": [
                "custom_sampler_name = path.to.sampler.factory.method:CustomSamplerFactory.get_sampler"
            ]
        }
    )
    # ...
    class CustomRatioSampler(Sampler):
        def __init__(rate):
            # ...
    # ...
    class CustomSamplerFactory:
        @staticmethod
        def get_sampler(sampler_argument):
            try:
                rate = float(sampler_argument)
                return CustomSampler(rate)
            except ValueError: # In case argument is empty string.
                return CustomSampler(0.5)

In order to configure you application with a custom sampler's entry point, set the ``OTEL_TRACES_SAMPLER`` environment variable to the key name of the entry point. For example, to configured the
above sampler, set ``OTEL_TRACES_SAMPLER=custom_sampler_name`` and ``OTEL_TRACES_SAMPLER_ARG=0.5``.
    N)	getLogger)MappingProxyType)OptionalSequence)Context)OTEL_TRACES_SAMPLEROTEL_TRACES_SAMPLER_ARG)LinkSpanKindget_current_span)
TraceState)
Attributesc                   $    e Zd ZdZdZdZd Zd Zy)Decisionr         c                 F    | t         j                  t         j                  fv S N)r   RECORD_ONLYRECORD_AND_SAMPLEselfs    U/var/www/openai/venv/lib/python3.12/site-packages/opentelemetry/sdk/trace/sampling.pyis_recordingzDecision.is_recording   s    ,,h.H.HIII    c                 &    | t         j                  u S r   )r   r   r   s    r   
is_sampledzDecision.is_sampled   s    x1111r   N)__name__
__module____qualname__DROPr   r   r   r    r   r   r   r      s    DKJ2r   r   c            	       @    e Zd ZdZdefdZ	 	 ddeddded	   ddfd
Zy)SamplingResulta  A sampling result as applied to a newly-created Span.

    Args:
        decision: A sampling decision based off of whether the span is recorded
            and the sampled flag in trace flags in the span context.
        attributes: Attributes to add to the `opentelemetry.trace.Span`.
        trace_state: The tracestate used for the `opentelemetry.trace.Span`.
            Could possibly have been modified by the sampler.
    returnc                     t        |       j                   dt        | j                         dt        | j                         dS )N(z, attributes=))typer   strdecision
attributesr   s    r   __repr__zSamplingResult.__repr__   s;    t*%%&aDMM(:';=T__I]H^^_``r   Nr+   r,   r   trace_stater   c                 t    || _         |t        i       | _        || _        y t        |      | _        || _        y r   )r+   r   r,   r.   )r   r+   r,   r.   s       r   __init__zSamplingResult.__init__   s=     !.r2DO ' /z:DO&r   )NN)	r   r   r    __doc__r*   r-   r   r   r0   r"   r   r   r$   r$      sM    a# a $(.2	'' !' l+	'
 
'r   r$   c                       e Zd Zej                  	 	 	 	 dded   dededee   de	dee
d	      d
ed   ddfd       Zej                  defd       Zy)SamplerNparent_contextr   trace_idnamekindr,   linksr
   r.   r   r%   r$   c                      y r   r"   r   r4   r5   r6   r7   r,   r8   r.   s           r   should_samplezSampler.should_sample   s     	r   c                      y r   r"   r   s    r   get_descriptionzSampler.get_description   s    r   NNNN)r   r   r    abcabstractmethodr   intr*   r   r   r   r;   r=   r"   r   r   r3   r3      s     $(!%,0.2
 +
 
 	

 x 
 
 ()
 l+
 

 
 	  r   r3   c                   t    e Zd ZdZddZ	 	 	 	 dded   deded	ee   d
e	dee
d      ded   ddfdZdefdZy)StaticSamplerz.Sampler that always returns the same decision.r%   Nc                     || _         y r   )	_decision)r   r+   s     r   r0   zStaticSampler.__init__   s	    !r   r4   r   r5   r6   r7   r,   r8   r
   r.   r   r$   c                 ~    | j                   t        j                  u rd }t        | j                   |t	        |            S r   )rE   r   r!   r$   _get_parent_trace_stater:   s           r   r;   zStaticSampler.should_sample   s8     >>X]]*JNN#N3
 	
r   c                 >    | j                   t        j                  u ryy)NAlwaysOffSamplerAlwaysOnSampler)rE   r   r!   r   s    r   r=   zStaticSampler.get_description   s    >>X]]*% r   )r+   r   r%   Nr>   )r   r   r    r1   r0   r   rA   r*   r   r   r   r;   r=   r"   r   r   rC   rC      s    8" $(!%,0.2
 +
 
 	

 x 
 
 ()
 l+
 

$! !r   rC   c                       e Zd ZdZdefdZdZededefd       Z	e
defd       Ze
defd       Z	 	 	 	 dd
ed   dededee   dedeed      ded   ddfdZdefdZy	)TraceIdRatioBasedz
    Sampler that makes sampling decisions probabilistically based on `rate`.

    Args:
        rate: Probability (between 0 and 1) that a span will be sampled
    ratec                 |    |dk  s|dkD  rt        d      || _        | j                  | j                        | _        y )Ng              ?z(Probability must be in range [0.0, 1.0].)
ValueError_rateget_bound_for_rate_bound)r   rM   s     r   r0   zTraceIdRatioBased.__init__  s8    #:GHH
--djj9r   l    r%   c                 8    t        || j                  dz   z        S )Nr   )roundTRACE_ID_LIMIT)clsrM   s     r   rR   z$TraceIdRatioBased.get_bound_for_rate  s    TS//!3455r   c                     | j                   S r   rQ   r   s    r   rM   zTraceIdRatioBased.rate  s    zzr   c                     | j                   S r   )rS   r   s    r   boundzTraceIdRatioBased.bound  s    {{r   Nr4   r   r5   r6   r7   r,   r8   r
   r.   r   r$   c                     t         j                  }|| j                  z  | j                  k  rt         j                  }|t         j                  u rd }t        ||t        |            S r   )r   r!   rV   r[   r   r$   rG   )	r   r4   r5   r6   r7   r,   r8   r.   r+   s	            r   r;   zTraceIdRatioBased.should_sample  s[     ==d)))DJJ611Hx}}$J#N3
 	
r   c                 "    d| j                    dS )NzTraceIdRatioBased{}rY   r   s    r   r=   z!TraceIdRatioBased.get_description1  s    $TZZL33r   r>   )r   r   r    r1   floatr0   rV   classmethodrA   rR   propertyrM   r[   r   r*   r   r   r   r;   r=   r"   r   r   rL   rL      s    :U : #N6e 6 6 6 e   s   $(!%,0.2
 +
 
 	

 x 
 
 ()
 l+
 

*4 4r   rL   c                       e Zd ZdZeeeefdededededef
dZ	 	 	 	 dd	ed
   de	de
dee   dedeed      ded   ddfdZd Zy)ParentBasedaE  
    If a parent is set, applies the respective delegate sampler.
    Otherwise, uses the root provided at initialization to make a
    decision.

    Args:
        root: Sampler called for spans with no parent (root spans).
        remote_parent_sampled: Sampler called for a remote sampled parent.
        remote_parent_not_sampled: Sampler called for a remote parent that is
            not sampled.
        local_parent_sampled: Sampler called for a local sampled parent.
        local_parent_not_sampled: Sampler called for a local parent that is
            not sampled.
    rootremote_parent_sampledremote_parent_not_sampledlocal_parent_sampledlocal_parent_not_sampledc                 J    || _         || _        || _        || _        || _        y r   )_root_remote_parent_sampled_remote_parent_not_sampled_local_parent_sampled_local_parent_not_sampled)r   rd   re   rf   rg   rh   s         r   r0   zParentBased.__init__E  s+     
&;#*C'%9")A&r   Nr4   r   r5   r6   r7   r,   r8   r
   r.   r   r%   r$   c                 l   t        |      j                         }| j                  }	|w|j                  rk|j                  r0|j
                  j                  r| j                  }	n<| j                  }	n/|j
                  j                  r| j                  }	n| j                  }	|	j                  ||||||      S )N)r4   r5   r6   r7   r,   r8   )r   get_span_contextrj   is_valid	is_remotetrace_flagssampledrk   rl   rm   rn   r;   )
r   r4   r5   r6   r7   r,   r8   r.   parent_span_contextsamplers
             r   r;   zParentBased.should_sampleS  s     /



 	 ***/B/K/K",,&22::"99G"==G&22::"88G"<<G$$)! % 
 	
r   c                    d| j                   j                          d| j                  j                          d| j                  j                          d| j                  j                          d| j
                  j                          dS )NzParentBased{root:z,remoteParentSampled:z,remoteParentNotSampled:z,localParentSampled:z,localParentNotSampled:r^   )rj   r=   rk   rl   rm   rn   r   s    r   r=   zParentBased.get_descriptionx  s    #DJJ$>$>$@#AAVW[WrWr  XC  XC  XE  WF  F^  _c  _~  _~  _N  _N  _P  ^Q  Qe  fj  f@  f@  fP  fP  fR  eS  Sj  ko  kI  kI  kY  kY  k[  j\  \^  _  	_r   r>   )r   r   r    r1   	ALWAYS_ON
ALWAYS_OFFr3   r0   r   rA   r*   r   r   r   r;   r=   r"   r   r   rc   rc   5  s    $ *3-7(1,6BB  'B $+	B
 &B #*B& $(!%,0.2#
 +#
 #
 	#

 x #
 #
 ()#
 l+#
 
#
J_r   rc   c                   (     e Zd ZdZdef fdZ xZS )ParentBasedTraceIdRatioz
    Sampler that respects its parent span's sampling decision, but otherwise
    samples probabilistically based on `rate`.
    rM   c                 >    t        |      }t        | 	  |       y )N)rM   )rd   )rL   superr0   )r   rM   rd   	__class__s      r   r0   z ParentBasedTraceIdRatio.__init__  s     d+d#r   )r   r   r    r1   r_   r0   __classcell__r~   s   @r   r{   r{     s    
$U $ $r   r{   c                        e Zd Z fdZ xZS )
_AlwaysOffc                 @    t         |   t        j                         y r   )r}   r0   r   r!   r   _r~   s     r   r0   z_AlwaysOff.__init__  s    'r   r   r   r    r0   r   r   s   @r   r   r     s    ( (r   r   c                        e Zd Z fdZ xZS )	_AlwaysOnc                 @    t         |   t        j                         y r   )r}   r0   r   r   r   s     r   r0   z_AlwaysOn.__init__  s    334r   r   r   s   @r   r   r     s    5 5r   r   c                        e Zd Z fdZ xZS )_ParentBasedAlwaysOffc                 ,    t         |   t               y r   )r}   r0   ry   r   s     r   r0   z_ParentBasedAlwaysOff.__init__  s    $r   r   r   s   @r   r   r     s    % %r   r   c                        e Zd Z fdZ xZS )_ParentBasedAlwaysOnc                 ,    t         |   t               y r   )r}   r0   rx   r   s     r   r0   z_ParentBasedAlwaysOn.__init__  s    #r   r   r   s   @r   r   r     s    $ $r   r   )	always_on
always_offparentbased_always_onparentbased_always_offtraceidratioparentbased_traceidratior%   c                  f   t        j                  t        d      j                         } | t        vrt
        j                  d|        d} | dv r1	 t        t        j                  t                    }t	        |    |      S t        |    S # t        t        f$ r t
        j                  d       d}Y ?w xY w)Nr   zCouldn't recognize sampler %s.)r   r   z.Could not convert TRACES_SAMPLER_ARG to float.rO   )osgetenvr   lower_KNOWN_SAMPLERS_loggerwarningr_   r	   rP   	TypeError)trace_samplerrM   s     r   _get_from_env_or_defaultr     s    II4eg  O+8-H/DD	#:;<D }-d33=)) I& 	OOLMD	s   "B &B0/B0r4   r   c                 j    t        |       j                         }||j                  sy |j                  S r   )r   rp   rq   r.   )r4   ru   s     r   rG   rG     s6     +>:KKM"*=*F*F***r   )0r1   r?   enumr   loggingr   typesr   typingr   r   opentelemetry.contextr   'opentelemetry.sdk.environment_variablesr   r	   opentelemetry.tracer
   r   r   opentelemetry.trace.spanr   opentelemetry.util.typesr   r   r   Enumr   r$   ABCr3   rC   r!   ry   r   rx   rL   rc   DEFAULT_OFF
DEFAULT_ONr{   r   r   r   r   r   r   rG   r"   r   r   <module>r      s[  vp   	  " % * A @ / /
H
2tyy 2' '8cgg &!G !< 8==)
 Z(445	 [44 44nD_' D_N *% ]#
 ^$k $( (
5 5
%K %
$; $ ')% 7*' *&+W%+l+r   