1 from __future__ import print_function
6 from requests.exceptions import HTTPError
9 #LABELS = [ 'irate(http_requests_total{code="200"}[1m])', 'collectd_cpu_percent{job="collectd", exported_instance="an11-31"}[1m]' ]
10 #LABELS = ['irate(collectd_cpufreq{exported_instance="otconap7",cpufreq="1"}[2m])', 'go_info']
11 API_VERSION = '/api/v1/query'
12 LIST_OF_ENV_VARIABLES = ["PROMETHEUS_SERVER_URL"]
13 MAP_ENV_VARIABLES = dict()
14 #MAP_ENV_VARIABLES['PROMETHEUS_SERVER_URL']='http://172.25.103.1:30090' #to be deleted
15 LOG = logging.getLogger(__name__)
18 logging.basicConfig(format='%(asctime)s ::%(filename)s :: %(funcName)s :: %(levelname)s :: %(message)s',
19 datefmt='%m-%d-%Y %I:%M:%S%p',
21 filename='promql_api.log',
23 LOG.info("Set the log configs.")
26 def load_and_validate_env_vars(list_of_env_vars):
27 LOG.info("Loading the env variables ...")
28 for env_var in list_of_env_vars:
29 if env_var in environ:
30 LOG.info("Found env variable: {} ".format(env_var.upper()))
31 MAP_ENV_VARIABLES[env_var.upper()] = environ.get(env_var)
33 #MAP_ENV_VARIABLES['PROMETHEUS_SERVER_URL']='http://172.25.103.1:30090' # to be deleted
34 LOG.error("Env var: {} not found ! ".format(env_var.upper()))
35 raise KeyError("Env variable: {} not found ! ".format(env_var.upper()))
38 def query_m3db(LABELS):
41 LABELS : a list of the LABELS
43 returns a list of result sets of different labels
46 LOG.info("Forming the get request ...")
47 list_of_substrings = []
49 list_of_result_sets = []
50 list_of_substrings.append(MAP_ENV_VARIABLES['PROMETHEUS_SERVER_URL'])
51 list_of_substrings.append(API_VERSION)
52 url = ''.join(list_of_substrings)
54 for each_label in LABELS:
55 params_map['query'] = each_label
57 LOG.info('API request::: URL: {} '.format(url))
58 LOG.info('API request::: params: {} '.format(params_map))
59 response = requests.get(url, params=params_map)
60 response.raise_for_status()
61 except HTTPError as http_err:
62 print(f'HTTP error occurred: {http_err}')
64 except Exception as err:
65 print(f'Other error occurred: {err}')
69 results = response.json()['data']['result']
70 LOG.info('::::::::::RESULTS::::::::::::: {}'.format(each_label))
71 for each_result in results:
73 list_of_result_sets.append(results)
74 return list_of_result_sets
79 # load_and_validate_env_vars(LIST_OF_ENV_VARIABLES)
82 # if __name__ == "__main__":