disk_status.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """Disk-usage rollup for ``/api/status``.
  2. Companion to :mod:`gateway.memory_status`: a hosted agent can fill its data
  3. volume (SQLite writes failing, config saves lost) while its dashboard looks
  4. healthy. Sampled live via one ``statvfs`` call, so there is no ``sampled_at``.
  5. ``/api/status`` is unauthenticated: only coarse numbers (MB, one-decimal
  6. percent) and an enum. Best-effort: an unreadable filesystem degrades to
  7. ``pressure="unknown"`` rather than raising into the status endpoint.
  8. """
  9. from __future__ import annotations
  10. import shutil
  11. from pathlib import Path
  12. from typing import Any, Dict, Optional
  13. from gateway.memory_status import _nonneg_int
  14. # Percent alone misleads both ways: 90% used on 100 GB leaves 10 GB, while 50% on a tiny
  15. # volume is one download from write failures. So percent triggers are gated on absolute
  16. # headroom also being low, and a hard floor applies regardless of size (below it SQLite
  17. # journaling / config writes are at risk). Rows: (level, free floor, used-%, headroom); worst first.
  18. _PRESSURE_TIERS = (
  19. ("critical", 256, 95.0, 1024), # < 256 MB free, or >= 95% used AND < 1 GB free
  20. ("elevated", 512, 85.0, 4096), # < 512 MB free, or >= 85% used AND < 4 GB free
  21. )
  22. _BYTES_PER_MB = 1024 * 1024
  23. def classify_disk_pressure(free_mb: Any, total_mb: Any) -> str:
  24. """``ok``/``elevated``/``critical`` from free/total MB; ``unknown`` when the sample
  25. is missing/malformed — "could not read it" must never read as "fine"."""
  26. free, total = _nonneg_int(free_mb), _nonneg_int(total_mb)
  27. if free is None or not total:
  28. return "unknown"
  29. used_percent = (1 - free / total) * 100.0
  30. for level, free_floor, percent_floor, headroom in _PRESSURE_TIERS:
  31. if free < free_floor or (used_percent >= percent_floor and free < headroom):
  32. return level
  33. return "ok"
  34. def collect_disk_status(home: Optional[Path] = None) -> dict[str, Any]:
  35. """``disk`` block for ``/api/status`` (same ``home`` contract as ``memory``).
  36. Never raises — an unreadable/unmounted filesystem yields ``pressure="unknown"``."""
  37. status: dict[str, Any] = {"pressure": "unknown", "total_mb": None, "free_mb": None, "used_percent": None}
  38. try:
  39. if home is None:
  40. from hermes_constants import get_hermes_home
  41. home = get_hermes_home()
  42. usage = shutil.disk_usage(home)
  43. except Exception:
  44. return status
  45. if usage.total <= 0:
  46. return status
  47. total_mb, free_mb = usage.total // _BYTES_PER_MB, usage.free // _BYTES_PER_MB
  48. status.update(total_mb=total_mb, free_mb=free_mb, used_percent=round((usage.used / usage.total) * 100, 1),
  49. pressure=classify_disk_pressure(free_mb, total_mb))
  50. return status