1 # -------------------------------------------------------------------------
2 # Copyright (c) 2019 Intel Corporation Intellectual Property
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
16 # -------------------------------------------------------------------------
19 from __future__ import print_function
20 from os import environ
23 from requests.exceptions import HTTPError
26 API_VERSION = '/api/v1/query'
27 LIST_OF_ENV_VARIABLES = ["DATA_ENDPOINT"]
28 MAP_ENV_VARIABLES = dict()
29 LOG = logging.getLogger(__name__)
33 logging.basicConfig(format='%(asctime)s ::%(filename)s :: %(funcName)s :: %(levelname)s :: %(message)s',
34 datefmt='%m-%d-%Y %I:%M:%S%p',
36 filename='promql_api.log',
38 LOG.info("Set the log configs.")
41 def load_and_validate_env_vars(list_of_env_vars):
42 LOG.info("Loading the env variables ...")
43 for env_var in list_of_env_vars:
44 if env_var in environ:
45 LOG.info("Found env variable: {} ".format(env_var.upper()))
46 MAP_ENV_VARIABLES[env_var.upper()] = environ.get(env_var)
48 #MAP_ENV_VARIABLES['DATA_ENDPOINT']='http://127.0.0.1:30090' # to be deleted
49 LOG.error("Env var: {} not found ! ".format(env_var.upper()))
50 raise KeyError("Env variable: {} not found ! ".format(env_var.upper()))
53 def query(QUERY_STRING):
56 QUERY_STRING : a list of the query strings like ['irate(collectd_cpufreq{exported_instance="otconap7",cpufreq="1"}[2m])']
58 returns a list of result sets corresponding to each of the query strings..
60 [{'metric': {'cpufreq': '1',
61 'endpoint': 'collectd-prometheus',
62 'exported_instance': 'otconap7',
63 'instance': '172.25.103.1:9103',
66 'pod': 'plundering-liger-collectd-wz7xg',
67 'service': 'collectd'},
68 'value': [1559177169.415, '119727200']}]
71 load_and_validate_env_vars(LIST_OF_ENV_VARIABLES)
72 LOG.info("Forming the get request ...")
73 list_of_substrings = []
75 list_of_result_sets = []
76 list_of_substrings.append(MAP_ENV_VARIABLES['DATA_ENDPOINT'])
77 list_of_substrings.append(API_VERSION)
78 url = ''.join(list_of_substrings)
80 for each_query_string in QUERY_STRING:
81 params_map['query'] = each_query_string
83 LOG.info('API request::: URL: {} '.format(url))
84 LOG.info('API request::: params: {} '.format(params_map))
85 response = requests.get(url, params=params_map)
86 response.raise_for_status() # This might raise HTTPError which is handled in except block
87 except HTTPError as http_err:
88 if response.json()['status'] == "error":
89 LOG.error("::::ERROR OCCURED::::")
90 LOG.error("::::ERROR TYPE:::: {}".format(response.json()['errorType']))
91 LOG.error("::::ERROR:::: {}".format(response.json()['error']))
92 list_of_result_sets.append(dict({'error':response.json()['error'],
93 'errorType' : response.json()['errorType']}))
94 print(f'Check logs..HTTP error occurred: {http_err}')
96 except Exception as err:
97 print(f'Check logs..Other error occurred: {err}')
100 if response.json()['status'] == "error":
101 LOG.error("::::ERROR OCCURED!::::")
102 LOG.error("::::ERROR TYPE:::: {}".format(response.json()['errorType']))
103 LOG.error("::::ERROR:::: {}".format(response.json()['error']))
104 list_of_result_sets.append(response.json()['error'])
105 list_of_result_sets.append(dict({'error':response.json()['error'],
106 'errorType' : response.json()['errorType']}))
108 results = response.json()['data']['result']
109 LOG.info('::::::::::RESULTS::::::::::::: {}'.format(each_query_string))
110 for each_result in results:
111 LOG.info(each_result)
112 list_of_result_sets.append(results)
113 return list_of_result_sets