Skip to content

Commit a408b2a

Browse files
committed
Use prometheus_client parser and address review feedback
Replace custom regex parser with prometheus_client.parser, apply removeprefix/removesuffix cleanup, and add request timeout.
1 parent e9f000d commit a408b2a

2 files changed

Lines changed: 6 additions & 25 deletions

File tree

tests/metrics.py

Lines changed: 5 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
import re
2-
31
import requests
2+
from prometheus_client.parser import text_string_to_metric_families
43

54

65
class MetricsSnapshot:
@@ -20,35 +19,16 @@ class MetricsSnapshot:
2019

2120
_PREFIX = "stackrox_fact_"
2221
_TOTAL_SUFFIX = "_total"
23-
_LINE_RE = re.compile(
24-
r'^(?P<name>\S+?)(?:\{(?P<labels>[^}]*)\})?\s+(?P<value>\S+)$'
25-
)
26-
_LABEL_RE = re.compile(r'(\w+)="([^"]*)"')
2722

2823
def __init__(self, text):
2924
self._entries = []
30-
for line in text.splitlines():
31-
if line.startswith('#') or not line.strip():
32-
continue
33-
34-
m = self._LINE_RE.match(line)
35-
if not m:
36-
continue
37-
38-
name, raw, labels = m.group('name', 'value', 'labels')
39-
40-
value = float(raw) if '.' in raw else int(raw)
41-
labels = dict(self._LABEL_RE.findall(labels or ''))
42-
43-
self._entries.append((name, labels, value))
25+
for family in text_string_to_metric_families(text):
26+
for sample in family.samples:
27+
self._entries.append((sample.name, sample.labels, sample.value))
4428

4529
@classmethod
4630
def _normalize(cls, name):
47-
if name.startswith(cls._PREFIX):
48-
name = name[len(cls._PREFIX):]
49-
if name.endswith(cls._TOTAL_SUFFIX):
50-
name = name[:-len(cls._TOTAL_SUFFIX)]
51-
return name
31+
return name.removeprefix(cls._PREFIX).removesuffix(cls._TOTAL_SUFFIX)
5232

5333
def get(self, metric, **labels):
5434
"""

tests/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
docker==7.1.0
22
grpcio==1.76.0
33
grpcio-tools==1.76.0
4+
prometheus-client==0.22.1
45
pytest==8.4.1
56
requests==2.32.4
67
pyyaml==6.0.3

0 commit comments

Comments
 (0)