o
    `jk(                     @   s`   d dl Z d dlZd dlZd dlZd dlmZmZmZmZ d dl	m
Z
 e eZG dd dZdS )    N)AnonMeasurableKafkaMetricMetricConfig
MetricName)Sensorc                   @   s   e Zd ZdZ		dddZedd Zedd	 Zd ddZdd Z	de
jdfddZdd Zd!ddZdd Zdd Zdd ZG dd dZdd ZdS )"Metricsa  
    A registry of sensors and metrics.

    A metric is a named, numerical measurement. A sensor is a handle to
    record numerical measurements as they occur. Each Sensor has zero or
    more associated metrics. For example a Sensor might represent message
    sizes and we might associate with this sensor a metric for the average,
    maximum, or other statistics computed off the sequence of message sizes
    that are recorded by the sensor.

    Usage looks something like this:
        # set up metrics:
        metrics = Metrics() # the global repository of metrics and sensors
        sensor = metrics.sensor('message-sizes')
        metric_name = MetricName('message-size-avg', 'producer-metrics')
        sensor.add(metric_name, Avg())
        metric_name = MetricName('message-size-max', 'producer-metrics')
        sensor.add(metric_name, Max())

        # as messages are sent we record the sizes
        sensor.record(message_size);
    NFc                    s   t   _|p	t  _i  _i  _i  _|pg  _ jD ]}|	g  qd _
|r< fdd}t j|d}d|_|    dddt fd	d
 dS )a  
        Create a metrics repository with a default config, given metric
        reporters and the ability to expire eligible sensors

        Arguments:
            default_config (MetricConfig, optional): The default config
            reporters (list of AbstractMetricsReporter, optional):
                The metrics reporters
            enable_expiration (bool, optional): true if the metrics instance
                can garbage collect inactive sensors, false otherwise
        Fc                      s*    j std  j   j rd S d S )N   )_closedtimesleepExpireSensorTaskrun selfr   S/home/djax/ivt_ai_plugin/venv/lib/python3.10/site-packages/kafka/metrics/metrics.pyexpire_loop;   s   
z%Metrics.__init__.<locals>.expire_loop)targetTcountzkafka-metrics-countz"total number of registered metricsc                    s
   t  jS N)len_metrics)confignowr   r   r   <lambda>G   s   
 z"Metrics.__init__.<locals>.<lambda>N)	threadingRLock_lockr   _config_sensorsr   _children_sensors
_reportersinitr	   Threaddaemonstart
add_metricmetric_namer   )r   default_config	reportersenable_expirationreporterr   metrics_schedulerr   r   r   __init__#   s&   


zMetrics.__init__c                 C      | j S r   )r   r   r   r   r   r   I   s   zMetrics.configc                 C   r.   )zT
        Get all the metrics currently maintained and indexed by metricName
        )r   r   r   r   r   metricsM   s   zMetrics.metrics c                 C   s(   t | jj}||pi  t||||S )a  
        Create a MetricName with the given name, group, description and tags,
        plus default tags specified in the metric configuration.
        Tag in tags takes precedence if the same tag key is specified in
        the default metric configuration.

        Arguments:
            name (str): The name of the metric
            group (str): logical group name of the metrics to which this
                metric belongs
            description (str, optional): A human-readable description to
                include in the metric
            tags (dict, optionals): additional key/value attributes of
                the metric
        )dictr   tagsupdater   )r   namegroupdescriptionr2   combined_tagsr   r   r   r'   T   s   zMetrics.metric_namec                 C   s   |st d| j|dS )z
        Get the sensor with the given name if it exists

        Arguments:
            name (str): The name of the sensor

        Returns:
            Sensor: The sensor or None if no such sensor exists
        zname must be non-emptyN)
