hetchyy's picture
deploy qua@8bd7ee6e
003b05a verified
Raw History Blame Contribute Delete
3.92 kB
"""Operator endpoints for the in-Space persistent CPU worker pool.
HF-token-gated, undocumented, and deliberately absent from ``/api/v1``: these
are not part of the public contract. ``cpu_pool_kill`` is kept because it is the
only remote lever when a worker wedges — without it, recovery means restarting
the whole Space.
"""
from __future__ import annotations
import os
# Seconds to let the OS reap a killed worker before re-checking liveness.
_REAP_GRACE_S = 0.3
# cgroup files that expose the container's real memory budget, which is the
# authoritative limit on a Space (psutil reports the host's, not the container's).
_CGROUP_LIMIT_PATHS = (
"/sys/fs/cgroup/memory.max",
"/sys/fs/cgroup/memory/memory.limit_in_bytes",
)
def _unauthorized(hf_token) -> dict | None:
"""Reject anyone who isn't holding the Space's own token."""
space_token = os.environ.get("HF_TOKEN", "")
if not hf_token or (space_token and hf_token != space_token):
return {"error": "Unauthorized"}
return None
def cpu_pool_kill(hf_token, worker_id):
"""Kill one persistent worker so the pool respawns it. HF-token-gated."""
denied = _unauthorized(hf_token)
if denied:
return denied
try:
import signal
import time
from src.core.cpu_worker_pool import _get_pool
pool = _get_pool()
wid = int(worker_id)
handle = pool.workers[wid]
pid = handle.pid
was_alive = handle.process is not None and handle.process.is_alive()
try:
os.kill(pid, signal.SIGKILL)
sent, send_err = True, None
except Exception as e:
sent, send_err = False, str(e)
time.sleep(_REAP_GRACE_S)
return {
"worker_id": wid,
"pid": pid,
"was_alive": was_alive,
"kill_sent": sent,
"send_err": send_err,
"alive_after": handle.process is not None and handle.process.is_alive(),
}
except Exception as e:
return {"error": str(e)}
def _augment_worker_rss(stats: dict) -> None:
from src.core.cpu_worker_pool import probe_rss
for worker in stats.get("workers", []):
try:
worker["rss_now"] = probe_rss(worker["id"])
except Exception as e:
worker["rss_now_error"] = str(e)
def _augment_host_memory(stats: dict) -> None:
try:
import psutil
stats["main_rss"] = psutil.Process(os.getpid()).memory_info().rss
vm = psutil.virtual_memory()
stats["host_mem"] = {
"total": vm.total, "available": vm.available,
"used": vm.used, "percent": vm.percent,
}
except Exception as e:
stats["main_rss_error"] = str(e)
def _augment_cgroup(stats: dict) -> None:
cgroup = {}
for path in _CGROUP_LIMIT_PATHS:
try:
with open(path) as f:
cgroup[path] = f.read().strip()
except Exception as e:
cgroup[path] = f"err: {e}"
try:
with open("/sys/fs/cgroup/memory.current") as f:
cgroup["memory.current"] = f.read().strip()
except Exception:
pass
stats["cgroup"] = cgroup
def cpu_pool_status(hf_token):
"""Persistent CPU pool state: per-worker snapshots, live RSS, job counts.
Safe to call before the pool has bootstrapped — returns ``started=False``.
"""
denied = _unauthorized(hf_token)
if denied:
return denied
try:
from src.core.cpu_worker_pool import is_started
from src.core.cpu_worker_pool import stats as pool_stats
except Exception as e:
return {"error": f"pool import failed: {e}"}
if not is_started():
return {"started": False, "note": "CPU pool not yet bootstrapped"}
stats = pool_stats()
_augment_worker_rss(stats)
_augment_host_memory(stats)
_augment_cgroup(stats)
return stats