|
| 1 | +import datetime |
1 | 2 | import logging |
| 3 | +from typing import TYPE_CHECKING |
2 | 4 |
|
3 | 5 | from timeout_sampler import TimeoutExpiredError, TimeoutSampler |
4 | 6 |
|
| 7 | +if TYPE_CHECKING: |
| 8 | + from ocp_utilities.monitoring import Prometheus |
| 9 | + |
5 | 10 | from utilities.constants import ( |
6 | 11 | FIRING_STATE, |
7 | 12 | KUBEVIRT_HYPERCONVERGED_OPERATOR_HEALTH_STATUS, |
@@ -175,6 +180,43 @@ def get_metrics_value(prometheus, metrics_name): |
175 | 180 | return 0 |
176 | 181 |
|
177 | 182 |
|
| 183 | +def validate_metrics_value( |
| 184 | + prometheus: "Prometheus", metric_name: str, expected_value: str | int, timeout: int = TIMEOUT_5MIN |
| 185 | +) -> None: |
| 186 | + """Wait until the metric matches the expected value. |
| 187 | +
|
| 188 | + Args: |
| 189 | + prometheus: Prometheus instance. |
| 190 | + metric_name: Name of the metric to query. |
| 191 | + expected_value: Expected value to match. Use str for emitted values (e.g. "0"), |
| 192 | + int 0 for absent/not-emitted metrics (get_metrics_value returns int 0 when absent). |
| 193 | + timeout: Maximum wait time in seconds. |
| 194 | +
|
| 195 | + Raises: |
| 196 | + TimeoutExpiredError: If the metric does not match within timeout. |
| 197 | + """ |
| 198 | + samples = TimeoutSampler( |
| 199 | + wait_timeout=timeout, |
| 200 | + sleep=TIMEOUT_5SEC, |
| 201 | + func=get_metrics_value, |
| 202 | + prometheus=prometheus, |
| 203 | + metrics_name=metric_name, |
| 204 | + ) |
| 205 | + sample = None |
| 206 | + comparison_values_log = {} |
| 207 | + try: |
| 208 | + for sample in samples: |
| 209 | + comparison_values_log[datetime.datetime.now()] = ( |
| 210 | + f"metric: {metric_name} value is: {sample}, the expected value is {expected_value}" |
| 211 | + ) |
| 212 | + if sample == expected_value: |
| 213 | + LOGGER.info(f"Metrics value matches the expected value: {expected_value}") |
| 214 | + return |
| 215 | + except TimeoutExpiredError: |
| 216 | + LOGGER.error(f"Metrics value: {sample}, expected: {expected_value}, comparison log: {comparison_values_log}") |
| 217 | + raise |
| 218 | + |
| 219 | + |
178 | 220 | def wait_for_gauge_metrics_value(prometheus, query, expected_value, timeout=TIMEOUT_5MIN): |
179 | 221 | samples = TimeoutSampler( |
180 | 222 | wait_timeout=timeout, |
|
0 commit comments