ValueErrorr   get)r   r4   r   r   r   
get_sensorh   s   
zMetrics.get_sensorc                 C   s   |  |}|r	|S | jB |  |}|sEt| |||p| j|}|| j|< |r?|D ]}| j|}|s9g }|| j|< || q(t	d| |W  d   S 1 sQw   Y  dS )a  
        Get or create a sensor with the given unique name and zero or
        more parent sensors. All parent sensors will receive every value
        recorded with this sensor.

        Arguments:
            name (str): The name of the sensor
            config (MetricConfig, optional): A default configuration to use
                for this sensor for metrics that don't have their own config
            inactive_sensor_expiration_time_seconds (int, optional):
                If no value if recorded on the Sensor for this duration of
                time, it is eligible for removal
            parents (list of Sensor): The parent sensors

        Returns:
            Sensor: The sensor that is created
        zAdded sensor with name %sN)
r:   r   r   r   r   r    r9   appendloggerdebug)r   r4   r   'inactive_sensor_expiration_time_secondsparentssensorparentchildrenr   r   r   r@   v   s(   



$zMetrics.sensorc              	   C   s   | j i | j|}|rTd}|j . | j|d}|r8||kr8|jD ]}| |j q"td| | j	|d}W d   n1 sBw   Y  |r\|D ]}| 
|j qKW d   dS W d   dS W d   dS 1 sow   Y  dS )z
        Remove a sensor (if it exists), associated metrics and its children.

        Arguments:
            name (str): The name of the sensor to be removed
        NzRemoved sensor with name %s)r   r   r9   popr/   remove_metricr'   r<   r=   r    remove_sensorr4   )r   r4   r@   child_sensorsvalmetricchild_sensorr   r   r   rE      s,   
"zMetrics.remove_sensorc                 C   s    t |||p| j}| | dS )a  
        Add a metric to monitor an object that implements measurable.
        This metric won't be associated with any sensor.
        This is a way to expose existing values as metrics.

        Arguments:
            metricName (MetricName): The name of the metric
            measurable (AbstractMeasurable): The measurable that will be
                measured by this metric
            config (MetricConfig, optional): The configuration to use when
                measuring this measurable
        N)r   r   register_metric)r   r'   
measurabler   rH   r   r   r   r&      s   zMetrics.add_metricc                 C   sV   | j  | j|d}|r| jD ]}|| q|W  d   S 1 s$w   Y  dS )aw  
        Remove a metric if it exists and return it. Return None otherwise.
        If a metric is removed, `metric_removal` will be invoked
        for each reporter.

        Arguments:
            metric_name (MetricName): The name of the metric

        Returns:
            KafkaMetric: the removed `KafkaMetric` or None if no such
                metric exists
        N)r   r   rC   r!   metric_removal)r   r'   rH   r+   r   r   r   rD      s   
$zMetrics.remove_metricc                 C   sL   | j  |t| j  | j| W d   dS 1 sw   Y  dS )zAdd a MetricReporterN)r   r"   listr/   valuesr!   r;   r   r+   r   r   r   add_reporter   s   "zMetrics.add_reporterc                 C   sj   | j ( |j| jv rtd|jf || j|j< | jD ]}|| qW d    d S 1 s.w   Y  d S )Nz@A metric named "%s" already exists, cannot register another one.)r   r'   r/   r8   r!   metric_change)r   rH   r+   r   r   r   rJ      s   
"zMetrics.register_metricc                   @   s   e Zd ZdZedd ZdS )zMetrics.ExpireSensorTaskz
        This iterates over every Sensor and triggers a remove_sensor
        if it has expired. Package private for testing
        c              	   C   sd   t | j }|D ]&\}}|j | r td| | | W d    n1 s*w   Y  q	d S )NzRemoving expired sensor %s)rM   r   itemsr   has_expiredr<   r=   rE   )r/   rR   r4   r@   r   r   r   r      s   

zMetrics.ExpireSensorTask.runN)__name__
__module____qualname____doc__staticmethodr   r   r   r   r   r      s    r   c                 C   s(   | j D ]}|  q| j  d| _dS )zClose this metrics repository.TN)r!   closer   clearr	   rO   r   r   r   rY      s   



zMetrics.close)NNF)r0   Nr   )rT   rU   rV   rW   r-   propertyr   r/   r'   r:   sysmaxsizer@   rE   r&   rD   rP   rJ   r   rY   r   r   r   r   r      s,    
&



(
	r   )loggingr\   r
   r   kafka.metricsr   r   r   r   kafka.metrics.statsr   	getLoggerrT   r<   r   r   r   r   r   <module>   s    
