douyinWEB/backend/app/procutil.py
eric fbdc3fc0db Harden dual-VPS API against live+encode CPU storms; document and ship YPP revenue.
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>
2026-09-16 20:50:45 -05:00

138 lines
4.1 KiB
Python

# -*- coding: utf-8 -*-
"""Spawn helpers: keep heavy ffmpeg out of douyinweb-api MemoryAccounting.
Children inherit the service cgroup; under MemoryHigh reclaim the API accept
loop freezes (D-state). Move ffmpeg PIDs into douyinweb-ffmpeg.slice so encode
/ relay push RAM is charged separately.
"""
from __future__ import annotations
import logging
import os
import subprocess
import time
from pathlib import Path
from typing import Any, Sequence
log = logging.getLogger("douyinweb.procutil")
FFMPEG_SLICE = "douyinweb-ffmpeg.slice"
_CGROUP_ROOT = Path("/sys/fs/cgroup")
_procs_path: Path | None = None
_ensured = False
def _resolve_cgroup_procs() -> Path | None:
"""Locate cgroup.procs for the ffmpeg slice (path varies by systemd layout)."""
global _procs_path
if _procs_path and _procs_path.is_file():
return _procs_path
candidates: list[Path] = [
_CGROUP_ROOT / "douyinweb.slice" / FFMPEG_SLICE / "cgroup.procs",
_CGROUP_ROOT / "system.slice" / FFMPEG_SLICE / "cgroup.procs",
_CGROUP_ROOT / FFMPEG_SLICE / "cgroup.procs",
]
try:
r = subprocess.run(
["systemctl", "show", "-p", "ControlGroup", "--value", FFMPEG_SLICE],
capture_output=True,
text=True,
timeout=5,
check=False,
)
cg = (r.stdout or "").strip().lstrip("/")
if cg:
candidates.insert(0, _CGROUP_ROOT / cg / "cgroup.procs")
except Exception:
pass
for p in candidates:
if p.is_file():
_procs_path = p
return p
return None
def ensure_ffmpeg_slice() -> bool:
"""Best-effort: create/start the slice so cgroup.procs is writable."""
global _ensured
if _resolve_cgroup_procs() is not None:
_ensured = True
return True
try:
subprocess.run(
["systemctl", "start", FFMPEG_SLICE],
capture_output=True,
timeout=8,
check=False,
)
except Exception:
pass
ok = _resolve_cgroup_procs() is not None
_ensured = ok
return ok
def detach_pid_from_service_cgroup(pid: int) -> bool:
"""Move *pid* into douyinweb-ffmpeg.slice (no-op on non-Linux / missing cgroup)."""
try:
pid_i = int(pid or 0)
except Exception:
return False
if pid_i <= 1:
return False
if os.name != "posix":
return False
if not ensure_ffmpeg_slice():
return False
procs = _resolve_cgroup_procs()
if procs is None:
return False
try:
# Writing the leader migrates the whole thread-group.
procs.write_text(f"{pid_i}\n", encoding="utf-8")
return True
except Exception as exc:
log.debug("cgroup detach pid=%s failed: %s", pid_i, exc)
return False
def popen_outside_api_cgroup(cmd: Sequence[str], **kwargs: Any) -> subprocess.Popen:
"""subprocess.Popen then migrate into ffmpeg slice."""
proc = subprocess.Popen(cmd, **kwargs) # noqa: S603
try:
if proc.pid:
# Brief yield so kernel registers the task before migrate.
time.sleep(0.02)
if detach_pid_from_service_cgroup(int(proc.pid)):
log.debug("detached pid=%s to %s", proc.pid, FFMPEG_SLICE)
except Exception:
pass
return proc
def run_outside_api_cgroup(
cmd: Sequence[str],
*,
timeout: float | None = None,
capture_output: bool = False,
text: bool = False,
**kwargs: Any,
) -> subprocess.CompletedProcess:
"""Like subprocess.run, but child is moved out of the API cgroup."""
stdout = subprocess.PIPE if capture_output else kwargs.pop("stdout", None)
stderr = subprocess.PIPE if capture_output else kwargs.pop("stderr", None)
proc = popen_outside_api_cgroup(
cmd,
stdout=stdout,
stderr=stderr,
text=text,
**kwargs,
)
try:
out, err = proc.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
proc.kill()
out, err = proc.communicate()
raise subprocess.TimeoutExpired(cmd, timeout, output=out, stderr=err) from None
return subprocess.CompletedProcess(cmd, proc.returncode, out, err)