Skip to content

Commit 3aff9fe

Browse files
committed
Add an exec promql command to execute promql against any cluster
1 parent a8a5766 commit 3aff9fe

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

deployer/__main__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import deployer.commands.deployer # noqa: F401
77
import deployer.commands.exec.cloud # noqa: F401
88
import deployer.commands.exec.infra_components # noqa: F401
9+
import deployer.commands.exec.promql # noqa: F401
910
import deployer.commands.generate.billing.cost_table # noqa: F401
1011
import deployer.commands.generate.cryptnono_config # noqa: F401
1112
import deployer.commands.generate.dedicated_cluster.aws # noqa: F401

deployer/commands/exec/promql.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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

Comments
 (0)