SPB Git

Repository Public

sysmon.py 8.3 KB 221 lines python

1# =============================================================================2#                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : MacLustr LLM API7# File             : src/maclustr_llm/sysmon.py8# Description      : Mesures réelles du Mac : CPU, mémoire unifiée, pression9#                    mémoire, swap, disque, réseau, GPU, thermique.10# Module           : maclustr_llm11# Repository       : https://git.spboucher.ai/maclustr-llm12# Created          : 2026-11-1913# Last Modified    : 2026-11-1914#15# Author           : Simon-Pierre Boucher16# Position         : Professor of Finance17# Institution      : Université du Québec en Outaouais (UQO)18# Organization     : SP Boucher19# Website          : https://spboucher.ai20# Git              : https://git.spboucher.ai21#22# Preferred Contact: admin@spboucher.ai23# Technical Contact: dev@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Mesures réelles du Mac : CPU, mémoire unifiée, pression mémoire, swap, disque, réseau, GPU, thermique.4243Sources (aucune n'exige sudo) : psutil, sysctl kern.memorystatus_*, ioreg IOAccelerator (GPU),44pmset -g therm. La température en °C n'est pas lisible sans privilèges sur Apple Silicon : elle est45rapportée comme non mesurable plutôt qu'estimée.46"""4748from __future__ import annotations4950import asyncio51import json52import re53import sqlite354import subprocess55import time56from typing import Any5758import psutil5960from .db import Database6162_PRESSURE = {1: "normal", 2: "warn", 4: "critical"}636465def _run(cmd: list[str], timeout: float = 4.0) -> str:66    try:67        return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False).stdout68    except (OSError, subprocess.SubprocessError):69        return ""707172def _sysctl_int(name: str) -> int | None:73    out = _run(["/usr/sbin/sysctl", "-n", name]).strip()74    return int(out) if out.lstrip("-").isdigit() else None757677def read_pressure() -> tuple[str, int | None]:78    level = _sysctl_int("kern.memorystatus_vm_pressure_level")79    free_pct = _sysctl_int("kern.memorystatus_level")80    return _PRESSURE.get(level or 1, "normal"), free_pct818283def read_gpu() -> dict[str, Any] | None:84    out = _run(["/usr/sbin/ioreg", "-r", "-d", "1", "-w", "0", "-c", "IOAccelerator"])85    m = re.search(r'"PerformanceStatistics"\s*=\s*\{([^}]*)\}', out)86    if not m:87        return None88    stats = dict(re.findall(r'"([^"]+)"=(\d+)', m.group(1)))89    if "Device Utilization %" not in stats:90        return None91    return {92        "utilization_pct": int(stats["Device Utilization %"]),93        "in_use_memory_bytes": int(stats["In use system memory"]) if "In use system memory" in stats else None,94        "allocated_memory_bytes": int(stats["Alloc system memory"]) if "Alloc system memory" in stats else None,95    }969798def read_thermal() -> dict[str, Any]:99    out = _run(["/usr/bin/pmset", "-g", "therm"])100    cpu_limit = re.search(r"CPU_Speed_Limit\s*=\s*(\d+)", out)101    warn = re.search(r"thermal warning level.*?(\d+)", out, re.I)102    state = "nominal"103    if cpu_limit and int(cpu_limit.group(1)) < 100:104        state = "throttled"105    elif warn and "No thermal warning" not in out and int(warn.group(1)) > 0:106        state = "warning"107    return {108        "state": state,109        "cpu_speed_limit_pct": int(cpu_limit.group(1)) if cpu_limit else None,110        "temperature_c": None,111        "temperature_note": "non mesurable sans privilèges sur Apple Silicon",112    }113114115class SysMonitor:116    def __init__(self, db: Database, disk_path: str, interval_s: float = 5.0) -> None:117        self.db = db118        self.disk_path = disk_path119        self.interval_s = interval_s120        self.latest: dict[str, Any] = {}121        self.pressure_level = "normal"122        self._net: tuple[float, int, int] | None = None123        self._task: asyncio.Task[None] | None = None124        self._last_persist = 0.0125        self.hardware = self._hardware()126127    @staticmethod128    def _hardware() -> dict[str, Any]:129        chip = _run(["/usr/sbin/sysctl", "-n", "machdep.cpu.brand_string"]).strip()130        model = _run(["/usr/sbin/sysctl", "-n", "hw.model"]).strip()131        os_ver = _run(["/usr/bin/sw_vers", "-productVersion"]).strip()132        return {133            "chip": chip or None,134            "model": model or None,135            "macos": os_ver or None,136            "cpu_cores": psutil.cpu_count(logical=True),137            "performance_cores": _sysctl_int("hw.perflevel0.physicalcpu"),138            "efficiency_cores": _sysctl_int("hw.perflevel1.physicalcpu"),139            "memory_bytes": psutil.virtual_memory().total,140        }141142    def sample(self) -> dict[str, Any]:143        vm = psutil.virtual_memory()144        sw = psutil.swap_memory()145        du = psutil.disk_usage(self.disk_path)146        io = psutil.net_io_counters()147        now = time.time()148        rx = tx = None149        if self._net is not None and now > self._net[0]:150            dt = now - self._net[0]151            rx, tx = (io.bytes_recv - self._net[1]) / dt, (io.bytes_sent - self._net[2]) / dt152        self._net = (now, io.bytes_recv, io.bytes_sent)153        level, free_pct = read_pressure()154        load = psutil.getloadavg()155        return {156            "ts": int(now),157            "cpu": {158                "percent": psutil.cpu_percent(interval=None),159                "load_1m": round(load[0], 2),160                "per_core": psutil.cpu_percent(interval=None, percpu=True),161            },162            "memory": {163                "total_bytes": vm.total,164                "used_bytes": vm.total - vm.available,165                "available_bytes": vm.available,166                "wired_bytes": getattr(vm, "wired", None),167                "pressure": level,168                "free_percent": free_pct,169            },170            "swap": {"total_bytes": sw.total, "used_bytes": sw.used},171            "disk": {"total_bytes": du.total, "free_bytes": du.free},172            "network": {173                "rx_bytes_per_s": round(rx) if rx is not None else None,174                "tx_bytes_per_s": round(tx) if tx is not None else None,175            },176            "gpu": read_gpu(),177            "thermal": read_thermal(),178        }179180    async def start(self) -> None:181        psutil.cpu_percent(interval=None)182        await self._tick()183        self._task = asyncio.create_task(self._loop())184185    async def stop(self) -> None:186        if self._task:187            self._task.cancel()188            try:189                await self._task190            except asyncio.CancelledError:191                pass192193    async def _tick(self) -> None:194        s = await asyncio.get_running_loop().run_in_executor(None, self.sample)195        self.latest = s196        self.pressure_level = s["memory"]["pressure"]197        if s["ts"] - self._last_persist >= 60:198            self._last_persist = s["ts"]199            slim = {k: v for k, v in s.items() if k != "thermal"}200            slim["cpu"] = {k: v for k, v in s["cpu"].items() if k != "per_core"}201            payload = json.dumps(slim, separators=(",", ":"))202203            def op(conn: sqlite3.Connection) -> None:204                conn.execute("INSERT OR REPLACE INTO sys_samples VALUES (?, ?)", (s["ts"] - s["ts"] % 60, payload))205206            await self.db.run(op)207208    async def _loop(self) -> None:209        while True:210            await asyncio.sleep(self.interval_s)211            try:212                await self._tick()213            except Exception:214                pass215216    async def history(self, since: int) -> list[dict[str, Any]]:217        rows = await self.db.run(218            lambda c: c.execute("SELECT sample FROM sys_samples WHERE ts >= ? ORDER BY ts", (since,)).fetchall()219        )220        return [json.loads(r[0]) for r in rows]221
Files main
Menu

Theme