完善脚本
This commit is contained in:
1 parent
9d9509a26b
commit
0c740f5a53
9 files changed
+1176
-212
No files matched your search
+185
-1
@@ -8,6 +8,7 @@ import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timezone
|
||||
from functools import wraps
|
||||
@@ -33,6 +34,7 @@ from maintain.cpa_runner_core import (
|
||||
runner_config_from_db,
|
||||
save_state,
|
||||
)
|
||||
import cliproxy_auth_sweeper as cliproxy_sweeper
|
||||
|
||||
_plog = logging.getLogger("cpa-runner")
|
||||
if not _plog.handlers:
|
||||
@@ -246,6 +248,15 @@ def api_overview():
|
||||
"cliproxy_probe_timeout_sec": settings.get(
|
||||
"cliproxy_probe_timeout_sec", "30"
|
||||
),
|
||||
"cliproxy_sweeper_threshold": settings.get(
|
||||
"cliproxy_sweeper_threshold", "3"
|
||||
),
|
||||
"cliproxy_sweeper_run_mode": settings.get(
|
||||
"cliproxy_sweeper_run_mode", "delete"
|
||||
),
|
||||
"cliproxy_sweeper_allow_name_fallback": settings.get(
|
||||
"cliproxy_sweeper_allow_name_fallback", "1"
|
||||
),
|
||||
"codex_stats_oauth_dir": settings.get("codex_stats_oauth_dir", ""),
|
||||
},
|
||||
}
|
||||
@@ -478,6 +489,27 @@ def _run_cliproxy_inspect_worker(task_id: int, source: str) -> None:
|
||||
message=f"管理端不可用或密钥无效(未删任何文件): {mgmt_err}",
|
||||
)
|
||||
return
|
||||
|
||||
# 巡检前先跑一次 usage 阈值失效清理,保证“巡检=检查+清理”。
|
||||
try:
|
||||
sweep = _run_cliproxy_sweeper_worker(
|
||||
task_id,
|
||||
f"{source} usage清理",
|
||||
finalize_task=False,
|
||||
)
|
||||
rtlog().info(
|
||||
"[inspect#%s] %s usage清理完成 threshold=%s matched=%s deleted=%s failed=%s mode=%s",
|
||||
task_id,
|
||||
source,
|
||||
sweep.get("threshold"),
|
||||
sweep.get("matched"),
|
||||
sweep.get("deleted"),
|
||||
sweep.get("failed"),
|
||||
sweep.get("mode"),
|
||||
)
|
||||
except Exception as e:
|
||||
rtlog().warning("[inspect#%s] %s usage清理异常,继续探测流程: %s", task_id, source, e)
|
||||
|
||||
entries = db.list_oauth_codex_entries()
|
||||
total = len(entries)
|
||||
rtlog().info(
|
||||
@@ -585,6 +617,137 @@ def _start_inspect_job(source: str) -> tuple[bool, Optional[int], str]:
|
||||
return True, tid, "ok"
|
||||
|
||||
|
||||
def _run_cliproxy_sweeper_worker(
|
||||
task_id: int,
|
||||
source: str,
|
||||
*,
|
||||
finalize_task: bool = True,
|
||||
) -> dict[str, int | str]:
|
||||
"""按 usage 连续失败阈值清理 auth-files 里的失效 JSON。"""
|
||||
base = db.get_setting("cliproxy_management_base", "").strip()
|
||||
key = db.get_setting("cliproxy_management_key", "").strip()
|
||||
if not base or not key:
|
||||
msg = "请先在「配置编辑」填写 Cliproxy 管理地址与密钥"
|
||||
if finalize_task:
|
||||
db.update_task(task_id, status="error", message=msg)
|
||||
raise RuntimeError(msg)
|
||||
|
||||
timeout = max(1, int(float(db.get_setting("cliproxy_probe_timeout_sec", "30"))))
|
||||
threshold = max(1, int(db.get_setting("cliproxy_sweeper_threshold", "3")))
|
||||
run_mode = db.get_setting("cliproxy_sweeper_run_mode", "delete").strip().lower()
|
||||
if run_mode not in {"delete", "observe"}:
|
||||
run_mode = "delete"
|
||||
allow_name_fallback = (
|
||||
db.get_setting("cliproxy_sweeper_allow_name_fallback", "1").strip() == "1"
|
||||
)
|
||||
apply_mode = run_mode == "delete"
|
||||
|
||||
rtlog().info(
|
||||
"[sweeper#%s] %s 开始 base=%s threshold=%s mode=%s",
|
||||
task_id,
|
||||
source,
|
||||
base,
|
||||
threshold,
|
||||
run_mode,
|
||||
)
|
||||
db.update_task(task_id, status="running", message=f"{source}: 拉取 usage/auth-files …", done=0)
|
||||
|
||||
headers = {
|
||||
"Accept": "application/json",
|
||||
"Authorization": f"Bearer {key}",
|
||||
"X-Management-Key": key,
|
||||
}
|
||||
run_started_epoch = int(time.time())
|
||||
|
||||
usage_obj = cliproxy_sweeper.request_json_or_die(
|
||||
base_url=base.rstrip("/"),
|
||||
path="/usage",
|
||||
method="GET",
|
||||
headers=headers,
|
||||
timeout=timeout,
|
||||
insecure=False,
|
||||
)
|
||||
analysis = cliproxy_sweeper.build_usage_analysis(
|
||||
usage_obj=usage_obj,
|
||||
threshold=threshold,
|
||||
run_started_epoch=run_started_epoch,
|
||||
)
|
||||
auth_files_obj = cliproxy_sweeper.request_json_or_die(
|
||||
base_url=base.rstrip("/"),
|
||||
path="/auth-files",
|
||||
method="GET",
|
||||
headers=headers,
|
||||
timeout=timeout,
|
||||
insecure=False,
|
||||
)
|
||||
match = cliproxy_sweeper.build_candidates(
|
||||
analysis=analysis,
|
||||
auth_files_obj=auth_files_obj,
|
||||
allow_name_fallback=allow_name_fallback,
|
||||
)
|
||||
|
||||
candidates = match.get("candidates", [])
|
||||
deleted = 0
|
||||
failed = 0
|
||||
if apply_mode:
|
||||
total = len(candidates)
|
||||
for i, c in enumerate(candidates, 1):
|
||||
db.update_task(
|
||||
task_id,
|
||||
message=f"{source}: 删除 {i}/{total} …",
|
||||
done=i,
|
||||
)
|
||||
file_name = str(c.get("file_name", ""))
|
||||
encoded_name = urllib.parse.quote(file_name, safe="")
|
||||
code, _ = cliproxy_sweeper.http_request_with_retry(
|
||||
base_url=base.rstrip("/"),
|
||||
path=f"/auth-files?name={encoded_name}",
|
||||
method="DELETE",
|
||||
headers=headers,
|
||||
timeout=timeout,
|
||||
insecure=False,
|
||||
)
|
||||
if 200 <= code < 300:
|
||||
deleted += 1
|
||||
else:
|
||||
failed += 1
|
||||
|
||||
msg = (
|
||||
f"{source}: 阈值={threshold} 命中={len(candidates)} "
|
||||
f"已删={deleted} 删除失败={failed} 模式={run_mode}"
|
||||
)
|
||||
rtlog().info("[sweeper#%s] %s", task_id, msg)
|
||||
if finalize_task:
|
||||
db.update_task(task_id, status="done", message=msg, done=1)
|
||||
return {
|
||||
"threshold": threshold,
|
||||
"matched": len(candidates),
|
||||
"deleted": deleted,
|
||||
"failed": failed,
|
||||
"mode": run_mode,
|
||||
"message": msg,
|
||||
}
|
||||
|
||||
|
||||
def _start_sweeper_job(source: str) -> tuple[bool, Optional[int], str]:
|
||||
# 与巡检共用锁,避免并发删除同一批 auth-files。
|
||||
if not INSPECT_LOCK.acquire(blocking=False):
|
||||
return False, None, "busy"
|
||||
tid = db.create_task("cliproxy_sweeper", "queued", f"{source}:排队…", None, 1)
|
||||
|
||||
def bg() -> None:
|
||||
try:
|
||||
_run_cliproxy_sweeper_worker(tid, source)
|
||||
except Exception as e:
|
||||
rtlog().exception("[sweeper#%s] 后台异常: %s", tid, e)
|
||||
db.update_task(tid, status="error", message=str(e)[:500])
|
||||
finally:
|
||||
INSPECT_LOCK.release()
|
||||
|
||||
threading.Thread(target=bg, daemon=True).start()
|
||||
return True, tid, "ok"
|
||||
|
||||
|
||||
def _start_pipeline_job(source: str) -> tuple[bool, Optional[int], str]:
|
||||
"""
|
||||
异步启动一条子进程流水线。全局 PIPELINE_LOCK 保证同时最多一条。
|
||||
@@ -773,7 +936,28 @@ def api_task_inspect_now():
|
||||
{
|
||||
"ok": True,
|
||||
"task_id": tid,
|
||||
"message": "已排队巡检;完成后若仍有缺口将自动批量补号(每批上限见 max_auto_register_per_tick)",
|
||||
"message": "已排队巡检(先按 /usage 阈值清理,再探测删失效);完成后若仍有缺口将自动批量补号",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/tasks/sweep-failed-now")
|
||||
@require_login
|
||||
def api_task_sweep_failed_now():
|
||||
if not db.cliproxy_inspect_configured():
|
||||
return jsonify(
|
||||
{
|
||||
"error": "未配置 Cliproxy 管理地址/密钥,请在「配置编辑」填写 cliproxy_management_base 与密钥",
|
||||
}
|
||||
), 400
|
||||
started, tid, reason = _start_sweeper_job("手动失效清理")
|
||||
if reason == "busy":
|
||||
return jsonify({"error": "已有巡检/清理任务在执行,请稍后再试"}), 409
|
||||
return jsonify(
|
||||
{
|
||||
"ok": True,
|
||||
"task_id": tid,
|
||||
"message": "已排队失效清理任务(基于 /usage 连续失败阈值)",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
Reference in new issue
Block a user