268 lines
9.9 KiB
Python
268 lines
9.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Relay business/process status — adapted from sh2 process_runtime_status (cloud, no PM2)."""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import time
|
|
from typing import Any
|
|
|
|
_FFMPEG_PROGRESS_RE = re.compile(
|
|
r"frame=\s*(?P<frame>\d+).*?"
|
|
r"(?:fps=\s*(?P<fps>[\d.]+)\s*)?"
|
|
r"(?:time=(?P<h>\d+):(?P<m>\d+):(?P<s>\d+(?:\.\d+)?).*?)?"
|
|
r"bitrate=\s*(?P<bitrate>[\d.]+\s*kbits/s)?.*?"
|
|
r"speed=\s*(?P<speed>\d+(?:\.\d+)?)x",
|
|
re.IGNORECASE,
|
|
)
|
|
|
|
_ERROR_HINTS = (
|
|
"error",
|
|
"failed",
|
|
"403 forbidden",
|
|
"404 not found",
|
|
"unauthorized",
|
|
"forbidden",
|
|
"io error",
|
|
"error opening output",
|
|
)
|
|
|
|
|
|
def _norm_log(text: str) -> str:
|
|
return (text or "").replace("\r\n", "\n").replace("\r", "\n")
|
|
|
|
|
|
def _has_any(text: str, patterns: tuple[str, ...]) -> bool:
|
|
low = text.lower()
|
|
return any(p in low for p in patterns)
|
|
|
|
|
|
def _looks_like_youtube_key_rejected(tail: str) -> bool:
|
|
if not _has_any(tail, ("rtmps://a.rtmps.youtube.com/live2/", "rtmp://a.rtmp.youtube.com/live2/")):
|
|
return False
|
|
if not _has_any(tail, ("error opening output", "error opening output file")):
|
|
return False
|
|
return _has_any(tail, ("io error", "401", "403", "unauthorized", "forbidden", "input/output error"))
|
|
|
|
|
|
def _ffmpeg_progress_samples(tail: str) -> list[dict[str, float | int]]:
|
|
samples: list[dict[str, float | int]] = []
|
|
for match in _FFMPEG_PROGRESS_RE.finditer(tail or ""):
|
|
try:
|
|
frame = int(match.group("frame"))
|
|
speed = float(match.group("speed"))
|
|
media_time = 0.0
|
|
if match.group("h") is not None:
|
|
media_time = (
|
|
int(match.group("h")) * 3600
|
|
+ int(match.group("m")) * 60
|
|
+ float(match.group("s") or 0)
|
|
)
|
|
row: dict[str, float | int] = {"frame": frame, "time": media_time, "speed": speed}
|
|
if match.group("fps"):
|
|
row["fps"] = float(match.group("fps"))
|
|
br = match.group("bitrate") or ""
|
|
m = re.search(r"([\d.]+)", br)
|
|
if m:
|
|
row["bitrate"] = float(m.group(1))
|
|
samples.append(row)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
return samples[-8:]
|
|
|
|
|
|
def _progress_stalled(samples: list[dict[str, float | int]]) -> bool:
|
|
if len(samples) < 3:
|
|
return False
|
|
tail = samples[-3:]
|
|
frames = {int(r["frame"]) for r in tail}
|
|
times = {round(float(r["time"]), 2) for r in tail}
|
|
return len(frames) == 1 and len(times) == 1
|
|
|
|
|
|
def _speed_low(samples: list[dict[str, float | int]], threshold: float = 0.98) -> bool:
|
|
if len(samples) < 4:
|
|
return False
|
|
tail = samples[-4:]
|
|
if not all(float(r["speed"]) < threshold for r in tail):
|
|
return False
|
|
return int(tail[-1]["frame"]) > int(tail[0]["frame"]) or float(tail[-1]["time"]) > float(tail[0]["time"])
|
|
|
|
|
|
def split_relay_logs(lines: list[str] | None) -> tuple[str, str]:
|
|
out: list[str] = []
|
|
err: list[str] = []
|
|
for line in lines or []:
|
|
low = line.lower()
|
|
if any(h in low for h in _ERROR_HINTS):
|
|
err.append(line)
|
|
else:
|
|
out.append(line)
|
|
return "\n".join(out), "\n".join(err)
|
|
|
|
|
|
def summarize_relay_group(
|
|
*,
|
|
group: dict[str, Any],
|
|
st: dict[str, Any],
|
|
session_running: bool,
|
|
pipeline_enabled: bool,
|
|
log_age_seconds: float | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Build process_monitor-style row for one assign group."""
|
|
gid = str(group.get("id") or st.get("group_id") or "")
|
|
has_key = bool(group.get("has_stream_key") or str(group.get("stream_key") or "").strip())
|
|
enabled = bool(group.get("enabled", True))
|
|
featured = group.get("featured") or []
|
|
featured_urls = [str(x.get("url") or "").strip() for x in featured if str(x.get("url") or "").strip()]
|
|
douyin_count = sum(1 for u in featured_urls if "douyin" in u.lower())
|
|
|
|
recent_log_lines = st.get("recent_log") if isinstance(st.get("recent_log"), list) else []
|
|
if not recent_log_lines and isinstance(st.get("recent_log"), str):
|
|
recent_log_lines = [st["recent_log"]]
|
|
recent_log, recent_error = split_relay_logs(recent_log_lines)
|
|
tail = _norm_log(f"{recent_log}\n{recent_error}")[-8000:].lower()
|
|
|
|
raw_status = str(st.get("status") or "idle").lower()
|
|
if session_running:
|
|
process_status = "online"
|
|
elif not enabled:
|
|
process_status = "stopped"
|
|
elif has_key and pipeline_enabled:
|
|
process_status = "configured" if raw_status in {"idle", "stopped"} else raw_status
|
|
elif has_key:
|
|
process_status = "configured"
|
|
else:
|
|
process_status = "stopped"
|
|
|
|
pids: list[int] = []
|
|
pid = int(st.get("ffmpeg_pid") or 0)
|
|
if pid > 0:
|
|
pids = [pid]
|
|
|
|
progress_samples = _ffmpeg_progress_samples(tail)
|
|
latest = progress_samples[-1] if progress_samples else {}
|
|
progress_stalled = _progress_stalled(progress_samples)
|
|
speed_low = _speed_low(progress_samples)
|
|
has_progress = "frame=" in tail and "speed=" in tail
|
|
log_recent = log_age_seconds is None or log_age_seconds <= 20
|
|
has_worker = bool(pids) or session_running
|
|
|
|
business_status = "inactive"
|
|
business_note = "未运行"
|
|
if not has_key:
|
|
business_status = "misconfigured"
|
|
business_note = "缺少 YouTube 直播 KEY"
|
|
elif not enabled:
|
|
business_status = "inactive"
|
|
business_note = "频道已停用"
|
|
elif not featured_urls:
|
|
business_status = "misconfigured"
|
|
business_note = "直播地址列表(精选)为空"
|
|
elif _looks_like_youtube_key_rejected(tail):
|
|
business_status = "youtube_key_rejected"
|
|
business_note = "YouTube 拒绝了 RTMPS 推流,请检查直播 KEY 或网络"
|
|
elif raw_status == "error" and st.get("error"):
|
|
business_status = "error"
|
|
business_note = str(st.get("error") or "")[:240]
|
|
elif session_running and has_progress and log_recent and progress_stalled:
|
|
business_status = "source_stalled"
|
|
business_note = "FFmpeg 在运行但帧/时间进度停滞"
|
|
elif session_running and has_progress and log_recent and speed_low:
|
|
business_status = "relay_slow"
|
|
business_note = "推流速度低于实时"
|
|
elif session_running and has_progress and log_recent:
|
|
business_status = "streaming"
|
|
business_note = "正在推流到 YouTube"
|
|
elif session_running and has_worker and log_recent and _has_any(tail, ("opening input", "opening output", "rtmps://")):
|
|
business_status = "relay_starting"
|
|
business_note = "FFmpeg 已启动,等待进度上报"
|
|
elif pipeline_enabled and enabled and has_key and not session_running:
|
|
if raw_status == "reconnecting":
|
|
business_status = "relay_starting"
|
|
business_note = "推流中断,正在重连"
|
|
elif log_age_seconds is not None and log_age_seconds > 180 and has_worker:
|
|
business_status = "stale"
|
|
business_note = "进程在线但日志心跳过期"
|
|
else:
|
|
live_ids_hint = bool(st.get("source_room_id"))
|
|
if live_ids_hint and not session_running:
|
|
business_status = "waiting_source"
|
|
business_note = "等待可用抖音源或 Worker 调度"
|
|
else:
|
|
business_status = "monitoring"
|
|
business_note = "Worker 运行中,等待推流"
|
|
elif has_key and featured_urls and pipeline_enabled:
|
|
business_status = "ready"
|
|
business_note = "已配置,等待自动推流"
|
|
elif process_status == "configured":
|
|
business_status = "ready"
|
|
business_note = "已配置(未推流)"
|
|
|
|
is_pushing = business_status in {"streaming", "relay_slow"} or (
|
|
business_status == "source_stalled" and has_progress and has_worker
|
|
)
|
|
|
|
speed = latest.get("speed")
|
|
if speed is None and st.get("speed"):
|
|
try:
|
|
speed = float(st.get("speed"))
|
|
except (TypeError, ValueError):
|
|
speed = None
|
|
|
|
frame = latest.get("frame")
|
|
if frame is None and st.get("frame"):
|
|
try:
|
|
frame = int(st.get("frame"))
|
|
except (TypeError, ValueError):
|
|
frame = None
|
|
|
|
return {
|
|
"group_id": gid,
|
|
"label": group.get("name") or gid,
|
|
"process_status": process_status,
|
|
"business_status": business_status,
|
|
"business_note": business_note,
|
|
"is_pushing": is_pushing,
|
|
"ffmpeg_active": has_worker,
|
|
"ffmpeg_pids": pids,
|
|
"ffmpeg_pid": pids[0] if pids else 0,
|
|
"ffmpeg_speed": speed,
|
|
"ffmpeg_frame": frame,
|
|
"ffmpeg_fps": latest.get("fps"),
|
|
"ffmpeg_bitrate_kbps": latest.get("bitrate"),
|
|
"ffmpeg_time_seconds": latest.get("time"),
|
|
"ffmpeg_progress_stalled": progress_stalled,
|
|
"ffmpeg_speed_low": speed_low,
|
|
"log_age_seconds": log_age_seconds,
|
|
"recent_log": recent_log,
|
|
"recent_error": recent_error,
|
|
"source_title": st.get("anchor_name") or "",
|
|
"source_room_id": st.get("source_room_id") or st.get("room_id") or "",
|
|
"source_url": st.get("source_url") or "",
|
|
"source_display": st.get("anchor_name") or "",
|
|
"url_count": len(featured_urls),
|
|
"douyin_count": douyin_count,
|
|
"has_stream_key": has_key,
|
|
"stream_key_suffix": _key_suffix(group),
|
|
"push_seconds": float(st.get("push_seconds") or 0),
|
|
"started_at": float(st.get("started_at") or 0),
|
|
"updated_at": float(st.get("updated_at") or 0),
|
|
}
|
|
|
|
|
|
def _key_suffix(group: dict[str, Any]) -> str:
|
|
sk = str(group.get("stream_key") or "").strip()
|
|
if len(sk) >= 4:
|
|
return sk[-4:]
|
|
masked = str(group.get("stream_key_masked") or "")
|
|
if masked.startswith("***") and len(masked) > 3:
|
|
return masked[3:]
|
|
return ""
|
|
|
|
|
|
def log_age_seconds(st: dict[str, Any], now: float | None = None) -> float | None:
|
|
updated = float(st.get("updated_at") or 0)
|
|
if updated <= 0:
|
|
return None
|
|
return max(0.0, (now or time.time()) - updated)
|