sh2/d2ypp2/src/web_process_backend.py
2026-06-14 10:41:48 -05:00

1210 lines
45 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Web 控制台进程后端:优先 PM2,不可用时回退为本地 PID 注册表(仅 Linux)。
"""
from __future__ import annotations
import asyncio
import contextlib
import json
import os
import re
import shlex
import signal
import subprocess
import sys
import time
from pathlib import Path
from typing import Any, Iterable, Optional
BACKEND_STATE_VERSION = 1
if not hasattr(os, "getpgid"):
def _unsupported_getpgid(pid: int) -> int:
raise OSError("process groups are not supported on this platform")
os.getpgid = _unsupported_getpgid # type: ignore[attr-defined]
def strip_ansi_codes(text: str) -> str:
return re.sub(r"\x1b\[[0-9;]*m", "", text)
def _looks_like_null_device(path: str | None) -> bool:
if not path:
return True
norm = str(path).replace("\\", "/").lower()
return "/dev/null" in norm or norm.endswith("/nul") or norm == "nul"
def _truncate_text_log(path: str | None) -> None:
if _looks_like_null_device(path):
return
log_path = Path(str(path))
try:
log_path.parent.mkdir(parents=True, exist_ok=True)
with log_path.open("w", encoding="utf-8", errors="ignore"):
pass
except OSError:
pass
async def _shell_out(cmd: str, timeout: float = 15.0) -> tuple[int, str]:
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
try:
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
except asyncio.TimeoutError:
with contextlib.suppress(ProcessLookupError):
proc.kill()
with contextlib.suppress(ProcessLookupError):
await proc.wait()
return 124, "ERROR: 命令超时"
out = (stdout or b"").decode(errors="ignore").strip()
err = (stderr or b"").decode(errors="ignore").strip()
text = out if out else err
return proc.returncode or 0, text if text else "命令执行完成(无输出)"
async def pm2_available() -> bool:
pm2_bin = resolve_pm2_bin()
if not pm2_bin:
return False
code, _ = await _shell_out(f"{shlex.quote(pm2_bin)} -v", timeout=5.0)
return code == 0
async def run_pm2_result(cmd: str, timeout: float = 15.0) -> tuple[int, str]:
pm2_bin = resolve_pm2_bin()
if not pm2_bin:
return 127, "ERROR: pm2 is not available"
return await _shell_out(f"{shlex.quote(pm2_bin)} {cmd}", timeout=timeout)
async def run_pm2(cmd: str, timeout: float = 15.0) -> str:
_, text = await run_pm2_result(cmd, timeout=timeout)
return text
def _ffmpeg_cmdline_markers(process_name: str, project_root: Path | None) -> list[str]:
safe = re.sub(r"[^a-zA-Z0-9_.-]", "_", process_name).strip()
markers: set[str] = set()
if project_root is not None and safe:
config_dir = project_root / "config"
markers.update(
{
f"youtube.{safe}.ini",
f"URL_config.{safe}.ini",
str(config_dir / f"youtube.{safe}.ini"),
str(config_dir / f"URL_config.{safe}.ini"),
}
)
ini_path = config_dir / f"youtube.{safe}.ini"
if ini_path.is_file():
try:
text = ini_path.read_text(encoding="utf-8", errors="replace")
except OSError:
text = ""
for line in text.splitlines():
match = re.match(r"^\s*key\s*=\s*(.+)$", line, flags=re.IGNORECASE)
if not match:
continue
value = match.group(1).strip().split("#", 1)[0].strip()
if not value:
continue
if "live2/" in value:
stream_key = value.rsplit("live2/", 1)[-1].strip("/")
else:
stream_key = value
if stream_key:
markers.add(stream_key)
markers.add(f"live2/{stream_key}")
break
return [m for m in markers if m]
def _read_proc_cmdline(pid: int) -> str:
try:
raw = (Path("/proc") / str(pid) / "cmdline").read_bytes()
except OSError:
return ""
if not raw:
return ""
return raw.replace(b"\0", b" ").decode("utf-8", "replace")
def _read_proc_env_value(pid: int, key: str) -> str:
try:
raw = (Path("/proc") / str(pid) / "environ").read_bytes()
except OSError:
return ""
prefix = f"{key}=".encode("utf-8")
for chunk in raw.split(b"\0"):
if chunk.startswith(prefix):
return chunk[len(prefix) :].decode("utf-8", "replace").strip()
return ""
def _ffmpeg_pid_matches_process(pid: int, process_name: str) -> bool:
target = (process_name or "").strip()
if not target:
return False
for key in ("LIVE_PM2_PROCESS_NAME", "PM2_SERVICE_NAME"):
if _read_proc_env_value(pid, key) == target:
return True
return False
def _proc_parent_and_group(pid: int) -> tuple[int | None, int | None]:
try:
raw = (Path("/proc") / str(pid) / "stat").read_text(encoding="utf-8", errors="ignore")
except OSError:
return None, None
end = raw.rfind(")")
if end < 0:
return None, None
tail = raw[end + 2 :].split()
if len(tail) < 3:
return None, None
try:
return int(tail[1]), int(tail[2])
except ValueError:
return None, None
def _linux_ffmpeg_pids_for_process_tree(root_pid: int, *, root_pgid: int | None = None) -> list[int]:
if root_pid <= 0:
return []
proc_root = Path("/proc")
if not proc_root.is_dir():
return []
children_map: dict[int, list[int]] = {}
group_map: dict[int, int] = {}
ffmpeg_pids: set[int] = set()
for entry in proc_root.iterdir():
if not entry.name.isdigit():
continue
try:
pid = int(entry.name)
except ValueError:
continue
parent_pid, process_group = _proc_parent_and_group(pid)
if parent_pid is not None:
children_map.setdefault(parent_pid, []).append(pid)
if process_group is not None:
group_map[pid] = process_group
if "ffmpeg" in _read_proc_cmdline(pid).lower():
ffmpeg_pids.add(pid)
descendants = {root_pid}
queue = [root_pid]
while queue:
current = queue.pop()
children = [pid for pid in children_map.get(current, []) if pid not in descendants]
if not children:
continue
descendants.update(children)
queue.extend(children)
group = root_pgid if root_pgid and root_pgid > 0 else group_map.get(root_pid)
matched = {
pid
for pid in ffmpeg_pids
if pid in descendants or (group is not None and group > 0 and group_map.get(pid) == group)
}
return sorted(matched)
def _linux_ffmpeg_pids_for_stack(process_name: str, project_root: Path | None) -> list[int]:
"""仅匹配继承了目标进程环境变量的 ffmpeg,避免按关键词误杀其它线路。"""
markers = _ffmpeg_cmdline_markers(process_name, project_root)
seen: set[int] = set()
proc_root = Path("/proc")
if not proc_root.is_dir():
return []
for entry in proc_root.iterdir():
if not entry.name.isdigit():
continue
try:
pid = int(entry.name)
except ValueError:
continue
cmdline = entry / "cmdline"
try:
raw = cmdline.read_bytes()
except OSError:
continue
if not raw or b"ffmpeg" not in raw.lower():
continue
if _ffmpeg_pid_matches_process(pid, process_name):
seen.add(pid)
continue
cmd = raw.replace(b"\0", b" ").decode("utf-8", "replace")
if any(m in cmd for m in markers):
seen.add(pid)
return sorted(seen)
def _signal_pids(pids: Iterable[int], sig: int) -> None:
for pid in pids:
try:
os.kill(pid, sig)
except (ProcessLookupError, PermissionError):
pass
async def force_kill_ffmpeg(
process_name: str,
project_root: Path | None = None,
*,
root_pid: int | None = None,
root_pgid: int | None = None,
) -> None:
"""结束与本业务相关的 ffmpeg:按 /proc 命令行匹配 + 可选 pkill。"""
pids = _linux_ffmpeg_pids_for_process_tree(int(root_pid or 0), root_pgid=root_pgid)
if not pids:
pids = _linux_ffmpeg_pids_for_stack(process_name, project_root)
if pids:
_signal_pids(pids, signal.SIGTERM)
await asyncio.sleep(0.6)
remaining = _linux_ffmpeg_pids_for_process_tree(int(root_pid or 0), root_pgid=root_pgid)
if not remaining:
remaining = _linux_ffmpeg_pids_for_stack(process_name, project_root)
if remaining:
_signal_pids(remaining, signal.SIGKILL)
await asyncio.sleep(0.2)
safe = re.sub(r"[^a-zA-Z0-9_.-]", "", process_name) or "x"
if safe != process_name:
proc = await asyncio.create_subprocess_shell(
f"pkill -f 'ffmpeg.*{safe}' || true",
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
await proc.wait()
class LocalProcessRegistry:
"""无 PM2 时:用 JSON 记录 pid,日志写入 .pm2/logs。"""
def __init__(self, base_dir: Path, log_dir: Path):
self.base_dir = base_dir.resolve()
self.log_dir = log_dir
self.state_path = self.base_dir / ".process_runner" / "state.json"
self._lock = asyncio.Lock()
def _read_state(self) -> dict[str, Any]:
if not self.state_path.exists():
return {"version": BACKEND_STATE_VERSION, "processes": {}}
try:
data = json.loads(self.state_path.read_text(encoding="utf-8"))
if not isinstance(data.get("processes"), dict):
data["processes"] = {}
return data
except Exception:
return {"version": BACKEND_STATE_VERSION, "processes": {}}
def _write_state(self, data: dict[str, Any]) -> None:
self.state_path.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps(data, indent=2, ensure_ascii=False)
tmp = self.state_path.with_suffix(".json.tmp")
tmp.write_text(payload, encoding="utf-8")
os.replace(str(tmp), str(self.state_path))
def _pid_alive(self, pid: int) -> bool:
if pid <= 0:
return False
try:
os.kill(pid, 0)
return True
except OSError:
return False
def _kill_tree(self, pid: int) -> None:
if pid <= 0:
return
try:
os.killpg(os.getpgid(pid), signal.SIGTERM)
except (ProcessLookupError, PermissionError, OSError):
try:
os.kill(pid, signal.SIGTERM)
except ProcessLookupError:
pass
def build_command(self, script: str) -> Optional[list[str]]:
path = self.base_dir / script
if not path.is_file():
return None
if script.lower().endswith(".py"):
return [sys.executable, str(path)]
if script.lower().endswith(".sh"):
bash = shutil_which("bash") or shutil_which("sh")
if not bash:
return None
return [bash, str(path)]
return None
async def start(self, name: str, script: str) -> str:
async with self._lock:
data = self._read_state()
procs = data["processes"]
if name in procs:
old_pid = int(procs[name].get("pid") or 0)
if self._pid_alive(old_pid):
return f"进程 {name} 已在运行 (PID {old_pid})"
cmd = self.build_command(script)
if not cmd:
return f"ERROR: 无法启动 {script}(文件不存在或缺少 bash/sh)"
self.log_dir.mkdir(parents=True, exist_ok=True)
_truncate_text_log(self.log_dir / f"{name}-out.log")
_truncate_text_log(self.log_dir / f"{name}-error.log")
out_log = open(self.log_dir / f"{name}-out.log", "a", encoding="utf-8", errors="ignore")
err_log = open(self.log_dir / f"{name}-error.log", "a", encoding="utf-8", errors="ignore")
try:
child_env = os.environ.copy()
child_env["LIVE_PM2_PROCESS_NAME"] = name
child_env["PYTHONUNBUFFERED"] = "1"
child_env["PYTHONIOENCODING"] = "utf-8"
kw: dict[str, Any] = {
"cwd": str(self.base_dir),
"stdout": out_log,
"stderr": err_log,
"preexec_fn": os.setsid,
"env": child_env,
}
proc = await asyncio.create_subprocess_exec(*cmd, **kw)
except Exception as e:
out_log.close()
err_log.close()
return f"ERROR: 启动失败: {e}"
out_log.close()
err_log.close()
procs[name] = {
"pid": proc.pid,
"script": script,
"started_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
}
self._write_state(data)
return f"已本地启动 {name} (PID {proc.pid}),命令: {' '.join(cmd)}"
async def stop(self, name: str) -> str:
async with self._lock:
data = self._read_state()
procs = data["processes"]
if name not in procs:
return f"进程 {name} 未在本地注册表中"
pid = int(procs[name].get("pid") or 0)
if self._pid_alive(pid):
self._kill_tree(pid)
await asyncio.sleep(0.5)
procs.pop(name, None)
self._write_state(data)
return f"已停止 {name}(本地后端)"
async def restart(self, name: str, script: str) -> str:
await self.stop(name)
await asyncio.sleep(0.3)
return await self.start(name, script)
def describe_status(self, name: str) -> dict[str, Any]:
data = self._read_state()
procs = data.get("processes") or {}
out_path = str(self.log_dir / f"{name}-out.log")
err_path = str(self.log_dir / f"{name}-error.log")
if name not in procs:
return {
"process_status": "not_found",
"out_path": out_path,
"err_path": err_path,
}
pid = int(procs[name].get("pid") or 0)
if self._pid_alive(pid):
status = "online"
else:
status = "stopped"
return {
"process_status": status,
"out_path": out_path,
"err_path": err_path,
"pid": pid if status == "online" else 0,
}
def status_table_text(self) -> str:
data = self._read_state()
lines = ["┌─────────────┬──────────┬──────────────────────────┐", "│ name │ status │ pid │", "├─────────────┼──────────┼──────────────────────────┤"]
for name, info in sorted((data.get("processes") or {}).items()):
pid = int(info.get("pid") or 0)
st = "online" if self._pid_alive(pid) else "stopped"
lines.append(f"│ {name:<11} │ {st:<8} │ {pid:<24} │")
lines.append("└─────────────┴──────────┴──────────────────────────┘")
lines.append("(本地进程后端,非 PM2)")
return "\n".join(lines)
def shutil_which(cmd: str) -> Optional[str]:
from shutil import which
return which(cmd)
def resolve_pm2_bin() -> Optional[str]:
for candidate in (shutil_which("pm2"), "/usr/local/bin/pm2", "/usr/bin/pm2"):
if candidate and Path(candidate).is_file() and os.access(candidate, os.X_OK):
return candidate
return None
def preferred_python_interpreter(base_dir: Path) -> str:
venv_python = base_dir / ".venv" / "bin" / "python"
if venv_python.is_file() and os.access(str(venv_python), os.X_OK):
return str(venv_python)
for candidate in (shutil_which("python3"), shutil_which("python")):
if not candidate:
continue
return str(candidate)
for candidate in (sys.executable,):
if not candidate:
continue
path = Path(candidate).expanduser()
if path.is_file() and os.access(str(path), os.X_OK):
return str(path)
return "python3"
def _resolved_pm2_item_path(item: dict[str, Any], *keys: str) -> Optional[Path]:
env = item.get("pm2_env") if isinstance(item.get("pm2_env"), dict) else {}
for key in keys:
raw = env.get(key)
if raw in (None, ""):
raw = item.get(key)
value = str(raw or "").strip()
if value:
return Path(value).expanduser()
return None
def _samefile_or_resolved_path(left: Path, right: Path) -> bool:
try:
return left.resolve() == right.resolve()
except OSError:
return False
def pm2_process_entry_needs_recreate(base_dir: Path, process: str, script: str, item: dict[str, Any] | None) -> bool:
if not item:
return False
script_path = (base_dir / script).resolve()
configured_script = _resolved_pm2_item_path(item, "pm_exec_path")
if configured_script is None or not _samefile_or_resolved_path(configured_script, script_path):
return True
configured_cwd = _resolved_pm2_item_path(item, "pm_cwd", "cwd")
if configured_cwd is None or not _samefile_or_resolved_path(configured_cwd, base_dir.resolve()):
return True
suffix = script_path.suffix.lower()
if suffix == ".py":
interpreter = _resolved_pm2_item_path(item, "exec_interpreter")
if interpreter is None or not interpreter.is_file() or not os.access(str(interpreter), os.X_OK):
return True
elif suffix == ".sh":
interpreter = _resolved_pm2_item_path(item, "exec_interpreter")
if interpreter is not None and (not interpreter.is_file() or not os.access(str(interpreter), os.X_OK)):
return True
return False
def build_pm2_start_command(base_dir: Path, process: str, script: str) -> Optional[str]:
script_path = (base_dir / script).resolve()
if not script_path.is_file():
return None
env_bits = [
f"LIVE_PM2_PROCESS_NAME={shlex.quote(process)}",
"PYTHONUNBUFFERED=1",
f"PYTHONPATH={shlex.quote(str(base_dir))}:${{PYTHONPATH:-}}",
]
for key in (
"http_proxy",
"https_proxy",
"all_proxy",
"HTTP_PROXY",
"HTTPS_PROXY",
"ALL_PROXY",
"no_proxy",
"NO_PROXY",
"LIVE_YOUTUBE_NETWORK_MODE",
"YOUTUBE_PUSH_PROXY",
"LIVE_YOUTUBE_PUSH_PROXY",
"YOUTUBE_PUSH_PROXY_MODE",
"LIVE_YOUTUBE_PUSH_PROXY_MODE",
"YOUTUBE_PUSH_PROXY_AUTO",
"SHELLCRASH_ATTACH_FFMPEG",
):
value = os.environ.get(key)
if value:
env_bits.append(f"{key}={shlex.quote(value)}")
pm2_bin = resolve_pm2_bin() or "pm2"
cmd_bits = [
shlex.quote(pm2_bin),
"start",
shlex.quote(str(script_path)),
"--name",
shlex.quote(process),
"--cwd",
shlex.quote(str(base_dir)),
"--time",
"--update-env",
]
suffix = script_path.suffix.lower()
if suffix == ".py":
cmd_bits.extend(["--interpreter", shlex.quote(preferred_python_interpreter(base_dir))])
elif suffix == ".sh":
shell = shutil_which("bash") or shutil_which("sh")
if shell:
cmd_bits.extend(["--interpreter", shlex.quote(shell)])
return " ".join(env_bits + cmd_bits)
def _pm2_log_slug(name: str) -> str:
return re.sub(r"[^A-Za-z0-9]", "-", str(name or "").strip()) or "process"
class WebProcessBackend:
def __init__(self, base_dir: Path, default_log_dir: Path):
self.base_dir = base_dir
self.default_log_dir = default_log_dir
self._local = LocalProcessRegistry(base_dir, default_log_dir)
self._pm2_desired_state_path = self.base_dir / ".process_runner" / "pm2_desired.json"
self._use_pm2: Optional[bool] = None
self._pm2_resurrect_lock = asyncio.Lock()
self._pm2_last_daemon_pid: Optional[int] = None
self._pm2_last_resurrect_attempt: float = 0.0
self._pm2_last_start_attempt: dict[str, float] = {}
self._pm2_jlist_cache_ttl: float = 0.8
self._pm2_jlist_stale_grace: float = 2.0
self._pm2_jlist_cached_at: float = 0.0
self._pm2_jlist_cache: list[dict[str, Any]] | None = None
self._pm2_dump_cache_ttl: float = 5.0
self._pm2_dump_cached_at: float = 0.0
self._pm2_dump_names_cache: set[str] | None = None
self._proc_runtime_cache_ttl: float = 0.8
self._proc_runtime_cached_at: float = 0.0
self._proc_runtime_cache: dict[str, dict[str, Any]] | None = None
self._ffmpeg_pid_cache_ttl: float = 0.8
self._ffmpeg_pid_cache: dict[tuple[str, int], tuple[float, list[int]]] = {}
async def refresh_mode(self) -> None:
self._use_pm2 = await pm2_available()
if self._use_pm2:
self.invalidate_pm2_cache()
@property
def mode(self) -> str:
if self._use_pm2 is None:
return "unknown"
return "pm2" if self._use_pm2 else "local"
async def ensure_mode(self) -> None:
if self._use_pm2 is None or (not self._use_pm2 and resolve_pm2_bin()):
await self.refresh_mode()
async def ensure_pm2_runtime(self) -> None:
await self.ensure_mode()
if self._use_pm2:
await self._ensure_pm2_process_table()
def invalidate_pm2_cache(self) -> None:
self._pm2_jlist_cache = None
self._pm2_jlist_cached_at = 0.0
self._pm2_dump_names_cache = None
self._pm2_dump_cached_at = 0.0
self._proc_runtime_cache = None
self._proc_runtime_cached_at = 0.0
self._ffmpeg_pid_cache.clear()
def _pm2_home_dir(self) -> Path:
raw = (os.environ.get("PM2_HOME") or "").strip()
if raw:
return Path(raw).expanduser()
home = (os.environ.get("HOME") or "").strip()
if home:
return Path(home).expanduser() / ".pm2"
return Path.home() / ".pm2"
def _pm2_pid_value(self) -> Optional[int]:
path = self._pm2_home_dir() / "pm2.pid"
try:
value = int(path.read_text(encoding="utf-8", errors="ignore").strip() or "0")
except (OSError, ValueError):
return None
return value if value > 0 else None
def _pm2_dump_has_entries(self) -> bool:
path = self._pm2_home_dir() / "dump.pm2"
if not path.is_file():
return False
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
try:
return path.stat().st_size > 2
except OSError:
return False
if not isinstance(payload, list):
return False
return any(isinstance(item, dict) and str(item.get("name") or "").strip() for item in payload)
def _pm2_dump_registered_names(self) -> set[str]:
now = time.monotonic()
if (
self._pm2_dump_names_cache is not None
and now - self._pm2_dump_cached_at <= self._pm2_dump_cache_ttl
):
return set(self._pm2_dump_names_cache)
path = self._pm2_home_dir() / "dump.pm2"
names: set[str] = set()
if path.is_file():
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
payload = []
if isinstance(payload, list):
for item in payload:
if not isinstance(item, dict):
continue
name = str(item.get("name") or "").strip()
if name:
names.add(name)
self._pm2_dump_names_cache = names
self._pm2_dump_cached_at = now
return set(names)
def _pm2_default_log_paths(self, process: str) -> tuple[str, str]:
log_dir = self._pm2_home_dir() / "logs"
slug = _pm2_log_slug(process)
return str(log_dir / f"{slug}-out.log"), str(log_dir / f"{slug}-error.log")
async def _proc_runtime_items(self) -> dict[str, dict[str, Any]]:
now = time.monotonic()
if (
self._proc_runtime_cache is not None
and now - self._proc_runtime_cached_at <= self._proc_runtime_cache_ttl
):
return {name: dict(info) for name, info in self._proc_runtime_cache.items()}
proc_root = Path("/proc")
if not proc_root.is_dir():
self._proc_runtime_cache = {}
self._proc_runtime_cached_at = now
return {}
chosen: dict[str, tuple[int, dict[str, Any]]] = {}
for entry in proc_root.iterdir():
if not entry.name.isdigit():
continue
try:
pid = int(entry.name)
except ValueError:
continue
process_name = _read_proc_env_value(pid, "LIVE_PM2_PROCESS_NAME")
if not process_name:
continue
cmdline = _read_proc_cmdline(pid)
if not cmdline or "ffmpeg" in cmdline.lower():
continue
parent_pid, process_group = _proc_parent_and_group(pid)
score = 0
if process_group and process_group == pid:
score += 100
if ".py" in cmdline or "python" in cmdline or "bash" in cmdline or " sh " in f" {cmdline} ":
score += 10
if parent_pid == 1:
score += 5
info = {
"pid": pid,
"ppid": parent_pid or 0,
"pgid": process_group or 0,
"cmdline": cmdline,
}
current = chosen.get(process_name)
if current is None or score > current[0] or (score == current[0] and pid < int(current[1].get("pid") or 0)):
chosen[process_name] = (score, info)
snapshot = {name: dict(info) for name, (_, info) in chosen.items()}
self._proc_runtime_cache = snapshot
self._proc_runtime_cached_at = now
return {name: dict(info) for name, info in snapshot.items()}
def _read_pm2_desired_state(self) -> dict[str, bool]:
path = self._pm2_desired_state_path
if not path.is_file():
return {}
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return {}
desired = payload.get("desired") if isinstance(payload, dict) else {}
if not isinstance(desired, dict):
return {}
out: dict[str, bool] = {}
for name, value in desired.items():
key = str(name or "").strip()
if key:
out[key] = bool(value)
return out
def _write_pm2_desired_state(self, desired: dict[str, bool]) -> None:
path = self._pm2_desired_state_path
path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"version": BACKEND_STATE_VERSION,
"desired": {str(name): bool(value) for name, value in sorted(desired.items()) if str(name).strip()},
}
tmp = path.with_suffix(".json.tmp")
tmp.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
os.replace(str(tmp), str(path))
async def _set_pm2_desired_running(self, process: str, should_run: bool) -> None:
desired = self._read_pm2_desired_state()
desired[str(process)] = bool(should_run)
self._write_pm2_desired_state(desired)
async def _pm2_jlist_items(self, *, force_refresh: bool = False) -> list[dict[str, Any]]:
now = time.monotonic()
if (
not force_refresh
and self._pm2_jlist_cache is not None
and now - self._pm2_jlist_cached_at <= self._pm2_jlist_cache_ttl
):
return list(self._pm2_jlist_cache)
pm2_bin = resolve_pm2_bin()
if not pm2_bin:
self.invalidate_pm2_cache()
return []
code, text = await _shell_out(f"{shlex.quote(pm2_bin)} jlist", timeout=20.0)
if code != 0 or not text.strip():
if (
self._pm2_jlist_cache is not None
and now - self._pm2_jlist_cached_at <= self._pm2_jlist_stale_grace
):
return list(self._pm2_jlist_cache)
self._pm2_jlist_cache = []
self._pm2_jlist_cached_at = now
return []
try:
items = json.loads(text)
except json.JSONDecodeError:
if (
self._pm2_jlist_cache is not None
and now - self._pm2_jlist_cached_at <= self._pm2_jlist_stale_grace
):
return list(self._pm2_jlist_cache)
self._pm2_jlist_cache = []
self._pm2_jlist_cached_at = now
return []
if not isinstance(items, list):
self._pm2_jlist_cache = []
self._pm2_jlist_cached_at = now
return []
filtered = [item for item in items if isinstance(item, dict)]
self._pm2_jlist_cache = filtered
self._pm2_jlist_cached_at = now
return list(filtered)
async def _pm2_jlist_index(self, *, force_refresh: bool = False) -> dict[str, dict[str, Any]]:
items = await self._pm2_jlist_items(force_refresh=force_refresh)
out: dict[str, dict[str, Any]] = {}
for item in items:
name = str(item.get("name") or "").strip()
if name:
out[name] = item
return out
def _pm2_info_from_item(self, process: str, item: dict[str, Any] | None) -> dict[str, Any]:
if not item:
return {
"process_status": "not_found",
"out_path": None,
"err_path": None,
"pid": 0,
}
env = item.get("pm2_env") if isinstance(item.get("pm2_env"), dict) else {}
raw_pid = item.get("pid")
try:
pid = int(raw_pid or 0)
except (TypeError, ValueError):
pid = 0
status = str(env.get("status") or item.get("status") or "").strip().lower()
if not status:
status = "online" if pid > 0 else "unknown"
out_path = env.get("pm_out_log_path") or item.get("pm_out_log_path")
err_path = env.get("pm_err_log_path") or item.get("pm_err_log_path")
if not out_path:
out_path = str(self.default_log_dir / f"{process}-out.log")
if not err_path:
err_path = str(self.default_log_dir / f"{process}-error.log")
return {
"process_status": status,
"out_path": out_path,
"err_path": err_path,
"pid": pid if pid > 0 else 0,
}
async def _ensure_pm2_process_table(self) -> None:
daemon_pid = self._pm2_pid_value()
if daemon_pid != self._pm2_last_daemon_pid:
self._pm2_last_daemon_pid = daemon_pid
self._pm2_last_resurrect_attempt = 0.0
self.invalidate_pm2_cache()
items = await self._pm2_jlist_items()
if items:
return
if not self._pm2_dump_has_entries():
return
now = time.monotonic()
if now - self._pm2_last_resurrect_attempt < 5.0:
return
async with self._pm2_resurrect_lock:
daemon_pid = self._pm2_pid_value()
if daemon_pid != self._pm2_last_daemon_pid:
self._pm2_last_daemon_pid = daemon_pid
self._pm2_last_resurrect_attempt = 0.0
self.invalidate_pm2_cache()
if await self._pm2_jlist_items():
return
if not self._pm2_dump_has_entries():
return
now = time.monotonic()
if now - self._pm2_last_resurrect_attempt < 5.0:
return
self._pm2_last_resurrect_attempt = now
with contextlib.suppress(Exception):
code, _ = await run_pm2_result("resurrect", timeout=45.0)
if code == 0:
self.invalidate_pm2_cache()
await asyncio.sleep(0.2)
await self._ensure_desired_pm2_processes()
async def _ensure_desired_pm2_processes(self) -> None:
desired = self._read_pm2_desired_state()
if not desired:
return
items = await self._pm2_jlist_items()
if not items:
return
for item in items:
name = str(item.get("name") or "").strip()
if not name or not desired.get(name):
continue
env = item.get("pm2_env") if isinstance(item.get("pm2_env"), dict) else {}
status = str(env.get("status") or "").lower()
if status in {"online", "running", "launching"}:
continue
now = time.monotonic()
last = self._pm2_last_start_attempt.get(name, 0.0)
if now - last < 5.0:
continue
self._pm2_last_start_attempt[name] = now
with contextlib.suppress(Exception):
code, _ = await run_pm2_result(f"start {name} --update-env", timeout=45.0)
if code == 0:
self.invalidate_pm2_cache()
await asyncio.sleep(0.2)
async def online_process_names(self) -> list[str]:
"""当前在线的 PM2 / 本地注册进程名(用于 TikTok·OBS 等 HDMI 链路互斥)。"""
await self.ensure_mode()
if not self._use_pm2:
data = self._local._read_state()
names: list[str] = []
for name, row in (data.get("processes") or {}).items():
try:
pid = int((row or {}).get("pid") or 0)
except (TypeError, ValueError):
continue
if self._local._pid_alive(pid):
names.append(str(name))
return sorted(names)
runtime = await self._proc_runtime_items()
return sorted(runtime)
async def _pm2_registered_names(self) -> set[str]:
desired = {
str(name).strip()
for name in self._read_pm2_desired_state().keys()
if str(name).strip()
}
runtime = set(await self.online_process_names())
jlist = set((await self._pm2_jlist_index()).keys())
return self._pm2_dump_registered_names() | desired | runtime | jlist
async def clear_process_logs(self, process: str) -> None:
await self.ensure_mode()
candidates: set[str] = {
str(self.default_log_dir / f"{process}-out.log"),
str(self.default_log_dir / f"{process}-error.log"),
}
try:
info = await self.parse_pm2_describe(process)
except Exception:
info = {}
for key in ("out_path", "err_path"):
value = info.get(key)
if value:
candidates.add(str(value))
for path in sorted(candidates):
if not _looks_like_null_device(path):
_truncate_text_log(path)
async def process_infos(self, processes: Iterable[str]) -> dict[str, dict[str, Any]]:
await self.ensure_mode()
names: list[str] = []
seen: set[str] = set()
for raw_name in processes:
name = str(raw_name or "").strip()
if not name or name in seen:
continue
seen.add(name)
names.append(name)
if not self._use_pm2:
runtime = await self._proc_runtime_items()
out: dict[str, dict[str, Any]] = {}
for name in names:
info = self._local.describe_status(name)
runtime_info = runtime.get(name)
if runtime_info:
info = dict(info)
info["process_status"] = "online"
info["pid"] = int(runtime_info.get("pid") or info.get("pid") or 0)
out[name] = info
return out
jlist = await self._pm2_jlist_index()
runtime = await self._proc_runtime_items()
known = self._pm2_dump_registered_names() | {
str(name).strip()
for name in self._read_pm2_desired_state().keys()
if str(name).strip()
} | set(jlist) | set(runtime)
out: dict[str, dict[str, Any]] = {}
for name in names:
process_info = runtime.get(name)
item_info = self._pm2_info_from_item(name, jlist.get(name)) if name in jlist else {}
default_out_path, default_err_path = self._pm2_default_log_paths(name)
out_path = item_info.get("out_path") or default_out_path
err_path = item_info.get("err_path") or default_err_path
if process_info is not None:
item_status = str(item_info.get("process_status") or "").strip().lower()
status = item_status if item_status in {"online", "running", "launching"} else "online"
out[name] = {
"process_status": status,
"out_path": out_path,
"err_path": err_path,
"pid": int(process_info.get("pid") or item_info.get("pid") or 0),
}
elif item_info:
out[name] = item_info
elif name in known:
out[name] = {
"process_status": "stopped",
"out_path": out_path,
"err_path": err_path,
"pid": 0,
}
else:
out[name] = {
"process_status": "not_found",
"out_path": None,
"err_path": None,
"pid": 0,
}
return out
async def process_pid(self, process: str) -> int:
await self.ensure_mode()
if not self._use_pm2:
info = self._local.describe_status(process)
try:
pid = int(info.get("pid") or 0)
except (TypeError, ValueError):
return 0
return pid if self._local._pid_alive(pid) else 0
info = (await self.process_infos([process])).get(process) or {}
try:
pid = int(info.get("pid") or 0)
except (TypeError, ValueError):
return 0
return pid if pid > 0 else 0
async def live_ffmpeg_pids(self, process: str, info: Optional[dict[str, Any]] = None) -> list[int]:
if info is None:
info = (await self.process_infos([process])).get(process) or {}
try:
pid = int(info.get("pid") or 0)
except (TypeError, ValueError):
pid = 0
if pid <= 0:
return []
try:
pgid = os.getpgid(pid)
except OSError:
pgid = None
cache_key = (str(process or "").strip(), pid)
now = time.monotonic()
cached = self._ffmpeg_pid_cache.get(cache_key)
if cached and now - cached[0] <= self._ffmpeg_pid_cache_ttl:
return list(cached[1])
result = await asyncio.to_thread(_linux_ffmpeg_pids_for_process_tree, pid, root_pgid=pgid)
if not result:
result = await asyncio.to_thread(_linux_ffmpeg_pids_for_stack, process, self.base_dir)
self._ffmpeg_pid_cache[cache_key] = (now, list(result))
return result
async def _pm2_save(self) -> None:
if not self._use_pm2:
return
with contextlib.suppress(Exception):
await run_pm2("save", timeout=20.0)
async def _pm2_start_fresh(self, process: str, script: str) -> str:
await self.clear_process_logs(process)
cmd = build_pm2_start_command(self.base_dir, process, script)
if not cmd:
return f"ERROR: script not found: {script}"
code, text = await _shell_out(cmd, timeout=45.0)
if code == 0:
await self._set_pm2_desired_running(process, True)
await self._pm2_save()
self.invalidate_pm2_cache()
return text
async def _pm2_delete_existing_process(self, process: str) -> None:
with contextlib.suppress(Exception):
await run_pm2_result(f"delete {process}", timeout=20.0)
self.invalidate_pm2_cache()
await asyncio.sleep(0.2)
async def start(self, process: str, script: str) -> str:
await self.ensure_pm2_runtime()
if self._use_pm2:
item = (await self._pm2_jlist_index(force_refresh=True)).get(process)
if pm2_process_entry_needs_recreate(self.base_dir, process, script, item):
await self._pm2_delete_existing_process(process)
item = None
if item is not None:
info = self._pm2_info_from_item(process, item)
if str(info.get("process_status") or "").lower() not in ("online", "running"):
await self.clear_process_logs(process)
code, text = await run_pm2_result(f"start {process} --update-env")
if code == 0:
await self._set_pm2_desired_running(process, True)
await self._pm2_save()
self.invalidate_pm2_cache()
return text
return await self._pm2_start_fresh(process, script)
return await self._local.start(process, script)
async def stop(self, process: str) -> str:
await self.ensure_pm2_runtime()
if self._use_pm2:
code, text = await run_pm2_result(f"stop {process}")
if code == 0:
await self._set_pm2_desired_running(process, False)
await self._pm2_save()
self.invalidate_pm2_cache()
return text
return await self._local.stop(process)
async def restart(self, process: str, script: str) -> str:
await self.ensure_pm2_runtime()
if self._use_pm2:
item = (await self._pm2_jlist_index(force_refresh=True)).get(process)
if item is None:
return await self.start(process, script)
if pm2_process_entry_needs_recreate(self.base_dir, process, script, item):
await self._pm2_delete_existing_process(process)
return await self._pm2_start_fresh(process, script)
await self.clear_process_logs(process)
code, text = await run_pm2_result(f"restart {process} --update-env")
if code == 0:
await self._set_pm2_desired_running(process, True)
await self._pm2_save()
self.invalidate_pm2_cache()
return text
return await self._local.restart(process, script)
async def describe_raw(self, process: str) -> str:
await self.ensure_mode()
if self._use_pm2:
return await run_pm2(f"describe {process}", timeout=10.0)
info = self._local.describe_status(process)
if info["process_status"] == "not_found":
return "No such process"
return f"status │ {info['process_status']}\nout_log_path │ {info['out_path']}\nerr_log_path │ {info['err_path']}"
async def full_status_raw(self) -> str:
await self.ensure_mode()
if self._use_pm2:
known = sorted(await self._pm2_registered_names())
if not known:
return "PM2 process list is empty"
info_map = await self.process_infos(known)
rows: list[tuple[str, str, str]] = []
for name in known:
info = info_map.get(name) or {}
rows.append((name, str(info.get("process_status") or "unknown"), str(info.get("pid") or 0)))
if not rows:
return "PM2 process list is empty"
name_w = max(len("name"), *(len(name) for name, _, _ in rows))
status_w = max(len("status"), *(len(status) for _, status, _ in rows))
pid_w = max(len("pid"), *(len(pid) for _, _, pid in rows))
lines = [
f"{'name':<{name_w}} {'status':<{status_w}} {'pid':<{pid_w}}",
f"{'-' * name_w} {'-' * status_w} {'-' * pid_w}",
]
for name, status, pid in rows:
lines.append(f"{name:<{name_w}} {status:<{status_w}} {pid:<{pid_w}}")
lines.append("(PM2 snapshot from jlist)")
return "\n".join(lines)
return self._local.status_table_text()
async def parse_pm2_describe(self, process: str) -> dict[str, Any]:
info = (await self.process_infos([process])).get(process) or {}
return {
"process_status": str(info.get("process_status") or "not_found"),
"out_path": info.get("out_path"),
"err_path": info.get("err_path"),
"pid": int(info.get("pid") or 0) if str(info.get("pid") or "0").isdigit() else 0,
}