-
Notifications
You must be signed in to change notification settings - Fork 3
feat: Serve resource usage metrics #58
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mfranczel
merged 7 commits into
main
from
michal/blu-5457-serve-resource-usage-metrics-from-deepnote-toolkit
Jan 16, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
fb25768
feat(resource-usage): Add lightweight resource metrics server
mfranczel 67859fa
fix(resource-usage): Handle None values for CPU count and usage percent
mfranczel 95b873a
fix: formatting issues in resource_usage
mfranczel 5ba4638
fix: dont shadow builtin format
mfranczel d0397d4
fix: subtract inactive fie from current memory
mfranczel 0a619ff
refactor(resource-usage): Replace print statements with logging for b…
mfranczel 9e9d988
refactor(resource-usage): Simplify parsing logic and improve early re…
mfranczel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,282 @@ | ||
| #!/usr/bin/env python3 | ||
| """Lightweight resource metrics server.""" | ||
|
|
||
| import json | ||
| import logging | ||
| import os | ||
| import threading | ||
| import time | ||
| from functools import partial | ||
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | ||
| from pathlib import Path | ||
| from typing import Any, Optional | ||
|
|
||
| try: | ||
| import psutil | ||
|
|
||
| HAS_PSUTIL = True | ||
| except ImportError: | ||
| HAS_PSUTIL = False | ||
|
|
||
|
|
||
| class ResourceMonitor: | ||
| """Monitors system resources via cgroups or psutil.""" | ||
|
|
||
| def __init__(self, root_path: str = "/sys/fs/cgroup") -> None: | ||
| self.root = Path(root_path) | ||
| self.backend = self._detect_backend() | ||
| self._last_cpu_sec: Optional[float] = None | ||
| self._last_time: Optional[float] = None | ||
| self._lock = threading.Lock() | ||
|
|
||
| def _detect_backend(self) -> str: | ||
| if (self.root / "cgroup.controllers").exists(): | ||
| return "cgroupv2" | ||
| if (self.root / "memory/memory.limit_in_bytes").exists(): | ||
| return "cgroupv1" | ||
| if HAS_PSUTIL: | ||
| return "psutil" | ||
| return "none" | ||
|
|
||
| def _read_file(self, path: Path) -> Optional[str]: | ||
| try: | ||
| return path.read_text().strip() | ||
| except (FileNotFoundError, PermissionError, OSError): | ||
| return None | ||
|
|
||
| def get_memory(self) -> tuple[int, Optional[int]]: | ||
| """Returns (used_bytes, limit_bytes). Limit is None if unlimited.""" | ||
| if self.backend == "cgroupv2": | ||
| current = self._parse_int(self.root / "memory.current", 0) | ||
| inactive_file = self._parse_memory_stat("inactive_file") | ||
| used = current - inactive_file | ||
| limit_str = self._read_file(self.root / "memory.max") | ||
| limit = self._parse_limit(limit_str, "max") | ||
| return used, limit | ||
|
|
||
| if self.backend == "cgroupv1": | ||
| used = self._parse_int(self.root / "memory/memory.usage_in_bytes", 0) | ||
| limit_str = self._read_file(self.root / "memory/memory.limit_in_bytes") | ||
| limit = self._parse_limit(limit_str, threshold=1_000_000_000_000_000) | ||
| return used, limit | ||
|
|
||
| if self.backend == "psutil": | ||
| proc = psutil.Process() | ||
| return proc.memory_info().rss, psutil.virtual_memory().total | ||
mfranczel marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return 0, None | ||
|
|
||
| def get_cpu(self) -> tuple[Optional[float], Optional[float]]: | ||
| """Returns (usage_percent, limit_cores).""" | ||
| usage_sec = self._get_cpu_seconds() | ||
| percent = self._calc_percent(usage_sec) | ||
| limit = self._get_cpu_limit() | ||
| return percent, limit | ||
|
|
||
| def _parse_int(self, path: Path, default: int = 0) -> int: | ||
| content = self._read_file(path) | ||
| if not content: | ||
| return default | ||
| try: | ||
| return int(content) | ||
| except ValueError: | ||
| return default | ||
|
|
||
| def _parse_limit( | ||
| self, | ||
| value: Optional[str], | ||
| unlimited_marker: Optional[str] = None, | ||
| threshold: Optional[int] = None, | ||
| ) -> Optional[int]: | ||
| if not value: | ||
| return None | ||
| if unlimited_marker and value == unlimited_marker: | ||
| return None | ||
| try: | ||
| parsed = int(value) | ||
| if threshold and parsed >= threshold: | ||
| return None | ||
| return parsed | ||
| except ValueError: | ||
| return None | ||
|
|
||
| def _parse_memory_stat(self, key: str) -> int: | ||
| """Parse a value from memory.stat file.""" | ||
| content = self._read_file(self.root / "memory.stat") | ||
| if not content: | ||
| return 0 | ||
| for line in content.splitlines(): | ||
| if not line.startswith(key): | ||
| continue | ||
| parts = line.split() | ||
| if len(parts) < 2: | ||
| continue | ||
| try: | ||
| return int(parts[1]) | ||
| except ValueError: | ||
| continue | ||
| return 0 | ||
mfranczel marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| def _get_cpu_seconds(self) -> float: | ||
| if self.backend == "cgroupv2": | ||
| content = self._read_file(self.root / "cpu.stat") | ||
| if not content: | ||
| return 0.0 | ||
| for line in content.splitlines(): | ||
| if not line.startswith("usage_usec"): | ||
| continue | ||
| parts = line.split() | ||
| if len(parts) >= 2: | ||
| return int(parts[1]) / 1_000_000.0 | ||
| return 0.0 | ||
|
|
||
| if self.backend == "cgroupv1": | ||
| content = self._read_file(self.root / "cpuacct/cpuacct.usage") | ||
| if not content: | ||
| return 0.0 | ||
| return int(content) / 1_000_000_000.0 | ||
|
|
||
| if self.backend == "psutil": | ||
| times = psutil.Process().cpu_times() | ||
| return times.user + times.system | ||
|
|
||
| return 0.0 | ||
|
|
||
| def _get_cpu_limit(self) -> Optional[float]: | ||
| if self.backend == "cgroupv2": | ||
| content = self._read_file(self.root / "cpu.max") | ||
| if not content: | ||
| return None | ||
| parts = content.split() | ||
| if len(parts) < 2 or parts[0] == "max": | ||
| return None | ||
| try: | ||
| return int(parts[0]) / int(parts[1]) | ||
| except (ValueError, ZeroDivisionError): | ||
| return None | ||
|
|
||
| if self.backend == "cgroupv1": | ||
| quota = self._parse_int(self.root / "cpu/cpu.cfs_quota_us", -1) | ||
| period = self._parse_int(self.root / "cpu/cpu.cfs_period_us", 0) | ||
| if quota <= 0 or period <= 0: | ||
| return None | ||
| return quota / period | ||
|
|
||
| if self.backend == "psutil": | ||
| cpu_count = psutil.cpu_count(logical=True) | ||
| return float(cpu_count) if cpu_count is not None else None | ||
|
|
||
| return None | ||
|
|
||
| def _calc_percent(self, current_sec: float) -> Optional[float]: | ||
| now = time.monotonic() | ||
| with self._lock: | ||
| if self._last_cpu_sec is None or self._last_time is None: | ||
| self._last_cpu_sec = current_sec | ||
| self._last_time = now | ||
| return None | ||
|
|
||
| time_delta = now - self._last_time | ||
| cpu_delta = current_sec - self._last_cpu_sec | ||
| self._last_cpu_sec = current_sec | ||
| self._last_time = now | ||
|
|
||
| if time_delta <= 0: | ||
| return 0.0 | ||
| return (cpu_delta / time_delta) * 100.0 | ||
mfranczel marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| class MetricsHandler(BaseHTTPRequestHandler): | ||
| """HTTP handler for resource metrics.""" | ||
|
|
||
| def __init__(self, monitor: ResourceMonitor, *args: Any, **kwargs: Any) -> None: | ||
| self.monitor = monitor | ||
| super().__init__(*args, **kwargs) | ||
|
|
||
| def do_GET(self) -> None: | ||
| if self.path in ("/", "/resource-usage"): | ||
| self._send_metrics() | ||
| elif self.path == "/health": | ||
| self._send_text(200, "ok") | ||
| else: | ||
| self.send_error(404) | ||
|
|
||
| def _send_metrics(self) -> None: | ||
| mem_used, mem_limit = self.monitor.get_memory() | ||
| cpu_percent, cpu_limit = self.monitor.get_cpu() | ||
|
|
||
| env_limit = os.environ.get("MEM_LIMIT") | ||
| if env_limit: | ||
| try: | ||
| mem_limit = int(env_limit) | ||
| except ValueError: | ||
| pass | ||
|
|
||
| mem_util = None | ||
| if mem_limit and mem_limit > 0: | ||
| mem_util = round((mem_used / mem_limit) * 100, 2) | ||
|
|
||
| cpu_sat = None | ||
| if cpu_percent is not None and cpu_limit: | ||
| cpu_sat = round(cpu_percent / cpu_limit, 2) | ||
|
|
||
| data = { | ||
| "meta": {"backend": self.monitor.backend, "timestamp": time.time()}, | ||
| "memory": { | ||
| "used_bytes": mem_used, | ||
| "limit_bytes": mem_limit, | ||
| "usage_percent": mem_util, | ||
| }, | ||
| "cpu": { | ||
| "usage_percent": ( | ||
| round(cpu_percent, 2) if cpu_percent is not None else None | ||
| ), | ||
| "limit_cores": cpu_limit, | ||
| "saturation_percent": cpu_sat, | ||
| }, | ||
| } | ||
| self._send_json(200, data) | ||
|
|
||
| def _send_json(self, code: int, data: dict[str, Any]) -> None: | ||
| body = json.dumps(data, indent=2).encode() | ||
| self._send_response(code, body, "application/json") | ||
|
|
||
| def _send_text(self, code: int, text: str) -> None: | ||
| self._send_response(code, text.encode(), "text/plain") | ||
|
|
||
| def _send_response(self, code: int, body: bytes, content_type: str) -> None: | ||
| self.send_response(code) | ||
| self.send_header("Content-Type", content_type) | ||
| self.send_header("Content-Length", str(len(body))) | ||
| self.send_header("X-Content-Type-Options", "nosniff") | ||
| self.end_headers() | ||
| self.wfile.write(body) | ||
|
|
||
| def log_message(self, msg_format: str, *args: Any) -> None: | ||
| logging.info(f"{self.address_string()} - {msg_format % args}") | ||
|
|
||
|
|
||
| def main() -> None: | ||
| logging.basicConfig( | ||
| level=logging.INFO, | ||
| format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", | ||
| ) | ||
|
|
||
| port = int(os.environ.get("RESOURCE_USAGE_METRICS_PORT", 9104)) | ||
| monitor = ResourceMonitor() | ||
| monitor.get_cpu() # Initialize CPU baseline | ||
|
|
||
| handler = partial(MetricsHandler, monitor) | ||
| server = ThreadingHTTPServer(("0.0.0.0", port), handler) | ||
mfranczel marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| logging.info(f"Starting server on port {port} (backend: {monitor.backend})") | ||
|
|
||
| try: | ||
| server.serve_forever() | ||
| except KeyboardInterrupt: | ||
| logging.info("Shutting down...") | ||
| server.server_close() | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.