File size: 3,915 Bytes
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
003b05a
35d8fb6
 
 
 
 
 
 
 
 
 
003b05a
35d8fb6
 
 
 
 
 
 
 
 
003b05a
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
 
003b05a
35d8fb6
 
 
 
 
 
 
 
 
003b05a
35d8fb6
 
 
 
003b05a
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
003b05a
 
 
35d8fb6
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
"""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