#!/usr/bin/env python3 """Codex 自动维护 Web 控制台 — python -m maintain.app""" from __future__ import annotations import json import logging import os import sys import threading import time from collections import defaultdict from datetime import datetime, timezone from functools import wraps from pathlib import Path from typing import Any, Optional ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if ROOT not in sys.path: sys.path.insert(0, ROOT) from flask import Flask, jsonify, render_template, request, session from maintain import db from maintain.batch_register import run_batch from maintain.runtime_log import rtlog, runtime_log_path from maintain.cliproxy_mgmt import ( probe_auth_file_models_for_oauth_stem, verify_management_auth, ) from maintain.cpa_runner_core import ( execute_pipeline_cycle, load_state, runner_config_from_db, save_state, ) _plog = logging.getLogger("cpa-runner") if not _plog.handlers: _h = logging.StreamHandler() _h.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")) _plog.addHandler(_h) _plog.setLevel(logging.INFO) app = Flask( __name__, template_folder=os.path.join(os.path.dirname(__file__), "templates"), static_folder=os.path.join(os.path.dirname(__file__), "static"), ) app.secret_key = os.environ.get("CODEX_MAINTAIN_SECRET", "dev-change-me-in-production") rtlog() # 进程内补号(run_batch)与 子进程流水线(run.py→迁出)分开加锁: # - 巡检结束后若仍有缺口 → 自动批量注册(REGISTER_LOCK),每批不超过 max_auto_register_per_tick # - 定时流水线仍用 PIPELINE_LOCK;手动批量补号与巡检触发的补号共 REGISTER_LOCK REGISTER_LOCK = threading.Lock() PIPELINE_LOCK = threading.Lock() INSPECT_LOCK = threading.Lock() _workers_started = False _worker_lock = threading.Lock() def _lock_busy(lock: threading.Lock) -> bool: if lock.acquire(blocking=False): lock.release() return False return True def _pipeline_lock_busy() -> bool: return _lock_busy(PIPELINE_LOCK) def _register_lock_busy() -> bool: return _lock_busy(REGISTER_LOCK) def _inspect_lock_busy() -> bool: return _lock_busy(INSPECT_LOCK) def _pipeline_public_snapshot() -> dict[str, Any]: cfg = runner_config_from_db(db.get_setting) st = load_state(cfg.state_file) s = db.all_settings() return { "state": st, "lock_busy": _pipeline_lock_busy(), "inspect_busy": _inspect_lock_busy(), "auto_enabled": s.get("pipeline_auto_enabled", "0") == "1", "interval_min": s.get("pipeline_interval_min", "10"), "paths": { "run_script": str(cfg.run_script), "oauth_dir": str(cfg.oauth_dir), "target_dir": str(cfg.target_dir), "state_file": str(cfg.state_file), }, "dingtalk_configured": bool(s.get("dingtalk_webhook", "").strip()), "register_busy": _register_lock_busy(), } def _password_ok(pw: str) -> bool: expected = os.environ.get("CODEX_MAINTAIN_PASSWORD", "admin") return pw == expected def require_login(f): @wraps(f) def w(*args, **kwargs): if not session.get("maintain_user"): return jsonify({"error": "未登录"}), 401 return f(*args, **kwargs) return w def _tail_text_file(path: Path, *, max_lines: int, max_bytes: int) -> str: if not path.is_file(): return f"(文件不存在,执行任务后会生成)\n路径: {path}\n" try: data = path.read_bytes() except OSError as e: return f"(读取失败: {e})\n" if len(data) > max_bytes: data = data[-max_bytes:] text = data.decode("utf-8", errors="replace") lines = text.splitlines() if len(lines) > max_lines: lines = lines[-max_lines:] lines.insert(0, f"... 仅显示最后 {max_lines} 行 ...") out = "\n".join(lines) return out if out.endswith("\n") else out + "\n" @app.get("/api/logs/tail") @require_login def api_logs_tail(): """维护台任务日志 / 流水线 cpa-runner 日志(文件尾)。""" name = request.args.get("name", "runtime").strip().lower() try: nlines = max(20, min(2000, int(request.args.get("lines", "400")))) except ValueError: nlines = 400 repo = Path(ROOT).resolve() if name == "runtime": path = runtime_log_path().resolve() elif name == "pipeline": raw = db.get_setting( "pipeline_log_file", str(repo / "maintain" / "data" / "pipeline.log"), ) path = Path(raw).expanduser().resolve() else: return jsonify({"error": "name 须为 runtime 或 pipeline"}), 400 try: path.relative_to(repo) except ValueError: return jsonify({"error": "日志路径必须在项目根目录内"}), 400 content = _tail_text_file(path, max_lines=nlines, max_bytes=400000) return jsonify({"name": name, "path": str(path), "content": content}) @app.route("/") def index(): if not session.get("maintain_user"): return render_template("login.html") return render_template("dashboard.html") @app.route("/api/login", methods=["POST"]) def api_login(): data = request.get_json(silent=True) or {} if _password_ok(str(data.get("password", ""))): session["maintain_user"] = "1" return jsonify({"ok": True}) return jsonify({"ok": False, "error": "密码错误"}), 403 @app.route("/api/logout", methods=["POST"]) def api_logout(): session.pop("maintain_user", None) return jsonify({"ok": True}) @app.get("/api/me") def api_me(): return jsonify({"logged_in": bool(session.get("maintain_user"))}) @app.get("/api/overview") @require_login def api_overview(): stats = db.overview_stats() active = db.get_active_task() settings = db.all_settings() if active: cpa_name = "" if active.get("cpa_id"): c = next( (x for x in stats["cpas"] if x["id"] == active["cpa_id"]), None, ) if c: cpa_name = c["name"] active = { **active, "cpa_name": cpa_name, } return jsonify( { "stats": stats, "active_task": active, "recent_tasks": db.list_recent_tasks(20), "pipeline": _pipeline_public_snapshot(), "settings": { "auto_inspect_enabled": settings.get("auto_inspect_enabled", "0"), "inspect_interval_min": settings.get("inspect_interval_min", "60"), "use_proxy_pool_auto": settings.get("use_proxy_pool_auto", "1"), "max_auto_register_per_tick": settings.get( "max_auto_register_per_tick", "30" ), "default_threads": settings.get("default_threads", "1"), "skip_oauth": settings.get("skip_oauth", "0"), "manual_default_proxy": settings.get("manual_default_proxy", ""), "pipeline_auto_enabled": settings.get("pipeline_auto_enabled", "0"), "pipeline_interval_min": settings.get("pipeline_interval_min", "10"), "pipeline_run_script": settings.get( "pipeline_run_script", "" ), "pipeline_oauth_dir": settings.get("pipeline_oauth_dir", ""), "cpa_target_dir": settings.get("cpa_target_dir", ""), "pipeline_python_bin": settings.get("pipeline_python_bin", "python3"), "run_subprocess_timeout_sec": settings.get( "run_subprocess_timeout_sec", "480" ), "cpa_exit_on_empty": settings.get("cpa_exit_on_empty", "0"), "dingtalk_webhook": settings.get("dingtalk_webhook", ""), "dingtalk_secret": settings.get("dingtalk_secret", ""), "cliproxy_management_base": settings.get( "cliproxy_management_base", "" ), "cliproxy_management_key_set": bool( settings.get("cliproxy_management_key", "").strip() ), "cliproxy_probe_timeout_sec": settings.get( "cliproxy_probe_timeout_sec", "30" ), "codex_stats_oauth_dir": settings.get("codex_stats_oauth_dir", ""), }, } ) @app.get("/api/proxies") @require_login def api_proxies(): return jsonify({"proxies": db.list_proxies()}) @app.post("/api/proxies") @require_login def api_proxies_add(): data = request.get_json(silent=True) or {} url = str(data.get("url", "")).strip() if not url: return jsonify({"error": "url 必填"}), 400 pid = db.add_proxy(url, str(data.get("label", ""))) return jsonify({"ok": True, "id": pid}) @app.delete("/api/proxies/") @require_login def api_proxies_del(pid: int): db.delete_proxy(pid) return jsonify({"ok": True}) @app.put("/api/cpas/") @require_login def api_cpa_update(cid: int): data = request.get_json(silent=True) or {} kw: dict[str, Any] = {} if "name" in data: kw["name"] = str(data["name"]) if "target_count" in data: kw["target_count"] = int(data["target_count"]) if "api_base_url" in data: kw["api_base_url"] = str(data["api_base_url"]) if kw: db.update_cpa(cid, **kw) return jsonify({"ok": True}) @app.post("/api/settings") @require_login def api_settings_save(): data = request.get_json(silent=True) or {} for k, v in data.items(): if isinstance(v, (dict, list)): continue db.set_setting(str(k), str(v)) return jsonify({"ok": True}) def _resolve_proxy(use_pool: bool) -> str: if use_pool: p = db.pick_random_proxy_url() if p: return p return db.get_setting("manual_default_proxy", "").strip() def _try_start_register_for_gap( best: dict[str, Any], *, inspect_task_id: Optional[int], source: str, ) -> tuple[bool, Optional[int], str]: """ 按当前缺口启动一批进程内注册(与手动批量补号同源)。 返回 (是否已排队, 补号任务 id, reason)。 """ if not REGISTER_LOCK.acquire(blocking=False): if inspect_task_id is not None: t = db.get_task(inspect_task_id) if t: prev = (t.get("message") or "").strip() db.update_task( inspect_task_id, message=prev + ";仍有缺口但补号锁占用(已有批量注册在进行),未自动补号", ) return False, None, "register_busy" gap = int(best.get("gap", 0)) cap = max(1, int(db.get_setting("max_auto_register_per_tick", "30"))) count = min(gap, cap, 500) cpa_id = int(best["id"]) cpa_code = str(best.get("code") or "").strip() if not cpa_code: REGISTER_LOCK.release() if inspect_task_id is not None: t = db.get_task(inspect_task_id) if t: prev = (t.get("message") or "").strip() db.update_task( inspect_task_id, message=prev + ";无法补号:账号池缺少 code", ) return False, None, "no_code" skip_oauth = db.get_setting("skip_oauth", "0") == "1" use_pool = db.get_setting("use_proxy_pool_auto", "1") == "1" proxy = _resolve_proxy(use_pool) reg_tid = db.create_task( "inspect_register", "queued", f"{source} 补号 {count}/{gap}…", cpa_id=cpa_id, total=count, ) rtlog().info( "[register#%s] 排队补号 gap=%s 本批=%s cpa_id=%s (%s)", reg_tid, gap, count, cpa_id, source, ) def reg_bg() -> None: try: _run_batch_task( reg_tid, cpa_id=cpa_id, cpa_code=cpa_code, count=count, proxy=proxy, skip_oauth=skip_oauth, ) finally: REGISTER_LOCK.release() threading.Thread(target=reg_bg, daemon=True).start() if inspect_task_id is not None: t = db.get_task(inspect_task_id) if t: prev = (t.get("message") or "").strip() db.update_task( inspect_task_id, message=prev + f";已排队批量补号 #{reg_tid}(本批 {count} 个,当前缺口 {gap})", ) return True, reg_tid, "ok" def _accounts_insufficient() -> tuple[bool, dict[str, Any]]: stats = db.overview_stats() if not stats["cpas"]: return False, {} best = max(stats["cpas"], key=lambda x: x["gap"]) return best["gap"] > 0, best def _persist_probe_result( by_cpa: dict[int, int], total_ok: int, total_fail: int, errors_sample: list[str], *, removed_count: int = 0, ) -> None: probed_at = datetime.now(timezone.utc).isoformat() db.set_setting( "inspect_probe_valid_json", json.dumps( { "by_cpa": {str(k): v for k, v in by_cpa.items()}, "total_ok": total_ok, "total_fail": total_fail, "removed_count": removed_count, "probed_at": probed_at, "errors_sample": errors_sample[:12], }, ensure_ascii=False, ), ) def _probe_error_skip_delete(err: str) -> bool: """网络/服务端波动或全局鉴权异常时不删本地文件。""" e = (err or "").lower() if "http 401" in e or "http 403" in e: return True needles = ( "timeout", "timed out", "connection", "econnrefused", "network is unreachable", "name or service not known", "temporary failure", "http 502", "http 503", "http 504", "http 500", ) return any(n in e for n in needles) def _run_cliproxy_inspect_worker(task_id: int, source: str) -> None: base = db.get_setting("cliproxy_management_base", "").strip() key = db.get_setting("cliproxy_management_key", "").strip() if not base or not key: rtlog().warning( "[inspect#%s] %s 中止: 未配置管理地址或密钥", task_id, source ) db.update_task( task_id, status="error", message="请先在「配置编辑」填写 Cliproxy 管理地址与密钥", ) return timeout = float(db.get_setting("cliproxy_probe_timeout_sec", "30")) ping_to = min(timeout, 20.0) ok_mgmt, mgmt_err = verify_management_auth(base, key, timeout_sec=ping_to) if not ok_mgmt: rtlog().error( "[inspect#%s] %s 管理端预检失败: %s", task_id, source, mgmt_err ) db.update_task( task_id, status="error", message=f"管理端不可用或密钥无效(未删任何文件): {mgmt_err}", ) return entries = db.list_oauth_codex_entries() total = len(entries) rtlog().info( "[inspect#%s] %s 统计目录=%s 待探测条目=%s timeout=%s", task_id, source, db.resolve_oauth_stats_dir(), total, timeout, ) if total == 0: _persist_probe_result({}, 0, 0, [], removed_count=0) rtlog().info("[inspect#%s] %s 无 oauth 条目,结束", task_id, source) db.update_task( task_id, status="done", message=f"{source}: 无 codex oauth JSON,已清空探测缓存", done=1, ) return by_cpa: defaultdict[int, int] = defaultdict(int) ok = 0 fail = 0 removed = 0 errors_sample: list[str] = [] db.update_task(task_id, status="running", message=f"{source}: 0/{total} …", done=0) for i, ent in enumerate(entries): if i % 7 == 0: db.update_task( task_id, message=f"{source}: 管理端探测 {i}/{total} …", done=i, ) good, err = probe_auth_file_models_for_oauth_stem( base, key, str(ent["stem"]), timeout_sec=timeout ) if good: ok += 1 by_cpa[int(ent["cpa_id"])] += 1 else: fail += 1 path_str = str(ent.get("path") or "") if _probe_error_skip_delete(err): if len(errors_sample) < 10: errors_sample.append(f'{ent["stem"]}: {err}(未删,疑为网络/服务波动)') elif db.safe_unlink_oauth_json(path_str): removed += 1 if len(errors_sample) < 10: errors_sample.append(f'{ent["stem"]}: 已删本地 JSON — {err}') else: if len(errors_sample) < 10: errors_sample.append(f'{ent["stem"]}: {err}(删文件失败)') _persist_probe_result( dict(by_cpa), ok, fail, errors_sample, removed_count=removed ) msg = f"{source}: 有效 {ok},探测失败 {fail},已删失效 {removed} 个本地 JSON" rtlog().info("[inspect#%s] %s", task_id, msg) if errors_sample: rtlog().info( "[inspect#%s] 样例: %s", task_id, "; ".join(errors_sample[:5]), ) db.update_task( task_id, status="done", message=msg, done=total, ) def _start_inspect_job(source: str) -> tuple[bool, Optional[int], str]: if not db.cliproxy_inspect_configured(): return False, None, "no_config" if not INSPECT_LOCK.acquire(blocking=False): return False, None, "busy" tid = db.create_task( "mgmt_inspect", "queued", f"{source}:排队…", None, 1, ) def bg() -> None: try: _run_cliproxy_inspect_worker(tid, source) tdone = db.get_task(tid) if not tdone or tdone.get("status") != "done": return need, best = _accounts_insufficient() if need: _try_start_register_for_gap( best, inspect_task_id=tid, source=source ) except Exception as e: rtlog().exception("[inspect#%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 保证同时最多一条。 返回 (是否已成功排队, task_id, 说明);说明为 busy 表示已有流水线在执行。 """ if not PIPELINE_LOCK.acquire(blocking=False): return False, None, "busy" tid = db.create_task( "pipeline_runpy", "queued", f"{source}:准备中…", None, 1, ) def bg() -> None: try: db.update_task(tid, status="running", message=f"{source}:run.py …", done=0) cfg = runner_config_from_db(db.get_setting) rtlog().info( "[pipeline#%s] %s 开始 run_script=%s log=%s", tid, source, cfg.run_script, cfg.log_file, ) cfg.target_dir.mkdir(parents=True, exist_ok=True) st = load_state(cfg.state_file) st = execute_pipeline_cycle(cfg, st, allow_sys_exit_on_empty=False) save_state(cfg.state_file, st) moved = st.get("last_run_moved", 0) rc = st.get("last_run_return_code") err = (st.get("last_error") or "").strip() if err: rtlog().warning("[pipeline#%s] last_error=%s", tid, err[:500]) rtlog().info( "[pipeline#%s] %s 完成 迁出=%s rc=%s", tid, source, moved, rc, ) db.update_task( tid, status="done", message=f"{source} 完成: 迁出 {moved} 个, 返回码 {rc}", done=1, ) except Exception as e: rtlog().exception("[pipeline#%s] %s 异常: %s", tid, source, e) db.update_task(tid, status="error", message=str(e)[:500]) finally: PIPELINE_LOCK.release() threading.Thread(target=bg, daemon=True).start() return True, tid, "ok" def _run_batch_task( task_id: int, *, cpa_id: int, cpa_code: str, count: int, proxy: str, skip_oauth: bool, ) -> None: threads = int(db.get_setting("default_threads", "1")) def on_progress(done: int, total: int) -> None: cpa = next((x for x in db.list_cpas() if x["id"] == cpa_id), {}) name = cpa.get("name", "") db.update_task( task_id, message=f"{done}/{total} 正在补号({name or '账号池'})…", done=done, ) try: db.update_task(task_id, status="running", message="启动注册线程…", done=0) rtlog().info( "[register#%s] 开始 cpa_id=%s count=%s threads=%s skip_oauth=%s proxy=%s", task_id, cpa_id, count, threads, skip_oauth, proxy or "(空)", ) ok, fail = run_batch( count=count, threads=threads, proxy=proxy, skip_oauth=skip_oauth, cpa_id=cpa_id, cpa_code=cpa_code, on_progress=on_progress, ) rtlog().info( "[register#%s] 结束 成功=%s 失败=%s", task_id, ok, fail ) db.update_task( task_id, status="done", message=f"完成: 成功 {ok}, 失败 {fail}", done=count, ) except Exception as e: rtlog().exception("[register#%s] 异常: %s", task_id, e) db.update_task(task_id, status="error", message=str(e)[:500]) @app.post("/api/pipeline/run-once") @require_login def api_pipeline_run_once(): """手动执行一次子进程流水线(与巡检/定时共用 PIPELINE_LOCK,同时仅一条)""" started, tid, _ = _start_pipeline_job("手动流水线") if not started: return jsonify({"error": "已有流水线在执行,请稍后再试"}), 409 return jsonify({"ok": True, "task_id": tid}) @app.post("/api/tasks/manual") @require_login def api_task_manual(): if not REGISTER_LOCK.acquire(blocking=False): return jsonify({"error": "已有批量补号任务在运行"}), 409 data = request.get_json(silent=True) or {} cpa_id = int(data.get("cpa_id", 0)) count = int(data.get("count", 1)) use_pool = bool(data.get("use_proxy_pool", True)) if count < 1 or count > 500: REGISTER_LOCK.release() return jsonify({"error": "count 范围 1–500"}), 400 cpas = db.list_cpas() cpa = next((c for c in cpas if c["id"] == cpa_id), None) if not cpa: REGISTER_LOCK.release() return jsonify({"error": "账号池不存在"}), 400 skip_oauth = db.get_setting("skip_oauth", "0") == "1" proxy = _resolve_proxy(use_pool) tid = db.create_task( "manual_register", "queued", "", cpa_id=cpa_id, total=count, ) def bg(): try: _run_batch_task( tid, cpa_id=cpa_id, cpa_code=str(cpa["code"]), count=count, proxy=proxy, skip_oauth=skip_oauth, ) finally: REGISTER_LOCK.release() threading.Thread(target=bg, daemon=True).start() return jsonify({"ok": True, "task_id": tid}) @app.post("/api/tasks/inspect-now") @require_login def api_task_inspect_now(): """ 巡检:Cliproxy 管理 API 探测、删失效 JSON;完成后若仍低于目标则排队一批批量注册。 """ if not db.cliproxy_inspect_configured(): return jsonify( { "error": "未配置 Cliproxy 管理地址/密钥,请在「配置编辑」填写 cliproxy_management_base 与密钥", } ), 400 started, tid, reason = _start_inspect_job("手动巡检") if reason == "busy": return jsonify( {"error": "已有巡检任务在执行,请稍后再试", "task_id": None} ), 409 return jsonify( { "ok": True, "task_id": tid, "message": "已排队巡检;完成后若仍有缺口将自动批量补号(每批上限见 max_auto_register_per_tick)", } ) def _pipeline_scheduler_loop() -> None: last_run = 0.0 while True: time.sleep(20) try: if db.get_setting("pipeline_auto_enabled", "0") != "1": continue need, _ = _accounts_insufficient() now = time.time() if not need: last_run = now continue interval = float(db.get_setting("pipeline_interval_min", "10")) * 60.0 if now - last_run < interval: continue started, _, _ = _start_pipeline_job("定时流水线") if started: last_run = time.time() except Exception: time.sleep(30) def _auto_worker_loop() -> None: """自动巡检:按间隔触发管理端全量探测;完成后若有效账号不足则排队流水线。""" last_run = 0.0 while True: time.sleep(15) try: if db.get_setting("auto_inspect_enabled", "0") != "1": continue if not db.cliproxy_inspect_configured(): continue interval = float(db.get_setting("inspect_interval_min", "60")) * 60.0 now = time.time() if now - last_run < interval: continue started, _, reason = _start_inspect_job("自动巡检") if started: last_run = time.time() elif reason == "busy": pass except Exception: time.sleep(30) def _ensure_worker() -> None: global _workers_started with _worker_lock: if _workers_started: return threading.Thread( target=_auto_worker_loop, daemon=True, name="maintain-auto-inspect" ).start() threading.Thread( target=_pipeline_scheduler_loop, daemon=True, name="maintain-pipeline" ).start() _workers_started = True @app.before_request def _before(): if request.endpoint and request.endpoint != "static": _ensure_worker() def main() -> None: db.init_db() host = os.environ.get("CODEX_MAINTAIN_HOST", "127.0.0.1") port = int(os.environ.get("CODEX_MAINTAIN_PORT", "8765")) print( f"Codex 维护台 http://{host}:{port} " f"(任务中心+流水线一体)密码: CODEX_MAINTAIN_PASSWORD,默认 admin" ) if host in ("127.0.0.1", "localhost", "::1"): print( "提示: 当前仅监听本机;用公网 IP 访问请设置 CODEX_MAINTAIN_HOST=0.0.0.0," "并放行防火墙/安全组 TCP 端口。" ) app.run(host=host, port=port, debug=False, threaded=True) if __name__ == "__main__": db.init_db() main()