|
| 1 | +from jsonschema import validate, exceptions |
| 2 | +from src.utils.arguments import arg_parser |
| 3 | +import requests |
| 4 | +import json |
| 5 | +import copy |
| 6 | +import csv |
| 7 | +import os |
| 8 | + |
| 9 | +prom_addr = arg_parser().get("prom.addr") |
| 10 | + |
| 11 | + |
| 12 | +def prom_query(query, range_query=False, start="0", end="0", |
| 13 | + step="0", url=prom_addr) -> tuple[bool, int, dict]: |
| 14 | + """ |
| 15 | + This function queries data from Prometheus |
| 16 | + based on the information provided by the |
| 17 | + user and returns the data as a dictionary. |
| 18 | + """ |
| 19 | + try: |
| 20 | + r = requests.post(f"{url}/api/v1/{'query_range' if range_query else 'query'}", |
| 21 | + data={ |
| 22 | + "query": query, |
| 23 | + "start": start, |
| 24 | + "end": end, |
| 25 | + "step": step}, |
| 26 | + headers={"Content-Type": "application/x-www-form-urlencoded"}) |
| 27 | + except BaseException as e: |
| 28 | + return False, 500, {"status": "error", |
| 29 | + "error": f"Prometheus query has failed. {e}"} |
| 30 | + else: |
| 31 | + return True if r.status_code == 200 else False, r.status_code, r.json() |
| 32 | + |
| 33 | + |
| 34 | +def data_processor(source_data: dict) -> tuple[list, list]: |
| 35 | + """ |
| 36 | + This function preprocesses the results |
| 37 | + of the Prometheus query for future formatting. |
| 38 | + It returns all labels of the query result |
| 39 | + and the data of each time series. |
| 40 | + """ |
| 41 | + data_raw = copy.deepcopy(source_data) |
| 42 | + data_processed, unique_labels = [], set() |
| 43 | + data_result = data_raw["data"]["result"] |
| 44 | + |
| 45 | + def vector_processor(): |
| 46 | + for ts in data_result: |
| 47 | + ts_labels = set(ts["metric"].keys()) |
| 48 | + unique_labels.update(ts_labels) |
| 49 | + series = ts["metric"] |
| 50 | + series["timestamp"] = ts["value"][0] |
| 51 | + series["value"] = ts["value"][1] |
| 52 | + data_processed.append(series) |
| 53 | + |
| 54 | + def matrix_processor(): |
| 55 | + for ts in data_result: |
| 56 | + ts_labels = set(ts["metric"].keys()) |
| 57 | + unique_labels.update(ts_labels) |
| 58 | + series = ts["metric"] |
| 59 | + for idx in range(len(ts["values"])): |
| 60 | + series_nested = copy.deepcopy(series) |
| 61 | + series_nested["timestamp"] = ts["values"][idx][0] |
| 62 | + series_nested["value"] = ts["values"][idx][1] |
| 63 | + data_processed.append(series_nested) |
| 64 | + del series_nested |
| 65 | + |
| 66 | + if data_raw["data"]["resultType"] == "vector": |
| 67 | + vector_processor() |
| 68 | + elif data_raw["data"]["resultType"] == "matrix": |
| 69 | + matrix_processor() |
| 70 | + |
| 71 | + unique_labels = sorted(unique_labels) |
| 72 | + unique_labels.extend(["timestamp", "value"]) |
| 73 | + return unique_labels, data_processed |
| 74 | + |
| 75 | + |
| 76 | +def validate_request(schema_file, data) -> tuple[bool, int, str, str]: |
| 77 | + """ |
| 78 | + This function validates the request object |
| 79 | + provided by the user against the required schema. |
| 80 | + It will be moved into the utils package in the future. |
| 81 | + """ |
| 82 | + schema_file = f"src/schemas/{schema_file}" |
| 83 | + with open(schema_file) as f: |
| 84 | + schema = json.load(f) |
| 85 | + try: |
| 86 | + validate(instance=data, schema=schema) |
| 87 | + except exceptions.ValidationError as e: |
| 88 | + return False, 400, "error", e.args[0] |
| 89 | + return True, 200, "success", "Request is valid" |
| 90 | + |
| 91 | + |
| 92 | +def cleanup_files(file) -> tuple[True, str]: |
| 93 | + """ |
| 94 | + This function removes the generated file |
| 95 | + once it sends a response to the user. |
| 96 | + """ |
| 97 | + try: |
| 98 | + os.remove(file) |
| 99 | + except BaseException as e: |
| 100 | + return False, str(e) |
| 101 | + else: |
| 102 | + return True, "File has been removed successfully" |
| 103 | + |
| 104 | + |
| 105 | +def csv_generator(data, fields, filename) -> tuple[bool, str, str]: |
| 106 | + """ |
| 107 | + This function generates a CSV file |
| 108 | + based on the provided objects. |
| 109 | + """ |
| 110 | + try: |
| 111 | + with open(filename, 'w') as csvfile: |
| 112 | + writer = csv.DictWriter( |
| 113 | + csvfile, fieldnames=fields, extrasaction='ignore') |
| 114 | + writer.writeheader() |
| 115 | + writer.writerows(data) |
| 116 | + except BaseException as e: |
| 117 | + return False, "error", str(e) |
| 118 | + else: |
| 119 | + return True, "success", "CSV file has been generated successfully" |
0 commit comments