1 from __future__ import print_function
5 from requests.exceptions import HTTPError
9 API_VERSION = '/api/v1/query'
10 LIST_OF_ENV_VARIABLES = ["DATA_ENDPOINT"]
11 MAP_ENV_VARIABLES = dict()
12 LOG = logging.getLogger(__name__)
15 logging.basicConfig(format='%(asctime)s ::%(filename)s :: %(funcName)s :: %(levelname)s :: %(message)s',
16 datefmt='%m-%d-%Y %I:%M:%S%p',
18 filename='promql_api.log',
20 LOG.info("Set the log configs.")
23 def load_and_validate_env_vars(list_of_env_vars):
24 LOG.info("Loading the env variables ...")
25 for env_var in list_of_env_vars:
26 if env_var in environ:
27 LOG.info("Found env variable: {} ".format(env_var.upper()))
28 MAP_ENV_VARIABLES[env_var.upper()] = environ.get(env_var)
30 #MAP_ENV_VARIABLES['DATA_ENDPOINT']='http://127.0.0.1:30090' # to be deleted
31 LOG.error("Env var: {} not found ! ".format(env_var.upper()))
32 raise KeyError("Env variable: {} not found ! ".format(env_var.upper()))
38 LABELS : a list of the LABELS like ['irate(collectd_cpufreq{exported_instance="otconap7",cpufreq="1"}[2m])']
40 returns a list of result sets of different labels.
42 [{'metric': {'cpufreq': '1',
43 'endpoint': 'collectd-prometheus',
44 'exported_instance': 'otconap7',
45 'instance': '172.25.103.1:9103',
48 'pod': 'plundering-liger-collectd-wz7xg',
49 'service': 'collectd'},
50 'value': [1559177169.415, '119727200']}]
53 load_and_validate_env_vars(LIST_OF_ENV_VARIABLES)
54 LOG.info("Forming the get request ...")
55 list_of_substrings = []
57 list_of_result_sets = []
58 list_of_substrings.append(MAP_ENV_VARIABLES['DATA_ENDPOINT'])
59 list_of_substrings.append(API_VERSION)
60 url = ''.join(list_of_substrings)
62 for each_label in LABELS:
63 params_map['query'] = each_label
65 LOG.info('API request::: URL: {} '.format(url))
66 LOG.info('API request::: params: {} '.format(params_map))
67 response = requests.get(url, params=params_map)
68 response.raise_for_status()
69 except HTTPError as http_err:
70 print(f'HTTP error occurred: {http_err}')
72 except Exception as err:
73 print(f'Other error occurred: {err}')
77 results = response.json()['data']['result']
78 LOG.info('::::::::::RESULTS::::::::::::: {}'.format(each_label))
79 for each_result in results:
81 list_of_result_sets.append(results)
82 return list_of_result_sets