
    &`i                     x   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Zd dlmZm	Z	 d dl
mZmZmZmZmZmZ d dlmZ d dlmZ d dlmZmZ d dlmZmZmZ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(m)Z*m+Z, d dl-m.Z.m/Z/m0Z0m1Z2 d dl3Z3d dl4m5Z5 d dl6m7Z7 d dl8m9Z9m:Z: d dl;m<Z< d dl=m1Z1 d dl>m?Z?  ej@        eA          ZBdZCdZD ejE        d          ZF G d de#          ZG e	dg d          ZHde1fdZI G d d          ZJ G d d           ZK G d! d"          ZL G d# d$          ZM G d% d&ejN                  ZOdS )'    N)defaultdict
namedtuple)AnyDictListSetTupleUnion)MetricDescriptorType)ValueDouble)aggregationmeasure)CountAggregationDataDistributionAggregationDataLastValueAggregationDataSumAggregationData)StatsExporter)StatsRecorder)View)ViewManager)tag_keytag_map	tag_value)CounterMetricFamilyGaugeMetricFamilyHistogramMetricFamilyMetricbuild_address)env_bool)WORKER_ID_TAG_KEYMetricCardinality)	GcsClient)r   )_is_invalid_metric_nameRAY_WORKER_TIMEOUT_SCOREz[^a-zA-Z0-9]c                       e Zd ZdZdee         fdZed             Zed             Z	ed             Z
ed             ZdS )	GaugezGauge representation of opencensus view.

    This class is used to collect process metrics from the reporter agent.
    Cpp metrics should be collected in a different way.
    tagsc                    t          |          rt          d| d          t          j        |||          | _        || _        d |D             }t          |||| j        t          j	                              | _
        d S )NzInvalid metric name: z. Metric will be discarded and data will not be collected or published. Metric names can only contain letters, numbers, _, and :. Metric names cannot start with numbers.c                 6    g | ]}t          j        |          S  )tag_key_moduleTagKey).0tags     n/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/_private/metrics_agent.py
<listcomp>z"Gauge.__init__.<locals>.<listcomp>J   s#    ;;;s%c**;;;    )r$   
ValueErrormeasure_module
MeasureInt_measure_descriptionr   r   r   LastValueAggregation_view)selfnamedescriptionunitr)   s        r1   __init__zGauge.__init__@   s    "4(( 	: : : :   '1$TJJ';;d;;;+tT\;3S3U3U
 



r3   c                     | j         S N)r7   r;   s    r1   r   zGauge.measureO   s
    }r3   c                     | j         S rA   )r:   rB   s    r1   viewz
Gauge.viewS   
    zr3   c                     | j         j        S rA   )r   r<   rB   s    r1   r<   z
Gauge.nameW   s    |  r3   c                     | j         S rA   )r8   rB   s    r1   r=   zGauge.description[   s      r3   N)__name__
__module____qualname____doc__r   strr?   propertyr   rD   r<   r=   r,   r3   r1   r(   r(   9   s         
d3i 
 
 
 
   X   X ! ! X! ! ! X! ! !r3   r(   Record)gaugevaluer)   metricc                 p   | j         j                            d          sdS t                              d| j         j                  | j         _        | j        D ]]}|j        D ]S}|                    d          r<|j        }|j	        j
        j        }t          |          dk    r|d         dk    rd|d<   T^dS )a  
    Fix the inbound `opencensus.proto.metrics.v1.Metric` protos to make it acceptable
    by opencensus.stats.DistributionAggregationData.

    - metric name: gRPC OpenCensus metrics have names with slashes and dots, e.g.
    `grpc.io/client/server_latency`[1]. However Prometheus metric names only take
    alphanums,underscores and colons[2]. We santinize the name by replacing non-alphanum
    chars to underscore, like the official opencensus prometheus exporter[3].
    - distribution bucket bounds: The Metric proto asks distribution bucket bounds to
    be > 0 [4]. However, gRPC OpenCensus metrics have their first bucket bound == 0 [1].
    This makes the `DistributionAggregationData` constructor to raise Exceptions. This
    applies to all bytes and milliseconds (latencies). The fix: we update the initial 0
    bounds to be 0.000_000_1. This will not affect the precision of the metrics, since
    we don't expect any less-than-1 bytes, or less-than-1-nanosecond times.

    [1] https://github.com/census-instrumentation/opencensus-specs/blob/master/stats/gRPC.md#units  # noqa: E501
    [2] https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels
    [3] https://github.com/census-instrumentation/opencensus-cpp/blob/50eb5de762e5f87e206c011a4f930adb1a1775b1/opencensus/exporters/stats/prometheus/internal/prometheus_utils.cc#L39 # noqa: E501
    [4] https://github.com/census-instrumentation/opencensus-proto/blob/master/src/opencensus/proto/metrics/v1/metrics.proto#L218 # noqa: E501
    zgrpc.io/N_distribution_valuer   gHz>)metric_descriptorr<   
startswithRE_NON_ALPHANUMSsub
timeseriespointsHasFieldrT   bucket_optionsexplicitboundslen)rQ   seriespoint
dist_valuebucket_boundss        r1   fix_grpc_metricrd   c   s    , #(33J?? $4$8$8V%*% %F! # 3 3] 	3 	3E~~233 3"5
 * 9 B I}%%))mA.>!.C.C'2M!$	33 3r3   c            	           e Zd Zdedededee         fdZed             Zed             Zed             Z	ed	             Z
ed
             Zd ZdedefdZdefdZdS )OpencensusProxyMetricr<   descr>   
label_keysc                 L    || _         || _        || _        || _        i | _        dS )z>Represents the OpenCensus metrics that will be proxy exported.N)_name_desc_unit_label_keys_data)r;   r<   rg   r>   rh   s        r1   r?   zOpencensusProxyMetric.__init__   s,    


% 


r3   c                     | j         S rA   )rj   rB   s    r1   r<   zOpencensusProxyMetric.name   rE   r3   c                     | j         S rA   )rk   rB   s    r1   rg   zOpencensusProxyMetric.desc   rE   r3   c                     | j         S rA   )rl   rB   s    r1   r>   zOpencensusProxyMetric.unit   rE   r3   c                     | j         S rA   )rm   rB   s    r1   rh   z OpencensusProxyMetric.label_keys   s    r3   c                     | j         S rA   rn   rB   s    r1   datazOpencensusProxyMetric.data   rE   r3   c                     t          | j                  dk    oEt          t          t	          | j                                                            t                    S )z8Check if the metric is a distribution aggreation metric.r   )r_   rn   
isinstancenextitervaluesr   rB   s    r1    is_distribution_aggregation_dataz6OpencensusProxyMetric.is_distribution_aggregation_data   sL    4:" 
zdj''))**++-H(
 (
 	
r3   label_valuesru   c                     || j         |<   dS )zAdd the data to the metric.

        Args:
            label_values: The label values of the metric.
            data: The data to be added.
        Nrt   )r;   r|   ru   s      r1   add_datazOpencensusProxyMetric.add_data   s     $(
<   r3   rQ   c           	         |j         }t          |          dk    rdS |D ]M}t          d |j        D                       }|j        D ]#}|j        j        t          j        k    rt          |j
                  }n|j        j        t          j        k    rt          t          |j                  }n|j        j        t          j        k    rt!          t          |j                  }n}|j        j        t          j        k    rT|j        }d |j        D             }|j        j        j        }	t/          |j        |j        z  |j        |j        ||	          }nt7          d          || j        |<   %OdS )zzParse the Opencensus Protobuf and store the data.

        The data can be accessed via `data` API once recorded.
        r   Nc              3   $   K   | ]}|j         V  d S rA   rP   )r/   vals     r1   	<genexpr>z/OpencensusProxyMetric.record.<locals>.<genexpr>   s$      DD39DDDDDDr3   c                     g | ]	}|j         
S r,   )count)r/   buckets     r1   r2   z0OpencensusProxyMetric.record.<locals>.<listcomp>   s    (W(W(W&(W(W(Wr3   zSummary is not supported)rY   r_   tupler|   rZ   rU   typer   CUMULATIVE_INT64r   int64_valueCUMULATIVE_DOUBLEr   r   double_valueGAUGE_DOUBLEr   CUMULATIVE_DISTRIBUTIONrT   bucketsr\   r]   r^   r   sumr   sum_of_squared_deviationr4   rn   )
r;   rQ   rY   r`   labelsra   ru   rb   counts_per_bucketrc   s
             r1   recordzOpencensusProxyMetric.record   s   
 &
z??aF ! !	* !	*FDD0CDDDDDF   * *,1+<= = 00ABBDD,1+=> > .k5;MNNDD-26J6WWW3KASTTDD,1+CD D "'!9J(W(WJDV(W(W(W%$.$=$F$MM6")99"(";)% DD %%?@@@%)
6"";*	!	* !	*r3   N)rH   rI   rJ   rL   r   r?   rM   r<   rg   r>   rh   ru   r{   r	   r   r~   r   r   r,   r3   r1   rf   rf      s       	S 	 	3 	DI 	 	 	 	   X   X   X     X    X
 
 
(U (# ( ( ( (,*V ,* ,* ,* ,* ,* ,*r3   rf   c                   t    e Zd ZdefdZedeeef         fd            Zed             Z	de
e         fdZdS )		Componentidc                 R    || _         t          j                    | _        i | _        dS )zyRepresent a component that requests to proxy export metrics

        Args:
            id: Id of this component.
        N)r   time	monotonic_last_reported_time_metrics)r;   r   s     r1   r?   zComponent.__init__   s*      $(>#3#3  r3   returnc                     | j         S )zAReturn the metrics requested to proxy export from this component.)r   rB   s    r1   metricszComponent.metrics   s     }r3   c                     | j         S rA   )r   rB   s    r1   last_reported_timezComponent.last_reported_time   s    ''r3   r   c                 6   t          j                    | _        |D ]}}t          |           |j        }|j        }d |j        D             }|| j        vr$t          ||j	        |j
        |          | j        |<   | j        |                             |           ~dS )zParse the Opencensus protobuf and store metrics.

        Metrics can be accessed via `metrics` API for proxy export.

        Args:
            metrics: A list of Opencensus protobuf for proxy export.
        c                     g | ]	}|j         
