Skip to content

Commit f0f9c71

Browse files
hmeirclaude
andcommitted
refactor: move validate_metrics_value to utilities/monitoring
Signed-off-by: Harel Meir <hmeir@redhat.com> Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
1 parent c39c1dc commit f0f9c71

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

utilities/monitoring.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
1+
import datetime
12
import logging
3+
from typing import TYPE_CHECKING
24

35
from timeout_sampler import TimeoutExpiredError, TimeoutSampler
46

7+
if TYPE_CHECKING:
8+
from ocp_utilities.monitoring import Prometheus
9+
510
from utilities.constants import (
611
FIRING_STATE,
712
KUBEVIRT_HYPERCONVERGED_OPERATOR_HEALTH_STATUS,
@@ -175,6 +180,43 @@ def get_metrics_value(prometheus, metrics_name):
175180
return 0
176181

177182

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+
178220
def wait_for_gauge_metrics_value(prometheus, query, expected_value, timeout=TIMEOUT_5MIN):
179221
samples = TimeoutSampler(
180222
wait_timeout=timeout,

0 commit comments

Comments
 (0)