|
3 | 3 | import time
|
4 | 4 | import logging
|
5 | 5 | from util import instances_per_hypervisor
|
| 6 | +import asyncio |
6 | 7 |
|
7 | 8 | logger = logging.getLogger(__name__)
|
8 | 9 |
|
9 | 10 |
|
10 | 11 | class InstancesPerHypervisorCollector(Collector):
|
11 |
| - def __init__(self, cloud_name): |
| 12 | + def __init__(self, cloud_name, cache_time): |
12 | 13 | super().__init__()
|
13 | 14 | self.cloud_name = cloud_name
|
14 | 15 | self.metrics = []
|
15 | 16 | self.last_update = 0
|
16 |
| - self.cache_time = 60 |
| 17 | + self.cache_time = cache_time |
| 18 | + self.gauge = None |
17 | 19 |
|
18 | 20 | def _fetch_metrics(self):
|
| 21 | + """Fetch metrics from OpenStack and update the gauge.""" |
19 | 22 | try:
|
20 |
| - new_metrics = instances_per_hypervisor.export_metrics(self.cloud_name) |
21 |
| - self.metrics = new_metrics |
22 |
| - self.last_update = time.time() |
| 23 | + # Clear previous metrics |
| 24 | + self.gauge = GaugeMetricFamily( |
| 25 | + "openstack_peepo_exporter_instances_per_hypervisor", |
| 26 | + "Number of instances per hypervisor", |
| 27 | + labels=["hypervisor_name", "hypervisor_id"], |
| 28 | + ) |
| 29 | + |
| 30 | + new_metrics = asyncio.run( |
| 31 | + instances_per_hypervisor.export_metrics(self.cloud_name) |
| 32 | + ) |
23 | 33 | logger.info(f"Updated metrics with {len(new_metrics)} hypervisors")
|
24 | 34 |
|
| 35 | + # Update the gauge with new values |
| 36 | + for metric in new_metrics: |
| 37 | + self.gauge.add_metric( |
| 38 | + [metric["hypervisor_name"], metric["hypervisor_id"]], |
| 39 | + metric["instance_count"], |
| 40 | + ) |
| 41 | + |
| 42 | + # Update last_update timestamp |
| 43 | + self.last_update = time.time() |
25 | 44 | except Exception as e:
|
26 |
| - logger.error(f"Error updating metrics: {str(e)}") |
27 |
| - raise |
| 45 | + logger.error(f"Error updating metrics: {e}") |
28 | 46 |
|
29 | 47 | def collect(self):
|
30 | 48 | if time.time() - self.last_update > self.cache_time:
|
31 | 49 | self._fetch_metrics()
|
32 | 50 |
|
33 |
| - gauge = GaugeMetricFamily( |
34 |
| - "openstack_peepo_exporter_instances_per_hypervisor", |
35 |
| - "Number of instances per hypervisor", |
36 |
| - labels=["hypervisor_name", "hypervisor_id"], |
37 |
| - ) |
38 |
| - |
39 |
| - for metric in self.metrics: |
40 |
| - gauge.add_metric( |
41 |
| - [metric["hypervisor_name"], metric["hypervisor_id"]], |
42 |
| - metric["instance_count"], |
43 |
| - ) |
44 |
| - |
45 |
| - yield gauge |
| 51 | + yield self.gauge |
0 commit comments