Add vFW and vLB HPA files from Casablanca
[demo.git] / vnfs / DAaaS / sample-apps / m3db_promql / promql_api / prom_ql_api.py
1 from __future__ import print_function
2 from os import environ
3 import logging
4 import sysconfig
5 import requests
6 from requests.exceptions import HTTPError
7
8
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__)
16
17 def set_log_config():
18     logging.basicConfig(format='%(asctime)s ::%(filename)s :: %(funcName)s :: %(levelname)s :: %(message)s', 
19                     datefmt='%m-%d-%Y %I:%M:%S%p',
20                     level=logging.DEBUG, 
21                     filename='promql_api.log',
22                     filemode='w')
23     LOG.info("Set the log configs.")
24
25
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)
32         else:
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()))
36
37
38 def query_m3db(LABELS):
39     """
40     Input parameters:
41         LABELS : a list of the LABELS
42     Return:
43         returns a list of  result sets of different labels
44     """
45
46     LOG.info("Forming the get request ...")
47     list_of_substrings = []
48     params_map = {}
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)
53     
54     for each_label in LABELS:
55         params_map['query'] = each_label
56         try:
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}')
63             return None  
64         except Exception as err:
65             print(f'Other error occurred: {err}')
66             return None 
67         else:
68             
69             results = response.json()['data']['result']
70             LOG.info('::::::::::RESULTS::::::::::::: {}'.format(each_label))
71             for each_result in results:
72                 LOG.info(each_result)
73             list_of_result_sets.append(results)
74     return list_of_result_sets
75
76
77 # def main():
78 #     set_log_config()
79 #     load_and_validate_env_vars(LIST_OF_ENV_VARIABLES)
80 #     query_m3db(LABELS)
81
82 # if __name__ == "__main__":
83 #     main()