Handle more error scenarios for promql_api
[demo.git] / vnfs / DAaaS / lib / promql_api / prom_ql_api.py
index 970d241..8a5ce50 100644 (file)
@@ -1,3 +1,21 @@
+# -------------------------------------------------------------------------
+#   Copyright (c) 2019 Intel Corporation Intellectual Property
+#
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an "AS IS" BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+#
+# -------------------------------------------------------------------------
+
+
 from __future__ import print_function
 from os import environ
 import logging
@@ -5,12 +23,12 @@ import requests
 from requests.exceptions import HTTPError
 
 
-
 API_VERSION = '/api/v1/query'
 LIST_OF_ENV_VARIABLES = ["DATA_ENDPOINT"]
 MAP_ENV_VARIABLES = dict()
 LOG = logging.getLogger(__name__)
 
+
 def set_log_config():
     logging.basicConfig(format='%(asctime)s ::%(filename)s :: %(funcName)s :: %(levelname)s :: %(message)s',
                     datefmt='%m-%d-%Y %I:%M:%S%p',
@@ -32,12 +50,12 @@ def load_and_validate_env_vars(list_of_env_vars):
             raise KeyError("Env variable: {} not found ! ".format(env_var.upper()))
 
 
-def query(LABELS):
+def query(QUERY_STRING):
     """
     Input parameters:
-        LABELS : a list of the LABELS like ['irate(collectd_cpufreq{exported_instance="otconap7",cpufreq="1"}[2m])']
+        QUERY_STRING : a list of the query strings like ['irate(collectd_cpufreq{exported_instance="otconap7",cpufreq="1"}[2m])']
     Return:
-        returns a list of  result sets of different labels.
+        returns a list of  result sets corresponding to each of the query strings..
         SAMPLE O/P:
         [{'metric': {'cpufreq': '1',
              'endpoint': 'collectd-prometheus',
@@ -59,24 +77,37 @@ def query(LABELS):
     list_of_substrings.append(API_VERSION)
     url = ''.join(list_of_substrings)
 
-    for each_label in LABELS:
-        params_map['query'] = each_label
+    for each_query_string in QUERY_STRING:
+        params_map['query'] = each_query_string
         try:
             LOG.info('API request::: URL: {} '.format(url))
             LOG.info('API request::: params: {} '.format(params_map))
             response = requests.get(url, params=params_map)
-            response.raise_for_status()
+            response.raise_for_status() # This might raise HTTPError which is handled in except block
         except HTTPError as http_err:
-            print(f'HTTP error occurred: {http_err}')
-            return None
+            if response.json()['status'] == "error":
+                LOG.error("::::ERROR OCCURED::::")
+                LOG.error("::::ERROR TYPE:::: {}".format(response.json()['errorType']))
+                LOG.error("::::ERROR:::: {}".format(response.json()['error']))
+                list_of_result_sets.append(dict({'error':response.json()['error'],
+                                                'errorType' : response.json()['errorType']}))
+            print(f'Check logs..HTTP error occurred: {http_err}')
+
         except Exception as err:
-            print(f'Other error occurred: {err}')
-            return None
-        else:
+            print(f'Check logs..Other error occurred: {err}')
 
-            results = response.json()['data']['result']
-            LOG.info('::::::::::RESULTS::::::::::::: {}'.format(each_label))
-            for each_result in results:
-                LOG.info(each_result)
-            list_of_result_sets.append(results)
+        else:
+            if response.json()['status'] == "error":
+                LOG.error("::::ERROR OCCURED!::::")
+                LOG.error("::::ERROR TYPE:::: {}".format(response.json()['errorType']))
+                LOG.error("::::ERROR:::: {}".format(response.json()['error']))
+                list_of_result_sets.append(response.json()['error'])
+                list_of_result_sets.append(dict({'error':response.json()['error'],
+                                                'errorType' : response.json()['errorType']}))
+            else:
+                results = response.json()['data']['result']
+                LOG.info('::::::::::RESULTS::::::::::::: {}'.format(each_query_string))
+                for each_result in results:
+                    LOG.info(each_result)
+                list_of_result_sets.append(results)
     return list_of_result_sets