Add vFW and vLB HPA files from Casablanca
[demo.git] / vnfs / DAaaS / lib / promql_api / prom_ql_api.py
1 from __future__ import print_function
2 from os import environ
3 import logging
4 import requests
5 from requests.exceptions import HTTPError
6
7
8
9 API_VERSION = '/api/v1/query'
10 LIST_OF_ENV_VARIABLES = ["DATA_ENDPOINT"]
11 MAP_ENV_VARIABLES = dict()
12 LOG = logging.getLogger(__name__)
13
14 def set_log_config():
15     logging.basicConfig(format='%(asctime)s ::%(filename)s :: %(funcName)s :: %(levelname)s :: %(message)s',
16                     datefmt='%m-%d-%Y %I:%M:%S%p',
17                     level=logging.DEBUG,
18                     filename='promql_api.log',
19                     filemode='w')
20     LOG.info("Set the log configs.")
21
22
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)
29         else:
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()))
33
34
35 def query(LABELS):
36     """
37     Input parameters:
38         LABELS : a list of the LABELS like ['irate(collectd_cpufreq{exported_instance="otconap7",cpufreq="1"}[2m])']
39     Return:
40         returns a list of  result sets of different labels.
41         SAMPLE O/P:
42         [{'metric': {'cpufreq': '1',
43              'endpoint': 'collectd-prometheus',
44              'exported_instance': 'otconap7',
45              'instance': '172.25.103.1:9103',
46              'job': 'collectd',
47              'namespace': 'edge1',
48              'pod': 'plundering-liger-collectd-wz7xg',
49              'service': 'collectd'},
50         'value': [1559177169.415, '119727200']}]
51     """
52     set_log_config()
53     load_and_validate_env_vars(LIST_OF_ENV_VARIABLES)
54     LOG.info("Forming the get request ...")
55     list_of_substrings = []
56     params_map = {}
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)
61
62     for each_label in LABELS:
63         params_map['query'] = each_label
64         try:
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}')
71             return None
72         except Exception as err:
73             print(f'Other error occurred: {err}')
74             return None
75         else:
76
77             results = response.json()['data']['result']
78             LOG.info('::::::::::RESULTS::::::::::::: {}'.format(each_label))
79             for each_result in results:
80                 LOG.info(each_result)
81             list_of_result_sets.append(results)
82     return list_of_result_sets