|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# Copyright 2014 Spanish National Research Council (CSIC) |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 6 | +# not use this file except in compliance with the License. You may obtain |
| 7 | +# a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 13 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 14 | +# License for the specific language governing permissions and limitations |
| 15 | +# under the License. |
| 16 | + |
| 17 | +"""Module containing the Prometheus extractor for energy consumption metrics.""" |
| 18 | + |
| 19 | +import uuid |
| 20 | + |
| 21 | +import requests |
| 22 | +from oslo_config import cfg |
| 23 | +from oslo_log import log |
| 24 | + |
| 25 | +from caso.extract import base |
| 26 | +from caso import record |
| 27 | + |
| 28 | +CONF = cfg.CONF |
| 29 | + |
| 30 | +opts = [ |
| 31 | + cfg.StrOpt( |
| 32 | + "prometheus_endpoint", |
| 33 | + default="http://localhost:9090", |
| 34 | + help="Prometheus server endpoint URL.", |
| 35 | + ), |
| 36 | + cfg.StrOpt( |
| 37 | + "prometheus_query", |
| 38 | + default="sum(rate(node_energy_joules_total[5m])) * 300 / 3600000", |
| 39 | + help="Prometheus query to retrieve energy consumption in kWh. " |
| 40 | + "The query should return energy consumption metrics.", |
| 41 | + ), |
| 42 | + cfg.IntOpt( |
| 43 | + "prometheus_timeout", |
| 44 | + default=30, |
| 45 | + help="Timeout for Prometheus API requests in seconds.", |
| 46 | + ), |
| 47 | +] |
| 48 | + |
| 49 | +CONF.import_opt("site_name", "caso.extract.base") |
| 50 | +CONF.register_opts(opts, group="prometheus") |
| 51 | + |
| 52 | +LOG = log.getLogger(__name__) |
| 53 | + |
| 54 | + |
| 55 | +class PrometheusExtractor(base.BaseProjectExtractor): |
| 56 | + """A Prometheus extractor for energy consumption metrics in cASO.""" |
| 57 | + |
| 58 | + def __init__(self, project, vo): |
| 59 | + """Initialize a Prometheus extractor for a given project.""" |
| 60 | + super(PrometheusExtractor, self).__init__(project) |
| 61 | + self.vo = vo |
| 62 | + self.project_id = project |
| 63 | + |
| 64 | + def _query_prometheus(self, query, timestamp=None): |
| 65 | + """Query Prometheus API and return results. |
| 66 | +
|
| 67 | + :param query: PromQL query string |
| 68 | + :param timestamp: Optional timestamp for query (datetime object) |
| 69 | + :returns: Query results |
| 70 | + """ |
| 71 | + endpoint = CONF.prometheus.prometheus_endpoint |
| 72 | + url = f"{endpoint}/api/v1/query" |
| 73 | + |
| 74 | + params = {"query": query} |
| 75 | + if timestamp: |
| 76 | + params["time"] = int(timestamp.timestamp()) |
| 77 | + |
| 78 | + try: |
| 79 | + response = requests.get( |
| 80 | + url, params=params, timeout=CONF.prometheus.prometheus_timeout |
| 81 | + ) |
| 82 | + response.raise_for_status() |
| 83 | + data = response.json() |
| 84 | + |
| 85 | + if data.get("status") != "success": |
| 86 | + error_msg = data.get("error", "Unknown error") |
| 87 | + LOG.error(f"Prometheus query failed: {error_msg}") |
| 88 | + return None |
| 89 | + |
| 90 | + return data.get("data", {}).get("result", []) |
| 91 | + except requests.exceptions.RequestException as e: |
| 92 | + LOG.error(f"Failed to query Prometheus: {e}") |
| 93 | + return None |
| 94 | + except Exception as e: |
| 95 | + LOG.error(f"Unexpected error querying Prometheus: {e}") |
| 96 | + return None |
| 97 | + |
| 98 | + def _build_energy_record(self, energy_value, measurement_time): |
| 99 | + """Build an energy consumption record. |
| 100 | +
|
| 101 | + :param energy_value: Energy consumption value in kWh |
| 102 | + :param measurement_time: Time of measurement |
| 103 | + :returns: EnergyRecord object |
| 104 | + """ |
| 105 | + r = record.EnergyRecord( |
| 106 | + uuid=uuid.uuid4(), |
| 107 | + measurement_time=measurement_time, |
| 108 | + site_name=CONF.site_name, |
| 109 | + user_id=None, |
| 110 | + group_id=self.project_id, |
| 111 | + user_dn=None, |
| 112 | + fqan=self.vo, |
| 113 | + energy_consumption=energy_value, |
| 114 | + energy_unit="kWh", |
| 115 | + compute_service=CONF.service_name, |
| 116 | + ) |
| 117 | + |
| 118 | + return r |
| 119 | + |
| 120 | + def extract(self, extract_from, extract_to): |
| 121 | + """Extract energy consumption records from Prometheus. |
| 122 | +
|
| 123 | + This method queries Prometheus for energy consumption metrics |
| 124 | + in the specified time range. |
| 125 | +
|
| 126 | + :param extract_from: datetime.datetime object indicating the date to |
| 127 | + extract records from |
| 128 | + :param extract_to: datetime.datetime object indicating the date to |
| 129 | + extract records to |
| 130 | + :returns: A list of energy records |
| 131 | + """ |
| 132 | + records = [] |
| 133 | + |
| 134 | + # Query Prometheus at the extract_to timestamp |
| 135 | + query = CONF.prometheus.prometheus_query |
| 136 | + LOG.debug( |
| 137 | + f"Querying Prometheus for project {self.project} " f"with query: {query}" |
| 138 | + ) |
| 139 | + |
| 140 | + results = self._query_prometheus(query, extract_to) |
| 141 | + |
| 142 | + if results is None: |
| 143 | + LOG.warning( |
| 144 | + f"No results returned from Prometheus for project {self.project}" |
| 145 | + ) |
| 146 | + return records |
| 147 | + |
| 148 | + # Process results and create records |
| 149 | + for result in results: |
| 150 | + value = result.get("value", []) |
| 151 | + |
| 152 | + if len(value) < 2: |
| 153 | + continue |
| 154 | + |
| 155 | + # value is [timestamp, value_string] |
| 156 | + energy_value = float(value[1]) |
| 157 | + |
| 158 | + LOG.debug( |
| 159 | + f"Creating energy record: {energy_value} kWh " |
| 160 | + f"for project {self.project}" |
| 161 | + ) |
| 162 | + |
| 163 | + energy_record = self._build_energy_record(energy_value, extract_to) |
| 164 | + records.append(energy_record) |
| 165 | + |
| 166 | + LOG.info(f"Extracted {len(records)} energy records for project {self.project}") |
| 167 | + |
| 168 | + return records |
0 commit comments