|
| 1 | +import json |
| 2 | + |
| 3 | +import requests |
| 4 | +import typer |
| 5 | +from rich.console import Console |
| 6 | +from rich.table import Table |
| 7 | +from ruamel.yaml import YAML |
| 8 | +from yarl import URL |
| 9 | + |
| 10 | +from deployer.cli_app import exec_app |
| 11 | +from deployer.infra_components.cluster import Cluster |
| 12 | + |
| 13 | +# Without `pure=True`, I get an exception about str / byte issues |
| 14 | +yaml = YAML(typ="safe", pure=True) |
| 15 | + |
| 16 | + |
| 17 | +@exec_app.command() |
| 18 | +def promql( |
| 19 | + cluster_name: str = typer.Argument(help="Name of the Cluster to Query"), |
| 20 | + query: str = typer.Argument(help="PromQL query to execute"), |
| 21 | + output_json: bool = typer.Option( |
| 22 | + False, "--json", help="Output JSON rather than pretty table" |
| 23 | + ), |
| 24 | +): |
| 25 | + """ |
| 26 | + Execute a PromQL query against a cluster's prometheus instance |
| 27 | + """ |
| 28 | + |
| 29 | + cluster = Cluster.from_name(cluster_name) |
| 30 | + |
| 31 | + promql_api = URL(f"{cluster.get_external_prometheus_url()}/api/v1/query") |
| 32 | + |
| 33 | + query_api = promql_api.with_query({"query": query}) |
| 34 | + |
| 35 | + resp = requests.get(str(query_api), auth=cluster.get_cluster_prometheus_creds()) |
| 36 | + resp.raise_for_status() |
| 37 | + |
| 38 | + result = resp.json()["data"]["result"] |
| 39 | + |
| 40 | + if output_json: |
| 41 | + data = [] |
| 42 | + for entry in result: |
| 43 | + row = entry["metric"].copy() |
| 44 | + row["value"] = entry["value"][1] |
| 45 | + data.append(row) |
| 46 | + |
| 47 | + print(json.dumps(data)) |
| 48 | + else: |
| 49 | + if len(result) == 0: |
| 50 | + print("No data returned") |
| 51 | + |
| 52 | + column_names = list(result[0]["metric"].keys()) |
| 53 | + |
| 54 | + table = Table() |
| 55 | + for cn in column_names: |
| 56 | + table.add_column(cn, justify="left") |
| 57 | + table.add_column("value", justify="right", no_wrap=True) |
| 58 | + |
| 59 | + for entry in result: |
| 60 | + row = [] |
| 61 | + for cn in column_names: |
| 62 | + row.append(entry["metric"][cn]) |
| 63 | + row.append(entry["value"][1]) |
| 64 | + table.add_row(*row) |
| 65 | + |
| 66 | + Console().print(table) |
0 commit comments