S r,   )key)r/   	label_keys     r1   r2   z$Component.record.<locals>.<listcomp>  s    OOOI)-OOOr3   N)r   r   r   rd   rU   r<   rh   r   rf   r=   r>   r   )r;   r   rQ   
descriptorr<   rh   s         r1   r   zComponent.record   s     $(>#3#3  
	/ 
	/FF###1J?DOO9NOOOJ4=((&;*0*/:' 'd# M$&&v....
	/ 
	/r3   N)rH   rI   rJ   rL   r?   rM   r   rf   r   r   r   r   r   r,   r3   r1   r   r      s        3     c#889    X ( ( X(/d6l / / / / / /r3   r   c                      e Zd ZddedefdZddee         defdZd	 Z	d
ededee         dede
ej                 dedeeee         f         ddfdZdeeeeef                  deeeef         fdZdee         dee         fdZd ZdS )OpenCensusProxyCollector<   	namespacecomponent_timeout_sc                     t          j                    | _        || _        || _        i | _        t          dd          | _        dS )a)  Prometheus collector implementation for opencensus proxy export.

        Prometheus collector requires to implement `collect` which is
        invoked whenever Prometheus queries the endpoint.

        The class is thread-safe.

        Args:
            namespace: Prometheus namespace.
        RAY_EXPORT_COUNTER_AS_GAUGETN)	threadingLock_components_lock_component_timeout_s
