55import time
66import dateparser
77import sys
8+ import os
89from retrying import retry
10+ import bz2
911
1012# set up logging
1113import logging
@@ -55,7 +57,7 @@ def get_current_metric_value(self, metric_name, label_config = None):
5557 query = metric_name + "{" + "," .join (label_list ) + "}"
5658 else :
5759 query = metric_name
58-
60+
5961 response = requests .get ('{0}/api/v1/query' .format (self .url ), # using the query API to get raw data
6062 params = {'query' : query },#label_config},
6163 verify = False , # Disable ssl certificate verification temporarily
@@ -72,7 +74,7 @@ def get_current_metric_value(self, metric_name, label_config = None):
7274 return (data )
7375
7476 @retry (stop_max_attempt_number = MAX_REQUEST_RETRIES , wait_fixed = CONNECTION_RETRY_WAIT_TIME )
75- def get_metric_range_data (self , metric_name , start_time , end_time = 'now' , chunk_size = None ,label_config = None ):
77+ def get_metric_range_data (self , metric_name , start_time , end_time = 'now' , chunk_size = None ,label_config = None , store_locally = False ):
7678 data = []
7779
7880 start = int (dateparser .parse (str (start_time )).timestamp ())
@@ -110,5 +112,44 @@ def get_metric_range_data(self, metric_name, start_time, end_time='now', chunk_s
110112 requests .status_codes ._codes [response .status_code ][0 ],
111113 response .content
112114 ))
115+ if store_locally :
116+ # store it locally
117+ self .store_metric_values_local (metric_name , (response .json ()['data' ]['result' ]), start + chunk_seconds )
118+
113119 start += chunk_seconds
114120 return (data )
121+
122+ def store_metric_values_local (self , metric_name , values , end_timestamp , file_path = None , compressed = True ):
123+ '''
124+ Function to store metrics locally
125+ '''
126+ if not values :
127+ return "No values for {}" .format (metric_name )
128+
129+ if not file_path :
130+ file_path = self ._metric_filename (metric_name , end_timestamp )
131+
132+ if compressed :
133+ payload = bz2 .compress (str (values ).encode ('utf-8' ))
134+ file_path = file_path + ".bz2"
135+ else :
136+ payload = (str (values ).encode ('utf-8' ))
137+
138+ os .makedirs (os .path .dirname (file_path ), exist_ok = True )
139+ with open (file_path , "wb" ) as file :
140+ file .write (payload )
141+
142+ def _metric_filename (self , metric_name , end_timestamp ):
143+ '''
144+ Adds a timestamp to the filename before it is stored
145+ '''
146+ end_timestamp = dateparser .parse (str (end_timestamp ))
147+ directory_name = end_timestamp .strftime ("%Y%m%d" )
148+ timestamp = end_timestamp .strftime ("%Y%m%d%H%M" )
149+ object_path = "./metrics/" + self .prometheus_host + "/" + metric_name + "/" + directory_name + "/" + timestamp + ".json"
150+ return object_path
151+
152+ def pretty_print_metric (self , metric_data ):
153+ data = metric_data
154+ for metric in data :
155+ print (json .dumps (metric , indent = 4 , sort_keys = True ))
0 commit comments