Spaces:
Running
Running
Download sysmon.py from bsweb3/Gpt2-stremio: direct link, hf CLI and curl.
- Browser
- Download file 7.45 kB
-
https://huggingface.co/spaces/bsweb3/Gpt2-stremio/resolve/main/sysmon.py
- Command line
-
hf download hf://spaces/bsweb3/Gpt2-stremio/sysmon.py
-
curl -L -o sysmon.py https://huggingface.co/spaces/bsweb3/Gpt2-stremio/resolve/main/sysmon.py
7.45 kB
| # -*- coding: utf-8 -*- | |
| """Monitor de recursos do servidor (CPU, RAM, disco) lendo cgroup/proc — sem dependências. | |
| Dentro de container (Pterodactyl/Docker) os valores do cgroup refletem o limite | |
| real do plano, ao contrário de ferramentas que leem o host inteiro. | |
| Variáveis opcionais para ajustar os limites exibidos: | |
| MEM_LIMIT_MB limite de RAM (senão SERVER_MEMORY do Pterodactyl, senão DEFAULT_MEM_MB) | |
| CPU_LIMIT_PCT limite de CPU em % (100 = 1 núcleo; senão cgroup, senão DEFAULT_CPU_PCT) | |
| DISK_LIMIT_MB limite de disco do plano (senão DEFAULT_DISK_MB) | |
| """ | |
| import asyncio | |
| import os | |
| import shutil | |
| import time | |
| from collections import deque | |
| from typing import Optional | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| CACHE_DIR = os.getenv("BSCINE_CACHE_DIR", "cache") | |
| # Limites do plano (Wispbyte). Variáveis de ambiente têm prioridade sobre estes padrões. | |
| DEFAULT_MEM_MB = 512 | |
| DEFAULT_CPU_PCT = 35 | |
| DEFAULT_DISK_MB = 1024 | |
| START = time.time() | |
| INTERVAL = 10 # segundos entre amostras | |
| HIST = deque(maxlen=360) # 1 hora de histórico (em RAM) | |
| _last_cpu_pct: Optional[float] = None | |
| def _read(path: str) -> Optional[str]: | |
| try: | |
| with open(path) as f: | |
| return f.read().strip() | |
| except Exception: | |
| return None | |
| def _int(path: str) -> Optional[int]: | |
| v = _read(path) | |
| try: | |
| return int(v) | |
| except (TypeError, ValueError): | |
| return None | |
| def _stat_field(path: str, key: str) -> Optional[int]: | |
| txt = _read(path) | |
| if not txt: | |
| return None | |
| for line in txt.splitlines(): | |
| parts = line.split() | |
| if len(parts) == 2 and parts[0] == key: | |
| try: | |
| return int(parts[1]) | |
| except ValueError: | |
| return None | |
| return None | |
| def _env_mb(name: str) -> Optional[int]: | |
| try: | |
| v = int(float(os.getenv(name, ""))) | |
| return v * 1024 * 1024 if v > 0 else None | |
| except ValueError: | |
| return None | |
| # ---------------- Memória ---------------- | |
| def mem_info() -> dict: | |
| used = limit = None | |
| src = "processo" | |
| cur = _int("/sys/fs/cgroup/memory.current") # cgroup v2 | |
| if cur is not None: | |
| inactive = _stat_field("/sys/fs/cgroup/memory.stat", "inactive_file") or 0 | |
| used = max(0, cur - inactive) | |
| raw = _read("/sys/fs/cgroup/memory.max") | |
| limit = int(raw) if raw and raw.isdigit() else None | |
| src = "cgroup" | |
| else: | |
| cur = _int("/sys/fs/cgroup/memory/memory.usage_in_bytes") # cgroup v1 | |
| if cur is not None: | |
| inactive = _stat_field("/sys/fs/cgroup/memory/memory.stat", "total_inactive_file") or 0 | |
| used = max(0, cur - inactive) | |
| lim = _int("/sys/fs/cgroup/memory/memory.limit_in_bytes") | |
| limit = lim if lim and lim < 2 ** 60 else None | |
| src = "cgroup" | |
| if used is None: # fallback: RSS do próprio processo | |
| txt = _read("/proc/self/status") or "" | |
| for line in txt.splitlines(): | |
| if line.startswith("VmRSS:"): | |
| used = int(line.split()[1]) * 1024 | |
| # limite: env > SERVER_MEMORY (Pterodactyl) > cgroup > RAM do host | |
| lim_src = "cgroup" | |
| env_limit = _env_mb("MEM_LIMIT_MB") or _env_mb("SERVER_MEMORY") or DEFAULT_MEM_MB * 1024 * 1024 | |
| if env_limit: | |
| limit, lim_src = env_limit, "config" | |
| elif limit is None: | |
| total = _stat_field("/proc/meminfo", "MemTotal") | |
| if total: | |
| limit, lim_src = total * 1024, "host" | |
| return {"used": used, "limit": limit, "source": src, "limit_source": lim_src} | |
| # ---------------- CPU ---------------- | |
| def _cpu_seconds() -> Optional[float]: | |
| usec = _stat_field("/sys/fs/cgroup/cpu.stat", "usage_usec") | |
| if usec is not None: | |
| return usec / 1e6 | |
| for p in ("/sys/fs/cgroup/cpuacct/cpuacct.usage", "/sys/fs/cgroup/cpu,cpuacct/cpuacct.usage"): | |
| ns = _int(p) | |
| if ns is not None: | |
| return ns / 1e9 | |
| txt = _read("/proc/self/stat") # fallback: só o processo | |
| if txt: | |
| parts = txt.rsplit(")", 1)[-1].split() | |
| try: | |
| return (int(parts[11]) + int(parts[12])) / os.sysconf("SC_CLK_TCK") | |
| except Exception: | |
| return None | |
| return None | |
| def cpu_limit_cores() -> float: | |
| try: | |
| pct = float(os.getenv("CPU_LIMIT_PCT", "")) | |
| if pct > 0: | |
| return pct / 100.0 | |
| except ValueError: | |
| pass | |
| raw = _read("/sys/fs/cgroup/cpu.max") # v2: "quota period" ou "max period" | |
| if raw: | |
| parts = raw.split() | |
| if len(parts) == 2 and parts[0].isdigit() and parts[1].isdigit() and int(parts[1]) > 0: | |
| return int(parts[0]) / int(parts[1]) | |
| quota = _int("/sys/fs/cgroup/cpu/cpu.cfs_quota_us") # v1 | |
| period = _int("/sys/fs/cgroup/cpu/cpu.cfs_period_us") | |
| if quota and quota > 0 and period: | |
| return quota / period | |
| return DEFAULT_CPU_PCT / 100.0 | |
| # ---------------- Disco ---------------- | |
| _disk_cache = (0.0, 0) | |
| def _dir_size(path: str) -> int: | |
| total = 0 | |
| stack = [path] | |
| while stack: | |
| p = stack.pop() | |
| try: | |
| with os.scandir(p) as it: | |
| for e in it: | |
| try: | |
| if e.is_symlink(): | |
| continue | |
| if e.is_dir(follow_symlinks=False): | |
| stack.append(e.path) | |
| else: | |
| total += e.stat(follow_symlinks=False).st_size | |
| except OSError: | |
| pass | |
| except OSError: | |
| pass | |
| return total | |
| def disk_info() -> dict: | |
| global _disk_cache | |
| now = time.time() | |
| if now - _disk_cache[0] > 60: # varrer pastas é caro: cache de 1 min | |
| paths = {BASE_DIR, os.path.abspath(CACHE_DIR)} | |
| paths = [p for p in paths if not any(p != q and p.startswith(q + os.sep) for q in paths)] | |
| _disk_cache = (now, sum(_dir_size(p) for p in paths if os.path.isdir(p))) | |
| info = {"used": _disk_cache[1], "limit": _env_mb("DISK_LIMIT_MB") or DEFAULT_DISK_MB * 1024 * 1024, "free_volume": None} | |
| try: | |
| info["free_volume"] = shutil.disk_usage(BASE_DIR).free | |
| except Exception: | |
| pass | |
| return info | |
| # ---------------- Amostragem ---------------- | |
| async def sampler(): | |
| global _last_cpu_pct | |
| prev_t, prev_c = time.time(), _cpu_seconds() | |
| while True: | |
| await asyncio.sleep(INTERVAL) | |
| try: | |
| now, c = time.time(), _cpu_seconds() | |
| pct = None | |
| if c is not None and prev_c is not None and now > prev_t: | |
| pct = max(0.0, (c - prev_c) / (now - prev_t) / cpu_limit_cores() * 100) | |
| prev_t, prev_c = now, c | |
| _last_cpu_pct = round(pct, 1) if pct is not None else None | |
| HIST.append({"t": now, "cpu": _last_cpu_pct, "mem": mem_info()["used"]}) | |
| except Exception: | |
| pass | |
| def snapshot(db_path: Optional[str] = None) -> dict: | |
| try: | |
| load = os.getloadavg()[0] | |
| except Exception: | |
| load = None | |
| try: | |
| db_size = os.path.getsize(db_path) if db_path else None | |
| except OSError: | |
| db_size = None | |
| return { | |
| "now": time.time(), | |
| "uptime": time.time() - START, | |
| "mem": mem_info(), | |
| "cpu": {"pct": _last_cpu_pct, "cores": round(cpu_limit_cores(), 2)}, | |
| "disk": disk_info(), | |
| "load": load, | |
| "db_size": db_size, | |
| "history": list(HIST), | |
| } | |