@@ -31,19 +31,19 @@ class PrometheusConnect:
31
31
for the http requests made to the prometheus host
32
32
"""
33
33
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
+ ):
36
37
"""
37
38
Constructor for the class PrometheusConnect
38
39
"""
39
40
self .headers = headers
40
41
self .url = url
41
42
self .prometheus_host = urlparse (self .url ).netloc
42
43
self ._all_metrics = None
43
- self .ssl_verification = ( not disable_ssl )
44
+ self .ssl_verification = not disable_ssl
44
45
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 )
47
47
def all_metrics (self , params : dict = None ):
48
48
"""
49
49
Get the list of all the metrics that the prometheus host scrapes
@@ -55,24 +55,25 @@ def all_metrics(self, params: dict = None):
55
55
:raises: (Http Response error) Raises an exception in case of a connection error
56
56
"""
57
57
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
+ )
62
64
63
65
if response .status_code == 200 :
64
- self ._all_metrics = response .json ()[' data' ]
66
+ self ._all_metrics = response .json ()[" data" ]
65
67
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
+ )
70
71
return self ._all_metrics
71
72
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 )
74
74
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
+ ):
76
77
"""
77
78
A method to get the current metric value for the specified metric
78
79
and label configuration.
@@ -95,38 +96,39 @@ def get_current_metric_value(
95
96
params = params or {}
96
97
data = []
97
98
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 ]
100
100
# print(label_list)
101
101
query = metric_name + "{" + "," .join (label_list ) + "}"
102
102
else :
103
103
query = metric_name
104
104
105
105
# 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
+ )
110
112
111
113
if response .status_code == 200 :
112
- data += response .json ()[' data' ][ ' result' ]
114
+ data += response .json ()[" data" ][ " result" ]
113
115
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
+ )
118
119
return data
119
120
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
+ ):
130
132
"""
131
133
A method to get the current metric value for the specified metric
132
134
and label configuration.
@@ -157,48 +159,49 @@ def get_metric_range_data(self,
157
159
chunk_seconds = int (end - start )
158
160
chunk_size = str (int (chunk_seconds )) + "s"
159
161
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
+ )
163
165
164
166
if int (end - start ) < chunk_seconds :
165
167
sys .exit ("specified chunk_size is too big" )
166
168
167
169
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 ]
170
171
# print(label_list)
171
172
query = metric_name + "{" + "," .join (label_list ) + "}"
172
173
else :
173
174
query = metric_name
174
175
175
176
while start < end :
176
177
# 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
+ )
183
187
if response .status_code == 200 :
184
- data += response .json ()[' data' ][ ' result' ]
188
+ data += response .json ()[" data" ][ " result" ]
185
189
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
+ )
190
193
if store_locally :
191
194
# 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
+ )
196
200
197
201
start += chunk_seconds
198
202
return data
199
203
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 ):
202
205
"""
203
206
Store metrics on the local filesystem, optionally with bz2 compression
204
207
@@ -215,10 +218,10 @@ def _store_metric_values_local(
215
218
file_path = self ._metric_filename (metric_name , end_timestamp )
216
219
217
220
if compressed :
218
- payload = bz2 .compress (str (values ).encode (' utf-8' ))
221
+ payload = bz2 .compress (str (values ).encode (" utf-8" ))
219
222
file_path = file_path + ".bz2"
220
223
else :
221
- payload = ( str (values ).encode (' utf-8' ) )
224
+ payload = str (values ).encode (" utf-8" )
222
225
223
226
os .makedirs (os .path .dirname (file_path ), exist_ok = True )
224
227
with open (file_path , "wb" ) as file :
@@ -237,12 +240,20 @@ def _metric_filename(self, metric_name: str, end_timestamp: str):
237
240
end_timestamp = dateparser .parse (str (end_timestamp ))
238
241
directory_name = end_timestamp .strftime ("%Y%m%d" )
239
242
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
+ )
242
254
return object_path
243
255
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 )
246
257
def custom_query (self , query : str , params : dict = None ):
247
258
"""
248
259
A method to send a custom query to a Prometheus Host.
@@ -268,12 +279,11 @@ def custom_query(self, query: str, params: dict = None):
268
279
headers = self .headers ,
269
280
)
270
281
if response .status_code == 200 :
271
- data = response .json ()[' data' ][ ' result' ]
282
+ data = response .json ()[" data" ][ " result" ]
272
283
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
+ )
277
287
278
288
return data
279
289
0 commit comments