Skip to content

Commit 07bc4d5

Browse files
author
Anand Sanmukhani
committed
Add a method in class PrometheusConnect for making custom queries to Prometheus.
Fix some documentation
1 parent 5701a4b commit 07bc4d5

File tree

1 file changed

+55
-14
lines changed

1 file changed

+55
-14
lines changed

prometheus_connect/prometheus_connect.py

Lines changed: 55 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# set up logging
1515
_LOGGER = logging.getLogger(__name__)
1616

17-
DEBUG = False
17+
# In case of a connection failure try 2 more times
1818
MAX_REQUEST_RETRIES = 3
1919
CONNECTION_RETRY_WAIT_TIME = 1000 # wait 1 second before retrying in case of an error
2020

@@ -24,9 +24,7 @@ class PrometheusConnect:
2424
"""
2525
def __init__(self, url='http://127.0.0.1:9090', headers=None, disable_ssl=False):
2626
"""
27-
A short description.
28-
29-
A bit longer description.
27+
Constructor for the class PrometheusConnect
3028
3129
Args:
3230
url (str): url for the prometheus host
@@ -50,10 +48,8 @@ def all_metrics(self):
5048
list: list of names of all the metrics available from the specified prometheus host
5149
5250
Raises:
53-
Exception: description
54-
51+
Http Response error: Raises an exception in case of a connection error
5552
"""
56-
5753
response = requests.get('{0}/api/v1/label/__name__/values'.format(self.url),
5854
verify=self.ssl_verification,
5955
headers=self.headers)
@@ -88,9 +84,7 @@ def get_current_metric_value(self, metric_name, label_config=None):
8884
8985
Raises:
9086
Http Response error: Raises an exception in case of a connection error
91-
9287
"""
93-
9488
data = []
9589
if label_config:
9690
label_list = [str(key+"="+ "'" + label_config[key]+ "'") for key in label_config]
@@ -135,8 +129,21 @@ def get_metric_range_data(self,
135129
Args:
136130
metric_name (str): The name of the metric
137131
label_config (dict): A dictionary that specifies metric labels and their values
138-
start_time (str):
139-
end_time (str):
132+
start_time (str): A string that specifies the metric range start time.
133+
It uses the dateparser (https://dateparser.readthedocs.io/en/v0.3.4/)
134+
module.
135+
Example:
136+
start_time='15m' will set the start time to
137+
15 mins before the current time
138+
start_time='1553092437' will set the start time
139+
to the given unix timestamp
140+
start_time='12 May 2018' will set the start time to
141+
'2018-05-12 00:00:00'
142+
end_time (str): A string that specifies the metric range end time.
143+
It follows the same rules as parameter start_time, it just
144+
needs to be a time later than the start_time.
145+
Example:
146+
end_time='now' will set the end time to the current time
140147
chunk_size (str): Duration of metric data downloaded in one request.
141148
example, setting it to '3h' will download 3 hours
142149
worth of data in each request made to the prometheus host
@@ -148,7 +155,6 @@ def get_metric_range_data(self,
148155
149156
Raises:
150157
Http Response error: Raises an exception in case of a connection error
151-
152158
"""
153159
data = []
154160

@@ -230,15 +236,50 @@ def _metric_filename(self, metric_name, end_timestamp):
230236
metric_name + "/" + directory_name + "/" + timestamp + ".json"
231237
return object_path
232238

239+
@retry(stop_max_attempt_number=MAX_REQUEST_RETRIES, wait_fixed=CONNECTION_RETRY_WAIT_TIME)
240+
def custom_query(self, query: str):
241+
"""
242+
A method to send a custom query to a Prometheus Host.
243+
244+
This method takes as input a string which will be sent as a query to
245+
the specified Prometheus Host. This query is a PromQL query.
246+
247+
Args:
248+
query (str): This is a PromQL query, a few examples can be found
249+
at https://prometheus.io/docs/prometheus/latest/querying/examples/
250+
251+
Returns:
252+
list: A list of metric data received in response of the query sent
253+
254+
Raises:
255+
Http Response error: Raises an exception in case of a connection error
256+
"""
257+
data = None
258+
query = str(query)
259+
# using the query API to get raw data
260+
response = requests.get('{0}/api/v1/query'.format(self.url),
261+
params={'query': query
262+
},
263+
verify=self.ssl_verification,
264+
headers=self.headers)
265+
if response.status_code == 200:
266+
data = response.json()['data']['result']
267+
else:
268+
raise Exception("HTTP Status Code {} ({})".format(
269+
response.status_code,
270+
response.content
271+
))
272+
273+
return data
274+
233275
def pretty_print_metric(metric_data):
234276
"""
235277
A function to pretty print the metric data downloaded using class PrometheusConnect.
236278
237279
Args:
238-
metric_data (list): This is the metric data returned from functions
280+
metric_data (list): This is the metric data list returned from methods
239281
get_metric_range_data and get_current_metric_value
240282
"""
241-
242283
data = metric_data
243284
for metric in data:
244285
print(json.dumps(metric, indent=4, sort_keys=True))

0 commit comments

Comments
 (0)