From a83e500b54cc7623aff042617f7c2499c97eb385 Mon Sep 17 00:00:00 2001 From: wmousa Date: Wed, 26 Aug 2026 21:42:32 +0200 Subject: [PATCH] fix(metrics): stop the v1 /cluster/metrics series leak The gauges were cached at module scope, so a Gauge child created for a label set lived as long as the worker process. Those label sets carry entity identity (lvol/lvol_name/pvc_name/device/...), so every volume that had ever existed kept being exported. Measured on a customer cluster (94 live volumes, ~1.2k volume deletions/day): * 11,534 distinct pvc_name label sets still being exported * ~83 MB and ~5 s per scrape, growing ~7 MB/day * 15 WebAppAPI containers (5 services x 3 managers), each with its own accumulated registry, so a single Prometheus target answered by HAProxy round-robin returned a different series set every scrape -- series flapped in and out and Grafana panels rendered empty * ~450 MiB RSS above a comparable app service, per container Fix: build the registry per request, and build each gauge family exactly once per request, before the entity loops. Both halves are required -- a Gauge registers its name on construction, so constructing a family inside the per-entity loops raises DuplicateTimeseries on the second node/device/pool/volume. After the equivalent change, customer scrapes went from 310,401 lines (and 298,851 from a sibling container) to a stable 3,741 lines in 2-3 s, identical across repeated scrapes, and the dashboards recovered. Also in this endpoint, both inseparable from the rewrite: * health_check is Optional[bool]; Gauge.set(None) raises TypeError and would fail the whole scrape. Report NaN, which Prometheus reads as "no sample" rather than as unhealthy. * The reactor walk sat inside the per-gauge-name loop, so every reactor was re-walked once per gauge name (~33x per node) while only two of those names consumed the result. It now runs once per node. * .labels() creates the child series and an un-set child exports as 0, so the value is resolved before .labels() is called; a metric with no source value stays absent instead of reading as a real zero. --- simplyblock_web/api/v1/metrics.py | 309 +++++++++++++++------------ tests/test_v1_metrics_series_leak.py | 245 +++++++++++++++++++++ 2 files changed, 419 insertions(+), 135 deletions(-) create mode 100644 tests/test_v1_metrics_series_leak.py diff --git a/simplyblock_web/api/v1/metrics.py b/simplyblock_web/api/v1/metrics.py index f700402b05..b34784b9a9 100644 --- a/simplyblock_web/api/v1/metrics.py +++ b/simplyblock_web/api/v1/metrics.py @@ -1,23 +1,17 @@ #!/usr/bin/env python -# encoding: utf-8 import logging -from flask import Blueprint +from flask import Blueprint, Response +from prometheus_client import CollectorRegistry, Gauge, generate_latest + +from simplyblock_core import db_controller from simplyblock_core.models.nvme_device import NVMeDevice from simplyblock_core.models.storage_node import StorageNode -from simplyblock_core import db_controller - - -from prometheus_client import generate_latest -from flask import Response -from prometheus_client import Gauge, CollectorRegistry - logger = logging.getLogger(__name__) bp = Blueprint("metrics", __name__) -registry = CollectorRegistry() db = db_controller.DBController() io_stats_keys = [ @@ -51,69 +45,96 @@ "write_latency_ticks", ] -ng: dict[str, Gauge] = {} -cg: dict[str, Gauge] = {} -dg: dict[str, Gauge] = {} -lg: dict[str, Gauge] = {} -pg: dict[str, Gauge] = {} - -def get_device_metrics(): - global dg - if not dg: - labels = ['cluster', "cluster_name", "snode", "device"] - for k in io_stats_keys + ["status_code", "health_check"]: - dg["device_" + k] = Gauge("device_" + k, "device_" + k, labelnames=labels, registry=registry) - return dg - -def get_snode_metrics(): - global ng - if not ng: - labels = ['cluster', "cluster_name", "snode", "hostname"] - for k in io_stats_keys + ["status_code", "health_check"]: - ng["snode_" + k] = Gauge("snode_" + k, "snode_" + k, labelnames=labels, registry=registry) - - # Additional SPDK-specific metrics - ng["snode_cpu_busy_percentage"] = Gauge( - "snode_cpu_busy_percentage", - "Per-thread CPU Busy %", - labelnames=['cluster', "cluster_name", 'snode', 'hostname', 'thread_name'], - registry=registry - ) - ng["snode_cpu_core_utilization"] = Gauge( - "snode_cpu_core_utilization", - "Per-core CPU Utilization %", - labelnames=['cluster', "cluster_name", 'snode', 'hostname', 'core_id', 'thread_names'], - registry=registry - ) - return ng - -def get_cluster_metrics(): - global cg - if not cg: - labels = ['cluster', "cluster_name"] - for k in io_stats_keys + ["status_code", "prov_cap_crit", "cap_crit"]: - cg["cluster_" + k] = Gauge("cluster_" + k, "cluster_" + k, labelnames=labels, registry=registry) - return cg - -def get_lvol_metrics(): - global lg - if not lg: - labels = ['cluster', "cluster_name", "pool", "lvol", "lvol_name", "pvc_name"] - for k in io_stats_keys + ["status_code", "health_check"]: - lg["lvol_" + k] = Gauge("lvol_" + k, "lvol_" + k, labelnames=labels, registry=registry) - return lg - -def get_pool_metrics(): - global pg - if not pg: - labels = ['cluster', "cluster_name", "pool", "name"] - for k in io_stats_keys + ["status_code"]: - pg["pool_" + k] = Gauge("pool_" + k, "pool_" + k, labelnames=labels, registry=registry) - return pg + +# Every gauge family below is constructed against a registry that lives only +# for the duration of one request (see get_data). They must NOT be cached at +# module scope: a Gauge keeps a child object per label set it has ever been +# given, and these label sets carry entity identity (lvol/pvc_name/device/...), +# so a process-lifetime gauge keeps reporting volumes that were deleted days +# ago. Constructing them per request is what bounds the exposition to the +# entities that currently exist. + +def get_device_metrics(registry): + labels = ['cluster', "cluster_name", "snode", "device"] + return { + "device_" + k: Gauge("device_" + k, "device_" + k, labelnames=labels, registry=registry) + for k in io_stats_keys + ["status_code", "health_check"] + } + + +def get_snode_metrics(registry): + labels = ['cluster', "cluster_name", "snode", "hostname"] + gauges = { + "snode_" + k: Gauge("snode_" + k, "snode_" + k, labelnames=labels, registry=registry) + for k in io_stats_keys + ["status_code", "health_check"] + } + # Additional SPDK-specific metrics + gauges["snode_cpu_busy_percentage"] = Gauge( + "snode_cpu_busy_percentage", + "Per-thread CPU Busy %", + labelnames=['cluster', "cluster_name", 'snode', 'hostname', 'thread_name'], + registry=registry + ) + gauges["snode_cpu_core_utilization"] = Gauge( + "snode_cpu_core_utilization", + "Per-core CPU Utilization %", + labelnames=['cluster', "cluster_name", 'snode', 'hostname', 'core_id', 'thread_names'], + registry=registry + ) + return gauges + + +def get_cluster_metrics(registry): + labels = ['cluster', "cluster_name"] + return { + "cluster_" + k: Gauge("cluster_" + k, "cluster_" + k, labelnames=labels, registry=registry) + for k in io_stats_keys + ["status_code", "prov_cap_crit", "cap_crit"] + } + + +def get_lvol_metrics(registry): + labels = ['cluster', "cluster_name", "pool", "lvol", "lvol_name", "pvc_name"] + return { + "lvol_" + k: Gauge("lvol_" + k, "lvol_" + k, labelnames=labels, registry=registry) + for k in io_stats_keys + ["status_code", "health_check"] + } + + +def get_pool_metrics(registry): + labels = ['cluster', "cluster_name", "pool", "name"] + return { + "pool_" + k: Gauge("pool_" + k, "pool_" + k, labelnames=labels, registry=registry) + for k in io_stats_keys + ["status_code"] + } + + +def _gauge_value(value): + """health_check is Optional[bool]: None means "not applicable" rather than + "unhealthy". Gauge.set(None) raises TypeError and would fail the whole + scrape, so report NaN, which Prometheus reads as "no sample" instead of 0. + """ + return float('nan') if value is None else float(value) @bp.route('/cluster/metrics', methods=['GET']) def get_data(): + # One registry per request, and every gauge family built exactly once here, + # before the loops below. + # + # Both halves matter. A registry that outlives the request accumulates a + # child series per label set forever, so deleted volumes keep being + # exported (observed on a customer cluster: 94 live volumes but ~350k + # series / 83 MB / 5 s per scrape, growing ~7 MB/day at ~1.2k volume + # deletions/day, until Prometheus could no longer usefully ingest it). + # And a Gauge registers its name with the registry on construction, so + # building a family inside the per-entity loops instead of here raises + # DuplicateTimeseries on the second node/device/pool/volume. + registry = CollectorRegistry() + cluster_gauges = get_cluster_metrics(registry) + snode_gauges = get_snode_metrics(registry) + device_gauges = get_device_metrics(registry) + pool_gauges = get_pool_metrics(registry) + lvol_gauges = get_lvol_metrics(registry) clusters = db.get_clusters() for cl in clusters: @@ -121,19 +142,24 @@ def get_data(): records = db.get_cluster_stats(cl, 1) if records: data = records[0].get_clean_dict() - object_data = cl.get_clean_dict() + object_data = cl.get_clean_dict() - ng = get_cluster_metrics() - for g in ng: + for g in cluster_gauges: v = g.replace("cluster_", "") + # Resolve the value first and skip if there isn't one: calling + # .labels() creates the child series, and an un-set child is + # exported as 0. A metric with no source value must stay absent + # rather than read as a real zero. if v in data: - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name).set(data[v]) + value = data[v] elif v == "status_code": - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name).set(cl.get_status_code()) - elif v == "prov_cap_crit": - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name).set(object_data[v]) - elif v == "cap_crit": - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name).set(object_data[v]) + value = cl.get_status_code() + elif v in ("prov_cap_crit", "cap_crit"): + value = object_data[v] + else: + continue + cluster_gauges[g].labels( + cluster=cl.get_id(), cluster_name=cl.cluster_name).set(value) snodes = db.get_storage_nodes_by_cluster_id(cl.get_id()) for node in snodes: @@ -145,53 +171,61 @@ def get_data(): if not node.nvme_devices: logger.error("No devices found in node: %s", node.get_id()) continue - + rpc_client = node.rpc_client(timeout=3*60, retry=10) reactor_data = rpc_client.framework_get_reactors() thread_data = rpc_client.thread_get_stats() - thread_busy_map = {t["id"]: t["busy"] for t in thread_data.get("threads", [])} + thread_busy_map = {t["id"]: t["busy"] for t in thread_data.get("threads", [])} node_records = db.get_node_stats(node, 1) if node_records: data = node_records[0].get_clean_dict() - ng = get_snode_metrics() - for g in ng: + for g in snode_gauges: v = g.replace("snode_", "") if v in data: - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, snode=node.get_id(), hostname=node.hostname).set(data[v]) + value = data[v] elif v == "status_code": - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, snode=node.get_id(), hostname=node.hostname).set(node.get_status_code()) + value = node.get_status_code() elif v == "health_check": - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, snode=node.get_id(), hostname=node.hostname).set(node.health_check) - if reactor_data and "reactors" in reactor_data: - for reactor in reactor_data.get("reactors", []): - lcore = reactor.get("lcore") - core_idle = reactor.get("idle", 0) - core_busy = reactor.get("busy", 0) - irq = reactor.get("irq", 0) - sys = reactor.get("sys", 0) - - thread_names = ", ".join(thread["name"] for thread in reactor.get("lw_threads", [])) - if v == "cpu_busy_percentage": - for thread in reactor.get("lw_threads", []): - thread_name = thread.get("name") - thread_id = thread.get("id") - thread_busy = thread_busy_map.get(thread_id, 0) - - total_core_cycles = core_busy + core_idle - cpu_usage_percent = (thread_busy / total_core_cycles) * 100 if total_core_cycles > 0 else 0 - - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, snode=node.get_id(), hostname=node.hostname, thread_name=thread_name).set(cpu_usage_percent) - - elif v == "cpu_core_utilization": - - total_cycle = core_busy + irq + sys - total_with_idle = total_cycle + core_idle - core_utilization = (total_cycle / total_with_idle) * 100 if total_with_idle > 0 else 0 - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, snode=node.get_id(), hostname=node.hostname, core_id=str(lcore), thread_names=thread_names).set(core_utilization) - + value = _gauge_value(node.health_check) + else: + continue # incl. cpu_*, which come from reactor_data below + snode_gauges[g].labels( + cluster=cl.get_id(), cluster_name=cl.cluster_name, + snode=node.get_id(), hostname=node.hostname).set(value) + + # Walked once per node. This used to sit inside the loop above, + # so every reactor was re-walked once per gauge name (~33x per + # node) while only two of those names ever consumed the result. + for reactor in (reactor_data or {}).get("reactors", []): + lcore = reactor.get("lcore") + core_idle = reactor.get("idle", 0) + core_busy = reactor.get("busy", 0) + irq = reactor.get("irq", 0) + sys = reactor.get("sys", 0) + + thread_names = ", ".join(thread["name"] for thread in reactor.get("lw_threads", [])) + + for thread in reactor.get("lw_threads", []): + thread_name = thread.get("name") + thread_id = thread.get("id") + thread_busy = thread_busy_map.get(thread_id, 0) + + total_core_cycles = core_busy + core_idle + cpu_usage_percent = (thread_busy / total_core_cycles) * 100 if total_core_cycles > 0 else 0 + + snode_gauges["snode_cpu_busy_percentage"].labels( + cluster=cl.get_id(), cluster_name=cl.cluster_name, snode=node.get_id(), + hostname=node.hostname, thread_name=thread_name).set(cpu_usage_percent) + + total_cycle = core_busy + irq + sys + total_with_idle = total_cycle + core_idle + core_utilization = (total_cycle / total_with_idle) * 100 if total_with_idle > 0 else 0 + snode_gauges["snode_cpu_core_utilization"].labels( + cluster=cl.get_id(), cluster_name=cl.cluster_name, snode=node.get_id(), + hostname=node.hostname, core_id=str(lcore), thread_names=thread_names).set(core_utilization) for device in node.nvme_devices: @@ -203,48 +237,53 @@ def get_data(): device_records = db.get_device_stats(device, 1) if device_records: data = device_records[0].get_clean_dict() - ng = get_device_metrics() - for g in ng: + for g in device_gauges: v = g.replace("device_", "") if v in data: - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, snode=node.get_id(), device=device.get_id()).set(data[v]) + value = data[v] elif v == "status_code": - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, snode=node.get_id(), device=device.get_id()).set( - device.get_status_code()) + value = device.get_status_code() elif v == "health_check": - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, snode=node.get_id(), device=device.get_id()).set( - device.health_check) - + value = _gauge_value(device.health_check) + else: + continue + device_gauges[g].labels( + cluster=cl.get_id(), cluster_name=cl.cluster_name, + snode=node.get_id(), device=device.get_id()).set(value) for pool in db.get_pools(): pool_records = db.get_pool_stats(pool, 1) if pool_records: data = pool_records[0].get_clean_dict() - ng = get_pool_metrics() - for g in ng: + for g in pool_gauges: v = g.replace("pool_", "") if v in data: - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, name=pool.pool_name, pool=pool.get_id()).set(data[v]) + value = data[v] elif v == "status_code": - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, name=pool.pool_name, pool=pool.get_id()).set( - pool.get_status_code()) + value = pool.get_status_code() + else: + continue + pool_gauges[g].labels( + cluster=cl.get_id(), cluster_name=cl.cluster_name, + name=pool.pool_name, pool=pool.get_id()).set(value) for lvol in db.get_lvols(cl.get_id()): lvol_records = db.get_lvol_stats(lvol, limit=1) if lvol_records: data = lvol_records[0].get_clean_dict() - ng = get_lvol_metrics() - for g in ng: + for g in lvol_gauges: v = g.replace("lvol_", "") if v in data: - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, lvol=lvol.get_id(), lvol_name=lvol.lvol_name, pvc_name=lvol.pvc_name, pool=lvol.pool_name).set(data[v]) + value = data[v] elif v == "status_code": - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, lvol=lvol.get_id(), lvol_name=lvol.lvol_name, pvc_name=lvol.pvc_name, pool=lvol.pool_name).set( - lvol.get_status_code()) + value = lvol.get_status_code() elif v == "health_check": - ng[g].labels(cluster=cl.get_id(), cluster_name=cl.cluster_name, lvol=lvol.get_id(), lvol_name=lvol.lvol_name, pvc_name=lvol.pvc_name, pool=lvol.pool_name).set( - lvol.health_check) - - - return Response(generate_latest(registry), mimetype=str('text/plain; version=0.0.4; charset=utf-8')) + value = _gauge_value(lvol.health_check) + else: + continue + lvol_gauges[g].labels( + cluster=cl.get_id(), cluster_name=cl.cluster_name, lvol=lvol.get_id(), + lvol_name=lvol.lvol_name, pvc_name=lvol.pvc_name, pool=lvol.pool_name).set(value) + + return Response(generate_latest(registry), mimetype='text/plain; version=0.0.4; charset=utf-8') diff --git a/tests/test_v1_metrics_series_leak.py b/tests/test_v1_metrics_series_leak.py new file mode 100644 index 0000000000..aa40a95c39 --- /dev/null +++ b/tests/test_v1_metrics_series_leak.py @@ -0,0 +1,245 @@ +"""Regression tests for the v1 /cluster/metrics Prometheus exposition. + +Two distinct faults are locked down here, both of which shipped because no +test ever exercised this endpoint with more than one entity: + + * **Series leak.** The gauges used to be cached at module scope, so a Gauge + child created for a label set -- and these label sets carry entity + identity (lvol/pvc_name/device/...) -- survived for the worker process's + whole life. Volumes deleted days earlier kept being exported. Observed on + a customer cluster: 94 live volumes but ~350k series / 83 MB / ~5 s per + scrape, growing ~7 MB/day at ~1.2k volume deletions/day, until Prometheus + could no longer usefully ingest it. + + * **DuplicateTimeseries.** A Gauge registers its name with the registry when + it is constructed, so building a gauge family inside the per-entity loops + raises ``DuplicateTimeseries`` on the *second* node/device/pool/volume. An + earlier attempt at fixing the leak moved construction into the request but + left it inside those loops, which would have 500'd every real cluster. + +The fix is both halves together: a registry per request, and each gauge family +built exactly once per request, before the loops. +""" + +import math +import unittest +from unittest.mock import MagicMock, patch + +from simplyblock_web.api.v1 import metrics + + +def _stats_record(): + """A stats row: every io_stats key present with a numeric value.""" + rec = MagicMock() + rec.get_clean_dict.return_value = {k: 1 for k in metrics.io_stats_keys} + return rec + + +def _cluster(uuid="cl-1"): + cl = MagicMock() + cl.get_id.return_value = uuid + cl.cluster_name = "test-cluster" + cl.get_status_code.return_value = 1 + cl.get_clean_dict.return_value = {"prov_cap_crit": 0, "cap_crit": 0} + return cl + + +def _device(uuid, health_check=True): + dev = MagicMock() + dev.uuid = uuid + dev.get_id.return_value = uuid + dev.status = "online" + dev.get_status_code.return_value = 1 + dev.health_check = health_check + return dev + + +def _node(uuid, devices, health_check=True): + node = MagicMock() + node.get_id.return_value = uuid + node.hostname = f"host-{uuid}" + node.status = "online" + node.get_status_code.return_value = 1 + node.health_check = health_check + node.nvme_devices = devices + rpc = MagicMock() + rpc.framework_get_reactors.return_value = {"reactors": [ + {"lcore": 0, "idle": 100, "busy": 100, "irq": 0, "sys": 0, + "lw_threads": [{"id": 1, "name": "app_thread"}]}, + {"lcore": 1, "idle": 100, "busy": 100, "irq": 0, "sys": 0, + "lw_threads": [{"id": 2, "name": "poller_0"}]}, + ]} + rpc.thread_get_stats.return_value = {"threads": [{"id": 1, "busy": 50}, {"id": 2, "busy": 25}]} + node.rpc_client.return_value = rpc + return node + + +def _pool(uuid): + pool = MagicMock() + pool.get_id.return_value = uuid + pool.pool_name = f"pool-{uuid}" + pool.get_status_code.return_value = 1 + return pool + + +def _lvol(uuid, health_check=True): + lvol = MagicMock() + lvol.get_id.return_value = uuid + lvol.lvol_name = f"vol-{uuid}" + lvol.pvc_name = f"pvc-{uuid}" + lvol.pool_name = "pool-p1" + lvol.get_status_code.return_value = 1 + lvol.health_check = health_check + return lvol + + +def _fake_db(nodes, pools, lvols, clusters=None): + db = MagicMock() + db.get_clusters.return_value = clusters if clusters is not None else [_cluster()] + db.get_storage_nodes_by_cluster_id.return_value = nodes + db.get_pools.return_value = pools + db.get_lvols.return_value = lvols + db.get_cluster_stats.return_value = [_stats_record()] + db.get_node_stats.return_value = [_stats_record()] + db.get_device_stats.return_value = [_stats_record()] + db.get_pool_stats.return_value = [_stats_record()] + db.get_lvol_stats.return_value = [_stats_record()] + return db + + +def _scrape(db): + with patch.object(metrics, "db", db): + return metrics.get_data().get_data(as_text=True) + + +class TestMultipleEntities(unittest.TestCase): + """The case that was never tested, and that both the original bug and the + first attempted fix fell down on.""" + + def test_many_entities_do_not_raise_duplicate_timeseries(self): + db = _fake_db( + nodes=[_node("n1", [_device("d1"), _device("d2")]), + _node("n2", [_device("d3"), _device("d4")])], + pools=[_pool("p1"), _pool("p2")], + lvols=[_lvol("l1"), _lvol("l2"), _lvol("l3")], + ) + body = _scrape(db) # must not raise DuplicateTimeseries + for uuid in ("n1", "n2", "d1", "d4", "p1", "p2", "l1", "l3"): + self.assertIn(uuid, body, f"{uuid} missing from exposition") + + def test_every_entity_is_reported_exactly_once_per_metric(self): + db = _fake_db(nodes=[_node("n1", [_device("d1")])], pools=[_pool("p1")], + lvols=[_lvol("l1"), _lvol("l2")]) + body = _scrape(db) + self.assertEqual(body.count('lvol_read_bytes{'), 2, "one series per volume") + self.assertEqual(body.count('device_read_bytes{'), 1) + self.assertEqual(body.count('pool_read_bytes{'), 1) + + +class TestNoSeriesLeak(unittest.TestCase): + + def test_deleted_volume_disappears_from_the_next_scrape(self): + nodes, pools = [_node("n1", [_device("d1")])], [_pool("p1")] + before = _scrape(_fake_db(nodes, pools, [_lvol("keep"), _lvol("doomed")])) + self.assertIn("doomed", before) + + # "doomed" is deleted; the very next scrape must not mention it. + after = _scrape(_fake_db(nodes, pools, [_lvol("keep")])) + self.assertIn("keep", after) + self.assertNotIn("doomed", after, + "deleted volume still exported -- the series leak is back") + + def test_payload_does_not_grow_across_repeated_scrapes(self): + """The leak showed up in production as a monotonically growing payload + (+~7 MB/day). Same entities in, same bytes out, every time.""" + db = _fake_db(nodes=[_node("n1", [_device("d1")])], pools=[_pool("p1")], + lvols=[_lvol("l1"), _lvol("l2")]) + sizes = {len(_scrape(db)) for _ in range(4)} + self.assertEqual(len(sizes), 1, f"payload size drifted across scrapes: {sizes}") + + def test_churn_does_not_accumulate(self): + """147 volumes came and went in 3 h on the affected cluster. Replaying + that shape must leave the exposition the size of the live set.""" + nodes, pools = [_node("n1", [_device("d1")])], [_pool("p1")] + baseline = len(_scrape(_fake_db(nodes, pools, [_lvol("live-1"), _lvol("live-2")]))) + for i in range(20): # 20 generations of ephemeral volumes + _scrape(_fake_db(nodes, pools, [_lvol("live-1"), _lvol("live-2"), _lvol(f"tmp-{i}")])) + after = len(_scrape(_fake_db(nodes, pools, [_lvol("live-1"), _lvol("live-2")]))) + self.assertEqual(after, baseline, + "exposition grew after volume churn -- entities are being retained") + + def test_no_module_level_registry(self): + """Drift guard: a registry (or gauge dict) at module scope is exactly + what made deleted entities immortal. It must not come back.""" + from prometheus_client import CollectorRegistry, Gauge + for name, value in vars(metrics).items(): + self.assertNotIsInstance( + value, CollectorRegistry, + f"module-level CollectorRegistry '{name}' reintroduces the leak") + self.assertNotIsInstance( + value, Gauge, + f"module-level Gauge '{name}' reintroduces the leak") + + +class TestAbsentValuesStayAbsent(unittest.TestCase): + """prometheus_client creates the child series on .labels(), and an un-set + child exports as 0. So .labels() must only be called once a value is known + -- otherwise a metric with no source value silently reads as a real zero.""" + + def test_metrics_missing_from_the_stats_row_are_not_exported_as_zero(self): + db = _fake_db(nodes=[_node("n1", [_device("d1")])], pools=[_pool("p1")], + lvols=[_lvol("l1")]) + # A stats row that only carries read_bytes: nothing else has a value. + sparse = MagicMock() + sparse.get_clean_dict.return_value = {"read_bytes": 7} + db.get_lvol_stats.return_value = [sparse] + + body = _scrape(db) + self.assertIn('lvol_read_bytes{', body) + self.assertNotIn('lvol_write_bytes{', body, + "absent stat exported as 0 -- would read as real data in Grafana") + + def test_cpu_gauges_are_not_zero_filled_from_the_node_stats_loop(self): + """cpu_busy_percentage/cpu_core_utilization are set from reactor data, + not from the node stats row; the stats loop must skip them rather than + create an empty child for the node label set.""" + db = _fake_db(nodes=[_node("n1", [_device("d1")])], pools=[], lvols=[]) + body = _scrape(db) + # Only the per-thread / per-core label sets, never a bare node-level one. + self.assertNotIn('snode_cpu_busy_percentage{cluster="cl-1",cluster_name="test-cluster",' + 'hostname="host-n1",snode="n1"}', body) + self.assertEqual(body.count('snode_cpu_busy_percentage{'), 2) + + +class TestCpuMetrics(unittest.TestCase): + + def test_one_core_utilization_series_per_reactor(self): + """The reactor walk used to sit inside the per-gauge-name loop, so it + re-walked every reactor ~33x per node. One series per core, per node.""" + db = _fake_db(nodes=[_node("n1", [_device("d1")])], pools=[], lvols=[]) + body = _scrape(db) + self.assertEqual(body.count('snode_cpu_core_utilization{'), 2, "two reactors -> two series") + self.assertEqual(body.count('snode_cpu_busy_percentage{'), 2, "two threads -> two series") + + def test_busy_percentage_is_computed_from_thread_and_core_cycles(self): + db = _fake_db(nodes=[_node("n1", [_device("d1")])], pools=[], lvols=[]) + body = _scrape(db) + # thread 1 busy=50, core busy+idle = 200 -> 25% + self.assertIn('thread_name="app_thread"} 25.0', body) + + +class TestHealthCheckNotApplicable(unittest.TestCase): + """health_check is Optional[bool]; None means "not applicable". Gauge.set(None) + raises TypeError, which would have failed the entire scrape.""" + + def test_none_health_check_reports_nan_instead_of_failing(self): + db = _fake_db( + nodes=[_node("n1", [_device("d1", health_check=None)], health_check=None)], + pools=[_pool("p1")], + lvols=[_lvol("l1", health_check=None)], + ) + body = _scrape(db) # must not raise TypeError + for metric in ("snode_health_check{", "device_health_check{", "lvol_health_check{"): + line = next(ln for ln in body.splitlines() if ln.startswith(metric)) + self.assertTrue(math.isnan(float(line.rsplit(" ", 1)[1])), + f"{metric} should be NaN when not applicable, got: {line}")