|
| 1 | +from dataclasses import dataclass |
| 2 | +from fastapi.responses import HTMLResponse |
| 3 | +from prometheus_api_client import PrometheusConnect |
| 4 | +from fastapi import FastAPI, Request |
| 5 | +from fastapi.templating import Jinja2Templates |
| 6 | +from fastapi.staticfiles import StaticFiles |
| 7 | +import uvicorn |
| 8 | +from flags import get_args |
| 9 | +import json |
| 10 | +import time |
| 11 | +import threading |
| 12 | +import os |
| 13 | +from datetime import datetime, timedelta |
| 14 | +import pytz |
| 15 | +import requests |
| 16 | + |
| 17 | + |
| 18 | + |
| 19 | +app = FastAPI() |
| 20 | + |
| 21 | +pacific_tz = pytz.timezone('US/Pacific') |
| 22 | + |
| 23 | +templates = Jinja2Templates(directory="templates") |
| 24 | + |
| 25 | +args = get_args() |
| 26 | + |
| 27 | +prom = PrometheusConnect(url = args.promurl, disable_ssl=True)#this will query "http://prometheus:9090/api/v1/query?query=up" |
| 28 | + |
| 29 | +metrics_data = [] |
| 30 | +up_hours = 24 |
| 31 | + |
| 32 | +@dataclass |
| 33 | +class metrics: |
| 34 | + job_name: str |
| 35 | + timestamp: float |
| 36 | + value: float |
| 37 | + |
| 38 | +def check_status(query): |
| 39 | + params = {"query" : query} |
| 40 | + try: |
| 41 | + response = requests.get("http://prometheus:9090/api/v1/query", params = params) |
| 42 | + response.raise_for_status()# Raise an error for HTTP issues |
| 43 | + json_response = response.json() |
| 44 | + if json_response["status"]=="success": |
| 45 | + return True |
| 46 | + elif json_response["status"]==None: |
| 47 | + print("the status key does not exist!") |
| 48 | + return False |
| 49 | + else: |
| 50 | + return False |
| 51 | + |
| 52 | + except Exception as e: |
| 53 | + print(f"Error querying Prometheus: {e}") |
| 54 | + return None |
| 55 | + |
| 56 | +def polling_loop(interval, config): |
| 57 | + while True: |
| 58 | + global metrics_data |
| 59 | + metrics_data = [] |
| 60 | + for hosts in config: |
| 61 | + service_name = hosts["job-id"] |
| 62 | + prom_query = hosts["query"] |
| 63 | + if prom_query == "up": |
| 64 | + process_up_query(prom_query, service_name) |
| 65 | + time.sleep(interval) |
| 66 | + |
| 67 | +service_data = {} |
| 68 | + |
| 69 | +def process_up_query(query, service_name): |
| 70 | + global metrics_data, service_data |
| 71 | + process_time_query("time() - process_start_time_seconds", service_name) |
| 72 | + if not check_status(query="up"): |
| 73 | + print("status is not success, please look into it!!") |
| 74 | + try: |
| 75 | + result = prom.custom_query(query=query) |
| 76 | + if not result: |
| 77 | + print(f"No results for query: {query}") |
| 78 | + last_active = datetime.now(pacific_tz).strftime("%Y-%m-%d %H:%M:%S %Z") |
| 79 | + metrics_data.append({ |
| 80 | + "instance": service_name, |
| 81 | + "status": "Error in querying" |
| 82 | + }) |
| 83 | + return |
| 84 | + |
| 85 | + for metric in result: |
| 86 | + job_name = metric.get('metric',{}).get('job', "")#for later use in dataclass |
| 87 | + time_stamp = metric.get('value', [])[0]#for later use in dataclass |
| 88 | + value = metric.get('value', [])[1] |
| 89 | + # last_active = datetime.now(pacific_tz).strftime("%Y-%m-%d %H:%M:%S %Z") |
| 90 | + status = "Healthy" if float(value) > 0 else "Unhealthy" |
| 91 | + if status == "Unhealthy": |
| 92 | + current = get_first_match_time(prom=prom, prom_query="up", match_value=0, hours=up_hours) |
| 93 | + metrics_data.append({ |
| 94 | + "instance": service_name, |
| 95 | + "status": current |
| 96 | + }) |
| 97 | + else: |
| 98 | + metrics_data.append({ |
| 99 | + "instance": service_name, |
| 100 | + "status": "Healthy" |
| 101 | + }) |
| 102 | + except Exception as e: |
| 103 | + print(f"Error processing query '{query}': {e}") |
| 104 | + metrics_data.append({ |
| 105 | + "instance": service_name, |
| 106 | + "status": "Unhealthy due to error!" |
| 107 | + }) |
| 108 | + |
| 109 | + |
| 110 | +def process_time_query(query, service_name): |
| 111 | + global metrics_data, up_hours |
| 112 | + try: |
| 113 | + result = prom.custom_query(query=query) |
| 114 | + if result and len(result) > 0: |
| 115 | + first_result = result[0] |
| 116 | + uptime_seconds = float(first_result["value"][1]) |
| 117 | + up_hours = int(uptime_seconds/3600) |
| 118 | + if up_hours == 0: |
| 119 | + up_hours = 1 |
| 120 | + except Exception as e: |
| 121 | + print(f"Error processing time query '{query}': {e}") |
| 122 | + |
| 123 | +def get_first_match_time(prom, prom_query, match_value=0, hours=24): |
| 124 | + global metrics_data |
| 125 | + prom_query = "up" |
| 126 | + start_time = datetime.now() - timedelta(hours=hours) |
| 127 | + end_time = datetime.now() |
| 128 | + |
| 129 | + try: |
| 130 | + result = prom.get_metric_range_data( |
| 131 | + metric_name=prom_query, |
| 132 | + start_time=start_time, |
| 133 | + end_time=end_time, |
| 134 | + ) |
| 135 | + |
| 136 | + for series in result: |
| 137 | + saw_up = False |
| 138 | + for timestamp, value in reversed(series["values"]): |
| 139 | + v = float(value) |
| 140 | + if v == 1: |
| 141 | + saw_up = True |
| 142 | + elif v == 0 and saw_up: |
| 143 | + utc_time = datetime.utcfromtimestamp(float(timestamp)) |
| 144 | + pacific_time = utc_time.astimezone(pacific_tz) |
| 145 | + readable_time = pacific_time.strftime("%Y-%m-%d %H:%M:%S %Z") |
| 146 | + status = f"Unhealthy as of {readable_time}" |
| 147 | + return status |
| 148 | + except Exception as e: |
| 149 | + print(f"Error in get_first_match_time: {e}") |
| 150 | + return "Error checking status history" |
| 151 | + |
| 152 | + |
| 153 | +@app.get("/", response_class=HTMLResponse) |
| 154 | +async def get_metrics(request: Request): |
| 155 | + return templates.TemplateResponse( |
| 156 | + "health.html", |
| 157 | + {"request": request, "metrics": metrics_data, "timestamp": datetime.now(pacific_tz).strftime("%Y-%m-%d %H:%M:%S %Z")} |
| 158 | + ) |
| 159 | + |
| 160 | +def main(): |
| 161 | + with open(args.json, "r") as file: |
| 162 | + config = json.load(file) |
| 163 | + |
| 164 | + polling_thread = threading.Thread(target = polling_loop, args = (args.interval,config), daemon=True)#The daemon=True ensures the thread exits when the main program exits. |
| 165 | + polling_thread.start() |
| 166 | + |
| 167 | + uvicorn.run(app, host="0.0.0.0", port=args.port) |
| 168 | + |
| 169 | +if __name__ == "__main__": |
| 170 | + main() |
0 commit comments