fix: use GraphQL DateTime type for start and end arguments in monitoring.py

This commit is contained in:
nhnn 2024-07-15 17:16:24 +03:00
parent 2797b0b331
commit 3bddfb15c4
3 changed files with 32 additions and 30 deletions

View file

@ -1,5 +1,6 @@
import strawberry import strawberry
from typing import Optional from typing import Optional
from datetime import datetime
from selfprivacy_api.utils.prometheus import PrometheusQueries, PrometheusQueryResult from selfprivacy_api.utils.prometheus import PrometheusQueries, PrometheusQueryResult
@ -8,8 +9,8 @@ class Monitoring:
@strawberry.field @strawberry.field
def disk_usage( def disk_usage(
self, self,
start: Optional[int] = None, start: Optional[datetime] = None,
end: Optional[int] = None, end: Optional[datetime] = None,
step: int = 60, step: int = 60,
) -> PrometheusQueryResult: ) -> PrometheusQueryResult:
return PrometheusQueries.disk_usage(start, end, step) return PrometheusQueries.disk_usage(start, end, step)
@ -17,8 +18,8 @@ class Monitoring:
@strawberry.field @strawberry.field
def memory_usage( def memory_usage(
self, self,
start: Optional[int] = None, start: Optional[datetime] = None,
end: Optional[int] = None, end: Optional[datetime] = None,
step: int = 60, step: int = 60,
) -> PrometheusQueryResult: ) -> PrometheusQueryResult:
return PrometheusQueries.memory_usage(start, end, step) return PrometheusQueries.memory_usage(start, end, step)
@ -26,8 +27,8 @@ class Monitoring:
@strawberry.field @strawberry.field
def cpu_usage( def cpu_usage(
self, self,
start: Optional[int] = None, start: Optional[datetime] = None,
end: Optional[int] = None, end: Optional[datetime] = None,
step: int = 60, step: int = 60,
) -> PrometheusQueryResult: ) -> PrometheusQueryResult:
return PrometheusQueries.cpu_usage(start, end, step) return PrometheusQueries.cpu_usage(start, end, step)

View file

@ -22,14 +22,14 @@ class PrometheusQueryResult:
class PrometheusQueries: class PrometheusQueries:
@staticmethod @staticmethod
def _send_query(query: str, start: int, end: int, step: int): def _send_query(query: str, start: datetime, end: datetime, step: int):
try: try:
response = requests.get( response = requests.get(
f"{PROMETHEUS_URL}/api/v1/query_range", f"{PROMETHEUS_URL}/api/v1/query_range",
params={ params={
"query": query, "query": query,
"start": start, "start": int(start.timestamp()),
"end": end, "end": int(start.timestamp()),
"step": step, "step": step,
}, },
) )
@ -47,26 +47,26 @@ class PrometheusQueries:
@staticmethod @staticmethod
def cpu_usage( def cpu_usage(
start: Optional[int] = None, start: Optional[datetime] = None,
end: Optional[int] = None, end: Optional[datetime] = None,
step: int = 60, # seconds step: int = 60, # seconds
) -> PrometheusQueryResult: ) -> PrometheusQueryResult:
""" """
Get CPU information. Get CPU information.
Args: Args:
start (int, optional): Unix timestamp indicating the start time. start (int, optional): Unix timestamp (in seconds) indicating the start time.
Defaults to 20 minutes ago if not provided. Defaults to 20 minutes ago if not provided.
end (int, optional): Unix timestamp indicating the end time. end (int, optional): Unix timestamp (in seconds) indicating the end time.
Defaults to current time if not provided. Defaults to current time if not provided.
step (int): Interval in seconds for querying disk usage data. step (int): Interval in seconds for querying disk usage data.
""" """
if not start: if not start:
start = int((datetime.now() - timedelta(minutes=20)).timestamp()) start = datetime.now() - timedelta(minutes=20)
if not end: if not end:
end = int(datetime.now().timestamp()) end = datetime.now()
query = '100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)' query = '100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)'
@ -74,8 +74,8 @@ class PrometheusQueries:
@staticmethod @staticmethod
def memory_usage( def memory_usage(
start: Optional[int] = None, start: Optional[datetime] = None,
end: Optional[int] = None, end: Optional[datetime] = None,
step: int = 60, # seconds step: int = 60, # seconds
) -> PrometheusQueryResult: ) -> PrometheusQueryResult:
""" """
@ -90,10 +90,10 @@ class PrometheusQueries:
""" """
if not start: if not start:
start = int((datetime.now() - timedelta(minutes=20)).timestamp()) start = datetime.now() - timedelta(minutes=20)
if not end: if not end:
end = int(datetime.now().timestamp()) end = datetime.now()
query = "100 - (100 * (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes))" query = "100 - (100 * (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes))"
@ -101,8 +101,8 @@ class PrometheusQueries:
@staticmethod @staticmethod
def disk_usage( def disk_usage(
start: Optional[int] = None, start: Optional[datetime] = None,
end: Optional[int] = None, end: Optional[datetime] = None,
step: int = 60, # seconds step: int = 60, # seconds
) -> PrometheusQueryResult: ) -> PrometheusQueryResult:
""" """
@ -117,10 +117,10 @@ class PrometheusQueries:
""" """
if not start: if not start:
start = int((datetime.now() - timedelta(minutes=20)).timestamp()) start = datetime.now() - timedelta(minutes=20)
if not end: if not end:
end = int(datetime.now().timestamp()) end = datetime.now()
query = '100 - (100 * ((node_filesystem_avail_bytes{mountpoint="/",fstype!="rootfs"} ) / (node_filesystem_size_bytes{mountpoint="/",fstype!="rootfs"}) ))' query = '100 - (100 * ((node_filesystem_avail_bytes{mountpoint="/",fstype!="rootfs"} ) / (node_filesystem_size_bytes{mountpoint="/",fstype!="rootfs"}) ))'

