douyinWEB/backend/app/ops_alerts.py
hackrobot 1e8eb0130a Sync dylive production working tree to test3.
Include latest server fixes for yt-long/disk/ops and related frontend.
Exclude .bak scratch files.
2026-10-14 07:04:18 +00:00

147 lines
4.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

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

# -*- coding: utf-8 -*-
"""Disk / quota / backlog alerts — off by default, cooldown dedupe."""
from __future__ import annotations
import time
from typing import Any
_last_fired: dict[str, float] = {}
def _cooldown_ok(key: str, cooldown_sec: float) -> bool:
now = time.time()
last = _last_fired.get(key, 0.0)
if now - last < max(300.0, cooldown_sec):
return False
_last_fired[key] = now
return True
async def _fire(event: str, message: str, extra: dict[str, Any] | None = None) -> None:
from .notify import send_webhook
payload = {"message": message, **(extra or {})}
await send_webhook(event, payload)
def collect_metrics() -> dict[str, Any]:
from . import db
from .clip_retention import disk_free_gb
from . import shorts_yt_quota
from . import yt_long_db
from . import tiktok_db
cfg = db.get_settings_map()
out: dict[str, Any] = {"ts": time.time()}
out["disk_free_gb"] = round(disk_free_gb(), 2)
try:
out["shorts_quota_gap"] = shorts_yt_quota.upload_gap(cfg=cfg)
except Exception:
out["shorts_quota_gap"] = -1
try:
out["yt_long_upload_gap"] = yt_long_db.yt_long_upload_gap(cfg=cfg)
except Exception:
out["yt_long_upload_gap"] = -1
try:
out["tiktok_daily_gap"] = tiktok_db.tiktok_total_quota_gap()
except Exception:
out["tiktok_daily_gap"] = -1
backlog = 0
for fn, st in (
(db.list_shorts_jobs, "failed"),
(tiktok_db.list_tiktok_jobs, "failed"),
):
try:
data = fn(status=st, limit=200, offset=0)
backlog += len(data.get("items") or [])
except Exception:
pass
out["failed_jobs"] = backlog
return out
async def check_and_alert() -> dict[str, Any]:
from . import db
cfg = db.get_settings_map()
if not cfg.get("ops_alerts_enabled", False):
return {"skipped": True}
try:
cooldown = float(cfg.get("ops_alert_cooldown_sec") or 3600)
except Exception:
cooldown = 3600.0
metrics = collect_metrics()
fired: list[str] = []
if cfg.get("ops_alert_disk_enabled", True):
try:
min_free = float(cfg.get("clips_min_free_gb") or 12)
except Exception:
min_free = 12.0
free = float(metrics.get("disk_free_gb") or 0)
if free < min_free and _cooldown_ok("ops_disk", cooldown):
await _fire(
"ops_disk",
f"磁盘空间不足:剩余 {free:.1f} GB(阈值 {min_free:.0f} GB)",
{"disk_free_gb": free, "threshold_gb": min_free},
)
fired.append("ops_disk")
if cfg.get("ops_alert_quota_enabled", False):
gaps = [
("shorts", metrics.get("shorts_quota_gap"), 0),
("yt_long", metrics.get("yt_long_upload_gap"), 0),
("tiktok", metrics.get("tiktok_daily_gap"), 0),
]
low = [f"{p}={g}" for p, g, th in gaps if isinstance(g, int) and g <= th]
if low and _cooldown_ok("ops_quota", cooldown):
await _fire(
"ops_quota",
f"上传配额已满或不足:{', '.join(low)}",
{"gaps": dict(gaps)},
)
fired.append("ops_quota")
try:
max_fail = int(cfg.get("ops_alert_failed_jobs_threshold") or 50)
except Exception:
max_fail = 50
failed = int(metrics.get("failed_jobs") or 0)
if failed >= max_fail and _cooldown_ok("ops_backlog", cooldown):
await _fire(
"ops_backlog",
f"失败任务积压:{failed} 条(阈值 {max_fail})",
{"failed_jobs": failed},
)
fired.append("ops_backlog")
return {"ok": True, "fired": fired, "metrics": metrics}
async def alert_loop() -> None:
import asyncio
from . import db
await asyncio.sleep(120)
while True:
try:
cfg = db.get_settings_map()
# Always reclaim under pressure (alert webhook remains optional).
try:
from .disk_guard import reclaim_once
reclaim_once(cfg)
except Exception:
pass
if cfg.get("ops_alerts_enabled", False):
await check_and_alert()
try:
interval = float(cfg.get("ops_alert_interval_sec") or 900)
except Exception:
interval = 900.0
await asyncio.sleep(max(300.0, interval))
except asyncio.CancelledError:
raise
except Exception:
await asyncio.sleep(600)