_namespace_componentsr    _export_counter_as_gauge)r;   r   r   s      r1   r?   z!OpenCensusProxyCollector.__init__  sK     !* 0 0 %8!#  )11NPT(U(U%%%r3   Nr   worker_id_hexc                     |st           n|}| j        5  || j        vrt          |          | j        |<   | j        |                             |           ddd           dS # 1 swxY w Y   dS )a.  Record the metrics reported from the component that reports it.

        Args:
            metrics: A list of opencensus protobuf to proxy export metrics.
            worker_id_hex: A worker id that reports these metrics.
                If None, it means they are reported from Raylet or GCS.
        N)GLOBAL_COMPONENT_KEYr   r   r   r   )r;   r   r   r   s       r1   r   zOpenCensusProxyCollector.record5  s     +8J""]" 	2 	2$***(1# %S!((111	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2s   AA!!A%(A%c                    | j         5  g }g }| j                                        D ]n\  }}t          j                    |j        z
  }|| j        k    rC|                    |           t          	                    d
                    ||                     o|D ]/}|                    | j                            |                     0|cddd           S # 1 swxY w Y   dS )zClean up stale components.

        Stale means the component is dead or unresponsive.

        Stale components won't be reported to Prometheus anymore.
        zSMetrics from a worker ({}) is cleaned up due to timeout. Time since last report {}sN)r   r   itemsr   r   r   r   appendloggerinfoformatpop)r;   stale_componentsstale_component_idsr   	componentelapseds         r1   clean_stale_componentsz/OpenCensusProxyCollector.clean_stale_componentsC  s?    " 	$ 	$!"$!%!1!7!7!9!9  I.**Y-IIT666'..r222KK>>DfR>Q>Q   * B B ''(8(<(<R(@(@AAAA#	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$s   C CCCmetric_namemetric_descriptionrh   metric_unitsr|   agg_datametrics_mapr   c                    | j                                         sJ | j         d| }t          |          t          |          k    sJ ||f            d |D             }t	          |t
                    rV|                    |          }|st          ||||          }	|	g}|||<   |d                             ||j	                   dS t	          |t                    r|                    |          }|st          |||          }	|	g}|||<   |d                             ||j                   | j        sn|                    d          rnwt          |          d	k    r-t          |d
| d| |          }	|                    |	           t          |          dk    sJ |d	                             ||j                   dS t	          |t                     r|j        t%          |j                  k    sJ g }
d}t'          |j                  D ];\  }}||j        |         z  }t+          |          |g}|
                    |           <|
                    d|j	        g           |                    |          }|st-          |||          }	|	g}|||<   |d                             ||
|j                   dS t	          |t0                    rU|                    |          }|st          |||          }	|	g}|||<   |d                             ||j                   dS t5          dt7          |                     )a  to_metric translate the data that OpenCensus create
        to Prometheus format, using Prometheus Metric object.

        This method is from Opencensus Prometheus Exporter.

        Args:
            metric_name: Name of the metric.
            metric_description: Description of the metric.
            label_keys: The fixed label keys of the metric.
            metric_units: Units of the metric.
            label_values: The values of `label_keys`.
            agg_data: `opencensus.stats.aggregation_data.AggregationData` object.
                Aggregated data that needs to be converted as Prometheus samples
            metrics_map: The converted metric is added to this map.

        rS   c                     g | ]}|r|nd 	S ) r,   )r/   tvs     r1   r2   zBOpenCensusProxyCollector.to_prometheus_metrics.<locals>.<listcomp>z  s!    @@@Rb(b@@@r3   )r<   documentationr>   r   r   )r   rP   N)r<   r   r   _total   z(DEPRECATED, use z_total metric instead)    z+Inf)r   r   	sum_valuezunsupported aggregation type )r   lockedr   r_   rw   r   getr   
