o
    $i4                     @   s   d dl Z d dl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mZmZmZ e eZG dd deZG dd	 d	eZG d
d dejZdd Zdd Zdd ZedejejB Zdd ZdS )    N)sync)aggregation_database_exporter)start_http_server)REGISTRYCounterMetricFamilyGaugeMetricFamilyHistogramMetricFamilyUnknownMetricFamilyc                   @   sR   e Zd ZdZdddefddZedd Zedd	 Zed
d Z	edd Z
dS )Optionsa  Options contains options for configuring the exporter.
    The address can be empty as the prometheus client will
    assume it's localhost
    :type namespace: str
    :param namespace: The prometheus namespace to be used. Defaults to ''.
    :type port: int
    :param port: The Prometheus port to be used. Defaults to 8000.
    :type address: str
    :param address: The Prometheus address to be used. Defaults to ''.
    :type registry: registry
    :param registry: The Prometheus address to be used. Defaults to ''.
    :type registry: :class:`~prometheus_client.core.CollectorRegistry`
    :param registry: A Prometheus collector registry instance.
     i@  c                 C   s    || _ || _t|| _|| _d S N)
_namespace	_registryint_port_address)self	namespaceportaddressregistry r   ]/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/ray/_private/prometheus_exporter.py__init__'   s   

zOptions.__init__c                 C      | j S z&Prometheus Collector Registry instancer   r   r   r   r   r   -      zOptions.registryc                 C   r   )z Prefix to be used with view name)r   r   r   r   r   r   2   r   zOptions.namespacec                 C   r   )zPort number to listen)r   r   r   r   r   r   7   r   zOptions.portc                 C   r   )z'Endpoint address (default is localhost))r   r   r   r   r   r   <   r   zOptions.addressN)__name__
__module____qualname____doc__r   r   propertyr   r   r   r   r   r   r   r   r      s    


r   c                   @   sp   e Zd ZdZe dfddZedd Zedd Zed	d
 Z	edd Z
dd Zdd Zdd Zdd ZdS )	Collectorz4Collector represents the Prometheus Collector objectNc                 C   s*   |d u ri }|| _ |j| _|| _i | _d S r   )_optionsr   r   _view_name_to_data_map_registered_views)r   optionsview_name_to_data_mapr   r   r   r   E   s   
zCollector.__init__c                 C   r   z,Options to be used to configure the exporterr&   r   r   r   r   r)   M   r   zCollector.optionsc                 C   r   r   r   r   r   r   r   r   R   r   zCollector.registryc                 C   r   )zOMap with all view data objects
        that will be sent to Prometheus
        )r'   r   r   r   r   r*   W      zCollector.view_name_to_data_mapc                 C   r   )zMap with all registered views)r(   r   r   r   r   registered_views^   r   zCollector.registered_viewsc                 C   sJ   t | jj|}|| jvr#||jttt|j|j	j
d}|| j|< dS dS )zrregister_view will create the needed structure
        in order to be able to sent all data to Prometheus
        )namedocumentationlabelsunitsN)get_view_namer)   r   r.   descriptionlistmapsanitizecolumnsmeasureunit)r   viewv_namedescr   r   r   register_viewc   s   
zCollector.register_viewc                 C   s*   |  |j t| jj|j}|| j|< dS )z)Add view data object to be sent to serverN)r>   r;   r3   r)   r   r*   )r   	view_datar<   r   r   r   add_view_datar   s   zCollector.add_view_datac                 C   s  |d }|d }|d }|d }t |t |ksJ ||fdd |D }t|tjrH||}	|	s>t||||d}	|	||< |	j||jd d	S t|tjr|j	t
|j	ksXJ g }
d
}t|j	D ]\}}||j| 7 }t||g}|
| qa|
d|jg ||}	|	st|||d}	|	||< |	j||
|jd d	S t|tjr||}	|	st|||d}	|	||< |	j||jd d	S t|tjr||}	|	st|||d}	|	||< |	j||jd d	S tdt| )a  to_metric translate the data that OpenCensus create
        to Prometheus format, using Prometheus Metric object
        :type desc: dict
        :param desc: The map that describes view definition
        :type tag_values: tuple of :class:
            `~opencensus.tags.tag_value.TagValue`
        :param object of opencensus.tags.tag_value.TagValue:
            TagValue object used as label values
        :type agg_data: object of :class:
            `~opencensus.stats.aggregation_data.AggregationData`
        :param object of opencensus.stats.aggregation_data.AggregationData:
            Aggregated data that needs to be converted as Prometheus samples
        :rtype: :class:`~prometheus_client.core.CounterMetricFamily` or
                :class:`~prometheus_client.core.HistogramMetricFamily` or
                :class:`~prometheus_client.core.UnknownMetricFamily` or
                :class:`~prometheus_client.core.GaugeMetricFamily`
        r/   r0   r1   r2   c                 S   s   g | ]}|r|nd qS )r   r   ).0tvr   r   r   
<listcomp>   s    z'Collector.to_metric.<locals>.<listcomp>)r/   r0   r:   r1   )r1   valueNr   z+Inf)r/   r0   r1   )r1   buckets	sum_valuezunsupported aggregation type )len
isinstanceaggregation_data_moduleCountAggregationDatagetr   
add_metric
count_dataDistributionAggregationDataboundssorted	enumeratecounts_per_bucketstrappendr	   sumSumAggregationDatar
   sum_dataLastValueAggregationDatar   rD   
