|
| 1 | +import re |
| 2 | + |
| 3 | +import requests |
| 4 | + |
| 5 | + |
| 6 | +class MetricsSnapshot: |
| 7 | + """ |
| 8 | + A parsed snapshot of Prometheus/OpenMetrics metrics. |
| 9 | +
|
| 10 | + Supports querying by metric name and labels: |
| 11 | +
|
| 12 | + ss = metrics.snapshot() |
| 13 | + assert ss.get("rate_limiter_events", label="Dropped") == 5 |
| 14 | + assert ss.get("bpf_events", label="Added") > 0 |
| 15 | +
|
| 16 | + Metric names are matched without the "stackrox_fact_" prefix and |
| 17 | + "_total" counter suffix, so "rate_limiter_events" matches |
| 18 | + "stackrox_fact_rate_limiter_events_total". |
| 19 | + """ |
| 20 | + |
| 21 | + _PREFIX = "stackrox_fact_" |
| 22 | + _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+)="([^"]*)"') |
| 27 | + |
| 28 | + def __init__(self, text): |
| 29 | + 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)) |
| 44 | + |
| 45 | + @classmethod |
| 46 | + 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 |
| 52 | + |
| 53 | + def get(self, metric, **labels): |
| 54 | + """ |
| 55 | + Get the value of a metric, optionally filtered by labels. |
| 56 | +
|
| 57 | + Args: |
| 58 | + metric: Metric name, with or without the "stackrox_fact_" |
| 59 | + prefix and "_total" suffix. |
| 60 | + **labels: Label key=value pairs to match. |
| 61 | +
|
| 62 | + Returns: |
| 63 | + The metric value as int or float. |
| 64 | +
|
| 65 | + Raises: |
| 66 | + KeyError: If no matching metric is found. |
| 67 | + ValueError: If multiple metrics match. |
| 68 | + """ |
| 69 | + target = self._normalize(metric) |
| 70 | + matches = [] |
| 71 | + for name, entry_labels, value in self._entries: |
| 72 | + if self._normalize(name) != target: |
| 73 | + continue |
| 74 | + if all(entry_labels.get(k) == v for k, v in labels.items()): |
| 75 | + matches.append(value) |
| 76 | + |
| 77 | + if not matches: |
| 78 | + label_desc = ', '.join(f'{k}="{v}"' for k, v in labels.items()) |
| 79 | + key = f'{metric}{{{label_desc}}}' if label_desc else metric |
| 80 | + available = '\n '.join( |
| 81 | + f'{n} {ls} = {v}' for n, ls, v in self._entries |
| 82 | + ) |
| 83 | + raise KeyError( |
| 84 | + f'metric {key!r} not found. Available:\n {available}' |
| 85 | + ) |
| 86 | + if len(matches) > 1: |
| 87 | + raise ValueError( |
| 88 | + f'{metric} matched {len(matches)} entries; use labels to ' |
| 89 | + f'narrow the result' |
| 90 | + ) |
| 91 | + return matches[0] |
| 92 | + |
| 93 | + def get_all(self, metric, **labels): |
| 94 | + """Like get(), but returns a list of all matching values.""" |
| 95 | + target = self._normalize(metric) |
| 96 | + return [ |
| 97 | + value for name, entry_labels, value in self._entries |
| 98 | + if self._normalize(name) == target |
| 99 | + and all(entry_labels.get(k) == v for k, v in labels.items()) |
| 100 | + ] |
| 101 | + |
| 102 | + |
| 103 | +class MetricsClient: |
| 104 | + """Fetches metrics snapshots from a FACT endpoint.""" |
| 105 | + |
| 106 | + def __init__(self, address): |
| 107 | + self._url = f'http://{address}/metrics' |
| 108 | + |
| 109 | + def snapshot(self, timeout=30): |
| 110 | + resp = requests.get(self._url, timeout=timeout) |
| 111 | + resp.raise_for_status() |
| 112 | + return MetricsSnapshot(resp.text) |
0 commit comments