File size: 1,782 Bytes
e59bd9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Background worker: status command helper for `lpu status`.

Reads controller status.json + active sessions + last discovery snapshot and
returns a human/parse-friendly report. Kept separate from the controller so
status queries never touch the controller loop.
"""

from __future__ import annotations

import json
import time
from pathlib import Path
from typing import Dict, List, Optional

from ..monitoring.logger import lpu_home, read_jsonl
from .lifecycle import find_controller_pid


def controller_status() -> dict:
    home = lpu_home()
    pid = find_controller_pid()
    st_path = home / "status.json"
    status: Dict = {
        "controller_running": pid is not None,
        "controller_pid": pid,
        "ts": time.time(),
    }
    try:
        status["controller"] = json.loads(st_path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        status["controller"] = None
        status["note"] = "no status file yet (controller never started or crashed)"
    return status


def active_sessions_report() -> List[dict]:
    from ..ipc import list_active_sessions

    return list_active_sessions(max_age_s=30.0)


def last_gpu_samples(count: int = 5) -> List[dict]:
    home = lpu_home()
    path = home / "logs" / "controller_metrics.jsonl"
    if not path.exists():
        return []
    recs = []
    for rec in read_jsonl(path):
        if isinstance(rec, dict) and rec.get("kind") == "gpu":
            recs.append(rec)
    return recs[-count:]


def full_report() -> dict:
    return {
        "controller": controller_status(),
        "sessions": active_sessions_report(),
        "gpu_samples": last_gpu_samples(),
    }


if __name__ == "__main__":  # pragma: no cover
    print(json.dumps(full_report(), indent=2, default=str))