Skip to content

Commit 922d9e4

Browse files
author
Anand Sanmukhani
committed
Format using black
No code changes
1 parent 6e3f0ef commit 922d9e4

File tree

1 file changed

+81
-71
lines changed

1 file changed

+81
-71
lines changed

prometheus_api_client/prometheus_connect.py

Lines changed: 81 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -31,19 +31,19 @@ class PrometheusConnect:
3131
for the http requests made to the prometheus host
3232
"""
3333

34-
def __init__(self, url: str = 'http://127.0.0.1:9090',
35-
headers: dict = None, disable_ssl: bool = False):
34+
def __init__(
35+
self, url: str = "http://127.0.0.1:9090", headers: dict = None, disable_ssl: bool = False
36+
):
3637
"""
3738
Constructor for the class PrometheusConnect
3839
"""
3940
self.headers = headers
4041
self.url = url
4142
self.prometheus_host = urlparse(self.url).netloc
4243
self._all_metrics = None
43-
self.ssl_verification = (not disable_ssl)
44+
self.ssl_verification = not disable_ssl
4445

45-
@retry(stop_max_attempt_number=MAX_REQUEST_RETRIES,
46-
wait_fixed=CONNECTION_RETRY_WAIT_TIME)
46+
@retry(stop_max_attempt_number=MAX_REQUEST_RETRIES, wait_fixed=CONNECTION_RETRY_WAIT_TIME)
4747
def all_metrics(self, params: dict = None):
4848
"""
4949
Get the list of all the metrics that the prometheus host scrapes
@@ -55,24 +55,25 @@ def all_metrics(self, params: dict = None):
5555
:raises: (Http Response error) Raises an exception in case of a connection error
5656
"""
5757
params = params or {}
58-
response = requests.get('{0}/api/v1/label/__name__/values'.format(self.url),
59-
verify=self.ssl_verification,
60-
headers=self.headers,
61-
params=params,)
58+
response = requests.get(
59+
"{0}/api/v1/label/__name__/values".format(self.url),
60+
verify=self.ssl_verification,
61+
headers=self.headers,
62+
params=params,
63+
)
6264

6365
if response.status_code == 200:
64-
self._all_metrics = response.json()['data']
66+
self._all_metrics = response.json()["data"]
6567
else:
66-
raise Exception("HTTP Status Code {} ({})".format(
67-
response.status_code,
68-
response.content
69-
))
68+
raise Exception(
69+
"HTTP Status Code {} ({})".format(response.status_code, response.content)
70+
)
7071
return self._all_metrics
7172

72-
@retry(stop_max_attempt_number=MAX_REQUEST_RETRIES,
73-
wait_fixed=CONNECTION_RETRY_WAIT_TIME)
73+
@retry(stop_max_attempt_number=MAX_REQUEST_RETRIES, wait_fixed=CONNECTION_RETRY_WAIT_TIME)
7474
def get_current_metric_value(
75-
self, metric_name: str, label_config: dict = None, params: dict = None):
75+
self, metric_name: str, label_config: dict = None, params: dict = None
76+
):
7677
"""
7778
A method to get the current metric value for the specified metric
7879
and label configuration.
@@ -95,38 +96,39 @@ def get_current_metric_value(
9596
params = params or {}
9697
data = []
9798
if label_config:
98-
label_list = [str(key + "=" + "'" + label_config[key] + "'")
99-
for key in label_config]
99+
label_list = [str(key + "=" + "'" + label_config[key] + "'") for key in label_config]
100100
# print(label_list)
101101
query = metric_name + "{" + ",".join(label_list) + "}"
102102
else:
103103
query = metric_name
104104

105105
# using the query API to get raw data
106-
response = requests.get('{0}/api/v1/query'.format(self.url),
107-
params={**{"query": query}, **params},
108-
verify=self.ssl_verification,
109-
headers=self.headers)
106+
response = requests.get(
107+
"{0}/api/v1/query".format(self.url),
108+
params={**{"query": query}, **params},
109+
verify=self.ssl_verification,
110+
headers=self.headers,
111+
)
110112

111113
if response.status_code == 200:
112-
data += response.json()['data']['result']
114+
data += response.json()["data"]["result"]
113115
else:
114-
raise Exception("HTTP Status Code {} ({})".format(
115-
response.status_code,
116-
response.content
117-
))
116+
raise Exception(
117+
"HTTP Status Code {} ({})".format(response.status_code, response.content)
118+
)
118119
return data
119120

120-
@retry(stop_max_attempt_number=MAX_REQUEST_RETRIES,
121-
wait_fixed=CONNECTION_RETRY_WAIT_TIME)
122-
def get_metric_range_data(self,
123-
metric_name: str,
124-
label_config: dict = None,
125-
start_time: str = '10m',
126-
end_time: str = 'now',
127-
chunk_size: str = None,
128-
store_locally: bool = False,
129-
params: dict = None):
121+
@retry(stop_max_attempt_number=MAX_REQUEST_RETRIES, wait_fixed=CONNECTION_RETRY_WAIT_TIME)
122+
def get_metric_range_data(
123+
self,
124+
metric_name: str,
125+
label_config: dict = None,
126+
start_time: str = "10m",
127+
end_time: str = "now",
128+
chunk_size: str = None,
129+
store_locally: bool = False,
130+
params: dict = None,
131+
):
130132
"""
131133
A method to get the current metric value for the specified metric
132134
and label configuration.
@@ -157,48 +159,49 @@ def get_metric_range_data(self,
157159
chunk_seconds = int(end - start)
158160
chunk_size = str(int(chunk_seconds)) + "s"
159161
else:
160-
chunk_seconds = (int(round((dateparser.parse('now') -
161-
dateparser.parse(chunk_size)
162-
).total_seconds())))
162+
chunk_seconds = int(
163+
round((dateparser.parse("now") - dateparser.parse(chunk_size)).total_seconds())
164+
)
163165

164166
if int(end - start) < chunk_seconds:
165167
sys.exit("specified chunk_size is too big")
166168

167169
if label_config:
168-
label_list = [str(key + "=" + "'" + label_config[key] + "'")
169-
for key in label_config]
170+
label_list = [str(key + "=" + "'" + label_config[key] + "'") for key in label_config]
170171
# print(label_list)
171172
query = metric_name + "{" + ",".join(label_list) + "}"
172173
else:
173174
query = metric_name
174175

175176
while start < end:
176177
# using the query API to get raw data
177-
response = requests.get('{0}/api/v1/query'.format(self.url),
178-
params={**{'query': query + '[' + chunk_size + ']',
179-
'time': start + chunk_seconds
180-
}, **params},
181-
verify=self.ssl_verification,
182-
headers=self.headers)
178+
response = requests.get(
179+
"{0}/api/v1/query".format(self.url),
180+
params={
181+
**{"query": query + "[" + chunk_size + "]", "time": start + chunk_seconds},
182+
**params,
183+
},
184+
verify=self.ssl_verification,
185+
headers=self.headers,
186+
)
183187
if response.status_code == 200:
184-
data += response.json()['data']['result']
188+
data += response.json()["data"]["result"]
185189
else:
186-
raise Exception("HTTP Status Code {} ({})".format(
187-
response.status_code,
188-
response.content
189-
))
190+
raise Exception(
191+
"HTTP Status Code {} ({})".format(response.status_code, response.content)
192+
)
190193
if store_locally:
191194
# store it locally
192-
self._store_metric_values_local(metric_name,
193-
json.dumps(
194-
response.json()['data']['result']),
195-
start + chunk_seconds)
195+
self._store_metric_values_local(
196+
metric_name,
197+
json.dumps(response.json()["data"]["result"]),
198+
start + chunk_seconds,
199+
)
196200

197201
start += chunk_seconds
198202
return data
199203

200-
def _store_metric_values_local(
201-
self, metric_name, values, end_timestamp, compressed=False):
204+
def _store_metric_values_local(self, metric_name, values, end_timestamp, compressed=False):
202205
"""
203206
Store metrics on the local filesystem, optionally with bz2 compression
204207
@@ -215,10 +218,10 @@ def _store_metric_values_local(
215218
file_path = self._metric_filename(metric_name, end_timestamp)
216219

217220
if compressed:
218-
payload = bz2.compress(str(values).encode('utf-8'))
221+
payload = bz2.compress(str(values).encode("utf-8"))
219222
file_path = file_path + ".bz2"
220223
else:
221-
payload = (str(values).encode('utf-8'))
224+
payload = str(values).encode("utf-8")
222225

223226
os.makedirs(os.path.dirname(file_path), exist_ok=True)
224227
with open(file_path, "wb") as file:
@@ -237,12 +240,20 @@ def _metric_filename(self, metric_name: str, end_timestamp: str):
237240
end_timestamp = dateparser.parse(str(end_timestamp))
238241
directory_name = end_timestamp.strftime("%Y%m%d")
239242
timestamp = end_timestamp.strftime("%Y%m%d%H%M")
240-
object_path = "./metrics/" + self.prometheus_host + "/" + \
241-
metric_name + "/" + directory_name + "/" + timestamp + ".json"
243+
object_path = (
244+
"./metrics/"
245+
+ self.prometheus_host
246+
+ "/"
247+
+ metric_name
248+
+ "/"
249+
+ directory_name
250+
+ "/"
251+
+ timestamp
252+
+ ".json"
253+
)
242254
return object_path
243255

244-
@retry(stop_max_attempt_number=MAX_REQUEST_RETRIES,
245-
wait_fixed=CONNECTION_RETRY_WAIT_TIME)
256+
@retry(stop_max_attempt_number=MAX_REQUEST_RETRIES, wait_fixed=CONNECTION_RETRY_WAIT_TIME)
246257
def custom_query(self, query: str, params: dict = None):
247258
"""
248259
A method to send a custom query to a Prometheus Host.
@@ -268,12 +279,11 @@ def custom_query(self, query: str, params: dict = None):
268279
headers=self.headers,
269280
)
270281
if response.status_code == 200:
271-
data = response.json()['data']['result']
282+
data = response.json()["data"]["result"]
272283
else:
273-
raise Exception("HTTP Status Code {} ({})".format(
274-
response.status_code,
275-
response.content
276-
))
284+
raise Exception(
285+
"HTTP Status Code {} ({})".format(response.status_code, response.content)
286+
)
277287

278288
return data
279289

0 commit comments

Comments
 (0)