-
Notifications
You must be signed in to change notification settings - Fork 4
Adds metrics helper test fixture #514
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Stringy
wants to merge
3
commits into
main
Choose a base branch
from
giles/metrics-test-utils
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+143
−122
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| import requests | ||
| from prometheus_client.parser import text_string_to_metric_families | ||
|
|
||
|
|
||
| class MetricsSnapshot: | ||
| """ | ||
| A parsed snapshot of Prometheus/OpenMetrics metrics. | ||
|
|
||
| Supports querying by metric name and labels: | ||
|
|
||
| ss = metrics.snapshot() | ||
| assert ss.get("rate_limiter_events", label="Dropped") == 5 | ||
| assert ss.get("bpf_events", label="Added") > 0 | ||
|
|
||
| Metric names are matched without the "stackrox_fact_" prefix and | ||
| "_total" counter suffix, so "rate_limiter_events" matches | ||
| "stackrox_fact_rate_limiter_events_total". | ||
| """ | ||
|
|
||
| _PREFIX = "stackrox_fact_" | ||
| _TOTAL_SUFFIX = "_total" | ||
|
|
||
| def __init__(self, text): | ||
| self._entries = [] | ||
| for family in text_string_to_metric_families(text): | ||
| for sample in family.samples: | ||
| self._entries.append((sample.name, sample.labels, sample.value)) | ||
|
|
||
| @classmethod | ||
| def _normalize(cls, name): | ||
| return name.removeprefix(cls._PREFIX).removesuffix(cls._TOTAL_SUFFIX) | ||
|
|
||
| def get(self, metric, **labels): | ||
| """ | ||
| Get the value of a metric, optionally filtered by labels. | ||
|
|
||
| Args: | ||
| metric: Metric name, with or without the "stackrox_fact_" | ||
| prefix and "_total" suffix. | ||
| **labels: Label key=value pairs to match. | ||
|
|
||
| Returns: | ||
| The metric value as int or float. | ||
|
|
||
| Raises: | ||
| KeyError: If no matching metric is found. | ||
| ValueError: If multiple metrics match. | ||
| """ | ||
| target = self._normalize(metric) | ||
| matches = [] | ||
| for name, entry_labels, value in self._entries: | ||
| if self._normalize(name) != target: | ||
| continue | ||
| if all(entry_labels.get(k) == v for k, v in labels.items()): | ||
| matches.append(value) | ||
|
|
||
| if not matches: | ||
| label_desc = ', '.join(f'{k}="{v}"' for k, v in labels.items()) | ||
| key = f'{metric}{{{label_desc}}}' if label_desc else metric | ||
| available = '\n '.join( | ||
| f'{n} {ls} = {v}' for n, ls, v in self._entries | ||
| ) | ||
| raise KeyError( | ||
| f'metric {key!r} not found. Available:\n {available}' | ||
| ) | ||
| if len(matches) > 1: | ||
| raise ValueError( | ||
| f'{metric} matched {len(matches)} entries; use labels to ' | ||
| f'narrow the result' | ||
| ) | ||
| return matches[0] | ||
|
|
||
| def get_all(self, metric, **labels): | ||
| """Like get(), but returns a list of all matching values.""" | ||
| target = self._normalize(metric) | ||
| return [ | ||
| value for name, entry_labels, value in self._entries | ||
| if self._normalize(name) == target | ||
| and all(entry_labels.get(k) == v for k, v in labels.items()) | ||
| ] | ||
|
|
||
|
|
||
| class MetricsClient: | ||
| """Fetches metrics snapshots from a FACT endpoint.""" | ||
|
|
||
| def __init__(self, address): | ||
| self._url = f'http://{address}/metrics' | ||
|
|
||
| def snapshot(self, timeout=30): | ||
| resp = requests.get(self._url, timeout=timeout) | ||
| resp.raise_for_status() | ||
| return MetricsSnapshot(resp.text) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,7 @@ | ||
| docker==7.1.0 | ||
| grpcio==1.76.0 | ||
| grpcio-tools==1.76.0 | ||
| prometheus-client==0.22.1 | ||
| pytest==8.4.1 | ||
| requests==2.32.4 | ||
| pyyaml==6.0.3 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Have you considered using the parser included in the prometheus
client_pythonpackage instead of building our own? https://prometheus.github.io/client_python/parser/If you have and still decided to build our own I'll take a closer look at the code in this file.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was not aware of its existence. I'll update to use it