View file

@ -2,6 +2,7 @@
# pylint: disable=unused-argument # pylint: disable=unused-argument
# pylint: disable=missing-function-docstring # pylint: disable=missing-function-docstring
from datetime import datetime
import pytest import pytest
from selfprivacy_api.utils.prometheus import PrometheusQueryResult from selfprivacy_api.utils.prometheus import PrometheusQueryResult
@ -68,7 +69,7 @@ def generate_mock_query(name):
def generate_mock_query_with_options(name): def generate_mock_query_with_options(name):
return f""" return f"""
query Query($start: Int, $end: Int, $step: Int) {{ query Query($start: DateTime, $end: DateTime, $step: Int) {{
monitoring {{ monitoring {{
{name}(start: $start, end: $end, step: $step) {{ resultType, result }} {name}(start: $start, end: $end, step: $step) {{ resultType, result }}
}} }}
@ -131,8 +132,8 @@ def test_graphql_get_disk_usage_with_options(
json={ json={
"query": generate_mock_query_with_options("diskUsage"), "query": generate_mock_query_with_options("diskUsage"),
"variables": { "variables": {
"start": 1720136108, "start": datetime.fromtimestamp(1720136108).isoformat(),
"end": 1720137319, "end": datetime.fromtimestamp(1720137319).isoformat(),
"step": 90, "step": 90,
}, },
}, },
@ -168,8 +169,8 @@ def test_graphql_get_memory_usage_with_options(
json={ json={
"query": generate_mock_query_with_options("memoryUsage"), "query": generate_mock_query_with_options("memoryUsage"),
"variables": { "variables": {
"start": 1720136108, "start": datetime.fromtimestamp(1720136108).isoformat(),
"end": 1720137319, "end": datetime.fromtimestamp(1720137319).isoformat(),
"step": 90, "step": 90,
}, },
}, },
@ -203,8 +204,8 @@ def test_graphql_get_cpu_usage_with_options(client, authorized_client, mock_cpu_
json={ json={
"query": generate_mock_query_with_options("cpuUsage"), "query": generate_mock_query_with_options("cpuUsage"),
"variables": { "variables": {
"start": 1720136108, "start": datetime.fromtimestamp(1720136108).isoformat(),
"end": 1720137319, "end": datetime.fromtimestamp(1720137319).isoformat(),
"step": 90, "step": 90,
}, },
}, },