Created
July 19, 2024 09:53
-
-
Save akunzai/da9f5a0d638fe53f1cb811245530a065 to your computer and use it in GitHub Desktop.
List Prometheus targets status
This file contains 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
#!/usr/bin/env python3 | |
import json | |
import sys | |
import urllib.request | |
from urllib.error import URLError | |
import textwrap | |
def fetch_targets(prometheus_url): | |
try: | |
with urllib.request.urlopen(f"{prometheus_url}/api/v1/targets") as response: | |
return json.loads(response.read().decode('utf-8')) | |
except URLError as e: | |
print(f"Error fetching data: {e}", file=sys.stderr) | |
sys.exit(1) | |
def parse_targets(data): | |
targets = [] | |
for target in data['data']['activeTargets']: | |
targets.append({ | |
'job': target['labels'].get('job', 'N/A'), | |
'instance': target['labels'].get('instance', 'N/A'), | |
'state': target['health'], | |
'lastError': target.get('lastError', '') | |
}) | |
return targets | |
def print_table(targets): | |
job_width = max(20, max(len(t['job']) for t in targets)) | |
instance_width = max(30, max(len(t['instance']) for t in targets)) | |
state_width = 10 | |
error_width = 50 | |
header = f"{'Job':<{job_width}} {'Instance':<{instance_width}} {'State':<{state_width}} {'Last Error':<{error_width}}" | |
print(header) | |
print("-" * len(header)) | |
for target in targets: | |
job = target['job'] | |
instance = target['instance'] | |
state = target['state'] | |
error = target['lastError'] | |
print(f"{job:<{job_width}} {instance:<{instance_width}} {state:<{state_width}}", end=" ") | |
if error: | |
wrapped_error = textwrap.wrap(error, width=error_width) | |
print(wrapped_error[0]) | |
for line in wrapped_error[1:]: | |
print(f"{'':<{job_width + instance_width + state_width + 3}}{line}") | |
else: | |
print() | |
def main(): | |
prometheus_url = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:9090" | |
data = fetch_targets(prometheus_url) | |
targets = parse_targets(data) | |
print_table(targets) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment