Include latest server fixes for yt-long/disk/ops and related frontend. Exclude .bak scratch files.
190 lines
5.9 KiB
Python
190 lines
5.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Proactive disk guard — reclaim before the box wedges API/Caddy.
|
|
|
|
Runs independently of webhook alerts. Safe defaults for ~60GB VPS.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import shutil
|
|
import time
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
|
|
def _free_gb(path: str | Path | None = None) -> float:
|
|
from .config import settings
|
|
|
|
try:
|
|
usage = shutil.disk_usage(str(path or settings.data_dir))
|
|
return float(usage.free) / (1024.0 ** 3)
|
|
except Exception:
|
|
return 999.0
|
|
|
|
|
|
def _used_pct(path: str | Path | None = None) -> float:
|
|
from .config import settings
|
|
|
|
try:
|
|
usage = shutil.disk_usage(str(path or settings.data_dir))
|
|
if usage.total <= 0:
|
|
return 0.0
|
|
return 100.0 * float(usage.used) / float(usage.total)
|
|
except Exception:
|
|
return 0.0
|
|
|
|
|
|
def reclaim_once(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
"""Purge clips + trim backups when disk is tight. Idempotent."""
|
|
from . import db
|
|
from .clip_retention import purge_stale_clips
|
|
from .db_backup import prune_backups, prune_legacy_db_copies
|
|
|
|
settings_map = cfg if cfg is not None else db.get_settings_map()
|
|
try:
|
|
min_free = float(settings_map.get("clips_min_free_gb") or 8)
|
|
except Exception:
|
|
min_free = 8.0
|
|
min_free = max(4.0, min(40.0, min_free))
|
|
try:
|
|
panic_pct = float(settings_map.get("disk_panic_used_pct") or 90)
|
|
except Exception:
|
|
panic_pct = 90.0
|
|
try:
|
|
keep_days = float(settings_map.get("db_backup_keep_days") or 3)
|
|
except Exception:
|
|
keep_days = 3.0
|
|
try:
|
|
keep_max = int(settings_map.get("db_backup_keep_max") or 3)
|
|
except Exception:
|
|
keep_max = 3
|
|
|
|
free_before = _free_gb()
|
|
used_before = _used_pct()
|
|
actions: list[str] = []
|
|
|
|
# Always keep backup pile small (cheap).
|
|
try:
|
|
pr = prune_backups(keep_days=keep_days, keep_max=keep_max)
|
|
if pr.get("removed"):
|
|
actions.append(f"prune_backups:{pr.get('removed')}")
|
|
lg = prune_legacy_db_copies(keep_max=2)
|
|
if lg.get("removed"):
|
|
actions.append(f"prune_legacy:{lg.get('removed')}")
|
|
except Exception as exc:
|
|
actions.append(f"prune_err:{exc}"[:80])
|
|
|
|
under = free_before < min_free or used_before >= panic_pct
|
|
purge_result: dict[str, Any] = {}
|
|
if under:
|
|
# Temporarily tighten max age so purge_stale_clips reclaims faster.
|
|
tight = dict(settings_map)
|
|
try:
|
|
age = float(tight.get("clips_max_age_hours") or 24)
|
|
except Exception:
|
|
age = 24.0
|
|
tight["clips_max_age_hours"] = min(age, 6.0 if used_before >= panic_pct else 12.0)
|
|
tight["clips_min_free_gb"] = min_free
|
|
try:
|
|
purge_result = purge_stale_clips(tight)
|
|
actions.append(f"purge_clips:del={purge_result.get('deleted')}")
|
|
except Exception as exc:
|
|
actions.append(f"purge_err:{exc}"[:80])
|
|
|
|
# Extreme: drop oldest non-inflight mp4 > 2h if still panic.
|
|
if _used_pct() >= panic_pct or _free_gb() < max(3.0, min_free * 0.5):
|
|
dropped = _drop_old_mp4(max_age_h=2.0, limit=40)
|
|
if dropped:
|
|
actions.append(f"drop_mp4:{dropped}")
|
|
|
|
free_after = _free_gb()
|
|
used_after = _used_pct()
|
|
out = {
|
|
"ok": True,
|
|
"under_pressure": under,
|
|
"free_gb_before": round(free_before, 2),
|
|
"free_gb_after": round(free_after, 2),
|
|
"used_pct_before": round(used_before, 1),
|
|
"used_pct_after": round(used_after, 1),
|
|
"min_free_gb": min_free,
|
|
"actions": actions,
|
|
"purge": purge_result,
|
|
}
|
|
if under and (free_after - free_before) > 0.05:
|
|
try:
|
|
db.add_event(
|
|
kind="disk_guard",
|
|
level="warn",
|
|
message=f"磁盘守护回收:{free_before:.1f}→{free_after:.1f} GB",
|
|
meta=out,
|
|
)
|
|
except Exception:
|
|
pass
|
|
return out
|
|
|
|
|
|
def _drop_old_mp4(*, max_age_h: float, limit: int) -> int:
|
|
from .clip_retention import _job_still_needs_file, unlink_clip
|
|
from .config import settings
|
|
|
|
root = Path(settings.clips_dir)
|
|
if not root.is_dir():
|
|
return 0
|
|
now = time.time()
|
|
cands: list[tuple[float, Path]] = []
|
|
for p in root.rglob("*.mp4"):
|
|
try:
|
|
if not p.is_file():
|
|
continue
|
|
age = now - p.stat().st_mtime
|
|
if age < max_age_h * 3600.0:
|
|
continue
|
|
variants = {str(p)}
|
|
try:
|
|
variants.add(str(p.resolve()))
|
|
except OSError:
|
|
pass
|
|
if any(_job_still_needs_file(sp) for sp in variants):
|
|
continue
|
|
cands.append((age, p))
|
|
except OSError:
|
|
continue
|
|
cands.sort(key=lambda x: x[0], reverse=True)
|
|
n = 0
|
|
for _age, p in cands[: max(1, limit)]:
|
|
if unlink_clip(str(p), clear_refs=True):
|
|
n += 1
|
|
return n
|
|
|
|
|
|
async def disk_guard_loop() -> None:
|
|
import asyncio
|
|
|
|
from . import db
|
|
|
|
await asyncio.sleep(45)
|
|
while True:
|
|
try:
|
|
cfg = db.get_settings_map()
|
|
# Allow kill-switch
|
|
if cfg.get("disk_guard_enabled", True) is False:
|
|
await asyncio.sleep(300)
|
|
continue
|
|
reclaim_once(cfg)
|
|
try:
|
|
interval = float(cfg.get("disk_guard_interval_sec") or 300)
|
|
except Exception:
|
|
interval = 300.0
|
|
# Faster poll when already tight
|
|
free = _free_gb()
|
|
try:
|
|
min_free = float(cfg.get("clips_min_free_gb") or 8)
|
|
except Exception:
|
|
min_free = 8.0
|
|
if free < min_free or _used_pct() >= 90:
|
|
interval = min(interval, 120.0)
|
|
await asyncio.sleep(max(60.0, interval))
|
|
except asyncio.CancelledError:
|
|
raise
|
|
except Exception:
|
|
await asyncio.sleep(180)
|