|
| 1 | +from urllib.parse import urlparse |
| 2 | +import requests |
| 3 | +import datetime |
| 4 | +import json |
| 5 | +import time |
| 6 | +import dateparser |
| 7 | +import sys |
| 8 | +from retrying import retry |
| 9 | + |
| 10 | +# set up logging |
| 11 | +import logging |
| 12 | +_LOGGER = logging.getLogger(__name__) |
| 13 | + |
| 14 | +# Disable SSL warnings |
| 15 | +from requests.packages.urllib3.exceptions import InsecureRequestWarning |
| 16 | +requests.packages.urllib3.disable_warnings(InsecureRequestWarning) |
| 17 | + |
| 18 | +DEBUG = False |
| 19 | +MAX_REQUEST_RETRIES = 3 |
| 20 | +CONNECTION_RETRY_WAIT_TIME = 1000 # wait 1 second before retrying in case of an error |
| 21 | + |
| 22 | +class PrometheusConnect: |
| 23 | + """docstring for Prometheus.""" |
| 24 | + def __init__(self, url='', token=None): |
| 25 | + self.headers = { 'Authorization': "bearer {}".format(token) } |
| 26 | + self.url = url |
| 27 | + self.prometheus_host = urlparse(self.url).netloc |
| 28 | + self._all_metrics = None |
| 29 | + |
| 30 | + @retry(stop_max_attempt_number=MAX_REQUEST_RETRIES, wait_fixed=CONNECTION_RETRY_WAIT_TIME) |
| 31 | + def all_metrics(self): |
| 32 | + ''' |
| 33 | + Get the list of all the metrics that the prometheus host has |
| 34 | + ''' |
| 35 | + response = requests.get('{0}/api/v1/label/__name__/values'.format(self.url), |
| 36 | + verify=False, # Disable ssl certificate verification temporarily |
| 37 | + headers=self.headers) |
| 38 | + |
| 39 | + if response.status_code == 200: |
| 40 | + self._all_metrics = response.json()['data'] |
| 41 | + else: |
| 42 | + raise Exception("HTTP Status Code {} {} ({})".format( |
| 43 | + response.status_code, |
| 44 | + requests.status_codes._codes[response.status_code][0], |
| 45 | + response.content |
| 46 | + )) |
| 47 | + return self._all_metrics |
| 48 | + |
| 49 | + @retry(stop_max_attempt_number=MAX_REQUEST_RETRIES, wait_fixed=CONNECTION_RETRY_WAIT_TIME) |
| 50 | + def get_current_metric_value(self, metric_name, label_config = None): |
| 51 | + data = [] |
| 52 | + if label_config: |
| 53 | + label_list = [str(key+"="+ "'" + label_config[key]+ "'") for key in label_config] |
| 54 | + # print(label_list) |
| 55 | + query = metric_name + "{" + ",".join(label_list) + "}" |
| 56 | + else: |
| 57 | + query = metric_name |
| 58 | + |
| 59 | + if response.status_code == 200: |
| 60 | + data += response.json()['data']['result'] |
| 61 | + else: |
| 62 | + raise Exception("HTTP Status Code {} {} ({})".format( |
| 63 | + response.status_code, |
| 64 | + requests.status_codes._codes[response.status_code][0], |
| 65 | + response.content |
| 66 | + )) |
| 67 | + return (data) |
| 68 | + |
| 69 | + @retry(stop_max_attempt_number=MAX_REQUEST_RETRIES, wait_fixed=CONNECTION_RETRY_WAIT_TIME) |
| 70 | + def get_metric_range_data(self, metric_name, start_time, end_time='now', chunk_size=None,label_config=None): |
| 71 | + data = [] |
| 72 | + |
| 73 | + start = int(dateparser.parse(str(start_time)).timestamp()) |
| 74 | + end = int(dateparser.parse(str(end_time)).timestamp()) |
| 75 | + |
| 76 | + if not chunk_size: |
| 77 | + chunk_seconds = int(end - start) |
| 78 | + chunk_size = str(int(chunk_seconds)) + "s" |
| 79 | + else: |
| 80 | + chunk_seconds = int(round((dateparser.parse('now') - dateparser.parse(chunk_size)).total_seconds())) |
| 81 | + |
| 82 | + if int(end-start) < chunk_seconds: |
| 83 | + sys.exit("specified chunk_size is too big") |
| 84 | + |
| 85 | + if label_config: |
| 86 | + label_list = [str(key+"="+ "'" + label_config[key]+ "'") for key in label_config] |
| 87 | + # print(label_list) |
| 88 | + query = metric_name + "{" + ",".join(label_list) + "}" |
| 89 | + else: |
| 90 | + query = metric_name |
| 91 | + |
| 92 | + while start < end: |
| 93 | + # print(chunk_size) |
| 94 | + response = requests.get('{0}/api/v1/query'.format(self.url), # using the query API to get raw data |
| 95 | + params={'query': query + '[' + chunk_size + ']', |
| 96 | + 'time': start + chunk_seconds |
| 97 | + }, |
| 98 | + verify=False, # Disable ssl certificate verification temporarily |
| 99 | + headers=self.headers) |
| 100 | + if response.status_code == 200: |
| 101 | + data += response.json()['data']['result'] |
| 102 | + else: |
| 103 | + raise Exception("HTTP Status Code {} {} ({})".format( |
| 104 | + response.status_code, |
| 105 | + requests.status_codes._codes[response.status_code][0], |
| 106 | + response.content |
| 107 | + )) |
| 108 | + start += chunk_seconds |
| 109 | + return (data) |
0 commit comments