o
    `۷i06                     @   s   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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)make_server)sync)aggregation_database_exporter)make_wsgi_app)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   V/home/ubuntu/vllm_env/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   4   r    zOptions.namespacec                 C   r   )zPort number to listenr   r   r   r   r   r   9   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   G   s   
zCollector.__init__c                 C   r   z,Options to be used to configure the exporterr(   r   r   r   r   r+   O   r    zCollector.optionsc                 C   r   r   r   r   r   r   r   r   T   r    zCollector.registryc                 C   r   )zOMap with all view data objects
        that will be sent to Prometheus
        )r)   r   r   r   r   r,   Y      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   r0   descriptionlistmapsanitizecolumnsmeasureunit)r   viewv_namedescr   r   r   register_viewe   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=   r5   r+   r   r,   )r   	view_datar>   r   r   r   add_view_datat   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`
        r1   r2   r3   r4   c                 S   s   g | ]}|r|nd qS )r   r   ).0tvr   r   r   
<listcomp>   s    z'Collector.to_metric.<locals>.<listcomp>)r1   r2   r<   r3   )r3   valueNr   z+Inf)r1   r2   r3   )r3   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	   rF   
ValueErrortype)r   r?   
tag_valuesagg_datametrics_mapmetric_namemetric_description
label_keysmetric_unitsmetricrG   	cum_countiiboundbucketr   r   r   	to_metric{   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itemsr0   tag_value_aggregation_data_mapri   values)r   r_   r>   rA   r?   r]   r^   rd   r   r   r   collect   s   



zCollector.collect)r"   r#   r$   r%   r   r   r&   r+   r   r,   r0   r@   rB   ri   rn   r   r   r   r   r'   D   s    



cr'   c                   @   s~   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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   s6   || _ || _|| _|| | _|  | _t| j d S r   )r(   	_gatherer
_collector
_transport
serve_httpr   r   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).
        )rr   r   r   r   r   rv     r/   z!PrometheusStatsExporter.transportc                 C   r   )zSCollector class instance to be used
        to communicate with Prometheus
        )rq   r   r   r   r   rw     r/   z!PrometheusStatsExporter.collectorc                 C   r   r   )rp   r   r   r   r   ru     r    z PrometheusStatsExporter.gathererc                 C   r   r-   r.   r   r   r   r   r+   #  r    zPrometheusStatsExporter.optionsc                 C   r   )z)The port the HTTP server is listening on.r!   r   r   r   r   r   (  r    zPrometheusStatsExporter.portc                 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)rv   export)r   rA   r   r   r   rx   -  s   zPrometheusStatsExporter.exportc                 C   s   t dS )NzNot supported by Prometheus)NotImplementedError)r   r=   r   r   r   on_register_view4  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)rl   rw   rB   )r   rA   v_datar   r   r   emit7  s
   
zPrometheusStatsExporter.emitc                 C   sD   | j jpd}t|| j jt }tj|jd}d|_|	  |j
d S )z*serve_http serves the Prometheus endpoint.r   )targetT   )r+   r   r   r   r   	threadingThreadserve_foreverdaemonstartserver_address)r   r   httpdtr   r   r   rs   E  s   
z"PrometheusStatsExporter.serve_httpN)r"   r#   r$   r%   r   SyncTransportr'   r   r&   rv   rw   ru   r+   r   rx   rz   r|   rs   r   r   r   r   ro      s$    






ro   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+   ru   rw   )r   r[   new_collectorro   r   )optionrw   exporterr   r   r   new_stats_exporterP  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   _  s   
r   c                 C   s"   d}| dkr
| d }t ||j S )zcreate the name for the viewr   _)r9   r1   )r   r=   r1   r   r   r   r5   g  s   r5   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   r9   r  s   r9   )#loggingrer   wsgiref.simple_serverr   opencensus.common.transportsr   opencensus.statsr   rK   r   prometheus_clientr   prometheus_client.corer   r   r	   r
   r   	getLoggerr"   loggerobjectr   r'   StatsExporterro   r   r   r5   compileUNICODE
IGNORECASEr   r9   r   r   r   r   <module>   s$   
+ 0]