Keep /api/health instant, isolate ffmpeg cgroups, defer clip encodes while live push runs, and align dy.live systemd with dylive. README covers the hang root cause and /yt-revenue. Co-authored-by: Cursor <cursoragent@cursor.com>
132 lines
4.2 KiB
Python
132 lines
4.2 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Host CPU / memory snapshot (no extra deps — reads /proc)."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import time
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
_prev_cpu: tuple[int, int] | None = None
|
|
_snapshot_cache: dict[str, Any] | None = None
|
|
_snapshot_cache_at = 0.0
|
|
_SNAPSHOT_TTL_SEC = 2.0
|
|
|
|
|
|
def _read_cpu_totals() -> tuple[int, int]:
|
|
line = Path("/proc/stat").read_text(encoding="utf-8", errors="replace").splitlines()[0]
|
|
parts = line.split()
|
|
if not parts or parts[0] != "cpu":
|
|
return 0, 0
|
|
nums = [int(x) for x in parts[1:]]
|
|
idle = nums[3] + (nums[4] if len(nums) > 4 else 0)
|
|
total = sum(nums[:10]) if len(nums) >= 10 else sum(nums)
|
|
return idle, total
|
|
|
|
|
|
def _cpu_percent(sample: bool = True) -> float:
|
|
"""Return busy CPU % since last call (or brief sleep sample on first call)."""
|
|
global _prev_cpu
|
|
idle, total = _read_cpu_totals()
|
|
if _prev_cpu is None:
|
|
if sample:
|
|
time.sleep(0.12)
|
|
idle2, total2 = _read_cpu_totals()
|
|
_prev_cpu = (idle2, total2)
|
|
dt = total2 - total
|
|
if dt <= 0:
|
|
return 0.0
|
|
return round(100.0 * (1.0 - (idle2 - idle) / dt), 1)
|
|
_prev_cpu = (idle, total)
|
|
return 0.0
|
|
prev_idle, prev_total = _prev_cpu
|
|
_prev_cpu = (idle, total)
|
|
dt = total - prev_total
|
|
if dt <= 0:
|
|
return 0.0
|
|
busy = 100.0 * (1.0 - (idle - prev_idle) / dt)
|
|
return round(max(0.0, min(100.0, busy)), 1)
|
|
|
|
|
|
def _mem_info() -> dict[str, float]:
|
|
kv: dict[str, int] = {}
|
|
for line in Path("/proc/meminfo").read_text(encoding="utf-8", errors="replace").splitlines():
|
|
if ":" not in line:
|
|
continue
|
|
k, v = line.split(":", 1)
|
|
num = v.strip().split()[0]
|
|
try:
|
|
kv[k.strip()] = int(num)
|
|
except ValueError:
|
|
continue
|
|
total_kb = float(kv.get("MemTotal") or 0)
|
|
avail_kb = float(kv.get("MemAvailable") or kv.get("MemFree") or 0)
|
|
used_kb = max(0.0, total_kb - avail_kb)
|
|
pct = round(100.0 * used_kb / total_kb, 1) if total_kb > 0 else 0.0
|
|
return {
|
|
"memory_total_gb": round(total_kb / 1024 / 1024, 2),
|
|
"memory_used_gb": round(used_kb / 1024 / 1024, 2),
|
|
"memory_available_gb": round(avail_kb / 1024 / 1024, 2),
|
|
"memory_percent": pct,
|
|
}
|
|
|
|
|
|
def snapshot(*, sample_cpu: bool = False) -> dict[str, Any]:
|
|
"""CPU % uses /proc delta between calls (no blocking sleep). First call may be 0."""
|
|
global _snapshot_cache, _snapshot_cache_at
|
|
now = time.time()
|
|
if (
|
|
not sample_cpu
|
|
and _snapshot_cache is not None
|
|
and (now - _snapshot_cache_at) < _SNAPSHOT_TTL_SEC
|
|
):
|
|
return dict(_snapshot_cache)
|
|
mem = _mem_info()
|
|
load1 = 0.0
|
|
try:
|
|
load1 = round(float(Path("/proc/loadavg").read_text().split()[0]), 2)
|
|
except Exception:
|
|
pass
|
|
nproc = max(1, int(os.cpu_count() or 1))
|
|
out = {
|
|
"ts": now,
|
|
"cpu_percent": _cpu_percent(sample=sample_cpu),
|
|
"load1": load1,
|
|
"cpu_cores": nproc,
|
|
**mem,
|
|
}
|
|
_snapshot_cache = out
|
|
_snapshot_cache_at = now
|
|
return dict(out)
|
|
|
|
|
|
def live_youtube_push_active() -> bool:
|
|
"""True when at least one YouTube live relay ffmpeg is pushing."""
|
|
try:
|
|
from .youtube_relay_pipeline import youtube_relay_pipeline as rp
|
|
|
|
flags = rp.pushing_flags() or {}
|
|
return any(bool((v or {}).get("is_pushing")) for v in flags.values())
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def clip_encode_defer_reason(*, respect_live_push: bool = True) -> str:
|
|
"""Why clip ffmpeg should wait. Empty string = OK to start encode.
|
|
|
|
Live relay must keep CPU headroom; concurrent yt_long/shorts encode is what
|
|
wedged dy.nomadro.live (load~47) while identical code on dylive stayed up.
|
|
"""
|
|
if respect_live_push and live_youtube_push_active():
|
|
return "live_relay_pushing"
|
|
snap = snapshot(sample_cpu=False)
|
|
cores = max(1, int(snap.get("cpu_cores") or 1))
|
|
load1 = float(snap.get("load1") or 0.0)
|
|
cpu = float(snap.get("cpu_percent") or 0.0)
|
|
# Leave ~1 core free for API accept loop + Neko CDP.
|
|
if load1 >= max(1.5, cores * 1.15):
|
|
return f"load1={load1}"
|
|
if cpu >= 80.0:
|
|
return f"cpu={cpu}"
|
|
return ""
|