ValueErrortype)r   r=   
tag_valuesagg_datametrics_mapmetric_namemetric_description
label_keysmetric_unitsmetricrE   	cum_countiiboundbucketr   r   r   	to_metricy   s   



zCollector.to_metricc                 c   sr    i }| j   D ]"\}}|| jvrq
| j| }|jD ]}|j| }| |||| qq
| D ]}|V  q1dS )zCollect 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.
        N)r'   copyitemsr.   tag_value_aggregation_data_maprg   values)r   r]   r<   r?   r=   r[   r\   rb   r   r   r   collect   s   



zCollector.collect)r    r!   r"   r#   r   r   r$   r)   r   r*   r.   r>   r@   rg   rl   r   r   r   r   r%   B   s    



cr%   c                   @   sr   e Zd ZdZeje fddZedd Z	edd Z
edd	 Zed
d Zdd Zdd Zdd Zdd ZdS )PrometheusStatsExportera^  Exporter exports stats to Prometheus, users need
        to register the exporter as an HTTP Handler to be
        able to export.
    :type options:
        :class:`~opencensus.ext.prometheus.stats_exporter.Options`
    :param options: An options object with the parameters to instantiate the
                         prometheus exporter.
    :type gatherer: :class:`~prometheus_client.core.CollectorRegistry`
    :param gatherer: A Prometheus collector registry instance.
    :type transport:
        :class:`opencensus.common.transports.sync.SyncTransport` or
        :class:`opencensus.common.transports.async_.AsyncTransport`
    :param transport: An instance of a Transpor to send data with.
    :type collector:
        :class:`~opencensus.ext.prometheus.stats_exporter.Collector`
    :param collector: An instance of the Prometheus Collector object.
    c                 C   s4   || _ || _|| _|| | _|   t| j d S r   )r&   	_gatherer
_collector
_transport
serve_httpr   register)r   r)   gatherer	transport	collectorr   r   r   r     s   
z PrometheusStatsExporter.__init__c                 C   r   )zOThe transport way to be sent data to server
        (default is sync).
        )rp   r   r   r   r   rt     r-   z!PrometheusStatsExporter.transportc                 C   r   )zSCollector class instance to be used
        to communicate with Prometheus
        )ro   r   r   r   r   ru     r-   z!PrometheusStatsExporter.collectorc                 C   r   r   )rn   r   r   r   r   rs     r   z PrometheusStatsExporter.gathererc                 C   r   r+   r,   r   r   r   r   r)   !  r   zPrometheusStatsExporter.optionsc                 C   s   |dur| j | dS dS )zvexport send the data to the transport class
        in order to be sent to Prometheus in a sync or async way.
        N)rt   export)r   r?   r   r   r   rv   &  s   zPrometheusStatsExporter.exportc                 C   s   t dS )NzNot supported by Prometheus)NotImplementedError)r   r;   r   r   r   on_register_view-  s   z(PrometheusStatsExporter.on_register_viewc                 C   s*   |D ]}|j du ri |_ | j| qdS )a=  Emit exports to the Prometheus if view data has one or more rows.
        Each OpenCensus AggregationData will be converted to
        corresponding Prometheus Metric: SumData will be converted
        to Untyped Metric, CountData will be a Counter Metric
        DistributionData will be a Histogram Metric.
        N)rj   ru   r@   )r   r?   v_datar   r   r   emit0  s
   
zPrometheusStatsExporter.emitc                 C   s6   t | jj}|rd|ini }tdd| jji| dS )z*serve_http serves the Prometheus endpoint.addrr   Nr   )rS   r)   r   r   r   )r   r   kwargsr   r   r   rq   >  s   z"PrometheusStatsExporter.serve_httpN)r    r!   r"   r#   r   SyncTransportr%   r   r$   rt   ru   rs   r)   rv   rx   rz   rq   r   r   r   r   rm      s     





rm   c                 C   s.   | j dkr	tdt| }t| | j|d}|S )zQnew_stats_exporter returns an exporter
    that exports stats to Prometheus.
    r   z"Namespace can not be empty string.)r)   rs   ru   )r   rY   new_collectorrm   r   )optionru   exporterr   r   r   new_stats_exporterE  s   
r   c                 C   s
   t | dS )znew_collector should be used
    to create instance of Collector class in order to
    prevent the usage of constructor directly
    r)   )r%   r   r   r   r   r~   T  s   
r~   c                 C   s"   d}| dkr
| d }t ||j S )zcreate the name for the viewr   _)r7   r/   )r   r;   r/   r   r   r   r3   \  s   r3   z[^\w]c                 C   s   t d| S )zsanitize the given metric name or label according to Prometheus rule.
    Replace all characters other than [A-Za-z0-9_] with '_'.
    r   )_NON_LETTERS_NOR_DIGITS_REsub)keyr   r   r   r7   g  s   r7   ) loggingreopencensus.common.transportsr   opencensus.statsr   rI   r   prometheus_clientr   prometheus_client.corer   r   r   r	   r
   	getLoggerr    loggerobjectr   r%   StatsExporterrm   r   r~   r3   compileUNICODE
IGNORECASEr   r7   r   r   r   r   <module>   s    
+ 0T