diff --git a/kiwi_simple_metrics/main.py b/kiwi_simple_metrics/main.py index 1139cf3..59c49b0 100644 --- a/kiwi_simple_metrics/main.py +++ b/kiwi_simple_metrics/main.py @@ -10,6 +10,7 @@ def main() -> None: print(metrics.cpu()) # MEM metric + print(metrics.memory()) # DISK metric print(metrics.disk()) diff --git a/kiwi_simple_metrics/metrics/__init__.py b/kiwi_simple_metrics/metrics/__init__.py index a2223b7..bada324 100644 --- a/kiwi_simple_metrics/metrics/__init__.py +++ b/kiwi_simple_metrics/metrics/__init__.py @@ -1,7 +1,9 @@ from .cpu import cpu from .disk import disk +from .memory import memory __all__ = [ "cpu", "disk", + "memory", ] diff --git a/kiwi_simple_metrics/metrics/memory.py b/kiwi_simple_metrics/metrics/memory.py new file mode 100644 index 0000000..4ae09c1 --- /dev/null +++ b/kiwi_simple_metrics/metrics/memory.py @@ -0,0 +1,56 @@ +import psutil + +from ..settings import SETTINGS +from ._report import Report + + +def memory() -> Report | None: + if not SETTINGS.memory.enabled: + return None + + def get_used_percent(free: float, total: float) -> float: + return (total - free) / total * 100 + + vmem = psutil.virtual_memory() + swap = psutil.swap_memory() + + if SETTINGS.memory.swap == "exclude": + data = { + SETTINGS.memory.name_ram: vmem.percent, + } + + elif SETTINGS.memory.swap == "combine": + data = { + SETTINGS.memory.name: get_used_percent( + vmem.available + swap.free, + vmem.total + swap.total, + ) + } + + else: + data = { + SETTINGS.memory.name_ram: vmem.percent, + SETTINGS.memory.name_swap: swap.percent, + } + + reports = [Report.new( + settings=SETTINGS.memory, + name=name, + value=value, + ) for name, value in data.items()] + + report_inner = ", ".join( + report.result + for report in reports + ) + + return Report( + SETTINGS.memory.report_outer.format( + name=SETTINGS.memory.name, + inner=report_inner, + ), + failed=any( + report.failed + for report in reports + ), + ) diff --git a/kiwi_simple_metrics/settings.py b/kiwi_simple_metrics/settings.py index e534b97..81dd5e4 100644 --- a/kiwi_simple_metrics/settings.py +++ b/kiwi_simple_metrics/settings.py @@ -35,6 +35,17 @@ class MultiMS(MetricSettings): class MemoryMS(MultiMS): name: str = "Memory" threshold: float = 90 + report_outer: str = "{inner}" + + # how to handle swap space + # exclude: swap space is not reported + # include: swap space is reported separately + # combine: ram and swap are combined + swap: Literal["exclude", "include", "combine"] = "include" + + # names for telling apart ram and swap space + name_ram: str = "RAM" + name_swap: str = "Swap" class DiskMS(MultiMS):