-
Notifications
You must be signed in to change notification settings - Fork 110
feat(must-gather): add Prometheus analysis #136
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
Merged
openshift-merge-bot
merged 10 commits into
openshift-eng:main
from
simonpasquier:add-prometheus-must-gather
Nov 12, 2025
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
d76d384
feat(must-gather): add Prometheus analysis
simonpasquier 40491c2
Address review comments
simonpasquier fc67306
Remove unused import
simonpasquier 08418fb
Avoid KeyError exceptions
simonpasquier dbfbe7e
Fix interpolation
simonpasquier 47b6676
Update plugins/must-gather/skills/must-gather-analyzer/scripts/analyz…
simonpasquier 9aeb04a
Fix bug
simonpasquier 10a05cb
Apply suggestion from @coderabbitai[bot]
simonpasquier f4b7247
Fix more bugs from CodeRabbit
simonpasquier b7193e4
Merge remote-tracking branch 'fork/add-prometheus-must-gather' into a…
simonpasquier 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
Some comments aren't visible on the classic Files Changed page.
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
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
117 changes: 117 additions & 0 deletions
117
plugins/must-gather/skills/must-gather-analyzer/scripts/analyze_prometheus.py
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,117 @@ | ||
| #!/usr/bin/env python3 | ||
| """ | ||
| Analyze Prometheus data from must-gather data. | ||
| Shows Prometheus status, targets, and active alerts. | ||
| """ | ||
|
|
||
| import sys | ||
| import os | ||
| import json | ||
| import argparse | ||
| from pathlib import Path | ||
| from typing import List, Dict, Any, Optional | ||
|
|
||
| def parse_json_file(file_path: Path) -> Optional[Dict[str, Any]]: | ||
| """Parse a JSON file.""" | ||
| try: | ||
| with open(file_path, 'r', encoding='utf-8') as f: | ||
| doc = json.load(f) | ||
| return doc | ||
| except (FileNotFoundError, json.JSONDecodeError, OSError) as e: | ||
| print(f"Error: Failed to parse {file_path}: {e}", file=sys.stderr) | ||
| return None | ||
|
|
||
| def print_alerts_table(alerts): | ||
| """Print alerts in a table format.""" | ||
| if not alerts: | ||
| print("No alerts found.") | ||
| return | ||
|
|
||
| print("ALERTS") | ||
| print(f"{'STATE':<10} {'NAMESPACE':<50} {'NAME':<50} {'SEVERITY':<10} {'SINCE':<20} LABELS") | ||
|
|
||
| for alert in alerts: | ||
| state = alert.get('state', '') | ||
| since = alert.get('activeAt', '')[:19] + 'Z' # timestamps are always UTC. | ||
| labels = alert.get('labels', {}) | ||
| namespace = labels.pop('namespace', '')[:50] | ||
| name = labels.pop('alertname', '')[:50] | ||
| severity = labels.pop('severity', '')[:10] | ||
|
|
||
| print(f"{state:<10} {namespace:<50} {name:<50} {severity:<10} {since:<20} {labels}") | ||
|
|
||
|
|
||
| def analyze_prometheus(must_gather_path: str, namespace: Optional[str] = None): | ||
| """Analyze Prometheus data in a must-gather directory.""" | ||
| base_path = Path(must_gather_path) | ||
|
|
||
| # Retrieve active alerts. | ||
| rules_path = base_path / "monitoring" / "prometheus" / "rules.json" | ||
| rules = parse_json_file(rules_path) | ||
|
|
||
| if rules is None: | ||
| return 1 | ||
| status = rules.get("status", "") | ||
| if status != "success": | ||
| print(f"{rules_path}: unexpected status {status}", file=sys.stderr) | ||
| return 1 | ||
|
|
||
| if "data" not in rules or "groups" not in rules["data"]: | ||
| print(f"Error: Unexpected JSON structure in {rules_path}", file=sys.stderr) | ||
| return 1 | ||
|
|
||
| alerts = [] | ||
| for group in rules["data"]["groups"]: | ||
| for rule in group["rules"]: | ||
| if rule["type"] == 'alerting' and rule["state"] != 'inactive': | ||
| for alert in rule["alerts"]: | ||
| if namespace is None or namespace == '': | ||
| alerts.append(alert) | ||
| elif alert.get('labels', {}).get('namespace', '') == namespace: | ||
| alerts.append(alert) | ||
|
|
||
| # Sort alerts by namespace, alertname and severity. | ||
| alerts.sort(key=lambda x: (x.get('labels', {}).get('namespace', ''), x.get('labels', {}).get('alertname', ''), x.get('labels', {}).get('severity', ''))) | ||
|
|
||
| # Print results | ||
| print_alerts_table(alerts) | ||
|
|
||
| # Summary | ||
| total_alerts = len(alerts) | ||
| pending = sum(1 for alert in alerts if alert.get('state') == 'pending') | ||
| firing = sum(1 for alert in alerts if alert.get('state') == 'firing') | ||
|
|
||
| print(f"\n{'='*80}") | ||
| print(f"SUMMARY") | ||
| print(f"Active alerts: {total_alerts} total ({pending} pending, {firing} firing)") | ||
| print(f"{'='*80}") | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return 0 | ||
|
|
||
|
|
||
| def main(): | ||
| parser = argparse.ArgumentParser( | ||
| description='Analyze Prometheus data from must-gather data', | ||
| formatter_class=argparse.RawDescriptionHelpFormatter, | ||
| epilog=""" | ||
| Examples: | ||
| %(prog)s ./must-gather | ||
| %(prog)s ./must-gather --namespace openshift-monitoring | ||
| """ | ||
| ) | ||
|
|
||
| parser.add_argument('must_gather_path', help='Path to must-gather directory') | ||
| parser.add_argument('-n', '--namespace', help='Filter information by namespace') | ||
|
|
||
| args = parser.parse_args() | ||
|
|
||
| if not os.path.isdir(args.must_gather_path): | ||
| print(f"Error: Directory not found: {args.must_gather_path}", file=sys.stderr) | ||
| return 1 | ||
|
|
||
| return analyze_prometheus(args.must_gather_path, args.namespace) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| sys.exit(main()) | ||
|
|
||
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.
Uh oh!
There was an error while loading. Please reload this page.