Handle more error scenarios for promql_api
[demo.git] / vnfs / DAaaS / lib / promql_api / prom_ql_api.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2019 Intel Corporation Intellectual Property
3 #
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
7 #
8 #       http://www.apache.org/licenses/LICENSE-2.0
9 #
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.
15 #
16 # -------------------------------------------------------------------------
17
18
19 from __future__ import print_function
20 from os import environ
21 import logging
22 import requests
23 from requests.exceptions import HTTPError
24
25
26 API_VERSION = '/api/v1/query'
27 LIST_OF_ENV_VARIABLES = ["DATA_ENDPOINT"]
28 MAP_ENV_VARIABLES = dict()
29 LOG = logging.getLogger(__name__)
30
31
32 def set_log_config():
33     logging.basicConfig(format='%(asctime)s ::%(filename)s :: %(funcName)s :: %(levelname)s :: %(message)s',
34                     datefmt='%m-%d-%Y %I:%M:%S%p',
35                     level=logging.DEBUG,
36                     filename='promql_api.log',
37                     filemode='w')
38     LOG.info("Set the log configs.")
39
40
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)
47         else:
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()))
51
52
53 def query(QUERY_STRING):
54     """
55     Input parameters:
56         QUERY_STRING : a list of the query strings like ['irate(collectd_cpufreq{exported_instance="otconap7",cpufreq="1"}[2m])']
57     Return:
58         returns a list of  result sets corresponding to each of the query strings..
59         SAMPLE O/P:
60         [{'metric': {'cpufreq': '1',
61              'endpoint': 'collectd-prometheus',
62              'exported_instance': 'otconap7',
63              'instance': '172.25.103.1:9103',
64              'job': 'collectd',
65              'namespace': 'edge1',
66              'pod': 'plundering-liger-collectd-wz7xg',
67              'service': 'collectd'},
68         'value': [1559177169.415, '119727200']}]
69     """
70     set_log_config()
71     load_and_validate_env_vars(LIST_OF_ENV_VARIABLES)
72     LOG.info("Forming the get request ...")
73     list_of_substrings = []
74     params_map = {}
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)
79
80     for each_query_string in QUERY_STRING:
81         params_map['query'] = each_query_string
82         try:
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}')
95
96         except Exception as err:
97             print(f'Check logs..Other error occurred: {err}')
98
99         else:
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']}))
107             else:
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