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>
This commit is contained in:
parent
c1f3bd3c57
commit
fbdc3fc0db
29
README.md
29
README.md
@ -435,13 +435,36 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
|
||||
|
||||
关闭软愈合(仅排障):`DY_DISABLE_NEKO_SOFT_HEAL=1` 或 `DY_DISABLE_STUDIO_CDP_LOOP=1`。日志关键字:`neko_runtime_heal`。
|
||||
|
||||
#### API 防挂死 / 直播优先 CPU(双 VPS)
|
||||
|
||||
现网根因(尤其 **VPS-B dy.nomadro.live**):直播推流 ffmpeg 与 yt_long/shorts 转码叠在一起 → load 飙高 → uvicorn 事件循环饿死 → `/api/health` 超时 → 整站「宕机」。**dylive 同代码**不叠加重转码时即可稳住。对策:
|
||||
|
||||
| 层 | 机制 | 行为 |
|
||||
|----|------|------|
|
||||
| 瞬时 health | `GET /api/health`(默认) | **禁止** await S3/YT/PB;仅进程态 + 可选缓存 deps。依赖探测用 `?detail=1` |
|
||||
| ffmpeg 隔离 | `backend/app/procutil.py` + `douyinweb-ffmpeg.slice` | 推流/成片子进程迁出 API cgroup,避免 `MemoryHigh` 回收把 API 打成 D-state |
|
||||
| 剪辑让路 | `host_metrics.clip_encode_defer_reason()` | 有 YouTube **直播推流** 或 load/CPU 过高时,yt_long / shorts / tiktok / x_clips **不新开** 录制 ffmpeg |
|
||||
| API 内存 | systemd drop-in(对齐 dylive 紧预算,按机内存微调) | 例:dylive ≈ High **700M** / Max **900M**;dy.live ≈ High **1100M** / Max **1500M**(ffmpeg 已外置) |
|
||||
| ffmpeg CPU | `douyinweb-ffmpeg.slice` `CPUQuota` | dy.live 现网 **200%**(4 核机留给 API/Neko 余量) |
|
||||
| 看门狗 | `scripts/linux/api_health_watch.sh` → `douyinweb-api-watch.service` | health 连续失败或 `:8014` Recv-Q 过高 → SIGKILL 重启 API |
|
||||
|
||||
对齐部署(代码 + systemd):`python scripts/_align_dy_to_dylive_harden.py`(经 VPS-A 跳到 VPS-B);仅 cgroup/watch 骨架也可用 `scripts/_deploy_api_hang_harden.py`。
|
||||
|
||||
#### 时段排除名单(timeslot exclude)
|
||||
|
||||
分配页「排除手动直播名单」:已用于手动开播的抖音房不再被时段自动挑选 / 日程自动填充。API:`/api/youtube/assign/timeslot-exclude*`。
|
||||
|
||||
#### YouTube YPP 频道创收 API(调研)
|
||||
#### YouTube YPP 频道创收
|
||||
|
||||
官方可通过 [YouTube Analytics API](https://developers.google.com/youtube/analytics/reference/reports/query) 拉取频道 **预估创收**(`estimatedRevenue` 等),需 OAuth scope `yt-analytics-monetary.readonly`。
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 控制台 | `/yt-revenue`(侧栏「收益」) |
|
||||
| API | `GET /api/yt-revenue/summary` · `GET /api/yt-revenue/channels/{channel_pk}` |
|
||||
| 后端 | `backend/app/yt_revenue.py`;频道需重新授权含 monetary scope,否则 `need_reauth` |
|
||||
| 调研 | [docs/YPP_REVENUE_API.md](docs/YPP_REVENUE_API.md);站点 AdSense 另见 [docs/ADSENSE_API.md](docs/ADSENSE_API.md) |
|
||||
|
||||
官方 **可以**通过 [YouTube Analytics API](https://developers.google.com/youtube/analytics/reference/reports/query) 拉取频道 **预估创收**(`estimatedRevenue` 等),需 OAuth scope `yt-analytics-monetary.readonly`。本仓库当前 Shorts OAuth **未包含**该 scope,也**尚未接入**收益拉取。分析结论见 [docs/YPP_REVENUE_API.md](docs/YPP_REVENUE_API.md)。(站点 AdSense 是另一套 API,见 [docs/ADSENSE_API.md](docs/ADSENSE_API.md)。)
|
||||
- **不复用** sh2 RTMP 转播通道
|
||||
|
||||
### 封面(S3)
|
||||
@ -482,6 +505,8 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
|
||||
| `/youtube` | 频道管理(默认)+ InnerTube 探测 |
|
||||
| `/youtube` → **分配** | Pro 转播:KEY / 精选源 / 时间段 / Neko / FFmpeg 实况 |
|
||||
| `/shorts` | 授权 / 任务 / 排程 / 立即上传 / 在播分析 |
|
||||
| `/yt-long` | 长视频成片 / 上传 |
|
||||
| `/yt-revenue` | YPP 预估创收(需 monetary OAuth) |
|
||||
| `/settings` | 防风控、通知、静默、YT/Shorts、**全局 SOCKS5**、改密、PB/S3 运维 |
|
||||
| `/ops` | 运维:Umami / ntfy / DNS / systemd;顶栏另有 CPU·内存条 |
|
||||
| `/web` | Umami 多站点访问分析 |
|
||||
|
||||
@ -94,7 +94,9 @@ def cut_segment(
|
||||
str(out),
|
||||
]
|
||||
try:
|
||||
proc = subprocess.run(copy_cmd, capture_output=True, text=True, timeout=dur + 60)
|
||||
from .procutil import run_outside_api_cgroup
|
||||
|
||||
proc = run_outside_api_cgroup(copy_cmd, capture_output=True, text=True, timeout=dur + 60)
|
||||
except Exception as exc:
|
||||
return {"ok": False, "error": str(exc)[:300]}
|
||||
if proc.returncode == 0 and out.is_file() and out.stat().st_size >= 20_000:
|
||||
@ -130,7 +132,9 @@ def cut_segment(
|
||||
str(out),
|
||||
]
|
||||
try:
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=dur + 120)
|
||||
from .procutil import run_outside_api_cgroup
|
||||
|
||||
proc = run_outside_api_cgroup(cmd, capture_output=True, text=True, timeout=dur + 120)
|
||||
except Exception as exc:
|
||||
return {"ok": False, "error": str(exc)[:300]}
|
||||
if proc.returncode != 0:
|
||||
|
||||
@ -3393,6 +3393,8 @@ def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]:
|
||||
"oauth_ok",
|
||||
"oauth_checked_at",
|
||||
"oauth_error",
|
||||
"ypp_ok",
|
||||
"ypp_checked_at",
|
||||
"yt_profile_json",
|
||||
"yt_profile_at",
|
||||
}
|
||||
@ -3411,6 +3413,13 @@ def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]:
|
||||
v = _normalize_daily_quota(v, default=SHORTS_DAILY_FORCE)
|
||||
if k == "enabled":
|
||||
v = 1 if v else 0
|
||||
if k == "ypp_ok":
|
||||
try:
|
||||
v = int(v)
|
||||
except Exception:
|
||||
continue
|
||||
if v not in (-1, 0, 1):
|
||||
continue
|
||||
if k == "oauth_profile_id":
|
||||
v = str(v or "").strip().upper()
|
||||
sets.append(f"{k} = ?")
|
||||
@ -3473,7 +3482,11 @@ def delete_shorts_jobs_for_channel(channel_pk: str) -> dict[str, int]:
|
||||
|
||||
|
||||
def delete_shorts_channel(channel_pk: str) -> dict[str, int]:
|
||||
"""Delete channel and cascade: jobs + local clip materials."""
|
||||
"""Delete Shorts channel + its jobs/clips only.
|
||||
|
||||
Never touches Live 分配 (yt_assign_*), stream keys, Neko binds, or yt_long
|
||||
channels — those are independent products linked by youtube_channel_id.
|
||||
"""
|
||||
pk = str(channel_pk or "").strip()
|
||||
stats = delete_shorts_jobs_for_channel(pk)
|
||||
with _lock:
|
||||
|
||||
@ -98,3 +98,34 @@ def snapshot(*, sample_cpu: bool = False) -> dict[str, Any]:
|
||||
_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 ""
|
||||
|
||||
@ -177,7 +177,7 @@ async def lifespan(_: FastAPI):
|
||||
try:
|
||||
from . import ops_neko_sync
|
||||
|
||||
asyncio.create_task(ops_neko_sync.edge_sync_loop(interval_sec=5.0))
|
||||
asyncio.create_task(ops_neko_sync.edge_sync_loop(interval_sec=30.0))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@ -325,7 +325,11 @@ _HEALTH_DEPS_TTL = float(os.environ.get("DY_HEALTH_DEPS_TTL", "5") or "5")
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health(detail: int = Query(0, ge=0, le=1)) -> dict[str, Any]:
|
||||
"""Fast health — default path must not touch thread pools or SQLite."""
|
||||
"""Fast health — default path must not await network / thread pools / SQLite.
|
||||
|
||||
Under CPU storm (live relay + clip encode) any await here times out the
|
||||
watchdog and looks like a full site outage. Use ?detail=1 for deps.
|
||||
"""
|
||||
if _DESKTOP_LIGHT:
|
||||
return {"ok": True, "time": time.time(), "desktop_light": True}
|
||||
out: dict[str, Any] = {
|
||||
@ -368,8 +372,7 @@ async def health(detail: int = Query(0, ge=0, le=1)) -> dict[str, Any]:
|
||||
},
|
||||
}
|
||||
|
||||
# Default liveness stays cheap, but still expose the fields the ops panel reads
|
||||
# so a missing youtube/pb/s3 key is not shown as "异常/已停".
|
||||
# Instant liveness for watchdog / Caddy / operators. Never block on S3/YT/PB.
|
||||
if not detail:
|
||||
try:
|
||||
out["monitor"] = {
|
||||
@ -395,54 +398,23 @@ async def health(detail: int = Query(0, ge=0, le=1)) -> dict[str, Any]:
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
# Cache youtube/pb/s3 pulses — ops/UI poll health often; identical shape, ≤TTL lag.
|
||||
now_deps = time.time()
|
||||
cached_deps = _HEALTH_DEPS_CACHE.get("payload")
|
||||
if (
|
||||
isinstance(cached_deps, dict)
|
||||
and now_deps - float(_HEALTH_DEPS_CACHE.get("at") or 0) < _HEALTH_DEPS_TTL
|
||||
):
|
||||
if isinstance(cached_deps, dict):
|
||||
out.update(cached_deps)
|
||||
out["deps_cached"] = True
|
||||
return out
|
||||
deps: dict[str, Any] = {}
|
||||
try:
|
||||
deps["youtube"] = await asyncio.wait_for(youtube_client.health(), timeout=0.6)
|
||||
except Exception as exc:
|
||||
deps["youtube"] = {"ok": False, "error": str(exc)[:120], "service": "youtube-svc"}
|
||||
try:
|
||||
deps["pocketbase"] = await asyncio.wait_for(pb_sync.health(), timeout=0.5)
|
||||
except Exception as exc:
|
||||
deps["pocketbase"] = {"ok": False, "error": str(exc)[:120]}
|
||||
try:
|
||||
from . import s3_storage
|
||||
|
||||
enabled = bool(s3_storage.s3_enabled())
|
||||
s3_info: dict[str, Any] = {
|
||||
"enabled": enabled,
|
||||
"ok": False,
|
||||
"endpoint": settings.s3_endpoint,
|
||||
"bucket": settings.s3_bucket,
|
||||
"public_base": settings.s3_public_base,
|
||||
else:
|
||||
# Stubs so ops UI does not flash "异常" before first detail refresh.
|
||||
out["youtube"] = {"ok": True, "service": "youtube-svc", "deferred": True}
|
||||
out["pocketbase"] = {"ok": True, "deferred": True}
|
||||
out["s3"] = {
|
||||
"enabled": bool(getattr(settings, "s3_endpoint", None)),
|
||||
"ok": True,
|
||||
"deferred": True,
|
||||
"endpoint": getattr(settings, "s3_endpoint", "") or "",
|
||||
"bucket": getattr(settings, "s3_bucket", "") or "",
|
||||
"public_base": getattr(settings, "s3_public_base", "") or "",
|
||||
}
|
||||
if enabled:
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
asyncio.to_thread(
|
||||
lambda: s3_storage._client().head_bucket(Bucket=settings.s3_bucket) # noqa: SLF001
|
||||
),
|
||||
timeout=0.6,
|
||||
)
|
||||
s3_info["ok"] = True
|
||||
except Exception as exc:
|
||||
s3_info["error"] = str(exc)[:80]
|
||||
deps["s3"] = s3_info
|
||||
except Exception:
|
||||
deps["s3"] = {"enabled": False, "ok": False}
|
||||
_HEALTH_DEPS_CACHE["at"] = now_deps
|
||||
_HEALTH_DEPS_CACHE["payload"] = deps
|
||||
out.update(deps)
|
||||
out["deps_cached"] = False
|
||||
out["deps_cached"] = False
|
||||
return out
|
||||
|
||||
try:
|
||||
@ -501,6 +473,11 @@ async def health(detail: int = Query(0, ge=0, le=1)) -> dict[str, Any]:
|
||||
out["s3"] = await asyncio.wait_for(asyncio.to_thread(_s3), timeout=1.0)
|
||||
except Exception as exc:
|
||||
out["s3"] = {"enabled": False, "ok": False, "error": str(exc)[:120]}
|
||||
# Feed default /api/health stubs so UI can show last-known without blocking.
|
||||
_HEALTH_DEPS_CACHE["at"] = time.time()
|
||||
_HEALTH_DEPS_CACHE["payload"] = {
|
||||
k: out[k] for k in ("youtube", "pocketbase", "s3") if k in out
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
@ -886,14 +863,23 @@ async def shorts_live_analytics(
|
||||
|
||||
|
||||
@app.get("/api/shorts/oauth/start")
|
||||
async def shorts_oauth_start(channel_pk: str, request: Request, return_to: str = "") -> RedirectResponse:
|
||||
async def shorts_oauth_start(
|
||||
channel_pk: str,
|
||||
request: Request,
|
||||
return_to: str = "",
|
||||
monetary: int = 0,
|
||||
) -> RedirectResponse:
|
||||
try:
|
||||
await shorts_oauth.prepare_reauthorize(channel_pk)
|
||||
ret = str(return_to or request.query_params.get("return_to") or "").strip()
|
||||
want_monetary = bool(int(monetary or 0)) or str(
|
||||
request.query_params.get("monetary") or ""
|
||||
).strip().lower() in {"1", "true", "yes"}
|
||||
url = shorts_oauth.build_authorize_url(
|
||||
channel_pk=channel_pk,
|
||||
request_base=_request_public_base(request),
|
||||
return_to=ret,
|
||||
include_monetary=want_monetary,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
@ -1049,8 +1035,9 @@ async def shorts_channels_update(channel_pk: str, body: ShortsChannelUpdate) ->
|
||||
|
||||
@app.delete("/api/shorts/channels/{channel_pk}")
|
||||
async def shorts_channels_delete(channel_pk: str) -> dict[str, Any]:
|
||||
"""Delete Shorts card only — Live 分配 / stream key / Neko 配置保留。"""
|
||||
stats = db.delete_shorts_channel(channel_pk)
|
||||
return {"ok": True, **stats}
|
||||
return {"ok": True, "live_assign_preserved": True, "yt_long_preserved": True, **stats}
|
||||
|
||||
|
||||
@app.get("/api/shorts/jobs")
|
||||
@ -1612,6 +1599,28 @@ async def x_clips_job_retry(job_id: str) -> dict[str, Any]:
|
||||
# ── YouTube long-form 9:16 (isolated; default disabled) ──────────────────────
|
||||
|
||||
|
||||
@app.get("/api/yt-revenue/summary")
|
||||
async def yt_revenue_summary(
|
||||
days: int = Query(28, ge=1, le=90),
|
||||
force: int = Query(0, ge=0, le=1),
|
||||
) -> dict[str, Any]:
|
||||
"""Fleet AdSense / YouTube Analytics estimated revenue (Live / Shorts / 长视频)."""
|
||||
from . import yt_revenue
|
||||
|
||||
return await yt_revenue.fleet_revenue(days=days, force=bool(force))
|
||||
|
||||
|
||||
@app.get("/api/yt-revenue/channels/{channel_pk}")
|
||||
async def yt_revenue_channel(
|
||||
channel_pk: str,
|
||||
days: int = Query(28, ge=1, le=90),
|
||||
force: int = Query(0, ge=0, le=1),
|
||||
) -> dict[str, Any]:
|
||||
from . import yt_revenue
|
||||
|
||||
return await yt_revenue.fetch_channel_revenue(channel_pk, days=days, force=bool(force))
|
||||
|
||||
|
||||
@app.get("/api/yt-long/status")
|
||||
async def yt_long_status(light: int = Query(0, ge=0, le=1)) -> dict[str, Any]:
|
||||
fn = yt_long_pipeline.status_light if light else yt_long_pipeline.status
|
||||
|
||||
@ -501,13 +501,45 @@ def push_catalog_to_hub() -> dict[str, Any]:
|
||||
return {"ok": False, "error": str(exc)[:300], "payload": payload}
|
||||
|
||||
|
||||
def ensure_slot_live_studio(slot: int, *, youtube_channel_id: str = "") -> dict[str, Any]:
|
||||
def ensure_slot_live_studio(
|
||||
slot: int,
|
||||
*,
|
||||
youtube_channel_id: str = "",
|
||||
skip_scrape_if_fresh_sec: float = 0.0,
|
||||
) -> dict[str, Any]:
|
||||
"""Physical edge: ensure ops-neko Chrome has YouTube Live Control Room open (待开播)."""
|
||||
from . import youtube_neko as yn
|
||||
|
||||
slot_i = int(slot or 0)
|
||||
if slot_i < 1:
|
||||
return {"ok": False, "error": "bad_slot"}
|
||||
fresh_sec = float(skip_scrape_if_fresh_sec or 0)
|
||||
if fresh_sec > 0:
|
||||
try:
|
||||
snap = yn.studio_snapshot_for_ref(
|
||||
f"ops:{slot_i}", max_age_sec=fresh_sec, include_minute_reports=False
|
||||
)
|
||||
age = snap.get("age_sec")
|
||||
if (
|
||||
snap.get("live_page_open")
|
||||
or snap.get("received_at")
|
||||
or snap.get("on_air")
|
||||
or snap.get("url")
|
||||
) and (age is None or float(age) <= fresh_sec):
|
||||
name = _container_name(slot_i)
|
||||
yt = str(youtube_channel_id or "").strip()
|
||||
studio_url = yn.studio_live_control_url(yt) if yt else str(snap.get("url") or "")
|
||||
if studio_url and _container_running(slot_i):
|
||||
yn._cdp_ensure_live_studio_in_container(name, studio_url=studio_url)
|
||||
return {
|
||||
"ok": True,
|
||||
"slot": slot_i,
|
||||
"skipped_scrape": True,
|
||||
"age_sec": age,
|
||||
"studio_url": studio_url,
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
name = _container_name(slot_i)
|
||||
if not _container_running(slot_i):
|
||||
try:
|
||||
@ -638,7 +670,7 @@ def ensure_slot_live_studio(slot: int, *, youtube_channel_id: str = "") -> dict[
|
||||
return {"ok": bool(opened.get("ok")), "slot": slot_i, "studio_url": studio_url, "cdp": opened}
|
||||
|
||||
|
||||
def ensure_bound_slots_live_studio() -> dict[str, Any]:
|
||||
def ensure_bound_slots_live_studio(*, skip_scrape_if_fresh_sec: float = 0.0) -> dict[str, Any]:
|
||||
"""Edge heartbeat: bound/running ops slots keep Live Control Room open."""
|
||||
cards_by_id: dict[str, dict[str, Any]] = {}
|
||||
try:
|
||||
@ -671,7 +703,13 @@ def ensure_bound_slots_live_studio() -> dict[str, Any]:
|
||||
break
|
||||
if not should:
|
||||
continue
|
||||
results.append(ensure_slot_live_studio(slot, youtube_channel_id=yt))
|
||||
results.append(
|
||||
ensure_slot_live_studio(
|
||||
slot,
|
||||
youtube_channel_id=yt,
|
||||
skip_scrape_if_fresh_sec=skip_scrape_if_fresh_sec,
|
||||
)
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"ensured": sum(1 for r in results if r.get("ok")),
|
||||
|
||||
@ -56,8 +56,15 @@ def sync_once() -> dict[str, Any]:
|
||||
|
||||
_state["enabled"] = True
|
||||
# Keep YouTube Live Control Room open on bound ops-neko Chrome before catalog push.
|
||||
# Skip heavy CDP scrape when extension/host ingest is already fresh (physical dy
|
||||
# used to docker-exec scrape every 5s → RSS thrash + accept backlog).
|
||||
try:
|
||||
live = ops_neko.ensure_bound_slots_live_studio()
|
||||
live = ops_neko.ensure_bound_slots_live_studio(skip_scrape_if_fresh_sec=45.0)
|
||||
except TypeError:
|
||||
try:
|
||||
live = ops_neko.ensure_bound_slots_live_studio()
|
||||
except Exception as exc:
|
||||
live = {"ok": False, "error": str(exc)[:200]}
|
||||
except Exception as exc:
|
||||
live = {"ok": False, "error": str(exc)[:200]}
|
||||
catalog = ops_neko.push_catalog_to_hub()
|
||||
@ -89,8 +96,13 @@ def sync_once() -> dict[str, Any]:
|
||||
return {"ok": ok, "catalog": catalog, "binds": binds}
|
||||
|
||||
|
||||
async def edge_sync_loop(*, interval_sec: float = 5.0) -> None:
|
||||
"""Background loop — only does work when peer role is edge."""
|
||||
async def edge_sync_loop(*, interval_sec: float = 30.0) -> None:
|
||||
"""Background loop — only does work when peer role is edge.
|
||||
|
||||
Default 30s (was 5s): physical dy was CDP-scraping + catalog-pushing every 5s
|
||||
while VPS hub skips this path entirely — that asymmetry is why same code
|
||||
hung on dy but not dylive.
|
||||
"""
|
||||
global _kick
|
||||
_kick = asyncio.Event()
|
||||
_state["interval_sec"] = float(interval_sec)
|
||||
|
||||
137
backend/app/procutil.py
Normal file
137
backend/app/procutil.py
Normal file
@ -0,0 +1,137 @@
|
||||
# -*- 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)
|
||||
@ -247,7 +247,11 @@ async def record_clip(
|
||||
|
||||
def _run(cmd_local: list[str] = cmd, used_url: str = url) -> dict[str, Any]:
|
||||
try:
|
||||
proc = subprocess.run(cmd_local, capture_output=True, text=True, timeout=sec + 90)
|
||||
from .procutil import run_outside_api_cgroup
|
||||
|
||||
proc = run_outside_api_cgroup(
|
||||
cmd_local, capture_output=True, text=True, timeout=sec + 90
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"ok": False, "error": "ffmpeg 录制超时"}
|
||||
except Exception as exc:
|
||||
|
||||
@ -28,6 +28,13 @@ YOUTUBE_SCOPES = " ".join(
|
||||
"https://www.googleapis.com/auth/youtube.force-ssl",
|
||||
]
|
||||
)
|
||||
# Opt-in only (收益 tab / reauth). Not required for oauth_ok.
|
||||
YT_MONETARY_SCOPES = " ".join(
|
||||
[
|
||||
"https://www.googleapis.com/auth/yt-analytics.readonly",
|
||||
"https://www.googleapis.com/auth/yt-analytics-monetary.readonly",
|
||||
]
|
||||
)
|
||||
# Requested on authorize so we can show Gmail on A/B/C/D; not required for oauth_ok.
|
||||
IDENTITY_SCOPES = "openid email profile"
|
||||
|
||||
@ -368,7 +375,13 @@ def channel_can_authorize(channel: dict[str, Any] | None, cfg: dict[str, Any] |
|
||||
return resolve_oauth_client(channel, cfg).get("source") != "none"
|
||||
|
||||
|
||||
def build_authorize_url(*, channel_pk: str, request_base: str = "", return_to: str = "") -> str:
|
||||
def build_authorize_url(
|
||||
*,
|
||||
channel_pk: str,
|
||||
request_base: str = "",
|
||||
return_to: str = "",
|
||||
include_monetary: bool = False,
|
||||
) -> str:
|
||||
_hydrate_oauth_states()
|
||||
cfg = _cfg()
|
||||
channel = db.get_shorts_channel(channel_pk)
|
||||
@ -395,11 +408,12 @@ def build_authorize_url(*, channel_pk: str, request_base: str = "", return_to: s
|
||||
else:
|
||||
_oauth_states[state] = (channel_pk, now + 600, client_id, client_secret)
|
||||
_persist_oauth_states()
|
||||
scope = authorize_scopes(include_monetary=bool(include_monetary))
|
||||
params = {
|
||||
"client_id": client_id,
|
||||
"redirect_uri": resolve_redirect_uri(request_base),
|
||||
"response_type": "code",
|
||||
"scope": authorize_scopes(),
|
||||
"scope": scope,
|
||||
"access_type": "offline",
|
||||
# Must force consent to obtain refresh_token. Do NOT set include_granted_scopes —
|
||||
# Google often omits refresh_token when the app "already has some access".
|
||||
@ -414,9 +428,18 @@ def requested_scopes() -> list[str]:
|
||||
return [s for s in YOUTUBE_SCOPES.split() if s]
|
||||
|
||||
|
||||
def authorize_scopes() -> str:
|
||||
def monetary_scopes() -> list[str]:
|
||||
return [s for s in YT_MONETARY_SCOPES.split() if s]
|
||||
|
||||
|
||||
def authorize_scopes(*, include_monetary: bool = False) -> str:
|
||||
"""Scopes for Google consent. YouTube only — brand accounts break with openid/email."""
|
||||
return " ".join(s for s in YOUTUBE_SCOPES.split() if s)
|
||||
scopes = [s for s in YOUTUBE_SCOPES.split() if s]
|
||||
if include_monetary:
|
||||
for s in monetary_scopes():
|
||||
if s not in scopes:
|
||||
scopes.append(s)
|
||||
return " ".join(scopes)
|
||||
|
||||
|
||||
FORCE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
|
||||
@ -565,15 +588,28 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
|
||||
_stamp_oauth_error(channel_pk, err)
|
||||
raise ValueError(err)
|
||||
items = ch_data.get("items") or []
|
||||
# Prefer the brand that already matches this card's UC (multi-brand Google logins).
|
||||
expected_uc = str(channel.get("youtube_channel_id") or "").strip()
|
||||
expected_name = str(channel.get("name") or "").strip()
|
||||
chosen: dict[str, Any] | None = None
|
||||
if expected_uc and isinstance(items, list):
|
||||
for it in items:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
if str(it.get("id") or "").strip() == expected_uc:
|
||||
chosen = it
|
||||
break
|
||||
if chosen is None and items and isinstance(items[0], dict):
|
||||
chosen = items[0]
|
||||
yt_id = ""
|
||||
yt_title = ""
|
||||
yt_handle = ""
|
||||
if items:
|
||||
sn = items[0].get("snippet") or {}
|
||||
yt_id = str(items[0].get("id") or "")
|
||||
if chosen:
|
||||
sn = chosen.get("snippet") or {}
|
||||
yt_id = str(chosen.get("id") or "")
|
||||
yt_title = str(sn.get("title") or "")
|
||||
yt_handle = str(sn.get("customUrl") or "").strip()
|
||||
if not items:
|
||||
if not items or not yt_id:
|
||||
err = (
|
||||
"Google 账号下没有可用的 YouTube 频道(mine=true 为空)。"
|
||||
"请确认授权时选的是有频道的品牌账号,不是空的 Google 登录号。"
|
||||
@ -581,9 +617,35 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
|
||||
_stamp_oauth_error(channel_pk, err)
|
||||
raise ValueError(err)
|
||||
|
||||
# Hard lock: re-auth must not rewrite this card into another brand.
|
||||
# (Previously we overwrote youtube_channel_id + name → duplicate 「nomad Street Food」.)
|
||||
if expected_uc and yt_id != expected_uc:
|
||||
err = (
|
||||
f"授权选中的 YouTube 频道是「{yt_title or yt_id}」({yt_id}),"
|
||||
f"但本卡绑定的是「{expected_name or expected_uc}」({expected_uc})。"
|
||||
"凭证未写入。请重新点授权,在 Google 账号/品牌列表里选对本卡的频道。"
|
||||
)
|
||||
_stamp_oauth_error(channel_pk, err)
|
||||
# Best-effort revoke the wrong-brand grant so it does not linger.
|
||||
try:
|
||||
async with httpx.AsyncClient(**_google_client_kwargs(timeout=15.0)) as client:
|
||||
await client.post(
|
||||
"https://oauth2.googleapis.com/revoke",
|
||||
data={"token": access},
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
if refresh:
|
||||
await client.post(
|
||||
"https://oauth2.googleapis.com/revoke",
|
||||
data={"token": refresh},
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
raise ValueError(err)
|
||||
|
||||
google_email = await fetch_google_account_email(access)
|
||||
|
||||
# Clicked card wins: accept whatever brand Google returned; never rewrite siblings.
|
||||
# Soft-warn if the same YouTube channel is already bound to another Shorts card.
|
||||
dup_warn = ""
|
||||
if yt_id:
|
||||
@ -637,12 +699,13 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
|
||||
"client_secret": client_secret,
|
||||
"refresh_token": refresh,
|
||||
}
|
||||
if yt_id:
|
||||
# Only set UC when card had none; never swap to a different UC (guarded above).
|
||||
if yt_id and not expected_uc:
|
||||
patch["youtube_channel_id"] = yt_id
|
||||
if google_email:
|
||||
patch["oauth_email"] = google_email
|
||||
# Refresh display name/handle from Google — brand label may differ from old card title.
|
||||
if yt_title:
|
||||
# Keep operator card title on reauth — never auto-rename into another brand's title.
|
||||
if yt_title and not expected_name:
|
||||
patch["name"] = yt_title
|
||||
if profile_id and not str(channel.get("oauth_profile_id") or "").strip():
|
||||
patch["oauth_profile_id"] = profile_id
|
||||
|
||||
@ -1097,9 +1097,16 @@ class ShortsPipeline:
|
||||
if job:
|
||||
runner = "upload"
|
||||
if not job and self._active_records < record_max:
|
||||
job = db.claim_pending_shorts_record()
|
||||
if job:
|
||||
runner = "record"
|
||||
try:
|
||||
from .host_metrics import clip_encode_defer_reason
|
||||
|
||||
defer_rec = clip_encode_defer_reason()
|
||||
except Exception:
|
||||
defer_rec = ""
|
||||
if not defer_rec:
|
||||
job = db.claim_pending_shorts_record()
|
||||
if job:
|
||||
runner = "record"
|
||||
if not job:
|
||||
await asyncio.sleep(2)
|
||||
continue
|
||||
|
||||
@ -427,7 +427,13 @@ class TikTokPipeline:
|
||||
self._active_uploads += 1
|
||||
asyncio.create_task(self._run_upload(job))
|
||||
max_rec = max(1, int(cfg.get("tiktok_max_concurrent") or 1))
|
||||
while self._active_records < max_rec:
|
||||
try:
|
||||
from .host_metrics import clip_encode_defer_reason
|
||||
|
||||
defer_rec = clip_encode_defer_reason()
|
||||
except Exception:
|
||||
defer_rec = ""
|
||||
while not defer_rec and self._active_records < max_rec:
|
||||
job = tiktok_db.claim_pending_tiktok_record()
|
||||
if not job:
|
||||
break
|
||||
|
||||
@ -392,7 +392,13 @@ class XClipsPipeline:
|
||||
self.last_error = str(exc)[:240]
|
||||
|
||||
max_rec = max(1, int(cfg.get("x_clips_max_concurrent") or 1))
|
||||
while self._active_records < max_rec:
|
||||
try:
|
||||
from .host_metrics import clip_encode_defer_reason
|
||||
|
||||
defer_rec = clip_encode_defer_reason()
|
||||
except Exception:
|
||||
defer_rec = ""
|
||||
while not defer_rec and self._active_records < max_rec:
|
||||
pending = x_clips_db.list_pending_x_clip_jobs(limit=1)
|
||||
if not pending:
|
||||
break
|
||||
|
||||
@ -756,10 +756,9 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
|
||||
assign_groups = await asyncio.to_thread(
|
||||
lambda: yt_assign_db.list_groups(include_urls=False)
|
||||
)
|
||||
relay_payload = await asyncio.to_thread(youtube_relay_pipeline.status)
|
||||
relay_rows = {
|
||||
str(r.get("group_id") or ""): r for r in (relay_payload.get("groups") or [])
|
||||
}
|
||||
# Do NOT call full relay.status() here — it rebuilds heavy studio/neko payloads and
|
||||
# used to recurse into douyin live-map (RSS blow-up on physical dy).
|
||||
relay_rows = await asyncio.to_thread(youtube_relay_pipeline.pushing_flags)
|
||||
pk_to_gid: dict[str, str] = {}
|
||||
gid_to_name: dict[str, str] = {}
|
||||
for g in assign_groups:
|
||||
|
||||
@ -221,33 +221,29 @@ async def _mirror_avatar_to_s3(channel_pk: str, cdn_url: str) -> str:
|
||||
|
||||
async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
|
||||
token, ch = await _access_for_channel(channel_pk)
|
||||
yt_id = str(ch.get("youtube_channel_id") or "").strip()
|
||||
expected_uc = str(ch.get("youtube_channel_id") or "").strip()
|
||||
# Include status → isChannelMonetizationEnabled so YPP is written with the same call.
|
||||
params: dict[str, Any] = {"part": "snippet,contentDetails,statistics,brandingSettings,status"}
|
||||
if yt_id:
|
||||
params["id"] = yt_id
|
||||
if expected_uc:
|
||||
params["id"] = expected_uc
|
||||
else:
|
||||
params["mine"] = "true"
|
||||
data = await _get("channels", token=token, params=params)
|
||||
items = data.get("items") or []
|
||||
if not items and yt_id:
|
||||
# Stored id may be stale — fall back to mine=true (brand picker during OAuth).
|
||||
data = await _get(
|
||||
"channels",
|
||||
token=token,
|
||||
params={"part": "snippet,contentDetails,statistics,brandingSettings,status", "mine": "true"},
|
||||
if not items and expected_uc:
|
||||
# Token may belong to another brand — refuse mine=true rewrite of this card.
|
||||
raise ValueError(
|
||||
f"授权凭证读不到本卡绑定的频道 {expected_uc}。"
|
||||
"请对本卡重新授权,并在 Google 品牌列表中选对频道(禁止选成其它品牌)。"
|
||||
)
|
||||
items = data.get("items") or []
|
||||
if not items:
|
||||
raise ValueError("未拿到频道资料(请确认授权账号下有频道,且 Google 项目已启用 YouTube Data API v3)")
|
||||
item = items[0]
|
||||
# If stored youtube_channel_id differs, still return mine (Brand account caveat)
|
||||
yt_id = str(item.get("id") or "")
|
||||
if yt_id and yt_id != str(ch.get("youtube_channel_id") or ""):
|
||||
try:
|
||||
db.update_shorts_channel(channel_pk, youtube_channel_id=yt_id, name=str((item.get("snippet") or {}).get("title") or ch.get("name")))
|
||||
except Exception:
|
||||
pass
|
||||
if expected_uc and yt_id and yt_id != expected_uc:
|
||||
raise ValueError(
|
||||
f"返回频道 {yt_id} 与本卡绑定 {expected_uc} 不一致,已拒绝写入资料缓存。"
|
||||
)
|
||||
uploads = ((item.get("contentDetails") or {}).get("relatedPlaylists") or {}).get("uploads") or ""
|
||||
sn = item.get("snippet") or {}
|
||||
st = item.get("statistics") or {}
|
||||
@ -264,13 +260,13 @@ async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
|
||||
try:
|
||||
from .yt_long_monetize import _persist_ypp_for_shorts
|
||||
|
||||
_persist_ypp_for_shorts(shorts_pk=channel_pk, ypp=ypp, youtube_channel_id=yt_id)
|
||||
_persist_ypp_for_shorts(shorts_pk=channel_pk, ypp=ypp, youtube_channel_id=yt_id or expected_uc)
|
||||
except Exception:
|
||||
log.exception("persist ypp_ok failed for %s", channel_pk)
|
||||
profile = {
|
||||
"ok": True,
|
||||
"channel_pk": channel_pk,
|
||||
"youtube_channel_id": yt_id,
|
||||
"youtube_channel_id": yt_id or expected_uc,
|
||||
"title": sn.get("title"),
|
||||
"description": sn.get("description"),
|
||||
"custom_url": sn.get("customUrl"),
|
||||
@ -331,6 +327,16 @@ def save_yt_profile_cache(channel_pk: str, profile: dict[str, Any]) -> None:
|
||||
import time
|
||||
|
||||
snippet = profile_snippet(profile) or {}
|
||||
# Refuse caching a profile for a different UC than this Shorts card
|
||||
# (bad OAuth brand pick used to poison the UI as another channel).
|
||||
try:
|
||||
ch = db.get_shorts_channel(channel_pk) or {}
|
||||
expect = str(ch.get("youtube_channel_id") or "").strip()
|
||||
got = str(snippet.get("youtube_channel_id") or profile.get("youtube_channel_id") or profile.get("id") or "").strip()
|
||||
if expect and got and expect != got:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
snippet["fetched_at"] = time.time()
|
||||
# Drop heavy raw if present
|
||||
payload = {
|
||||
|
||||
@ -1048,10 +1048,14 @@ def sync_caddy_neko_snippet(count: int) -> dict[str, Any]:
|
||||
def _host_http_ok(instance_id: int) -> bool:
|
||||
"""True when published host port answers (detects stale containers with empty PortBindings)."""
|
||||
port = _http_port(int(instance_id))
|
||||
# Always bypass env HTTP(S)_PROXY — otherwise curl to 127.0.0.1:920x goes via proxy
|
||||
# and falsely reports dead, triggering endless force-recreate → public /neko/N 502.
|
||||
code, text = _run(
|
||||
[
|
||||
"curl",
|
||||
"-sS",
|
||||
"--noproxy",
|
||||
"*",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
@ -1437,20 +1441,88 @@ def stop_instances_except(keep_instance_id: int) -> list[int]:
|
||||
return stopped
|
||||
|
||||
|
||||
def _host_http_published(instance_id: int) -> bool:
|
||||
"""True when docker-proxy has the instance HTTP port (even if app still booting)."""
|
||||
port = _http_port(int(instance_id))
|
||||
code, text = _run(
|
||||
["ss", "-lnt"],
|
||||
timeout=6,
|
||||
)
|
||||
needle = f":{port}"
|
||||
return code == 0 and needle in (text or "")
|
||||
|
||||
|
||||
def ensure_instance_running(instance_id: int) -> dict[str, Any]:
|
||||
"""Ensure one Neko container exists and is running (for exclusive-live winner)."""
|
||||
import time as _time
|
||||
|
||||
_ensure_browser_launch_exec()
|
||||
idx = int(instance_id or 0)
|
||||
if idx < 1:
|
||||
return {"ok": False, "skipped": "no_instance"}
|
||||
desired = max(_desired_from_db(), idx)
|
||||
ensure_capacity(desired, start_instances={idx}, reconcile_running=False)
|
||||
name = _container_name(idx)
|
||||
svc = f"neko{idx}"
|
||||
st = _container_state(idx)
|
||||
if st.get("running"):
|
||||
if st.get("running") and _host_http_ok(idx):
|
||||
return {"ok": True, "id": idx, "already": True}
|
||||
code, out = _run(["docker", "start", _container_name(idx)], timeout=60)
|
||||
|
||||
# Booting: port published but / not answering yet — wait, do not recreate (avoids 502 races).
|
||||
if st.get("running") and _host_http_published(idx) and not _host_http_ok(idx):
|
||||
for _ in range(20):
|
||||
_time.sleep(2.0)
|
||||
if _host_http_ok(idx):
|
||||
return {"ok": True, "id": idx, "waited_boot": True}
|
||||
# fall through to recreate only if still dead after ~40s
|
||||
|
||||
# Stale exists with no published HTTP — force remove then compose up once.
|
||||
if st.get("exists") and (not st.get("running") or not _host_http_ok(idx)):
|
||||
_run(["docker", "rm", "-f", name], timeout=45)
|
||||
ensure_capacity(desired, start_instances=set())
|
||||
code, out = _run(
|
||||
_compose_cmd("up", "-d", "--force-recreate", "--no-deps", svc),
|
||||
timeout=300,
|
||||
)
|
||||
if code != 0:
|
||||
return {"ok": False, "id": idx, "error": (out or "force-recreate failed")[:300]}
|
||||
_run(["docker", "start", name], timeout=60)
|
||||
for _ in range(20):
|
||||
if _host_http_ok(idx):
|
||||
return {"ok": True, "id": idx, "recreated": True}
|
||||
_time.sleep(2.0)
|
||||
return {
|
||||
"ok": False,
|
||||
"id": idx,
|
||||
"error": f"recreated but host port {_http_port(idx)} unreachable",
|
||||
}
|
||||
|
||||
code, out = _run(["docker", "start", name], timeout=60)
|
||||
if code != 0:
|
||||
return {"ok": False, "id": idx, "error": (out or "start failed")[:300]}
|
||||
for _ in range(15):
|
||||
if _host_http_ok(idx):
|
||||
return {"ok": True, "id": idx, "started": True}
|
||||
_time.sleep(2.0)
|
||||
if not _host_http_ok(idx):
|
||||
_run(["docker", "rm", "-f", name], timeout=45)
|
||||
ensure_capacity(desired, start_instances=set())
|
||||
code, out = _run(
|
||||
_compose_cmd("up", "-d", "--force-recreate", "--no-deps", svc),
|
||||
timeout=300,
|
||||
)
|
||||
if code != 0:
|
||||
return {"ok": False, "id": idx, "error": (out or "force-recreate failed")[:300]}
|
||||
_run(["docker", "start", name], timeout=60)
|
||||
for _ in range(20):
|
||||
if _host_http_ok(idx):
|
||||
return {"ok": True, "id": idx, "recreated": True}
|
||||
_time.sleep(2.0)
|
||||
return {
|
||||
"ok": False,
|
||||
"id": idx,
|
||||
"error": f"started but host port {_http_port(idx)} unreachable",
|
||||
}
|
||||
return {"ok": True, "id": idx, "started": True}
|
||||
|
||||
|
||||
@ -2403,15 +2475,38 @@ def wait_instance_ready_for_live(
|
||||
if isinstance(sig, dict) and sig.get("ok"):
|
||||
preparing = bool(sig.get("preparing_stream"))
|
||||
control_ready = bool(sig.get("control_ready"))
|
||||
chrome_offline = bool(sig.get("chrome_offline")) or (
|
||||
"err_internet" in str(sig.get("text") or "").lower()
|
||||
or "no internet" in str(sig.get("text") or "").lower()
|
||||
)
|
||||
encoder_receiving = bool(
|
||||
(sig.get("encoder_receiving") or sig.get("on_air"))
|
||||
and not chrome_offline
|
||||
)
|
||||
if sig.get("live_status"):
|
||||
live_status = str(sig.get("live_status") or live_status)
|
||||
if sig.get("health"):
|
||||
health = str(sig.get("health") or health)
|
||||
if chrome_offline:
|
||||
# Chrome interstitial ≠ Studio receiving — keep waiting.
|
||||
_time.sleep(2.0)
|
||||
continue
|
||||
if preparing:
|
||||
# Keep waiting — never hand off to FFmpeg while preview spins.
|
||||
_time.sleep(2.0)
|
||||
continue
|
||||
if not control_ready and live_status not in {"live", "waiting", "encoder_lost"}:
|
||||
# Receiving-first: Studio already accepting encoder → do not block on
|
||||
# SPA chrome flags (control_ready can lag while ingest is healthy).
|
||||
if encoder_receiving:
|
||||
control_ready = True
|
||||
if not live_status:
|
||||
live_status = "live" if sig.get("on_air") else "receiving"
|
||||
if not control_ready and live_status not in {
|
||||
"live",
|
||||
"waiting",
|
||||
"encoder_lost",
|
||||
"receiving",
|
||||
}:
|
||||
_time.sleep(2.0)
|
||||
continue
|
||||
return {
|
||||
@ -2633,16 +2728,23 @@ def recreate_all_instances(*, start_enabled: bool = True) -> dict[str, Any]:
|
||||
|
||||
# --- Studio telemetry ingest (sh2 live-ops extension) ---
|
||||
_studio_events: list[dict[str, Any]] = []
|
||||
_STUDIO_EVENTS_MAX = 200
|
||||
# Keep ring buffer small — dozens of Nekos POSTing every few seconds otherwise
|
||||
# retain hundreds of full Studio payloads and push RSS over MemoryHigh.
|
||||
_STUDIO_EVENTS_MAX = 80
|
||||
_studio_latest_by_neko: dict[int, dict[str, Any]] = {}
|
||||
_studio_latest_by_ref: dict[str, dict[str, Any]] = {}
|
||||
_studio_minute_reports: dict[int, list[dict[str, Any]]] = {}
|
||||
_studio_minute_reports_by_ref: dict[str, list[dict[str, Any]]] = {}
|
||||
_studio_minute_last_at: dict[int, float] = {}
|
||||
_studio_minute_last_at_by_ref: dict[str, float] = {}
|
||||
_STUDIO_MINUTE_MAX = 120
|
||||
_STUDIO_MINUTE_MAX = 60
|
||||
_studio_bootstrapped = False
|
||||
_CDP_POLL_INTERVAL_SEC = 55.0
|
||||
# Per-ref coalesce: drop duplicate ingest storms that only update timestamps.
|
||||
_studio_ingest_last_fp: dict[str, tuple[float, str]] = {}
|
||||
_STUDIO_INGEST_COALESCE_SEC = 12.0
|
||||
_STUDIO_DISK_WRITE_MIN_INTERVAL = 30.0
|
||||
_studio_disk_write_at = 0.0
|
||||
|
||||
|
||||
def parse_neko_ref(raw: Any) -> tuple[str, str, int]:
|
||||
@ -2966,12 +3068,34 @@ def _maybe_append_minute_report(neko_id: int, event: dict[str, Any], *, ref_key:
|
||||
pass
|
||||
|
||||
|
||||
_studio_disk_write_at: float = 0.0
|
||||
_STUDIO_DISK_WRITE_MIN_INTERVAL = 2.0
|
||||
def _studio_ingest_fingerprint(body: dict[str, Any]) -> str:
|
||||
"""Cheap fingerprint so unchanged Studio chrome doesn't allocate new events.
|
||||
|
||||
Intentionally ignores tick-level viewer_count / duration — those change every few
|
||||
seconds during a live and would defeat coalesce (dy RSS climb).
|
||||
"""
|
||||
signals = body.get("signals") if isinstance(body.get("signals"), dict) else {}
|
||||
return "|".join(
|
||||
[
|
||||
str(body.get("live_status") or ""),
|
||||
str(body.get("health") or ""),
|
||||
"1" if body.get("on_air") else "0",
|
||||
"1" if signals.get("encoder_receiving") else "0",
|
||||
"1" if signals.get("nodata") else "0",
|
||||
"1" if signals.get("encoder_lost") else "0",
|
||||
"1" if signals.get("chrome_offline") else "0",
|
||||
str(body.get("url") or "")[-48:],
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""Accept Studio telemetry from in-container Chrome extension (local or ops-neko)."""
|
||||
"""Accept Studio telemetry from in-container Chrome extension (local or ops-neko).
|
||||
|
||||
Hot path must stay allocation-light: Neko tabs POST every few seconds. Duplicate
|
||||
fingerprints are coalesced in-place so RSS cannot climb into MemoryHigh thrash
|
||||
(dy historically hung in D-state with /api/health timing out while PID stayed "active").
|
||||
"""
|
||||
import time as _time
|
||||
import uuid
|
||||
|
||||
@ -2986,6 +3110,60 @@ def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]:
|
||||
body["neko_ref"] = ref_key
|
||||
body["neko_kind"] = kind
|
||||
now = float(body.get("received_at") or _time.time())
|
||||
coalesce_key = ref_key or (f"local:{neko_id}" if neko_id > 0 else "")
|
||||
fp = _studio_ingest_fingerprint(body)
|
||||
if coalesce_key:
|
||||
prev = _studio_ingest_last_fp.get(coalesce_key)
|
||||
if prev and (now - float(prev[0])) < _STUDIO_INGEST_COALESCE_SEC and prev[1] == fp:
|
||||
# Refresh latest timestamp + volatile counters in-place — no new event alloc.
|
||||
existing = _studio_latest_by_ref.get(coalesce_key) or (
|
||||
_studio_latest_by_neko.get(neko_id) if neko_id > 0 else None
|
||||
)
|
||||
if isinstance(existing, dict):
|
||||
existing["received_at"] = now
|
||||
payload_ex = existing.get("payload")
|
||||
if isinstance(payload_ex, dict):
|
||||
payload_ex["received_at"] = now
|
||||
for k in (
|
||||
"viewer_count",
|
||||
"total_views",
|
||||
"like_count",
|
||||
"live_duration",
|
||||
"live_duration_sec",
|
||||
"stream_title",
|
||||
):
|
||||
if k in body and body.get(k) is not None:
|
||||
payload_ex[k] = body.get(k)
|
||||
# Still stamp minute buckets while coalescing (55s gate inside).
|
||||
try:
|
||||
_maybe_append_minute_report(
|
||||
neko_id,
|
||||
existing,
|
||||
ref_key=ref_key or coalesce_key,
|
||||
kind=kind,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# Slide coalesce window so stable live doesn't allocate every 12s forever.
|
||||
_studio_ingest_last_fp[coalesce_key] = (now, fp)
|
||||
return {
|
||||
"ok": True,
|
||||
"coalesced": True,
|
||||
"event": {
|
||||
"id": existing.get("id"),
|
||||
"received_at": now,
|
||||
"neko_instance_id": neko_id,
|
||||
"neko_ref": ref_key,
|
||||
"neko_kind": kind,
|
||||
},
|
||||
}
|
||||
_studio_ingest_last_fp[coalesce_key] = (now, fp)
|
||||
# Bound coalesce map (ops refs can churn over weeks).
|
||||
if len(_studio_ingest_last_fp) > 256:
|
||||
oldest = sorted(_studio_ingest_last_fp.items(), key=lambda kv: float(kv[1][0]))[:64]
|
||||
for k, _ in oldest:
|
||||
_studio_ingest_last_fp.pop(k, None)
|
||||
|
||||
event = {
|
||||
"id": str(uuid.uuid4()),
|
||||
"received_at": now,
|
||||
@ -3004,8 +3182,7 @@ def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]:
|
||||
_maybe_append_minute_report(neko_id, event, ref_key=f"local:{neko_id}", kind="local")
|
||||
if neko_id > 0:
|
||||
_studio_latest_by_neko[neko_id] = event
|
||||
# Dozens of Neko tabs POST every ~1–2s; indent+rewrite of one file saturates the
|
||||
# default thread pool and wedges /api/health (to_thread). Debounce disk persist.
|
||||
# Debounce disk persist — under MemoryHigh reclaim, sync writes → D-state hangs.
|
||||
if now - _studio_disk_write_at >= _STUDIO_DISK_WRITE_MIN_INTERVAL:
|
||||
_studio_disk_write_at = now
|
||||
try:
|
||||
@ -3018,7 +3195,7 @@ def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"event": {
|
||||
"id": event["id"],
|
||||
"received_at": event["received_at"],
|
||||
"neko_instance_id": neko_id,
|
||||
"neko_instance_id": event["neko_instance_id"],
|
||||
"neko_ref": ref_key,
|
||||
"neko_kind": kind,
|
||||
},
|
||||
|
||||
@ -219,6 +219,95 @@ def _terminate_proc(proc: subprocess.Popen | None) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def kill_ffmpeg_sharing_rtmp(youtube_rtmp: str, *, keep_pid: int = 0) -> list[int]:
|
||||
"""Kill other host ffmpeg processes already pushing the same YouTube stream key.
|
||||
|
||||
YouTube returns "More than one ingestion is using the primary URL" when two
|
||||
encoders share one key — Studio health goes Poor and public live flaps.
|
||||
"""
|
||||
import os
|
||||
|
||||
key = (youtube_rtmp or "").rstrip("/").split("/")[-1].strip()
|
||||
if len(key) < 8:
|
||||
return []
|
||||
try:
|
||||
out = subprocess.check_output(["ps", "-eo", "pid,cmd"], text=True, timeout=8)
|
||||
except Exception:
|
||||
return []
|
||||
killed: list[int] = []
|
||||
keep = int(keep_pid or 0)
|
||||
keep_set = {keep} if keep > 0 else set()
|
||||
# Also protect children of keep (proxychains → ffmpeg).
|
||||
if keep > 0:
|
||||
try:
|
||||
for line in out.splitlines():
|
||||
parts = line.split(None, 1)
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
try:
|
||||
pid = int(parts[0])
|
||||
except Exception:
|
||||
continue
|
||||
# /proc ppid check below
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
import pathlib
|
||||
|
||||
for proc_dir in pathlib.Path("/proc").iterdir():
|
||||
if not proc_dir.name.isdigit():
|
||||
continue
|
||||
pid = int(proc_dir.name)
|
||||
try:
|
||||
status = (proc_dir / "status").read_text(encoding="utf-8", errors="ignore")
|
||||
except Exception:
|
||||
continue
|
||||
for ln in status.splitlines():
|
||||
if ln.startswith("PPid:"):
|
||||
try:
|
||||
ppid = int(ln.split()[1])
|
||||
except Exception:
|
||||
break
|
||||
if ppid in keep_set or pid == keep:
|
||||
keep_set.add(pid)
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
for line in out.splitlines():
|
||||
low = line.lower()
|
||||
if "ffmpeg" not in low or key not in line:
|
||||
continue
|
||||
# Only YouTube ingest destinations — never match unrelated ffmpeg with same token.
|
||||
if "rtmps.youtube.com" not in low and "rtmp.youtube.com" not in low and "/live2/" not in low:
|
||||
continue
|
||||
try:
|
||||
pid = int(line.split(None, 1)[0])
|
||||
except Exception:
|
||||
continue
|
||||
if pid in keep_set:
|
||||
continue
|
||||
try:
|
||||
os.kill(pid, 9)
|
||||
killed.append(pid)
|
||||
except Exception:
|
||||
pass
|
||||
return killed
|
||||
|
||||
|
||||
_RTMP_SPAWN_LOCKS: dict[str, threading.Lock] = {}
|
||||
_RTMP_SPAWN_LOCKS_MU = threading.Lock()
|
||||
|
||||
|
||||
def _rtmp_spawn_lock(youtube_rtmp: str) -> threading.Lock:
|
||||
key = (youtube_rtmp or "").rstrip("/").split("/")[-1].strip() or "_"
|
||||
with _RTMP_SPAWN_LOCKS_MU:
|
||||
lock = _RTMP_SPAWN_LOCKS.get(key)
|
||||
if lock is None:
|
||||
lock = threading.Lock()
|
||||
_RTMP_SPAWN_LOCKS[key] = lock
|
||||
return lock
|
||||
|
||||
|
||||
class RelayPushSession:
|
||||
"""One FFmpeg push subprocess with stderr monitoring.
|
||||
|
||||
@ -325,6 +414,51 @@ class RelayPushSession:
|
||||
self.stats.recent_log.append(
|
||||
f"[ffmpeg] source {self._source_index + 1}/{len(self.input_urls)} -i {self.input_url[:160]}"
|
||||
)
|
||||
# Serialize spawn per stream key so two sessions cannot Popen then
|
||||
# mutually kill each other via post-spawn rival cleanup.
|
||||
with _rtmp_spawn_lock(self.youtube_rtmp):
|
||||
# Do NOT pre-kill without keep_pid: a concurrent session may already
|
||||
# hold the only healthy encoder for this key.
|
||||
try:
|
||||
try:
|
||||
from . import egress_hub
|
||||
|
||||
wrapped = egress_hub.wrap_ffmpeg_cmd(cmd)
|
||||
if wrapped != cmd:
|
||||
self.stats.recent_log.append(
|
||||
f"[ffmpeg] egress proxychains mode={egress_hub.get_mode()}"
|
||||
)
|
||||
cmd = wrapped
|
||||
except Exception as exc:
|
||||
self.stats.recent_log.append(f"[ffmpeg] egress wrap skipped: {exc}")
|
||||
# Keep encode RAM out of douyinweb-api MemoryHigh (D-state hang).
|
||||
from .procutil import popen_outside_api_cgroup
|
||||
|
||||
self._proc = popen_outside_api_cgroup(
|
||||
cmd,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
self.stats.recent_log.append("[ffmpeg] ERROR: ffmpeg binary not found")
|
||||
self.stats.running = False
|
||||
return
|
||||
except Exception as exc:
|
||||
self.stats.recent_log.append(f"[ffmpeg] ERROR spawn failed: {exc}")
|
||||
self.stats.running = False
|
||||
return
|
||||
|
||||
self.stats.pid = int(self._proc.pid or 0)
|
||||
self.stats.running = True
|
||||
try:
|
||||
rivals = kill_ffmpeg_sharing_rtmp(self.youtube_rtmp, keep_pid=self.stats.pid)
|
||||
if rivals:
|
||||
self.stats.recent_log.append(f"[ffmpeg] post-spawn killed rivals {rivals}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _reader() -> None:
|
||||
proc = self._proc
|
||||
@ -345,37 +479,6 @@ class RelayPushSession:
|
||||
finally:
|
||||
q.put(None)
|
||||
|
||||
try:
|
||||
try:
|
||||
from . import egress_hub
|
||||
|
||||
wrapped = egress_hub.wrap_ffmpeg_cmd(cmd)
|
||||
if wrapped != cmd:
|
||||
self.stats.recent_log.append(
|
||||
f"[ffmpeg] egress proxychains mode={egress_hub.get_mode()}"
|
||||
)
|
||||
cmd = wrapped
|
||||
except Exception as exc:
|
||||
self.stats.recent_log.append(f"[ffmpeg] egress wrap skipped: {exc}")
|
||||
self._proc = subprocess.Popen(
|
||||
cmd,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
self.stats.recent_log.append("[ffmpeg] ERROR: ffmpeg binary not found")
|
||||
self.stats.running = False
|
||||
return
|
||||
except Exception as exc:
|
||||
self.stats.recent_log.append(f"[ffmpeg] ERROR spawn failed: {exc}")
|
||||
self.stats.running = False
|
||||
return
|
||||
|
||||
self.stats.pid = int(self._proc.pid or 0)
|
||||
self.stats.running = True
|
||||
self.stats.recent_log.append(f"[ffmpeg] pid={self.stats.pid} started")
|
||||
if self.on_stats:
|
||||
try:
|
||||
|
||||
@ -37,10 +37,19 @@ def _live_room_ids() -> set[str]:
|
||||
|
||||
|
||||
def _douyin_live_count_cached() -> int:
|
||||
"""Cheap live room count — never rebuild the full douyin live-map (that allocates huge dicts)."""
|
||||
try:
|
||||
from . import douyin_live
|
||||
|
||||
return int(douyin_live.build_live_map().get("live_count") or 0)
|
||||
cached = douyin_live._CACHE.get("payload") # noqa: SLF001
|
||||
if isinstance(cached, dict) and (time.time() - float(douyin_live._CACHE.get("at") or 0)) < float(
|
||||
getattr(douyin_live, "_CACHE_TTL_SEC", 12.0)
|
||||
):
|
||||
return int(cached.get("live_count") or 0)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
return int(db.monitor_status_data(light=True).get("counts", {}).get("live_rooms") or 0)
|
||||
except Exception:
|
||||
try:
|
||||
return len(_live_room_ids())
|
||||
@ -305,6 +314,29 @@ class YoutubeRelayPipeline:
|
||||
)
|
||||
return True, msg
|
||||
|
||||
def pushing_flags(self) -> dict[str, dict[str, bool]]:
|
||||
"""Lightweight {group_id: {is_pushing}} for live-map — avoids full status rebuild."""
|
||||
out: dict[str, dict[str, bool]] = {}
|
||||
try:
|
||||
states = {str(s.get("group_id") or ""): s for s in youtube_relay_db.list_relay_states()}
|
||||
except Exception:
|
||||
states = {}
|
||||
for gid, st in states.items():
|
||||
if not gid:
|
||||
continue
|
||||
sess = self._sessions.get(gid)
|
||||
running = bool(sess and sess.stats.running)
|
||||
orphan_pid = int(st.get("ffmpeg_pid") or 0)
|
||||
orphan_alive = (not running) and _ffmpeg_pid_alive(orphan_pid)
|
||||
raw = str(st.get("status") or "").lower()
|
||||
pushing = running or orphan_alive or raw in {"pushing", "streaming"}
|
||||
out[gid] = {"is_pushing": pushing}
|
||||
for gid, sess in list(self._sessions.items()):
|
||||
if gid in out:
|
||||
continue
|
||||
out[gid] = {"is_pushing": bool(sess and sess.stats.running)}
|
||||
return out
|
||||
|
||||
def status(self) -> dict[str, Any]:
|
||||
now = time.time()
|
||||
cached = self._status_cache
|
||||
@ -429,7 +461,30 @@ class YoutubeRelayPipeline:
|
||||
"ops_neko_slot": int(g.get("ops_neko_slot") or 0),
|
||||
}
|
||||
try:
|
||||
snap = youtube_neko.studio_snapshot_for_group(g, max_age_sec=120.0)
|
||||
# Keep lean minute_reports for the status panel chart (LIVE 时长≠空报告).
|
||||
# Cap fields so poll JSON stays small — no text/html blobs.
|
||||
snap = youtube_neko.studio_snapshot_for_group(
|
||||
g, max_age_sec=120.0, include_minute_reports=True
|
||||
)
|
||||
raw_reports = snap.get("minute_reports") if isinstance(snap.get("minute_reports"), list) else []
|
||||
lean_reports: list[dict[str, Any]] = []
|
||||
for mr in raw_reports[:45]:
|
||||
if not isinstance(mr, dict):
|
||||
continue
|
||||
lean_reports.append(
|
||||
{
|
||||
"ts": mr.get("ts"),
|
||||
"viewer_count": mr.get("viewer_count"),
|
||||
"total_views": mr.get("total_views"),
|
||||
"like_count": mr.get("like_count"),
|
||||
"live_duration": str(mr.get("live_duration") or "")[:16],
|
||||
"live_duration_sec": mr.get("live_duration_sec"),
|
||||
"on_air": bool(mr.get("on_air")),
|
||||
"live_status": str(mr.get("live_status") or "")[:24],
|
||||
"health": str(mr.get("health") or "")[:24],
|
||||
"neko_ref": str(mr.get("neko_ref") or "")[:32],
|
||||
}
|
||||
)
|
||||
neko_state["studio"] = {
|
||||
"live_page_open": bool(snap.get("live_page_open")),
|
||||
"on_air": bool(snap.get("on_air")),
|
||||
@ -445,7 +500,7 @@ class YoutubeRelayPipeline:
|
||||
"received_at": snap.get("received_at") or 0,
|
||||
"age_sec": snap.get("age_sec"),
|
||||
"detect_source": snap.get("detect_source") or "",
|
||||
"minute_reports": snap.get("minute_reports") or [],
|
||||
"minute_reports": lean_reports,
|
||||
"neko_ref": snap.get("neko_ref") or "",
|
||||
"neko_kind": snap.get("neko_kind") or "",
|
||||
"ui_source": snap.get("ui_source") or "",
|
||||
|
||||
@ -135,7 +135,9 @@ async def record_long_clip(
|
||||
|
||||
def _run(cmd_local: list[str] = cmd, used_url: str = url) -> dict[str, Any]:
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
from .procutil import run_outside_api_cgroup
|
||||
|
||||
proc = run_outside_api_cgroup(
|
||||
cmd_local,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
|
||||
@ -535,6 +535,13 @@ class YtLongPipeline:
|
||||
cfg = db.get_settings_map()
|
||||
max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1))
|
||||
# Never reclaim active long recordings here (3–8 min + encode); loop handles orphans safely
|
||||
try:
|
||||
from .host_metrics import clip_encode_defer_reason
|
||||
|
||||
if clip_encode_defer_reason():
|
||||
return 0
|
||||
except Exception:
|
||||
pass
|
||||
db_recording = yt_long_db.count_yt_long_jobs_by_status("recording")
|
||||
slots = max(0, max_rec - max(self._active_records, db_recording))
|
||||
if slots <= 0:
|
||||
@ -642,7 +649,18 @@ class YtLongPipeline:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
while self._active_records < max_rec and db_recording < max_rec:
|
||||
# Never steal CPU from live YouTube push (site hang root cause on dy VPS).
|
||||
try:
|
||||
from .host_metrics import clip_encode_defer_reason
|
||||
|
||||
defer = clip_encode_defer_reason()
|
||||
except Exception:
|
||||
defer = ""
|
||||
while (
|
||||
not defer
|
||||
and self._active_records < max_rec
|
||||
and db_recording < max_rec
|
||||
):
|
||||
pending = yt_long_db.list_pending_yt_long_jobs(limit=1)
|
||||
if not pending:
|
||||
break
|
||||
|
||||
413
backend/app/yt_revenue.py
Normal file
413
backend/app/yt_revenue.py
Normal file
@ -0,0 +1,413 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""YouTube AdSense / Analytics monetary revenue — linked to Live / Shorts / 长视频.
|
||||
|
||||
Uses YouTube Analytics API v2 estimatedRevenue metrics. Requires opt-in OAuth
|
||||
scopes (yt-analytics-monetary.readonly) — not part of default upload oauth_ok.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from . import db
|
||||
from . import yt_assign_db
|
||||
from .shorts_oauth import channel_oauth_creds, monetary_scopes, token_scopes
|
||||
from .shorts_upload import refresh_access_token
|
||||
|
||||
_ANALYTICS = "https://youtubeanalytics.googleapis.com/v2/reports"
|
||||
_CACHE: dict[str, tuple[float, dict[str, Any]]] = {}
|
||||
_CACHE_TTL_SEC = 900.0 # 15 min
|
||||
|
||||
_CONTENT_MAP = {
|
||||
"LIVE_STREAM": "live",
|
||||
"SHORTS": "shorts",
|
||||
"VIDEO_ON_DEMAND": "long",
|
||||
# legacy / alternate labels
|
||||
"LIVE": "live",
|
||||
"ON_DEMAND": "long",
|
||||
}
|
||||
|
||||
|
||||
def _beijing_today() -> date:
|
||||
return datetime.now(timezone(timedelta(hours=8))).date()
|
||||
|
||||
|
||||
def _httpx_kwargs(*, timeout: float = 45.0) -> dict[str, Any]:
|
||||
try:
|
||||
from . import egress_hub
|
||||
|
||||
return egress_hub.google_httpx_kwargs(timeout=timeout)
|
||||
except Exception:
|
||||
return {"timeout": timeout, "trust_env": False}
|
||||
|
||||
|
||||
def _parse_float(v: Any) -> float | None:
|
||||
try:
|
||||
if v is None or v == "":
|
||||
return None
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _empty_bucket() -> dict[str, Any]:
|
||||
return {
|
||||
"estimated_revenue": 0.0,
|
||||
"estimated_ad_revenue": 0.0,
|
||||
"gross_revenue": 0.0,
|
||||
"monetized_playbacks": 0.0,
|
||||
"ad_impressions": 0.0,
|
||||
"playback_based_cpm": None,
|
||||
}
|
||||
|
||||
|
||||
def _add_row(bucket: dict[str, Any], cols: dict[str, Any]) -> None:
|
||||
for k in (
|
||||
"estimated_revenue",
|
||||
"estimated_ad_revenue",
|
||||
"gross_revenue",
|
||||
"monetized_playbacks",
|
||||
"ad_impressions",
|
||||
):
|
||||
bucket[k] = float(bucket.get(k) or 0) + float(cols.get(k) or 0)
|
||||
cpm = cols.get("playback_based_cpm")
|
||||
if cpm is not None:
|
||||
bucket["playback_based_cpm"] = cpm
|
||||
|
||||
|
||||
async def _access_for_channel(channel_pk: str) -> tuple[str, dict[str, Any]]:
|
||||
ch = db.get_shorts_channel(channel_pk)
|
||||
if not ch:
|
||||
raise ValueError("频道不存在")
|
||||
creds = channel_oauth_creds(ch)
|
||||
if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]):
|
||||
raise ValueError("频道未授权 Google OAuth")
|
||||
token = await refresh_access_token(
|
||||
client_id=creds["client_id"],
|
||||
client_secret=creds["client_secret"],
|
||||
refresh_token=creds["refresh_token"],
|
||||
)
|
||||
return token, ch
|
||||
|
||||
|
||||
async def channel_monetary_ready(channel_pk: str) -> dict[str, Any]:
|
||||
"""Check whether this Shorts OAuth token has Analytics monetary scopes."""
|
||||
try:
|
||||
token, ch = await _access_for_channel(channel_pk)
|
||||
except Exception as exc:
|
||||
return {
|
||||
"ok": False,
|
||||
"authorized": False,
|
||||
"monetary_ok": False,
|
||||
"error": str(exc)[:200],
|
||||
"missing_scopes": monetary_scopes(),
|
||||
}
|
||||
granted = await token_scopes(token)
|
||||
need = set(monetary_scopes())
|
||||
missing = sorted(s for s in need if s not in granted)
|
||||
return {
|
||||
"ok": True,
|
||||
"authorized": True,
|
||||
"monetary_ok": not missing,
|
||||
"missing_scopes": missing,
|
||||
"channel_pk": channel_pk,
|
||||
"youtube_channel_id": str(ch.get("youtube_channel_id") or ""),
|
||||
"name": str(ch.get("name") or ch.get("title") or ""),
|
||||
}
|
||||
|
||||
|
||||
async def _query_reports(
|
||||
access: str,
|
||||
*,
|
||||
start: str,
|
||||
end: str,
|
||||
metrics: str,
|
||||
dimensions: str = "",
|
||||
filters: str = "",
|
||||
) -> dict[str, Any]:
|
||||
params: dict[str, str] = {
|
||||
"ids": "channel==MINE",
|
||||
"startDate": start,
|
||||
"endDate": end,
|
||||
"metrics": metrics,
|
||||
}
|
||||
if dimensions:
|
||||
params["dimensions"] = dimensions
|
||||
if filters:
|
||||
params["filters"] = filters
|
||||
async with httpx.AsyncClient(**_httpx_kwargs()) as client:
|
||||
resp = await client.get(
|
||||
_ANALYTICS,
|
||||
params=params,
|
||||
headers={"Authorization": f"Bearer {access}"},
|
||||
)
|
||||
data = resp.json() if resp.content else {}
|
||||
if resp.status_code >= 400:
|
||||
err = data.get("error") if isinstance(data, dict) else None
|
||||
msg = ""
|
||||
if isinstance(err, dict):
|
||||
msg = str(err.get("message") or err)
|
||||
raise RuntimeError(msg or f"analytics HTTP {resp.status_code}: {str(data)[:240]}")
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _rows_as_dicts(report: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
headers = [str(h.get("name") or "") for h in (report.get("columnHeaders") or []) if isinstance(h, dict)]
|
||||
out: list[dict[str, Any]] = []
|
||||
for row in report.get("rows") or []:
|
||||
if not isinstance(row, (list, tuple)):
|
||||
continue
|
||||
item: dict[str, Any] = {}
|
||||
for i, name in enumerate(headers):
|
||||
if i >= len(row):
|
||||
break
|
||||
item[name] = row[i]
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def _metric_cols(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"estimated_revenue": _parse_float(row.get("estimatedRevenue")) or 0.0,
|
||||
"estimated_ad_revenue": _parse_float(row.get("estimatedAdRevenue")) or 0.0,
|
||||
"gross_revenue": _parse_float(row.get("grossRevenue")) or 0.0,
|
||||
"monetized_playbacks": _parse_float(row.get("monetizedPlaybacks")) or 0.0,
|
||||
"ad_impressions": _parse_float(row.get("adImpressions")) or 0.0,
|
||||
"playback_based_cpm": _parse_float(row.get("playbackBasedCpm")),
|
||||
}
|
||||
|
||||
|
||||
_METRICS = (
|
||||
"estimatedRevenue,estimatedAdRevenue,grossRevenue,"
|
||||
"monetizedPlaybacks,adImpressions,playbackBasedCpm"
|
||||
)
|
||||
|
||||
|
||||
async def fetch_channel_revenue(
|
||||
channel_pk: str,
|
||||
*,
|
||||
days: int = 28,
|
||||
force: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Pull AdSense-linked YouTube Analytics revenue for one OAuth channel."""
|
||||
days_i = max(1, min(90, int(days or 28)))
|
||||
cache_key = f"{channel_pk}:{days_i}"
|
||||
now = time.time()
|
||||
if not force:
|
||||
hit = _CACHE.get(cache_key)
|
||||
if hit and (now - float(hit[0])) < _CACHE_TTL_SEC:
|
||||
return dict(hit[1])
|
||||
|
||||
ready = await channel_monetary_ready(channel_pk)
|
||||
if not ready.get("authorized"):
|
||||
out = {
|
||||
"ok": False,
|
||||
"channel_pk": channel_pk,
|
||||
"error": ready.get("error") or "未授权",
|
||||
"monetary_ok": False,
|
||||
"need_reauth": True,
|
||||
}
|
||||
return out
|
||||
if not ready.get("monetary_ok"):
|
||||
out = {
|
||||
"ok": False,
|
||||
"channel_pk": channel_pk,
|
||||
"name": ready.get("name"),
|
||||
"youtube_channel_id": ready.get("youtube_channel_id"),
|
||||
"error": "缺少 YouTube Analytics 收益权限,请在本页点击「授权收益」",
|
||||
"monetary_ok": False,
|
||||
"need_reauth": True,
|
||||
"missing_scopes": ready.get("missing_scopes") or [],
|
||||
}
|
||||
return out
|
||||
|
||||
token, ch = await _access_for_channel(channel_pk)
|
||||
end = _beijing_today()
|
||||
start = end - timedelta(days=days_i - 1)
|
||||
start_s, end_s = start.isoformat(), end.isoformat()
|
||||
|
||||
by_type = {
|
||||
"live": _empty_bucket(),
|
||||
"shorts": _empty_bucket(),
|
||||
"long": _empty_bucket(),
|
||||
"other": _empty_bucket(),
|
||||
}
|
||||
daily: list[dict[str, Any]] = []
|
||||
totals = _empty_bucket()
|
||||
type_error = ""
|
||||
|
||||
try:
|
||||
total_report = await _query_reports(
|
||||
token, start=start_s, end=end_s, metrics=_METRICS, dimensions="day"
|
||||
)
|
||||
for row in _rows_as_dicts(total_report):
|
||||
cols = _metric_cols(row)
|
||||
_add_row(totals, cols)
|
||||
daily.append({"day": str(row.get("day") or ""), **cols})
|
||||
except Exception as exc:
|
||||
return {
|
||||
"ok": False,
|
||||
"channel_pk": channel_pk,
|
||||
"name": str(ch.get("name") or ""),
|
||||
"youtube_channel_id": str(ch.get("youtube_channel_id") or ""),
|
||||
"error": str(exc)[:300],
|
||||
"monetary_ok": True,
|
||||
"need_reauth": "insufficient" in str(exc).lower() or "scope" in str(exc).lower(),
|
||||
}
|
||||
|
||||
try:
|
||||
type_report = await _query_reports(
|
||||
token,
|
||||
start=start_s,
|
||||
end=end_s,
|
||||
metrics=_METRICS,
|
||||
dimensions="creatorContentType",
|
||||
)
|
||||
for row in _rows_as_dicts(type_report):
|
||||
raw = str(row.get("creatorContentType") or "").strip().upper()
|
||||
key = _CONTENT_MAP.get(raw, "other")
|
||||
_add_row(by_type[key], _metric_cols(row))
|
||||
except Exception as exc:
|
||||
# Some channels/API versions lack creatorContentType — keep totals, note gap.
|
||||
type_error = str(exc)[:240]
|
||||
# Fallback: liveOrOnDemand if available
|
||||
try:
|
||||
lod = await _query_reports(
|
||||
token,
|
||||
start=start_s,
|
||||
end=end_s,
|
||||
metrics=_METRICS,
|
||||
dimensions="liveOrOnDemand",
|
||||
)
|
||||
for row in _rows_as_dicts(lod):
|
||||
raw = str(row.get("liveOrOnDemand") or "").strip().upper()
|
||||
key = "live" if raw == "LIVE" else "long"
|
||||
_add_row(by_type[key], _metric_cols(row))
|
||||
type_error = ""
|
||||
except Exception as exc2:
|
||||
type_error = f"{type_error}; fallback: {exc2}"[:300]
|
||||
|
||||
links = _product_links(
|
||||
youtube_channel_id=str(ch.get("youtube_channel_id") or ""),
|
||||
shorts_pk=channel_pk,
|
||||
)
|
||||
out: dict[str, Any] = {
|
||||
"ok": True,
|
||||
"channel_pk": channel_pk,
|
||||
"name": str(ch.get("name") or ch.get("title") or ""),
|
||||
"youtube_channel_id": str(ch.get("youtube_channel_id") or ""),
|
||||
"oauth_profile_id": str(ch.get("oauth_profile_id") or ""),
|
||||
"currency": "USD",
|
||||
"window": {"start": start_s, "end": end_s, "days": days_i},
|
||||
"totals": totals,
|
||||
"by_type": by_type,
|
||||
"daily": daily,
|
||||
"links": links,
|
||||
"type_error": type_error,
|
||||
"monetary_ok": True,
|
||||
"need_reauth": False,
|
||||
"fetched_at": now,
|
||||
}
|
||||
_CACHE[cache_key] = (now, out)
|
||||
return out
|
||||
|
||||
|
||||
def _product_links(*, youtube_channel_id: str, shorts_pk: str) -> dict[str, Any]:
|
||||
"""Map UC… / Shorts pk → Live 分配 / Shorts / 长视频 cards."""
|
||||
ucid = str(youtube_channel_id or "").strip()
|
||||
live_groups: list[dict[str, Any]] = []
|
||||
long_channels: list[dict[str, Any]] = []
|
||||
try:
|
||||
for g in yt_assign_db.list_groups(include_urls=False):
|
||||
gid = str(g.get("id") or "")
|
||||
g_uc = str(g.get("youtube_channel_id") or "").strip()
|
||||
g_pk = str(g.get("channel_pk") or "").strip()
|
||||
if (ucid and g_uc == ucid) or (shorts_pk and g_pk == shorts_pk):
|
||||
live_groups.append(
|
||||
{
|
||||
"group_id": gid,
|
||||
"name": str(g.get("name") or ""),
|
||||
"youtube_channel_id": g_uc,
|
||||
"href": f"/youtube?live=1&focus={gid}" if gid else "/youtube",
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from . import yt_long_db
|
||||
|
||||
for c in yt_long_db.list_yt_long_channels():
|
||||
c_uc = str(c.get("youtube_channel_id") or "").strip()
|
||||
src = str(c.get("source_shorts_channel_pk") or "").strip()
|
||||
if (ucid and c_uc == ucid) or (shorts_pk and src == shorts_pk):
|
||||
long_channels.append(
|
||||
{
|
||||
"id": str(c.get("id") or ""),
|
||||
"name": str(c.get("name") or ""),
|
||||
"youtube_channel_id": c_uc,
|
||||
"href": "/yt-long",
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
"live": live_groups,
|
||||
"shorts": {
|
||||
"channel_pk": shorts_pk,
|
||||
"href": f"/shorts?focus={shorts_pk}" if shorts_pk else "/shorts",
|
||||
},
|
||||
"long": long_channels,
|
||||
}
|
||||
|
||||
|
||||
async def fleet_revenue(*, days: int = 28, force: bool = False) -> dict[str, Any]:
|
||||
"""Aggregate revenue across all authorized Shorts channels."""
|
||||
days_i = max(1, min(90, int(days or 28)))
|
||||
channels = db.list_shorts_channels()
|
||||
rows: list[dict[str, Any]] = []
|
||||
fleet_totals = _empty_bucket()
|
||||
fleet_by_type = {
|
||||
"live": _empty_bucket(),
|
||||
"shorts": _empty_bucket(),
|
||||
"long": _empty_bucket(),
|
||||
"other": _empty_bucket(),
|
||||
}
|
||||
need_reauth = 0
|
||||
ok_n = 0
|
||||
for ch in channels:
|
||||
pk = str(ch.get("id") or "").strip()
|
||||
if not pk:
|
||||
continue
|
||||
if not str(ch.get("refresh_token") or "").strip():
|
||||
continue
|
||||
try:
|
||||
one = await fetch_channel_revenue(pk, days=days_i, force=force)
|
||||
except Exception as exc:
|
||||
one = {"ok": False, "channel_pk": pk, "error": str(exc)[:200], "need_reauth": True}
|
||||
rows.append(one)
|
||||
if one.get("need_reauth"):
|
||||
need_reauth += 1
|
||||
if not one.get("ok"):
|
||||
continue
|
||||
ok_n += 1
|
||||
_add_row(fleet_totals, one.get("totals") or {})
|
||||
bt = one.get("by_type") or {}
|
||||
for k in ("live", "shorts", "long", "other"):
|
||||
_add_row(fleet_by_type[k], bt.get(k) or {})
|
||||
|
||||
end = _beijing_today()
|
||||
start = end - timedelta(days=days_i - 1)
|
||||
return {
|
||||
"ok": True,
|
||||
"window": {"start": start.isoformat(), "end": end.isoformat(), "days": days_i},
|
||||
"currency": "USD",
|
||||
"totals": fleet_totals,
|
||||
"by_type": fleet_by_type,
|
||||
"channels": rows,
|
||||
"ok_count": ok_n,
|
||||
"need_reauth_count": need_reauth,
|
||||
"fetched_at": time.time(),
|
||||
}
|
||||
@ -161,6 +161,14 @@ def main() -> None:
|
||||
pass
|
||||
|
||||
lower = text.lower()
|
||||
# Chrome error / offline interstitial — never treat as Studio receiving.
|
||||
chrome_offline = bool(
|
||||
re.search(
|
||||
r"err_internet_disconnected|err_name_not_resolved|err_connection|"
|
||||
r"no internet|没有网络|无法访问此网站|aw,\s*snap",
|
||||
lower,
|
||||
)
|
||||
)
|
||||
nodata = bool(
|
||||
re.search(r"(?:^|[^a-z])no\s*data(?:[^a-z]|$)|nodata|无数据|尚未收到数据", lower)
|
||||
)
|
||||
@ -286,18 +294,36 @@ def main() -> None:
|
||||
status = "live"
|
||||
|
||||
# 开播 = session live + encoder has data. 断播 ≠ 开播 ≠ 待开播. Preparing ≠ 开播.
|
||||
on_air = bool(status == "live" and not nodata and not encoder_lost_hint and not preparing)
|
||||
encoder_lost = status == "encoder_lost" or (session_live and nodata)
|
||||
encoder_receiving = bool(
|
||||
not preparing
|
||||
on_air = bool(
|
||||
status == "live"
|
||||
and not nodata
|
||||
and not encoder_lost
|
||||
and (
|
||||
status == "live"
|
||||
or health
|
||||
or re.search(r"starting|receiving|connecting|正在接收|连接中", lower)
|
||||
and not encoder_lost_hint
|
||||
and not preparing
|
||||
and not chrome_offline
|
||||
)
|
||||
encoder_lost = status == "encoder_lost" or (session_live and nodata)
|
||||
# Do NOT match bare "connecting" — Chrome offline page says "Reconnecting to Wi-Fi".
|
||||
ingest_hint = bool(
|
||||
re.search(
|
||||
r"(?:^|[^a-z])(?:starting|receiving)(?:[^a-z]|$)|正在接收|编码器正在接收|"
|
||||
r"stream health|excellent connection|good connection",
|
||||
lower,
|
||||
)
|
||||
)
|
||||
encoder_receiving = bool(
|
||||
not chrome_offline
|
||||
and not preparing
|
||||
and not nodata
|
||||
and not encoder_lost
|
||||
and (status == "live" or health or ingest_hint)
|
||||
)
|
||||
if chrome_offline:
|
||||
status = "offline"
|
||||
control_ready = False
|
||||
on_air = False
|
||||
encoder_receiving = False
|
||||
encoder_lost = False
|
||||
session_live = False
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
@ -316,6 +342,7 @@ def main() -> None:
|
||||
"encoder_receiving": encoder_receiving,
|
||||
"encoder_lost": encoder_lost,
|
||||
"session_live": bool(session_live or status in {"live", "encoder_lost"}),
|
||||
"chrome_offline": chrome_offline,
|
||||
"text": text[:500],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
|
||||
@ -334,5 +334,5 @@ setInterval(() => {
|
||||
injectMemCss();
|
||||
tameMedia();
|
||||
sendTelemetry(false);
|
||||
}, 8000);
|
||||
}, 12000);
|
||||
sendTelemetry(true);
|
||||
|
||||
383
frontend/src/app/yt-revenue/page.tsx
Normal file
383
frontend/src/app/yt-revenue/page.tsx
Normal file
@ -0,0 +1,383 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import {
|
||||
Clapperboard,
|
||||
DollarSign,
|
||||
Link2,
|
||||
Loader2,
|
||||
Radio,
|
||||
RefreshCw,
|
||||
Smartphone,
|
||||
} from "lucide-react";
|
||||
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { OauthClientBadge, normalizeOauthProfileId } from "@/components/OauthClientBadge";
|
||||
import { fetchJson, fmtTs } from "@/lib/api";
|
||||
|
||||
type MoneyBucket = {
|
||||
estimated_revenue?: number;
|
||||
estimated_ad_revenue?: number;
|
||||
gross_revenue?: number;
|
||||
monetized_playbacks?: number;
|
||||
ad_impressions?: number;
|
||||
playback_based_cpm?: number | null;
|
||||
};
|
||||
|
||||
type ChannelRow = {
|
||||
ok?: boolean;
|
||||
channel_pk?: string;
|
||||
name?: string;
|
||||
youtube_channel_id?: string;
|
||||
oauth_profile_id?: string;
|
||||
error?: string;
|
||||
monetary_ok?: boolean;
|
||||
need_reauth?: boolean;
|
||||
totals?: MoneyBucket;
|
||||
by_type?: {
|
||||
live?: MoneyBucket;
|
||||
shorts?: MoneyBucket;
|
||||
long?: MoneyBucket;
|
||||
other?: MoneyBucket;
|
||||
};
|
||||
links?: {
|
||||
live?: Array<{ group_id?: string; name?: string; href?: string }>;
|
||||
shorts?: { channel_pk?: string; href?: string };
|
||||
long?: Array<{ id?: string; name?: string; href?: string }>;
|
||||
};
|
||||
window?: { start?: string; end?: string; days?: number };
|
||||
};
|
||||
|
||||
type Summary = {
|
||||
ok?: boolean;
|
||||
currency?: string;
|
||||
window?: { start?: string; end?: string; days?: number };
|
||||
totals?: MoneyBucket;
|
||||
by_type?: {
|
||||
live?: MoneyBucket;
|
||||
shorts?: MoneyBucket;
|
||||
long?: MoneyBucket;
|
||||
other?: MoneyBucket;
|
||||
};
|
||||
channels?: ChannelRow[];
|
||||
ok_count?: number;
|
||||
need_reauth_count?: number;
|
||||
fetched_at?: number;
|
||||
};
|
||||
|
||||
function fmtUsd(n: number | null | undefined): string {
|
||||
if (n == null || !Number.isFinite(Number(n))) return "—";
|
||||
const v = Number(n);
|
||||
return v.toLocaleString(undefined, {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
}
|
||||
|
||||
function TypeCard({
|
||||
title,
|
||||
emoji,
|
||||
href,
|
||||
bucket,
|
||||
links,
|
||||
}: {
|
||||
title: string;
|
||||
emoji: string;
|
||||
href: string;
|
||||
bucket?: MoneyBucket;
|
||||
links?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-white/10 bg-white/[0.04] p-4">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="text-xs uppercase tracking-wide text-slate-500">
|
||||
{emoji} {title}
|
||||
</div>
|
||||
<div className="mt-1 font-display text-2xl font-semibold text-emerald-100">
|
||||
{fmtUsd(bucket?.estimated_revenue)}
|
||||
</div>
|
||||
<div className="mt-1 text-[11px] text-slate-500">
|
||||
广告预估 {fmtUsd(bucket?.estimated_ad_revenue)} · 展示{" "}
|
||||
{Number(bucket?.ad_impressions || 0).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
<Link
|
||||
href={href}
|
||||
className="rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-300 hover:bg-white/10"
|
||||
>
|
||||
打开
|
||||
</Link>
|
||||
</div>
|
||||
{links ? <div className="mt-3 space-y-1 text-[11px] text-slate-400">{links}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function YtRevenuePage() {
|
||||
const [days, setDays] = useState(28);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [data, setData] = useState<Summary | null>(null);
|
||||
const [expanded, setExpanded] = useState<string>("");
|
||||
|
||||
const load = useCallback(
|
||||
async (force = false) => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const q = new URLSearchParams({ days: String(days), force: force ? "1" : "0" });
|
||||
const res = (await fetchJson(`/api/yt-revenue/summary?${q}`)) as Summary;
|
||||
setData(res);
|
||||
} catch (e: any) {
|
||||
setError(String(e?.message || e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[days]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void load(false);
|
||||
}, [load]);
|
||||
|
||||
const channels = useMemo(() => data?.channels || [], [data]);
|
||||
|
||||
function authHref(pk: string) {
|
||||
const ret = encodeURIComponent("/yt-revenue");
|
||||
return `/api/shorts/oauth/start?channel_pk=${encodeURIComponent(pk)}&monetary=1&return_to=${ret}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<Shell>
|
||||
<div className="relative mx-auto max-w-7xl px-3 pb-20 pt-4 md:px-6">
|
||||
<div className="pointer-events-none absolute inset-x-0 top-0 -z-10 h-[420px]">
|
||||
<div className="absolute left-8 top-8 h-64 w-64 rounded-full bg-emerald-500/15 blur-3xl" />
|
||||
<div className="absolute right-0 top-0 h-72 w-72 rounded-full bg-amber-500/10 blur-3xl" />
|
||||
</div>
|
||||
|
||||
<div className="mb-5 flex flex-wrap items-end justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="font-display text-3xl font-semibold tracking-tight text-white">
|
||||
💰 YouTube 收益
|
||||
</h1>
|
||||
<p className="mt-1 max-w-2xl text-sm text-slate-400">
|
||||
YouTube Analytics 预估 AdSense 收益,按直播 / Shorts / 长视频拆分,并关联本机分配频道与任务台。
|
||||
需频道补授权「Analytics 收益」权限(不影响上传)。
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<select
|
||||
value={days}
|
||||
onChange={(e) => setDays(Number(e.target.value))}
|
||||
className="rounded-lg border border-white/10 bg-black/40 px-2.5 py-1.5 text-sm text-slate-200"
|
||||
>
|
||||
<option value={7}>近 7 天</option>
|
||||
<option value={28}>近 28 天</option>
|
||||
<option value={90}>近 90 天</option>
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void load(true)}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-sm text-slate-200 hover:bg-white/10"
|
||||
>
|
||||
{loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<div className="mb-4 rounded-xl border border-rose-400/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-100">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div className="rounded-2xl border border-emerald-400/20 bg-emerald-500/10 p-4">
|
||||
<div className="flex items-center gap-2 text-xs text-emerald-200/80">
|
||||
<DollarSign className="h-3.5 w-3.5" /> 合计预估收益
|
||||
</div>
|
||||
<div className="mt-1 font-display text-3xl font-semibold text-emerald-50">
|
||||
{fmtUsd(data?.totals?.estimated_revenue)}
|
||||
</div>
|
||||
<div className="mt-1 text-[11px] text-emerald-100/60">
|
||||
{data?.window?.start || "—"} → {data?.window?.end || "—"} · {data?.currency || "USD"}
|
||||
</div>
|
||||
</div>
|
||||
<TypeCard title="直播 Live" emoji="▶️" href="/youtube" bucket={data?.by_type?.live} />
|
||||
<TypeCard title="Shorts" emoji="📱" href="/shorts" bucket={data?.by_type?.shorts} />
|
||||
<TypeCard title="长视频" emoji="🎞️" href="/yt-long" bucket={data?.by_type?.long} />
|
||||
</div>
|
||||
|
||||
<div className="mb-3 flex flex-wrap gap-3 text-xs text-slate-500">
|
||||
<span>已出数 {data?.ok_count ?? 0} 频道</span>
|
||||
<span>待补授权 {data?.need_reauth_count ?? 0}</span>
|
||||
{data?.fetched_at ? <span>拉取 {fmtTs(data.fetched_at)}</span> : null}
|
||||
</div>
|
||||
|
||||
{loading && !data ? (
|
||||
<div className="flex items-center gap-2 py-16 text-slate-400">
|
||||
<Loader2 className="h-4 w-4 animate-spin" /> 加载收益…
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{channels.length === 0 ? (
|
||||
<div className="rounded-2xl border border-dashed border-white/15 bg-white/[0.03] px-4 py-10 text-center text-sm text-slate-400">
|
||||
暂无已授权 Shorts 频道。请先在{" "}
|
||||
<Link href="/shorts" className="text-emerald-300 hover:underline">
|
||||
Shorts
|
||||
</Link>{" "}
|
||||
完成 Google 授权。
|
||||
</div>
|
||||
) : null}
|
||||
{channels.map((ch) => {
|
||||
const pk = String(ch.channel_pk || "");
|
||||
const open = expanded === pk;
|
||||
const liveLinks = ch.links?.live || [];
|
||||
const longLinks = ch.links?.long || [];
|
||||
return (
|
||||
<div
|
||||
key={pk || ch.name}
|
||||
className="rounded-2xl border border-white/10 bg-black/25 p-4"
|
||||
>
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h2 className="truncate text-base font-medium text-white">
|
||||
{ch.name || pk || "未命名频道"}
|
||||
</h2>
|
||||
{ch.oauth_profile_id ? (
|
||||
<OauthClientBadge profileId={normalizeOauthProfileId(ch.oauth_profile_id)} />
|
||||
) : null}
|
||||
{ch.ok ? (
|
||||
<span className="rounded-md bg-emerald-500/15 px-1.5 py-0.5 text-[10px] text-emerald-100 ring-1 ring-emerald-400/25">
|
||||
已出数
|
||||
</span>
|
||||
) : ch.need_reauth ? (
|
||||
<span className="rounded-md bg-amber-500/15 px-1.5 py-0.5 text-[10px] text-amber-100 ring-1 ring-amber-400/25">
|
||||
需授权收益
|
||||
</span>
|
||||
) : (
|
||||
<span className="rounded-md bg-rose-500/15 px-1.5 py-0.5 text-[10px] text-rose-100 ring-1 ring-rose-400/25">
|
||||
失败
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1 truncate text-[11px] text-slate-500">
|
||||
{ch.youtube_channel_id || "无 UC…"}
|
||||
{ch.error ? ` · ${ch.error}` : null}
|
||||
</div>
|
||||
{ch.ok ? (
|
||||
<div className="mt-2 grid gap-2 sm:grid-cols-4">
|
||||
<div className="rounded-lg bg-white/5 px-2.5 py-2">
|
||||
<div className="text-[10px] text-slate-500">合计</div>
|
||||
<div className="text-sm text-emerald-100">
|
||||
{fmtUsd(ch.totals?.estimated_revenue)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-lg bg-white/5 px-2.5 py-2">
|
||||
<div className="inline-flex items-center gap-1 text-[10px] text-slate-500">
|
||||
<Radio className="h-3 w-3" /> 直播
|
||||
</div>
|
||||
<div className="text-sm text-slate-100">
|
||||
{fmtUsd(ch.by_type?.live?.estimated_revenue)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-lg bg-white/5 px-2.5 py-2">
|
||||
<div className="inline-flex items-center gap-1 text-[10px] text-slate-500">
|
||||
<Smartphone className="h-3 w-3" /> Shorts
|
||||
</div>
|
||||
<div className="text-sm text-slate-100">
|
||||
{fmtUsd(ch.by_type?.shorts?.estimated_revenue)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-lg bg-white/5 px-2.5 py-2">
|
||||
<div className="inline-flex items-center gap-1 text-[10px] text-slate-500">
|
||||
<Clapperboard className="h-3 w-3" /> 长视频
|
||||
</div>
|
||||
<div className="text-sm text-slate-100">
|
||||
{fmtUsd(ch.by_type?.long?.estimated_revenue)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{ch.need_reauth && pk ? (
|
||||
<a
|
||||
href={authHref(pk)}
|
||||
className="rounded-lg border border-amber-400/30 bg-amber-500/15 px-3 py-1.5 text-xs text-amber-50 hover:bg-amber-500/25"
|
||||
>
|
||||
授权收益
|
||||
</a>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpanded(open ? "" : pk)}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-200 hover:bg-white/10"
|
||||
>
|
||||
<Link2 className="h-3 w-3" />
|
||||
{open ? "收起关联" : "关联业务"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{open ? (
|
||||
<div className="mt-3 grid gap-3 border-t border-white/10 pt-3 md:grid-cols-3">
|
||||
<div>
|
||||
<div className="mb-1 text-[11px] font-medium text-slate-400">直播 Live 分配</div>
|
||||
{liveLinks.length ? (
|
||||
liveLinks.map((g) => (
|
||||
<Link
|
||||
key={g.group_id || g.name}
|
||||
href={g.href || "/youtube"}
|
||||
className="mb-1 block truncate rounded-md bg-white/5 px-2 py-1.5 text-xs text-sky-100 hover:bg-white/10"
|
||||
>
|
||||
{g.name || g.group_id}
|
||||
</Link>
|
||||
))
|
||||
) : (
|
||||
<div className="text-[11px] text-slate-600">未绑定分配卡</div>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-1 text-[11px] font-medium text-slate-400">Shorts</div>
|
||||
<Link
|
||||
href={ch.links?.shorts?.href || "/shorts"}
|
||||
className="block truncate rounded-md bg-white/5 px-2 py-1.5 text-xs text-violet-100 hover:bg-white/10"
|
||||
>
|
||||
打开 Shorts 频道
|
||||
</Link>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-1 text-[11px] font-medium text-slate-400">长视频</div>
|
||||
{longLinks.length ? (
|
||||
longLinks.map((c) => (
|
||||
<Link
|
||||
key={c.id || c.name}
|
||||
href={c.href || "/yt-long"}
|
||||
className="mb-1 block truncate rounded-md bg-white/5 px-2 py-1.5 text-xs text-amber-100 hover:bg-white/10"
|
||||
>
|
||||
{c.name || c.id}
|
||||
</Link>
|
||||
))
|
||||
) : (
|
||||
<div className="text-[11px] text-slate-600">未关联长视频频道</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@ -30,6 +30,7 @@ export const LIVE_TABS: NavItem[] = [
|
||||
{ href: "/youtube", label: "直播Live", emoji: "▶️" },
|
||||
{ href: "/shorts", label: "Shorts", emoji: "📱" },
|
||||
{ href: "/yt-long", label: "长视频", emoji: "🎞️" },
|
||||
{ href: "/yt-revenue", label: "收益", emoji: "💰" },
|
||||
];
|
||||
|
||||
/** Sub-tabs under 运维(Neko 已升为一级导航) */
|
||||
@ -40,7 +41,14 @@ export const OPS_TABS: NavItem[] = [
|
||||
];
|
||||
|
||||
const OVERVIEW_PATHS = OVERVIEW_TABS.map((t) => t.href);
|
||||
const LIVE_PATHS = ["/youtube", "/shorts", "/yt-long", "/youtube-relay-log", "/youtube/health"];
|
||||
const LIVE_PATHS = [
|
||||
"/youtube",
|
||||
"/shorts",
|
||||
"/yt-long",
|
||||
"/yt-revenue",
|
||||
"/youtube-relay-log",
|
||||
"/youtube/health",
|
||||
];
|
||||
const OPS_PATHS = OPS_TABS.map((t) => t.href);
|
||||
|
||||
export type NavSection = "overview" | "live" | "ops";
|
||||
|
||||
272
scripts/_align_dy_to_dylive_harden.py
Normal file
272
scripts/_align_dy_to_dylive_harden.py
Normal file
@ -0,0 +1,272 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Align dy.nomadro.live (108 VPS) with stable dylive harden + clip CPU guard."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
JUMP = "107.173.30.245"
|
||||
DY = "108.174.50.68"
|
||||
PASS = "Xiao4669805"
|
||||
|
||||
FILES = [
|
||||
"backend/app/host_metrics.py",
|
||||
"backend/app/main.py",
|
||||
"backend/app/yt_long_pipeline.py",
|
||||
"backend/app/shorts_pipeline.py",
|
||||
"backend/app/tiktok_pipeline.py",
|
||||
"backend/app/x_clips_pipeline.py",
|
||||
"backend/app/procutil.py",
|
||||
"backend/app/youtube_relay.py",
|
||||
"backend/app/yt_long_clip.py",
|
||||
"backend/app/shorts_clip.py",
|
||||
"backend/app/clip_cascade.py",
|
||||
"scripts/linux/api_health_watch.sh",
|
||||
]
|
||||
|
||||
# Match dylive tightness but scaled for 8G (dylive=700/900 on 4G).
|
||||
OOM_CONF = """[Service]
|
||||
MemoryAccounting=yes
|
||||
# Python-only after ffmpeg is in douyinweb-ffmpeg.slice (dylive pattern).
|
||||
MemoryHigh=1100M
|
||||
MemoryMax=1500M
|
||||
MemorySwapMax=256M
|
||||
OOMPolicy=kill
|
||||
OOMScoreAdjust=400
|
||||
"""
|
||||
|
||||
OVERRIDE = """[Service]
|
||||
TimeoutStartSec=180
|
||||
TimeoutStopSec=15
|
||||
KillMode=control-group
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
"""
|
||||
|
||||
PUBLIC_BASE = """[Service]
|
||||
Environment=DY_PUBLIC_BASE_URL=https://dy.nomadro.live
|
||||
Environment=DY_INSTALL_SHAPE=vps
|
||||
Environment=DY_NEKO_HTTP_BIND=127.0.0.1
|
||||
"""
|
||||
|
||||
CPU_API = """[Service]
|
||||
Nice=5
|
||||
CPUWeight=100
|
||||
"""
|
||||
|
||||
CPU_WEB = """[Service]
|
||||
Nice=10
|
||||
CPUWeight=40
|
||||
"""
|
||||
|
||||
FFMPEG_SLICE = """[Unit]
|
||||
Description=douyinWEB ffmpeg memory slice (outside API cgroup)
|
||||
Before=douyinweb-api.service
|
||||
|
||||
[Slice]
|
||||
MemoryAccounting=yes
|
||||
MemoryHigh=1800M
|
||||
MemoryMax=2800M
|
||||
MemorySwapMax=512M
|
||||
CPUAccounting=yes
|
||||
# Cap encode so live+clip cannot pin all cores (4c host → leave ~2 for API/Neko).
|
||||
CPUQuota=200%
|
||||
CPUWeight=40
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
"""
|
||||
|
||||
API_WATCH = """[Unit]
|
||||
Description=douyinWEB API health hang watchdog
|
||||
After=network-online.target douyinweb-api.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Environment=DY_API_WATCH_INTERVAL=15
|
||||
Environment=DY_API_WATCH_FAILS=3
|
||||
Environment=DY_API_WATCH_COOLDOWN=90
|
||||
Environment=DY_API_WATCH_START_GRACE=90
|
||||
Environment=DY_API_WATCH_RECVQ_LIMIT=80
|
||||
ExecStart=/bin/bash /opt/douyinWEB/scripts/linux/api_health_watch.sh
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
"""
|
||||
|
||||
REMOTE = r'''
|
||||
set -e
|
||||
TS=$(date +%s)
|
||||
install -d -m 755 /opt/douyinWEB/scripts/linux
|
||||
install -d -m 755 /etc/systemd/system/douyinweb-api.service.d
|
||||
install -d -m 755 /etc/systemd/system/douyinweb-web.service.d
|
||||
|
||||
for f in host_metrics.py main.py yt_long_pipeline.py shorts_pipeline.py tiktok_pipeline.py x_clips_pipeline.py procutil.py youtube_relay.py yt_long_clip.py shorts_clip.py clip_cascade.py; do
|
||||
[ -f /tmp/_align_$f ] || continue
|
||||
cp -a /opt/douyinWEB/backend/app/$f /opt/douyinWEB/backend/app/${f}.bak-align-${TS} 2>/dev/null || true
|
||||
cp -a /tmp/_align_$f /opt/douyinWEB/backend/app/$f
|
||||
done
|
||||
install -m 755 /tmp/_align_api_health_watch.sh /opt/douyinWEB/scripts/linux/api_health_watch.sh
|
||||
install -m 644 /tmp/_align_ffmpeg.slice /etc/systemd/system/douyinweb-ffmpeg.slice
|
||||
install -m 644 /tmp/_align_api_watch.service /etc/systemd/system/douyinweb-api-watch.service
|
||||
install -m 644 /tmp/_align_oom.conf /etc/systemd/system/douyinweb-api.service.d/oom-protect-chrome.conf
|
||||
install -m 644 /tmp/_align_override.conf /etc/systemd/system/douyinweb-api.service.d/override.conf
|
||||
install -m 644 /tmp/_align_public.conf /etc/systemd/system/douyinweb-api.service.d/public-base.conf
|
||||
install -m 644 /tmp/_align_cpu_api.conf /etc/systemd/system/douyinweb-api.service.d/cpu.conf
|
||||
install -m 644 /tmp/_align_cpu_web.conf /etc/systemd/system/douyinweb-web.service.d/cpu.conf
|
||||
|
||||
cd /opt/douyinWEB/backend
|
||||
.venv/bin/python -m py_compile app/host_metrics.py app/main.py app/yt_long_pipeline.py app/shorts_pipeline.py app/tiktok_pipeline.py app/x_clips_pipeline.py
|
||||
echo COMPILE_OK
|
||||
grep -n "clip_encode_defer_reason\|Instant liveness" app/host_metrics.py app/main.py app/yt_long_pipeline.py | head -20
|
||||
|
||||
.venv/bin/python - <<'PY'
|
||||
from app import db
|
||||
patch = {
|
||||
"yt_long_max_concurrent": 1,
|
||||
"shorts_max_concurrent": 1,
|
||||
"shorts_upload_max_concurrent": 1,
|
||||
"tiktok_max_concurrent": 1,
|
||||
"x_clips_max_concurrent": 1,
|
||||
"youtube_relay_quality_preset": "vps_ultra",
|
||||
}
|
||||
out = db.update_settings_map(patch, audit_actor="align_dylive")
|
||||
print("settings", {k: (out or {}).get(k) for k in patch})
|
||||
PY
|
||||
|
||||
# If a clip encode is fighting live push right now, stop clip-only ffmpeg (keep rtmps youtube).
|
||||
echo "=== reclaim clip ffmpeg if live push ==="
|
||||
if pgrep -f 'ffmpeg.*rtmps?://.*(youtube|youtu)' >/dev/null 2>&1; then
|
||||
echo live_push_present
|
||||
# kill non-push encodes (mp4 output / clips paths) only
|
||||
pkill -9 -f 'ffmpeg.*(clips/yt_long|clips/shorts|/data/clips/)' 2>/dev/null || true
|
||||
fi
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable douyinweb-ffmpeg.slice douyinweb-api-watch.service
|
||||
systemctl start douyinweb-ffmpeg.slice
|
||||
systemctl restart douyinweb-api
|
||||
sleep 5
|
||||
for i in $(seq 1 25); do
|
||||
code=$(curl -sS -m 3 -o /dev/null -w "%{http_code}" http://127.0.0.1:8014/api/health || echo x)
|
||||
echo health_$i:$code
|
||||
[ "$code" = "200" ] && break
|
||||
sleep 2
|
||||
done
|
||||
systemctl restart douyinweb-api-watch
|
||||
sleep 1
|
||||
systemctl is-active douyinweb-api douyinweb-api-watch douyinweb-ffmpeg.slice douyinweb-web
|
||||
echo MEM: $(systemctl show douyinweb-api -p MemoryHigh,MemoryMax,MemoryCurrent --value | tr '\n' ' ')
|
||||
echo SLICE_CPU: $(systemctl show douyinweb-ffmpeg.slice -p CPUQuota --value)
|
||||
curl -sS -m 3 -o /dev/null -w "health_t=%{time_total} code=%{http_code}\n" http://127.0.0.1:8014/api/health
|
||||
uptime
|
||||
ps -eo pid,pcpu,cgroup:40,cmd | grep '[f]fmpeg' | head -8 || true
|
||||
echo DY_ALIGN_DONE
|
||||
'''
|
||||
|
||||
|
||||
def main() -> int:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(JUMP, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
for rel in FILES:
|
||||
name = Path(rel).name
|
||||
data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n")
|
||||
with sftp.file(f"/tmp/_align_{name}", "wb") as f:
|
||||
f.write(data)
|
||||
print("staged", name, len(data), flush=True)
|
||||
with sftp.file("/tmp/_align_oom.conf", "w") as f:
|
||||
f.write(OOM_CONF)
|
||||
with sftp.file("/tmp/_align_override.conf", "w") as f:
|
||||
f.write(OVERRIDE)
|
||||
with sftp.file("/tmp/_align_public.conf", "w") as f:
|
||||
f.write(PUBLIC_BASE)
|
||||
with sftp.file("/tmp/_align_cpu_api.conf", "w") as f:
|
||||
f.write(CPU_API)
|
||||
with sftp.file("/tmp/_align_cpu_web.conf", "w") as f:
|
||||
f.write(CPU_WEB)
|
||||
with sftp.file("/tmp/_align_ffmpeg.slice", "w") as f:
|
||||
f.write(FFMPEG_SLICE)
|
||||
with sftp.file("/tmp/_align_api_watch.service", "w") as f:
|
||||
f.write(API_WATCH)
|
||||
with sftp.file("/tmp/_align_remote.sh", "w") as f:
|
||||
f.write(REMOTE)
|
||||
sftp.close()
|
||||
|
||||
# Also ship same app code to dylive (parity; leave its MemoryHigh alone).
|
||||
print("=== dylive code parity ===", flush=True)
|
||||
_, o, e = c.exec_command(
|
||||
"cp -a /tmp/_align_host_metrics.py /opt/douyinWEB/backend/app/host_metrics.py; "
|
||||
"cp -a /tmp/_align_main.py /opt/douyinWEB/backend/app/main.py; "
|
||||
"cp -a /tmp/_align_yt_long_pipeline.py /opt/douyinWEB/backend/app/yt_long_pipeline.py; "
|
||||
"cp -a /tmp/_align_shorts_pipeline.py /opt/douyinWEB/backend/app/shorts_pipeline.py; "
|
||||
"cp -a /tmp/_align_tiktok_pipeline.py /opt/douyinWEB/backend/app/tiktok_pipeline.py; "
|
||||
"cp -a /tmp/_align_x_clips_pipeline.py /opt/douyinWEB/backend/app/x_clips_pipeline.py; "
|
||||
"cd /opt/douyinWEB/backend && .venv/bin/python -m py_compile "
|
||||
"app/host_metrics.py app/main.py app/yt_long_pipeline.py app/shorts_pipeline.py "
|
||||
"app/tiktok_pipeline.py app/x_clips_pipeline.py && "
|
||||
"systemctl restart douyinweb-api && "
|
||||
"for i in $(seq 1 15); do c=$(curl -sS -m 3 -o /dev/null -w %{http_code} "
|
||||
"http://127.0.0.1:8014/api/health || echo x); echo dylive:$c; [ \"$c\" = 200 ] && break; sleep 2; done",
|
||||
timeout=90,
|
||||
)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace")[-3000:], flush=True)
|
||||
|
||||
print("=== dy 108 deploy ===", flush=True)
|
||||
chan = c.get_transport().open_session()
|
||||
chan.exec_command(
|
||||
f"SSHPASS={PASS} sshpass -e scp -o StrictHostKeyChecking=no "
|
||||
"/tmp/_align_host_metrics.py /tmp/_align_main.py /tmp/_align_yt_long_pipeline.py "
|
||||
"/tmp/_align_shorts_pipeline.py /tmp/_align_tiktok_pipeline.py /tmp/_align_x_clips_pipeline.py "
|
||||
"/tmp/_align_procutil.py /tmp/_align_youtube_relay.py /tmp/_align_yt_long_clip.py "
|
||||
"/tmp/_align_shorts_clip.py /tmp/_align_clip_cascade.py /tmp/_align_api_health_watch.sh "
|
||||
"/tmp/_align_oom.conf /tmp/_align_override.conf /tmp/_align_public.conf "
|
||||
"/tmp/_align_cpu_api.conf /tmp/_align_cpu_web.conf /tmp/_align_ffmpeg.slice "
|
||||
"/tmp/_align_api_watch.service /tmp/_align_remote.sh "
|
||||
f"root@{DY}:/tmp/ && "
|
||||
f"SSHPASS={PASS} sshpass -e ssh -o StrictHostKeyChecking=no root@{DY} "
|
||||
"'bash /tmp/_align_remote.sh' > /tmp/_align_dy.out 2>&1; echo EXIT:$? >> /tmp/_align_dy.out"
|
||||
)
|
||||
out = ""
|
||||
for i in range(90):
|
||||
time.sleep(2)
|
||||
_, o2, _ = c.exec_command("tail -c 25000 /tmp/_align_dy.out 2>/dev/null", timeout=20)
|
||||
out = o2.read().decode("utf-8", "replace")
|
||||
if "EXIT:" in out:
|
||||
print(out[-12000:], flush=True)
|
||||
break
|
||||
if i % 5 == 0:
|
||||
print("poll", i, out[-160:].replace("\n", " | "), flush=True)
|
||||
else:
|
||||
print("TIMEOUT", out[-4000:], flush=True)
|
||||
c.close()
|
||||
return 1
|
||||
|
||||
print("=== public ===", flush=True)
|
||||
for url in (
|
||||
"https://dy.nomadro.live/api/health",
|
||||
"https://dylive.nomadro.com/api/health",
|
||||
"https://dy.nomadro.live/",
|
||||
):
|
||||
try:
|
||||
with httpx.Client(timeout=20, verify=False, follow_redirects=False) as h:
|
||||
r = h.get(url)
|
||||
print(url, r.status_code, f"t~{r.elapsed.total_seconds():.3f}", (r.text or "")[:100].replace("\n", " "), flush=True)
|
||||
except Exception as ex:
|
||||
print(url, "ERR", ex, flush=True)
|
||||
c.close()
|
||||
return 0 if "DY_ALIGN_DONE" in out and "EXIT:0" in out else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
221
scripts/_deploy_api_hang_harden.py
Normal file
221
scripts/_deploy_api_hang_harden.py
Normal file
@ -0,0 +1,221 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Deploy API hang harden: ffmpeg cgroup split + health watchdog + concurrency cap.
|
||||
|
||||
Physical dy (108.174.50.68) via VPS; also refresh dylive code for parity.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VPS = "107.173.30.245"
|
||||
DY = "108.174.50.68"
|
||||
PASS = "Xiao4669805"
|
||||
|
||||
FILES = [
|
||||
("backend/app/procutil.py", "_hang_procutil.py"),
|
||||
("backend/app/youtube_relay.py", "_hang_youtube_relay.py"),
|
||||
("backend/app/yt_long_clip.py", "_hang_yt_long_clip.py"),
|
||||
("backend/app/shorts_clip.py", "_hang_shorts_clip.py"),
|
||||
("backend/app/clip_cascade.py", "_hang_clip_cascade.py"),
|
||||
("scripts/linux/api_health_watch.sh", "_hang_api_health_watch.sh"),
|
||||
]
|
||||
|
||||
SLICE_UNIT = """[Unit]
|
||||
Description=douyinWEB ffmpeg memory slice (outside API cgroup)
|
||||
Before=douyinweb-api.service
|
||||
|
||||
[Slice]
|
||||
MemoryAccounting=yes
|
||||
MemoryHigh=1800M
|
||||
MemoryMax=2800M
|
||||
MemorySwapMax=512M
|
||||
CPUAccounting=yes
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
"""
|
||||
|
||||
API_WATCH_UNIT = """[Unit]
|
||||
Description=douyinWEB API health hang watchdog
|
||||
After=network-online.target douyinweb-api.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Environment=DY_API_WATCH_INTERVAL=20
|
||||
Environment=DY_API_WATCH_FAILS=3
|
||||
Environment=DY_API_WATCH_COOLDOWN=120
|
||||
Environment=DY_API_WATCH_START_GRACE=120
|
||||
Environment=DY_API_WATCH_RECVQ_LIMIT=120
|
||||
ExecStart=/bin/bash /opt/douyinWEB/scripts/linux/api_health_watch.sh
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
"""
|
||||
|
||||
OOM_CONF = """[Service]
|
||||
MemoryAccounting=yes
|
||||
# Python-only budget after ffmpeg moved to douyinweb-ffmpeg.slice.
|
||||
MemoryHigh=2200M
|
||||
MemoryMax=3000M
|
||||
MemorySwapMax=512M
|
||||
OOMPolicy=kill
|
||||
OOMScoreAdjust=400
|
||||
"""
|
||||
|
||||
PHYS_SH = r'''
|
||||
set -e
|
||||
TS=$(date +%s)
|
||||
install -d -m 755 /opt/douyinWEB/scripts/linux
|
||||
install -d -m 755 /etc/systemd/system/douyinweb-api.service.d
|
||||
|
||||
for f in youtube_relay.py yt_long_clip.py shorts_clip.py clip_cascade.py; do
|
||||
cp -a /opt/douyinWEB/backend/app/$f /opt/douyinWEB/backend/app/${f}.bak-hang-${TS} 2>/dev/null || true
|
||||
done
|
||||
cp -a /tmp/_hang_procutil.py /opt/douyinWEB/backend/app/procutil.py
|
||||
cp -a /tmp/_hang_youtube_relay.py /opt/douyinWEB/backend/app/youtube_relay.py
|
||||
cp -a /tmp/_hang_yt_long_clip.py /opt/douyinWEB/backend/app/yt_long_clip.py
|
||||
cp -a /tmp/_hang_shorts_clip.py /opt/douyinWEB/backend/app/shorts_clip.py
|
||||
cp -a /tmp/_hang_clip_cascade.py /opt/douyinWEB/backend/app/clip_cascade.py
|
||||
install -m 755 /tmp/_hang_api_health_watch.sh /opt/douyinWEB/scripts/linux/api_health_watch.sh
|
||||
install -m 644 /tmp/_hang_ffmpeg.slice /etc/systemd/system/douyinweb-ffmpeg.slice
|
||||
install -m 644 /tmp/_hang_api_watch.service /etc/systemd/system/douyinweb-api-watch.service
|
||||
install -m 644 /tmp/_hang_oom.conf /etc/systemd/system/douyinweb-api.service.d/oom-protect-chrome.conf
|
||||
|
||||
cd /opt/douyinWEB/backend
|
||||
.venv/bin/python -m py_compile app/procutil.py app/youtube_relay.py app/yt_long_clip.py app/shorts_clip.py app/clip_cascade.py
|
||||
echo COMPILE_OK
|
||||
|
||||
# Cap concurrent encode on this host (settings DB)
|
||||
.venv/bin/python - <<'PY'
|
||||
import sys
|
||||
sys.path.insert(0, "/opt/douyinWEB/backend")
|
||||
from app import db
|
||||
patch = {
|
||||
"yt_long_max_concurrent": 1,
|
||||
"shorts_max_concurrent": 1,
|
||||
"shorts_upload_max_concurrent": 1,
|
||||
"tiktok_max_concurrent": 1,
|
||||
"x_clips_max_concurrent": 1,
|
||||
}
|
||||
out = db.update_settings_map(patch, audit_actor="hang_harden")
|
||||
print("settings_ok", {k: (out or {}).get(k) for k in patch})
|
||||
PY
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable douyinweb-ffmpeg.slice douyinweb-api-watch.service
|
||||
systemctl start douyinweb-ffmpeg.slice
|
||||
systemctl restart douyinweb-api
|
||||
sleep 4
|
||||
for i in $(seq 1 20); do
|
||||
code=$(curl -sS -m 4 -o /dev/null -w "%{http_code}" http://127.0.0.1:8014/api/health || echo x)
|
||||
echo health:$code
|
||||
[ "$code" = "200" ] && break
|
||||
sleep 2
|
||||
done
|
||||
systemctl restart douyinweb-api-watch
|
||||
sleep 2
|
||||
systemctl is-active douyinweb-api douyinweb-api-watch douyinweb-ffmpeg.slice
|
||||
systemctl show douyinweb-api -p MemoryHigh,MemoryMax,MemoryCurrent --value | tr '\n' ' '; echo
|
||||
ls -la /sys/fs/cgroup/system.slice/douyinweb-ffmpeg.slice/cgroup.procs 2>/dev/null || echo NO_CGROUP_PROCS
|
||||
# if a relay ffmpeg is running, show its cgroup
|
||||
ff=$(pgrep -n -f 'ffmpeg.*rtmps://' || true)
|
||||
if [ -n "$ff" ]; then
|
||||
echo ffmpeg_pid=$ff
|
||||
cat /proc/$ff/cgroup 2>/dev/null | head -5
|
||||
fi
|
||||
echo PHYS_DONE
|
||||
'''
|
||||
|
||||
|
||||
def main() -> int:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(VPS, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False)
|
||||
|
||||
sftp = c.open_sftp()
|
||||
for rel, tmp in FILES:
|
||||
data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n")
|
||||
with sftp.file(f"/tmp/{tmp}", "wb") as f:
|
||||
f.write(data)
|
||||
print("staged", tmp, len(data), flush=True)
|
||||
with sftp.file("/tmp/_hang_ffmpeg.slice", "w") as f:
|
||||
f.write(SLICE_UNIT)
|
||||
with sftp.file("/tmp/_hang_api_watch.service", "w") as f:
|
||||
f.write(API_WATCH_UNIT)
|
||||
with sftp.file("/tmp/_hang_oom.conf", "w") as f:
|
||||
f.write(OOM_CONF)
|
||||
with sftp.file("/tmp/_hang_phys.sh", "w") as f:
|
||||
f.write(PHYS_SH)
|
||||
sftp.close()
|
||||
|
||||
# Also refresh dylive code (no MemoryHigh change required there as much)
|
||||
print("=== dylive code parity ===", flush=True)
|
||||
_, o, e = c.exec_command(
|
||||
"cp -a /tmp/_hang_procutil.py /opt/douyinWEB/backend/app/procutil.py; "
|
||||
"cp -a /tmp/_hang_youtube_relay.py /opt/douyinWEB/backend/app/youtube_relay.py; "
|
||||
"cp -a /tmp/_hang_yt_long_clip.py /opt/douyinWEB/backend/app/yt_long_clip.py; "
|
||||
"cp -a /tmp/_hang_shorts_clip.py /opt/douyinWEB/backend/app/shorts_clip.py; "
|
||||
"cp -a /tmp/_hang_clip_cascade.py /opt/douyinWEB/backend/app/clip_cascade.py; "
|
||||
"install -D -m 755 /tmp/_hang_api_health_watch.sh /opt/douyinWEB/scripts/linux/api_health_watch.sh; "
|
||||
"install -m 644 /tmp/_hang_ffmpeg.slice /etc/systemd/system/douyinweb-ffmpeg.slice; "
|
||||
"install -m 644 /tmp/_hang_api_watch.service /etc/systemd/system/douyinweb-api-watch.service; "
|
||||
"systemctl daemon-reload; systemctl enable --now douyinweb-ffmpeg.slice douyinweb-api-watch.service; "
|
||||
"systemctl restart douyinweb-api; "
|
||||
"for i in $(seq 1 15); do c=$(curl -sS -m 3 -o /dev/null -w %{http_code} http://127.0.0.1:8014/api/health || echo x); "
|
||||
"echo dylive_health:$c; [ \"$c\" = 200 ] && break; sleep 2; done; "
|
||||
"systemctl is-active douyinweb-api douyinweb-api-watch",
|
||||
timeout=120,
|
||||
)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace")[-4000:], flush=True)
|
||||
|
||||
print("=== physical deploy ===", flush=True)
|
||||
chan = c.get_transport().open_session()
|
||||
chan.exec_command(
|
||||
f"SSHPASS={PASS} sshpass -e scp -o StrictHostKeyChecking=no "
|
||||
f"/tmp/_hang_procutil.py /tmp/_hang_youtube_relay.py /tmp/_hang_yt_long_clip.py "
|
||||
f"/tmp/_hang_shorts_clip.py /tmp/_hang_clip_cascade.py /tmp/_hang_api_health_watch.sh "
|
||||
f"/tmp/_hang_ffmpeg.slice /tmp/_hang_api_watch.service /tmp/_hang_oom.conf /tmp/_hang_phys.sh "
|
||||
f"root@{DY}:/tmp/ && "
|
||||
f"SSHPASS={PASS} sshpass -e ssh -o StrictHostKeyChecking=no root@{DY} "
|
||||
f"'bash /tmp/_hang_phys.sh' > /tmp/_hang_phys.out 2>&1; echo EXIT:$? >> /tmp/_hang_phys.out"
|
||||
)
|
||||
out = ""
|
||||
for i in range(90):
|
||||
time.sleep(2)
|
||||
_, o2, _ = c.exec_command("tail -c 25000 /tmp/_hang_phys.out 2>/dev/null", timeout=20)
|
||||
out = o2.read().decode("utf-8", "replace")
|
||||
if "EXIT:" in out:
|
||||
print(out[-14000:], flush=True)
|
||||
break
|
||||
if i % 5 == 0:
|
||||
print("poll", i, out[-180:].replace("\n", " | "), flush=True)
|
||||
else:
|
||||
print("TIMEOUT", out[-5000:], flush=True)
|
||||
c.close()
|
||||
return 1
|
||||
|
||||
print("=== public ===", flush=True)
|
||||
for url in ("https://dy.nomadro.live/api/health", "https://dylive.nomadro.com/api/health"):
|
||||
try:
|
||||
with httpx.Client(timeout=20, verify=False) as h:
|
||||
r = h.get(url)
|
||||
print(url, r.status_code, r.text[:120], flush=True)
|
||||
except Exception as ex:
|
||||
print(url, "ERR", ex, flush=True)
|
||||
c.close()
|
||||
return 0 if "PHYS_DONE" in out and "EXIT:0" in out else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
136
scripts/_deploy_yt_revenue.py
Normal file
136
scripts/_deploy_yt_revenue.py
Normal file
@ -0,0 +1,136 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Deploy yt-revenue tab + API to dy + dylive."""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
JUMP = "107.173.30.245"
|
||||
DY = "108.174.50.68"
|
||||
PASS = "Xiao4669805"
|
||||
|
||||
BACKEND = [
|
||||
"backend/app/yt_revenue.py",
|
||||
"backend/app/shorts_oauth.py",
|
||||
"backend/app/main.py",
|
||||
]
|
||||
FRONTEND = [
|
||||
"frontend/src/lib/shellNav.ts",
|
||||
"frontend/src/app/yt-revenue/page.tsx",
|
||||
]
|
||||
|
||||
|
||||
def put_files(sftp, remote_prefix: str = "/tmp") -> None:
|
||||
for rel in BACKEND + FRONTEND:
|
||||
data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n")
|
||||
name = Path(rel).name
|
||||
# disambiguate page.tsx
|
||||
if rel.endswith("yt-revenue/page.tsx"):
|
||||
name = "yt_revenue_page.tsx"
|
||||
with sftp.file(f"{remote_prefix}/_rev_{name}", "wb") as f:
|
||||
f.write(data)
|
||||
|
||||
|
||||
REMOTE_DY = r'''
|
||||
set -e
|
||||
cp -a /tmp/_rev_yt_revenue.py /opt/douyinWEB/backend/app/yt_revenue.py
|
||||
cp -a /tmp/_rev_shorts_oauth.py /opt/douyinWEB/backend/app/shorts_oauth.py
|
||||
cp -a /tmp/_rev_main.py /opt/douyinWEB/backend/app/main.py
|
||||
mkdir -p /opt/douyinWEB/frontend/src/app/yt-revenue
|
||||
cp -a /tmp/_rev_shellNav.ts /opt/douyinWEB/frontend/src/lib/shellNav.ts
|
||||
cp -a /tmp/_rev_yt_revenue_page.tsx /opt/douyinWEB/frontend/src/app/yt-revenue/page.tsx
|
||||
systemctl restart douyinweb-api
|
||||
for i in $(seq 1 20); do
|
||||
c=$(curl -sS -m 3 -o /dev/null -w "%{http_code}" http://127.0.0.1:8014/api/health || echo x)
|
||||
echo health:$c
|
||||
[ "$c" = "200" ] && break
|
||||
sleep 2
|
||||
done
|
||||
# rebuild next if script exists
|
||||
if [ -x /opt/douyinWEB/frontend/node_modules/.bin/next ] || [ -f /opt/douyinWEB/frontend/package.json ]; then
|
||||
cd /opt/douyinWEB/frontend
|
||||
if systemctl list-unit-files | grep -q douyinweb-web; then
|
||||
npm run build >/tmp/_yt_rev_fe_build.log 2>&1 || true
|
||||
systemctl restart douyinweb-web || true
|
||||
elif systemctl list-unit-files | grep -q douyinweb-next; then
|
||||
npm run build >/tmp/_yt_rev_fe_build.log 2>&1 || true
|
||||
systemctl restart douyinweb-next || true
|
||||
else
|
||||
# try pm2 / generic
|
||||
npm run build >/tmp/_yt_rev_fe_build.log 2>&1 || true
|
||||
systemctl restart douyinweb-frontend 2>/dev/null || true
|
||||
fi
|
||||
tail -5 /tmp/_yt_rev_fe_build.log 2>/dev/null || true
|
||||
fi
|
||||
curl -sk -m 8 -o /dev/null -w "pub_api:%{http_code}\n" https://dy.nomadro.live/api/health
|
||||
curl -sk -m 8 -o /dev/null -w "rev_page:%{http_code}\n" https://dy.nomadro.live/yt-revenue
|
||||
curl -sS -m 20 "http://127.0.0.1:8014/api/yt-revenue/summary?days=7" | head -c 400; echo
|
||||
echo DONE
|
||||
'''
|
||||
|
||||
|
||||
def main() -> int:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(JUMP, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
put_files(sftp)
|
||||
with sftp.file("/tmp/_rev_dy.sh", "w") as f:
|
||||
f.write(REMOTE_DY)
|
||||
sftp.close()
|
||||
|
||||
print("===== dy =====", flush=True)
|
||||
chan = c.get_transport().open_session()
|
||||
chan.exec_command(
|
||||
f"SSHPASS={PASS} sshpass -e scp -o StrictHostKeyChecking=no "
|
||||
"/tmp/_rev_yt_revenue.py /tmp/_rev_shorts_oauth.py /tmp/_rev_main.py "
|
||||
"/tmp/_rev_shellNav.ts /tmp/_rev_yt_revenue_page.tsx /tmp/_rev_dy.sh "
|
||||
f"root@{DY}:/tmp/; "
|
||||
f"SSHPASS={PASS} sshpass -e ssh -o StrictHostKeyChecking=no root@{DY} "
|
||||
"'bash /tmp/_rev_dy.sh > /tmp/_rev_dy.out 2>&1; echo EXIT:$? >> /tmp/_rev_dy.out'"
|
||||
)
|
||||
out = ""
|
||||
for i in range(180):
|
||||
time.sleep(3)
|
||||
_, o, _ = c.exec_command(
|
||||
f"SSHPASS={PASS} sshpass -e ssh -o StrictHostKeyChecking=no root@{DY} "
|
||||
"'tail -c 20000 /tmp/_rev_dy.out 2>/dev/null'",
|
||||
timeout=25,
|
||||
)
|
||||
out = o.read().decode("utf-8", "replace")
|
||||
if "DONE" in out or "EXIT:" in out:
|
||||
print(out[-8000:])
|
||||
break
|
||||
if i % 5 == 0:
|
||||
print("poll", i, out[-140:].replace("\n", " | "), flush=True)
|
||||
else:
|
||||
print("TIMEOUT\n", out[-5000:])
|
||||
|
||||
print("===== dylive =====", flush=True)
|
||||
_, o, e = c.exec_command(
|
||||
"cp -a /tmp/_rev_yt_revenue.py /opt/douyinWEB/backend/app/yt_revenue.py; "
|
||||
"cp -a /tmp/_rev_shorts_oauth.py /opt/douyinWEB/backend/app/shorts_oauth.py; "
|
||||
"cp -a /tmp/_rev_main.py /opt/douyinWEB/backend/app/main.py; "
|
||||
"mkdir -p /opt/douyinWEB/frontend/src/app/yt-revenue; "
|
||||
"cp -a /tmp/_rev_shellNav.ts /opt/douyinWEB/frontend/src/lib/shellNav.ts; "
|
||||
"cp -a /tmp/_rev_yt_revenue_page.tsx /opt/douyinWEB/frontend/src/app/yt-revenue/page.tsx; "
|
||||
"systemctl restart douyinweb-api; "
|
||||
"for i in 1 2 3 4 5 6 7 8 9 10 12 14 16; do "
|
||||
"c=$(curl -sS -m 3 -o /dev/null -w %{http_code} http://127.0.0.1:8014/api/health || echo x); "
|
||||
"echo health:$c; [ \"$c\" = 200 ] && break; sleep 2; done; "
|
||||
"cd /opt/douyinWEB/frontend && npm run build >/tmp/_yt_rev_fe_build.log 2>&1 || true; "
|
||||
"systemctl restart douyinweb-web 2>/dev/null || systemctl restart douyinweb-next 2>/dev/null || true; "
|
||||
"tail -3 /tmp/_yt_rev_fe_build.log; "
|
||||
"curl -sS -m 20 'http://127.0.0.1:8014/api/yt-revenue/summary?days=7' | head -c 300; echo",
|
||||
timeout=600,
|
||||
)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace")[-6000:])
|
||||
c.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Loading…
Reference in New Issue
Block a user