From 1854c4d40ebd4342471a668ec45372fb381853ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rn-Michael=20Miehe?= <40151420+ldericher@users.noreply.github.com> Date: Thu, 31 Aug 2023 09:00:22 +0000 Subject: [PATCH] metrics.cpu_metric --- kiwi_simple_metrics/main.py | 5 ++--- kiwi_simple_metrics/metrics.py | 36 +++++++++++++++++++++++++++++++++ kiwi_simple_metrics/settings.py | 3 +++ 3 files changed, 41 insertions(+), 3 deletions(-) create mode 100644 kiwi_simple_metrics/metrics.py diff --git a/kiwi_simple_metrics/main.py b/kiwi_simple_metrics/main.py index 155cf4e..c189eb7 100644 --- a/kiwi_simple_metrics/main.py +++ b/kiwi_simple_metrics/main.py @@ -1,8 +1,7 @@ import os import shutil -import psutil - +from .metrics import cpu_metric from .settings import SETTINGS @@ -11,7 +10,7 @@ def main() -> None: print(SETTINGS.model_dump()) # CPU metric - print(psutil.cpu_percent(interval=1)) + print(cpu_metric()) # MEM metric diff --git a/kiwi_simple_metrics/metrics.py b/kiwi_simple_metrics/metrics.py new file mode 100644 index 0000000..a790536 --- /dev/null +++ b/kiwi_simple_metrics/metrics.py @@ -0,0 +1,36 @@ +from dataclasses import dataclass, field + +import psutil + +from .settings import SETTINGS, MetricSettings + + +@dataclass(slots=True, frozen=True) +class Report: + result: str + failed: bool = field(default=False, kw_only=True) + + +def _report( + settings: MetricSettings, + name: str, + value: float, +) -> Report | None: + if not settings.enabled: + return None + + result = settings.report.format(name=name, value=value) + + if ( + value > settings.threshold and not settings.inverted + or value < settings.threshold and settings.inverted + ): + return Report(result, failed=True) + + else: + return Report(result) + + +def cpu_metric() -> Report | None: + value = psutil.cpu_percent(interval=1) + return _report(SETTINGS.cpu, "CPU", value) diff --git a/kiwi_simple_metrics/settings.py b/kiwi_simple_metrics/settings.py index 375ff75..a92159d 100644 --- a/kiwi_simple_metrics/settings.py +++ b/kiwi_simple_metrics/settings.py @@ -8,6 +8,9 @@ class MetricSettings(BaseModel): # metric will be reported enabled: bool = True + # format string to report the metric + report: str = "{name}: {value:.2f}%" + # if the metric value exceeds this percentage, the report fails threshold: float