2024-06-15 18:17:08 +00:00
|
|
|
"""Prometheus monitoring queries."""
|
|
|
|
|
|
|
|
# pylint: disable=too-few-public-methods
|
|
|
|
import time
|
2024-06-22 12:12:29 +00:00
|
|
|
import requests
|
2024-06-25 17:25:31 +00:00
|
|
|
from typing import Optional, Dict
|
|
|
|
from datetime import datetime, timedelta
|
2024-06-15 18:17:08 +00:00
|
|
|
|
2024-06-17 18:56:58 +00:00
|
|
|
PROMETHEUS_URL = "http://localhost:9001"
|
2024-06-15 18:17:08 +00:00
|
|
|
|
|
|
|
|
|
|
|
class PrometheusInfo:
|
|
|
|
""" """
|
|
|
|
|
|
|
|
http_response: int
|
2024-06-25 17:25:31 +00:00
|
|
|
output: Optional[Dict] = None
|
2024-06-15 18:17:08 +00:00
|
|
|
error: Optional[str] = None
|
|
|
|
|
|
|
|
|
|
|
|
class PrometheusQueries:
|
|
|
|
@staticmethod
|
2024-06-15 18:31:39 +00:00
|
|
|
def _send_request(endpoint="/api/v1/query", params=None) -> PrometheusInfo:
|
2024-06-15 18:17:08 +00:00
|
|
|
try:
|
|
|
|
response = requests.get(f"{PROMETHEUS_URL}{endpoint}", params=params)
|
|
|
|
return PrometheusInfo(
|
|
|
|
http_response=response.status_code,
|
|
|
|
output=(response.json() if response.status_code == 200 else None),
|
|
|
|
)
|
|
|
|
except requests.RequestException as error:
|
|
|
|
return PrometheusInfo(
|
|
|
|
http_response=500,
|
|
|
|
error=str(error),
|
|
|
|
)
|
|
|
|
|
|
|
|
@staticmethod
|
2024-06-21 16:33:37 +00:00
|
|
|
def cpu_usage(
|
|
|
|
start: int = int((datetime.now() - timedelta(minutes=20)).timestamp()),
|
|
|
|
end: int = int(datetime.now().timestamp()),
|
|
|
|
step: int = 60,
|
|
|
|
) -> PrometheusInfo:
|
2024-06-15 18:17:08 +00:00
|
|
|
"""Get CPU information"""
|
2024-06-21 16:33:37 +00:00
|
|
|
|
2024-06-15 18:17:08 +00:00
|
|
|
query = '100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)'
|
|
|
|
|
2024-06-21 16:33:37 +00:00
|
|
|
params = {"query": query, "start": start, "end": end, "step": step}
|
2024-06-15 18:17:08 +00:00
|
|
|
|
2024-06-15 18:28:10 +00:00
|
|
|
return self._send_request(params=params)
|
2024-06-15 18:17:08 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2024-06-21 16:33:37 +00:00
|
|
|
def disk_usage(
|
|
|
|
start: int = int((datetime.now() - timedelta(minutes=20)).timestamp()),
|
|
|
|
end: int = int(datetime.now().timestamp()),
|
|
|
|
step: int = 60,
|
|
|
|
) -> PrometheusInfo:
|
2024-06-16 19:01:25 +00:00
|
|
|
"""Get disk usage information"""
|
2024-06-16 19:06:40 +00:00
|
|
|
query = '100 - (100 * ((node_filesystem_avail_bytes{mountpoint="/",fstype!="rootfs"} ) / (node_filesystem_size_bytes{mountpoint="/",fstype!="rootfs"}) ))'
|
2024-06-16 19:01:25 +00:00
|
|
|
|
2024-06-21 16:33:37 +00:00
|
|
|
params = {"query": query, "start": start, "end": end, "step": step}
|
2024-06-16 19:01:25 +00:00
|
|
|
return self._send_request(params=params)
|