add_metric
count_datar   sum_datar   endswithr   r   r   r^   sorted	enumerater   rL   r   r   r   rP   r4   r   )r;   r   r   rh   r   r|   r   r   r   rQ   r   	cum_countiiboundr   s                  r1   to_prometheus_metricsz.OpenCensusProxyCollector.to_prometheus_metricsZ  s	   4 $++-----88;88<  C
OO333lJ5O333 A@<@@@h 455 	!ook22G 3,$"4%%	   "(+2K(AJ!!X=P!QQQFh 233 \	O "ook22G 3,$"4%  
 "(+2K(AJ!!X=N!OOO0 T%%h// T w<<1$$.(4 4 414 4  *  F NN6***7||q((((
%%\AR%SSSF"=>> .	O?fX_&=&===== GI&x77 ' '	EX7;;	e**i0v&&&& NNFH$78999!ook22G 3.$"4%  
 "(+2K(AJ!!#", "   
 F":;; 	O!ook22G 3*$"4%  
 "(+2K(AJ!!X^!LLLF MT(^^MMNNNr3   datasc                 ,   t          |          dk    sJ |d         }t          |t                    r,t          t          t	          d |D                                 S t          |t
                    r&t          t	          d |D                                 S t          |t                    r,t          t          t	          d |D                                 S t          dt          |           dt
           dt           dt           d| d	          )
Nr   c                     g | ]	}|j         
S r,   r   r/   ru   s     r1   r2   zCOpenCensusProxyCollector._aggregate_metric_data.<locals>.<listcomp>  s    !?!?!?$*!?!?!?r3   c                     g | ]	}|j         
S r,   )r   r   s     r1   r2   zCOpenCensusProxyCollector._aggregate_metric_data.<locals>.<listcomp>  s    ,O,O,OT_,O,O,Or3   c                     g | ]	}|j         
S r,   )r   r   s     r1   r2   zCOpenCensusProxyCollector._aggregate_metric_data.<locals>.<listcomp>  s    !B!B!BD$-!B!B!Br3   zUnsupported aggregation type z. Supported types are z, z.Got .)	r_   rw   r   r   r   r   r   r4   r   )r;   r   samples      r1   _aggregate_metric_dataz/OpenCensusProxyCollector._aggregate_metric_data  sC    5zzA~~~~qf677 	+S!?!?!?!?!?@@   f233 	R',O,O,O,O,O(P(PQQQf011 	%S!B!BE!B!B!BCC   DLL  # '? CU    
 
 	
r3   per_worker_metricsc           	         t          t          |          d          }|rt          |j        vr|S |j                            t                    }t          t                    }|D ]R}|j                                        D ]6\  }}||d|         ||dz   d         z            	                    |           7St          |j        |j        |j        |j        d|         |j        |dz   d         z             }|                                D ].\  }}|                    ||                     |                     /|gS )a  Collect per-worker metrics, aggregate them into per-node metrics and convert
        them to Prometheus format.

        Args:
            per_worker_metrics: A list of per-worker metrics for the same metric name.
        Returns:
            A list of per-node metrics for the same metric name, with the high
            cardinality labels removed and the values aggregated.
        Nr   )r<   rg   r>   rh   )rx   ry   r!   rh   indexr   listru   r   r   rf   r<   rg   r>   r~   r   )	r;   r   rQ   worker_id_label_indexlabel_value_to_datar|   ru   aggregated_metricr   s	            r1   '_aggregate_with_recommended_cardinalityz@OpenCensusProxyCollector._aggregate_with_recommended_cardinality  s    d-..55 	&*&2CCC%% & 1 7 78I J J  	 ) 	 	F&,k&7&7&9&9  "d# !7"7!78"#81#<#>#>?@ &,,,, 2()?*?)?@ 5 9 ; ;<=
 
 
 $7#<#<#>#> 	 	L%&&++E22   
 """r3   c              #   (  K   | j         5  g }t          t                    }t          j                    }| j                                        D ]x}|j                                        D ]\}|t          j        k    r5|	                                s!||j
                                     |           G|                    |           ]y|                                D ]*}|                    |                     |                     +i }|D ]P}|j                                        D ]4\  }}	|                     |j
        |j        |j        |j        ||	|           5Q	 ddd           n# 1 swxY w Y   |                                D ]}
|
D ]}|V  dS )a,  Collect fetches the statistics from OpenCensus
        and delivers them as Prometheus Metrics.
        Collect is invoked every time a prometheus.Gatherer is run
        for example when the HTTP endpoint is invoked by Prometheus.

        This method is required as a Prometheus Collector.
        N)r   r   r   r"   get_cardinality_levelr   rz   r   RECOMMENDEDr{   r<   r   extendr   ru   r   r   rg   rh   r>   )r;   open_cencus_metricsto_lower_cardinalitycardinality_levelr   rQ   r   prometheus_metrics_mapr|   ru   r   s              r1   collectz OpenCensusProxyCollector.collect9  sM      " ,	 ,	
 @B LWL L  !2 G I I!-4466 ; ;	'/6688 ; ;F)->-JJJ & G G I I K -V[9@@HHHH+226::::; ';&A&A&C&C  "#**@@*     &("- 
 
*0+*;*;*=*= 	 	&L$..)$.   	
E,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	\ .4466 	 	G!  	 	s   EE''E+.E+)r   rA   )rH   rI   rJ   rL   intr?   r   r   r   r   r	   tag_value_moduleTagValuer   r   PrometheusMetricr   r
   r   r   r   r   rf   r   r   r,   r3   r1   r   r     s       V V# VC V V V V>2 2d6l 23 2 2 2 2$ $ $.LOLO  LO I	LO
 LO ,56LO LO #t$4556LO 
LO LO LO LO\
*,@BTTU


 
')=?QQ	R
 
 
 
45# !675# 
#	$5# 5# 5# 5#n8 8 8 8 8r3   r   c                       e Zd Z	 ddededefdZddee         fdZ	de
d	ed
efdZddee         defdZddee         defdZd ZdS )MetricsAgentNview_managerstats_recorderstats_exporterc           	      z   t          j                    | _        || _        || _        || _        d| _        | j        d| _        nd| j                            |           t          | j        j	        j
        t          t          j        t          d                              | _        t                      | _        dS )a+  A class to record and export metrics.

        The class exports metrics in 2 different ways.
        - Directly record and export metrics using OpenCensus.
        - Proxy metrics from other core components
            (e.g., raylet, GCS, core workers).

        This class is thread-safe.
        Nx   )r   )r   r   _lockr   r   r   proxy_exporter_collectorregister_exporterr   optionsr   r   osgetenvr%   set_registered_views)r;   r   r   r   s       r1   r?   zMetricsAgent.__init__u  s    " ^%%
 ) -, )-%& !%D//???,D#+5$'	2F(L(L$M$M- - -D) ,/55r3   recordsc                 p   |pi }| j         5  | j        s	 ddd           dS |D ]x}|j        }|j        }|j        }	 |                     ||i ||           4# t          $ r8}t                              d|j	         d| d|d|d|
           Y d}~qd}~ww xY w	 ddd           dS # 1 swxY w Y   dS )z7Directly record and export stats from the same process.NzFailed to record metric z with value z with tags z and global tags 	 due to: )
r  r   rO   rP   r)   _record_gauge	Exceptionr   errorr<   )r;   r  global_tagsr   rO   rP   r)   es           r1   record_and_exportzMetricsAgent.record_and_export  s   !'RZ 	 	$ 	 	 	 	 	 	 	 	 " 	 	{&&ue5L5L5LMMMM    LL T5:  T  T5  T  T]a  T  T  wB  T  T  OP  T  T       			 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s?   	B+B+AB+
B".BB+BB++B/2B/rO   rP   r)   c                    |j         | j        vr>| j                            |j                   | j                            |j                    | j                                        }t          j	                    }|
                                D ]\  }}	 t          j        |          }n<# t          $ r/}	t                              d| d|j          d|	           |	d }	~	ww xY w	 t!          j        |          }
n?# t          $ r2}	t                              d| d| d|j          d|	           |	d }	~	ww xY w|                    ||
           |                    |j        |           |                    |           d S )NzFailed to create tag key z for metric r  zFailed to create tag value z	 for key )r<   r
  r   register_viewrD   addr   new_measurement_maptag_map_moduleTagMapr   r-   r.   r4   r   r  r   r   insertmeasure_float_putr   r   )r;   rO   rP   r)   measurement_mapr   r   tag_valr   r  r   s              r1   r  zMetricsAgent._record_gauge  s   :T333++EJ777"&&uz222-AACC ')) JJLL 	/ 	/LC(/44   [[[[[VW[[   	
,5g>>		   o'ooCooUZU_oojkoo   	
 NN7I....))%-???w'''''s0   B((
C!2*CC!%C::
D6-D11D6r   r   c                     | j         5  | j        s	 ddd           dS 	 ddd           n# 1 swxY w Y   |                     ||           dS )a{  Proxy export metrics specified by a Opencensus Protobuf.

        This API is used to export metrics emitted from
        core components.

        Args:
            metrics: A list of protobuf Metric defined from OpenCensus.
            worker_id_hex: The worker ID it proxies metrics export. None
                if the metric is not from a worker (i.e., raylet, GCS).
        N)r  r   _proxy_export_metricsr;   r   r   s      r1   proxy_export_metricsz!MetricsAgent.proxy_export_metrics  s     Z 	 	$ 	 	 	 	 	 	 	 		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	""7M:::::   	+//c                 <    | j                             ||           d S rA   )r  r   r   s      r1   r  z"MetricsAgent._proxy_export_metrics  s!    %,,WmDDDDDr3   c                     | j         5  | j        s	 ddd           dS 	 ddd           n# 1 swxY w Y   | j                                         dS )zClean dead worker's metrics.

        Worker metrics are cleaned up and won't be exported once
        it is considered as dead.

        This method has to be periodically called by a caller.
        N)r  r   r  r   rB   s    r1   clean_all_dead_worker_metricsz*MetricsAgent.clean_all_dead_worker_metrics  s     Z 	 	$ 	 	 	 	 	 	 	 		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	%<<>>>>>r"  rA   )rH   rI   rJ   r   r   r   r?   r   rN   r  r(   floatdictr  r   rL   r!  r  r%  r,   r3   r1   r   r   t  s       
 )-	/1 /1!/1 &/1 &	/1 /1 /1 /1b f    $(5 ( (d ( ( ( (4; ;DL ; ; ; ; ;"E ET&\ E# E E E E? ? ? ? ?r3   r   c                   F     e Zd ZdZ fdZd Zd Zd Zd Zd Z	d Z
 xZS )	 PrometheusServiceDiscoveryWriteraF  A class to support Prometheus service discovery.

    It supports file-based service discovery. Checkout
    https://prometheus.io/docs/guides/file-sd/ for more details.

    Args:
        gcs_address: Gcs address for this cluster.
        temp_dir: Temporary directory used by
            Ray to store logs and metadata.
    c                 R   t           j        j                            |d dd          }|| _        t           j        j        j                            |           || _        d| _	        g | _
        t          j                    | _        t                                                       d S )NTF)allow_cluster_id_nilfetch_cluster_id_if_nil   )ray_rayletGcsClientOptionscreategcs_address_privatestate_initialize_global_statetemp_dir&default_service_discovery_flush_period latest_service_discovery_contentr   RLock_content_locksuperr?   )r;   r2  r6  gcs_client_options	__class__s       r1   r?   z)PrometheusServiceDiscoveryWriter.__init__  s     [9@@DRW A 
 
 ' 99:LMMM 673 13-&_..r3   c                 R    | j         5  | j        cddd           S # 1 swxY w Y   dS )z3Return the latest stored service discovery content.N)r:  r8  rB   s    r1   $get_latest_service_discovery_contentzEPrometheusServiceDiscoveryWriter.get_latest_service_discovery_content  su     	9 	98	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9s     c                    t          j                    }d |D             }t          | j                  }|                    dd          }|r(|                    |                    d                     |                    dd          }|r(|                    |                    d                     ddi|d	g}| j        5  || _        ddd           n# 1 swxY w Y   t          j
        |          S )
z4Return the content for Prometheus service discovery.c                 Z    g | ](}|d          du t          |d         |d                   )S )aliveTNodeManagerAddressMetricsExportPortr   )r/   nodes     r1   r2   zOPrometheusServiceDiscoveryWriter.get_file_discovery_content.<locals>.<listcomp>  sG     $
 $
 $
G}$$ $34d;N6OPP$$$r3   )addresss   AutoscalerMetricsAddressNzutf-8s   DashboardMetricsAddressjobr.  )r   targets)r.  nodesr#   r2  internal_kv_getr   decoder:  r8  jsondumps)r;   rI  metrics_export_addresses
gcs_clientautoscaler_addrdashboard_addrcontents          r1   get_file_discovery_contentz;PrometheusServiceDiscoveryWriter.get_file_discovery_content  sP   	$
 $
$
 $
 $
 
 t'7888
$445PRVWW 	M$++O,B,B7,K,KLLL#334NPTUU 	L$++N,A,A',J,JKKK$en9QRRS 	< 	<4;D1	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	<z'"""s   CCCc                    |                                  }t          |d          5 }|                    |                                            d d d            n# 1 swxY w Y   t	          j        ||                                            d S )Nw)get_temp_file_nameopenwriterS  r  replaceget_target_file_name)r;   temp_file_name	json_files      r1   rX  z&PrometheusServiceDiscoveryWriter.write*  s     0022.#&& 	?)OOD;;==>>>	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	
>4#<#<#>#>?????s   (AA Ac                 t    t           j                            | j        t          j        j        j                  S rA   )r  pathjoinr6  r.  r3  ray_constants!PROMETHEUS_SERVICE_DISCOVERY_FILErB   s    r1   rZ  z5PrometheusServiceDiscoveryWriter.get_target_file_name7  s)    w||M3<5W
 
 	
r3   c                     t           j                            | j        d                    dt
          j        j        j                            S )Nz{}_{}tmp)	r  r^  r_  r6  r   r.  r3  r`  ra  rB   s    r1   rV  z3PrometheusServiceDiscoveryWriter.get_temp_file_name<  s=    w||MNNs|1S 
 
 	
r3   c                    	 	 |                                   n# t          $ r}t                              d                    |                                                      t                              t          j                               t                              d|            Y d }~nd }~ww xY wt          j	        | j
                   )NTz,Writing a service discovery file, {},failed.zError message: )rX  r  r   warningr   rZ  	traceback
format_excr   sleepr7  )r;   r  s     r1   runz$PrometheusServiceDiscoveryWriter.runD  s    	D6

 6 6 6$fT%>%>%@%@AA   y355666444555555556 JtBCCC	Ds    
B3BB..B3)rH   rI   rJ   rK   r?   r?  rS  rX  rZ  rV  ri  __classcell__)r=  s   @r1   r)  r)    s        	 	     9 9 9
# # #(@ @ @
 
 


 
 
D D D D D D Dr3   r)  )PrL  loggingr  rer   r   rf  collectionsr   r   typingr   r   r   r   r	   r
   +opencensus.metrics.export.metric_descriptorr   opencensus.metrics.export.valuer   opencensus.statsr   r   r5   !opencensus.stats.aggregation_datar   r   r   r   opencensus.stats.base_exporterr   opencensus.stats.stats_recorderr   opencensus.stats.viewr   opencensus.stats.view_managerr   opencensus.tagsr   r-   r   r  r   r   prometheus_client.corer   r   r   r   r   r.  ray._common.network_utilsr   ray._private.ray_constantsr    )ray._private.telemetry.metric_cardinalityr!   r"   ray._rayletr#   ray.core.generated.metrics_pb2ray.util.metricsr$   	getLoggerrH   r   r%   r   compilerW   r(   rN   rd   rf   r   r   r   Threadr)  r,   r3   r1   <module>r     s     				 				          / / / / / / / / 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 L L L L L L 7 7 7 7 7 7 C C C C C C C C            9 8 8 8 8 8 9 9 9 9 9 9 & & & & & & 5 5 5 5 5 5         
            


 3 3 3 3 3 3 / / / / / /        " ! ! ! ! ! 1 1 1 1 1 1 4 4 4 4 4 4		8	$	$
 .  2:o.. $! $! $! $! $!D $! $! $!N 
H888	9	9#3F #3 #3 #3 #3L[* [* [* [* [* [* [* [*|+/ +/ +/ +/ +/ +/ +/ +/\\ \ \ \ \ \ \ \~
~? ~? ~? ~? ~? ~? ~? ~?B[D [D [D [D [Dy'7 [D [D [D [D [Dr3   